node.go 6.24 KB
Newer Older
1
// Copyright 2014 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 13 14
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
15
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16

17
package trie
obscuren's avatar
obscuren committed
18

Felix Lange's avatar
Felix Lange committed
19 20 21 22 23 24 25 26
import (
	"fmt"
	"io"
	"strings"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/rlp"
)
obscuren's avatar
obscuren committed
27 28 29

var indices = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "[17]"}

Felix Lange's avatar
Felix Lange committed
30
type node interface {
obscuren's avatar
obscuren committed
31
	fstring(string) string
32
	cache() (hashNode, bool)
obscuren's avatar
obscuren committed
33 34
}

Felix Lange's avatar
Felix Lange committed
35
type (
36 37
	fullNode struct {
		Children [17]node // Actual trie node data to encode/decode (needs custom encoder)
38
		flags    nodeFlag
39
	}
Felix Lange's avatar
Felix Lange committed
40
	shortNode struct {
41 42
		Key   []byte
		Val   node
43
		flags nodeFlag
Felix Lange's avatar
Felix Lange committed
44 45 46 47
	}
	hashNode  []byte
	valueNode []byte
)
48

49 50 51 52
// nilValueNode is used when collapsing internal trie nodes for hashing, since
// unset children need to serialize correctly.
var nilValueNode = valueNode(nil)

53
// EncodeRLP encodes a full node into the consensus RLP format.
54
func (n *fullNode) EncodeRLP(w io.Writer) error {
55 56
	var nodes [17]node

57
	for i, child := range &n.Children {
58 59 60 61 62 63 64
		if child != nil {
			nodes[i] = child
		} else {
			nodes[i] = nilValueNode
		}
	}
	return rlp.Encode(w, nodes)
65 66
}

67 68 69 70 71 72 73 74 75 76 77 78 79
func (n *fullNode) copy() *fullNode   { copy := *n; return &copy }
func (n *shortNode) copy() *shortNode { copy := *n; return &copy }

// nodeFlag contains caching-related metadata about a node.
type nodeFlag struct {
	hash  hashNode // cached hash of the node (may be nil)
	dirty bool     // whether the node has changes that must be written to the database
}

func (n *fullNode) cache() (hashNode, bool)  { return n.flags.hash, n.flags.dirty }
func (n *shortNode) cache() (hashNode, bool) { return n.flags.hash, n.flags.dirty }
func (n hashNode) cache() (hashNode, bool)   { return nil, true }
func (n valueNode) cache() (hashNode, bool)  { return nil, true }
80

Felix Lange's avatar
Felix Lange committed
81
// Pretty printing.
82 83 84 85
func (n *fullNode) String() string  { return n.fstring("") }
func (n *shortNode) String() string { return n.fstring("") }
func (n hashNode) String() string   { return n.fstring("") }
func (n valueNode) String() string  { return n.fstring("") }
obscuren's avatar
obscuren committed
86

87
func (n *fullNode) fstring(ind string) string {
obscuren's avatar
obscuren committed
88
	resp := fmt.Sprintf("[\n%s  ", ind)
89
	for i, node := range &n.Children {
obscuren's avatar
obscuren committed
90 91 92 93 94 95 96 97
		if node == nil {
			resp += fmt.Sprintf("%s: <nil> ", indices[i])
		} else {
			resp += fmt.Sprintf("%s: %v", indices[i], node.fstring(ind+"  "))
		}
	}
	return resp + fmt.Sprintf("\n%s] ", ind)
}
98
func (n *shortNode) fstring(ind string) string {
Felix Lange's avatar
Felix Lange committed
99 100 101 102 103 104 105 106 107
	return fmt.Sprintf("{%x: %v} ", n.Key, n.Val.fstring(ind+"  "))
}
func (n hashNode) fstring(ind string) string {
	return fmt.Sprintf("<%x> ", []byte(n))
}
func (n valueNode) fstring(ind string) string {
	return fmt.Sprintf("%x ", []byte(n))
}

108 109
func mustDecodeNode(hash, buf []byte) node {
	n, err := decodeNode(hash, buf)
Felix Lange's avatar
Felix Lange committed
110
	if err != nil {
111
		panic(fmt.Sprintf("node %x: %v", hash, err))
Felix Lange's avatar
Felix Lange committed
112 113 114 115 116
	}
	return n
}

