github.com/annchain/OG@v0.0.9/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 "github.com/annchain/OG/arefactor/og/types" 24 ) 25 26 // Iterator is a key-value trie iterator that traverses a Trie. 27 type Iterator struct { 28 nodeIt NodeIterator 29 30 Key []byte // Current data key on which the iterator is positioned on 31 Value []byte // Current data value on which the iterator is positioned on 32 Err error 33 } 34 35 // NewIterator creates a new key-value iterator from a node iterator 36 func NewIterator(it NodeIterator) *Iterator { 37 return &Iterator{ 38 nodeIt: it, 39 } 40 } 41 42 // Next moves the iterator forward one key-value entry. 43 func (it *Iterator) Next() bool { 44 for it.nodeIt.Next(true) { 45 if it.nodeIt.Leaf() { 46 it.Key = it.nodeIt.LeafKey() 47 it.Value = it.nodeIt.LeafBlob() 48 return true 49 } 50 } 51 it.Key = nil 52 it.Value = nil 53 it.Err = it.nodeIt.Error() 54 return false 55 } 56 57 // Prove generates the Merkle proof for the leaf node the iterator is currently 58 // positioned on. 59 func (it *Iterator) Prove() [][]byte { 60 return it.nodeIt.LeafProof() 61 } 62 63 // NodeIterator is an iterator to traverse the trie pre-order. 64 type NodeIterator interface { 65 // Next moves the iterator to the next node. If the parameter is false, any child 66 // nodes will be skipped. 67 Next(bool) bool 68 69 // Error returns the error status of the iterator. 70 Error() error 71 72 // Hash returns the hash of the current node. 73 Hash() types.Hash 74 75 // Parent returns the hash of the parent of the current node. The hash may be the one 76 // grandparent if the immediate parent is an internal node with no hash. 77 Parent() types.Hash 78 79 // Path returns the hex-encoded path to the current node. 80 // Callers must not retain references to the return value after calling Next. 81 // For leaf nodes, the last element of the path is the 'terminator symbol' 0x10. 82 Path() []byte 83 84 // Leaf returns true iff the current node is a leaf node. 85 Leaf() bool 86 87 // LeafKey returns the key of the leaf. The method panics if the iterator is not 88 // positioned at a leaf. Callers must not retain references to the value after 89 // calling Next. 90 LeafKey() []byte 91 92 // LeafBlob returns the content of the leaf. The method panics if the iterator 93 // is not positioned at a leaf. Callers must not retain references to the value 94 // after calling Next. 95 LeafBlob() []byte 96 97 // LeafProof returns the Merkle proof of the leaf. The method panics if the 98 // iterator is not positioned at a leaf. Callers must not retain references 99 // to the value after calling Next. 100 LeafProof() [][]byte 101 } 102 103 // nodeIteratorState represents the iteration state at one particular node of the 104 // trie, which can be resumed at a later invocation. 105 type nodeIteratorState struct { 106 hash types.Hash // Hash of the node being iterated (nil if not standalone) 107 node Node // Trie node being iterated 108 parent types.Hash // Hash of the first full ancestor node (nil if current is the root) 109 index int // Child to be processed next 110 pathlen int // Length of the path to this node 111 } 112 113 type nodeIterator struct { 114 trie *Trie // Trie being iterated 115 stack []*nodeIteratorState // Hierarchy of trie nodes persisting the iteration state 116 path []byte // Path to the current node 117 err error // Failure set in case of an internal error in the iterator 118 } 119 120 // errIteratorEnd is stored in nodeIterator.err when iteration is done. 121 var errIteratorEnd = errors.New("end of iteration") 122 123 // seekError is stored in nodeIterator.err if the initial seek has failed. 124 type seekError struct { 125 key []byte 126 err error 127 } 128 129 func (e seekError) Error() string { 130 return "seek error: " + e.err.Error() 131 } 132 133 func newNodeIterator(trie *Trie, start []byte) NodeIterator { 134 if trie.Hash() == emptyState { 135 return new(nodeIterator) 136 } 137 it := &nodeIterator{trie: trie} 138 it.err = it.seek(start) 139 return it 140 } 141 142 func (it *nodeIterator) Hash() types.Hash { 143 if len(it.stack) == 0 { 144 return types.Hash{} 145 } 146 return it.stack[len(it.stack)-1].hash 147 } 148 149 func (it *nodeIterator) Parent() types.Hash { 150 if len(it.stack) == 0 { 151 return types.Hash{} 152 } 153 return it.stack[len(it.stack)-1].parent 154 } 155 156 func (it *nodeIterator) Leaf() bool { 157 return hasTerm(it.path) 158 } 159 160 func (it *nodeIterator) LeafKey() []byte { 161 if len(it.stack) > 0 { 162 if _, ok := it.stack[len(it.stack)-1].node.(ValueNode); ok { 163 return hexToKeybytes(it.path) 164 } 165 } 166 panic("not at leaf") 167 } 168 169 func (it *nodeIterator) LeafBlob() []byte { 170 if len(it.stack) > 0 { 171 if node, ok := it.stack[len(it.stack)-1].node.(ValueNode); ok { 172 return []byte(node) 173 } 174 } 175 panic("not at leaf") 176 } 177 178 func (it *nodeIterator) LeafProof() [][]byte { 179 if len(it.stack) > 0 { 180 if _, ok := it.stack[len(it.stack)-1].node.(ValueNode); ok { 181 hasher := newHasher(0, 0, nil) 182 proofs := make([][]byte, 0, len(it.stack)) 183 184 for i, item := range it.stack[:len(it.stack)-1] { 185 // Gather nodes that end up as hash nodes (or the root) 186 node, _, _ := hasher.hashChildren(item.node, nil, false) 187 hashed, _ := hasher.store(node, nil, false, false) 188 if _, ok := hashed.(HashNode); ok || i == 0 { 189 enc := node.encodeNode() 190 // TODO 191 // delete this line later. 192 // enc, _ := rlp.EncodeToBytes(node) 193 proofs = append(proofs, enc) 194 } 195 } 196 return proofs 197 } 198 } 199 panic("not at leaf") 200 } 201 202 func (it *nodeIterator) Path() []byte { 203 return it.path 204 } 205 206 func (it *nodeIterator) Error() error { 207 if it.err == errIteratorEnd { 208 return nil 209 } 210 if seek, ok := it.err.(seekError); ok { 211 return seek.err 212 } 213 return it.err 214 } 215 216 // Next moves the iterator to the next node, returning whether there are any 217 // further nodes. In case of an internal error this method returns false and 218 // sets the Error field to the encountered failure. If `descend` is false, 219 // skips iterating over any subnodes of the current node. 220 func (it *nodeIterator) Next(descend bool) bool { 221 if it.err == errIteratorEnd { 222 return false 223 } 224 if seek, ok := it.err.(seekError); ok { 225 if it.err = it.seek(seek.key); it.err != nil { 226 return false 227 } 228 } 229 // Otherwise step forward with the iterator and report any errors. 230 state, parentIndex, path, err := it.peek(descend) 231 it.err = err 232 if it.err != nil { 233 return false 234 } 235 it.push(state, parentIndex, path) 236 return true 237 } 238 239 func (it *nodeIterator) seek(prefix []byte) error { 240 // The path we're looking for is the hex encoded key without terminator. 241 key := keybytesToHex(prefix) 242 key = key[:len(key)-1] 243 // Move forward until we're just before the closest match to key. 244 for { 245 state, parentIndex, path, err := it.peek(bytes.HasPrefix(key, it.path)) 246 if err == errIteratorEnd { 247 return errIteratorEnd 248 } else if err != nil { 249 return seekError{prefix, err} 250 } else if bytes.Compare(path, key) >= 0 { 251 return nil 252 } 253 it.push(state, parentIndex, path) 254 } 255 } 256 257 // peek creates the next state of the iterator. 258 func (it *nodeIterator) peek(descend bool) (*nodeIteratorState, *int, []byte, error) { 259 if len(it.stack) == 0 { 260 // Initialize the iterator if we've just started. 261 root := it.trie.Hash() 262 state := &nodeIteratorState{node: it.trie.root, index: -1} 263 if root != emptyRoot { 264 state.hash = root 265 } 266 err := state.resolve(it.trie, nil) 267 return state, nil, nil, err 268 } 269 if !descend { 270 // If we're skipping children, pop the current node first 271 it.pop() 272 } 273 274 // Continue iteration to the next child 275 for len(it.stack) > 0 { 276 parent := it.stack[len(it.stack)-1] 277 ancestor := parent.hash 278 if (ancestor == types.Hash{}) { 279 ancestor = parent.parent 280 } 281 state, path, ok := it.nextChild(parent, ancestor) 282 if ok { 283 if err := state.resolve(it.trie, path); err != nil { 284 return parent, &parent.index, path, err 285 } 286 return state, &parent.index, path, nil 287 } 288 // No more child nodes, move back up. 289 it.pop() 290 } 291 return nil, nil, nil, errIteratorEnd 292 } 293 294 func (st *nodeIteratorState) resolve(tr *Trie, path []byte) error { 295 if hash, ok := st.node.(HashNode); ok { 296 resolved, err := tr.resolveHash(hash, path) 297 if err != nil { 298 return err 299 } 300 st.node = resolved 301 st.hash = types.BytesToHash(hash) 302 } 303 return nil 304 } 305 306 func (it *nodeIterator) nextChild(parent *nodeIteratorState, ancestor types.Hash) (*nodeIteratorState, []byte, bool) { 307 switch node := parent.node.(type) { 308 case *FullNode: 309 // Full node, move to the first non-nil child. 310 for i := parent.index + 1; i < len(node.Children); i++ { 311 child := node.Children[i] 312 if child != nil { 313 hash, _ := child.cache() 314 state := &nodeIteratorState{ 315 hash: types.BytesToHash(hash), 316 node: child, 317 parent: ancestor, 318 index: -1, 319 pathlen: len(it.path), 320 } 321 path := append(it.path, byte(i)) 322 parent.index = i - 1 323 return state, path, true 324 } 325 } 326 case *ShortNode: 327 // Short node, return the pointer singleton child 328 if parent.index < 0 { 329 hash, _ := node.Val.cache() 330 state := &nodeIteratorState{ 331 hash: types.BytesToHash(hash), 332 node: node.Val, 333 parent: ancestor, 334 index: -1, 335 pathlen: len(it.path), 336 } 337 path := append(it.path, node.Key...) 338 return state, path, true 339 } 340 } 341 return parent, it.path, false 342 } 343 344 func (it *nodeIterator) push(state *nodeIteratorState, parentIndex *int, path []byte) { 345 it.path = path 346 it.stack = append(it.stack, state) 347 if parentIndex != nil { 348 *parentIndex++ 349 } 350 } 351 352 func (it *nodeIterator) pop() { 353 parent := it.stack[len(it.stack)-1] 354 it.path = it.path[:parent.pathlen] 355 it.stack = it.stack[:len(it.stack)-1] 356 } 357 358 func compareNodes(a, b NodeIterator) int { 359 if cmp := bytes.Compare(a.Path(), b.Path()); cmp != 0 { 360 return cmp 361 } 362 if a.Leaf() && !b.Leaf() { 363 return -1 364 } else if b.Leaf() && !a.Leaf() { 365 return 1 366 } 367 if cmp := bytes.Compare(a.Hash().ToBytes(), b.Hash().ToBytes()); cmp != 0 { 368 return cmp 369 } 370 if a.Leaf() && b.Leaf() { 371 return bytes.Compare(a.LeafBlob(), b.LeafBlob()) 372 } 373 return 0 374 } 375 376 type differenceIterator struct { 377 a, b NodeIterator // Nodes returned are those in b - a. 378 eof bool // Indicates a has run out of elements 379 count int // Number of nodes scanned on either trie 380 } 381 382 // NewDifferenceIterator constructs a NodeIterator that iterates over elements in b that 383 // are not in a. Returns the iterator, and a pointer to an integer recording the number 384 // of nodes seen. 385 func NewDifferenceIterator(a, b NodeIterator) (NodeIterator, *int) { 386 a.Next(true) 387 it := &differenceIterator{ 388 a: a, 389 b: b, 390 } 391 return it, &it.count 392 } 393 394 func (it *differenceIterator) Hash() types.Hash { 395 return it.b.Hash() 396 } 397 398 func (it *differenceIterator) Parent() types.Hash { 399 return it.b.Parent() 400 } 401 402 func (it *differenceIterator) Leaf() bool { 403 return it.b.Leaf() 404 } 405 406 func (it *differenceIterator) LeafKey() []byte { 407 return it.b.LeafKey() 408 } 409 410 func (it *differenceIterator) LeafBlob() []byte { 411 return it.b.LeafBlob() 412 } 413 414 func (it *differenceIterator) LeafProof() [][]byte { 415 return it.b.LeafProof() 416 } 417 418 func (it *differenceIterator) Path() []byte { 419 return it.b.Path() 420 } 421 422 func (it *differenceIterator) Next(bool) bool { 423 // Invariants: 424 // - We always advance at least one element in b. 425 // - At the start of this function, a's path is lexically greater than b's. 426 if !it.b.Next(true) { 427 return false 428 } 429 it.count++ 430 431 if it.eof { 432 // a has reached eof, so we just return all elements from b 433 return true 434 } 435 436 for { 437 switch compareNodes(it.a, it.b) { 438 case -1: 439 // b jumped past a; advance a 440 if !it.a.Next(true) { 441 it.eof = true 442 return true 443 } 444 it.count++ 445 case 1: 446 // b is before a 447 return true 448 case 0: 449 // a and b are identical; skip this whole subtree if the nodes have hashes 450 hasHash := it.a.Hash() == types.Hash{} 451 if !it.b.Next(hasHash) { 452 return false 453 } 454 it.count++ 455 if !it.a.Next(hasHash) { 456 it.eof = true 457 return true 458 } 459 it.count++ 460 } 461 } 462 } 463 464 func (it *differenceIterator) Error() error { 465 if err := it.a.Error(); err != nil { 466 return err 467 } 468 return it.b.Error() 469 } 470 471 type nodeIteratorHeap []NodeIterator 472 473 func (h nodeIteratorHeap) Len() int { return len(h) } 474 func (h nodeIteratorHeap) Less(i, j int) bool { return compareNodes(h[i], h[j]) < 0 } 475 func (h nodeIteratorHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } 476 func (h *nodeIteratorHeap) Push(x interface{}) { *h = append(*h, x.(NodeIterator)) } 477 func (h *nodeIteratorHeap) Pop() interface{} { 478 n := len(*h) 479 x := (*h)[n-1] 480 *h = (*h)[0 : n-1] 481 return x 482 } 483 484 type unionIterator struct { 485 items *nodeIteratorHeap // Nodes returned are the union of the ones in these iterators 486 count int // Number of nodes scanned across all tries 487 } 488 489 // NewUnionIterator constructs a NodeIterator that iterates over elements in the union 490 // of the provided NodeIterators. Returns the iterator, and a pointer to an integer 491 // recording the number of nodes visited. 492 func NewUnionIterator(iters []NodeIterator) (NodeIterator, *int) { 493 h := make(nodeIteratorHeap, len(iters)) 494 copy(h, iters) 495 heap.Init(&h) 496 497 ui := &unionIterator{items: &h} 498 return ui, &ui.count 499 } 500 501 func (it *unionIterator) Hash() types.Hash { 502 return (*it.items)[0].Hash() 503 } 504 505 func (it *unionIterator) Parent() types.Hash { 506 return (*it.items)[0].Parent() 507 } 508 509 func (it *unionIterator) Leaf() bool { 510 return (*it.items)[0].Leaf() 511 } 512 513 func (it *unionIterator) LeafKey() []byte { 514 return (*it.items)[0].LeafKey() 515 } 516 517 func (it *unionIterator) LeafBlob() []byte { 518 return (*it.items)[0].LeafBlob() 519 } 520 521 func (it *unionIterator) LeafProof() [][]byte { 522 return (*it.items)[0].LeafProof() 523 } 524 525 func (it *unionIterator) Path() []byte { 526 return (*it.items)[0].Path() 527 } 528 529 // Next returns the next node in the union of tries being iterated over. 530 // 531 // It does this by maintaining a heap of iterators, sorted by the iteration 532 // order of their next elements, with one entry for each source trie. Each 533 // time Next() is called, it takes the least element from the heap to return, 534 // advancing any other iterators that also point to that same element. These 535 // iterators are called with descend=false, since we know that any nodes under 536 // these nodes will also be duplicates, found in the currently selected iterator. 537 // Whenever an iterator is advanced, it is pushed back into the heap if it still 538 // has elements remaining. 539 // 540 // In the case that descend=false - eg, we're asked to ignore all subnodes of the 541 // current node - we also advance any iterators in the heap that have the current 542 // path as a prefix. 543 func (it *unionIterator) Next(descend bool) bool { 544 if len(*it.items) == 0 { 545 return false 546 } 547 548 // Get the next key from the union 549 least := heap.Pop(it.items).(NodeIterator) 550 551 // Skip over other nodes as long as they're identical, or, if we're not descending, as 552 // long as they have the same prefix as the current node. 553 for len(*it.items) > 0 && ((!descend && bytes.HasPrefix((*it.items)[0].Path(), least.Path())) || compareNodes(least, (*it.items)[0]) == 0) { 554 skipped := heap.Pop(it.items).(NodeIterator) 555 // Skip the whole subtree if the nodes have hashes; otherwise just skip this node 556 if skipped.Next(skipped.Hash() == types.Hash{}) { 557 it.count++ 558 // If there are more elements, push the iterator back on the heap 559 heap.Push(it.items, skipped) 560 } 561 } 562 if least.Next(descend) { 563 it.count++ 564 heap.Push(it.items, least) 565 } 566 return len(*it.items) > 0 567 } 568 569 func (it *unionIterator) Error() error { 570 for i := 0; i < len(*it.items); i++ { 571 if err := (*it.items)[i].Error(); err != nil { 572 return err 573 } 574 } 575 return nil 576 }