gitee.com/liu-zhao234568/cntest@v1.0.0/trie/iterator.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 "bytes" 21 "container/heap" 22 "errors" 23 24 "gitee.com/liu-zhao234568/cntest/common" 25 "gitee.com/liu-zhao234568/cntest/ethdb" 26 "gitee.com/liu-zhao234568/cntest/rlp" 27 ) 28 29 // Iterator is a key-value trie iterator that traverses a Trie. 30 type Iterator struct { 31 nodeIt NodeIterator 32 33 Key []byte // Current data key on which the iterator is positioned on 34 Value []byte // Current data value on which the iterator is positioned on 35 Err error 36 } 37 38 // NewIterator creates a new key-value iterator from a node iterator. 39 // Note that the value returned by the iterator is raw. If the content is encoded 40 // (e.g. storage value is RLP-encoded), it's caller's duty to decode it. 41 func NewIterator(it NodeIterator) *Iterator { 42 return &Iterator{ 43 nodeIt: it, 44 } 45 } 46 47 // Next moves the iterator forward one key-value entry. 48 func (it *Iterator) Next() bool { 49 for it.nodeIt.Next(true) { 50 if it.nodeIt.Leaf() { 51 it.Key = it.nodeIt.LeafKey() 52 it.Value = it.nodeIt.LeafBlob() 53 return true 54 } 55 } 56 it.Key = nil 57 it.Value = nil 58 it.Err = it.nodeIt.Error() 59 return false 60 } 61 62 // Prove generates the Merkle proof for the leaf node the iterator is currently 63 // positioned on. 64 func (it *Iterator) Prove() [][]byte { 65 return it.nodeIt.LeafProof() 66 } 67 68 // NodeIterator is an iterator to traverse the trie pre-order. 69 type NodeIterator interface { 70 // Next moves the iterator to the next node. If the parameter is false, any child 71 // nodes will be skipped. 72 Next(bool) bool 73 74 // Error returns the error status of the iterator. 75 Error() error 76 77 // Hash returns the hash of the current node. 78 Hash() common.Hash 79 80 // Parent returns the hash of the parent of the current node. The hash may be the one 81 // grandparent if the immediate parent is an internal node with no hash. 82 Parent() common.Hash 83 84 // Path returns the hex-encoded path to the current node. 85 // Callers must not retain references to the return value after calling Next. 86 // For leaf nodes, the last element of the path is the 'terminator symbol' 0x10. 87 Path() []byte 88 89 // Leaf returns true iff the current node is a leaf node. 90 Leaf() bool 91 92 // LeafKey returns the key of the leaf. The method panics if the iterator is not 93 // positioned at a leaf. Callers must not retain references to the value after 94 // calling Next. 95 LeafKey() []byte 96 97 // LeafBlob returns the content of the leaf. The method panics if the iterator 98 // is not positioned at a leaf. Callers must not retain references to the value 99 // after calling Next. 100 LeafBlob() []byte 101 102 // LeafProof returns the Merkle proof of the leaf. The method panics if the 103 // iterator is not positioned at a leaf. Callers must not retain references 104 // to the value after calling Next. 105 LeafProof() [][]byte 106 107 // AddResolver sets an intermediate database to use for looking up trie nodes 108 // before reaching into the real persistent layer. 109 // 110 // This is not required for normal operation, rather is an optimization for 111 // cases where trie nodes can be recovered from some external mechanism without 112 // reading from disk. In those cases, this resolver allows short circuiting 113 // accesses and returning them from memory. 114 // 115 // Before adding a similar mechanism to any other place in Geth, consider 116 // making trie.Database an interface and wrapping at that level. It's a huge 117 // refactor, but it could be worth it if another occurrence arises. 118 AddResolver(ethdb.KeyValueStore) 119 } 120 121 // nodeIteratorState represents the iteration state at one particular node of the 122 // trie, which can be resumed at a later invocation. 123 type nodeIteratorState struct { 124 hash common.Hash // Hash of the node being iterated (nil if not standalone) 125 node node // Trie node being iterated 126 parent common.Hash // Hash of the first full ancestor node (nil if current is the root) 127 index int // Child to be processed next 128 pathlen int // Length of the path to this node 129 } 130 131 type nodeIterator struct { 132 trie *Trie // Trie being iterated 133 stack []*nodeIteratorState // Hierarchy of trie nodes persisting the iteration state 134 path []byte // Path to the current node 135 err error // Failure set in case of an internal error in the iterator 136 137 resolver ethdb.KeyValueStore // Optional intermediate resolver above the disk layer 138 } 139 140 // errIteratorEnd is stored in nodeIterator.err when iteration is done. 141 var errIteratorEnd = errors.New("end of iteration") 142 143 // seekError is stored in nodeIterator.err if the initial seek has failed. 144 type seekError struct { 145 key []byte 146 err error 147 } 148 149 func (e seekError) Error() string { 150 return "seek error: " + e.err.Error() 151 } 152 153 func newNodeIterator(trie *Trie, start []byte) NodeIterator { 154 if trie.Hash() == emptyState { 155 return new(nodeIterator) 156 } 157 it := &nodeIterator{trie: trie} 158 it.err = it.seek(start) 159 return it 160 } 161 162 func (it *nodeIterator) AddResolver(resolver ethdb.KeyValueStore) { 163 it.resolver = resolver 164 } 165 166 func (it *nodeIterator) Hash() common.Hash { 167 if len(it.stack) == 0 { 168 return common.Hash{} 169 } 170 return it.stack[len(it.stack)-1].hash 171 } 172 173 func (it *nodeIterator) Parent() common.Hash { 174 if len(it.stack) == 0 { 175 return common.Hash{} 176 } 177 return it.stack[len(it.stack)-1].parent 178 } 179 180 func (it *nodeIterator) Leaf() bool { 181 return hasTerm(it.path) 182 } 183 184 func (it *nodeIterator) LeafKey() []byte { 185 if len(it.stack) > 0 { 186 if _, ok := it.stack[len(it.stack)-1].node.(valueNode); ok { 187 return hexToKeybytes(it.path) 188 } 189 } 190 panic("not at leaf") 191 } 192 193 func (it *nodeIterator) LeafBlob() []byte { 194 if len(it.stack) > 0 { 195 if node, ok := it.stack[len(it.stack)-1].node.(valueNode); ok { 196 return node 197 } 198 } 199 panic("not at leaf") 200 } 201 202 func (it *nodeIterator) LeafProof() [][]byte { 203 if len(it.stack) > 0 { 204 if _, ok := it.stack[len(it.stack)-1].node.(valueNode); ok { 205 hasher := newHasher(false) 206 defer returnHasherToPool(hasher) 207 proofs := make([][]byte, 0, len(it.stack)) 208 209 for i, item := range it.stack[:len(it.stack)-1] { 210 // Gather nodes that end up as hash nodes (or the root) 211 node, hashed := hasher.proofHash(item.node) 212 if _, ok := hashed.(hashNode); ok || i == 0 { 213 enc, _ := rlp.EncodeToBytes(node) 214 proofs = append(proofs, enc) 215 } 216 } 217 return proofs 218 } 219 } 220 panic("not at leaf") 221 } 222 223 func (it *nodeIterator) Path() []byte { 224 return it.path 225 } 226 227 func (it *nodeIterator) Error() error { 228 if it.err == errIteratorEnd { 229 return nil 230 } 231 if seek, ok := it.err.(seekError); ok { 232 return seek.err 233 } 234 return it.err 235 } 236 237 // Next moves the iterator to the next node, returning whether there are any 238 // further nodes. In case of an internal error this method returns false and 239 // sets the Error field to the encountered failure. If `descend` is false, 240 // skips iterating over any subnodes of the current node. 241 func (it *nodeIterator) Next(descend bool) bool { 242 if it.err == errIteratorEnd { 243 return false 244 } 245 if seek, ok := it.err.(seekError); ok { 246 if it.err = it.seek(seek.key); it.err != nil { 247 return false 248 } 249 } 250 // Otherwise step forward with the iterator and report any errors. 251 state, parentIndex, path, err := it.peek(descend) 252 it.err = err 253 if it.err != nil { 254 return false 255 } 256 it.push(state, parentIndex, path) 257 return true 258 } 259 260 func (it *nodeIterator) seek(prefix []byte) error { 261 // The path we're looking for is the hex encoded key without terminator. 262 key := keybytesToHex(prefix) 263 key = key[:len(key)-1] 264 // Move forward until we're just before the closest match to key. 265 for { 266 state, parentIndex, path, err := it.peekSeek(key) 267 if err == errIteratorEnd { 268 return errIteratorEnd 269 } else if err != nil { 270 return seekError{prefix, err} 271 } else if bytes.Compare(path, key) >= 0 { 272 return nil 273 } 274 it.push(state, parentIndex, path) 275 } 276 } 277 278 // init initializes the the iterator. 279 func (it *nodeIterator) init() (*nodeIteratorState, error) { 280 root := it.trie.Hash() 281 state := &nodeIteratorState{node: it.trie.root, index: -1} 282 if root != emptyRoot { 283 state.hash = root 284 } 285 return state, state.resolve(it, nil) 286 } 287 288 // peek creates the next state of the iterator. 289 func (it *nodeIterator) peek(descend bool) (*nodeIteratorState, *int, []byte, error) { 290 // Initialize the iterator if we've just started. 291 if len(it.stack) == 0 { 292 state, err := it.init() 293 return state, nil, nil, err 294 } 295 if !descend { 296 // If we're skipping children, pop the current node first 297 it.pop() 298 } 299 300 // Continue iteration to the next child 301 for len(it.stack) > 0 { 302 parent := it.stack[len(it.stack)-1] 303 ancestor := parent.hash 304 if (ancestor == common.Hash{}) { 305 ancestor = parent.parent 306 } 307 state, path, ok := it.nextChild(parent, ancestor) 308 if ok { 309 if err := state.resolve(it, path); err != nil { 310 return parent, &parent.index, path, err 311 } 312 return state, &parent.index, path, nil 313 } 314 // No more child nodes, move back up. 315 it.pop() 316 } 317 return nil, nil, nil, errIteratorEnd 318 } 319 320 // peekSeek is like peek, but it also tries to skip resolving hashes by skipping 321 // over the siblings that do not lead towards the desired seek position. 322 func (it *nodeIterator) peekSeek(seekKey []byte) (*nodeIteratorState, *int, []byte, error) { 323 // Initialize the iterator if we've just started. 324 if len(it.stack) == 0 { 325 state, err := it.init() 326 return state, nil, nil, err 327 } 328 if !bytes.HasPrefix(seekKey, it.path) { 329 // If we're skipping children, pop the current node first 330 it.pop() 331 } 332 333 // Continue iteration to the next child 334 for len(it.stack) > 0 { 335 parent := it.stack[len(it.stack)-1] 336 ancestor := parent.hash 337 if (ancestor == common.Hash{}) { 338 ancestor = parent.parent 339 } 340 state, path, ok := it.nextChildAt(parent, ancestor, seekKey) 341 if ok { 342 if err := state.resolve(it, path); err != nil { 343 return parent, &parent.index, path, err 344 } 345 return state, &parent.index, path, nil 346 } 347 // No more child nodes, move back up. 348 it.pop() 349 } 350 return nil, nil, nil, errIteratorEnd 351 } 352 353 func (it *nodeIterator) resolveHash(hash hashNode, path []byte) (node, error) { 354 if it.resolver != nil { 355 if blob, err := it.resolver.Get(hash); err == nil && len(blob) > 0 { 356 if resolved, err := decodeNode(hash, blob); err == nil { 357 return resolved, nil 358 } 359 } 360 } 361 resolved, err := it.trie.resolveHash(hash, path) 362 return resolved, err 363 } 364 365 func (st *nodeIteratorState) resolve(it *nodeIterator, path []byte) error { 366 if hash, ok := st.node.(hashNode); ok { 367 resolved, err := it.resolveHash(hash, path) 368 if err != nil { 369 return err 370 } 371 st.node = resolved 372 st.hash = common.BytesToHash(hash) 373 } 374 return nil 375 } 376 377 func findChild(n *fullNode, index int, path []byte, ancestor common.Hash) (node, *nodeIteratorState, []byte, int) { 378 var ( 379 child node 380 state *nodeIteratorState 381 childPath []byte 382 ) 383 for ; index < len(n.Children); index++ { 384 if n.Children[index] != nil { 385 child = n.Children[index] 386 hash, _ := child.cache() 387 state = &nodeIteratorState{ 388 hash: common.BytesToHash(hash), 389 node: child, 390 parent: ancestor, 391 index: -1, 392 pathlen: len(path), 393 } 394 childPath = append(childPath, path...) 395 childPath = append(childPath, byte(index)) 396 return child, state, childPath, index 397 } 398 } 399 return nil, nil, nil, 0 400 } 401 402 func (it *nodeIterator) nextChild(parent *nodeIteratorState, ancestor common.Hash) (*nodeIteratorState, []byte, bool) { 403 switch node := parent.node.(type) { 404 case *fullNode: 405 //Full node, move to the first non-nil child. 406 if child, state, path, index := findChild(node, parent.index+1, it.path, ancestor); child != nil { 407 parent.index = index - 1 408 return state, path, true 409 } 410 case *shortNode: 411 // Short node, return the pointer singleton child 412 if parent.index < 0 { 413 hash, _ := node.Val.cache() 414 state := &nodeIteratorState{ 415 hash: common.BytesToHash(hash), 416 node: node.Val, 417 parent: ancestor, 418 index: -1, 419 pathlen: len(it.path), 420 } 421 path := append(it.path, node.Key...) 422 return state, path, true 423 } 424 } 425 return parent, it.path, false 426 } 427 428 // nextChildAt is similar to nextChild, except that it targets a child as close to the 429 // target key as possible, thus skipping siblings. 430 func (it *nodeIterator) nextChildAt(parent *nodeIteratorState, ancestor common.Hash, key []byte) (*nodeIteratorState, []byte, bool) { 431 switch n := parent.node.(type) { 432 case *fullNode: 433 // Full node, move to the first non-nil child before the desired key position 434 child, state, path, index := findChild(n, parent.index+1, it.path, ancestor) 435 if child == nil { 436 // No more children in this fullnode 437 return parent, it.path, false 438 } 439 // If the child we found is already past the seek position, just return it. 440 if bytes.Compare(path, key) >= 0 { 441 parent.index = index - 1 442 return state, path, true 443 } 444 // The child is before the seek position. Try advancing 445 for { 446 nextChild, nextState, nextPath, nextIndex := findChild(n, index+1, it.path, ancestor) 447 // If we run out of children, or skipped past the target, return the 448 // previous one 449 if nextChild == nil || bytes.Compare(nextPath, key) >= 0 { 450 parent.index = index - 1 451 return state, path, true 452 } 453 // We found a better child closer to the target 454 state, path, index = nextState, nextPath, nextIndex 455 } 456 case *shortNode: 457 // Short node, return the pointer singleton child 458 if parent.index < 0 { 459 hash, _ := n.Val.cache() 460 state := &nodeIteratorState{ 461 hash: common.BytesToHash(hash), 462 node: n.Val, 463 parent: ancestor, 464 index: -1, 465 pathlen: len(it.path), 466 } 467 path := append(it.path, n.Key...) 468 return state, path, true 469 } 470 } 471 return parent, it.path, false 472 } 473 474 func (it *nodeIterator) push(state *nodeIteratorState, parentIndex *int, path []byte) { 475 it.path = path 476 it.stack = append(it.stack, state) 477 if parentIndex != nil { 478 *parentIndex++ 479 } 480 } 481 482 func (it *nodeIterator) pop() { 483 parent := it.stack[len(it.stack)-1] 484 it.path = it.path[:parent.pathlen] 485 it.stack = it.stack[:len(it.stack)-1] 486 } 487 488 func compareNodes(a, b NodeIterator) int { 489 if cmp := bytes.Compare(a.Path(), b.Path()); cmp != 0 { 490 return cmp 491 } 492 if a.Leaf() && !b.Leaf() { 493 return -1 494 } else if b.Leaf() && !a.Leaf() { 495 return 1 496 } 497 if cmp := bytes.Compare(a.Hash().Bytes(), b.Hash().Bytes()); cmp != 0 { 498 return cmp 499 } 500 if a.Leaf() && b.Leaf() { 501 return bytes.Compare(a.LeafBlob(), b.LeafBlob()) 502 } 503 return 0 504 } 505 506 type differenceIterator struct { 507 a, b NodeIterator // Nodes returned are those in b - a. 508 eof bool // Indicates a has run out of elements 509 count int // Number of nodes scanned on either trie 510 } 511 512 // NewDifferenceIterator constructs a NodeIterator that iterates over elements in b that 513 // are not in a. Returns the iterator, and a pointer to an integer recording the number 514 // of nodes seen. 515 func NewDifferenceIterator(a, b NodeIterator) (NodeIterator, *int) { 516 a.Next(true) 517 it := &differenceIterator{ 518 a: a, 519 b: b, 520 } 521 return it, &it.count 522 } 523 524 func (it *differenceIterator) Hash() common.Hash { 525 return it.b.Hash() 526 } 527 528 func (it *differenceIterator) Parent() common.Hash { 529 return it.b.Parent() 530 } 531 532 func (it *differenceIterator) Leaf() bool { 533 return it.b.Leaf() 534 } 535 536 func (it *differenceIterator) LeafKey() []byte { 537 return it.b.LeafKey() 538 } 539 540 func (it *differenceIterator) LeafBlob() []byte { 541 return it.b.LeafBlob() 542 } 543 544 func (it *differenceIterator) LeafProof() [][]byte { 545 return it.b.LeafProof() 546 } 547 548 func (it *differenceIterator) Path() []byte { 549 return it.b.Path() 550 } 551 552 func (it *differenceIterator) AddResolver(resolver ethdb.KeyValueStore) { 553 panic("not implemented") 554 } 555 556 func (it *differenceIterator) Next(bool) bool { 557 // Invariants: 558 // - We always advance at least one element in b. 559 // - At the start of this function, a's path is lexically greater than b's. 560 if !it.b.Next(true) { 561 return false 562 } 563 it.count++ 564 565 if it.eof { 566 // a has reached eof, so we just return all elements from b 567 return true 568 } 569 570 for { 571 switch compareNodes(it.a, it.b) { 572 case -1: 573 // b jumped past a; advance a 574 if !it.a.Next(true) { 575 it.eof = true 576 return true 577 } 578 it.count++ 579 case 1: 580 // b is before a 581 return true 582 case 0: 583 // a and b are identical; skip this whole subtree if the nodes have hashes 584 hasHash := it.a.Hash() == common.Hash{} 585 if !it.b.Next(hasHash) { 586 return false 587 } 588 it.count++ 589 if !it.a.Next(hasHash) { 590 it.eof = true 591 return true 592 } 593 it.count++ 594 } 595 } 596 } 597 598 func (it *differenceIterator) Error() error { 599 if err := it.a.Error(); err != nil { 600 return err 601 } 602 return it.b.Error() 603 } 604 605 type nodeIteratorHeap []NodeIterator 606 607 func (h nodeIteratorHeap) Len() int { return len(h) } 608 func (h nodeIteratorHeap) Less(i, j int) bool { return compareNodes(h[i], h[j]) < 0 } 609 func (h nodeIteratorHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 610 func (h *nodeIteratorHeap) Push(x interface{}) { *h = append(*h, x.(NodeIterator)) } 611 func (h *nodeIteratorHeap) Pop() interface{} { 612 n := len(*h) 613 x := (*h)[n-1] 614 *h = (*h)[0 : n-1] 615 return x 616 } 617 618 type unionIterator struct { 619 items *nodeIteratorHeap // Nodes returned are the union of the ones in these iterators 620 count int // Number of nodes scanned across all tries 621 } 622 623 // NewUnionIterator constructs a NodeIterator that iterates over elements in the union 624 // of the provided NodeIterators. Returns the iterator, and a pointer to an integer 625 // recording the number of nodes visited. 626 func NewUnionIterator(iters []NodeIterator) (NodeIterator, *int) { 627 h := make(nodeIteratorHeap, len(iters)) 628 copy(h, iters) 629 heap.Init(&h) 630 631 ui := &unionIterator{items: &h} 632 return ui, &ui.count 633 } 634 635 func (it *unionIterator) Hash() common.Hash { 636 return (*it.items)[0].Hash() 637 } 638 639 func (it *unionIterator) Parent() common.Hash { 640 return (*it.items)[0].Parent() 641 } 642 643 func (it *unionIterator) Leaf() bool { 644 return (*it.items)[0].Leaf() 645 } 646 647 func (it *unionIterator) LeafKey() []byte { 648 return (*it.items)[0].LeafKey() 649 } 650 651 func (it *unionIterator) LeafBlob() []byte { 652 return (*it.items)[0].LeafBlob() 653 } 654 655 func (it *unionIterator) LeafProof() [][]byte { 656 return (*it.items)[0].LeafProof() 657 } 658 659 func (it *unionIterator) Path() []byte { 660 return (*it.items)[0].Path() 661 } 662 663 func (it *unionIterator) AddResolver(resolver ethdb.KeyValueStore) { 664 panic("not implemented") 665 } 666 667 // Next returns the next node in the union of tries being iterated over. 668 // 669 // It does this by maintaining a heap of iterators, sorted by the iteration 670 // order of their next elements, with one entry for each source trie. Each 671 // time Next() is called, it takes the least element from the heap to return, 672 // advancing any other iterators that also point to that same element. These 673 // iterators are called with descend=false, since we know that any nodes under 674 // these nodes will also be duplicates, found in the currently selected iterator. 675 // Whenever an iterator is advanced, it is pushed back into the heap if it still 676 // has elements remaining. 677 // 678 // In the case that descend=false - eg, we're asked to ignore all subnodes of the 679 // current node - we also advance any iterators in the heap that have the current 680 // path as a prefix. 681 func (it *unionIterator) Next(descend bool) bool { 682 if len(*it.items) == 0 { 683 return false 684 } 685 686 // Get the next key from the union 687 least := heap.Pop(it.items).(NodeIterator) 688 689 // Skip over other nodes as long as they're identical, or, if we're not descending, as 690 // long as they have the same prefix as the current node. 691 for len(*it.items) > 0 && ((!descend && bytes.HasPrefix((*it.items)[0].Path(), least.Path())) || compareNodes(least, (*it.items)[0]) == 0) { 692 skipped := heap.Pop(it.items).(NodeIterator) 693 // Skip the whole subtree if the nodes have hashes; otherwise just skip this node 694 if skipped.Next(skipped.Hash() == common.Hash{}) { 695 it.count++ 696 // If there are more elements, push the iterator back on the heap 697 heap.Push(it.items, skipped) 698 } 699 } 700 if least.Next(descend) { 701 it.count++ 702 heap.Push(it.items, least) 703 } 704 return len(*it.items) > 0 705 } 706 707 func (it *unionIterator) Error() error { 708 for i := 0; i < len(*it.items); i++ { 709 if err := (*it.items)[i].Error(); err != nil { 710 return err 711 } 712 } 713 return nil 714 }