difflayer.go 18 KB

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