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