iterator_fast.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // Copyright 2019 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 snapshot
  17. import (
  18. "bytes"
  19. "fmt"
  20. "sort"
  21. "github.com/ethereum/go-ethereum/common"
  22. )
  23. // weightedAccountIterator is an account iterator with an assigned weight. It is
  24. // used to prioritise which account is the correct one if multiple iterators find
  25. // the same one (modified in multiple consecutive blocks).
  26. type weightedAccountIterator struct {
  27. it AccountIterator
  28. priority int
  29. }
  30. // weightedAccountIterators is a set of iterators implementing the sort.Interface.
  31. type weightedAccountIterators []*weightedAccountIterator
  32. // Len implements sort.Interface, returning the number of active iterators.
  33. func (its weightedAccountIterators) Len() int { return len(its) }
  34. // Less implements sort.Interface, returning which of two iterators in the stack
  35. // is before the other.
  36. func (its weightedAccountIterators) Less(i, j int) bool {
  37. // Order the iterators primarilly by the account hashes
  38. hashI := its[i].it.Hash()
  39. hashJ := its[j].it.Hash()
  40. switch bytes.Compare(hashI[:], hashJ[:]) {
  41. case -1:
  42. return true
  43. case 1:
  44. return false
  45. }
  46. // Same account in multiple layers, split by priority
  47. return its[i].priority < its[j].priority
  48. }
  49. // Swap implements sort.Interface, swapping two entries in the iterator stack.
  50. func (its weightedAccountIterators) Swap(i, j int) {
  51. its[i], its[j] = its[j], its[i]
  52. }
  53. // fastAccountIterator is a more optimized multi-layer iterator which maintains a
  54. // direct mapping of all iterators leading down to the bottom layer.
  55. type fastAccountIterator struct {
  56. tree *Tree // Snapshot tree to reinitialize stale sub-iterators with
  57. root common.Hash // Root hash to reinitialize stale sub-iterators through
  58. iterators weightedAccountIterators
  59. initiated bool
  60. fail error
  61. }
  62. // newFastAccountIterator creates a new hierarhical account iterator with one
  63. // element per diff layer. The returned combo iterator can be used to walk over
  64. // the entire snapshot diff stack simultaneously.
  65. func newFastAccountIterator(tree *Tree, root common.Hash, seek common.Hash) (AccountIterator, error) {
  66. snap := tree.Snapshot(root)
  67. if snap == nil {
  68. return nil, fmt.Errorf("unknown snapshot: %x", root)
  69. }
  70. fi := &fastAccountIterator{
  71. tree: tree,
  72. root: root,
  73. }
  74. current := snap.(snapshot)
  75. for depth := 0; current != nil; depth++ {
  76. fi.iterators = append(fi.iterators, &weightedAccountIterator{
  77. it: current.AccountIterator(seek),
  78. priority: depth,
  79. })
  80. current = current.Parent()
  81. }
  82. fi.init()
  83. return fi, nil
  84. }
  85. // init walks over all the iterators and resolves any clashes between them, after
  86. // which it prepares the stack for step-by-step iteration.
  87. func (fi *fastAccountIterator) init() {
  88. // Track which account hashes are iterators positioned on
  89. var positioned = make(map[common.Hash]int)
  90. // Position all iterators and track how many remain live
  91. for i := 0; i < len(fi.iterators); i++ {
  92. // Retrieve the first element and if it clashes with a previous iterator,
  93. // advance either the current one or the old one. Repeat until nothing is
  94. // clashing any more.
  95. it := fi.iterators[i]
  96. for {
  97. // If the iterator is exhausted, drop it off the end
  98. if !it.it.Next() {
  99. it.it.Release()
  100. last := len(fi.iterators) - 1
  101. fi.iterators[i] = fi.iterators[last]
  102. fi.iterators[last] = nil
  103. fi.iterators = fi.iterators[:last]
  104. i--
  105. break
  106. }
  107. // The iterator is still alive, check for collisions with previous ones
  108. hash := it.it.Hash()
  109. if other, exist := positioned[hash]; !exist {
  110. positioned[hash] = i
  111. break
  112. } else {
  113. // Iterators collide, one needs to be progressed, use priority to
  114. // determine which.
  115. //
  116. // This whole else-block can be avoided, if we instead
  117. // do an inital priority-sort of the iterators. If we do that,
  118. // then we'll only wind up here if a lower-priority (preferred) iterator
  119. // has the same value, and then we will always just continue.
  120. // However, it costs an extra sort, so it's probably not better
  121. if fi.iterators[other].priority < it.priority {
  122. // The 'it' should be progressed
  123. continue
  124. } else {
  125. // The 'other' should be progressed, swap them
  126. it = fi.iterators[other]
  127. fi.iterators[other], fi.iterators[i] = fi.iterators[i], fi.iterators[other]
  128. continue
  129. }
  130. }
  131. }
  132. }
  133. // Re-sort the entire list
  134. sort.Sort(fi.iterators)
  135. fi.initiated = false
  136. }
  137. // Next steps the iterator forward one element, returning false if exhausted.
  138. func (fi *fastAccountIterator) Next() bool {
  139. if len(fi.iterators) == 0 {
  140. return false
  141. }
  142. if !fi.initiated {
  143. // Don't forward first time -- we had to 'Next' once in order to
  144. // do the sorting already
  145. fi.initiated = true
  146. return true
  147. }
  148. return fi.next(0)
  149. }
  150. // next handles the next operation internally and should be invoked when we know
  151. // that two elements in the list may have the same value.
  152. //
  153. // For example, if the iterated hashes become [2,3,5,5,8,9,10], then we should
  154. // invoke next(3), which will call Next on elem 3 (the second '5') and will
  155. // cascade along the list, applying the same operation if needed.
  156. func (fi *fastAccountIterator) next(idx int) bool {
  157. // If this particular iterator got exhausted, remove it and return true (the
  158. // next one is surely not exhausted yet, otherwise it would have been removed
  159. // already).
  160. if it := fi.iterators[idx].it; !it.Next() {
  161. it.Release()
  162. fi.iterators = append(fi.iterators[:idx], fi.iterators[idx+1:]...)
  163. return len(fi.iterators) > 0
  164. }
  165. // If there's noone left to cascade into, return
  166. if idx == len(fi.iterators)-1 {
  167. return true
  168. }
  169. // We next-ed the iterator at 'idx', now we may have to re-sort that element
  170. var (
  171. cur, next = fi.iterators[idx], fi.iterators[idx+1]
  172. curHash, nextHash = cur.it.Hash(), next.it.Hash()
  173. )
  174. if diff := bytes.Compare(curHash[:], nextHash[:]); diff < 0 {
  175. // It is still in correct place
  176. return true
  177. } else if diff == 0 && cur.priority < next.priority {
  178. // So still in correct place, but we need to iterate on the next
  179. fi.next(idx + 1)
  180. return true
  181. }
  182. // At this point, the iterator is in the wrong location, but the remaining
  183. // list is sorted. Find out where to move the item.
  184. clash := -1
  185. index := sort.Search(len(fi.iterators), func(n int) bool {
  186. // The iterator always advances forward, so anything before the old slot
  187. // is known to be behind us, so just skip them altogether. This actually
  188. // is an important clause since the sort order got invalidated.
  189. if n < idx {
  190. return false
  191. }
  192. if n == len(fi.iterators)-1 {
  193. // Can always place an elem last
  194. return true
  195. }
  196. nextHash := fi.iterators[n+1].it.Hash()
  197. if diff := bytes.Compare(curHash[:], nextHash[:]); diff < 0 {
  198. return true
  199. } else if diff > 0 {
  200. return false
  201. }
  202. // The elem we're placing it next to has the same value,
  203. // so whichever winds up on n+1 will need further iteraton
  204. clash = n + 1
  205. if cur.priority < fi.iterators[n+1].priority {
  206. // We can drop the iterator here
  207. return true
  208. }
  209. // We need to move it one step further
  210. return false
  211. // TODO benchmark which is best, this works too:
  212. //clash = n
  213. //return true
  214. // Doing so should finish the current search earlier
  215. })
  216. fi.move(idx, index)
  217. if clash != -1 {
  218. fi.next(clash)
  219. }
  220. return true
  221. }
  222. // move advances an iterator to another position in the list.
  223. func (fi *fastAccountIterator) move(index, newpos int) {
  224. elem := fi.iterators[index]
  225. copy(fi.iterators[index:], fi.iterators[index+1:newpos+1])
  226. fi.iterators[newpos] = elem
  227. }
  228. // Error returns any failure that occurred during iteration, which might have
  229. // caused a premature iteration exit (e.g. snapshot stack becoming stale).
  230. func (fi *fastAccountIterator) Error() error {
  231. return fi.fail
  232. }
  233. // Hash returns the current key
  234. func (fi *fastAccountIterator) Hash() common.Hash {
  235. return fi.iterators[0].it.Hash()
  236. }
  237. // Account returns the current key
  238. func (fi *fastAccountIterator) Account() []byte {
  239. return fi.iterators[0].it.Account()
  240. }
  241. // Release iterates over all the remaining live layer iterators and releases each
  242. // of thme individually.
  243. func (fi *fastAccountIterator) Release() {
  244. for _, it := range fi.iterators {
  245. it.it.Release()
  246. }
  247. fi.iterators = nil
  248. }
  249. // Debug is a convencience helper during testing
  250. func (fi *fastAccountIterator) Debug() {
  251. for _, it := range fi.iterators {
  252. fmt.Printf("[p=%v v=%v] ", it.priority, it.it.Hash()[0])
  253. }
  254. fmt.Println()
  255. }