iterator.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. "fmt"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/logger"
  22. "github.com/ethereum/go-ethereum/logger/glog"
  23. )
  24. // Iterator is a key-value trie iterator to traverse the data contents.
  25. type Iterator struct {
  26. trie *Trie
  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. }
  30. // NewIterator creates a new key-value iterator.
  31. func NewIterator(trie *Trie) *Iterator {
  32. return &Iterator{trie: trie, Key: nil}
  33. }
  34. // Next moves the iterator forward with one key-value entry.
  35. func (self *Iterator) Next() bool {
  36. isIterStart := false
  37. if self.Key == nil {
  38. isIterStart = true
  39. self.Key = make([]byte, 32)
  40. }
  41. key := remTerm(compactHexDecode(self.Key))
  42. k := self.next(self.trie.root, key, isIterStart)
  43. self.Key = []byte(decodeCompact(k))
  44. return len(k) > 0
  45. }
  46. func (self *Iterator) next(node interface{}, key []byte, isIterStart bool) []byte {
  47. if node == nil {
  48. return nil
  49. }
  50. switch node := node.(type) {
  51. case fullNode:
  52. if len(key) > 0 {
  53. k := self.next(node[key[0]], key[1:], isIterStart)
  54. if k != nil {
  55. return append([]byte{key[0]}, k...)
  56. }
  57. }
  58. var r byte
  59. if len(key) > 0 {
  60. r = key[0] + 1
  61. }
  62. for i := r; i < 16; i++ {
  63. k := self.key(node[i])
  64. if k != nil {
  65. return append([]byte{i}, k...)
  66. }
  67. }
  68. case shortNode:
  69. k := remTerm(node.Key)
  70. if vnode, ok := node.Val.(valueNode); ok {
  71. switch bytes.Compare([]byte(k), key) {
  72. case 0:
  73. if isIterStart {
  74. self.Value = vnode
  75. return k
  76. }
  77. case 1:
  78. self.Value = vnode
  79. return k
  80. }
  81. } else {
  82. cnode := node.Val
  83. var ret []byte
  84. skey := key[len(k):]
  85. if bytes.HasPrefix(key, k) {
  86. ret = self.next(cnode, skey, isIterStart)
  87. } else if bytes.Compare(k, key[:len(k)]) > 0 {
  88. return self.key(node)
  89. }
  90. if ret != nil {
  91. return append(k, ret...)
  92. }
  93. }
  94. case hashNode:
  95. rn, err := self.trie.resolveHash(node, nil, nil)
  96. if err != nil && glog.V(logger.Error) {
  97. glog.Errorf("Unhandled trie error: %v", err)
  98. }
  99. return self.next(rn, key, isIterStart)
  100. }
  101. return nil
  102. }
  103. func (self *Iterator) key(node interface{}) []byte {
  104. switch node := node.(type) {
  105. case shortNode:
  106. // Leaf node
  107. k := remTerm(node.Key)
  108. if vnode, ok := node.Val.(valueNode); ok {
  109. self.Value = vnode
  110. return k
  111. }
  112. return append(k, self.key(node.Val)...)
  113. case fullNode:
  114. if node[16] != nil {
  115. self.Value = node[16].(valueNode)
  116. return []byte{16}
  117. }
  118. for i := 0; i < 16; i++ {
  119. k := self.key(node[i])
  120. if k != nil {
  121. return append([]byte{byte(i)}, k...)
  122. }
  123. }
  124. case hashNode:
  125. rn, err := self.trie.resolveHash(node, nil, nil)
  126. if err != nil && glog.V(logger.Error) {
  127. glog.Errorf("Unhandled trie error: %v", err)
  128. }
  129. return self.key(rn)
  130. }
  131. return nil
  132. }
  133. // nodeIteratorState represents the iteration state at one particular node of the
  134. // trie, which can be resumed at a later invocation.
  135. type nodeIteratorState struct {
  136. hash common.Hash // Hash of the node being iterated (nil if not standalone)
  137. node node // Trie node being iterated
  138. parent common.Hash // Hash of the first full ancestor node (nil if current is the root)
  139. child int // Child to be processed next
  140. }
  141. // NodeIterator is an iterator to traverse the trie post-order.
  142. type NodeIterator struct {
  143. trie *Trie // Trie being iterated
  144. stack []*nodeIteratorState // Hierarchy of trie nodes persisting the iteration state
  145. Hash common.Hash // Hash of the current node being iterated (nil if not standalone)
  146. Node node // Current node being iterated (internal representation)
  147. Parent common.Hash // Hash of the first full ancestor node (nil if current is the root)
  148. Leaf bool // Flag whether the current node is a value (data) node
  149. LeafBlob []byte // Data blob contained within a leaf (otherwise nil)
  150. Error error // Failure set in case of an internal error in the iterator
  151. }
  152. // NewNodeIterator creates an post-order trie iterator.
  153. func NewNodeIterator(trie *Trie) *NodeIterator {
  154. if bytes.Compare(trie.Root(), emptyRoot.Bytes()) == 0 {
  155. return new(NodeIterator)
  156. }
  157. return &NodeIterator{trie: trie}
  158. }
  159. // Next moves the iterator to the next node, returning whether there are any
  160. // further nodes. In case of an internal error this method returns false and
  161. // sets the Error field to the encountered failure.
  162. func (it *NodeIterator) Next() bool {
  163. // If the iterator failed previously, don't do anything
  164. if it.Error != nil {
  165. return false
  166. }
  167. // Otherwise step forward with the iterator and report any errors
  168. if err := it.step(); err != nil {
  169. it.Error = err
  170. return false
  171. }
  172. return it.retrieve()
  173. }
  174. // step moves the iterator to the next node of the trie.
  175. func (it *NodeIterator) step() error {
  176. // Abort if we reached the end of the iteration
  177. if it.trie == nil {
  178. return nil
  179. }
  180. // Initialize the iterator if we've just started, or pop off the old node otherwise
  181. if len(it.stack) == 0 {
  182. it.stack = append(it.stack, &nodeIteratorState{node: it.trie.root, child: -1})
  183. if it.stack[0].node == nil {
  184. return fmt.Errorf("root node missing: %x", it.trie.Root())
  185. }
  186. } else {
  187. it.stack = it.stack[:len(it.stack)-1]
  188. if len(it.stack) == 0 {
  189. it.trie = nil
  190. return nil
  191. }
  192. }
  193. // Continue iteration to the next child
  194. for {
  195. parent := it.stack[len(it.stack)-1]
  196. ancestor := parent.hash
  197. if (ancestor == common.Hash{}) {
  198. ancestor = parent.parent
  199. }
  200. if node, ok := parent.node.(fullNode); ok {
  201. // Full node, traverse all children, then the node itself
  202. if parent.child >= len(node) {
  203. break
  204. }
  205. for parent.child++; parent.child < len(node); parent.child++ {
  206. if current := node[parent.child]; current != nil {
  207. it.stack = append(it.stack, &nodeIteratorState{node: current, parent: ancestor, child: -1})
  208. break
  209. }
  210. }
  211. } else if node, ok := parent.node.(shortNode); ok {
  212. // Short node, traverse the pointer singleton child, then the node itself
  213. if parent.child >= 0 {
  214. break
  215. }
  216. parent.child++
  217. it.stack = append(it.stack, &nodeIteratorState{node: node.Val, parent: ancestor, child: -1})
  218. } else if hash, ok := parent.node.(hashNode); ok {
  219. // Hash node, resolve the hash child from the database, then the node itself
  220. if parent.child >= 0 {
  221. break
  222. }
  223. parent.child++
  224. node, err := it.trie.resolveHash(hash, nil, nil)
  225. if err != nil {
  226. return err
  227. }
  228. it.stack = append(it.stack, &nodeIteratorState{hash: common.BytesToHash(hash), node: node, parent: ancestor, child: -1})
  229. } else {
  230. break
  231. }
  232. }
  233. return nil
  234. }
  235. // retrieve pulls and caches the current trie node the iterator is traversing.
  236. // In case of a value node, the additional leaf blob is also populated with the
  237. // data contents for external interpretation.
  238. //
  239. // The method returns whether there are any more data left for inspection.
  240. func (it *NodeIterator) retrieve() bool {
  241. // Clear out any previously set values
  242. it.Hash, it.Node, it.Parent, it.Leaf, it.LeafBlob = common.Hash{}, nil, common.Hash{}, false, nil
  243. // If the iteration's done, return no available data
  244. if it.trie == nil {
  245. return false
  246. }
  247. // Otherwise retrieve the current node and resolve leaf accessors
  248. state := it.stack[len(it.stack)-1]
  249. it.Hash, it.Node, it.Parent = state.hash, state.node, state.parent
  250. if value, ok := it.Node.(valueNode); ok {
  251. it.Leaf, it.LeafBlob = true, []byte(value)
  252. }
  253. return true
  254. }