difflayer.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. "encoding/binary"
  19. "bytes"
  20. "fmt"
  21. "math"
  22. "math/rand"
  23. "sort"
  24. "sync"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/rlp"
  29. "github.com/steakknife/bloomfilter"
  30. )
  31. var (
  32. // aggregatorMemoryLimit is the maximum size of the bottom-most diff layer
  33. // that aggregates the writes from above until it's flushed into the disk
  34. // layer.
  35. //
  36. // Note, bumping this up might drastically increase the size of the bloom
  37. // filters that's stored in every diff layer. Don't do that without fully
  38. // understanding all the implications.
  39. aggregatorMemoryLimit = uint64(4 * 1024 * 1024)
  40. // aggregatorItemLimit is an approximate number of items that will end up
  41. // in the agregator layer before it's flushed out to disk. A plain account
  42. // weighs around 14B (+hash), a storage slot 32B (+hash), a deleted slot
  43. // 0B (+hash). Slots are mostly set/unset in lockstep, so thet average at
  44. // 16B (+hash). All in all, the average entry seems to be 15+32=47B. Use a
  45. // smaller number to be on the safe side.
  46. aggregatorItemLimit = aggregatorMemoryLimit / 42
  47. // bloomTargetError is the target false positive rate when the aggregator
  48. // layer is at its fullest. The actual value will probably move around up
  49. // and down from this number, it's mostly a ballpark figure.
  50. //
  51. // Note, dropping this down might drastically increase the size of the bloom
  52. // filters that's stored in every diff layer. Don't do that without fully
  53. // understanding all the implications.
  54. bloomTargetError = 0.02
  55. // bloomSize is the ideal bloom filter size given the maximum number of items
  56. // it's expected to hold and the target false positive error rate.
  57. bloomSize = math.Ceil(float64(aggregatorItemLimit) * math.Log(bloomTargetError) / math.Log(1/math.Pow(2, math.Log(2))))
  58. // bloomFuncs is the ideal number of bits a single entry should set in the
  59. // bloom filter to keep its size to a minimum (given it's size and maximum
  60. // entry count).
  61. bloomFuncs = math.Round((bloomSize / float64(aggregatorItemLimit)) * math.Log(2))
  62. // bloomHashesOffset is a runtime constant which determines which part of the
  63. // the account/storage hash the hasher functions looks at, to determine the
  64. // bloom key for an account/slot. This is randomized at init(), so that the
  65. // global population of nodes do not all display the exact same behaviour with
  66. // regards to bloom content
  67. bloomHasherOffset = 0
  68. )
  69. func init() {
  70. // Init bloomHasherOffset in the range [0:24] (requires 8 bytes)
  71. bloomHasherOffset = rand.Intn(25)
  72. }
  73. // diffLayer represents a collection of modifications made to a state snapshot
  74. // after running a block on top. It contains one sorted list for the account trie
  75. // and one-one list for each storage tries.
  76. //
  77. // The goal of a diff layer is to act as a journal, tracking recent modifications
  78. // made to the state, that have not yet graduated into a semi-immutable state.
  79. type diffLayer struct {
  80. origin *diskLayer // Base disk layer to directly use on bloom misses
  81. parent snapshot // Parent snapshot modified by this one, never nil
  82. memory uint64 // Approximate guess as to how much memory we use
  83. root common.Hash // Root hash to which this snapshot diff belongs to
  84. stale bool // Signals that the layer became stale (state progressed)
  85. accountList []common.Hash // List of account for iteration. If it exists, it's sorted, otherwise it's nil
  86. accountData map[common.Hash][]byte // Keyed accounts for direct retrival (nil means deleted)
  87. storageList map[common.Hash][]common.Hash // List of storage slots for iterated retrievals, one per account. Any existing lists are sorted if non-nil
  88. storageData map[common.Hash]map[common.Hash][]byte // Keyed storage slots for direct retrival. one per account (nil means deleted)
  89. diffed *bloomfilter.Filter // Bloom filter tracking all the diffed items up to the disk layer
  90. lock sync.RWMutex
  91. }
  92. // accountBloomHasher is a wrapper around a common.Hash to satisfy the interface
  93. // API requirements of the bloom library used. It's used to convert an account
  94. // hash into a 64 bit mini hash.
  95. type accountBloomHasher common.Hash
  96. func (h accountBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") }
  97. func (h accountBloomHasher) Sum(b []byte) []byte { panic("not implemented") }
  98. func (h accountBloomHasher) Reset() { panic("not implemented") }
  99. func (h accountBloomHasher) BlockSize() int { panic("not implemented") }
  100. func (h accountBloomHasher) Size() int { return 8 }
  101. func (h accountBloomHasher) Sum64() uint64 {
  102. return binary.BigEndian.Uint64(h[bloomHasherOffset : bloomHasherOffset+8])
  103. }
  104. // storageBloomHasher is a wrapper around a [2]common.Hash to satisfy the interface
  105. // API requirements of the bloom library used. It's used to convert an account
  106. // hash into a 64 bit mini hash.
  107. type storageBloomHasher [2]common.Hash
  108. func (h storageBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") }
  109. func (h storageBloomHasher) Sum(b []byte) []byte { panic("not implemented") }
  110. func (h storageBloomHasher) Reset() { panic("not implemented") }
  111. func (h storageBloomHasher) BlockSize() int { panic("not implemented") }
  112. func (h storageBloomHasher) Size() int { return 8 }
  113. func (h storageBloomHasher) Sum64() uint64 {
  114. return binary.BigEndian.Uint64(h[0][bloomHasherOffset:bloomHasherOffset+8]) ^
  115. binary.BigEndian.Uint64(h[1][bloomHasherOffset:bloomHasherOffset+8])
  116. }
  117. // newDiffLayer creates a new diff on top of an existing snapshot, whether that's a low
  118. // level persistent database or a hierarchical diff already.
  119. func newDiffLayer(parent snapshot, root common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
  120. // Create the new layer with some pre-allocated data segments
  121. dl := &diffLayer{
  122. parent: parent,
  123. root: root,
  124. accountData: accounts,
  125. storageData: storage,
  126. }
  127. switch parent := parent.(type) {
  128. case *diskLayer:
  129. dl.rebloom(parent)
  130. case *diffLayer:
  131. dl.rebloom(parent.origin)
  132. default:
  133. panic("unknown parent type")
  134. }
  135. // Determine memory size and track the dirty writes
  136. for _, data := range accounts {
  137. dl.memory += uint64(common.HashLength + len(data))
  138. snapshotDirtyAccountWriteMeter.Mark(int64(len(data)))
  139. }
  140. // Fill the storage hashes and sort them for the iterator
  141. dl.storageList = make(map[common.Hash][]common.Hash)
  142. for accountHash, slots := range storage {
  143. // If the slots are nil, sanity check that it's a deleted account
  144. if slots == nil {
  145. // Ensure that the account was just marked as deleted
  146. if account, ok := accounts[accountHash]; account != nil || !ok {
  147. panic(fmt.Sprintf("storage in %#x nil, but account conflicts (%#x, exists: %v)", accountHash, account, ok))
  148. }
  149. // Everything ok, store the deletion mark and continue
  150. dl.storageList[accountHash] = nil
  151. continue
  152. }
  153. // Storage slots are not nil so entire contract was not deleted, ensure the
  154. // account was just updated.
  155. if account, ok := accounts[accountHash]; account == nil || !ok {
  156. log.Error(fmt.Sprintf("storage in %#x exists, but account nil (exists: %v)", accountHash, ok))
  157. }
  158. // Determine memory size and track the dirty writes
  159. for _, data := range slots {
  160. dl.memory += uint64(common.HashLength + len(data))
  161. snapshotDirtyStorageWriteMeter.Mark(int64(len(data)))
  162. }
  163. }
  164. dl.memory += uint64(len(dl.storageList) * common.HashLength)
  165. return dl
  166. }
  167. // rebloom discards the layer's current bloom and rebuilds it from scratch based
  168. // on the parent's and the local diffs.
  169. func (dl *diffLayer) rebloom(origin *diskLayer) {
  170. dl.lock.Lock()
  171. defer dl.lock.Unlock()
  172. defer func(start time.Time) {
  173. snapshotBloomIndexTimer.Update(time.Since(start))
  174. }(time.Now())
  175. // Inject the new origin that triggered the rebloom
  176. dl.origin = origin
  177. // Retrieve the parent bloom or create a fresh empty one
  178. if parent, ok := dl.parent.(*diffLayer); ok {
  179. parent.lock.RLock()
  180. dl.diffed, _ = parent.diffed.Copy()
  181. parent.lock.RUnlock()
  182. } else {
  183. dl.diffed, _ = bloomfilter.New(uint64(bloomSize), uint64(bloomFuncs))
  184. }
  185. // Iterate over all the accounts and storage slots and index them
  186. for hash := range dl.accountData {
  187. dl.diffed.Add(accountBloomHasher(hash))
  188. }
  189. for accountHash, slots := range dl.storageData {
  190. for storageHash := range slots {
  191. dl.diffed.Add(storageBloomHasher{accountHash, storageHash})
  192. }
  193. }
  194. // Calculate the current false positive rate and update the error rate meter.
  195. // This is a bit cheating because subsequent layers will overwrite it, but it
  196. // should be fine, we're only interested in ballpark figures.
  197. k := float64(dl.diffed.K())
  198. n := float64(dl.diffed.N())
  199. m := float64(dl.diffed.M())
  200. snapshotBloomErrorGauge.Update(math.Pow(1.0-math.Exp((-k)*(n+0.5)/(m-1)), k))
  201. }
  202. // Root returns the root hash for which this snapshot was made.
  203. func (dl *diffLayer) Root() common.Hash {
  204. return dl.root
  205. }
  206. // Stale return whether this layer has become stale (was flattened across) or if
  207. // it's still live.
  208. func (dl *diffLayer) Stale() bool {
  209. dl.lock.RLock()
  210. defer dl.lock.RUnlock()
  211. return dl.stale
  212. }
  213. // Account directly retrieves the account associated with a particular hash in
  214. // the snapshot slim data format.
  215. func (dl *diffLayer) Account(hash common.Hash) (*Account, error) {
  216. data, err := dl.AccountRLP(hash)
  217. if err != nil {
  218. return nil, err
  219. }
  220. if len(data) == 0 { // can be both nil and []byte{}
  221. return nil, nil
  222. }
  223. account := new(Account)
  224. if err := rlp.DecodeBytes(data, account); err != nil {
  225. panic(err)
  226. }
  227. return account, nil
  228. }
  229. // AccountRLP directly retrieves the account RLP associated with a particular
  230. // hash in the snapshot slim data format.
  231. func (dl *diffLayer) AccountRLP(hash common.Hash) ([]byte, error) {
  232. // Check the bloom filter first whether there's even a point in reaching into
  233. // all the maps in all the layers below
  234. dl.lock.RLock()
  235. hit := dl.diffed.Contains(accountBloomHasher(hash))
  236. dl.lock.RUnlock()
  237. // If the bloom filter misses, don't even bother with traversing the memory
  238. // diff layers, reach straight into the bottom persistent disk layer
  239. if !hit {
  240. snapshotBloomAccountMissMeter.Mark(1)
  241. return dl.origin.AccountRLP(hash)
  242. }
  243. // The bloom filter hit, start poking in the internal maps
  244. return dl.accountRLP(hash, 0)
  245. }
  246. // accountRLP is an internal version of AccountRLP that skips the bloom filter
  247. // checks and uses the internal maps to try and retrieve the data. It's meant
  248. // to be used if a higher layer's bloom filter hit already.
  249. func (dl *diffLayer) accountRLP(hash common.Hash, depth int) ([]byte, error) {
  250. dl.lock.RLock()
  251. defer dl.lock.RUnlock()
  252. // If the layer was flattened into, consider it invalid (any live reference to
  253. // the original should be marked as unusable).
  254. if dl.stale {
  255. return nil, ErrSnapshotStale
  256. }
  257. // If the account is known locally, return it. Note, a nil account means it was
  258. // deleted, and is a different notion than an unknown account!
  259. if data, ok := dl.accountData[hash]; ok {
  260. snapshotDirtyAccountHitMeter.Mark(1)
  261. snapshotDirtyAccountHitDepthHist.Update(int64(depth))
  262. if n := len(data); n > 0 {
  263. snapshotDirtyAccountReadMeter.Mark(int64(n))
  264. } else {
  265. snapshotDirtyAccountInexMeter.Mark(1)
  266. }
  267. snapshotBloomAccountTrueHitMeter.Mark(1)
  268. return data, nil
  269. }
  270. // Account unknown to this diff, resolve from parent
  271. if diff, ok := dl.parent.(*diffLayer); ok {
  272. return diff.accountRLP(hash, depth+1)
  273. }
  274. // Failed to resolve through diff layers, mark a bloom error and use the disk
  275. snapshotBloomAccountFalseHitMeter.Mark(1)
  276. return dl.parent.AccountRLP(hash)
  277. }
  278. // Storage directly retrieves the storage data associated with a particular hash,
  279. // within a particular account. If the slot is unknown to this diff, it's parent
  280. // is consulted.
  281. func (dl *diffLayer) Storage(accountHash, storageHash common.Hash) ([]byte, error) {
  282. // Check the bloom filter first whether there's even a point in reaching into
  283. // all the maps in all the layers below
  284. dl.lock.RLock()
  285. hit := dl.diffed.Contains(storageBloomHasher{accountHash, storageHash})
  286. dl.lock.RUnlock()
  287. // If the bloom filter misses, don't even bother with traversing the memory
  288. // diff layers, reach straight into the bottom persistent disk layer
  289. if !hit {
  290. snapshotBloomStorageMissMeter.Mark(1)
  291. return dl.origin.Storage(accountHash, storageHash)
  292. }
  293. // The bloom filter hit, start poking in the internal maps
  294. return dl.storage(accountHash, storageHash, 0)
  295. }
  296. // storage is an internal version of Storage that skips the bloom filter checks
  297. // and uses the internal maps to try and retrieve the data. It's meant to be
  298. // used if a higher layer's bloom filter hit already.
  299. func (dl *diffLayer) storage(accountHash, storageHash common.Hash, depth int) ([]byte, error) {
  300. dl.lock.RLock()
  301. defer dl.lock.RUnlock()
  302. // If the layer was flattened into, consider it invalid (any live reference to
  303. // the original should be marked as unusable).
  304. if dl.stale {
  305. return nil, ErrSnapshotStale
  306. }
  307. // If the account is known locally, try to resolve the slot locally. Note, a nil
  308. // account means it was deleted, and is a different notion than an unknown account!
  309. if storage, ok := dl.storageData[accountHash]; ok {
  310. if storage == nil {
  311. snapshotDirtyStorageHitMeter.Mark(1)
  312. snapshotDirtyStorageHitDepthHist.Update(int64(depth))
  313. snapshotDirtyStorageInexMeter.Mark(1)
  314. snapshotBloomStorageTrueHitMeter.Mark(1)
  315. return nil, nil
  316. }
  317. if data, ok := storage[storageHash]; ok {
  318. snapshotDirtyStorageHitMeter.Mark(1)
  319. snapshotDirtyStorageHitDepthHist.Update(int64(depth))
  320. if n := len(data); n > 0 {
  321. snapshotDirtyStorageReadMeter.Mark(int64(n))
  322. } else {
  323. snapshotDirtyStorageInexMeter.Mark(1)
  324. }
  325. snapshotBloomStorageTrueHitMeter.Mark(1)
  326. return data, nil
  327. }
  328. }
  329. // Storage slot unknown to this diff, resolve from parent
  330. if diff, ok := dl.parent.(*diffLayer); ok {
  331. return diff.storage(accountHash, storageHash, depth+1)
  332. }
  333. // Failed to resolve through diff layers, mark a bloom error and use the disk
  334. snapshotBloomStorageFalseHitMeter.Mark(1)
  335. return dl.parent.Storage(accountHash, storageHash)
  336. }
  337. // Update creates a new layer on top of the existing snapshot diff tree with
  338. // the specified data items.
  339. func (dl *diffLayer) Update(blockRoot common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
  340. return newDiffLayer(dl, blockRoot, accounts, storage)
  341. }
  342. // flatten pushes all data from this point downwards, flattening everything into
  343. // a single diff at the bottom. Since usually the lowermost diff is the largest,
  344. // the flattening bulds up from there in reverse.
  345. func (dl *diffLayer) flatten() snapshot {
  346. // If the parent is not diff, we're the first in line, return unmodified
  347. parent, ok := dl.parent.(*diffLayer)
  348. if !ok {
  349. return dl
  350. }
  351. // Parent is a diff, flatten it first (note, apart from weird corned cases,
  352. // flatten will realistically only ever merge 1 layer, so there's no need to
  353. // be smarter about grouping flattens together).
  354. parent = parent.flatten().(*diffLayer)
  355. parent.lock.Lock()
  356. defer parent.lock.Unlock()
  357. // Before actually writing all our data to the parent, first ensure that the
  358. // parent hasn't been 'corrupted' by someone else already flattening into it
  359. if parent.stale {
  360. panic("parent diff layer is stale") // we've flattened into the same parent from two children, boo
  361. }
  362. parent.stale = true
  363. // Overwrite all the updated accounts blindly, merge the sorted list
  364. for hash, data := range dl.accountData {
  365. parent.accountData[hash] = data
  366. }
  367. // Overwrite all the updates storage slots (individually)
  368. for accountHash, storage := range dl.storageData {
  369. // If storage didn't exist (or was deleted) in the parent; or if the storage
  370. // was freshly deleted in the child, overwrite blindly
  371. if parent.storageData[accountHash] == nil || storage == nil {
  372. parent.storageData[accountHash] = storage
  373. continue
  374. }
  375. // Storage exists in both parent and child, merge the slots
  376. comboData := parent.storageData[accountHash]
  377. for storageHash, data := range storage {
  378. comboData[storageHash] = data
  379. }
  380. parent.storageData[accountHash] = comboData
  381. }
  382. // Return the combo parent
  383. return &diffLayer{
  384. parent: parent.parent,
  385. origin: parent.origin,
  386. root: dl.root,
  387. storageList: parent.storageList,
  388. storageData: parent.storageData,
  389. accountList: parent.accountList,
  390. accountData: parent.accountData,
  391. diffed: dl.diffed,
  392. memory: parent.memory + dl.memory,
  393. }
  394. }
  395. // AccountList returns a sorted list of all accounts in this difflayer.
  396. func (dl *diffLayer) AccountList() []common.Hash {
  397. dl.lock.Lock()
  398. defer dl.lock.Unlock()
  399. if dl.accountList != nil {
  400. return dl.accountList
  401. }
  402. accountList := make([]common.Hash, len(dl.accountData))
  403. i := 0
  404. for k, _ := range dl.accountData {
  405. accountList[i] = k
  406. i++
  407. // This would be a pretty good opportunity to also
  408. // calculate the size, if we want to
  409. }
  410. sort.Sort(hashes(accountList))
  411. dl.accountList = accountList
  412. return dl.accountList
  413. }
  414. // StorageList returns a sorted list of all storage slot hashes
  415. // in this difflayer for the given account.
  416. func (dl *diffLayer) StorageList(accountHash common.Hash) []common.Hash {
  417. dl.lock.Lock()
  418. defer dl.lock.Unlock()
  419. if dl.storageList[accountHash] != nil {
  420. return dl.storageList[accountHash]
  421. }
  422. accountStorageMap := dl.storageData[accountHash]
  423. accountStorageList := make([]common.Hash, len(accountStorageMap))
  424. i := 0
  425. for k, _ := range accountStorageMap {
  426. accountStorageList[i] = k
  427. i++
  428. // This would be a pretty good opportunity to also
  429. // calculate the size, if we want to
  430. }
  431. sort.Sort(hashes(accountStorageList))
  432. dl.storageList[accountHash] = accountStorageList
  433. return accountStorageList
  434. }
  435. type Iterator interface {
  436. // Next steps the iterator forward one element, and returns false if
  437. // the iterator is exhausted
  438. Next() bool
  439. // Key returns the current key
  440. Key() common.Hash
  441. // Seek steps the iterator forward as many elements as needed, so that after
  442. // calling Next(), the iterator will be at a key higher than the given hash
  443. Seek(common.Hash)
  444. }
  445. func (dl *diffLayer) newIterator() Iterator {
  446. dl.AccountList()
  447. return &dlIterator{dl, -1}
  448. }
  449. type dlIterator struct {
  450. layer *diffLayer
  451. index int
  452. }
  453. func (it *dlIterator) Next() bool {
  454. if it.index < len(it.layer.accountList) {
  455. it.index++
  456. }
  457. return it.index < len(it.layer.accountList)
  458. }
  459. func (it *dlIterator) Key() common.Hash {
  460. if it.index < len(it.layer.accountList) {
  461. return it.layer.accountList[it.index]
  462. }
  463. return common.Hash{}
  464. }
  465. func (it *dlIterator) Seek(key common.Hash) {
  466. // Search uses binary search to find and return the smallest index i
  467. // in [0, n) at which f(i) is true
  468. size := len(it.layer.accountList)
  469. index := sort.Search(size,
  470. func(i int) bool {
  471. v := it.layer.accountList[i]
  472. return bytes.Compare(key[:], v[:]) < 0
  473. })
  474. it.index = index - 1
  475. }
  476. type binaryIterator struct {
  477. a Iterator
  478. b Iterator
  479. aDone bool
  480. bDone bool
  481. k common.Hash
  482. }
  483. func (dl *diffLayer) newBinaryIterator() Iterator {
  484. parent, ok := dl.parent.(*diffLayer)
  485. if !ok {
  486. // parent is the disk layer
  487. return dl.newIterator()
  488. }
  489. l := &binaryIterator{
  490. a: dl.newIterator(),
  491. b: parent.newBinaryIterator()}
  492. l.aDone = !l.a.Next()
  493. l.bDone = !l.b.Next()
  494. return l
  495. }
  496. func (it *binaryIterator) Next() bool {
  497. if it.aDone && it.bDone {
  498. return false
  499. }
  500. nextB := it.b.Key()
  501. first:
  502. nextA := it.a.Key()
  503. if it.aDone {
  504. it.bDone = !it.b.Next()
  505. it.k = nextB
  506. return true
  507. }
  508. if it.bDone {
  509. it.aDone = !it.a.Next()
  510. it.k = nextA
  511. return true
  512. }
  513. if diff := bytes.Compare(nextA[:], nextB[:]); diff < 0 {
  514. it.aDone = !it.a.Next()
  515. it.k = nextA
  516. return true
  517. } else if diff == 0 {
  518. // Now we need to advance one of them
  519. it.aDone = !it.a.Next()
  520. goto first
  521. }
  522. it.bDone = !it.b.Next()
  523. it.k = nextB
  524. return true
  525. }
  526. func (it *binaryIterator) Key() common.Hash {
  527. return it.k
  528. }
  529. func (it *binaryIterator) Seek(key common.Hash) {
  530. panic("todo: implement")
  531. }
  532. func (dl *diffLayer) iterators() []Iterator {
  533. if parent, ok := dl.parent.(*diffLayer); ok {
  534. iterators := parent.iterators()
  535. return append(iterators, dl.newIterator())
  536. }
  537. return []Iterator{dl.newIterator()}
  538. }
  539. // fastIterator is a more optimized multi-layer iterator which maintains a
  540. // direct mapping of all iterators leading down to the bottom layer
  541. type fastIterator struct {
  542. iterators []Iterator
  543. initiated bool
  544. }
  545. // Len returns the number of active iterators
  546. func (fi *fastIterator) Len() int {
  547. return len(fi.iterators)
  548. }
  549. // Less implements sort.Interface
  550. func (fi *fastIterator) Less(i, j int) bool {
  551. a := fi.iterators[i].Key()
  552. b := fi.iterators[j].Key()
  553. return bytes.Compare(a[:], b[:]) < 0
  554. }
  555. // Swap implements sort.Interface
  556. func (fi *fastIterator) Swap(i, j int) {
  557. fi.iterators[i], fi.iterators[j] = fi.iterators[j], fi.iterators[i]
  558. }
  559. // Next implements the Iterator interface. It returns false if no more elemnts
  560. // can be retrieved (false == exhausted)
  561. func (fi *fastIterator) Next() bool {
  562. if len(fi.iterators) == 0 {
  563. return false
  564. }
  565. if !fi.initiated {
  566. // Don't forward first time -- we had to 'Next' once in order to
  567. // do the sorting already
  568. fi.initiated = true
  569. return true
  570. }
  571. return fi.innerNext(0)
  572. }
  573. // innerNext handles the next operation internally,
  574. // and should be invoked when we know that two elements in the list may have
  575. // the same value.
  576. // For example, if the list becomes [2,3,5,5,8,9,10], then we should invoke
  577. // innerNext(3), which will call Next on elem 3 (the second '5'). It will continue
  578. // along the list and apply the same operation if needed
  579. func (fi *fastIterator) innerNext(pos int) bool {
  580. if !fi.iterators[pos].Next() {
  581. //Exhausted, remove this iterator
  582. fi.remove(pos)
  583. if len(fi.iterators) == 0 {
  584. return false
  585. }
  586. return true
  587. }
  588. if pos == len(fi.iterators)-1 {
  589. // Only one iterator left
  590. return true
  591. }
  592. // We next:ed the elem at 'pos'. Now we may have to re-sort that elem
  593. val, neighbour := fi.iterators[pos].Key(), fi.iterators[pos+1].Key()
  594. diff := bytes.Compare(val[:], neighbour[:])
  595. if diff < 0 {
  596. // It is still in correct place
  597. return true
  598. }
  599. if diff == 0 {
  600. // It has same value as the neighbour. So still in correct place, but
  601. // we need to iterate on the neighbour
  602. fi.innerNext(pos + 1)
  603. return true
  604. }
  605. // At this point, the elem is in the wrong location, but the
  606. // remaining list is sorted. Find out where to move the elem
  607. iterationNeeded := false
  608. index := sort.Search(len(fi.iterators), func(n int) bool {
  609. if n <= pos {
  610. // No need to search 'behind' us
  611. return false
  612. }
  613. if n == len(fi.iterators)-1 {
  614. // Can always place an elem last
  615. return true
  616. }
  617. neighbour := fi.iterators[n+1].Key()
  618. diff := bytes.Compare(val[:], neighbour[:])
  619. if diff == 0 {
  620. // The elem we're placing it next to has the same value,
  621. // so it's going to need further iteration
  622. iterationNeeded = true
  623. }
  624. return diff < 0
  625. })
  626. fi.move(pos, index)
  627. if iterationNeeded {
  628. fi.innerNext(index)
  629. }
  630. return true
  631. }
  632. // move moves an iterator to another position in the list
  633. func (fi *fastIterator) move(index, newpos int) {
  634. if newpos > len(fi.iterators)-1 {
  635. newpos = len(fi.iterators) - 1
  636. }
  637. var (
  638. elem = fi.iterators[index]
  639. middle = fi.iterators[index+1 : newpos+1]
  640. suffix []Iterator
  641. )
  642. if newpos < len(fi.iterators)-1 {
  643. suffix = fi.iterators[newpos+1:]
  644. }
  645. fi.iterators = append(fi.iterators[:index], middle...)
  646. fi.iterators = append(fi.iterators, elem)
  647. fi.iterators = append(fi.iterators, suffix...)
  648. }
  649. // remove drops an iterator from the list
  650. func (fi *fastIterator) remove(index int) {
  651. fi.iterators = append(fi.iterators[:index], fi.iterators[index+1:]...)
  652. }
  653. // Key returns the current key
  654. func (fi *fastIterator) Key() common.Hash {
  655. return fi.iterators[0].Key()
  656. }
  657. func (fi *fastIterator) Seek(key common.Hash) {
  658. // We need to apply this across all iterators
  659. var seen = make(map[common.Hash]struct{})
  660. length := len(fi.iterators)
  661. for i, it := range fi.iterators {
  662. it.Seek(key)
  663. for {
  664. if !it.Next() {
  665. // To be removed
  666. // swap it to the last position for now
  667. fi.iterators[i], fi.iterators[length-1] = fi.iterators[length-1], fi.iterators[i]
  668. length--
  669. break
  670. }
  671. v := it.Key()
  672. if _, exist := seen[v]; !exist {
  673. seen[v] = struct{}{}
  674. break
  675. }
  676. }
  677. }
  678. // Now remove those that were placed in the end
  679. fi.iterators = fi.iterators[:length]
  680. // The list is now totally unsorted, need to re-sort the entire list
  681. sort.Sort(fi)
  682. fi.initiated = false
  683. }
  684. // The fast iterator does not query parents as much.
  685. func (dl *diffLayer) newFastIterator() Iterator {
  686. f := &fastIterator{dl.iterators(), false}
  687. f.Seek(common.Hash{})
  688. return f
  689. }
  690. // Debug is a convencience helper during testing
  691. func (fi *fastIterator) Debug() {
  692. for _, it := range fi.iterators {
  693. fmt.Printf(" %v ", it.Key()[31])
  694. }
  695. fmt.Println()
  696. }