iterator.go 16 KB

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