// decodeNode parses the RLP encoding of a trie node.
117
func decodeNode(hash, buf []byte) (node, error) {
Felix Lange's avatar
Felix Lange committed
118 119 120 121 122 123 124 125 126
	if len(buf) == 0 {
		return nil, io.ErrUnexpectedEOF
	}
	elems, _, err := rlp.SplitList(buf)
	if err != nil {
		return nil, fmt.Errorf("decode error: %v", err)
	}
	switch c, _ := rlp.CountValues(elems); c {
	case 2:
127
		n, err := decodeShort(hash, elems)
Felix Lange's avatar
Felix Lange committed
128 129
		return n, wrapError(err, "short")
	case 17:
130
		n, err := decodeFull(hash, elems)
Felix Lange's avatar
Felix Lange committed
131 132 133 134 135 136
		return n, wrapError(err, "full")
	default:
		return nil, fmt.Errorf("invalid number of list elements: %v", c)
	}
}

137
func decodeShort(hash, elems []byte) (node, error) {
138
	kbuf, rest, err := rlp.SplitString(elems)
Felix Lange's avatar
Felix Lange committed
139 140 141
	if err != nil {
		return nil, err
	}
142
	flag := nodeFlag{hash: hash}
143 144
	key := compactToHex(kbuf)
	if hasTerm(key) {
Felix Lange's avatar
Felix Lange committed
145 146 147 148 149
		// value node
		val, _, err := rlp.SplitString(rest)
		if err != nil {
			return nil, fmt.Errorf("invalid value node: %v", err)
		}
150
		return &shortNode{key, append(valueNode{}, val...), flag}, nil
Felix Lange's avatar
Felix Lange committed
151
	}
152
	r, _, err := decodeRef(rest)
Felix Lange's avatar
Felix Lange committed
153 154 155
	if err != nil {
		return nil, wrapError(err, "val")
	}
156
	return &shortNode{key, r, flag}, nil
Felix Lange's avatar
Felix Lange committed
157 158
}

159 160
func decodeFull(hash, elems []byte) (*fullNode, error) {
	n := &fullNode{flags: nodeFlag{hash: hash}}
Felix Lange's avatar
Felix Lange committed
161
	for i := 0; i < 16; i++ {
162
		cld, rest, err := decodeRef(elems)
Felix Lange's avatar
Felix Lange committed
163 164 165
		if err != nil {
			return n, wrapError(err, fmt.Sprintf("[%d]", i))
		}
166
		n.Children[i], elems = cld, rest
Felix Lange's avatar
Felix Lange committed
167
	}
168
	val, _, err := rlp.SplitString(elems)
Felix Lange's avatar
Felix Lange committed
169 170 171 172
	if err != nil {
		return n, err
	}
	if len(val) > 0 {
173
		n.Children[16] = append(valueNode{}, val...)
Felix Lange's avatar
Felix Lange committed
174 175 176 177 178 179
	}
	return n, nil
}

const hashLen = len(common.Hash{})

180
func decodeRef(buf []byte) (node, []byte, error) {
Felix Lange's avatar
Felix Lange committed
181 182 183 184 185 186 187 188 189 190 191 192
	kind, val, rest, err := rlp.Split(buf)
	if err != nil {
		return nil, buf, err
	}
	switch {
	case kind == rlp.List:
		// 'embedded' node reference. The encoding must be smaller
		// than a hash in order to be valid.
		if size := len(buf) - len(rest); size > hashLen {
			err := fmt.Errorf("oversized embedded node (size is %d bytes, want size < %d)", size, hashLen)
			return nil, buf, err
		}
193
		n, err := decodeNode(nil, buf)
Felix Lange's avatar
Felix Lange committed
194 195 196 197 198
		return n, rest, err
	case kind == rlp.String && len(val) == 0:
		// empty node
		return nil, rest, nil
	case kind == rlp.String && len(val) == 32:
199
		return append(hashNode{}, val...), rest, nil
Felix Lange's avatar
Felix Lange committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
	default:
		return nil, nil, fmt.Errorf("invalid RLP string size %d (want 0 or 32)", len(val))
	}
}

// wraps a decoding error with information about the path to the
// invalid child node (for debugging encoding issues).
type decodeError struct {
	what  error
	stack []string
}

func wrapError(err error, ctx string) error {
	if err == nil {
		return nil
	}
	if decErr, ok := err.(*decodeError); ok {
		decErr.stack = append(decErr.stack, ctx)
		return decErr
	}
	return &decodeError{err, []string{ctx}}
}
obscuren's avatar
obscuren committed
222

Felix Lange's avatar
Felix Lange committed
223 224
func (err *decodeError) Error() string {
	return fmt.Sprintf("%v (decode path: %s)", err.what, strings.Join(err.stack, "<-"))
obscuren's avatar
obscuren committed
225
}