iterator.go 21 KB

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