iterator.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. "github.com/ethereum/go-ethereum/common"
  20. )
  21. // Iterator is a key-value trie iterator that traverses a Trie.
  22. type Iterator struct {
  23. nodeIt NodeIterator
  24. Key []byte // Current data key on which the iterator is positioned on
  25. Value []byte // Current data value on which the iterator is positioned on
  26. }
  27. // NewIterator creates a new key-value iterator.
  28. func NewIterator(trie *Trie) *Iterator {
  29. return &Iterator{
  30. nodeIt: NewNodeIterator(trie),
  31. }
  32. }
  33. // FromNodeIterator creates a new key-value iterator from a node iterator
  34. func NewIteratorFromNodeIterator(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 = decodeCompact(it.nodeIt.Path())
  44. it.Value = it.nodeIt.LeafBlob()
  45. return true
  46. }
  47. }
  48. it.Key = nil
  49. it.Value = nil
  50. return false
  51. }
  52. // NodeIterator is an iterator to traverse the trie pre-order.
  53. type NodeIterator interface {
  54. // Hash returns the hash of the current node
  55. Hash() common.Hash
  56. // Parent returns the hash of the parent of the current node
  57. Parent() common.Hash
  58. // Leaf returns true iff the current node is a leaf node.
  59. Leaf() bool
  60. // LeafBlob returns the contents of the node, if it is a leaf.
  61. // Callers must not retain references to the return value after calling Next()
  62. LeafBlob() []byte
  63. // Path returns the hex-encoded path to the current node.
  64. // Callers must not retain references to the return value after calling Next()
  65. Path() []byte
  66. // Next moves the iterator to the next node. If the parameter is false, any child
  67. // nodes will be skipped.
  68. Next(bool) bool
  69. // Error returns the error status of the iterator.
  70. Error() error
  71. }
  72. // nodeIteratorState represents the iteration state at one particular node of the
  73. // trie, which can be resumed at a later invocation.
  74. type nodeIteratorState struct {
  75. hash common.Hash // Hash of the node being iterated (nil if not standalone)
  76. node node // Trie node being iterated
  77. parent common.Hash // Hash of the first full ancestor node (nil if current is the root)
  78. child int // Child to be processed next
  79. pathlen int // Length of the path to this node
  80. }
  81. type nodeIterator struct {
  82. trie *Trie // Trie being iterated
  83. stack []*nodeIteratorState // Hierarchy of trie nodes persisting the iteration state
  84. err error // Failure set in case of an internal error in the iterator
  85. path []byte // Path to the current node
  86. }
  87. // NewNodeIterator creates an post-order trie iterator.
  88. func NewNodeIterator(trie *Trie) NodeIterator {
  89. if trie.Hash() == emptyState {
  90. return new(nodeIterator)
  91. }
  92. return &nodeIterator{trie: trie}
  93. }
  94. // Hash returns the hash of the current node
  95. func (it *nodeIterator) Hash() common.Hash {
  96. if len(it.stack) == 0 {
  97. return common.Hash{}
  98. }
  99. return it.stack[len(it.stack)-1].hash
  100. }
  101. // Parent returns the hash of the parent node
  102. func (it *nodeIterator) Parent() common.Hash {
  103. if len(it.stack) == 0 {
  104. return common.Hash{}
  105. }
  106. return it.stack[len(it.stack)-1].parent
  107. }
  108. // Leaf returns true if the current node is a leaf
  109. func (it *nodeIterator) Leaf() bool {
  110. if len(it.stack) == 0 {
  111. return false
  112. }
  113. _, ok := it.stack[len(it.stack)-1].node.(valueNode)
  114. return ok
  115. }
  116. // LeafBlob returns the data for the current node, if it is a leaf
  117. func (it *nodeIterator) LeafBlob() []byte {
  118. if len(it.stack) == 0 {
  119. return nil
  120. }
  121. if node, ok := it.stack[len(it.stack)-1].node.(valueNode); ok {
  122. return []byte(node)
  123. }
  124. return nil
  125. }
  126. // Path returns the hex-encoded path to the current node
  127. func (it *nodeIterator) Path() []byte {
  128. return it.path
  129. }
  130. // Error returns the error set in case of an internal error in the iterator
  131. func (it *nodeIterator) Error() error {
  132. return it.err
  133. }
  134. // Next moves the iterator to the next node, returning whether there are any
  135. // further nodes. In case of an internal error this method returns false and
  136. // sets the Error field to the encountered failure. If `descend` is false,
  137. // skips iterating over any subnodes of the current node.
  138. func (it *nodeIterator) Next(descend bool) bool {
  139. // If the iterator failed previously, don't do anything
  140. if it.err != nil {
  141. return false
  142. }
  143. // Otherwise step forward with the iterator and report any errors
  144. if err := it.step(descend); err != nil {
  145. it.err = err
  146. return false
  147. }
  148. return it.trie != nil
  149. }
  150. // step moves the iterator to the next node of the trie.
  151. func (it *nodeIterator) step(descend bool) error {
  152. if it.trie == nil {
  153. // Abort if we reached the end of the iteration
  154. return nil
  155. }
  156. if len(it.stack) == 0 {
  157. // Initialize the iterator if we've just started.
  158. root := it.trie.Hash()
  159. state := &nodeIteratorState{node: it.trie.root, child: -1}
  160. if root != emptyRoot {
  161. state.hash = root
  162. }
  163. it.stack = append(it.stack, state)
  164. return nil
  165. }
  166. if !descend {
  167. // If we're skipping children, pop the current node first
  168. it.path = it.path[:it.stack[len(it.stack)-1].pathlen]
  169. it.stack = it.stack[:len(it.stack)-1]
  170. }
  171. // Continue iteration to the next child
  172. outer:
  173. for {
  174. if len(it.stack) == 0 {
  175. it.trie = nil
  176. return nil
  177. }
  178. parent := it.stack[len(it.stack)-1]
  179. ancestor := parent.hash
  180. if (ancestor == common.Hash{}) {
  181. ancestor = parent.parent
  182. }
  183. if node, ok := parent.node.(*fullNode); ok {
  184. // Full node, iterate over children
  185. for parent.child++; parent.child < len(node.Children); parent.child++ {
  186. child := node.Children[parent.child]
  187. if child != nil {
  188. hash, _ := child.cache()
  189. it.stack = append(it.stack, &nodeIteratorState{
  190. hash: common.BytesToHash(hash),
  191. node: child,
  192. parent: ancestor,
  193. child: -1,
  194. pathlen: len(it.path),
  195. })
  196. it.path = append(it.path, byte(parent.child))
  197. break outer
  198. }
  199. }
  200. } else if node, ok := parent.node.(*shortNode); ok {
  201. // Short node, return the pointer singleton child
  202. if parent.child < 0 {
  203. parent.child++
  204. hash, _ := node.Val.cache()
  205. it.stack = append(it.stack, &nodeIteratorState{
  206. hash: common.BytesToHash(hash),
  207. node: node.Val,
  208. parent: ancestor,
  209. child: -1,
  210. pathlen: len(it.path),
  211. })
  212. if hasTerm(node.Key) {
  213. it.path = append(it.path, node.Key[:len(node.Key)-1]...)
  214. } else {
  215. it.path = append(it.path, node.Key...)
  216. }
  217. break
  218. }
  219. } else if hash, ok := parent.node.(hashNode); ok {
  220. // Hash node, resolve the hash child from the database
  221. if parent.child < 0 {
  222. parent.child++
  223. node, err := it.trie.resolveHash(hash, nil, nil)
  224. if err != nil {
  225. return err
  226. }
  227. it.stack = append(it.stack, &nodeIteratorState{
  228. hash: common.BytesToHash(hash),
  229. node: node,
  230. parent: ancestor,
  231. child: -1,
  232. pathlen: len(it.path),
  233. })
  234. break
  235. }
  236. }
  237. it.path = it.path[:parent.pathlen]
  238. it.stack = it.stack[:len(it.stack)-1]
  239. }
  240. return nil
  241. }
  242. type differenceIterator struct {
  243. a, b NodeIterator // Nodes returned are those in b - a.
  244. eof bool // Indicates a has run out of elements
  245. count int // Number of nodes scanned on either trie
  246. }
  247. // NewDifferenceIterator constructs a NodeIterator that iterates over elements in b that
  248. // are not in a. Returns the iterator, and a pointer to an integer recording the number
  249. // of nodes seen.
  250. func NewDifferenceIterator(a, b NodeIterator) (NodeIterator, *int) {
  251. a.Next(true)
  252. it := &differenceIterator{
  253. a: a,
  254. b: b,
  255. }
  256. return it, &it.count
  257. }
  258. func (it *differenceIterator) Hash() common.Hash {
  259. return it.b.Hash()
  260. }
  261. func (it *differenceIterator) Parent() common.Hash {
  262. return it.b.Parent()
  263. }
  264. func (it *differenceIterator) Leaf() bool {
  265. return it.b.Leaf()
  266. }
  267. func (it *differenceIterator) LeafBlob() []byte {
  268. return it.b.LeafBlob()
  269. }
  270. func (it *differenceIterator) Path() []byte {
  271. return it.b.Path()
  272. }
  273. func (it *differenceIterator) Next(bool) bool {
  274. // Invariants:
  275. // - We always advance at least one element in b.
  276. // - At the start of this function, a's path is lexically greater than b's.
  277. if !it.b.Next(true) {
  278. return false
  279. }
  280. it.count += 1
  281. if it.eof {
  282. // a has reached eof, so we just return all elements from b
  283. return true
  284. }
  285. for {
  286. apath, bpath := it.a.Path(), it.b.Path()
  287. switch bytes.Compare(apath, bpath) {
  288. case -1:
  289. // b jumped past a; advance a
  290. if !it.a.Next(true) {
  291. it.eof = true
  292. return true
  293. }
  294. it.count += 1
  295. case 1:
  296. // b is before a
  297. return true
  298. case 0:
  299. if it.a.Hash() != it.b.Hash() || it.a.Leaf() != it.b.Leaf() {
  300. // Keys are identical, but hashes or leaf status differs
  301. return true
  302. }
  303. if it.a.Leaf() && it.b.Leaf() && !bytes.Equal(it.a.LeafBlob(), it.b.LeafBlob()) {
  304. // Both are leaf nodes, but with different values
  305. return true
  306. }
  307. // a and b are identical; skip this whole subtree if the nodes have hashes
  308. hasHash := it.a.Hash() == common.Hash{}
  309. if !it.b.Next(hasHash) {
  310. return false
  311. }
  312. it.count += 1
  313. if !it.a.Next(hasHash) {
  314. it.eof = true
  315. return true
  316. }
  317. it.count += 1
  318. }
  319. }
  320. }
  321. func (it *differenceIterator) Error() error {
  322. if err := it.a.Error(); err != nil {
  323. return err
  324. }
  325. return it.b.Error()
  326. }