iterator.go 20 KB

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