Blockchain foundations in Go · 5 MIN READ
RLP: Ethereum's canonical encoding, and why its decoder rejects every other spelling
Encode and decode Go structs with go-ethereum's rlp package, recognize the canonical-form rules, and bound untrusted input before decoding it.
Ethereum hashes and signs bytes, so every value needs exactly one byte form. On the execution layer that form is Recursive Length Prefix (RLP): transactions, headers and receipts are RLP, and typed transactions are a type byte followed by an RLP payload. RLP encodes byte strings and nested lists and nothing else. go-ethereum's decoder is deliberately strict, because accepting a second spelling of a value means accepting a second hash for it.
blockchain · A MAP OF THE IDEA
- Map Go types to RLP
- Cap raw input size
- Decode with stream limit
- Bound decoded values
Useful when
- One canonical byte form per value keeps hashes and signatures stable.
- The decoder rejects non-canonical sizes, integers and trailing data.
Watch out
- rlp.Decode on an arbitrary io.Reader sets no input limit.
- Typed decode errors do not match ErrCanonInt with errors.Is.
Implementation & operation cost: Reflection-based encoding is slower than generated code, and a format without field names makes every schema change a versioning decision.
Two kinds of item and a length prefix
A single byte below 0x80 is its own encoding. A string of 0 to 55 bytes is 0x80 plus its length followed by the bytes; a longer string is 0xb7 plus the length of the length, the length in big-endian, then the bytes. Lists follow the same pattern from 0xc0 and 0xf7. Integers are not a separate type: they are big-endian strings with no leading zero bytes, so zero is the empty string 0x80. go-ethereum maps Go types onto this. Structs become lists of their exported fields in declaration order, unsigned integers and *big.Int become minimal strings, byte slices and arrays become strings, other slices become lists. Signed integers, floats and maps are refused because they have no canonical form, and a negative big.Int returns an error. The hash-chain lesson made these choices by hand; RLP is the standardized version.
Encode, decode and feed the decoder bad input
The program prints the specification's own examples, round-trips a struct holding an address, a *big.Int and an empty byte slice, then decodes five malformed inputs into a uint64 and one oversized value from a reader with an explicit limit. No network or chain is involved; these are pure functions over bytes.
package main
import (
"bytes"
"encoding/hex"
"fmt"
"io"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
)
type Transfer struct {
Nonce uint64
To common.Address
Value *big.Int
Data []byte
}
func enc(v any) string {
b, err := rlp.EncodeToBytes(v)
if err != nil {
return "error: " + err.Error()
}
return hex.EncodeToString(b)
}
func main() {
// Vectors from the RLP specification.
fmt.Println("0:", enc(uint64(0)), "15:", enc(uint64(15)), "1024:", enc(uint64(1024)))
fmt.Println("dog:", enc("dog"), "[cat dog]:", enc([]string{"cat", "dog"}), "[]:", enc([]uint64{}))
fmt.Println("negative big.Int:", enc(big.NewInt(-1)))
t := Transfer{Nonce: 7, To: common.HexToAddress("0x00000000000000000000000000000000000000aa"), Value: big.NewInt(1000)}
raw, _ := rlp.EncodeToBytes(t)
fmt.Println("transfer:", len(raw), "bytes", hex.EncodeToString(raw[:4])+"...")
var back Transfer
err := rlp.DecodeBytes(raw, &back)
again, _ := rlp.EncodeToBytes(back)
fmt.Println("round trip:", err == nil && bytes.Equal(raw, again))
// Each input below decodes to 5 or 15 in a lax decoder; rlp rejects them.
for _, in := range []string{"8105", "820005", "b80105", "0f0f", "bbffffffff"} {
b, _ := hex.DecodeString(in)
var n uint64
fmt.Printf("%-10s %v\n", in, rlp.DecodeBytes(b, &n))
}
// A stream from the network has no length; cap it explicitly.
big100 := append([]byte{0xb8, 100}, make([]byte, 100)...)
var payload []byte
s := rlp.NewStream(io.MultiReader(bytes.NewReader(big100)), 64)
fmt.Println("stream limit 64:", s.Decode(&payload))
}0 encodes as 80, 15 as the single byte 0f and 1024 as 82 04 00; dog is 83 followed by its ASCII bytes, and [cat dog] is the list header c8 over two strings. The 27-byte transfer starts with da (0xc0 + 26), then 07 for the nonce and 94 for the 20-byte address. Each malformed input breaks a different rule: 8105 wraps a byte that must stand alone, 820005 has a leading zero, b80105 uses the long form for a short string, 0f0f leaves trailing bytes, and bbffffffff claims a 4 GiB string inside 5 bytes. io.MultiReader hides the underlying bytes.Reader, as a network connection would, so only the explicit 64-byte limit stops the 100-byte value, and it does so before allocating.
Why consensus decoders refuse non-canonical bytes
Each rejected input is something a lax decoder could interpret: 8105 and 820005 as the integer 5, b80105 as the one-byte string 05. If a node accepted them, one transaction would have several byte forms and therefore several hashes. A node that accepted a form and a node that rejected it would disagree about a block's validity, which is a consensus split. The property that protects everyone is a bijection: decoding b succeeds only if encoding the result gives back b. go-ethereum's Stream enforces it with ErrCanonSize for a size that should have used a shorter form, ErrCanonInt for leading zeros and, in DecodeBytes, ErrMoreThanOneValue for trailing data. Struct decoding also rejects too few or too many list elements unless trailing fields carry the optional or tail tags.
Bound untrusted input before you decode it
An RLP header can claim a length up to 2^64-1, and a naive decoder allocates what the header says. DecodeBytes, and NewStream over a bytes.Reader, bytes.Buffer or strings.Reader, know the input length and return ErrValueTooLarge for larger claims. Over any other io.Reader, such as a connection or an HTTP body, the stream has no limit unless you pass one, and rlp.Decode offers no way to pass one, as its documentation warns. Cap the raw message first (go-ethereum's eth protocol caps messages at 10 MiB, and its legacy transaction pool refuses transactions over 128 KiB), then decode with NewStream(r, limit). After decoding, bound the values: RLP puts no size limit on *big.Int, so check BitLen, as the transaction pool does for fee caps over 256 bits. One API surprise: when DecodeBytes fills a typed value, canonical-form failures come back wrapped in a descriptive error that errors.Is does not match against ErrCanonInt or ErrCanonSize, so treat any decode error as invalid input.
Test with vectors and round trips
Check in the specification examples and the RLP fixtures from the ethereum/tests repository as known answers. For every type you decode from outside, fuzz with go test -fuzz: when DecodeBytes succeeds, re-encode and require identical bytes; when it fails, require no panic and no large allocation. Add cases for each rule above, for a nested list whose inner length exceeds its parent (ErrElemTooLarge), for structs with missing or extra elements, and for optional trailing fields. For hot paths, go-ethereum's rlpgen generates reflection-free encoders. Keep RLP where it belongs: it is the execution layer's consensus encoding, the consensus layer uses SSZ, and your own service APIs are better served by formats with field names and explicit schemas.
TAKE THIS WITH YOU
Let the rlp package define the bytes, cap untrusted input and decode with an explicit stream limit, bound decoded big integers, and treat every non-canonical form as invalid.
Check your understanding
A lax decoder reads the bytes 0x820005 as the integer 5. Why must a consensus decoder reject them?
Go to the source
Progress stays in this browser. No account needed.