iterator_fast.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. return false
  151. }
  152. if fi.curAccount != nil {
  153. return true
  154. }
  155. // Implicit else: we've hit a nil-account, and need to fall through to the
  156. // loop below to land on something non-nil
  157. }
  158. // If an account is deleted in one of the layers, the key will still be there,
  159. // but the actual value will be nil. However, the iterator should not
  160. // export nil-values (but instead simply omit the key), so we need to loop
  161. // here until we either
  162. // - get a non-nil value,
  163. // - hit an error,
  164. // - or exhaust the iterator
  165. for {
  166. if !fi.next(0) {
  167. return false // exhausted
  168. }
  169. fi.curAccount = fi.iterators[0].it.Account()
  170. if innerErr := fi.iterators[0].it.Error(); innerErr != nil {
  171. fi.fail = innerErr
  172. return false // error
  173. }
  174. if fi.curAccount != nil {
  175. break // non-nil value found
  176. }
  177. }
  178. return true
  179. }
  180. // next handles the next operation internally and should be invoked when we know
  181. // that two elements in the list may have the same value.
  182. //
  183. // For example, if the iterated hashes become [2,3,5,5,8,9,10], then we should
  184. // invoke next(3), which will call Next on elem 3 (the second '5') and will
  185. // cascade along the list, applying the same operation if needed.
  186. func (fi *fastAccountIterator) next(idx int) bool {
  187. // If this particular iterator got exhausted, remove it and return true (the
  188. // next one is surely not exhausted yet, otherwise it would have been removed
  189. // already).
  190. if it := fi.iterators[idx].it; !it.Next() {
  191. it.Release()
  192. fi.iterators = append(fi.iterators[:idx], fi.iterators[idx+1:]...)
  193. return len(fi.iterators) > 0
  194. }
  195. // If there's noone left to cascade into, return
  196. if idx == len(fi.iterators)-1 {
  197. return true
  198. }
  199. // We next-ed the iterator at 'idx', now we may have to re-sort that element
  200. var (
  201. cur, next = fi.iterators[idx], fi.iterators[idx+1]
  202. curHash, nextHash = cur.it.Hash(), next.it.Hash()
  203. )
  204. if diff := bytes.Compare(curHash[:], nextHash[:]); diff < 0 {
  205. // It is still in correct place
  206. return true
  207. } else if diff == 0 && cur.priority < next.priority {
  208. // So still in correct place, but we need to iterate on the next
  209. fi.next(idx + 1)
  210. return true
  211. }
  212. // At this point, the iterator is in the wrong location, but the remaining
  213. // list is sorted. Find out where to move the item.
  214. clash := -1
  215. index := sort.Search(len(fi.iterators), func(n int) bool {
  216. // The iterator always advances forward, so anything before the old slot
  217. // is known to be behind us, so just skip them altogether. This actually
  218. // is an important clause since the sort order got invalidated.
  219. if n < idx {
  220. return false
  221. }
  222. if n == len(fi.iterators)-1 {
  223. // Can always place an elem last
  224. return true
  225. }
  226. nextHash := fi.iterators[n+1].it.Hash()
  227. if diff := bytes.Compare(curHash[:], nextHash[:]); diff < 0 {
  228. return true
  229. } else if diff > 0 {
  230. return false
  231. }
  232. // The elem we're placing it next to has the same value,
  233. // so whichever winds up on n+1 will need further iteraton
  234. clash = n + 1
  235. return cur.priority < fi.iterators[n+1].priority
  236. })
  237. fi.move(idx, index)
  238. if clash != -1 {
  239. fi.next(clash)
  240. }
  241. return true
  242. }
  243. // move advances an iterator to another position in the list.
  244. func (fi *fastAccountIterator) move(index, newpos int) {
  245. elem := fi.iterators[index]
  246. copy(fi.iterators[index:], fi.iterators[index+1:newpos+1])
  247. fi.iterators[newpos] = elem
  248. }
  249. // Error returns any failure that occurred during iteration, which might have
  250. // caused a premature iteration exit (e.g. snapshot stack becoming stale).
  251. func (fi *fastAccountIterator) Error() error {
  252. return fi.fail
  253. }
  254. // Hash returns the current key
  255. func (fi *fastAccountIterator) Hash() common.Hash {
  256. return fi.iterators[0].it.Hash()
  257. }
  258. // Account returns the current key
  259. func (fi *fastAccountIterator) Account() []byte {
  260. return fi.curAccount
  261. }
  262. // Release iterates over all the remaining live layer iterators and releases each
  263. // of thme individually.
  264. func (fi *fastAccountIterator) Release() {
  265. for _, it := range fi.iterators {
  266. it.it.Release()
  267. }
  268. fi.iterators = nil
  269. }
  270. // Debug is a convencience helper during testing
  271. func (fi *fastAccountIterator) Debug() {
  272. for _, it := range fi.iterators {
  273. fmt.Printf("[p=%v v=%v] ", it.priority, it.it.Hash()[0])
  274. }
  275. fmt.Println()
  276. }