Skip to content

Commit f958d7d

Browse files
committed
trie: rework and document key encoding
'encode' and 'decode' are meaningless because the code deals with three encodings. Document the encodings and give a name to each one.
1 parent a31d268 commit f958d7d

7 files changed

Lines changed: 121 additions & 159 deletions

File tree

‎trie/encoding.go‎

Lines changed: 50 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -16,49 +16,54 @@
1616

1717
package trie
1818

19-
func compactEncode(hexSlice []byte) []byte {
19+
// Trie keys are dealt with in three distinct encodings:
20+
//
21+
// KEYBYTES encoding contains the actual key and nothing else. This encoding is the
22+
// input to most API functions.
23+
//
24+
// HEX encoding contains one byte for each nibble of the key and an optional trailing
25+
// 'terminator' byte of value 0x10 which indicates whether or not the node at the key
26+
// contains a value. Hex key encoding is used for nodes loaded in memory because it's
27+
// convenient to access.
28+
//
29+
// COMPACT encoding is defined by the Ethereum Yellow Paper (it's called "hex prefix
30+
// encoding" there) and contains the bytes of the key and a flag. The high nibble of the
31+
// first byte contains the flag; the lowest bit encoding the oddness of the length and
32+
// the second-lowest encoding whether the node at the key is a value node. The low nibble
33+
// of the first byte is zero in the case of an even number of nibbles and the first nibble
34+
// in the case of an odd number. All remaining nibbles (now an even number) fit properly
35+
// into the remaining bytes. Compact encoding is used for nodes stored on disk.
36+
37+
func hexToCompact(hex []byte) []byte {
2038
terminator := byte(0)
21-
if hexSlice[len(hexSlice)-1] == 16 {
39+
if hasTerm(hex) {
2240
terminator = 1
23-
hexSlice = hexSlice[:len(hexSlice)-1]
24-
}
25-
var (
26-
odd = byte(len(hexSlice) % 2)
27-
buflen = len(hexSlice)/2 + 1
28-
bi, hi = 0, 0 // indices
29-
hs = byte(0) // shift: flips between 0 and 4
30-
)
31-
if odd == 0 {
32-
bi = 1
33-
hs = 4
41+
hex = hex[:len(hex)-1]
3442
}
35-
buf := make([]byte, buflen)
36-
buf[0] = terminator<<5 | byte(odd)<<4
37-
for bi < len(buf) && hi < len(hexSlice) {
38-
buf[bi] |= hexSlice[hi] << hs
39-
if hs == 0 {
40-
bi++
41-
}
42-
hi, hs = hi+1, hs^(1<<2)
43+
buf := make([]byte, len(hex)/2+1)
44+
buf[0] = terminator << 5 // the flag byte
45+
if len(hex)&1 == 1 {
46+
buf[0] |= 1 << 4 // odd flag
47+
buf[0] |= hex[0] // first nibble is contained in the first byte
48+
hex = hex[1:]
4349
}
50+
decodeNibbles(hex, buf[1:])
4451
return buf
4552
}
4653

47-
func compactDecode(str []byte) []byte {
48-
base := compactHexDecode(str)
54+
func compactToHex(compact []byte) []byte {
55+
base := keybytesToHex(compact)
4956
base = base[:len(base)-1]
57+
// apply terminator flag
5058
if base[0] >= 2 {
5159
base = append(base, 16)
5260
}
53-
if base[0]%2 == 1 {
54-
base = base[1:]
55-
} else {
56-
base = base[2:]
57-
}
58-
return base
61+
// apply odd flag
62+
chop := 2 - base[0]&1
63+
return base[chop:]
5964
}
6065

61-
func compactHexDecode(str []byte) []byte {
66+
func keybytesToHex(str []byte) []byte {
6267
l := len(str)*2 + 1
6368
var nibbles = make([]byte, l)
6469
for i, b := range str {
@@ -69,35 +74,24 @@ func compactHexDecode(str []byte) []byte {
6974
return nibbles
7075
}
7176

72-
// compactHexEncode encodes a series of nibbles into a byte array
73-
func compactHexEncode(nibbles []byte) []byte {
74-
nl := len(nibbles)
75-
if nl == 0 {
76-
return nil
77-
}
78-
if nibbles[nl-1] == 16 {
79-
nl--
77+
// hexToKeybytes turns hex nibbles into key bytes.
78+
// This can only be used for keys of even length.
79+
func hexToKeybytes(hex []byte) []byte {
80+
if hasTerm(hex) {
81+
hex = hex[:len(hex)-1]
8082
}
81-
l := (nl + 1) / 2
82-
var str = make([]byte, l)
83-
for i := range str {
84-
b := nibbles[i*2] * 16
85-
if nl > i*2 {
86-
b += nibbles[i*2+1]
87-
}
88-
str[i] = b
83+
if len(hex)&1 != 0 {
84+
panic("can't convert hex key of odd length")
8985
}
90-
return str
86+
key := make([]byte, (len(hex)+1)/2)
87+
decodeNibbles(hex, key)
88+
return key
9189
}
9290

93-
func decodeCompact(key []byte) []byte {
94-
l := len(key) / 2
95-
var res = make([]byte, l)
96-
for i := 0; i < l; i++ {
97-
v1, v0 := key[2*i], key[2*i+1]
98-
res[i] = v1*16 + v0
91+
func decodeNibbles(nibbles []byte, bytes []byte) {
92+
for bi, ni := 0, 0; ni < len(nibbles); bi, ni = bi+1, ni+2 {
93+
bytes[bi] = nibbles[ni]<<4 | nibbles[ni+1]
9994
}
100-
return res
10195
}
10296

10397
// prefixLen returns the length of the common prefix of a and b.
@@ -114,15 +108,7 @@ func prefixLen(a, b []byte) int {
114108
return i
115109
}
116110

111+
// hasTerm returns whether a hex key has the terminator flag.
117112
func hasTerm(s []byte) bool {
118-
return s[len(s)-1] == 16
119-
}
120-
121-
func remTerm(s []byte) []byte {
122-
if hasTerm(s) {
123-
b := make([]byte, len(s)-1)
124-
copy(b, s)
125-
return b
126-
}
127-
return s
113+
return len(s) > 0 && s[len(s)-1] == 16
128114
}

‎trie/encoding_test.go‎

Lines changed: 61 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -17,113 +17,88 @@
1717
package trie
1818

1919
import (
20-
"encoding/hex"
20+
"bytes"
2121
"testing"
22-
23-
checker "gopkg.in/check.v1"
2422
)
2523

26-
func TestEncoding(t *testing.T) { checker.TestingT(t) }
27-
28-
type TrieEncodingSuite struct{}
29-
30-
var _ = checker.Suite(&TrieEncodingSuite{})
31-
32-
func (s *TrieEncodingSuite) TestCompactEncode(c *checker.C) {
33-
// even compact encode
34-
test1 := []byte{1, 2, 3, 4, 5}
35-
res1 := compactEncode(test1)
36-
c.Assert(res1, checker.DeepEquals, []byte("\x11\x23\x45"))
37-
38-
// odd compact encode
39-
test2 := []byte{0, 1, 2, 3, 4, 5}
40-
res2 := compactEncode(test2)
41-
c.Assert(res2, checker.DeepEquals, []byte("\x00\x01\x23\x45"))
42-
43-
//odd terminated compact encode
44-
test3 := []byte{0, 15, 1, 12, 11, 8 /*term*/, 16}
45-
res3 := compactEncode(test3)
46-
c.Assert(res3, checker.DeepEquals, []byte("\x20\x0f\x1c\xb8"))
47-
48-
// even terminated compact encode
49-
test4 := []byte{15, 1, 12, 11, 8 /*term*/, 16}
50-
res4 := compactEncode(test4)
51-
c.Assert(res4, checker.DeepEquals, []byte("\x3f\x1c\xb8"))
52-
}
53-
54-
func (s *TrieEncodingSuite) TestCompactHexDecode(c *checker.C) {
55-
exp := []byte{7, 6, 6, 5, 7, 2, 6, 2, 16}
56-
res := compactHexDecode([]byte("verb"))
57-
c.Assert(res, checker.DeepEquals, exp)
58-
}
59-
60-
func (s *TrieEncodingSuite) TestCompactHexEncode(c *checker.C) {
61-
exp := []byte("verb")
62-
res := compactHexEncode([]byte{7, 6, 6, 5, 7, 2, 6, 2, 16})
63-
c.Assert(res, checker.DeepEquals, exp)
64-
}
65-
66-
func (s *TrieEncodingSuite) TestCompactDecode(c *checker.C) {
67-
// odd compact decode
68-
exp := []byte{1, 2, 3, 4, 5}
69-
res := compactDecode([]byte("\x11\x23\x45"))
70-
c.Assert(res, checker.DeepEquals, exp)
71-
72-
// even compact decode
73-
exp = []byte{0, 1, 2, 3, 4, 5}
74-
res = compactDecode([]byte("\x00\x01\x23\x45"))
75-
c.Assert(res, checker.DeepEquals, exp)
76-
77-
// even terminated compact decode
78-
exp = []byte{0, 15, 1, 12, 11, 8 /*term*/, 16}
79-
res = compactDecode([]byte("\x20\x0f\x1c\xb8"))
80-
c.Assert(res, checker.DeepEquals, exp)
81-
82-
// even terminated compact decode
83-
exp = []byte{15, 1, 12, 11, 8 /*term*/, 16}
84-
res = compactDecode([]byte("\x3f\x1c\xb8"))
85-
c.Assert(res, checker.DeepEquals, exp)
24+
func TestHexCompact(t *testing.T) {
25+
tests := []struct{ hex, compact []byte }{
26+
// empty keys, with and without terminator.
27+
{hex: []byte{}, compact: []byte{0x00}},
28+
{hex: []byte{16}, compact: []byte{0x20}},
29+
// odd length, no terminator
30+
{hex: []byte{1, 2, 3, 4, 5}, compact: []byte{0x11, 0x23, 0x45}},
31+
// even length, no terminator
32+
{hex: []byte{0, 1, 2, 3, 4, 5}, compact: []byte{0x00, 0x01, 0x23, 0x45}},
33+
// odd length, terminator
34+
{hex: []byte{15, 1, 12, 11, 8, 16 /*term*/}, compact: []byte{0x3f, 0x1c, 0xb8}},
35+
// even length, terminator
36+
{hex: []byte{0, 15, 1, 12, 11, 8, 16 /*term*/}, compact: []byte{0x20, 0x0f, 0x1c, 0xb8}},
37+
}
38+
for _, test := range tests {
39+
if c := hexToCompact(test.hex); !bytes.Equal(c, test.compact) {
40+
t.Errorf("hexToCompact(%x) -> %x, want %x", test.hex, c, test.compact)
41+
}
42+
if h := compactToHex(test.compact); !bytes.Equal(h, test.hex) {
43+
t.Errorf("compactToHex(%x) -> %x, want %x", test.compact, h, test.hex)
44+
}
45+
}
8646
}
8747

88-
func (s *TrieEncodingSuite) TestDecodeCompact(c *checker.C) {
89-
exp, _ := hex.DecodeString("012345")
90-
res := decodeCompact([]byte{0, 1, 2, 3, 4, 5})
91-
c.Assert(res, checker.DeepEquals, exp)
92-
93-
exp, _ = hex.DecodeString("012345")
94-
res = decodeCompact([]byte{0, 1, 2, 3, 4, 5, 16})
95-
c.Assert(res, checker.DeepEquals, exp)
96-
97-
exp, _ = hex.DecodeString("abcdef")
98-
res = decodeCompact([]byte{10, 11, 12, 13, 14, 15})
99-
c.Assert(res, checker.DeepEquals, exp)
48+
func TestHexKeybytes(t *testing.T) {
49+
tests := []struct{ key, hexIn, hexOut []byte }{
50+
{key: []byte{}, hexIn: []byte{16}, hexOut: []byte{16}},
51+
{key: []byte{}, hexIn: []byte{}, hexOut: []byte{16}},
52+
{
53+
key: []byte{0x12, 0x34, 0x56},
54+
hexIn: []byte{1, 2, 3, 4, 5, 6, 16},
55+
hexOut: []byte{1, 2, 3, 4, 5, 6, 16},
56+
},
57+
{
58+
key: []byte{0x12, 0x34, 0x5},
59+
hexIn: []byte{1, 2, 3, 4, 0, 5, 16},
60+
hexOut: []byte{1, 2, 3, 4, 0, 5, 16},
61+
},
62+
{
63+
key: []byte{0x12, 0x34, 0x56},
64+
hexIn: []byte{1, 2, 3, 4, 5, 6},
65+
hexOut: []byte{1, 2, 3, 4, 5, 6, 16},
66+
},
67+
}
68+
for _, test := range tests {
69+
if h := keybytesToHex(test.key); !bytes.Equal(h, test.hexOut) {
70+
t.Errorf("keybytesToHex(%x) -> %x, want %x", test.key, h, test.hexOut)
71+
}
72+
if k := hexToKeybytes(test.hexIn); !bytes.Equal(k, test.key) {
73+
t.Errorf("hexToKeybytes(%x) -> %x, want %x", test.hexIn, k, test.key)
74+
}
75+
}
10076
}
10177

102-
func BenchmarkCompactEncode(b *testing.B) {
103-
104-
testBytes := []byte{0, 15, 1, 12, 11, 8 /*term*/, 16}
78+
func BenchmarkHexToCompact(b *testing.B) {
79+
testBytes := []byte{0, 15, 1, 12, 11, 8, 16 /*term*/}
10580
for i := 0; i < b.N; i++ {
106-
compactEncode(testBytes)
81+
hexToCompact(testBytes)
10782
}
10883
}
10984

110-
func BenchmarkCompactDecode(b *testing.B) {
111-
testBytes := []byte{0, 15, 1, 12, 11, 8 /*term*/, 16}
85+
func BenchmarkCompactToHex(b *testing.B) {
86+
testBytes := []byte{0, 15, 1, 12, 11, 8, 16 /*term*/}
11287
for i := 0; i < b.N; i++ {
113-
compactDecode(testBytes)
88+
compactToHex(testBytes)
11489
}
11590
}
11691

117-
func BenchmarkCompactHexDecode(b *testing.B) {
92+
func BenchmarkKeybytesToHex(b *testing.B) {
11893
testBytes := []byte{7, 6, 6, 5, 7, 2, 6, 2, 16}
11994
for i := 0; i < b.N; i++ {
120-
compactHexDecode(testBytes)
95+
keybytesToHex(testBytes)
12196
}
12297
}
12398

124-
func BenchmarkDecodeCompact(b *testing.B) {
99+
func BenchmarkHexToKeybytes(b *testing.B) {
125100
testBytes := []byte{7, 6, 6, 5, 7, 2, 6, 2, 16}
126101
for i := 0; i < b.N; i++ {
127-
decodeCompact(testBytes)
102+
hexToKeybytes(testBytes)
128103
}
129104
}

‎trie/hasher.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ func (h *hasher) hashChildren(original node, db DatabaseWriter) (node, node, err
105105
case *shortNode:
106106
// Hash the short node's child, caching the newly hashed subtree
107107
collapsed, cached := n.copy(), n.copy()
108-
collapsed.Key = compactEncode(n.Key)
108+
collapsed.Key = hexToCompact(n.Key)
109109
cached.Key = common.CopyBytes(n.Key)
110110

111111
if _, ok := n.Val.(valueNode); !ok {

‎trie/iterator.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package trie
1919
import (
2020
"bytes"
2121
"container/heap"
22+
2223
"github.com/ethereum/go-ethereum/common"
2324
)
2425

@@ -48,7 +49,7 @@ func NewIteratorFromNodeIterator(it NodeIterator) *Iterator {
4849
func (it *Iterator) Next() bool {
4950
for it.nodeIt.Next(true) {
5051
if it.nodeIt.Leaf() {
51-
it.Key = decodeCompact(it.nodeIt.Path())
52+
it.Key = hexToKeybytes(it.nodeIt.Path())
5253
it.Value = it.nodeIt.LeafBlob()
5354
return true
5455
}

‎trie/node.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,8 @@ func decodeShort(hash, buf, elems []byte, cachegen uint16) (node, error) {
139139
return nil, err
140140
}
141141
flag := nodeFlag{hash: hash, gen: cachegen}
142-
key := compactDecode(kbuf)
143-
if key[len(key)-1] == 16 {
142+
key := compactToHex(kbuf)
143+
if hasTerm(key) {
144144
// value node
145145
val, _, err := rlp.SplitString(rest)
146146
if err != nil {

‎trie/proof.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ import (
3838
// absence of the key.
3939
func (t *Trie) Prove(key []byte) []rlp.RawValue {
4040
// Collect all nodes on the path to key.
41-
key = compactHexDecode(key)
41+
key = keybytesToHex(key)
4242
nodes := []node{}
4343
tn := t.root
4444
for len(key) > 0 && tn != nil {
@@ -89,7 +89,7 @@ func (t *Trie) Prove(key []byte) []rlp.RawValue {
8989
// returns an error if the proof contains invalid trie nodes or the
9090
// wrong value.
9191
func VerifyProof(rootHash common.Hash, key []byte, proof []rlp.RawValue) (value []byte, err error) {
92-
key = compactHexDecode(key)
92+
key = keybytesToHex(key)
9393
sha := sha3.NewKeccak256()
9494
wantHash := rootHash.Bytes()
9595
for i, buf := range proof {

0 commit comments

Comments
 (0)