difflayer.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. "fmt"
  20. "math"
  21. "sort"
  22. "sync"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/rlp"
  27. "github.com/steakknife/bloomfilter"
  28. )
  29. var (
  30. // aggregatorMemoryLimit is the maximum size of the bottom-most diff layer
  31. // that aggregates the writes from above until it's flushed into the disk
  32. // layer.
  33. //
  34. // Note, bumping this up might drastically increase the size of the bloom
  35. // filters that's stored in every diff layer. Don't do that without fully
  36. // understanding all the implications.
  37. aggregatorMemoryLimit = uint64(4 * 1024 * 1024)
  38. // aggregatorItemLimit is an approximate number of items that will end up
  39. // in the agregator layer before it's flushed out to disk. A plain account
  40. // weighs around 14B (+hash), a storage slot 32B (+hash), so 50 is a very
  41. // rough average of what we might see.
  42. aggregatorItemLimit = aggregatorMemoryLimit / 55
  43. // bloomTargetError is the target false positive rate when the aggregator
  44. // layer is at its fullest. The actual value will probably move around up
  45. // and down from this number, it's mostly a ballpark figure.
  46. //
  47. // Note, dropping this down might drastically increase the size of the bloom
  48. // filters that's stored in every diff layer. Don't do that without fully
  49. // understanding all the implications.
  50. bloomTargetError = 0.02
  51. // bloomSize is the ideal bloom filter size given the maximum number of items
  52. // it's expected to hold and the target false positive error rate.
  53. bloomSize = math.Ceil(float64(aggregatorItemLimit) * math.Log(bloomTargetError) / math.Log(1/math.Pow(2, math.Log(2))))
  54. // bloomFuncs is the ideal number of bits a single entry should set in the
  55. // bloom filter to keep its size to a minimum (given it's size and maximum
  56. // entry count).
  57. bloomFuncs = math.Round((bloomSize / float64(aggregatorItemLimit)) * math.Log(2))
  58. )
  59. // diffLayer represents a collection of modifications made to a state snapshot
  60. // after running a block on top. It contains one sorted list for the account trie
  61. // and one-one list for each storage tries.
  62. //
  63. // The goal of a diff layer is to act as a journal, tracking recent modifications
  64. // made to the state, that have not yet graduated into a semi-immutable state.
  65. type diffLayer struct {
  66. origin *diskLayer // Base disk layer to directly use on bloom misses
  67. parent snapshot // Parent snapshot modified by this one, never nil
  68. memory uint64 // Approximate guess as to how much memory we use
  69. root common.Hash // Root hash to which this snapshot diff belongs to
  70. stale bool // Signals that the layer became stale (state progressed)
  71. accountList []common.Hash // List of account for iteration. If it exists, it's sorted, otherwise it's nil
  72. accountData map[common.Hash][]byte // Keyed accounts for direct retrival (nil means deleted)
  73. storageList map[common.Hash][]common.Hash // List of storage slots for iterated retrievals, one per account. Any existing lists are sorted if non-nil
  74. storageData map[common.Hash]map[common.Hash][]byte // Keyed storage slots for direct retrival. one per account (nil means deleted)
  75. diffed *bloomfilter.Filter // Bloom filter tracking all the diffed items up to the disk layer
  76. lock sync.RWMutex
  77. }
  78. // accountBloomHasher is a wrapper around a common.Hash to satisfy the interface
  79. // API requirements of the bloom library used. It's used to convert an account
  80. // hash into a 64 bit mini hash.
  81. type accountBloomHasher common.Hash
  82. func (h accountBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") }
  83. func (h accountBloomHasher) Sum(b []byte) []byte { panic("not implemented") }
  84. func (h accountBloomHasher) Reset() { panic("not implemented") }
  85. func (h accountBloomHasher) BlockSize() int { panic("not implemented") }
  86. func (h accountBloomHasher) Size() int { return 8 }
  87. func (h accountBloomHasher) Sum64() uint64 {
  88. return binary.BigEndian.Uint64(h[:8])
  89. }
  90. // storageBloomHasher is a wrapper around a [2]common.Hash to satisfy the interface
  91. // API requirements of the bloom library used. It's used to convert an account
  92. // hash into a 64 bit mini hash.
  93. type storageBloomHasher [2]common.Hash
  94. func (h storageBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") }
  95. func (h storageBloomHasher) Sum(b []byte) []byte { panic("not implemented") }
  96. func (h storageBloomHasher) Reset() { panic("not implemented") }
  97. func (h storageBloomHasher) BlockSize() int { panic("not implemented") }
  98. func (h storageBloomHasher) Size() int { return 8 }
  99. func (h storageBloomHasher) Sum64() uint64 {
  100. return binary.BigEndian.Uint64(h[0][:8]) ^ binary.BigEndian.Uint64(h[1][:8])
  101. }
  102. // newDiffLayer creates a new diff on top of an existing snapshot, whether that's a low
  103. // level persistent database or a hierarchical diff already.
  104. func newDiffLayer(parent snapshot, root common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
  105. // Create the new layer with some pre-allocated data segments
  106. dl := &diffLayer{
  107. parent: parent,
  108. root: root,
  109. accountData: accounts,
  110. storageData: storage,
  111. }
  112. switch parent := parent.(type) {
  113. case *diskLayer:
  114. dl.rebloom(parent)
  115. case *diffLayer:
  116. dl.rebloom(parent.origin)
  117. default:
  118. panic("unknown parent type")
  119. }
  120. // Determine memory size and track the dirty writes
  121. for _, data := range accounts {
  122. dl.memory += uint64(common.HashLength + len(data))
  123. snapshotDirtyAccountWriteMeter.Mark(int64(len(data)))
  124. }
  125. // Fill the storage hashes and sort them for the iterator
  126. dl.storageList = make(map[common.Hash][]common.Hash)
  127. for accountHash, slots := range storage {
  128. // If the slots are nil, sanity check that it's a deleted account
  129. if slots == nil {
  130. // Ensure that the account was just marked as deleted
  131. if account, ok := accounts[accountHash]; account != nil || !ok {
  132. panic(fmt.Sprintf("storage in %#x nil, but account conflicts (%#x, exists: %v)", accountHash, account, ok))
  133. }
  134. // Everything ok, store the deletion mark and continue
  135. dl.storageList[accountHash] = nil
  136. continue
  137. }
  138. // Storage slots are not nil so entire contract was not deleted, ensure the
  139. // account was just updated.
  140. if account, ok := accounts[accountHash]; account == nil || !ok {
  141. log.Error(fmt.Sprintf("storage in %#x exists, but account nil (exists: %v)", accountHash, ok))
  142. }
  143. // Determine memory size and track the dirty writes
  144. for _, data := range slots {
  145. dl.memory += uint64(common.HashLength + len(data))
  146. snapshotDirtyStorageWriteMeter.Mark(int64(len(data)))
  147. }
  148. }
  149. dl.memory += uint64(len(dl.storageList) * common.HashLength)
  150. return dl
  151. }
  152. // rebloom discards the layer's current bloom and rebuilds it from scratch based
  153. // on the parent's and the local diffs.
  154. func (dl *diffLayer) rebloom(origin *diskLayer) {
  155. dl.lock.Lock()
  156. defer dl.lock.Unlock()
  157. defer func(start time.Time) {
  158. snapshotBloomIndexTimer.Update(time.Since(start))
  159. }(time.Now())
  160. // Inject the new origin that triggered the rebloom
  161. dl.origin = origin
  162. // Retrieve the parent bloom or create a fresh empty one
  163. if parent, ok := dl.parent.(*diffLayer); ok {
  164. parent.lock.RLock()
  165. dl.diffed, _ = parent.diffed.Copy()
  166. parent.lock.RUnlock()
  167. } else {
  168. dl.diffed, _ = bloomfilter.New(uint64(bloomSize), uint64(bloomFuncs))
  169. }
  170. // Iterate over all the accounts and storage slots and index them
  171. for hash := range dl.accountData {
  172. dl.diffed.Add(accountBloomHasher(hash))
  173. }
  174. for accountHash, slots := range dl.storageData {
  175. for storageHash := range slots {
  176. dl.diffed.Add(storageBloomHasher{accountHash, storageHash})
  177. }
  178. }
  179. // Calculate the current false positive rate and update the error rate meter.
  180. // This is a bit cheating because subsequent layers will overwrite it, but it
  181. // should be fine, we're only interested in ballpark figures.
  182. k := float64(dl.diffed.K())
  183. n := float64(dl.diffed.N())
  184. m := float64(dl.diffed.M())
  185. snapshotBloomErrorGauge.Update(math.Pow(1.0-math.Exp((-k)*(n+0.5)/(m-1)), k))
  186. }
  187. // Root returns the root hash for which this snapshot was made.
  188. func (dl *diffLayer) Root() common.Hash {
  189. return dl.root
  190. }
  191. // Stale return whether this layer has become stale (was flattened across) or if
  192. // it's still live.
  193. func (dl *diffLayer) Stale() bool {
  194. dl.lock.RLock()
  195. defer dl.lock.RUnlock()
  196. return dl.stale
  197. }
  198. // Account directly retrieves the account associated with a particular hash in
  199. // the snapshot slim data format.
  200. func (dl *diffLayer) Account(hash common.Hash) (*Account, error) {
  201. data, err := dl.AccountRLP(hash)
  202. if err != nil {
  203. return nil, err
  204. }
  205. if len(data) == 0 { // can be both nil and []byte{}
  206. return nil, nil
  207. }
  208. account := new(Account)
  209. if err := rlp.DecodeBytes(data, account); err != nil {
  210. panic(err)
  211. }
  212. return account, nil
  213. }
  214. // AccountRLP directly retrieves the account RLP associated with a particular
  215. // hash in the snapshot slim data format.
  216. func (dl *diffLayer) AccountRLP(hash common.Hash) ([]byte, error) {
  217. // Check the bloom filter first whether there's even a point in reaching into
  218. // all the maps in all the layers below
  219. dl.lock.RLock()
  220. hit := dl.diffed.Contains(accountBloomHasher(hash))
  221. dl.lock.RUnlock()
  222. // If the bloom filter misses, don't even bother with traversing the memory
  223. // diff layers, reach straight into the bottom persistent disk layer
  224. if !hit {
  225. snapshotBloomAccountMissMeter.Mark(1)
  226. return dl.origin.AccountRLP(hash)
  227. }
  228. // The bloom filter hit, start poking in the internal maps
  229. return dl.accountRLP(hash)
  230. }
  231. // accountRLP is an internal version of AccountRLP that skips the bloom filter
  232. // checks and uses the internal maps to try and retrieve the data. It's meant
  233. // to be used if a higher layer's bloom filter hit already.
  234. func (dl *diffLayer) accountRLP(hash common.Hash) ([]byte, error) {
  235. dl.lock.RLock()
  236. defer dl.lock.RUnlock()
  237. // If the layer was flattened into, consider it invalid (any live reference to
  238. // the original should be marked as unusable).
  239. if dl.stale {
  240. return nil, ErrSnapshotStale
  241. }
  242. // If the account is known locally, return it. Note, a nil account means it was
  243. // deleted, and is a different notion than an unknown account!
  244. if data, ok := dl.accountData[hash]; ok {
  245. snapshotDirtyAccountHitMeter.Mark(1)
  246. snapshotDirtyAccountReadMeter.Mark(int64(len(data)))
  247. snapshotBloomAccountTrueHitMeter.Mark(1)
  248. return data, nil
  249. }
  250. // Account unknown to this diff, resolve from parent
  251. if diff, ok := dl.parent.(*diffLayer); ok {
  252. return diff.accountRLP(hash)
  253. }
  254. // Failed to resolve through diff layers, mark a bloom error and use the disk
  255. snapshotBloomAccountFalseHitMeter.Mark(1)
  256. return dl.parent.AccountRLP(hash)
  257. }
  258. // Storage directly retrieves the storage data associated with a particular hash,
  259. // within a particular account. If the slot is unknown to this diff, it's parent
  260. // is consulted.
  261. func (dl *diffLayer) Storage(accountHash, storageHash common.Hash) ([]byte, error) {
  262. // Check the bloom filter first whether there's even a point in reaching into
  263. // all the maps in all the layers below
  264. dl.lock.RLock()
  265. hit := dl.diffed.Contains(storageBloomHasher{accountHash, storageHash})
  266. dl.lock.RUnlock()
  267. // If the bloom filter misses, don't even bother with traversing the memory
  268. // diff layers, reach straight into the bottom persistent disk layer
  269. if !hit {
  270. snapshotBloomStorageMissMeter.Mark(1)
  271. return dl.origin.Storage(accountHash, storageHash)
  272. }
  273. // The bloom filter hit, start poking in the internal maps
  274. return dl.storage(accountHash, storageHash)
  275. }
  276. // storage is an internal version of Storage that skips the bloom filter checks
  277. // and uses the internal maps to try and retrieve the data. It's meant to be
  278. // used if a higher layer's bloom filter hit already.
  279. func (dl *diffLayer) storage(accountHash, storageHash common.Hash) ([]byte, error) {
  280. dl.lock.RLock()
  281. defer dl.lock.RUnlock()
  282. // If the layer was flattened into, consider it invalid (any live reference to
  283. // the original should be marked as unusable).
  284. if dl.stale {
  285. return nil, ErrSnapshotStale
  286. }
  287. // If the account is known locally, try to resolve the slot locally. Note, a nil
  288. // account means it was deleted, and is a different notion than an unknown account!
  289. if storage, ok := dl.storageData[accountHash]; ok {
  290. if storage == nil {
  291. snapshotDirtyStorageHitMeter.Mark(1)
  292. snapshotBloomStorageTrueHitMeter.Mark(1)
  293. return nil, nil
  294. }
  295. if data, ok := storage[storageHash]; ok {
  296. snapshotDirtyStorageHitMeter.Mark(1)
  297. snapshotDirtyStorageReadMeter.Mark(int64(len(data)))
  298. snapshotBloomStorageTrueHitMeter.Mark(1)
  299. return data, nil
  300. }
  301. }
  302. // Storage slot unknown to this diff, resolve from parent
  303. if diff, ok := dl.parent.(*diffLayer); ok {
  304. return diff.storage(accountHash, storageHash)
  305. }
  306. // Failed to resolve through diff layers, mark a bloom error and use the disk
  307. snapshotBloomStorageFalseHitMeter.Mark(1)
  308. return dl.parent.Storage(accountHash, storageHash)
  309. }
  310. // Update creates a new layer on top of the existing snapshot diff tree with
  311. // the specified data items.
  312. func (dl *diffLayer) Update(blockRoot common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
  313. return newDiffLayer(dl, blockRoot, accounts, storage)
  314. }
  315. // flatten pushes all data from this point downwards, flattening everything into
  316. // a single diff at the bottom. Since usually the lowermost diff is the largest,
  317. // the flattening bulds up from there in reverse.
  318. func (dl *diffLayer) flatten() snapshot {
  319. // If the parent is not diff, we're the first in line, return unmodified
  320. parent, ok := dl.parent.(*diffLayer)
  321. if !ok {
  322. return dl
  323. }
  324. // Parent is a diff, flatten it first (note, apart from weird corned cases,
  325. // flatten will realistically only ever merge 1 layer, so there's no need to
  326. // be smarter about grouping flattens together).
  327. parent = parent.flatten().(*diffLayer)
  328. parent.lock.Lock()
  329. defer parent.lock.Unlock()
  330. // Before actually writing all our data to the parent, first ensure that the
  331. // parent hasn't been 'corrupted' by someone else already flattening into it
  332. if parent.stale {
  333. panic("parent diff layer is stale") // we've flattened into the same parent from two children, boo
  334. }
  335. parent.stale = true
  336. // Overwrite all the updated accounts blindly, merge the sorted list
  337. for hash, data := range dl.accountData {
  338. parent.accountData[hash] = data
  339. }
  340. // Overwrite all the updates storage slots (individually)
  341. for accountHash, storage := range dl.storageData {
  342. // If storage didn't exist (or was deleted) in the parent; or if the storage
  343. // was freshly deleted in the child, overwrite blindly
  344. if parent.storageData[accountHash] == nil || storage == nil {
  345. parent.storageData[accountHash] = storage
  346. continue
  347. }
  348. // Storage exists in both parent and child, merge the slots
  349. comboData := parent.storageData[accountHash]
  350. for storageHash, data := range storage {
  351. comboData[storageHash] = data
  352. }
  353. parent.storageData[accountHash] = comboData
  354. }
  355. // Return the combo parent
  356. return &diffLayer{
  357. parent: parent.parent,
  358. origin: parent.origin,
  359. root: dl.root,
  360. storageList: parent.storageList,
  361. storageData: parent.storageData,
  362. accountList: parent.accountList,
  363. accountData: parent.accountData,
  364. diffed: dl.diffed,
  365. memory: parent.memory + dl.memory,
  366. }
  367. }
  368. // AccountList returns a sorted list of all accounts in this difflayer.
  369. func (dl *diffLayer) AccountList() []common.Hash {
  370. dl.lock.Lock()
  371. defer dl.lock.Unlock()
  372. if dl.accountList != nil {
  373. return dl.accountList
  374. }
  375. accountList := make([]common.Hash, len(dl.accountData))
  376. i := 0
  377. for k, _ := range dl.accountData {
  378. accountList[i] = k
  379. i++
  380. // This would be a pretty good opportunity to also
  381. // calculate the size, if we want to
  382. }
  383. sort.Sort(hashes(accountList))
  384. dl.accountList = accountList
  385. return dl.accountList
  386. }
  387. // StorageList returns a sorted list of all storage slot hashes
  388. // in this difflayer for the given account.
  389. func (dl *diffLayer) StorageList(accountHash common.Hash) []common.Hash {
  390. dl.lock.Lock()
  391. defer dl.lock.Unlock()
  392. if dl.storageList[accountHash] != nil {
  393. return dl.storageList[accountHash]
  394. }
  395. accountStorageMap := dl.storageData[accountHash]
  396. accountStorageList := make([]common.Hash, len(accountStorageMap))
  397. i := 0
  398. for k, _ := range accountStorageMap {
  399. accountStorageList[i] = k
  400. i++
  401. // This would be a pretty good opportunity to also
  402. // calculate the size, if we want to
  403. }
  404. sort.Sort(hashes(accountStorageList))
  405. dl.storageList[accountHash] = accountStorageList
  406. return accountStorageList
  407. }