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