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