github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/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 "slices" 25 "sync" 26 "sync/atomic" 27 "time" 28 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/core/types" 31 "github.com/ethereum/go-ethereum/rlp" 32 bloomfilter "github.com/holiman/bloomfilter/v2" 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 aggregator 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 // destructBloomHash is used to convert a destruct event into a 64 bit mini hash. 128 func destructBloomHash(h common.Hash) uint64 { 129 return binary.BigEndian.Uint64(h[bloomDestructHasherOffset : bloomDestructHasherOffset+8]) 130 } 131 132 // accountBloomHash is used to convert an account hash into a 64 bit mini hash. 133 func accountBloomHash(h common.Hash) uint64 { 134 return binary.BigEndian.Uint64(h[bloomAccountHasherOffset : bloomAccountHasherOffset+8]) 135 } 136 137 // storageBloomHash is used to convert an account hash and a storage hash into a 64 bit mini hash. 138 func storageBloomHash(h0, h1 common.Hash) uint64 { 139 return binary.BigEndian.Uint64(h0[bloomStorageHasherOffset:bloomStorageHasherOffset+8]) ^ 140 binary.BigEndian.Uint64(h1[bloomStorageHasherOffset:bloomStorageHasherOffset+8]) 141 } 142 143 // newDiffLayer creates a new diff on top of an existing snapshot, whether that's a low 144 // level persistent database or a hierarchical diff already. 145 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 { 146 // Create the new layer with some pre-allocated data segments 147 dl := &diffLayer{ 148 parent: parent, 149 root: root, 150 destructSet: destructs, 151 accountData: accounts, 152 storageData: storage, 153 storageList: make(map[common.Hash][]common.Hash), 154 } 155 switch parent := parent.(type) { 156 case *diskLayer: 157 dl.rebloom(parent) 158 case *diffLayer: 159 dl.rebloom(parent.origin) 160 default: 161 panic("unknown parent type") 162 } 163 // Sanity check that accounts or storage slots are never nil 164 for accountHash, blob := range accounts { 165 if blob == nil { 166 panic(fmt.Sprintf("account %#x nil", accountHash)) 167 } 168 // Determine memory size and track the dirty writes 169 dl.memory += uint64(common.HashLength + len(blob)) 170 snapshotDirtyAccountWriteMeter.Mark(int64(len(blob))) 171 } 172 for accountHash, slots := range storage { 173 if slots == nil { 174 panic(fmt.Sprintf("storage %#x nil", accountHash)) 175 } 176 // Determine memory size and track the dirty writes 177 for _, data := range slots { 178 dl.memory += uint64(common.HashLength + len(data)) 179 snapshotDirtyStorageWriteMeter.Mark(int64(len(data))) 180 } 181 } 182 dl.memory += uint64(len(destructs) * common.HashLength) 183 return dl 184 } 185 186 // rebloom discards the layer's current bloom and rebuilds it from scratch based 187 // on the parent's and the local diffs. 188 func (dl *diffLayer) rebloom(origin *diskLayer) { 189 dl.lock.Lock() 190 defer dl.lock.Unlock() 191 192 defer func(start time.Time) { 193 snapshotBloomIndexTimer.Update(time.Since(start)) 194 }(time.Now()) 195 196 // Inject the new origin that triggered the rebloom 197 dl.origin = origin 198 199 // Retrieve the parent bloom or create a fresh empty one 200 if parent, ok := dl.parent.(*diffLayer); ok { 201 parent.lock.RLock() 202 dl.diffed, _ = parent.diffed.Copy() 203 parent.lock.RUnlock() 204 } else { 205 dl.diffed, _ = bloomfilter.New(uint64(bloomSize), uint64(bloomFuncs)) 206 } 207 // Iterate over all the accounts and storage slots and index them 208 for hash := range dl.destructSet { 209 dl.diffed.AddHash(destructBloomHash(hash)) 210 } 211 for hash := range dl.accountData { 212 dl.diffed.AddHash(accountBloomHash(hash)) 213 } 214 for accountHash, slots := range dl.storageData { 215 for storageHash := range slots { 216 dl.diffed.AddHash(storageBloomHash(accountHash, storageHash)) 217 } 218 } 219 // Calculate the current false positive rate and update the error rate meter. 220 // This is a bit cheating because subsequent layers will overwrite it, but it 221 // should be fine, we're only interested in ballpark figures. 222 k := float64(dl.diffed.K()) 223 n := float64(dl.diffed.N()) 224 m := float64(dl.diffed.M()) 225 snapshotBloomErrorGauge.Update(math.Pow(1.0-math.Exp((-k)*(n+0.5)/(m-1)), k)) 226 } 227 228 // Root returns the root hash for which this snapshot was made. 229 func (dl *diffLayer) Root() common.Hash { 230 return dl.root 231 } 232 233 // Parent returns the subsequent layer of a diff layer. 234 func (dl *diffLayer) Parent() snapshot { 235 dl.lock.RLock() 236 defer dl.lock.RUnlock() 237 238 return dl.parent 239 } 240 241 // Stale return whether this layer has become stale (was flattened across) or if 242 // it's still live. 243 func (dl *diffLayer) Stale() bool { 244 return dl.stale.Load() 245 } 246 247 // Account directly retrieves the account associated with a particular hash in 248 // the snapshot slim data format. 249 func (dl *diffLayer) Account(hash common.Hash) (*types.SlimAccount, error) { 250 data, err := dl.AccountRLP(hash) 251 if err != nil { 252 return nil, err 253 } 254 if len(data) == 0 { // can be both nil and []byte{} 255 return nil, nil 256 } 257 account := new(types.SlimAccount) 258 if err := rlp.DecodeBytes(data, account); err != nil { 259 panic(err) 260 } 261 return account, nil 262 } 263 264 // AccountRLP directly retrieves the account RLP associated with a particular 265 // hash in the snapshot slim data format. 266 // 267 // Note the returned account is not a copy, please don't modify it. 268 func (dl *diffLayer) AccountRLP(hash common.Hash) ([]byte, error) { 269 // Check staleness before reaching further. 270 dl.lock.RLock() 271 if dl.Stale() { 272 dl.lock.RUnlock() 273 return nil, ErrSnapshotStale 274 } 275 // Check the bloom filter first whether there's even a point in reaching into 276 // all the maps in all the layers below 277 hit := dl.diffed.ContainsHash(accountBloomHash(hash)) 278 if !hit { 279 hit = dl.diffed.ContainsHash(destructBloomHash(hash)) 280 } 281 var origin *diskLayer 282 if !hit { 283 origin = dl.origin // extract origin while holding the lock 284 } 285 dl.lock.RUnlock() 286 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 origin != nil { 290 snapshotBloomAccountMissMeter.Mark(1) 291 return origin.AccountRLP(hash) 292 } 293 // The bloom filter hit, start poking in the internal maps 294 return dl.accountRLP(hash, 0) 295 } 296 297 // accountRLP is an internal version of AccountRLP that skips the bloom filter 298 // checks and uses the internal maps to try and retrieve the data. It's meant 299 // to be used if a higher layer's bloom filter hit already. 300 func (dl *diffLayer) accountRLP(hash common.Hash, depth int) ([]byte, error) { 301 dl.lock.RLock() 302 defer dl.lock.RUnlock() 303 304 // If the layer was flattened into, consider it invalid (any live reference to 305 // the original should be marked as unusable). 306 if dl.Stale() { 307 return nil, ErrSnapshotStale 308 } 309 // If the account is known locally, return it 310 if data, ok := dl.accountData[hash]; ok { 311 snapshotDirtyAccountHitMeter.Mark(1) 312 snapshotDirtyAccountHitDepthHist.Update(int64(depth)) 313 snapshotDirtyAccountReadMeter.Mark(int64(len(data))) 314 snapshotBloomAccountTrueHitMeter.Mark(1) 315 return data, nil 316 } 317 // If the account is known locally, but deleted, return it 318 if _, ok := dl.destructSet[hash]; ok { 319 snapshotDirtyAccountHitMeter.Mark(1) 320 snapshotDirtyAccountHitDepthHist.Update(int64(depth)) 321 snapshotDirtyAccountInexMeter.Mark(1) 322 snapshotBloomAccountTrueHitMeter.Mark(1) 323 return nil, nil 324 } 325 // Account unknown to this diff, resolve from parent 326 if diff, ok := dl.parent.(*diffLayer); ok { 327 return diff.accountRLP(hash, depth+1) 328 } 329 // Failed to resolve through diff layers, mark a bloom error and use the disk 330 snapshotBloomAccountFalseHitMeter.Mark(1) 331 return dl.parent.AccountRLP(hash) 332 } 333 334 // Storage directly retrieves the storage data associated with a particular hash, 335 // within a particular account. If the slot is unknown to this diff, it's parent 336 // is consulted. 337 // 338 // Note the returned slot is not a copy, please don't modify it. 339 func (dl *diffLayer) Storage(accountHash, storageHash common.Hash) ([]byte, error) { 340 // Check the bloom filter first whether there's even a point in reaching into 341 // all the maps in all the layers below 342 dl.lock.RLock() 343 // Check staleness before reaching further. 344 if dl.Stale() { 345 dl.lock.RUnlock() 346 return nil, ErrSnapshotStale 347 } 348 hit := dl.diffed.ContainsHash(storageBloomHash(accountHash, storageHash)) 349 if !hit { 350 hit = dl.diffed.ContainsHash(destructBloomHash(accountHash)) 351 } 352 var origin *diskLayer 353 if !hit { 354 origin = dl.origin // extract origin while holding the lock 355 } 356 dl.lock.RUnlock() 357 358 // If the bloom filter misses, don't even bother with traversing the memory 359 // diff layers, reach straight into the bottom persistent disk layer 360 if origin != nil { 361 snapshotBloomStorageMissMeter.Mark(1) 362 return origin.Storage(accountHash, storageHash) 363 } 364 // The bloom filter hit, start poking in the internal maps 365 return dl.storage(accountHash, storageHash, 0) 366 } 367 368 // storage is an internal version of Storage that skips the bloom filter checks 369 // and uses the internal maps to try and retrieve the data. It's meant to be 370 // used if a higher layer's bloom filter hit already. 371 func (dl *diffLayer) storage(accountHash, storageHash common.Hash, depth int) ([]byte, error) { 372 dl.lock.RLock() 373 defer dl.lock.RUnlock() 374 375 // If the layer was flattened into, consider it invalid (any live reference to 376 // the original should be marked as unusable). 377 if dl.Stale() { 378 return nil, ErrSnapshotStale 379 } 380 // If the account is known locally, try to resolve the slot locally 381 if storage, ok := dl.storageData[accountHash]; ok { 382 if data, ok := storage[storageHash]; ok { 383 snapshotDirtyStorageHitMeter.Mark(1) 384 snapshotDirtyStorageHitDepthHist.Update(int64(depth)) 385 if n := len(data); n > 0 { 386 snapshotDirtyStorageReadMeter.Mark(int64(n)) 387 } else { 388 snapshotDirtyStorageInexMeter.Mark(1) 389 } 390 snapshotBloomStorageTrueHitMeter.Mark(1) 391 return data, nil 392 } 393 } 394 // If the account is known locally, but deleted, return an empty slot 395 if _, ok := dl.destructSet[accountHash]; ok { 396 snapshotDirtyStorageHitMeter.Mark(1) 397 snapshotDirtyStorageHitDepthHist.Update(int64(depth)) 398 snapshotDirtyStorageInexMeter.Mark(1) 399 snapshotBloomStorageTrueHitMeter.Mark(1) 400 return nil, nil 401 } 402 // Storage slot unknown to this diff, resolve from parent 403 if diff, ok := dl.parent.(*diffLayer); ok { 404 return diff.storage(accountHash, storageHash, depth+1) 405 } 406 // Failed to resolve through diff layers, mark a bloom error and use the disk 407 snapshotBloomStorageFalseHitMeter.Mark(1) 408 return dl.parent.Storage(accountHash, storageHash) 409 } 410 411 // Update creates a new layer on top of the existing snapshot diff tree with 412 // the specified data items. 413 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 { 414 return newDiffLayer(dl, blockRoot, destructs, accounts, storage) 415 } 416 417 // flatten pushes all data from this point downwards, flattening everything into 418 // a single diff at the bottom. Since usually the lowermost diff is the largest, 419 // the flattening builds up from there in reverse. 420 func (dl *diffLayer) flatten() snapshot { 421 // If the parent is not diff, we're the first in line, return unmodified 422 parent, ok := dl.parent.(*diffLayer) 423 if !ok { 424 return dl 425 } 426 // Parent is a diff, flatten it first (note, apart from weird corned cases, 427 // flatten will realistically only ever merge 1 layer, so there's no need to 428 // be smarter about grouping flattens together). 429 parent = parent.flatten().(*diffLayer) 430 431 parent.lock.Lock() 432 defer parent.lock.Unlock() 433 434 // Before actually writing all our data to the parent, first ensure that the 435 // parent hasn't been 'corrupted' by someone else already flattening into it 436 if parent.stale.Swap(true) { 437 panic("parent diff layer is stale") // we've flattened into the same parent from two children, boo 438 } 439 // Overwrite all the updated accounts blindly, merge the sorted list 440 for hash := range dl.destructSet { 441 parent.destructSet[hash] = struct{}{} 442 delete(parent.accountData, hash) 443 delete(parent.storageData, hash) 444 } 445 for hash, data := range dl.accountData { 446 parent.accountData[hash] = data 447 } 448 // Overwrite all the updated storage slots (individually) 449 for accountHash, storage := range dl.storageData { 450 // If storage didn't exist (or was deleted) in the parent, overwrite blindly 451 if _, ok := parent.storageData[accountHash]; !ok { 452 parent.storageData[accountHash] = storage 453 continue 454 } 455 // Storage exists in both parent and child, merge the slots 456 comboData := parent.storageData[accountHash] 457 for storageHash, data := range storage { 458 comboData[storageHash] = data 459 } 460 } 461 // Return the combo parent 462 return &diffLayer{ 463 parent: parent.parent, 464 origin: parent.origin, 465 root: dl.root, 466 destructSet: parent.destructSet, 467 accountData: parent.accountData, 468 storageData: parent.storageData, 469 storageList: make(map[common.Hash][]common.Hash), 470 diffed: dl.diffed, 471 memory: parent.memory + dl.memory, 472 } 473 } 474 475 // AccountList returns a sorted list of all accounts in this diffLayer, including 476 // the deleted ones. 477 // 478 // Note, the returned slice is not a copy, so do not modify it. 479 func (dl *diffLayer) AccountList() []common.Hash { 480 // If an old list already exists, return it 481 dl.lock.RLock() 482 list := dl.accountList 483 dl.lock.RUnlock() 484 485 if list != nil { 486 return list 487 } 488 // No old sorted account list exists, generate a new one 489 dl.lock.Lock() 490 defer dl.lock.Unlock() 491 492 dl.accountList = make([]common.Hash, 0, len(dl.destructSet)+len(dl.accountData)) 493 for hash := range dl.accountData { 494 dl.accountList = append(dl.accountList, hash) 495 } 496 for hash := range dl.destructSet { 497 if _, ok := dl.accountData[hash]; !ok { 498 dl.accountList = append(dl.accountList, hash) 499 } 500 } 501 slices.SortFunc(dl.accountList, common.Hash.Cmp) 502 dl.memory += uint64(len(dl.accountList) * common.HashLength) 503 return dl.accountList 504 } 505 506 // StorageList returns a sorted list of all storage slot hashes in this diffLayer 507 // for the given account. If the whole storage is destructed in this layer, then 508 // an additional flag *destructed = true* will be returned, otherwise the flag is 509 // false. Besides, the returned list will include the hash of deleted storage slot. 510 // Note a special case is an account is deleted in a prior tx but is recreated in 511 // the following tx with some storage slots set. In this case the returned list is 512 // not empty but the flag is true. 513 // 514 // Note, the returned slice is not a copy, so do not modify it. 515 func (dl *diffLayer) StorageList(accountHash common.Hash) ([]common.Hash, bool) { 516 dl.lock.RLock() 517 _, destructed := dl.destructSet[accountHash] 518 if _, ok := dl.storageData[accountHash]; !ok { 519 // Account not tracked by this layer 520 dl.lock.RUnlock() 521 return nil, destructed 522 } 523 // If an old list already exists, return it 524 if list, exist := dl.storageList[accountHash]; exist { 525 dl.lock.RUnlock() 526 return list, destructed // the cached list can't be nil 527 } 528 dl.lock.RUnlock() 529 530 // No old sorted account list exists, generate a new one 531 dl.lock.Lock() 532 defer dl.lock.Unlock() 533 534 storageMap := dl.storageData[accountHash] 535 storageList := make([]common.Hash, 0, len(storageMap)) 536 for k := range storageMap { 537 storageList = append(storageList, k) 538 } 539 slices.SortFunc(storageList, common.Hash.Cmp) 540 dl.storageList[accountHash] = storageList 541 dl.memory += uint64(len(dl.storageList)*common.HashLength + common.HashLength) 542 return storageList, destructed 543 }