Skip to content

Commit 2fd8ea9

Browse files
committed
Improved code for inlined nodes decoding
1 parent 37c3d46 commit 2fd8ea9

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed

internal/trie/node/decode.go

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ func Decode(reader io.Reader) (n *Node, err error) {
5050
}
5151
}
5252

53+
var ErrInlinedVariantNotSupported = errors.New("inlined variant not supported")
54+
5355
// decodeBranch reads from a reader and decodes to a node branch.
5456
// Note that since the encoded branch stores the hash of the children nodes, we are not
5557
// reconstructing the child nodes from the encoding. This function instead stubs where the
@@ -95,22 +97,32 @@ func decodeBranch(reader io.Reader, variant byte, partialKeyLength uint16) (
9597
}
9698

9799
const hashLength = 32
98-
childNode := &Node{
99-
HashDigest: hash,
100-
}
101-
if len(hash) < hashLength {
102-
// Handle inlined nodes
103-
reader = bytes.NewReader(hash)
104-
variant, partialKeyLength, err := decodeHeader(reader)
105-
if err == nil && variant == leafVariant.bits {
106-
childNode, err = decodeLeaf(reader, partialKeyLength)
107-
if err != nil {
108-
return nil, fmt.Errorf("%w: at index %d: %s",
109-
ErrDecodeValue, i, err)
110-
}
100+
if len(hash) == hashLength {
101+
node.Descendants++
102+
node.Children[i] = &Node{
103+
HashDigest: hash,
111104
}
105+
continue
106+
}
107+
108+
// Handle inlined nodes
109+
reader = bytes.NewReader(hash)
110+
variant, partialKeyLength, err := decodeHeader(reader)
111+
if err != nil {
112+
return nil, fmt.Errorf("malformed inlined node: 0x%x: %w", hash, err)
112113
}
113114

115+
var childNode *Node
116+
switch variant {
117+
case leafVariant.bits:
118+
childNode, err = decodeLeaf(reader, partialKeyLength)
119+
if err != nil {
120+
return nil, fmt.Errorf("%w: at index %d: %s",
121+
ErrDecodeValue, i, err)
122+
}
123+
default:
124+
return nil, fmt.Errorf("%w: %08b", ErrInlinedVariantNotSupported, variant)
125+
}
114126
node.Descendants++
115127
node.Children[i] = childNode
116128
}

0 commit comments

Comments
 (0)