iterator.go 14 KB

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