github.com/theQRL/go-zond@v0.1.1/trie/node.go (about) 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 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 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 // GNU Lesser General Public License for more details. 13 // 14 // 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 18 19 import ( 20 "fmt" 21 "io" 22 "strings" 23 24 "github.com/theQRL/go-zond/common" 25 "github.com/theQRL/go-zond/rlp" 26 ) 27 28 var indices = []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "[17]"} 29 30 type node interface { 31 cache() (hashNode, bool) 32 encode(w rlp.EncoderBuffer) 33 fstring(string) string 34 } 35 36 type ( 37 fullNode struct { 38 Children [17]node // Actual trie node data to encode/decode (needs custom encoder) 39 flags nodeFlag 40 } 41 shortNode struct { 42 Key []byte 43 Val node 44 flags nodeFlag 45 } 46 hashNode []byte 47 valueNode []byte 48 ) 49 50 // nilValueNode is used when collapsing internal trie nodes for hashing, since 51 // unset children need to serialize correctly. 52 var nilValueNode = valueNode(nil) 53 54 // EncodeRLP encodes a full node into the consensus RLP format. 55 func (n *fullNode) EncodeRLP(w io.Writer) error { 56 eb := rlp.NewEncoderBuffer(w) 57 n.encode(eb) 58 return eb.Flush() 59 } 60 61 func (n *fullNode) copy() *fullNode { copy := *n; return © } 62 func (n *shortNode) copy() *shortNode { copy := *n; return © } 63 64 // nodeFlag contains caching-related metadata about a node. 65 type nodeFlag struct { 66 hash hashNode // cached hash of the node (may be nil) 67 dirty bool // whether the node has changes that must be written to the database 68 } 69 70 func (n *fullNode) cache() (hashNode, bool) { return n.flags.hash, n.flags.dirty } 71 func (n *shortNode) cache() (hashNode, bool) { return n.flags.hash, n.flags.dirty } 72 func (n hashNode) cache() (hashNode, bool) { return nil, true } 73 func (n valueNode) cache() (hashNode, bool) { return nil, true } 74 75 // Pretty printing. 76 func (n *fullNode) String() string { return n.fstring("") } 77 func (n *shortNode) String() string { return n.fstring("") } 78 func (n hashNode) String() string { return n.fstring("") } 79 func (n valueNode) String() string { return n.fstring("") } 80 81 func (n *fullNode) fstring(ind string) string { 82 resp := fmt.Sprintf("[\n%s ", ind) 83 for i, node := range &n.Children { 84 if node == nil { 85 resp += fmt.Sprintf("%s: <nil> ", indices[i]) 86 } else { 87 resp += fmt.Sprintf("%s: %v", indices[i], node.fstring(ind+" ")) 88 } 89 } 90 return resp + fmt.Sprintf("\n%s] ", ind) 91 } 92 func (n *shortNode) fstring(ind string) string { 93 return fmt.Sprintf("{%x: %v} ", n.Key, n.Val.fstring(ind+" ")) 94 } 95 func (n hashNode) fstring(ind string) string { 96 return fmt.Sprintf("<%x> ", []byte(n)) 97 } 98 func (n valueNode) fstring(ind string) string { 99 return fmt.Sprintf("%x ", []byte(n)) 100 } 101 102 // rawNode is a simple binary blob used to differentiate between collapsed trie 103 // nodes and already encoded RLP binary blobs (while at the same time store them 104 // in the same cache fields). 105 type rawNode []byte 106 107 func (n rawNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") } 108 func (n rawNode) fstring(ind string) string { panic("this should never end up in a live trie") } 109 110 func (n rawNode) EncodeRLP(w io.Writer) error { 111 _, err := w.Write(n) 112 return err 113 } 114 115 // mustDecodeNode is a wrapper of decodeNode and panic if any error is encountered. 116 func mustDecodeNode(hash, buf []byte) node { 117 n, err := decodeNode(hash, buf) 118 if err != nil { 119 panic(fmt.Sprintf("node %x: %v", hash, err)) 120 } 121 return n 122 } 123 124 // mustDecodeNodeUnsafe is a wrapper of decodeNodeUnsafe and panic if any error is 125 // encountered. 126 func mustDecodeNodeUnsafe(hash, buf []byte) node { 127 n, err := decodeNodeUnsafe(hash, buf) 128 if err != nil { 129 panic(fmt.Sprintf("node %x: %v", hash, err)) 130 } 131 return n 132 } 133 134 // decodeNode parses the RLP encoding of a trie node. It will deep-copy the passed 135 // byte slice for decoding, so it's safe to modify the byte slice afterwards. The- 136 // decode performance of this function is not optimal, but it is suitable for most 137 // scenarios with low performance requirements and hard to determine whether the 138 // byte slice be modified or not. 139 func decodeNode(hash, buf []byte) (node, error) { 140 return decodeNodeUnsafe(hash, common.CopyBytes(buf)) 141 } 142 143 // decodeNodeUnsafe parses the RLP encoding of a trie node. The passed byte slice 144 // will be directly referenced by node without bytes deep copy, so the input MUST 145 // not be changed after. 146 func decodeNodeUnsafe(hash, buf []byte) (node, error) { 147 if len(buf) == 0 { 148 return nil, io.ErrUnexpectedEOF 149 } 150 elems, _, err := rlp.SplitList(buf) 151 if err != nil { 152 return nil, fmt.Errorf("decode error: %v", err) 153 } 154 switch c, _ := rlp.CountValues(elems); c { 155 case 2: 156 n, err := decodeShort(hash, elems) 157 return n, wrapError(err, "short") 158 case 17: 159 n, err := decodeFull(hash, elems) 160 return n, wrapError(err, "full") 161 default: 162 return nil, fmt.Errorf("invalid number of list elements: %v", c) 163 } 164 } 165 166 func decodeShort(hash, elems []byte) (node, error) { 167 kbuf, rest, err := rlp.SplitString(elems) 168 if err != nil { 169 return nil, err 170 } 171 flag := nodeFlag{hash: hash} 172 key := compactToHex(kbuf) 173 if hasTerm(key) { 174 // value node 175 val, _, err := rlp.SplitString(rest) 176 if err != nil { 177 return nil, fmt.Errorf("invalid value node: %v", err) 178 } 179 return &shortNode{key, valueNode(val), flag}, nil 180 } 181 r, _, err := decodeRef(rest) 182 if err != nil { 183 return nil, wrapError(err, "val") 184 } 185 return &shortNode{key, r, flag}, nil 186 } 187 188 func decodeFull(hash, elems []byte) (*fullNode, error) { 189 n := &fullNode{flags: nodeFlag{hash: hash}} 190 for i := 0; i < 16; i++ { 191 cld, rest, err := decodeRef(elems) 192 if err != nil { 193 return n, wrapError(err, fmt.Sprintf("[%d]", i)) 194 } 195 n.Children[i], elems = cld, rest 196 } 197 val, _, err := rlp.SplitString(elems) 198 if err != nil { 199 return n, err 200 } 201 if len(val) > 0 { 202 n.Children[16] = valueNode(val) 203 } 204 return n, nil 205 } 206 207 const hashLen = len(common.Hash{}) 208 209 func decodeRef(buf []byte) (node, []byte, error) { 210 kind, val, rest, err := rlp.Split(buf) 211 if err != nil { 212 return nil, buf, err 213 } 214 switch { 215 case kind == rlp.List: 216 // 'embedded' node reference. The encoding must be smaller 217 // than a hash in order to be valid. 218 if size := len(buf) - len(rest); size > hashLen { 219 err := fmt.Errorf("oversized embedded node (size is %d bytes, want size < %d)", size, hashLen) 220 return nil, buf, err 221 } 222 n, err := decodeNode(nil, buf) 223 return n, rest, err 224 case kind == rlp.String && len(val) == 0: 225 // empty node 226 return nil, rest, nil 227 case kind == rlp.String && len(val) == 32: 228 return hashNode(val), rest, nil 229 default: 230 return nil, nil, fmt.Errorf("invalid RLP string size %d (want 0 or 32)", len(val)) 231 } 232 } 233 234 // wraps a decoding error with information about the path to the 235 // invalid child node (for debugging encoding issues). 236 type decodeError struct { 237 what error 238 stack []string 239 } 240 241 func wrapError(err error, ctx string) error { 242 if err == nil { 243 return nil 244 } 245 if decErr, ok := err.(*decodeError); ok { 246 decErr.stack = append(decErr.stack, ctx) 247 return decErr 248 } 249 return &decodeError{err, []string{ctx}} 250 } 251 252 func (err *decodeError) Error() string { 253 return fmt.Sprintf("%v (decode path: %s)", err.what, strings.Join(err.stack, "<-")) 254 }