iterator_fast.go 9.0 KB

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