github.com/theQRL/go-zond@v0.1.1/core/state/snapshot/difflayer.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 "encoding/binary" 21 "fmt" 22 "math" 23 "math/rand" 24 "sync" 25 "sync/atomic" 26 "time" 27 28 bloomfilter "github.com/holiman/bloomfilter/v2" 29 "github.com/theQRL/go-zond/common" 30 "github.com/theQRL/go-zond/core/types" 31 "github.com/theQRL/go-zond/rlp" 32 "golang.org/x/exp/slices" 33 ) 34 35 var ( 36 // aggregatorMemoryLimit is the maximum size of the bottom-most diff layer 37 // that aggregates the writes from above until it's flushed into the disk 38 // layer. 39 // 40 // Note, bumping this up might drastically increase the size of the bloom 41 // filters that's stored in every diff layer. Don't do that without fully 42 // understanding all the implications. 43 aggregatorMemoryLimit = uint64(4 * 1024 * 1024) 44 45 // aggregatorItemLimit is an approximate number of items that will end up 46 // in the agregator layer before it's flushed out to disk. A plain account 47 // weighs around 14B (+hash), a storage slot 32B (+hash), a deleted slot 48 // 0B (+hash). Slots are mostly set/unset in lockstep, so that average at 49 // 16B (+hash). All in all, the average entry seems to be 15+32=47B. Use a 50 // smaller number to be on the safe side. 51 aggregatorItemLimit = aggregatorMemoryLimit / 42 52 53 // bloomTargetError is the target false positive rate when the aggregator 54 // layer is at its fullest. The actual value will probably move around up 55 // and down from this number, it's mostly a ballpark figure. 56 // 57 // Note, dropping this down might drastically increase the size of the bloom 58 // filters that's stored in every diff layer. Don't do that without fully 59 // understanding all the implications. 60 bloomTargetError = 0.02 61 62 // bloomSize is the ideal bloom filter size given the maximum number of items 63 // it's expected to hold and the target false positive error rate. 64 bloomSize = math.Ceil(float64(aggregatorItemLimit) * math.Log(bloomTargetError) / math.Log(1/math.Pow(2, math.Log(2)))) 65 66 // bloomFuncs is the ideal number of bits a single entry should set in the 67 // bloom filter to keep its size to a minimum (given it's size and maximum 68 // entry count). 69 bloomFuncs = math.Round((bloomSize / float64(aggregatorItemLimit)) * math.Log(2)) 70 71 // the bloom offsets are runtime constants which determines which part of the 72 // account/storage hash the hasher functions looks at, to determine the 73 // bloom key for an account/slot. This is randomized at init(), so that the 74 // global population of nodes do not all display the exact same behaviour with 75 // regards to bloom content 76 bloomDestructHasherOffset = 0 77 bloomAccountHasherOffset = 0 78 bloomStorageHasherOffset = 0 79 ) 80 81 func init() { 82 // Init the bloom offsets in the range [0:24] (requires 8 bytes) 83 bloomDestructHasherOffset = rand.Intn(25) 84 bloomAccountHasherOffset = rand.Intn(25) 85 bloomStorageHasherOffset = rand.Intn(25) 86 87 // The destruct and account blooms must be different, as the storage slots 88 // will check for destruction too for every bloom miss. It should not collide 89 // with modified accounts. 90 for bloomAccountHasherOffset == bloomDestructHasherOffset { 91 bloomAccountHasherOffset = rand.Intn(25) 92 } 93 } 94 95 // diffLayer represents a collection of modifications made to a state snapshot 96 // after running a block on top. It contains one sorted list for the account trie 97 // and one-one list for each storage tries. 98 // 99 // The goal of a diff layer is to act as a journal, tracking recent modifications 100 // made to the state, that have not yet graduated into a semi-immutable state. 101 type diffLayer struct { 102 origin *diskLayer // Base disk layer to directly use on bloom misses 103 parent snapshot // Parent snapshot modified by this one, never nil 104 memory uint64 // Approximate guess as to how much memory we use 105 106 root common.Hash // Root hash to which this snapshot diff belongs to 107 stale atomic.Bool // Signals that the layer became stale (state progressed) 108 109 // destructSet is a very special helper marker. If an account is marked as 110 // deleted, then it's recorded in this set. However it's allowed that an account 111 // is included here but still available in other sets(e.g. storageData). The 112 // reason is the diff layer includes all the changes in a *block*. It can 113 // happen that in the tx_1, account A is self-destructed while in the tx_2 114 // it's recreated. But we still need this marker to indicate the "old" A is 115 // deleted, all data in other set belongs to the "new" A. 116 destructSet map[common.Hash]struct{} // Keyed markers for deleted (and potentially) recreated accounts 117 accountList []common.Hash // List of account for iteration. If it exists, it's sorted, otherwise it's nil 118 accountData map[common.Hash][]byte // Keyed accounts for direct retrieval (nil means deleted) 119 storageList map[common.Hash][]common.Hash // List of storage slots for iterated retrievals, one per account. Any existing lists are sorted if non-nil 120 storageData map[common.Hash]map[common.Hash][]byte // Keyed storage slots for direct retrieval. one per account (nil means deleted) 121 122 diffed *bloomfilter.Filter // Bloom filter tracking all the diffed items up to the disk layer 123 124 lock sync.RWMutex 125 } 126 127 // destructBloomHasher is a wrapper around a common.Hash to satisfy the interface 128 // API requirements of the bloom library used. It's used to convert a destruct 129 // event into a 64 bit mini hash. 130 type destructBloomHasher common.Hash 131 132 func (h destructBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") } 133 func (h destructBloomHasher) Sum(b []byte) []byte { panic("not implemented") } 134 func (h destructBloomHasher) Reset() { panic("not implemented") } 135 func (h destructBloomHasher) BlockSize() int { panic("not implemented") } 136 func (h destructBloomHasher) Size() int { return 8 } 137 func (h destructBloomHasher) Sum64() uint64 { 138 return binary.BigEndian.Uint64(h[bloomDestructHasherOffset : bloomDestructHasherOffset+8]) 139 } 140 141 // accountBloomHasher is a wrapper around a common.Hash to satisfy the interface 142 // API requirements of the bloom library used. It's used to convert an account 143 // hash into a 64 bit mini hash. 144 type accountBloomHasher common.Hash 145 146 func (h accountBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") } 147 func (h accountBloomHasher) Sum(b []byte) []byte { panic("not implemented") } 148 func (h accountBloomHasher) Reset() { panic("not implemented") } 149 func (h accountBloomHasher) BlockSize() int { panic("not implemented") } 150 func (h accountBloomHasher) Size() int { return 8 } 151 func (h accountBloomHasher) Sum64() uint64 { 152 return binary.BigEndian.Uint64(h[bloomAccountHasherOffset : bloomAccountHasherOffset+8]) 153 } 154 155 // storageBloomHasher is a wrapper around a [2]common.Hash to satisfy the interface 156 // API requirements of the bloom library used. It's used to convert an account 157 // hash into a 64 bit mini hash. 158 type storageBloomHasher [2]common.Hash 159 160 func (h storageBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") } 161 func (h storageBloomHasher) Sum(b []byte) []byte { panic("not implemented") } 162 func (h storageBloomHasher) Reset() { panic("not implemented") } 163 func (h storageBloomHasher) BlockSize() int { panic("not implemented") } 164 func (h storageBloomHasher) Size() int { return 8 } 165 func (h storageBloomHasher) Sum64() uint64 { 166 return binary.BigEndian.Uint64(h[0][bloomStorageHasherOffset:bloomStorageHasherOffset+8]) ^ 167 binary.BigEndian.Uint64(h[1][bloomStorageHasherOffset:bloomStorageHasherOffset+8]) 168 } 169 170 // newDiffLayer creates a new diff on top of an existing snapshot, whether that's a low 171 // level persistent database or a hierarchical diff already. 172 func newDiffLayer(parent snapshot, root common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer { 173 // Create the new layer with some pre-allocated data segments 174 dl := &diffLayer{ 175 parent: parent, 176 root: root, 177 destructSet: destructs, 178 accountData: accounts, 179 storageData: storage, 180 storageList: make(map[common.Hash][]common.Hash), 181 } 182 switch parent := parent.(type) { 183 case *diskLayer: 184 dl.rebloom(parent) 185 case *diffLayer: 186 dl.rebloom(parent.origin) 187 default: 188 panic("unknown parent type") 189 } 190 // Sanity check that accounts or storage slots are never nil 191 for accountHash, blob := range accounts { 192 if blob == nil { 193 panic(fmt.Sprintf("account %#x nil", accountHash)) 194 } 195 // Determine memory size and track the dirty writes 196 dl.memory += uint64(common.HashLength + len(blob)) 197 snapshotDirtyAccountWriteMeter.Mark(int64(len(blob))) 198 } 199 for accountHash, slots := range storage { 200 if slots == nil { 201 panic(fmt.Sprintf("storage %#x nil", accountHash)) 202 } 203 // Determine memory size and track the dirty writes 204 for _, data := range slots { 205 dl.memory += uint64(common.HashLength + len(data)) 206 snapshotDirtyStorageWriteMeter.Mark(int64(len(data))) 207 } 208 } 209 dl.memory += uint64(len(destructs) * common.HashLength) 210 return dl 211 } 212 213 // rebloom discards the layer's current bloom and rebuilds it from scratch based 214 // on the parent's and the local diffs. 215 func (dl *diffLayer) rebloom(origin *diskLayer) { 216 dl.lock.Lock() 217 defer dl.lock.Unlock() 218 219 defer func(start time.Time) { 220 snapshotBloomIndexTimer.Update(time.Since(start)) 221 }(time.Now()) 222 223 // Inject the new origin that triggered the rebloom 224 dl.origin = origin 225 226 // Retrieve the parent bloom or create a fresh empty one 227 if parent, ok := dl.parent.(*diffLayer); ok { 228 parent.lock.RLock() 229 dl.diffed, _ = parent.diffed.Copy() 230 parent.lock.RUnlock() 231 } else { 232 dl.diffed, _ = bloomfilter.New(uint64(bloomSize), uint64(bloomFuncs)) 233 } 234 // Iterate over all the accounts and storage slots and index them 235 for hash := range dl.destructSet { 236 dl.diffed.Add(destructBloomHasher(hash)) 237 } 238 for hash := range dl.accountData { 239 dl.diffed.Add(accountBloomHasher(hash)) 240 } 241 for accountHash, slots := range dl.storageData { 242 for storageHash := range slots { 243 dl.diffed.Add(storageBloomHasher{accountHash, storageHash}) 244 } 245 } 246 // Calculate the current false positive rate and update the error rate meter. 247 // This is a bit cheating because subsequent layers will overwrite it, but it 248 // should be fine, we're only interested in ballpark figures. 249 k := float64(dl.diffed.K()) 250 n := float64(dl.diffed.N()) 251 m := float64(dl.diffed.M()) 252 snapshotBloomErrorGauge.Update(math.Pow(1.0-math.Exp((-k)*(n+0.5)/(m-1)), k)) 253 } 254 255 // Root returns the root hash for which this snapshot was made. 256 func (dl *diffLayer) Root() common.Hash { 257 return dl.root 258 } 259 260 // Parent returns the subsequent layer of a diff layer. 261 func (dl *diffLayer) Parent() snapshot { 262 dl.lock.RLock() 263 defer dl.lock.RUnlock() 264 265 return dl.parent 266 } 267 268 // Stale return whether this layer has become stale (was flattened across) or if 269 // it's still live. 270 func (dl *diffLayer) Stale() bool { 271 return dl.stale.Load() 272 } 273 274 // Account directly retrieves the account associated with a particular hash in 275 // the snapshot slim data format. 276 func (dl *diffLayer) Account(hash common.Hash) (*types.SlimAccount, error) { 277 data, err := dl.AccountRLP(hash) 278 if err != nil { 279 return nil, err 280 } 281 if len(data) == 0 { // can be both nil and []byte{} 282 return nil, nil 283 } 284 account := new(types.SlimAccount) 285 if err := rlp.DecodeBytes(data, account); err != nil { 286 panic(err) 287 } 288 return account, nil 289 } 290 291 // AccountRLP directly retrieves the account RLP associated with a particular 292 // hash in the snapshot slim data format. 293 // 294 // Note the returned account is not a copy, please don't modify it. 295 func (dl *diffLayer) AccountRLP(hash common.Hash) ([]byte, error) { 296 // Check staleness before reaching further. 297 dl.lock.RLock() 298 if dl.Stale() { 299 dl.lock.RUnlock() 300 return nil, ErrSnapshotStale 301 } 302 // Check the bloom filter first whether there's even a point in reaching into 303 // all the maps in all the layers below 304 hit := dl.diffed.Contains(accountBloomHasher(hash)) 305 if !hit { 306 hit = dl.diffed.Contains(destructBloomHasher(hash)) 307 } 308 var origin *diskLayer 309 if !hit { 310 origin = dl.origin // extract origin while holding the lock 311 } 312 dl.lock.RUnlock() 313 314 // If the bloom filter misses, don't even bother with traversing the memory 315 // diff layers, reach straight into the bottom persistent disk layer 316 if origin != nil { 317 snapshotBloomAccountMissMeter.Mark(1) 318 return origin.AccountRLP(hash) 319 } 320 // The bloom filter hit, start poking in the internal maps 321 return dl.accountRLP(hash, 0) 322 } 323 324 // accountRLP is an internal version of AccountRLP that skips the bloom filter 325 // checks and uses the internal maps to try and retrieve the data. It's meant 326 // to be used if a higher layer's bloom filter hit already. 327 func (dl *diffLayer) accountRLP(hash common.Hash, depth int) ([]byte, error) { 328 dl.lock.RLock() 329 defer dl.lock.RUnlock() 330 331 // If the layer was flattened into, consider it invalid (any live reference to 332 // the original should be marked as unusable). 333 if dl.Stale() { 334 return nil, ErrSnapshotStale 335 } 336 // If the account is known locally, return it 337 if data, ok := dl.accountData[hash]; ok { 338 snapshotDirtyAccountHitMeter.Mark(1) 339 snapshotDirtyAccountHitDepthHist.Update(int64(depth)) 340 snapshotDirtyAccountReadMeter.Mark(int64(len(data))) 341 snapshotBloomAccountTrueHitMeter.Mark(1) 342 return data, nil 343 } 344 // If the account is known locally, but deleted, return it 345 if _, ok := dl.destructSet[hash]; ok { 346 snapshotDirtyAccountHitMeter.Mark(1) 347 snapshotDirtyAccountHitDepthHist.Update(int64(depth)) 348 snapshotDirtyAccountInexMeter.Mark(1) 349 snapshotBloomAccountTrueHitMeter.Mark(1) 350 return nil, nil 351 } 352 // Account unknown to this diff, resolve from parent 353 if diff, ok := dl.parent.(*diffLayer); ok { 354 return diff.accountRLP(hash, depth+1) 355 } 356 // Failed to resolve through diff layers, mark a bloom error and use the disk 357 snapshotBloomAccountFalseHitMeter.Mark(1) 358 return dl.parent.AccountRLP(hash) 359 } 360 361 // Storage directly retrieves the storage data associated with a particular hash, 362 // within a particular account. If the slot is unknown to this diff, it's parent 363 // is consulted. 364 // 365 // Note the returned slot is not a copy, please don't modify it. 366 func (dl *diffLayer) Storage(accountHash, storageHash common.Hash) ([]byte, error) { 367 // Check the bloom filter first whether there's even a point in reaching into 368 // all the maps in all the layers below 369 dl.lock.RLock() 370 // Check staleness before reaching further. 371 if dl.Stale() { 372 dl.lock.RUnlock() 373 return nil, ErrSnapshotStale 374 } 375 hit := dl.diffed.Contains(storageBloomHasher{accountHash, storageHash}) 376 if !hit { 377 hit = dl.diffed.Contains(destructBloomHasher(accountHash)) 378 } 379 var origin *diskLayer 380 if !hit { 381 origin = dl.origin // extract origin while holding the lock 382 } 383 dl.lock.RUnlock() 384 385 // If the bloom filter misses, don't even bother with traversing the memory 386 // diff layers, reach straight into the bottom persistent disk layer 387 if origin != nil { 388 snapshotBloomStorageMissMeter.Mark(1) 389 return origin.Storage(accountHash, storageHash) 390 } 391 // The bloom filter hit, start poking in the internal maps 392 return dl.storage(accountHash, storageHash, 0) 393 } 394 395 // storage is an internal version of Storage that skips the bloom filter checks 396 // and uses the internal maps to try and retrieve the data. It's meant to be 397 // used if a higher layer's bloom filter hit already. 398 func (dl *diffLayer) storage(accountHash, storageHash common.Hash, depth int) ([]byte, error) { 399 dl.lock.RLock() 400 defer dl.lock.RUnlock() 401 402 // If the layer was flattened into, consider it invalid (any live reference to 403 // the original should be marked as unusable). 404 if dl.Stale() { 405 return nil, ErrSnapshotStale 406 } 407 // If the account is known locally, try to resolve the slot locally 408 if storage, ok := dl.storageData[accountHash]; ok { 409 if data, ok := storage[storageHash]; ok { 410 snapshotDirtyStorageHitMeter.Mark(1) 411 snapshotDirtyStorageHitDepthHist.Update(int64(depth)) 412 if n := len(data); n > 0 { 413 snapshotDirtyStorageReadMeter.Mark(int64(n)) 414 } else { 415 snapshotDirtyStorageInexMeter.Mark(1) 416 } 417 snapshotBloomStorageTrueHitMeter.Mark(1) 418 return data, nil 419 } 420 } 421 // If the account is known locally, but deleted, return an empty slot 422 if _, ok := dl.destructSet[accountHash]; ok { 423 snapshotDirtyStorageHitMeter.Mark(1) 424 snapshotDirtyStorageHitDepthHist.Update(int64(depth)) 425 snapshotDirtyStorageInexMeter.Mark(1) 426 snapshotBloomStorageTrueHitMeter.Mark(1) 427 return nil, nil 428 } 429 // Storage slot unknown to this diff, resolve from parent 430 if diff, ok := dl.parent.(*diffLayer); ok { 431 return diff.storage(accountHash, storageHash, depth+1) 432 } 433 // Failed to resolve through diff layers, mark a bloom error and use the disk 434 snapshotBloomStorageFalseHitMeter.Mark(1) 435 return dl.parent.Storage(accountHash, storageHash) 436 } 437 438 // Update creates a new layer on top of the existing snapshot diff tree with 439 // the specified data items. 440 func (dl *diffLayer) Update(blockRoot common.Hash, destructs map[common.Hash]struct{}, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer { 441 return newDiffLayer(dl, blockRoot, destructs, accounts, storage) 442 } 443 444 // flatten pushes all data from this point downwards, flattening everything into 445 // a single diff at the bottom. Since usually the lowermost diff is the largest, 446 // the flattening builds up from there in reverse. 447 func (dl *diffLayer) flatten() snapshot { 448 // If the parent is not diff, we're the first in line, return unmodified 449 parent, ok := dl.parent.(*diffLayer) 450 if !ok { 451 return dl 452 } 453 // Parent is a diff, flatten it first (note, apart from weird corned cases, 454 // flatten will realistically only ever merge 1 layer, so there's no need to 455 // be smarter about grouping flattens together). 456 parent = parent.flatten().(*diffLayer) 457 458 parent.lock.Lock() 459 defer parent.lock.Unlock() 460 461 // Before actually writing all our data to the parent, first ensure that the 462 // parent hasn't been 'corrupted' by someone else already flattening into it 463 if parent.stale.Swap(true) { 464 panic("parent diff layer is stale") // we've flattened into the same parent from two children, boo 465 } 466 // Overwrite all the updated accounts blindly, merge the sorted list 467 for hash := range dl.destructSet { 468 parent.destructSet[hash] = struct{}{} 469 delete(parent.accountData, hash) 470 delete(parent.storageData, hash) 471 } 472 for hash, data := range dl.accountData { 473 parent.accountData[hash] = data 474 } 475 // Overwrite all the updated storage slots (individually) 476 for accountHash, storage := range dl.storageData { 477 // If storage didn't exist (or was deleted) in the parent, overwrite blindly 478 if _, ok := parent.storageData[accountHash]; !ok { 479 parent.storageData[accountHash] = storage 480 continue 481 } 482 // Storage exists in both parent and child, merge the slots 483 comboData := parent.storageData[accountHash] 484 for storageHash, data := range storage { 485 comboData[storageHash] = data 486 } 487 } 488 // Return the combo parent 489 return &diffLayer{ 490 parent: parent.parent, 491 origin: parent.origin, 492 root: dl.root, 493 destructSet: parent.destructSet, 494 accountData: parent.accountData, 495 storageData: parent.storageData, 496 storageList: make(map[common.Hash][]common.Hash), 497 diffed: dl.diffed, 498 memory: parent.memory + dl.memory, 499 } 500 } 501 502 // AccountList returns a sorted list of all accounts in this diffLayer, including 503 // the deleted ones. 504 // 505 // Note, the returned slice is not a copy, so do not modify it. 506 func (dl *diffLayer) AccountList() []common.Hash { 507 // If an old list already exists, return it 508 dl.lock.RLock() 509 list := dl.accountList 510 dl.lock.RUnlock() 511 512 if list != nil { 513 return list 514 } 515 // No old sorted account list exists, generate a new one 516 dl.lock.Lock() 517 defer dl.lock.Unlock() 518 519 dl.accountList = make([]common.Hash, 0, len(dl.destructSet)+len(dl.accountData)) 520 for hash := range dl.accountData { 521 dl.accountList = append(dl.accountList, hash) 522 } 523 for hash := range dl.destructSet { 524 if _, ok := dl.accountData[hash]; !ok { 525 dl.accountList = append(dl.accountList, hash) 526 } 527 } 528 slices.SortFunc(dl.accountList, common.Hash.Cmp) 529 dl.memory += uint64(len(dl.accountList) * common.HashLength) 530 return dl.accountList 531 } 532 533 // StorageList returns a sorted list of all storage slot hashes in this diffLayer 534 // for the given account. If the whole storage is destructed in this layer, then 535 // an additional flag *destructed = true* will be returned, otherwise the flag is 536 // false. Besides, the returned list will include the hash of deleted storage slot. 537 // Note a special case is an account is deleted in a prior tx but is recreated in 538 // the following tx with some storage slots set. In this case the returned list is 539 // not empty but the flag is true. 540 // 541 // Note, the returned slice is not a copy, so do not modify it. 542 func (dl *diffLayer) StorageList(accountHash common.Hash) ([]common.Hash, bool) { 543 dl.lock.RLock() 544 _, destructed := dl.destructSet[accountHash] 545 if _, ok := dl.storageData[accountHash]; !ok { 546 // Account not tracked by this layer 547 dl.lock.RUnlock() 548 return nil, destructed 549 } 550 // If an old list already exists, return it 551 if list, exist := dl.storageList[accountHash]; exist { 552 dl.lock.RUnlock() 553 return list, destructed // the cached list can't be nil 554 } 555 dl.lock.RUnlock() 556 557 // No old sorted account list exists, generate a new one 558 dl.lock.Lock() 559 defer dl.lock.Unlock() 560 561 storageMap := dl.storageData[accountHash] 562 storageList := make([]common.Hash, 0, len(storageMap)) 563 for k := range storageMap { 564 storageList = append(storageList, k) 565 } 566 slices.SortFunc(storageList, common.Hash.Cmp) 567 dl.storageList[accountHash] = storageList 568 dl.memory += uint64(len(dl.storageList)*common.HashLength + common.HashLength) 569 return storageList, destructed 570 }