gitlab.com/yannislg/go-pulse@v0.0.0-20210722055913-a3e24e95638d/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/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/rlp" 31 "github.com/steakknife/bloomfilter" 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 thet 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 map[common.Hash]struct{} // Keyed markers for deleted (and potentially) recreated accounts 109 accountList []common.Hash // List of account for iteration. If it exists, it's sorted, otherwise it's nil 110 accountData map[common.Hash][]byte // Keyed accounts for direct retrival (nil means deleted) 111 storageList map[common.Hash][]common.Hash // List of storage slots for iterated retrievals, one per account. Any existing lists are sorted if non-nil 112 storageData map[common.Hash]map[common.Hash][]byte // Keyed storage slots for direct retrival. one per account (nil means deleted) 113 114 diffed *bloomfilter.Filter // Bloom filter tracking all the diffed items up to the disk layer 115 116 lock sync.RWMutex 117 } 118 119 // destructBloomHasher is a wrapper around a common.Hash to satisfy the interface 120 // API requirements of the bloom library used. It's used to convert a destruct 121 // event into a 64 bit mini hash. 122 type destructBloomHasher common.Hash 123 124 func (h destructBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") } 125 func (h destructBloomHasher) Sum(b []byte) []byte { panic("not implemented") } 126 func (h destructBloomHasher) Reset() { panic("not implemented") } 127 func (h destructBloomHasher) BlockSize() int { panic("not implemented") } 128 func (h destructBloomHasher) Size() int { return 8 } 129 func (h destructBloomHasher) Sum64() uint64 { 130 return binary.BigEndian.Uint64(h[bloomDestructHasherOffset : bloomDestructHasherOffset+8]) 131 } 132 133 // accountBloomHasher is a wrapper around a common.Hash to satisfy the interface 134 // API requirements of the bloom library used. It's used to convert an account 135 // hash into a 64 bit mini hash. 136 type accountBloomHasher common.Hash 137 138 func (h accountBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") } 139 func (h accountBloomHasher) Sum(b []byte) []byte { panic("not implemented") } 140 func (h accountBloomHasher) Reset() { panic("not implemented") } 141 func (h accountBloomHasher) BlockSize() int { panic("not implemented") } 142 func (h accountBloomHasher) Size() int { return 8 } 143 func (h accountBloomHasher) Sum64() uint64 { 144 return binary.BigEndian.Uint64(h[bloomAccountHasherOffset : bloomAccountHasherOffset+8]) 145 } 146 147 // storageBloomHasher is a wrapper around a [2]common.Hash to satisfy the interface 148 // API requirements of the bloom library used. It's used to convert an account 149 // hash into a 64 bit mini hash. 150 type storageBloomHasher [2]common.Hash 151 152 func (h storageBloomHasher) Write(p []byte) (n int, err error) { panic("not implemented") } 153 func (h storageBloomHasher) Sum(b []byte) []byte { panic("not implemented") } 154 func (h storageBloomHasher) Reset() { panic("not implemented") } 155 func (h storageBloomHasher) BlockSize() int { panic("not implemented") } 156 func (h storageBloomHasher) Size() int { return 8 } 157 func (h storageBloomHasher) Sum64() uint64 { 158 return binary.BigEndian.Uint64(h[0][bloomStorageHasherOffset:bloomStorageHasherOffset+8]) ^ 159 binary.BigEndian.Uint64(h[1][bloomStorageHasherOffset:bloomStorageHasherOffset+8]) 160 } 161 162 // newDiffLayer creates a new diff on top of an existing snapshot, whether that's a low 163 // level persistent database or a hierarchical diff already. 164 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 { 165 // Create the new layer with some pre-allocated data segments 166 dl := &diffLayer{ 167 parent: parent, 168 root: root, 169 destructSet: destructs, 170 accountData: accounts, 171 storageData: storage, 172 } 173 switch parent := parent.(type) { 174 case *diskLayer: 175 dl.rebloom(parent) 176 case *diffLayer: 177 dl.rebloom(parent.origin) 178 default: 179 panic("unknown parent type") 180 } 181 // Sanity check that accounts or storage slots are never nil 182 for accountHash, blob := range accounts { 183 if blob == nil { 184 panic(fmt.Sprintf("account %#x nil", accountHash)) 185 } 186 } 187 for accountHash, slots := range storage { 188 if slots == nil { 189 panic(fmt.Sprintf("storage %#x nil", accountHash)) 190 } 191 } 192 // Determine memory size and track the dirty writes 193 for _, data := range accounts { 194 dl.memory += uint64(common.HashLength + len(data)) 195 snapshotDirtyAccountWriteMeter.Mark(int64(len(data))) 196 } 197 // Fill the storage hashes and sort them for the iterator 198 dl.storageList = make(map[common.Hash][]common.Hash) 199 for accountHash := range destructs { 200 dl.storageList[accountHash] = nil 201 } 202 // Determine memory size and track the dirty writes 203 for _, slots := range storage { 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(dl.storageList) * 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 return dl.parent 263 } 264 265 // Stale return whether this layer has become stale (was flattened across) or if 266 // it's still live. 267 func (dl *diffLayer) Stale() bool { 268 return atomic.LoadUint32(&dl.stale) != 0 269 } 270 271 // Account directly retrieves the account associated with a particular hash in 272 // the snapshot slim data format. 273 func (dl *diffLayer) Account(hash common.Hash) (*Account, error) { 274 data, err := dl.AccountRLP(hash) 275 if err != nil { 276 return nil, err 277 } 278 if len(data) == 0 { // can be both nil and []byte{} 279 return nil, nil 280 } 281 account := new(Account) 282 if err := rlp.DecodeBytes(data, account); err != nil { 283 panic(err) 284 } 285 return account, nil 286 } 287 288 // AccountRLP directly retrieves the account RLP associated with a particular 289 // hash in the snapshot slim data format. 290 func (dl *diffLayer) AccountRLP(hash common.Hash) ([]byte, error) { 291 // Check the bloom filter first whether there's even a point in reaching into 292 // all the maps in all the layers below 293 dl.lock.RLock() 294 hit := dl.diffed.Contains(accountBloomHasher(hash)) 295 if !hit { 296 hit = dl.diffed.Contains(destructBloomHasher(hash)) 297 } 298 dl.lock.RUnlock() 299 300 // If the bloom filter misses, don't even bother with traversing the memory 301 // diff layers, reach straight into the bottom persistent disk layer 302 if !hit { 303 snapshotBloomAccountMissMeter.Mark(1) 304 return dl.origin.AccountRLP(hash) 305 } 306 // The bloom filter hit, start poking in the internal maps 307 return dl.accountRLP(hash, 0) 308 } 309 310 // accountRLP is an internal version of AccountRLP that skips the bloom filter 311 // checks and uses the internal maps to try and retrieve the data. It's meant 312 // to be used if a higher layer's bloom filter hit already. 313 func (dl *diffLayer) accountRLP(hash common.Hash, depth int) ([]byte, error) { 314 dl.lock.RLock() 315 defer dl.lock.RUnlock() 316 317 // If the layer was flattened into, consider it invalid (any live reference to 318 // the original should be marked as unusable). 319 if dl.Stale() { 320 return nil, ErrSnapshotStale 321 } 322 // If the account is known locally, return it 323 if data, ok := dl.accountData[hash]; ok { 324 snapshotDirtyAccountHitMeter.Mark(1) 325 snapshotDirtyAccountHitDepthHist.Update(int64(depth)) 326 snapshotDirtyAccountReadMeter.Mark(int64(len(data))) 327 snapshotBloomAccountTrueHitMeter.Mark(1) 328 return data, nil 329 } 330 // If the account is known locally, but deleted, return it 331 if _, ok := dl.destructSet[hash]; ok { 332 snapshotDirtyAccountHitMeter.Mark(1) 333 snapshotDirtyAccountHitDepthHist.Update(int64(depth)) 334 snapshotDirtyAccountInexMeter.Mark(1) 335 snapshotBloomAccountTrueHitMeter.Mark(1) 336 return nil, nil 337 } 338 // Account unknown to this diff, resolve from parent 339 if diff, ok := dl.parent.(*diffLayer); ok { 340 return diff.accountRLP(hash, depth+1) 341 } 342 // Failed to resolve through diff layers, mark a bloom error and use the disk 343 snapshotBloomAccountFalseHitMeter.Mark(1) 344 return dl.parent.AccountRLP(hash) 345 } 346 347 // Storage directly retrieves the storage data associated with a particular hash, 348 // within a particular account. If the slot is unknown to this diff, it's parent 349 // is consulted. 350 func (dl *diffLayer) Storage(accountHash, storageHash common.Hash) ([]byte, error) { 351 // Check the bloom filter first whether there's even a point in reaching into 352 // all the maps in all the layers below 353 dl.lock.RLock() 354 hit := dl.diffed.Contains(storageBloomHasher{accountHash, storageHash}) 355 if !hit { 356 hit = dl.diffed.Contains(destructBloomHasher(accountHash)) 357 } 358 dl.lock.RUnlock() 359 360 // If the bloom filter misses, don't even bother with traversing the memory 361 // diff layers, reach straight into the bottom persistent disk layer 362 if !hit { 363 snapshotBloomStorageMissMeter.Mark(1) 364 return dl.origin.Storage(accountHash, storageHash) 365 } 366 // The bloom filter hit, start poking in the internal maps 367 return dl.storage(accountHash, storageHash, 0) 368 } 369 370 // storage is an internal version of Storage that skips the bloom filter checks 371 // and uses the internal maps to try and retrieve the data. It's meant to be 372 // used if a higher layer's bloom filter hit already. 373 func (dl *diffLayer) storage(accountHash, storageHash common.Hash, depth int) ([]byte, error) { 374 dl.lock.RLock() 375 defer dl.lock.RUnlock() 376 377 // If the layer was flattened into, consider it invalid (any live reference to 378 // the original should be marked as unusable). 379 if dl.Stale() { 380 return nil, ErrSnapshotStale 381 } 382 // If the account is known locally, try to resolve the slot locally 383 if storage, ok := dl.storageData[accountHash]; ok { 384 if data, ok := storage[storageHash]; ok { 385 snapshotDirtyStorageHitMeter.Mark(1) 386 snapshotDirtyStorageHitDepthHist.Update(int64(depth)) 387 if n := len(data); n > 0 { 388 snapshotDirtyStorageReadMeter.Mark(int64(n)) 389 } else { 390 snapshotDirtyStorageInexMeter.Mark(1) 391 } 392 snapshotBloomStorageTrueHitMeter.Mark(1) 393 return data, nil 394 } 395 } 396 // If the account is known locally, but deleted, return an empty slot 397 if _, ok := dl.destructSet[accountHash]; ok { 398 snapshotDirtyStorageHitMeter.Mark(1) 399 snapshotDirtyStorageHitDepthHist.Update(int64(depth)) 400 snapshotDirtyStorageInexMeter.Mark(1) 401 snapshotBloomStorageTrueHitMeter.Mark(1) 402 return nil, nil 403 } 404 // Storage slot unknown to this diff, resolve from parent 405 if diff, ok := dl.parent.(*diffLayer); ok { 406 return diff.storage(accountHash, storageHash, depth+1) 407 } 408 // Failed to resolve through diff layers, mark a bloom error and use the disk 409 snapshotBloomStorageFalseHitMeter.Mark(1) 410 return dl.parent.Storage(accountHash, storageHash) 411 } 412 413 // Update creates a new layer on top of the existing snapshot diff tree with 414 // the specified data items. 415 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 { 416 return newDiffLayer(dl, blockRoot, destructs, accounts, storage) 417 } 418 419 // flatten pushes all data from this point downwards, flattening everything into 420 // a single diff at the bottom. Since usually the lowermost diff is the largest, 421 // the flattening bulds up from there in reverse. 422 func (dl *diffLayer) flatten() snapshot { 423 // If the parent is not diff, we're the first in line, return unmodified 424 parent, ok := dl.parent.(*diffLayer) 425 if !ok { 426 return dl 427 } 428 // Parent is a diff, flatten it first (note, apart from weird corned cases, 429 // flatten will realistically only ever merge 1 layer, so there's no need to 430 // be smarter about grouping flattens together). 431 parent = parent.flatten().(*diffLayer) 432 433 parent.lock.Lock() 434 defer parent.lock.Unlock() 435 436 // Before actually writing all our data to the parent, first ensure that the 437 // parent hasn't been 'corrupted' by someone else already flattening into it 438 if atomic.SwapUint32(&parent.stale, 1) != 0 { 439 panic("parent diff layer is stale") // we've flattened into the same parent from two children, boo 440 } 441 // Overwrite all the updated accounts blindly, merge the sorted list 442 for hash := range dl.destructSet { 443 parent.destructSet[hash] = struct{}{} 444 delete(parent.accountData, hash) 445 delete(parent.storageData, hash) 446 } 447 for hash, data := range dl.accountData { 448 parent.accountData[hash] = data 449 } 450 // Overwrite all the updated storage slots (individually) 451 for accountHash, storage := range dl.storageData { 452 // If storage didn't exist (or was deleted) in the parent, overwrite blindly 453 if _, ok := parent.storageData[accountHash]; !ok { 454 parent.storageData[accountHash] = storage 455 continue 456 } 457 // Storage exists in both parent and child, merge the slots 458 comboData := parent.storageData[accountHash] 459 for storageHash, data := range storage { 460 comboData[storageHash] = data 461 } 462 parent.storageData[accountHash] = comboData 463 } 464 // Return the combo parent 465 return &diffLayer{ 466 parent: parent.parent, 467 origin: parent.origin, 468 root: dl.root, 469 destructSet: parent.destructSet, 470 accountData: parent.accountData, 471 storageData: parent.storageData, 472 storageList: make(map[common.Hash][]common.Hash), 473 diffed: dl.diffed, 474 memory: parent.memory + dl.memory, 475 } 476 } 477 478 // AccountList returns a sorted list of all accounts in this difflayer, including 479 // the deleted ones. 480 // 481 // Note, the returned slice is not a copy, so do not modify it. 482 func (dl *diffLayer) AccountList() []common.Hash { 483 // If an old list already exists, return it 484 dl.lock.RLock() 485 list := dl.accountList 486 dl.lock.RUnlock() 487 488 if list != nil { 489 return list 490 } 491 // No old sorted account list exists, generate a new one 492 dl.lock.Lock() 493 defer dl.lock.Unlock() 494 495 dl.accountList = make([]common.Hash, 0, len(dl.destructSet)+len(dl.accountData)) 496 for hash := range dl.accountData { 497 dl.accountList = append(dl.accountList, hash) 498 } 499 for hash := range dl.destructSet { 500 if _, ok := dl.accountData[hash]; !ok { 501 dl.accountList = append(dl.accountList, hash) 502 } 503 } 504 sort.Sort(hashes(dl.accountList)) 505 return dl.accountList 506 } 507 508 // StorageList returns a sorted list of all storage slot hashes in this difflayer 509 // for the given account. 510 // 511 // Note, the returned slice is not a copy, so do not modify it. 512 func (dl *diffLayer) StorageList(accountHash common.Hash) []common.Hash { 513 // If an old list already exists, return it 514 dl.lock.RLock() 515 list := dl.storageList[accountHash] 516 dl.lock.RUnlock() 517 518 if list != nil { 519 return list 520 } 521 // No old sorted account list exists, generate a new one 522 dl.lock.Lock() 523 defer dl.lock.Unlock() 524 525 storageMap := dl.storageData[accountHash] 526 storageList := make([]common.Hash, 0, len(storageMap)) 527 for k := range storageMap { 528 storageList = append(storageList, k) 529 } 530 sort.Sort(hashes(storageList)) 531 dl.storageList[accountHash] = storageList 532 return storageList 533 }