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