github.com/core-coin/go-core/v2@v2.1.9/trie/stacktrie.go (about) 1 // Copyright 2020 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package trie 18 19 import ( 20 "errors" 21 "fmt" 22 "sync" 23 24 "github.com/core-coin/go-core/v2/xcbdb" 25 26 "github.com/core-coin/go-core/v2/common" 27 "github.com/core-coin/go-core/v2/log" 28 "github.com/core-coin/go-core/v2/rlp" 29 ) 30 31 var ErrCommitDisabled = errors.New("no database for committing") 32 33 var stPool = sync.Pool{ 34 New: func() interface{} { 35 return NewStackTrie(nil) 36 }, 37 } 38 39 func stackTrieFromPool(db xcbdb.KeyValueStore) *StackTrie { 40 st := stPool.Get().(*StackTrie) 41 st.db = db 42 return st 43 } 44 45 func returnToPool(st *StackTrie) { 46 st.Reset() 47 stPool.Put(st) 48 } 49 50 // StackTrie is a trie implementation that expects keys to be inserted 51 // in order. Once it determines that a subtree will no longer be inserted 52 // into, it will hash it and free up the memory it uses. 53 type StackTrie struct { 54 nodeType uint8 // node type (as in branch, ext, leaf) 55 val []byte // value contained by this node if it's a leaf 56 key []byte // key chunk covered by this (full|ext) node 57 keyOffset int // offset of the key chunk inside a full key 58 children [16]*StackTrie // list of children (for fullnodes and exts) 59 60 db xcbdb.KeyValueStore // Pointer to the commit db, can be nil 61 } 62 63 // NewStackTrie allocates and initializes an empty trie. 64 func NewStackTrie(db xcbdb.KeyValueStore) *StackTrie { 65 return &StackTrie{ 66 nodeType: emptyNode, 67 db: db, 68 } 69 } 70 71 func newLeaf(ko int, key, val []byte, db xcbdb.KeyValueStore) *StackTrie { 72 st := stackTrieFromPool(db) 73 st.nodeType = leafNode 74 st.keyOffset = ko 75 st.key = append(st.key, key[ko:]...) 76 st.val = val 77 return st 78 } 79 80 func newExt(ko int, key []byte, child *StackTrie, db xcbdb.KeyValueStore) *StackTrie { 81 st := stackTrieFromPool(db) 82 st.nodeType = extNode 83 st.keyOffset = ko 84 st.key = append(st.key, key[ko:]...) 85 st.children[0] = child 86 return st 87 } 88 89 // List all values that StackTrie#nodeType can hold 90 const ( 91 emptyNode = iota 92 branchNode 93 extNode 94 leafNode 95 hashedNode 96 ) 97 98 // TryUpdate inserts a (key, value) pair into the stack trie 99 func (st *StackTrie) TryUpdate(key, value []byte) error { 100 k := keybytesToHex(key) 101 if len(value) == 0 { 102 panic("deletion not supported") 103 } 104 st.insert(k[:len(k)-1], value) 105 return nil 106 } 107 108 func (st *StackTrie) Update(key, value []byte) { 109 if err := st.TryUpdate(key, value); err != nil { 110 log.Error(fmt.Sprintf("Unhandled trie error: %v", err)) 111 } 112 } 113 114 func (st *StackTrie) Reset() { 115 st.db = nil 116 st.key = st.key[:0] 117 st.val = nil 118 for i := range st.children { 119 st.children[i] = nil 120 } 121 st.nodeType = emptyNode 122 st.keyOffset = 0 123 } 124 125 // Helper function that, given a full key, determines the index 126 // at which the chunk pointed by st.keyOffset is different from 127 // the same chunk in the full key. 128 func (st *StackTrie) getDiffIndex(key []byte) int { 129 diffindex := 0 130 for ; diffindex < len(st.key) && st.key[diffindex] == key[st.keyOffset+diffindex]; diffindex++ { 131 } 132 return diffindex 133 } 134 135 // Helper function to that inserts a (key, value) pair into 136 // the trie. 137 func (st *StackTrie) insert(key, value []byte) { 138 switch st.nodeType { 139 case branchNode: /* Branch */ 140 idx := int(key[st.keyOffset]) 141 // Unresolve elder siblings 142 for i := idx - 1; i >= 0; i-- { 143 if st.children[i] != nil { 144 if st.children[i].nodeType != hashedNode { 145 st.children[i].hash() 146 } 147 break 148 } 149 } 150 // Add new child 151 if st.children[idx] == nil { 152 st.children[idx] = stackTrieFromPool(st.db) 153 st.children[idx].keyOffset = st.keyOffset + 1 154 } 155 st.children[idx].insert(key, value) 156 case extNode: /* Ext */ 157 // Compare both key chunks and see where they differ 158 diffidx := st.getDiffIndex(key) 159 160 // Check if chunks are identical. If so, recurse into 161 // the child node. Otherwise, the key has to be split 162 // into 1) an optional common prefix, 2) the fullnode 163 // representing the two differing path, and 3) a leaf 164 // for each of the differentiated subtrees. 165 if diffidx == len(st.key) { 166 // Ext key and key segment are identical, recurse into 167 // the child node. 168 st.children[0].insert(key, value) 169 return 170 } 171 // Save the original part. Depending if the break is 172 // at the extension's last byte or not, create an 173 // intermediate extension or use the extension's child 174 // node directly. 175 var n *StackTrie 176 if diffidx < len(st.key)-1 { 177 n = newExt(diffidx+1, st.key, st.children[0], st.db) 178 } else { 179 // Break on the last byte, no need to insert 180 // an extension node: reuse the current node 181 n = st.children[0] 182 } 183 // Convert to hash 184 n.hash() 185 var p *StackTrie 186 if diffidx == 0 { 187 // the break is on the first byte, so 188 // the current node is converted into 189 // a branch node. 190 st.children[0] = nil 191 p = st 192 st.nodeType = branchNode 193 } else { 194 // the common prefix is at least one byte 195 // long, insert a new intermediate branch 196 // node. 197 st.children[0] = stackTrieFromPool(st.db) 198 st.children[0].nodeType = branchNode 199 st.children[0].keyOffset = st.keyOffset + diffidx 200 p = st.children[0] 201 } 202 // Create a leaf for the inserted part 203 o := newLeaf(st.keyOffset+diffidx+1, key, value, st.db) 204 205 // Insert both child leaves where they belong: 206 origIdx := st.key[diffidx] 207 newIdx := key[diffidx+st.keyOffset] 208 p.children[origIdx] = n 209 p.children[newIdx] = o 210 st.key = st.key[:diffidx] 211 212 case leafNode: /* Leaf */ 213 // Compare both key chunks and see where they differ 214 diffidx := st.getDiffIndex(key) 215 216 // Overwriting a key isn't supported, which means that 217 // the current leaf is expected to be split into 1) an 218 // optional extension for the common prefix of these 2 219 // keys, 2) a fullnode selecting the path on which the 220 // keys differ, and 3) one leaf for the differentiated 221 // component of each key. 222 if diffidx >= len(st.key) { 223 panic("Trying to insert into existing key") 224 } 225 226 // Check if the split occurs at the first nibble of the 227 // chunk. In that case, no prefix extnode is necessary. 228 // Otherwise, create that 229 var p *StackTrie 230 if diffidx == 0 { 231 // Convert current leaf into a branch 232 st.nodeType = branchNode 233 p = st 234 st.children[0] = nil 235 } else { 236 // Convert current node into an ext, 237 // and insert a child branch node. 238 st.nodeType = extNode 239 st.children[0] = NewStackTrie(st.db) 240 st.children[0].nodeType = branchNode 241 st.children[0].keyOffset = st.keyOffset + diffidx 242 p = st.children[0] 243 } 244 245 // Create the two child leaves: the one containing the 246 // original value and the one containing the new value 247 // The child leave will be hashed directly in order to 248 // free up some memory. 249 origIdx := st.key[diffidx] 250 p.children[origIdx] = newLeaf(diffidx+1, st.key, st.val, st.db) 251 p.children[origIdx].hash() 252 253 newIdx := key[diffidx+st.keyOffset] 254 p.children[newIdx] = newLeaf(p.keyOffset+1, key, value, st.db) 255 256 // Finally, cut off the key part that has been passed 257 // over to the children. 258 st.key = st.key[:diffidx] 259 st.val = nil 260 case emptyNode: /* Empty */ 261 st.nodeType = leafNode 262 st.key = key[st.keyOffset:] 263 st.val = value 264 case hashedNode: 265 panic("trying to insert into hash") 266 default: 267 panic("invalid type") 268 } 269 } 270 271 // hash() hashes the node 'st' and converts it into 'hashedNode', if possible. 272 // Possible outcomes: 273 // 1. The rlp-encoded value was >= 32 bytes: 274 // - Then the 32-byte `hash` will be accessible in `st.val`. 275 // - And the 'st.type' will be 'hashedNode' 276 // 277 // 2. The rlp-encoded value was < 32 bytes 278 // - Then the <32 byte rlp-encoded value will be accessible in 'st.val'. 279 // - And the 'st.type' will be 'hashedNode' AGAIN 280 // 281 // This method will also: 282 // set 'st.type' to hashedNode 283 // clear 'st.key' 284 func (st *StackTrie) hash() { 285 /* Shortcut if node is already hashed */ 286 if st.nodeType == hashedNode { 287 return 288 } 289 // The 'hasher' is taken from a pool, but we don't actually 290 // claim an instance until all children are done with their hashing, 291 // and we actually need one 292 var h *hasher 293 294 switch st.nodeType { 295 case branchNode: 296 var nodes [17]node 297 for i, child := range st.children { 298 if child == nil { 299 nodes[i] = nilValueNode 300 continue 301 } 302 child.hash() 303 if len(child.val) < 32 { 304 nodes[i] = rawNode(child.val) 305 } else { 306 nodes[i] = hashNode(child.val) 307 } 308 st.children[i] = nil // Reclaim mem from subtree 309 returnToPool(child) 310 } 311 nodes[16] = nilValueNode 312 h = newHasher(false) 313 defer returnHasherToPool(h) 314 h.tmp.Reset() 315 if err := rlp.Encode(&h.tmp, nodes); err != nil { 316 panic(err) 317 } 318 case extNode: 319 st.children[0].hash() 320 h = newHasher(false) 321 defer returnHasherToPool(h) 322 h.tmp.Reset() 323 var valuenode node 324 if len(st.children[0].val) < 32 { 325 valuenode = rawNode(st.children[0].val) 326 } else { 327 valuenode = hashNode(st.children[0].val) 328 } 329 n := struct { 330 Key []byte 331 Val node 332 }{ 333 Key: hexToCompact(st.key), 334 Val: valuenode, 335 } 336 if err := rlp.Encode(&h.tmp, n); err != nil { 337 panic(err) 338 } 339 returnToPool(st.children[0]) 340 st.children[0] = nil // Reclaim mem from subtree 341 case leafNode: 342 h = newHasher(false) 343 defer returnHasherToPool(h) 344 h.tmp.Reset() 345 st.key = append(st.key, byte(16)) 346 sz := hexToCompactInPlace(st.key) 347 n := [][]byte{st.key[:sz], st.val} 348 if err := rlp.Encode(&h.tmp, n); err != nil { 349 panic(err) 350 } 351 case emptyNode: 352 st.val = st.val[:0] 353 st.val = append(st.val, emptyRoot[:]...) 354 st.key = st.key[:0] 355 st.nodeType = hashedNode 356 return 357 default: 358 panic("Invalid node type") 359 } 360 st.key = st.key[:0] 361 st.nodeType = hashedNode 362 if len(h.tmp) < 32 { 363 st.val = st.val[:0] 364 st.val = append(st.val, h.tmp...) 365 return 366 } 367 // Going to write the hash to the 'val'. Need to ensure it's properly sized first 368 // Typically, 'branchNode's will have no 'val', and require this allocation 369 if required := 32 - len(st.val); required > 0 { 370 buf := make([]byte, required) 371 st.val = append(st.val, buf...) 372 } 373 st.val = st.val[:32] 374 h.sha.Reset() 375 h.sha.Write(h.tmp) 376 h.sha.Read(st.val) 377 if st.db != nil { 378 // TODO! Is it safe to Put the slice here? 379 // Do all db implementations copy the value provided? 380 st.db.Put(st.val, h.tmp) 381 } 382 } 383 384 // Hash returns the hash of the current node 385 func (st *StackTrie) Hash() (h common.Hash) { 386 st.hash() 387 if len(st.val) != 32 { 388 // If the node's RLP isn't 32 bytes long, the node will not 389 // be hashed, and instead contain the rlp-encoding of the 390 // node. For the top level node, we need to force the hashing. 391 ret := make([]byte, 32) 392 h := newHasher(false) 393 defer returnHasherToPool(h) 394 h.sha.Reset() 395 h.sha.Write(st.val) 396 h.sha.Read(ret) 397 return common.BytesToHash(ret) 398 } 399 return common.BytesToHash(st.val) 400 } 401 402 // Commit will firstly hash the entrie trie if it's still not hashed 403 // and then commit all nodes to the associated database. Actually most 404 // of the trie nodes MAY have been committed already. The main purpose 405 // here is to commit the root node. 406 // 407 // The associated database is expected, otherwise the whole commit 408 // functionality should be disabled. 409 func (st *StackTrie) Commit() (common.Hash, error) { 410 if st.db == nil { 411 return common.Hash{}, ErrCommitDisabled 412 } 413 st.hash() 414 if len(st.val) != 32 { 415 // If the node's RLP isn't 32 bytes long, the node will not 416 // be hashed (and committed), and instead contain the rlp-encoding of the 417 // node. For the top level node, we need to force the hashing+commit. 418 ret := make([]byte, 32) 419 h := newHasher(false) 420 defer returnHasherToPool(h) 421 h.sha.Reset() 422 h.sha.Write(st.val) 423 h.sha.Read(ret) 424 st.db.Put(ret, st.val) 425 return common.BytesToHash(ret), nil 426 } 427 return common.BytesToHash(st.val), nil 428 }