iterator.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 "github.com/ethereum/go-ethereum/common"
  18. // Iterator is a key-value trie iterator that traverses a Trie.
  19. type Iterator struct {
  20. trie *Trie
  21. nodeIt *NodeIterator
  22. keyBuf []byte
  23. Key []byte // Current data key on which the iterator is positioned on
  24. Value []byte // Current data value on which the iterator is positioned on
  25. }
  26. // NewIterator creates a new key-value iterator.
  27. func NewIterator(trie *Trie) *Iterator {
  28. return &Iterator{
  29. trie: trie,
  30. nodeIt: NewNodeIterator(trie),
  31. keyBuf: make([]byte, 0, 64),
  32. Key: nil,
  33. }
  34. }
  35. // Next moves the iterator forward one key-value entry.
  36. func (it *Iterator) Next() bool {
  37. for it.nodeIt.Next() {
  38. if it.nodeIt.Leaf {
  39. it.Key = it.makeKey()
  40. it.Value = it.nodeIt.LeafBlob
  41. return true
  42. }
  43. }
  44. it.Key = nil
  45. it.Value = nil
  46. return false
  47. }
  48. func (it *Iterator) makeKey() []byte {
  49. key := it.keyBuf[:0]
  50. for _, se := range it.nodeIt.stack {
  51. switch node := se.node.(type) {
  52. case fullNode:
  53. if se.child <= 16 {
  54. key = append(key, byte(se.child))
  55. }
  56. case shortNode:
  57. if hasTerm(node.Key) {
  58. key = append(key, node.Key[:len(node.Key)-1]...)
  59. } else {
  60. key = append(key, node.Key...)
  61. }
  62. }
  63. }
  64. return decodeCompact(key)
  65. }
  66. // nodeIteratorState represents the iteration state at one particular node of the
  67. // trie, which can be resumed at a later invocation.
  68. type nodeIteratorState struct {
  69. hash common.Hash // Hash of the node being iterated (nil if not standalone)
  70. node node // Trie node being iterated
  71. parent common.Hash // Hash of the first full ancestor node (nil if current is the root)
  72. child int // Child to be processed next
  73. }
  74. // NodeIterator is an iterator to traverse the trie post-order.
  75. type NodeIterator struct {
  76. trie *Trie // Trie being iterated
  77. stack []*nodeIteratorState // Hierarchy of trie nodes persisting the iteration state
  78. Hash common.Hash // Hash of the current node being iterated (nil if not standalone)
  79. Node node // Current node being iterated (internal representation)
  80. Parent common.Hash // Hash of the first full ancestor node (nil if current is the root)
  81. Leaf bool // Flag whether the current node is a value (data) node
  82. LeafBlob []byte // Data blob contained within a leaf (otherwise nil)
  83. Error error // Failure set in case of an internal error in the iterator
  84. }
  85. // NewNodeIterator creates an post-order trie iterator.
  86. func NewNodeIterator(trie *Trie) *NodeIterator {
  87. if trie.Hash() == emptyState {
  88. return new(NodeIterator)
  89. }
  90. return &NodeIterator{trie: trie}
  91. }
  92. // Next moves the iterator to the next node, returning whether there are any
  93. // further nodes. In case of an internal error this method returns false and
  94. // sets the Error field to the encountered failure.
  95. func (it *NodeIterator) Next() bool {
  96. // If the iterator failed previously, don't do anything
  97. if it.Error != nil {
  98. return false
  99. }
  100. // Otherwise step forward with the iterator and report any errors
  101. if err := it.step(); err != nil {
  102. it.Error = err
  103. return false
  104. }
  105. return it.retrieve()
  106. }
  107. // step moves the iterator to the next node of the trie.
  108. func (it *NodeIterator) step() error {
  109. if it.trie == nil {
  110. // Abort if we reached the end of the iteration
  111. return nil
  112. }
  113. if len(it.stack) == 0 {
  114. // Initialize the iterator if we've just started.
  115. root := it.trie.Hash()
  116. state := &nodeIteratorState{node: it.trie.root, child: -1}
  117. if root != emptyRoot {
  118. state.hash = root
  119. }
  120. it.stack = append(it.stack, state)
  121. } else {
  122. // Continue iterating at the previous node otherwise.
  123. it.stack = it.stack[:len(it.stack)-1]
  124. if len(it.stack) == 0 {
  125. it.trie = nil
  126. return nil
  127. }
  128. }
  129. // Continue iteration to the next child
  130. for {
  131. parent := it.stack[len(it.stack)-1]
  132. ancestor := parent.hash
  133. if (ancestor == common.Hash{}) {
  134. ancestor = parent.parent
  135. }
  136. if node, ok := parent.node.(fullNode); ok {
  137. // Full node, traverse all children, then the node itself
  138. if parent.child >= len(node.Children) {
  139. break
  140. }
  141. for parent.child++; parent.child < len(node.Children); parent.child++ {
  142. if current := node.Children[parent.child]; current != nil {
  143. it.stack = append(it.stack, &nodeIteratorState{
  144. hash: common.BytesToHash(node.hash),
  145. node: current,
  146. parent: ancestor,
  147. child: -1,
  148. })
  149. break
  150. }
  151. }
  152. } else if node, ok := parent.node.(shortNode); ok {
  153. // Short node, traverse the pointer singleton child, then the node itself
  154. if parent.child >= 0 {
  155. break
  156. }
  157. parent.child++
  158. it.stack = append(it.stack, &nodeIteratorState{
  159. hash: common.BytesToHash(node.hash),
  160. node: node.Val,
  161. parent: ancestor,
  162. child: -1,
  163. })
  164. } else if hash, ok := parent.node.(hashNode); ok {
  165. // Hash node, resolve the hash child from the database, then the node itself
  166. if parent.child >= 0 {
  167. break
  168. }
  169. parent.child++
  170. node, err := it.trie.resolveHash(hash, nil, nil)
  171. if err != nil {
  172. return err
  173. }
  174. it.stack = append(it.stack, &nodeIteratorState{
  175. hash: common.BytesToHash(hash),
  176. node: node,
  177. parent: ancestor,
  178. child: -1,
  179. })
  180. } else {
  181. break
  182. }
  183. }
  184. return nil
  185. }
  186. // retrieve pulls and caches the current trie node the iterator is traversing.
  187. // In case of a value node, the additional leaf blob is also populated with the
  188. // data contents for external interpretation.
  189. //
  190. // The method returns whether there are any more data left for inspection.
  191. func (it *NodeIterator) retrieve() bool {
  192. // Clear out any previously set values
  193. it.Hash, it.Node, it.Parent, it.Leaf, it.LeafBlob = common.Hash{}, nil, common.Hash{}, false, nil
  194. // If the iteration's done, return no available data
  195. if it.trie == nil {
  196. return false
  197. }
  198. // Otherwise retrieve the current node and resolve leaf accessors
  199. state := it.stack[len(it.stack)-1]
  200. it.Hash, it.Node, it.Parent = state.hash, state.node, state.parent
  201. if value, ok := it.Node.(valueNode); ok {
  202. it.Leaf, it.LeafBlob = true, []byte(value)
  203. }
  204. return true
  205. }