github.com/phillinzzz/newBsc@v1.1.6/core/state/statedb.go (about) 1 // Copyright 2014 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 state provides a caching layer atop the Ethereum state trie. 18 package state 19 20 import ( 21 "errors" 22 "fmt" 23 "math/big" 24 "runtime" 25 "sort" 26 "sync" 27 "time" 28 29 "github.com/phillinzzz/newBsc/common" 30 "github.com/phillinzzz/newBsc/common/gopool" 31 "github.com/phillinzzz/newBsc/core/rawdb" 32 "github.com/phillinzzz/newBsc/core/state/snapshot" 33 "github.com/phillinzzz/newBsc/core/types" 34 "github.com/phillinzzz/newBsc/crypto" 35 "github.com/phillinzzz/newBsc/ethdb" 36 "github.com/phillinzzz/newBsc/log" 37 "github.com/phillinzzz/newBsc/metrics" 38 "github.com/phillinzzz/newBsc/rlp" 39 "github.com/phillinzzz/newBsc/trie" 40 ) 41 42 const ( 43 preLoadLimit = 128 44 defaultNumOfSlots = 100 45 ) 46 47 type revision struct { 48 id int 49 journalIndex int 50 } 51 52 var ( 53 // emptyRoot is the known root hash of an empty trie. 54 emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") 55 56 emptyAddr = crypto.Keccak256Hash(common.Address{}.Bytes()) 57 ) 58 59 type proofList [][]byte 60 61 func (n *proofList) Put(key []byte, value []byte) error { 62 *n = append(*n, value) 63 return nil 64 } 65 66 func (n *proofList) Delete(key []byte) error { 67 panic("not supported") 68 } 69 70 // StateDB structs within the ethereum protocol are used to store anything 71 // within the merkle trie. StateDBs take care of caching and storing 72 // nested states. It's the general query interface to retrieve: 73 // * Contracts 74 // * Accounts 75 type StateDB struct { 76 db Database 77 prefetcher *triePrefetcher 78 originalRoot common.Hash // The pre-state root, before any changes were made 79 trie Trie 80 hasher crypto.KeccakState 81 diffLayer *types.DiffLayer 82 diffTries map[common.Address]Trie 83 diffCode map[common.Hash][]byte 84 lightProcessed bool 85 86 snapMux sync.Mutex 87 snaps *snapshot.Tree 88 snap snapshot.Snapshot 89 snapDestructs map[common.Address]struct{} 90 snapAccounts map[common.Address][]byte 91 snapStorage map[common.Address]map[string][]byte 92 93 // This map holds 'live' objects, which will get modified while processing a state transition. 94 stateObjects map[common.Address]*StateObject 95 stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie 96 stateObjectsDirty map[common.Address]struct{} // State objects modified in the current execution 97 98 // DB error. 99 // State objects are used by the consensus core and VM which are 100 // unable to deal with database-level errors. Any error that occurs 101 // during a database read is memoized here and will eventually be returned 102 // by StateDB.Commit. 103 dbErr error 104 105 // The refund counter, also used by state transitioning. 106 refund uint64 107 108 thash, bhash common.Hash 109 txIndex int 110 logs map[common.Hash][]*types.Log 111 logSize uint 112 113 preimages map[common.Hash][]byte 114 115 // Per-transaction access list 116 accessList *accessList 117 118 // Journal of state modifications. This is the backbone of 119 // Snapshot and RevertToSnapshot. 120 journal *journal 121 validRevisions []revision 122 nextRevisionId int 123 124 // Measurements gathered during execution for debugging purposes 125 MetricsMux sync.Mutex 126 AccountReads time.Duration 127 AccountHashes time.Duration 128 AccountUpdates time.Duration 129 AccountCommits time.Duration 130 StorageReads time.Duration 131 StorageHashes time.Duration 132 StorageUpdates time.Duration 133 StorageCommits time.Duration 134 SnapshotAccountReads time.Duration 135 SnapshotStorageReads time.Duration 136 SnapshotCommits time.Duration 137 } 138 139 // New creates a new state from a given trie. 140 func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) { 141 return newStateDB(root, db, snaps) 142 } 143 144 func newStateDB(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) { 145 sdb := &StateDB{ 146 db: db, 147 originalRoot: root, 148 snaps: snaps, 149 stateObjects: make(map[common.Address]*StateObject, defaultNumOfSlots), 150 stateObjectsPending: make(map[common.Address]struct{}, defaultNumOfSlots), 151 stateObjectsDirty: make(map[common.Address]struct{}, defaultNumOfSlots), 152 logs: make(map[common.Hash][]*types.Log, defaultNumOfSlots), 153 preimages: make(map[common.Hash][]byte), 154 journal: newJournal(), 155 hasher: crypto.NewKeccakState(), 156 } 157 tr, err := db.OpenTrie(root) 158 if err != nil { 159 return nil, err 160 } 161 sdb.trie = tr 162 if sdb.snaps != nil { 163 if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil { 164 sdb.snapDestructs = make(map[common.Address]struct{}) 165 sdb.snapAccounts = make(map[common.Address][]byte) 166 sdb.snapStorage = make(map[common.Address]map[string][]byte) 167 } 168 } 169 return sdb, nil 170 } 171 172 // StartPrefetcher initializes a new trie prefetcher to pull in nodes from the 173 // state trie concurrently while the state is mutated so that when we reach the 174 // commit phase, most of the needed data is already hot. 175 func (s *StateDB) StartPrefetcher(namespace string) { 176 if s.prefetcher != nil { 177 s.prefetcher.close() 178 s.prefetcher = nil 179 } 180 if s.snap != nil { 181 s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace) 182 } 183 } 184 185 // StopPrefetcher terminates a running prefetcher and reports any leftover stats 186 // from the gathered metrics. 187 func (s *StateDB) StopPrefetcher() { 188 if s.prefetcher != nil { 189 s.prefetcher.close() 190 s.prefetcher = nil 191 } 192 } 193 194 // Mark that the block is processed by diff layer 195 func (s *StateDB) MarkLightProcessed() { 196 s.lightProcessed = true 197 } 198 199 func (s *StateDB) IsLightProcessed() bool { 200 return s.lightProcessed 201 } 202 203 // setError remembers the first non-nil error it is called with. 204 func (s *StateDB) setError(err error) { 205 if s.dbErr == nil { 206 s.dbErr = err 207 } 208 } 209 210 func (s *StateDB) Error() error { 211 return s.dbErr 212 } 213 214 func (s *StateDB) Trie() Trie { 215 return s.trie 216 } 217 218 func (s *StateDB) SetDiff(diffLayer *types.DiffLayer, diffTries map[common.Address]Trie, diffCode map[common.Hash][]byte) { 219 s.diffLayer, s.diffTries, s.diffCode = diffLayer, diffTries, diffCode 220 } 221 222 func (s *StateDB) SetSnapData(snapDestructs map[common.Address]struct{}, snapAccounts map[common.Address][]byte, 223 snapStorage map[common.Address]map[string][]byte) { 224 s.snapDestructs, s.snapAccounts, s.snapStorage = snapDestructs, snapAccounts, snapStorage 225 } 226 227 func (s *StateDB) AddLog(log *types.Log) { 228 s.journal.append(addLogChange{txhash: s.thash}) 229 230 log.TxHash = s.thash 231 log.BlockHash = s.bhash 232 log.TxIndex = uint(s.txIndex) 233 log.Index = s.logSize 234 s.logs[s.thash] = append(s.logs[s.thash], log) 235 s.logSize++ 236 } 237 238 func (s *StateDB) GetLogs(hash common.Hash) []*types.Log { 239 return s.logs[hash] 240 } 241 242 func (s *StateDB) Logs() []*types.Log { 243 var logs []*types.Log 244 for _, lgs := range s.logs { 245 logs = append(logs, lgs...) 246 } 247 return logs 248 } 249 250 // AddPreimage records a SHA3 preimage seen by the VM. 251 func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 252 if _, ok := s.preimages[hash]; !ok { 253 s.journal.append(addPreimageChange{hash: hash}) 254 pi := make([]byte, len(preimage)) 255 copy(pi, preimage) 256 s.preimages[hash] = pi 257 } 258 } 259 260 // Preimages returns a list of SHA3 preimages that have been submitted. 261 func (s *StateDB) Preimages() map[common.Hash][]byte { 262 return s.preimages 263 } 264 265 // AddRefund adds gas to the refund counter 266 func (s *StateDB) AddRefund(gas uint64) { 267 s.journal.append(refundChange{prev: s.refund}) 268 s.refund += gas 269 } 270 271 // SubRefund removes gas from the refund counter. 272 // This method will panic if the refund counter goes below zero 273 func (s *StateDB) SubRefund(gas uint64) { 274 s.journal.append(refundChange{prev: s.refund}) 275 if gas > s.refund { 276 panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund)) 277 } 278 s.refund -= gas 279 } 280 281 // Exist reports whether the given account address exists in the state. 282 // Notably this also returns true for suicided accounts. 283 func (s *StateDB) Exist(addr common.Address) bool { 284 return s.getStateObject(addr) != nil 285 } 286 287 // Empty returns whether the state object is either non-existent 288 // or empty according to the EIP161 specification (balance = nonce = code = 0) 289 func (s *StateDB) Empty(addr common.Address) bool { 290 so := s.getStateObject(addr) 291 return so == nil || so.empty() 292 } 293 294 // GetBalance retrieves the balance from the given address or 0 if object not found 295 func (s *StateDB) GetBalance(addr common.Address) *big.Int { 296 stateObject := s.getStateObject(addr) 297 if stateObject != nil { 298 return stateObject.Balance() 299 } 300 return common.Big0 301 } 302 303 func (s *StateDB) GetNonce(addr common.Address) uint64 { 304 stateObject := s.getStateObject(addr) 305 if stateObject != nil { 306 return stateObject.Nonce() 307 } 308 309 return 0 310 } 311 312 // TxIndex returns the current transaction index set by Prepare. 313 func (s *StateDB) TxIndex() int { 314 return s.txIndex 315 } 316 317 // BlockHash returns the current block hash set by Prepare. 318 func (s *StateDB) BlockHash() common.Hash { 319 return s.bhash 320 } 321 322 func (s *StateDB) GetCode(addr common.Address) []byte { 323 stateObject := s.getStateObject(addr) 324 if stateObject != nil { 325 return stateObject.Code(s.db) 326 } 327 return nil 328 } 329 330 func (s *StateDB) GetCodeSize(addr common.Address) int { 331 stateObject := s.getStateObject(addr) 332 if stateObject != nil { 333 return stateObject.CodeSize(s.db) 334 } 335 return 0 336 } 337 338 func (s *StateDB) GetCodeHash(addr common.Address) common.Hash { 339 stateObject := s.getStateObject(addr) 340 if stateObject == nil { 341 return common.Hash{} 342 } 343 return common.BytesToHash(stateObject.CodeHash()) 344 } 345 346 // GetState retrieves a value from the given account's storage trie. 347 func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { 348 stateObject := s.getStateObject(addr) 349 if stateObject != nil { 350 return stateObject.GetState(s.db, hash) 351 } 352 return common.Hash{} 353 } 354 355 // GetProof returns the Merkle proof for a given account. 356 func (s *StateDB) GetProof(addr common.Address) ([][]byte, error) { 357 return s.GetProofByHash(crypto.Keccak256Hash(addr.Bytes())) 358 } 359 360 // GetProofByHash returns the Merkle proof for a given account. 361 func (s *StateDB) GetProofByHash(addrHash common.Hash) ([][]byte, error) { 362 var proof proofList 363 err := s.trie.Prove(addrHash[:], 0, &proof) 364 return proof, err 365 } 366 367 // GetStorageProof returns the Merkle proof for given storage slot. 368 func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) { 369 var proof proofList 370 trie := s.StorageTrie(a) 371 if trie == nil { 372 return proof, errors.New("storage trie for requested address does not exist") 373 } 374 err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof) 375 return proof, err 376 } 377 378 // GetStorageProofByHash returns the Merkle proof for given storage slot. 379 func (s *StateDB) GetStorageProofByHash(a common.Address, key common.Hash) ([][]byte, error) { 380 var proof proofList 381 trie := s.StorageTrie(a) 382 if trie == nil { 383 return proof, errors.New("storage trie for requested address does not exist") 384 } 385 err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof) 386 return proof, err 387 } 388 389 // GetCommittedState retrieves a value from the given account's committed storage trie. 390 func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { 391 stateObject := s.getStateObject(addr) 392 if stateObject != nil { 393 return stateObject.GetCommittedState(s.db, hash) 394 } 395 return common.Hash{} 396 } 397 398 // Database retrieves the low level database supporting the lower level trie ops. 399 func (s *StateDB) Database() Database { 400 return s.db 401 } 402 403 // StorageTrie returns the storage trie of an account. 404 // The return value is a copy and is nil for non-existent accounts. 405 func (s *StateDB) StorageTrie(addr common.Address) Trie { 406 stateObject := s.getStateObject(addr) 407 if stateObject == nil { 408 return nil 409 } 410 cpy := stateObject.deepCopy(s) 411 cpy.updateTrie(s.db) 412 return cpy.getTrie(s.db) 413 } 414 415 func (s *StateDB) HasSuicided(addr common.Address) bool { 416 stateObject := s.getStateObject(addr) 417 if stateObject != nil { 418 return stateObject.suicided 419 } 420 return false 421 } 422 423 /* 424 * SETTERS 425 */ 426 427 // AddBalance adds amount to the account associated with addr. 428 func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) { 429 stateObject := s.GetOrNewStateObject(addr) 430 if stateObject != nil { 431 stateObject.AddBalance(amount) 432 } 433 } 434 435 // SubBalance subtracts amount from the account associated with addr. 436 func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) { 437 stateObject := s.GetOrNewStateObject(addr) 438 if stateObject != nil { 439 stateObject.SubBalance(amount) 440 } 441 } 442 443 func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) { 444 stateObject := s.GetOrNewStateObject(addr) 445 if stateObject != nil { 446 stateObject.SetBalance(amount) 447 } 448 } 449 450 func (s *StateDB) SetNonce(addr common.Address, nonce uint64) { 451 stateObject := s.GetOrNewStateObject(addr) 452 if stateObject != nil { 453 stateObject.SetNonce(nonce) 454 } 455 } 456 457 func (s *StateDB) SetCode(addr common.Address, code []byte) { 458 stateObject := s.GetOrNewStateObject(addr) 459 if stateObject != nil { 460 stateObject.SetCode(crypto.Keccak256Hash(code), code) 461 } 462 } 463 464 func (s *StateDB) SetState(addr common.Address, key, value common.Hash) { 465 stateObject := s.GetOrNewStateObject(addr) 466 if stateObject != nil { 467 stateObject.SetState(s.db, key, value) 468 } 469 } 470 471 // SetStorage replaces the entire storage for the specified account with given 472 // storage. This function should only be used for debugging. 473 func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) { 474 stateObject := s.GetOrNewStateObject(addr) 475 if stateObject != nil { 476 stateObject.SetStorage(storage) 477 } 478 } 479 480 // Suicide marks the given account as suicided. 481 // This clears the account balance. 482 // 483 // The account's state object is still available until the state is committed, 484 // getStateObject will return a non-nil account after Suicide. 485 func (s *StateDB) Suicide(addr common.Address) bool { 486 stateObject := s.getStateObject(addr) 487 if stateObject == nil { 488 return false 489 } 490 s.journal.append(suicideChange{ 491 account: &addr, 492 prev: stateObject.suicided, 493 prevbalance: new(big.Int).Set(stateObject.Balance()), 494 }) 495 stateObject.markSuicided() 496 stateObject.data.Balance = new(big.Int) 497 498 return true 499 } 500 501 // 502 // Setting, updating & deleting state object methods. 503 // 504 505 // updateStateObject writes the given object to the trie. 506 func (s *StateDB) updateStateObject(obj *StateObject) { 507 // Track the amount of time wasted on updating the account from the trie 508 if metrics.EnabledExpensive { 509 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 510 } 511 // Encode the account and update the account trie 512 addr := obj.Address() 513 data := obj.encodeData 514 var err error 515 if data == nil { 516 data, err = rlp.EncodeToBytes(obj) 517 if err != nil { 518 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 519 } 520 } 521 if err = s.trie.TryUpdate(addr[:], data); err != nil { 522 s.setError(fmt.Errorf("updateStateObject (%x) error: %v", addr[:], err)) 523 } 524 } 525 526 // deleteStateObject removes the given object from the state trie. 527 func (s *StateDB) deleteStateObject(obj *StateObject) { 528 // Track the amount of time wasted on deleting the account from the trie 529 if metrics.EnabledExpensive { 530 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 531 } 532 // Delete the account from the trie 533 addr := obj.Address() 534 if err := s.trie.TryDelete(addr[:]); err != nil { 535 s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err)) 536 } 537 } 538 539 // getStateObject retrieves a state object given by the address, returning nil if 540 // the object is not found or was deleted in this execution context. If you need 541 // to differentiate between non-existent/just-deleted, use getDeletedStateObject. 542 func (s *StateDB) getStateObject(addr common.Address) *StateObject { 543 if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted { 544 return obj 545 } 546 return nil 547 } 548 549 func (s *StateDB) TryPreload(block *types.Block, signer types.Signer) { 550 accounts := make(map[common.Address]bool, block.Transactions().Len()) 551 accountsSlice := make([]common.Address, 0, block.Transactions().Len()) 552 for _, tx := range block.Transactions() { 553 from, err := types.Sender(signer, tx) 554 if err != nil { 555 break 556 } 557 accounts[from] = true 558 if tx.To() != nil { 559 accounts[*tx.To()] = true 560 } 561 } 562 for account := range accounts { 563 accountsSlice = append(accountsSlice, account) 564 } 565 if len(accountsSlice) >= preLoadLimit && len(accountsSlice) > runtime.NumCPU() { 566 objsChan := make(chan []*StateObject, runtime.NumCPU()) 567 for i := 0; i < runtime.NumCPU(); i++ { 568 start := i * len(accountsSlice) / runtime.NumCPU() 569 end := (i + 1) * len(accountsSlice) / runtime.NumCPU() 570 if i+1 == runtime.NumCPU() { 571 end = len(accountsSlice) 572 } 573 go func(start, end int) { 574 objs := s.preloadStateObject(accountsSlice[start:end]) 575 objsChan <- objs 576 }(start, end) 577 } 578 for i := 0; i < runtime.NumCPU(); i++ { 579 objs := <-objsChan 580 for _, obj := range objs { 581 s.SetStateObject(obj) 582 } 583 } 584 } 585 } 586 587 func (s *StateDB) preloadStateObject(address []common.Address) []*StateObject { 588 // Prefer live objects if any is available 589 if s.snap == nil { 590 return nil 591 } 592 hasher := crypto.NewKeccakState() 593 objs := make([]*StateObject, 0, len(address)) 594 for _, addr := range address { 595 // If no live objects are available, attempt to use snapshots 596 if acc, err := s.snap.Account(crypto.HashData(hasher, addr.Bytes())); err == nil { 597 if acc == nil { 598 continue 599 } 600 data := &Account{ 601 Nonce: acc.Nonce, 602 Balance: acc.Balance, 603 CodeHash: acc.CodeHash, 604 Root: common.BytesToHash(acc.Root), 605 } 606 if len(data.CodeHash) == 0 { 607 data.CodeHash = emptyCodeHash 608 } 609 if data.Root == (common.Hash{}) { 610 data.Root = emptyRoot 611 } 612 // Insert into the live set 613 obj := newObject(s, addr, *data) 614 objs = append(objs, obj) 615 } 616 // Do not enable this feature when snapshot is not enabled. 617 } 618 return objs 619 } 620 621 // getDeletedStateObject is similar to getStateObject, but instead of returning 622 // nil for a deleted state object, it returns the actual object with the deleted 623 // flag set. This is needed by the state journal to revert to the correct s- 624 // destructed object instead of wiping all knowledge about the state object. 625 func (s *StateDB) getDeletedStateObject(addr common.Address) *StateObject { 626 // Prefer live objects if any is available 627 if obj := s.stateObjects[addr]; obj != nil { 628 return obj 629 } 630 // If no live objects are available, attempt to use snapshots 631 var ( 632 data *Account 633 err error 634 ) 635 if s.snap != nil { 636 if metrics.EnabledExpensive { 637 defer func(start time.Time) { s.SnapshotAccountReads += time.Since(start) }(time.Now()) 638 } 639 var acc *snapshot.Account 640 if acc, err = s.snap.Account(crypto.HashData(s.hasher, addr.Bytes())); err == nil { 641 if acc == nil { 642 return nil 643 } 644 data = &Account{ 645 Nonce: acc.Nonce, 646 Balance: acc.Balance, 647 CodeHash: acc.CodeHash, 648 Root: common.BytesToHash(acc.Root), 649 } 650 if len(data.CodeHash) == 0 { 651 data.CodeHash = emptyCodeHash 652 } 653 if data.Root == (common.Hash{}) { 654 data.Root = emptyRoot 655 } 656 } 657 } 658 // If snapshot unavailable or reading from it failed, load from the database 659 if s.snap == nil || err != nil { 660 if s.trie == nil { 661 tr, err := s.db.OpenTrie(s.originalRoot) 662 if err != nil { 663 s.setError(fmt.Errorf("failed to open trie tree")) 664 return nil 665 } 666 s.trie = tr 667 } 668 if metrics.EnabledExpensive { 669 defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now()) 670 } 671 enc, err := s.trie.TryGet(addr.Bytes()) 672 if err != nil { 673 s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %v", addr.Bytes(), err)) 674 return nil 675 } 676 if len(enc) == 0 { 677 return nil 678 } 679 data = new(Account) 680 if err := rlp.DecodeBytes(enc, data); err != nil { 681 log.Error("Failed to decode state object", "addr", addr, "err", err) 682 return nil 683 } 684 } 685 // Insert into the live set 686 obj := newObject(s, addr, *data) 687 s.SetStateObject(obj) 688 return obj 689 } 690 691 func (s *StateDB) SetStateObject(object *StateObject) { 692 s.stateObjects[object.Address()] = object 693 } 694 695 // GetOrNewStateObject retrieves a state object or create a new state object if nil. 696 func (s *StateDB) GetOrNewStateObject(addr common.Address) *StateObject { 697 stateObject := s.getStateObject(addr) 698 if stateObject == nil { 699 stateObject, _ = s.createObject(addr) 700 } 701 return stateObject 702 } 703 704 // createObject creates a new state object. If there is an existing account with 705 // the given address, it is overwritten and returned as the second return value. 706 func (s *StateDB) createObject(addr common.Address) (newobj, prev *StateObject) { 707 prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that! 708 709 var prevdestruct bool 710 if s.snap != nil && prev != nil { 711 _, prevdestruct = s.snapDestructs[prev.address] 712 if !prevdestruct { 713 s.snapDestructs[prev.address] = struct{}{} 714 } 715 } 716 newobj = newObject(s, addr, Account{}) 717 newobj.setNonce(0) // sets the object to dirty 718 if prev == nil { 719 s.journal.append(createObjectChange{account: &addr}) 720 } else { 721 s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct}) 722 } 723 s.SetStateObject(newobj) 724 if prev != nil && !prev.deleted { 725 return newobj, prev 726 } 727 return newobj, nil 728 } 729 730 // CreateAccount explicitly creates a state object. If a state object with the address 731 // already exists the balance is carried over to the new account. 732 // 733 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 734 // a contract does the following: 735 // 736 // 1. sends funds to sha(account ++ (nonce + 1)) 737 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 738 // 739 // Carrying over the balance ensures that Ether doesn't disappear. 740 func (s *StateDB) CreateAccount(addr common.Address) { 741 newObj, prev := s.createObject(addr) 742 if prev != nil { 743 newObj.setBalance(prev.data.Balance) 744 } 745 } 746 747 func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error { 748 so := db.getStateObject(addr) 749 if so == nil { 750 return nil 751 } 752 it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) 753 754 for it.Next() { 755 key := common.BytesToHash(db.trie.GetKey(it.Key)) 756 if value, dirty := so.dirtyStorage[key]; dirty { 757 if !cb(key, value) { 758 return nil 759 } 760 continue 761 } 762 763 if len(it.Value) > 0 { 764 _, content, _, err := rlp.Split(it.Value) 765 if err != nil { 766 return err 767 } 768 if !cb(key, common.BytesToHash(content)) { 769 return nil 770 } 771 } 772 } 773 return nil 774 } 775 776 // Copy creates a deep, independent copy of the state. 777 // Snapshots of the copied state cannot be applied to the copy. 778 func (s *StateDB) Copy() *StateDB { 779 // Copy all the basic fields, initialize the memory ones 780 state := &StateDB{ 781 db: s.db, 782 trie: s.db.CopyTrie(s.trie), 783 stateObjects: make(map[common.Address]*StateObject, len(s.journal.dirties)), 784 stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)), 785 stateObjectsDirty: make(map[common.Address]struct{}, len(s.journal.dirties)), 786 refund: s.refund, 787 logs: make(map[common.Hash][]*types.Log, len(s.logs)), 788 logSize: s.logSize, 789 preimages: make(map[common.Hash][]byte, len(s.preimages)), 790 journal: newJournal(), 791 hasher: crypto.NewKeccakState(), 792 } 793 // Copy the dirty states, logs, and preimages 794 for addr := range s.journal.dirties { 795 // As documented [here](https://github.com/phillinzzz/newBsc/pull/16485#issuecomment-380438527), 796 // and in the Finalise-method, there is a case where an object is in the journal but not 797 // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for 798 // nil 799 if object, exist := s.stateObjects[addr]; exist { 800 // Even though the original object is dirty, we are not copying the journal, 801 // so we need to make sure that anyside effect the journal would have caused 802 // during a commit (or similar op) is already applied to the copy. 803 state.stateObjects[addr] = object.deepCopy(state) 804 805 state.stateObjectsDirty[addr] = struct{}{} // Mark the copy dirty to force internal (code/state) commits 806 state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits 807 } 808 } 809 // Above, we don't copy the actual journal. This means that if the copy is copied, the 810 // loop above will be a no-op, since the copy's journal is empty. 811 // Thus, here we iterate over stateObjects, to enable copies of copies 812 for addr := range s.stateObjectsPending { 813 if _, exist := state.stateObjects[addr]; !exist { 814 state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state) 815 } 816 state.stateObjectsPending[addr] = struct{}{} 817 } 818 for addr := range s.stateObjectsDirty { 819 if _, exist := state.stateObjects[addr]; !exist { 820 state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state) 821 } 822 state.stateObjectsDirty[addr] = struct{}{} 823 } 824 for hash, logs := range s.logs { 825 cpy := make([]*types.Log, len(logs)) 826 for i, l := range logs { 827 cpy[i] = new(types.Log) 828 *cpy[i] = *l 829 } 830 state.logs[hash] = cpy 831 } 832 for hash, preimage := range s.preimages { 833 state.preimages[hash] = preimage 834 } 835 // Do we need to copy the access list? In practice: No. At the start of a 836 // transaction, the access list is empty. In practice, we only ever copy state 837 // _between_ transactions/blocks, never in the middle of a transaction. 838 // However, it doesn't cost us much to copy an empty list, so we do it anyway 839 // to not blow up if we ever decide copy it in the middle of a transaction 840 if s.accessList != nil { 841 state.accessList = s.accessList.Copy() 842 } 843 844 // If there's a prefetcher running, make an inactive copy of it that can 845 // only access data but does not actively preload (since the user will not 846 // know that they need to explicitly terminate an active copy). 847 if s.prefetcher != nil { 848 state.prefetcher = s.prefetcher.copy() 849 } 850 if s.snaps != nil { 851 // In order for the miner to be able to use and make additions 852 // to the snapshot tree, we need to copy that aswell. 853 // Otherwise, any block mined by ourselves will cause gaps in the tree, 854 // and force the miner to operate trie-backed only 855 state.snaps = s.snaps 856 state.snap = s.snap 857 // deep copy needed 858 state.snapDestructs = make(map[common.Address]struct{}) 859 for k, v := range s.snapDestructs { 860 state.snapDestructs[k] = v 861 } 862 state.snapAccounts = make(map[common.Address][]byte) 863 for k, v := range s.snapAccounts { 864 state.snapAccounts[k] = v 865 } 866 state.snapStorage = make(map[common.Address]map[string][]byte) 867 for k, v := range s.snapStorage { 868 temp := make(map[string][]byte) 869 for kk, vv := range v { 870 temp[kk] = vv 871 } 872 state.snapStorage[k] = temp 873 } 874 } 875 return state 876 } 877 878 // Snapshot returns an identifier for the current revision of the state. 879 func (s *StateDB) Snapshot() int { 880 id := s.nextRevisionId 881 s.nextRevisionId++ 882 s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()}) 883 return id 884 } 885 886 // RevertToSnapshot reverts all state changes made since the given revision. 887 func (s *StateDB) RevertToSnapshot(revid int) { 888 // Find the snapshot in the stack of valid snapshots. 889 idx := sort.Search(len(s.validRevisions), func(i int) bool { 890 return s.validRevisions[i].id >= revid 891 }) 892 if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid { 893 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 894 } 895 snapshot := s.validRevisions[idx].journalIndex 896 897 // Replay the journal to undo changes and remove invalidated snapshots 898 s.journal.revert(s, snapshot) 899 s.validRevisions = s.validRevisions[:idx] 900 } 901 902 // GetRefund returns the current value of the refund counter. 903 func (s *StateDB) GetRefund() uint64 { 904 return s.refund 905 } 906 907 // Finalise finalises the state by removing the s destructed objects and clears 908 // the journal as well as the refunds. Finalise, however, will not push any updates 909 // into the tries just yet. Only IntermediateRoot or Commit will do that. 910 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 911 addressesToPrefetch := make([][]byte, 0, len(s.journal.dirties)) 912 for addr := range s.journal.dirties { 913 obj, exist := s.stateObjects[addr] 914 if !exist { 915 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 916 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 917 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 918 // it will persist in the journal even though the journal is reverted. In this special circumstance, 919 // it may exist in `s.journal.dirties` but not in `s.stateObjects`. 920 // Thus, we can safely ignore it here 921 continue 922 } 923 if obj.suicided || (deleteEmptyObjects && obj.empty()) { 924 obj.deleted = true 925 926 // If state snapshotting is active, also mark the destruction there. 927 // Note, we can't do this only at the end of a block because multiple 928 // transactions within the same block might self destruct and then 929 // ressurrect an account; but the snapshotter needs both events. 930 if s.snap != nil { 931 s.snapDestructs[obj.address] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely) 932 delete(s.snapAccounts, obj.address) // Clear out any previously updated account data (may be recreated via a ressurrect) 933 delete(s.snapStorage, obj.address) // Clear out any previously updated storage data (may be recreated via a ressurrect) 934 } 935 } else { 936 obj.finalise(true) // Prefetch slots in the background 937 } 938 if _, exist := s.stateObjectsPending[addr]; !exist { 939 s.stateObjectsPending[addr] = struct{}{} 940 } 941 if _, exist := s.stateObjectsDirty[addr]; !exist { 942 s.stateObjectsDirty[addr] = struct{}{} 943 // At this point, also ship the address off to the precacher. The precacher 944 // will start loading tries, and when the change is eventually committed, 945 // the commit-phase will be a lot faster 946 addressesToPrefetch = append(addressesToPrefetch, common.CopyBytes(addr[:])) // Copy needed for closure 947 } 948 } 949 if s.prefetcher != nil && len(addressesToPrefetch) > 0 { 950 s.prefetcher.prefetch(s.originalRoot, addressesToPrefetch, emptyAddr) 951 } 952 // Invalidate journal because reverting across transactions is not allowed. 953 s.clearJournalAndRefund() 954 } 955 956 // IntermediateRoot computes the current root hash of the state trie. 957 // It is called in between transactions to get the root hash that 958 // goes into transaction receipts. 959 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 960 if s.lightProcessed { 961 return s.trie.Hash() 962 } 963 // Finalise all the dirty storage states and write them into the tries 964 s.Finalise(deleteEmptyObjects) 965 966 // If there was a trie prefetcher operating, it gets aborted and irrevocably 967 // modified after we start retrieving tries. Remove it from the statedb after 968 // this round of use. 969 // 970 // This is weird pre-byzantium since the first tx runs with a prefetcher and 971 // the remainder without, but pre-byzantium even the initial prefetcher is 972 // useless, so no sleep lost. 973 prefetcher := s.prefetcher 974 if s.prefetcher != nil { 975 defer func() { 976 s.prefetcher.close() 977 s.prefetcher = nil 978 }() 979 } 980 981 tasks := make(chan func()) 982 finishCh := make(chan struct{}) 983 defer close(finishCh) 984 wg := sync.WaitGroup{} 985 for i := 0; i < runtime.NumCPU(); i++ { 986 go func() { 987 for { 988 select { 989 case task := <-tasks: 990 task() 991 case <-finishCh: 992 return 993 } 994 } 995 }() 996 } 997 // Although naively it makes sense to retrieve the account trie and then do 998 // the contract storage and account updates sequentially, that short circuits 999 // the account prefetcher. Instead, let's process all the storage updates 1000 // first, giving the account prefeches just a few more milliseconds of time 1001 // to pull useful data from disk. 1002 for addr := range s.stateObjectsPending { 1003 if obj := s.stateObjects[addr]; !obj.deleted { 1004 wg.Add(1) 1005 tasks <- func() { 1006 obj.updateRoot(s.db) 1007 1008 // If state snapshotting is active, cache the data til commit. Note, this 1009 // update mechanism is not symmetric to the deletion, because whereas it is 1010 // enough to track account updates at commit time, deletions need tracking 1011 // at transaction boundary level to ensure we capture state clearing. 1012 if s.snap != nil && !obj.deleted { 1013 s.snapMux.Lock() 1014 // It is possible to add unnecessary change, but it is fine. 1015 s.snapAccounts[obj.address] = snapshot.SlimAccountRLP(obj.data.Nonce, obj.data.Balance, obj.data.Root, obj.data.CodeHash) 1016 s.snapMux.Unlock() 1017 } 1018 data, err := rlp.EncodeToBytes(obj) 1019 if err != nil { 1020 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 1021 } 1022 obj.encodeData = data 1023 wg.Done() 1024 } 1025 } 1026 } 1027 wg.Wait() 1028 // Now we're about to start to write changes to the trie. The trie is so far 1029 // _untouched_. We can check with the prefetcher, if it can give us a trie 1030 // which has the same root, but also has some content loaded into it. 1031 if prefetcher != nil { 1032 if trie := prefetcher.trie(s.originalRoot); trie != nil { 1033 s.trie = trie 1034 } 1035 } 1036 if s.trie == nil { 1037 tr, err := s.db.OpenTrie(s.originalRoot) 1038 if err != nil { 1039 panic("Failed to open trie tree") 1040 } 1041 s.trie = tr 1042 } 1043 usedAddrs := make([][]byte, 0, len(s.stateObjectsPending)) 1044 for addr := range s.stateObjectsPending { 1045 if obj := s.stateObjects[addr]; obj.deleted { 1046 s.deleteStateObject(obj) 1047 } else { 1048 s.updateStateObject(obj) 1049 } 1050 usedAddrs = append(usedAddrs, common.CopyBytes(addr[:])) // Copy needed for closure 1051 } 1052 if prefetcher != nil { 1053 prefetcher.used(s.originalRoot, usedAddrs) 1054 } 1055 if len(s.stateObjectsPending) > 0 { 1056 s.stateObjectsPending = make(map[common.Address]struct{}) 1057 } 1058 // Track the amount of time wasted on hashing the account trie 1059 if metrics.EnabledExpensive { 1060 defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now()) 1061 } 1062 root := s.trie.Hash() 1063 return root 1064 } 1065 1066 // Prepare sets the current transaction hash and index and block hash which is 1067 // used when the EVM emits new state logs. 1068 func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) { 1069 s.thash = thash 1070 s.bhash = bhash 1071 s.txIndex = ti 1072 s.accessList = nil 1073 } 1074 1075 func (s *StateDB) clearJournalAndRefund() { 1076 if len(s.journal.entries) > 0 { 1077 s.journal = newJournal() 1078 s.refund = 0 1079 } 1080 s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires 1081 } 1082 1083 func (s *StateDB) LightCommit(root common.Hash) (common.Hash, *types.DiffLayer, error) { 1084 codeWriter := s.db.TrieDB().DiskDB().NewBatch() 1085 1086 commitFuncs := []func() error{ 1087 func() error { 1088 for codeHash, code := range s.diffCode { 1089 rawdb.WriteCode(codeWriter, codeHash, code) 1090 if codeWriter.ValueSize() >= ethdb.IdealBatchSize { 1091 if err := codeWriter.Write(); err != nil { 1092 return err 1093 } 1094 codeWriter.Reset() 1095 } 1096 } 1097 if codeWriter.ValueSize() > 0 { 1098 if err := codeWriter.Write(); err != nil { 1099 return err 1100 } 1101 } 1102 return nil 1103 }, 1104 func() error { 1105 tasks := make(chan func()) 1106 taskResults := make(chan error, len(s.diffTries)) 1107 tasksNum := 0 1108 finishCh := make(chan struct{}) 1109 defer close(finishCh) 1110 threads := gopool.Threads(len(s.diffTries)) 1111 1112 for i := 0; i < threads; i++ { 1113 go func() { 1114 for { 1115 select { 1116 case task := <-tasks: 1117 task() 1118 case <-finishCh: 1119 return 1120 } 1121 } 1122 }() 1123 } 1124 1125 for account, diff := range s.diffTries { 1126 tmpAccount := account 1127 tmpDiff := diff 1128 tasks <- func() { 1129 root, err := tmpDiff.Commit(nil) 1130 if err != nil { 1131 taskResults <- err 1132 return 1133 } 1134 s.db.CacheStorage(crypto.Keccak256Hash(tmpAccount[:]), root, tmpDiff) 1135 taskResults <- nil 1136 } 1137 tasksNum++ 1138 } 1139 1140 for i := 0; i < tasksNum; i++ { 1141 err := <-taskResults 1142 if err != nil { 1143 return err 1144 } 1145 } 1146 1147 // commit account trie 1148 var account Account 1149 root, err := s.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash) error { 1150 if err := rlp.DecodeBytes(leaf, &account); err != nil { 1151 return nil 1152 } 1153 if account.Root != emptyRoot { 1154 s.db.TrieDB().Reference(account.Root, parent) 1155 } 1156 return nil 1157 }) 1158 if err != nil { 1159 return err 1160 } 1161 if root != emptyRoot { 1162 s.db.CacheAccount(root, s.trie) 1163 } 1164 return nil 1165 }, 1166 func() error { 1167 if s.snap != nil { 1168 if metrics.EnabledExpensive { 1169 defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now()) 1170 } 1171 // Only update if there's a state transition (skip empty Clique blocks) 1172 if parent := s.snap.Root(); parent != root { 1173 if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil { 1174 log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err) 1175 } 1176 // Keep n diff layers in the memory 1177 // - head layer is paired with HEAD state 1178 // - head-1 layer is paired with HEAD-1 state 1179 // - head-(n-1) layer(bottom-most diff layer) is paired with HEAD-(n-1)state 1180 if err := s.snaps.Cap(root, s.snaps.CapLimit()); err != nil { 1181 log.Warn("Failed to cap snapshot tree", "root", root, "layers", s.snaps.CapLimit(), "err", err) 1182 } 1183 } 1184 } 1185 return nil 1186 }, 1187 } 1188 commitRes := make(chan error, len(commitFuncs)) 1189 for _, f := range commitFuncs { 1190 tmpFunc := f 1191 go func() { 1192 commitRes <- tmpFunc() 1193 }() 1194 } 1195 for i := 0; i < len(commitFuncs); i++ { 1196 r := <-commitRes 1197 if r != nil { 1198 return common.Hash{}, nil, r 1199 } 1200 } 1201 s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil 1202 s.diffTries, s.diffCode = nil, nil 1203 return root, s.diffLayer, nil 1204 } 1205 1206 // Commit writes the state to the underlying in-memory trie database. 1207 func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, *types.DiffLayer, error) { 1208 if s.dbErr != nil { 1209 return common.Hash{}, nil, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr) 1210 } 1211 // Finalize any pending changes and merge everything into the tries 1212 root := s.IntermediateRoot(deleteEmptyObjects) 1213 if s.lightProcessed { 1214 return s.LightCommit(root) 1215 } 1216 var diffLayer *types.DiffLayer 1217 if s.snap != nil { 1218 diffLayer = &types.DiffLayer{} 1219 } 1220 commitFuncs := []func() error{ 1221 func() error { 1222 // Commit objects to the trie, measuring the elapsed time 1223 tasks := make(chan func(batch ethdb.KeyValueWriter)) 1224 taskResults := make(chan error, len(s.stateObjectsDirty)) 1225 tasksNum := 0 1226 finishCh := make(chan struct{}) 1227 1228 threads := gopool.Threads(len(s.stateObjectsDirty)) 1229 wg := sync.WaitGroup{} 1230 for i := 0; i < threads; i++ { 1231 wg.Add(1) 1232 go func() { 1233 defer wg.Done() 1234 codeWriter := s.db.TrieDB().DiskDB().NewBatch() 1235 for { 1236 select { 1237 case task := <-tasks: 1238 task(codeWriter) 1239 case <-finishCh: 1240 if codeWriter.ValueSize() > 0 { 1241 if err := codeWriter.Write(); err != nil { 1242 log.Crit("Failed to commit dirty codes", "error", err) 1243 } 1244 } 1245 return 1246 } 1247 } 1248 }() 1249 } 1250 1251 if s.snap != nil { 1252 for addr := range s.stateObjectsDirty { 1253 if obj := s.stateObjects[addr]; !obj.deleted { 1254 if obj.code != nil && obj.dirtyCode { 1255 diffLayer.Codes = append(diffLayer.Codes, types.DiffCode{ 1256 Hash: common.BytesToHash(obj.CodeHash()), 1257 Code: obj.code, 1258 }) 1259 } 1260 } 1261 } 1262 } 1263 1264 for addr := range s.stateObjectsDirty { 1265 if obj := s.stateObjects[addr]; !obj.deleted { 1266 // Write any contract code associated with the state object 1267 tasks <- func(codeWriter ethdb.KeyValueWriter) { 1268 if obj.code != nil && obj.dirtyCode { 1269 rawdb.WriteCode(codeWriter, common.BytesToHash(obj.CodeHash()), obj.code) 1270 obj.dirtyCode = false 1271 } 1272 // Write any storage changes in the state object to its storage trie 1273 if err := obj.CommitTrie(s.db); err != nil { 1274 taskResults <- err 1275 } 1276 taskResults <- nil 1277 } 1278 tasksNum++ 1279 } 1280 } 1281 1282 for i := 0; i < tasksNum; i++ { 1283 err := <-taskResults 1284 if err != nil { 1285 close(finishCh) 1286 return err 1287 } 1288 } 1289 close(finishCh) 1290 1291 if len(s.stateObjectsDirty) > 0 { 1292 s.stateObjectsDirty = make(map[common.Address]struct{}, len(s.stateObjectsDirty)/2) 1293 } 1294 // Write the account trie changes, measuing the amount of wasted time 1295 var start time.Time 1296 if metrics.EnabledExpensive { 1297 start = time.Now() 1298 } 1299 // The onleaf func is called _serially_, so we can reuse the same account 1300 // for unmarshalling every time. 1301 var account Account 1302 root, err := s.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash) error { 1303 if err := rlp.DecodeBytes(leaf, &account); err != nil { 1304 return nil 1305 } 1306 if account.Root != emptyRoot { 1307 s.db.TrieDB().Reference(account.Root, parent) 1308 } 1309 return nil 1310 }) 1311 if err != nil { 1312 return err 1313 } 1314 if metrics.EnabledExpensive { 1315 s.AccountCommits += time.Since(start) 1316 } 1317 if root != emptyRoot { 1318 s.db.CacheAccount(root, s.trie) 1319 } 1320 wg.Wait() 1321 return nil 1322 }, 1323 func() error { 1324 // If snapshotting is enabled, update the snapshot tree with this new version 1325 if s.snap != nil { 1326 if metrics.EnabledExpensive { 1327 defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now()) 1328 } 1329 // Only update if there's a state transition (skip empty Clique blocks) 1330 if parent := s.snap.Root(); parent != root { 1331 if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil { 1332 log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err) 1333 } 1334 // Keep n diff layers in the memory 1335 // - head layer is paired with HEAD state 1336 // - head-1 layer is paired with HEAD-1 state 1337 // - head-(n-1) layer(bottom-most diff layer) is paired with HEAD-(n-1)state 1338 if err := s.snaps.Cap(root, s.snaps.CapLimit()); err != nil { 1339 log.Warn("Failed to cap snapshot tree", "root", root, "layers", s.snaps.CapLimit(), "err", err) 1340 } 1341 } 1342 } 1343 return nil 1344 }, 1345 func() error { 1346 if s.snap != nil { 1347 diffLayer.Destructs, diffLayer.Accounts, diffLayer.Storages = s.SnapToDiffLayer() 1348 } 1349 return nil 1350 }, 1351 } 1352 commitRes := make(chan error, len(commitFuncs)) 1353 for _, f := range commitFuncs { 1354 tmpFunc := f 1355 go func() { 1356 commitRes <- tmpFunc() 1357 }() 1358 } 1359 for i := 0; i < len(commitFuncs); i++ { 1360 r := <-commitRes 1361 if r != nil { 1362 return common.Hash{}, nil, r 1363 } 1364 } 1365 s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil 1366 return root, diffLayer, nil 1367 } 1368 1369 func (s *StateDB) DiffLayerToSnap(diffLayer *types.DiffLayer) (map[common.Address]struct{}, map[common.Address][]byte, map[common.Address]map[string][]byte, error) { 1370 snapDestructs := make(map[common.Address]struct{}) 1371 snapAccounts := make(map[common.Address][]byte) 1372 snapStorage := make(map[common.Address]map[string][]byte) 1373 1374 for _, des := range diffLayer.Destructs { 1375 snapDestructs[des] = struct{}{} 1376 } 1377 for _, account := range diffLayer.Accounts { 1378 snapAccounts[account.Account] = account.Blob 1379 } 1380 for _, storage := range diffLayer.Storages { 1381 // should never happen 1382 if len(storage.Keys) != len(storage.Vals) { 1383 return nil, nil, nil, errors.New("invalid diffLayer: length of keys and values mismatch") 1384 } 1385 snapStorage[storage.Account] = make(map[string][]byte, len(storage.Keys)) 1386 n := len(storage.Keys) 1387 for i := 0; i < n; i++ { 1388 snapStorage[storage.Account][storage.Keys[i]] = storage.Vals[i] 1389 } 1390 } 1391 return snapDestructs, snapAccounts, snapStorage, nil 1392 } 1393 1394 func (s *StateDB) SnapToDiffLayer() ([]common.Address, []types.DiffAccount, []types.DiffStorage) { 1395 destructs := make([]common.Address, 0, len(s.snapDestructs)) 1396 for account := range s.snapDestructs { 1397 destructs = append(destructs, account) 1398 } 1399 accounts := make([]types.DiffAccount, 0, len(s.snapAccounts)) 1400 for accountHash, account := range s.snapAccounts { 1401 accounts = append(accounts, types.DiffAccount{ 1402 Account: accountHash, 1403 Blob: account, 1404 }) 1405 } 1406 storages := make([]types.DiffStorage, 0, len(s.snapStorage)) 1407 for accountHash, storage := range s.snapStorage { 1408 keys := make([]string, 0, len(storage)) 1409 values := make([][]byte, 0, len(storage)) 1410 for k, v := range storage { 1411 keys = append(keys, k) 1412 values = append(values, v) 1413 } 1414 storages = append(storages, types.DiffStorage{ 1415 Account: accountHash, 1416 Keys: keys, 1417 Vals: values, 1418 }) 1419 } 1420 return destructs, accounts, storages 1421 } 1422 1423 // PrepareAccessList handles the preparatory steps for executing a state transition with 1424 // regards to both EIP-2929 and EIP-2930: 1425 // 1426 // - Add sender to access list (2929) 1427 // - Add destination to access list (2929) 1428 // - Add precompiles to access list (2929) 1429 // - Add the contents of the optional tx access list (2930) 1430 // 1431 // This method should only be called if Yolov3/Berlin/2929+2930 is applicable at the current number. 1432 func (s *StateDB) PrepareAccessList(sender common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) { 1433 s.AddAddressToAccessList(sender) 1434 if dst != nil { 1435 s.AddAddressToAccessList(*dst) 1436 // If it's a create-tx, the destination will be added inside evm.create 1437 } 1438 for _, addr := range precompiles { 1439 s.AddAddressToAccessList(addr) 1440 } 1441 for _, el := range list { 1442 s.AddAddressToAccessList(el.Address) 1443 for _, key := range el.StorageKeys { 1444 s.AddSlotToAccessList(el.Address, key) 1445 } 1446 } 1447 } 1448 1449 // AddAddressToAccessList adds the given address to the access list 1450 func (s *StateDB) AddAddressToAccessList(addr common.Address) { 1451 if s.accessList == nil { 1452 s.accessList = newAccessList() 1453 } 1454 if s.accessList.AddAddress(addr) { 1455 s.journal.append(accessListAddAccountChange{&addr}) 1456 } 1457 } 1458 1459 // AddSlotToAccessList adds the given (address, slot)-tuple to the access list 1460 func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) { 1461 if s.accessList == nil { 1462 s.accessList = newAccessList() 1463 } 1464 addrMod, slotMod := s.accessList.AddSlot(addr, slot) 1465 if addrMod { 1466 // In practice, this should not happen, since there is no way to enter the 1467 // scope of 'address' without having the 'address' become already added 1468 // to the access list (via call-variant, create, etc). 1469 // Better safe than sorry, though 1470 s.journal.append(accessListAddAccountChange{&addr}) 1471 } 1472 if slotMod { 1473 s.journal.append(accessListAddSlotChange{ 1474 address: &addr, 1475 slot: &slot, 1476 }) 1477 } 1478 } 1479 1480 // AddressInAccessList returns true if the given address is in the access list. 1481 func (s *StateDB) AddressInAccessList(addr common.Address) bool { 1482 if s.accessList == nil { 1483 return false 1484 } 1485 return s.accessList.ContainsAddress(addr) 1486 } 1487 1488 // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list. 1489 func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) { 1490 if s.accessList == nil { 1491 return false, false 1492 } 1493 return s.accessList.Contains(addr, slot) 1494 }