github.com/ethereum/go-ethereum@v1.16.1/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 "maps" 24 "slices" 25 "sync" 26 "sync/atomic" 27 "time" 28 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/core/rawdb" 31 "github.com/ethereum/go-ethereum/core/state/snapshot" 32 "github.com/ethereum/go-ethereum/core/stateless" 33 "github.com/ethereum/go-ethereum/core/tracing" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/crypto" 36 "github.com/ethereum/go-ethereum/log" 37 "github.com/ethereum/go-ethereum/params" 38 "github.com/ethereum/go-ethereum/trie" 39 "github.com/ethereum/go-ethereum/trie/trienode" 40 "github.com/ethereum/go-ethereum/trie/utils" 41 "github.com/holiman/uint256" 42 "golang.org/x/sync/errgroup" 43 ) 44 45 // TriesInMemory represents the number of layers that are kept in RAM. 46 const TriesInMemory = 128 47 48 type mutationType int 49 50 const ( 51 update mutationType = iota 52 deletion 53 ) 54 55 type mutation struct { 56 typ mutationType 57 applied bool 58 } 59 60 func (m *mutation) copy() *mutation { 61 return &mutation{typ: m.typ, applied: m.applied} 62 } 63 64 func (m *mutation) isDelete() bool { 65 return m.typ == deletion 66 } 67 68 // StateDB structs within the ethereum protocol are used to store anything 69 // within the merkle trie. StateDBs take care of caching and storing 70 // nested states. It's the general query interface to retrieve: 71 // 72 // * Contracts 73 // * Accounts 74 // 75 // Once the state is committed, tries cached in stateDB (including account 76 // trie, storage tries) will no longer be functional. A new state instance 77 // must be created with new root and updated database for accessing post- 78 // commit states. 79 type StateDB struct { 80 db Database 81 prefetcher *triePrefetcher 82 reader Reader 83 trie Trie // it's resolved on first access 84 85 // originalRoot is the pre-state root, before any changes were made. 86 // It will be updated when the Commit is called. 87 originalRoot common.Hash 88 89 // This map holds 'live' objects, which will get modified while 90 // processing a state transition. 91 stateObjects map[common.Address]*stateObject 92 93 // This map holds 'deleted' objects. An object with the same address 94 // might also occur in the 'stateObjects' map due to account 95 // resurrection. The account value is tracked as the original value 96 // before the transition. This map is populated at the transaction 97 // boundaries. 98 stateObjectsDestruct map[common.Address]*stateObject 99 100 // This map tracks the account mutations that occurred during the 101 // transition. Uncommitted mutations belonging to the same account 102 // can be merged into a single one which is equivalent from database's 103 // perspective. This map is populated at the transaction boundaries. 104 mutations map[common.Address]*mutation 105 106 // DB error. 107 // State objects are used by the consensus core and VM which are 108 // unable to deal with database-level errors. Any error that occurs 109 // during a database read is memoized here and will eventually be 110 // returned by StateDB.Commit. Notably, this error is also shared 111 // by all cached state objects in case the database failure occurs 112 // when accessing state of accounts. 113 dbErr error 114 115 // The refund counter, also used by state transitioning. 116 refund uint64 117 118 // The tx context and all occurred logs in the scope of transaction. 119 thash common.Hash 120 txIndex int 121 logs map[common.Hash][]*types.Log 122 logSize uint 123 124 // Preimages occurred seen by VM in the scope of block. 125 preimages map[common.Hash][]byte 126 127 // Per-transaction access list 128 accessList *accessList 129 accessEvents *AccessEvents 130 131 // Transient storage 132 transientStorage transientStorage 133 134 // Journal of state modifications. This is the backbone of 135 // Snapshot and RevertToSnapshot. 136 journal *journal 137 138 // State witness if cross validation is needed 139 witness *stateless.Witness 140 141 // Measurements gathered during execution for debugging purposes 142 AccountReads time.Duration 143 AccountHashes time.Duration 144 AccountUpdates time.Duration 145 AccountCommits time.Duration 146 StorageReads time.Duration 147 StorageUpdates time.Duration 148 StorageCommits time.Duration 149 SnapshotCommits time.Duration 150 TrieDBCommits time.Duration 151 152 AccountLoaded int // Number of accounts retrieved from the database during the state transition 153 AccountUpdated int // Number of accounts updated during the state transition 154 AccountDeleted int // Number of accounts deleted during the state transition 155 StorageLoaded int // Number of storage slots retrieved from the database during the state transition 156 StorageUpdated atomic.Int64 // Number of storage slots updated during the state transition 157 StorageDeleted atomic.Int64 // Number of storage slots deleted during the state transition 158 } 159 160 // New creates a new state from a given trie. 161 func New(root common.Hash, db Database) (*StateDB, error) { 162 reader, err := db.Reader(root) 163 if err != nil { 164 return nil, err 165 } 166 return NewWithReader(root, db, reader) 167 } 168 169 // NewWithReader creates a new state for the specified state root. Unlike New, 170 // this function accepts an additional Reader which is bound to the given root. 171 func NewWithReader(root common.Hash, db Database, reader Reader) (*StateDB, error) { 172 sdb := &StateDB{ 173 db: db, 174 originalRoot: root, 175 reader: reader, 176 stateObjects: make(map[common.Address]*stateObject), 177 stateObjectsDestruct: make(map[common.Address]*stateObject), 178 mutations: make(map[common.Address]*mutation), 179 logs: make(map[common.Hash][]*types.Log), 180 preimages: make(map[common.Hash][]byte), 181 journal: newJournal(), 182 accessList: newAccessList(), 183 transientStorage: newTransientStorage(), 184 } 185 if db.TrieDB().IsVerkle() { 186 sdb.accessEvents = NewAccessEvents(db.PointCache()) 187 } 188 return sdb, nil 189 } 190 191 // StartPrefetcher initializes a new trie prefetcher to pull in nodes from the 192 // state trie concurrently while the state is mutated so that when we reach the 193 // commit phase, most of the needed data is already hot. 194 func (s *StateDB) StartPrefetcher(namespace string, witness *stateless.Witness) { 195 // Terminate any previously running prefetcher 196 s.StopPrefetcher() 197 198 // Enable witness collection if requested 199 s.witness = witness 200 201 // With the switch to the Proof-of-Stake consensus algorithm, block production 202 // rewards are now handled at the consensus layer. Consequently, a block may 203 // have no state transitions if it contains no transactions and no withdrawals. 204 // In such cases, the account trie won't be scheduled for prefetching, leading 205 // to unnecessary error logs. 206 // 207 // To prevent this, the account trie is always scheduled for prefetching once 208 // the prefetcher is constructed. For more details, see: 209 // https://github.com/ethereum/go-ethereum/issues/29880 210 s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace, witness == nil) 211 if err := s.prefetcher.prefetch(common.Hash{}, s.originalRoot, common.Address{}, nil, nil, false); err != nil { 212 log.Error("Failed to prefetch account trie", "root", s.originalRoot, "err", err) 213 } 214 } 215 216 // StopPrefetcher terminates a running prefetcher and reports any leftover stats 217 // from the gathered metrics. 218 func (s *StateDB) StopPrefetcher() { 219 if s.prefetcher != nil { 220 s.prefetcher.terminate(false) 221 s.prefetcher.report() 222 s.prefetcher = nil 223 } 224 } 225 226 // setError remembers the first non-nil error it is called with. 227 func (s *StateDB) setError(err error) { 228 if s.dbErr == nil { 229 s.dbErr = err 230 } 231 } 232 233 // Error returns the memorized database failure occurred earlier. 234 func (s *StateDB) Error() error { 235 return s.dbErr 236 } 237 238 func (s *StateDB) AddLog(log *types.Log) { 239 s.journal.logChange(s.thash) 240 241 log.TxHash = s.thash 242 log.TxIndex = uint(s.txIndex) 243 log.Index = s.logSize 244 s.logs[s.thash] = append(s.logs[s.thash], log) 245 s.logSize++ 246 } 247 248 // GetLogs returns the logs matching the specified transaction hash, and annotates 249 // them with the given blockNumber and blockHash. 250 func (s *StateDB) GetLogs(hash common.Hash, blockNumber uint64, blockHash common.Hash, blockTime uint64) []*types.Log { 251 logs := s.logs[hash] 252 for _, l := range logs { 253 l.BlockNumber = blockNumber 254 l.BlockHash = blockHash 255 l.BlockTimestamp = blockTime 256 } 257 return logs 258 } 259 260 func (s *StateDB) Logs() []*types.Log { 261 var logs []*types.Log 262 for _, lgs := range s.logs { 263 logs = append(logs, lgs...) 264 } 265 return logs 266 } 267 268 // AddPreimage records a SHA3 preimage seen by the VM. 269 func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 270 if _, ok := s.preimages[hash]; !ok { 271 s.preimages[hash] = slices.Clone(preimage) 272 } 273 } 274 275 // Preimages returns a list of SHA3 preimages that have been submitted. 276 func (s *StateDB) Preimages() map[common.Hash][]byte { 277 return s.preimages 278 } 279 280 // AddRefund adds gas to the refund counter 281 func (s *StateDB) AddRefund(gas uint64) { 282 s.journal.refundChange(s.refund) 283 s.refund += gas 284 } 285 286 // SubRefund removes gas from the refund counter. 287 // This method will panic if the refund counter goes below zero 288 func (s *StateDB) SubRefund(gas uint64) { 289 s.journal.refundChange(s.refund) 290 if gas > s.refund { 291 panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund)) 292 } 293 s.refund -= gas 294 } 295 296 // Exist reports whether the given account address exists in the state. 297 // Notably this also returns true for self-destructed accounts within the current transaction. 298 func (s *StateDB) Exist(addr common.Address) bool { 299 return s.getStateObject(addr) != nil 300 } 301 302 // Empty returns whether the state object is either non-existent 303 // or empty according to the EIP161 specification (balance = nonce = code = 0) 304 func (s *StateDB) Empty(addr common.Address) bool { 305 so := s.getStateObject(addr) 306 return so == nil || so.empty() 307 } 308 309 // GetBalance retrieves the balance from the given address or 0 if object not found 310 func (s *StateDB) GetBalance(addr common.Address) *uint256.Int { 311 stateObject := s.getStateObject(addr) 312 if stateObject != nil { 313 return stateObject.Balance() 314 } 315 return common.U2560 316 } 317 318 // GetNonce retrieves the nonce from the given address or 0 if object not found 319 func (s *StateDB) GetNonce(addr common.Address) uint64 { 320 stateObject := s.getStateObject(addr) 321 if stateObject != nil { 322 return stateObject.Nonce() 323 } 324 325 return 0 326 } 327 328 // GetStorageRoot retrieves the storage root from the given address or empty 329 // if object not found. 330 func (s *StateDB) GetStorageRoot(addr common.Address) common.Hash { 331 stateObject := s.getStateObject(addr) 332 if stateObject != nil { 333 return stateObject.Root() 334 } 335 return common.Hash{} 336 } 337 338 // TxIndex returns the current transaction index set by SetTxContext. 339 func (s *StateDB) TxIndex() int { 340 return s.txIndex 341 } 342 343 func (s *StateDB) GetCode(addr common.Address) []byte { 344 stateObject := s.getStateObject(addr) 345 if stateObject != nil { 346 if s.witness != nil { 347 s.witness.AddCode(stateObject.Code()) 348 } 349 return stateObject.Code() 350 } 351 return nil 352 } 353 354 func (s *StateDB) GetCodeSize(addr common.Address) int { 355 stateObject := s.getStateObject(addr) 356 if stateObject != nil { 357 if s.witness != nil { 358 s.witness.AddCode(stateObject.Code()) 359 } 360 return stateObject.CodeSize() 361 } 362 return 0 363 } 364 365 func (s *StateDB) GetCodeHash(addr common.Address) common.Hash { 366 stateObject := s.getStateObject(addr) 367 if stateObject != nil { 368 return common.BytesToHash(stateObject.CodeHash()) 369 } 370 return common.Hash{} 371 } 372 373 // GetState retrieves the value associated with the specific key. 374 func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { 375 stateObject := s.getStateObject(addr) 376 if stateObject != nil { 377 return stateObject.GetState(hash) 378 } 379 return common.Hash{} 380 } 381 382 // GetCommittedState retrieves the value associated with the specific key 383 // without any mutations caused in the current execution. 384 func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { 385 stateObject := s.getStateObject(addr) 386 if stateObject != nil { 387 return stateObject.GetCommittedState(hash) 388 } 389 return common.Hash{} 390 } 391 392 // Database retrieves the low level database supporting the lower level trie ops. 393 func (s *StateDB) Database() Database { 394 return s.db 395 } 396 397 // Reader retrieves the low level database reader supporting the 398 // lower level operations. 399 func (s *StateDB) Reader() Reader { 400 return s.reader 401 } 402 403 func (s *StateDB) HasSelfDestructed(addr common.Address) bool { 404 stateObject := s.getStateObject(addr) 405 if stateObject != nil { 406 return stateObject.selfDestructed 407 } 408 return false 409 } 410 411 /* 412 * SETTERS 413 */ 414 415 // AddBalance adds amount to the account associated with addr. 416 func (s *StateDB) AddBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) uint256.Int { 417 stateObject := s.getOrNewStateObject(addr) 418 if stateObject == nil { 419 return uint256.Int{} 420 } 421 return stateObject.AddBalance(amount) 422 } 423 424 // SubBalance subtracts amount from the account associated with addr. 425 func (s *StateDB) SubBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) uint256.Int { 426 stateObject := s.getOrNewStateObject(addr) 427 if stateObject == nil { 428 return uint256.Int{} 429 } 430 if amount.IsZero() { 431 return *(stateObject.Balance()) 432 } 433 return stateObject.SetBalance(new(uint256.Int).Sub(stateObject.Balance(), amount)) 434 } 435 436 func (s *StateDB) SetBalance(addr common.Address, amount *uint256.Int, reason tracing.BalanceChangeReason) { 437 stateObject := s.getOrNewStateObject(addr) 438 if stateObject != nil { 439 stateObject.SetBalance(amount) 440 } 441 } 442 443 func (s *StateDB) SetNonce(addr common.Address, nonce uint64, reason tracing.NonceChangeReason) { 444 stateObject := s.getOrNewStateObject(addr) 445 if stateObject != nil { 446 stateObject.SetNonce(nonce) 447 } 448 } 449 450 func (s *StateDB) SetCode(addr common.Address, code []byte) (prev []byte) { 451 stateObject := s.getOrNewStateObject(addr) 452 if stateObject != nil { 453 return stateObject.SetCode(crypto.Keccak256Hash(code), code) 454 } 455 return nil 456 } 457 458 func (s *StateDB) SetState(addr common.Address, key, value common.Hash) common.Hash { 459 if stateObject := s.getOrNewStateObject(addr); stateObject != nil { 460 return stateObject.SetState(key, value) 461 } 462 return common.Hash{} 463 } 464 465 // SetStorage replaces the entire storage for the specified account with given 466 // storage. This function should only be used for debugging and the mutations 467 // must be discarded afterwards. 468 func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) { 469 // SetStorage needs to wipe the existing storage. We achieve this by marking 470 // the account as self-destructed in this block. The effect is that storage 471 // lookups will not hit the disk, as it is assumed that the disk data belongs 472 // to a previous incarnation of the object. 473 // 474 // TODO (rjl493456442): This function should only be supported by 'unwritable' 475 // state, and all mutations made should be discarded afterward. 476 obj := s.getStateObject(addr) 477 if obj != nil { 478 if _, ok := s.stateObjectsDestruct[addr]; !ok { 479 s.stateObjectsDestruct[addr] = obj 480 } 481 } 482 newObj := s.createObject(addr) 483 for k, v := range storage { 484 newObj.SetState(k, v) 485 } 486 // Inherit the metadata of original object if it was existent 487 if obj != nil { 488 newObj.SetCode(common.BytesToHash(obj.CodeHash()), obj.code) 489 newObj.SetNonce(obj.Nonce()) 490 newObj.SetBalance(obj.Balance()) 491 } 492 } 493 494 // SelfDestruct marks the given account as selfdestructed. 495 // This clears the account balance. 496 // 497 // The account's state object is still available until the state is committed, 498 // getStateObject will return a non-nil account after SelfDestruct. 499 func (s *StateDB) SelfDestruct(addr common.Address) uint256.Int { 500 stateObject := s.getStateObject(addr) 501 var prevBalance uint256.Int 502 if stateObject == nil { 503 return prevBalance 504 } 505 prevBalance = *(stateObject.Balance()) 506 // Regardless of whether it is already destructed or not, we do have to 507 // journal the balance-change, if we set it to zero here. 508 if !stateObject.Balance().IsZero() { 509 stateObject.SetBalance(new(uint256.Int)) 510 } 511 // If it is already marked as self-destructed, we do not need to add it 512 // for journalling a second time. 513 if !stateObject.selfDestructed { 514 s.journal.destruct(addr) 515 stateObject.markSelfdestructed() 516 } 517 return prevBalance 518 } 519 520 func (s *StateDB) SelfDestruct6780(addr common.Address) (uint256.Int, bool) { 521 stateObject := s.getStateObject(addr) 522 if stateObject == nil { 523 return uint256.Int{}, false 524 } 525 if stateObject.newContract { 526 return s.SelfDestruct(addr), true 527 } 528 return *(stateObject.Balance()), false 529 } 530 531 // SetTransientState sets transient storage for a given account. It 532 // adds the change to the journal so that it can be rolled back 533 // to its previous value if there is a revert. 534 func (s *StateDB) SetTransientState(addr common.Address, key, value common.Hash) { 535 prev := s.GetTransientState(addr, key) 536 if prev == value { 537 return 538 } 539 s.journal.transientStateChange(addr, key, prev) 540 s.setTransientState(addr, key, value) 541 } 542 543 // setTransientState is a lower level setter for transient storage. It 544 // is called during a revert to prevent modifications to the journal. 545 func (s *StateDB) setTransientState(addr common.Address, key, value common.Hash) { 546 s.transientStorage.Set(addr, key, value) 547 } 548 549 // GetTransientState gets transient storage for a given account. 550 func (s *StateDB) GetTransientState(addr common.Address, key common.Hash) common.Hash { 551 return s.transientStorage.Get(addr, key) 552 } 553 554 // 555 // Setting, updating & deleting state object methods. 556 // 557 558 // updateStateObject writes the given object to the trie. 559 func (s *StateDB) updateStateObject(obj *stateObject) { 560 // Encode the account and update the account trie 561 if err := s.trie.UpdateAccount(obj.Address(), &obj.data, len(obj.code)); err != nil { 562 s.setError(fmt.Errorf("updateStateObject (%x) error: %v", obj.Address(), err)) 563 } 564 if obj.dirtyCode { 565 s.trie.UpdateContractCode(obj.Address(), common.BytesToHash(obj.CodeHash()), obj.code) 566 } 567 } 568 569 // deleteStateObject removes the given object from the state trie. 570 func (s *StateDB) deleteStateObject(addr common.Address) { 571 if err := s.trie.DeleteAccount(addr); err != nil { 572 s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err)) 573 } 574 } 575 576 // getStateObject retrieves a state object given by the address, returning nil if 577 // the object is not found or was deleted in this execution context. 578 func (s *StateDB) getStateObject(addr common.Address) *stateObject { 579 // Prefer live objects if any is available 580 if obj := s.stateObjects[addr]; obj != nil { 581 return obj 582 } 583 // Short circuit if the account is already destructed in this block. 584 if _, ok := s.stateObjectsDestruct[addr]; ok { 585 return nil 586 } 587 s.AccountLoaded++ 588 589 start := time.Now() 590 acct, err := s.reader.Account(addr) 591 if err != nil { 592 s.setError(fmt.Errorf("getStateObject (%x) error: %w", addr.Bytes(), err)) 593 return nil 594 } 595 s.AccountReads += time.Since(start) 596 597 // Short circuit if the account is not found 598 if acct == nil { 599 return nil 600 } 601 // Schedule the resolved account for prefetching if it's enabled. 602 if s.prefetcher != nil { 603 if err = s.prefetcher.prefetch(common.Hash{}, s.originalRoot, common.Address{}, []common.Address{addr}, nil, true); err != nil { 604 log.Error("Failed to prefetch account", "addr", addr, "err", err) 605 } 606 } 607 // Insert into the live set 608 obj := newObject(s, addr, acct) 609 s.setStateObject(obj) 610 return obj 611 } 612 613 func (s *StateDB) setStateObject(object *stateObject) { 614 s.stateObjects[object.Address()] = object 615 } 616 617 // getOrNewStateObject retrieves a state object or create a new state object if nil. 618 func (s *StateDB) getOrNewStateObject(addr common.Address) *stateObject { 619 obj := s.getStateObject(addr) 620 if obj == nil { 621 obj = s.createObject(addr) 622 } 623 return obj 624 } 625 626 // createObject creates a new state object. The assumption is held there is no 627 // existing account with the given address, otherwise it will be silently overwritten. 628 func (s *StateDB) createObject(addr common.Address) *stateObject { 629 obj := newObject(s, addr, nil) 630 s.journal.createObject(addr) 631 s.setStateObject(obj) 632 return obj 633 } 634 635 // CreateAccount explicitly creates a new state object, assuming that the 636 // account did not previously exist in the state. If the account already 637 // exists, this function will silently overwrite it which might lead to a 638 // consensus bug eventually. 639 func (s *StateDB) CreateAccount(addr common.Address) { 640 s.createObject(addr) 641 } 642 643 // CreateContract is used whenever a contract is created. This may be preceded 644 // by CreateAccount, but that is not required if it already existed in the 645 // state due to funds sent beforehand. 646 // This operation sets the 'newContract'-flag, which is required in order to 647 // correctly handle EIP-6780 'delete-in-same-transaction' logic. 648 func (s *StateDB) CreateContract(addr common.Address) { 649 obj := s.getStateObject(addr) 650 if !obj.newContract { 651 obj.newContract = true 652 s.journal.createContract(addr) 653 } 654 } 655 656 // Copy creates a deep, independent copy of the state. 657 // Snapshots of the copied state cannot be applied to the copy. 658 func (s *StateDB) Copy() *StateDB { 659 // Copy all the basic fields, initialize the memory ones 660 state := &StateDB{ 661 db: s.db, 662 reader: s.reader, 663 originalRoot: s.originalRoot, 664 stateObjects: make(map[common.Address]*stateObject, len(s.stateObjects)), 665 stateObjectsDestruct: make(map[common.Address]*stateObject, len(s.stateObjectsDestruct)), 666 mutations: make(map[common.Address]*mutation, len(s.mutations)), 667 dbErr: s.dbErr, 668 refund: s.refund, 669 thash: s.thash, 670 txIndex: s.txIndex, 671 logs: make(map[common.Hash][]*types.Log, len(s.logs)), 672 logSize: s.logSize, 673 preimages: maps.Clone(s.preimages), 674 675 // Do we need to copy the access list and transient storage? 676 // In practice: No. At the start of a transaction, these two lists are empty. 677 // In practice, we only ever copy state _between_ transactions/blocks, never 678 // in the middle of a transaction. However, it doesn't cost us much to copy 679 // empty lists, so we do it anyway to not blow up if we ever decide copy them 680 // in the middle of a transaction. 681 accessList: s.accessList.Copy(), 682 transientStorage: s.transientStorage.Copy(), 683 journal: s.journal.copy(), 684 } 685 if s.trie != nil { 686 state.trie = mustCopyTrie(s.trie) 687 } 688 if s.witness != nil { 689 state.witness = s.witness.Copy() 690 } 691 if s.accessEvents != nil { 692 state.accessEvents = s.accessEvents.Copy() 693 } 694 // Deep copy cached state objects. 695 for addr, obj := range s.stateObjects { 696 state.stateObjects[addr] = obj.deepCopy(state) 697 } 698 // Deep copy destructed state objects. 699 for addr, obj := range s.stateObjectsDestruct { 700 state.stateObjectsDestruct[addr] = obj.deepCopy(state) 701 } 702 // Deep copy the object state markers. 703 for addr, op := range s.mutations { 704 state.mutations[addr] = op.copy() 705 } 706 // Deep copy the logs occurred in the scope of block 707 for hash, logs := range s.logs { 708 cpy := make([]*types.Log, len(logs)) 709 for i, l := range logs { 710 cpy[i] = new(types.Log) 711 *cpy[i] = *l 712 } 713 state.logs[hash] = cpy 714 } 715 return state 716 } 717 718 // Snapshot returns an identifier for the current revision of the state. 719 func (s *StateDB) Snapshot() int { 720 return s.journal.snapshot() 721 } 722 723 // RevertToSnapshot reverts all state changes made since the given revision. 724 func (s *StateDB) RevertToSnapshot(revid int) { 725 s.journal.revertToSnapshot(revid, s) 726 } 727 728 // GetRefund returns the current value of the refund counter. 729 func (s *StateDB) GetRefund() uint64 { 730 return s.refund 731 } 732 733 // Finalise finalises the state by removing the destructed objects and clears 734 // the journal as well as the refunds. Finalise, however, will not push any updates 735 // into the tries just yet. Only IntermediateRoot or Commit will do that. 736 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 737 addressesToPrefetch := make([]common.Address, 0, len(s.journal.dirties)) 738 for addr := range s.journal.dirties { 739 obj, exist := s.stateObjects[addr] 740 if !exist { 741 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 742 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 743 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 744 // it will persist in the journal even though the journal is reverted. In this special circumstance, 745 // it may exist in `s.journal.dirties` but not in `s.stateObjects`. 746 // Thus, we can safely ignore it here 747 continue 748 } 749 if obj.selfDestructed || (deleteEmptyObjects && obj.empty()) { 750 delete(s.stateObjects, obj.address) 751 s.markDelete(addr) 752 // We need to maintain account deletions explicitly (will remain 753 // set indefinitely). Note only the first occurred self-destruct 754 // event is tracked. 755 if _, ok := s.stateObjectsDestruct[obj.address]; !ok { 756 s.stateObjectsDestruct[obj.address] = obj 757 } 758 } else { 759 obj.finalise() 760 s.markUpdate(addr) 761 } 762 // At this point, also ship the address off to the precacher. The precacher 763 // will start loading tries, and when the change is eventually committed, 764 // the commit-phase will be a lot faster 765 addressesToPrefetch = append(addressesToPrefetch, addr) // Copy needed for closure 766 } 767 if s.prefetcher != nil && len(addressesToPrefetch) > 0 { 768 if err := s.prefetcher.prefetch(common.Hash{}, s.originalRoot, common.Address{}, addressesToPrefetch, nil, false); err != nil { 769 log.Error("Failed to prefetch addresses", "addresses", len(addressesToPrefetch), "err", err) 770 } 771 } 772 // Invalidate journal because reverting across transactions is not allowed. 773 s.clearJournalAndRefund() 774 } 775 776 // IntermediateRoot computes the current root hash of the state trie. 777 // It is called in between transactions to get the root hash that 778 // goes into transaction receipts. 779 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 780 // Finalise all the dirty storage states and write them into the tries 781 s.Finalise(deleteEmptyObjects) 782 783 // Initialize the trie if it's not constructed yet. If the prefetch 784 // is enabled, the trie constructed below will be replaced by the 785 // prefetched one. 786 // 787 // This operation must be done before state object storage hashing, 788 // as it assumes the main trie is already loaded. 789 if s.trie == nil { 790 tr, err := s.db.OpenTrie(s.originalRoot) 791 if err != nil { 792 s.setError(err) 793 return common.Hash{} 794 } 795 s.trie = tr 796 } 797 // If there was a trie prefetcher operating, terminate it async so that the 798 // individual storage tries can be updated as soon as the disk load finishes. 799 if s.prefetcher != nil { 800 s.prefetcher.terminate(true) 801 defer func() { 802 s.prefetcher.report() 803 s.prefetcher = nil // Pre-byzantium, unset any used up prefetcher 804 }() 805 } 806 // Process all storage updates concurrently. The state object update root 807 // method will internally call a blocking trie fetch from the prefetcher, 808 // so there's no need to explicitly wait for the prefetchers to finish. 809 var ( 810 start = time.Now() 811 workers errgroup.Group 812 ) 813 if s.db.TrieDB().IsVerkle() { 814 // Whilst MPT storage tries are independent, Verkle has one single trie 815 // for all the accounts and all the storage slots merged together. The 816 // former can thus be simply parallelized, but updating the latter will 817 // need concurrency support within the trie itself. That's a TODO for a 818 // later time. 819 workers.SetLimit(1) 820 } 821 for addr, op := range s.mutations { 822 if op.applied || op.isDelete() { 823 continue 824 } 825 obj := s.stateObjects[addr] // closure for the task runner below 826 workers.Go(func() error { 827 if s.db.TrieDB().IsVerkle() { 828 obj.updateTrie() 829 } else { 830 obj.updateRoot() 831 832 // If witness building is enabled and the state object has a trie, 833 // gather the witnesses for its specific storage trie 834 if s.witness != nil && obj.trie != nil { 835 s.witness.AddState(obj.trie.Witness()) 836 } 837 } 838 return nil 839 }) 840 } 841 // If witness building is enabled, gather all the read-only accesses. 842 // Skip witness collection in Verkle mode, they will be gathered 843 // together at the end. 844 if s.witness != nil && !s.db.TrieDB().IsVerkle() { 845 // Pull in anything that has been accessed before destruction 846 for _, obj := range s.stateObjectsDestruct { 847 // Skip any objects that haven't touched their storage 848 if len(obj.originStorage) == 0 { 849 continue 850 } 851 if trie := obj.getPrefetchedTrie(); trie != nil { 852 s.witness.AddState(trie.Witness()) 853 } else if obj.trie != nil { 854 s.witness.AddState(obj.trie.Witness()) 855 } 856 } 857 // Pull in only-read and non-destructed trie witnesses 858 for _, obj := range s.stateObjects { 859 // Skip any objects that have been updated 860 if _, ok := s.mutations[obj.address]; ok { 861 continue 862 } 863 // Skip any objects that haven't touched their storage 864 if len(obj.originStorage) == 0 { 865 continue 866 } 867 if trie := obj.getPrefetchedTrie(); trie != nil { 868 s.witness.AddState(trie.Witness()) 869 } else if obj.trie != nil { 870 s.witness.AddState(obj.trie.Witness()) 871 } 872 } 873 } 874 workers.Wait() 875 s.StorageUpdates += time.Since(start) 876 877 // Now we're about to start to write changes to the trie. The trie is so far 878 // _untouched_. We can check with the prefetcher, if it can give us a trie 879 // which has the same root, but also has some content loaded into it. 880 // 881 // Don't check prefetcher if verkle trie has been used. In the context of verkle, 882 // only a single trie is used for state hashing. Replacing a non-nil verkle tree 883 // here could result in losing uncommitted changes from storage. 884 start = time.Now() 885 if s.prefetcher != nil { 886 if trie := s.prefetcher.trie(common.Hash{}, s.originalRoot); trie == nil { 887 log.Error("Failed to retrieve account pre-fetcher trie") 888 } else { 889 s.trie = trie 890 } 891 } 892 // Perform updates before deletions. This prevents resolution of unnecessary trie nodes 893 // in circumstances similar to the following: 894 // 895 // Consider nodes `A` and `B` who share the same full node parent `P` and have no other siblings. 896 // During the execution of a block: 897 // - `A` self-destructs, 898 // - `C` is created, and also shares the parent `P`. 899 // If the self-destruct is handled first, then `P` would be left with only one child, thus collapsed 900 // into a shortnode. This requires `B` to be resolved from disk. 901 // Whereas if the created node is handled first, then the collapse is avoided, and `B` is not resolved. 902 var ( 903 usedAddrs []common.Address 904 deletedAddrs []common.Address 905 ) 906 for addr, op := range s.mutations { 907 if op.applied { 908 continue 909 } 910 op.applied = true 911 912 if op.isDelete() { 913 deletedAddrs = append(deletedAddrs, addr) 914 } else { 915 s.updateStateObject(s.stateObjects[addr]) 916 s.AccountUpdated += 1 917 } 918 usedAddrs = append(usedAddrs, addr) // Copy needed for closure 919 } 920 for _, deletedAddr := range deletedAddrs { 921 s.deleteStateObject(deletedAddr) 922 s.AccountDeleted += 1 923 } 924 s.AccountUpdates += time.Since(start) 925 926 if s.prefetcher != nil { 927 s.prefetcher.used(common.Hash{}, s.originalRoot, usedAddrs, nil) 928 } 929 // Track the amount of time wasted on hashing the account trie 930 defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now()) 931 932 hash := s.trie.Hash() 933 934 // If witness building is enabled, gather the account trie witness 935 if s.witness != nil { 936 s.witness.AddState(s.trie.Witness()) 937 } 938 return hash 939 } 940 941 // SetTxContext sets the current transaction hash and index which are 942 // used when the EVM emits new state logs. It should be invoked before 943 // transaction execution. 944 func (s *StateDB) SetTxContext(thash common.Hash, ti int) { 945 s.thash = thash 946 s.txIndex = ti 947 } 948 949 func (s *StateDB) clearJournalAndRefund() { 950 s.journal.reset() 951 s.refund = 0 952 } 953 954 // fastDeleteStorage is the function that efficiently deletes the storage trie 955 // of a specific account. It leverages the associated state snapshot for fast 956 // storage iteration and constructs trie node deletion markers by creating 957 // stack trie with iterated slots. 958 func (s *StateDB) fastDeleteStorage(snaps *snapshot.Tree, addrHash common.Hash, root common.Hash) (map[common.Hash][]byte, map[common.Hash][]byte, *trienode.NodeSet, error) { 959 iter, err := snaps.StorageIterator(s.originalRoot, addrHash, common.Hash{}) 960 if err != nil { 961 return nil, nil, nil, err 962 } 963 defer iter.Release() 964 965 var ( 966 nodes = trienode.NewNodeSet(addrHash) // the set for trie node mutations (value is nil) 967 storages = make(map[common.Hash][]byte) // the set for storage mutations (value is nil) 968 storageOrigins = make(map[common.Hash][]byte) // the set for tracking the original value of slot 969 ) 970 stack := trie.NewStackTrie(func(path []byte, hash common.Hash, blob []byte) { 971 nodes.AddNode(path, trienode.NewDeleted()) 972 }) 973 for iter.Next() { 974 slot := common.CopyBytes(iter.Slot()) 975 if err := iter.Error(); err != nil { // error might occur after Slot function 976 return nil, nil, nil, err 977 } 978 key := iter.Hash() 979 storages[key] = nil 980 storageOrigins[key] = slot 981 982 if err := stack.Update(key.Bytes(), slot); err != nil { 983 return nil, nil, nil, err 984 } 985 } 986 if err := iter.Error(); err != nil { // error might occur during iteration 987 return nil, nil, nil, err 988 } 989 if stack.Hash() != root { 990 return nil, nil, nil, fmt.Errorf("snapshot is not matched, exp %x, got %x", root, stack.Hash()) 991 } 992 return storages, storageOrigins, nodes, nil 993 } 994 995 // slowDeleteStorage serves as a less-efficient alternative to "fastDeleteStorage," 996 // employed when the associated state snapshot is not available. It iterates the 997 // storage slots along with all internal trie nodes via trie directly. 998 func (s *StateDB) slowDeleteStorage(addr common.Address, addrHash common.Hash, root common.Hash) (map[common.Hash][]byte, map[common.Hash][]byte, *trienode.NodeSet, error) { 999 tr, err := s.db.OpenStorageTrie(s.originalRoot, addr, root, s.trie) 1000 if err != nil { 1001 return nil, nil, nil, fmt.Errorf("failed to open storage trie, err: %w", err) 1002 } 1003 it, err := tr.NodeIterator(nil) 1004 if err != nil { 1005 return nil, nil, nil, fmt.Errorf("failed to open storage iterator, err: %w", err) 1006 } 1007 var ( 1008 nodes = trienode.NewNodeSet(addrHash) // the set for trie node mutations (value is nil) 1009 storages = make(map[common.Hash][]byte) // the set for storage mutations (value is nil) 1010 storageOrigins = make(map[common.Hash][]byte) // the set for tracking the original value of slot 1011 ) 1012 for it.Next(true) { 1013 if it.Leaf() { 1014 key := common.BytesToHash(it.LeafKey()) 1015 storages[key] = nil 1016 storageOrigins[key] = common.CopyBytes(it.LeafBlob()) 1017 continue 1018 } 1019 if it.Hash() == (common.Hash{}) { 1020 continue 1021 } 1022 nodes.AddNode(it.Path(), trienode.NewDeleted()) 1023 } 1024 if err := it.Error(); err != nil { 1025 return nil, nil, nil, err 1026 } 1027 return storages, storageOrigins, nodes, nil 1028 } 1029 1030 // deleteStorage is designed to delete the storage trie of a designated account. 1031 // The function will make an attempt to utilize an efficient strategy if the 1032 // associated state snapshot is reachable; otherwise, it will resort to a less 1033 // efficient approach. 1034 func (s *StateDB) deleteStorage(addr common.Address, addrHash common.Hash, root common.Hash) (map[common.Hash][]byte, map[common.Hash][]byte, *trienode.NodeSet, error) { 1035 var ( 1036 err error 1037 nodes *trienode.NodeSet // the set for trie node mutations (value is nil) 1038 storages map[common.Hash][]byte // the set for storage mutations (value is nil) 1039 storageOrigins map[common.Hash][]byte // the set for tracking the original value of slot 1040 ) 1041 // The fast approach can be failed if the snapshot is not fully 1042 // generated, or it's internally corrupted. Fallback to the slow 1043 // one just in case. 1044 snaps := s.db.Snapshot() 1045 if snaps != nil { 1046 storages, storageOrigins, nodes, err = s.fastDeleteStorage(snaps, addrHash, root) 1047 } 1048 if snaps == nil || err != nil { 1049 storages, storageOrigins, nodes, err = s.slowDeleteStorage(addr, addrHash, root) 1050 } 1051 if err != nil { 1052 return nil, nil, nil, err 1053 } 1054 return storages, storageOrigins, nodes, nil 1055 } 1056 1057 // handleDestruction processes all destruction markers and deletes the account 1058 // and associated storage slots if necessary. There are four potential scenarios 1059 // as following: 1060 // 1061 // (a) the account was not existent and be marked as destructed 1062 // (b) the account was not existent and be marked as destructed, 1063 // however, it's resurrected later in the same block. 1064 // (c) the account was existent and be marked as destructed 1065 // (d) the account was existent and be marked as destructed, 1066 // however it's resurrected later in the same block. 1067 // 1068 // In case (a), nothing needs be deleted, nil to nil transition can be ignored. 1069 // In case (b), nothing needs be deleted, nil is used as the original value for 1070 // newly created account and storages 1071 // In case (c), **original** account along with its storages should be deleted, 1072 // with their values be tracked as original value. 1073 // In case (d), **original** account along with its storages should be deleted, 1074 // with their values be tracked as original value. 1075 func (s *StateDB) handleDestruction(noStorageWiping bool) (map[common.Hash]*accountDelete, []*trienode.NodeSet, error) { 1076 var ( 1077 nodes []*trienode.NodeSet 1078 deletes = make(map[common.Hash]*accountDelete) 1079 ) 1080 for addr, prevObj := range s.stateObjectsDestruct { 1081 prev := prevObj.origin 1082 1083 // The account was non-existent, and it's marked as destructed in the scope 1084 // of block. It can be either case (a) or (b) and will be interpreted as 1085 // null->null state transition. 1086 // - for (a), skip it without doing anything 1087 // - for (b), the resurrected account with nil as original will be handled afterwards 1088 if prev == nil { 1089 continue 1090 } 1091 // The account was existent, it can be either case (c) or (d). 1092 addrHash := crypto.Keccak256Hash(addr.Bytes()) 1093 op := &accountDelete{ 1094 address: addr, 1095 origin: types.SlimAccountRLP(*prev), 1096 } 1097 deletes[addrHash] = op 1098 1099 // Short circuit if the origin storage was empty. 1100 if prev.Root == types.EmptyRootHash || s.db.TrieDB().IsVerkle() { 1101 continue 1102 } 1103 if noStorageWiping { 1104 return nil, nil, fmt.Errorf("unexpected storage wiping, %x", addr) 1105 } 1106 // Remove storage slots belonging to the account. 1107 storages, storagesOrigin, set, err := s.deleteStorage(addr, addrHash, prev.Root) 1108 if err != nil { 1109 return nil, nil, fmt.Errorf("failed to delete storage, err: %w", err) 1110 } 1111 op.storages = storages 1112 op.storagesOrigin = storagesOrigin 1113 1114 // Aggregate the associated trie node changes. 1115 nodes = append(nodes, set) 1116 } 1117 return deletes, nodes, nil 1118 } 1119 1120 // GetTrie returns the account trie. 1121 func (s *StateDB) GetTrie() Trie { 1122 return s.trie 1123 } 1124 1125 // commit gathers the state mutations accumulated along with the associated 1126 // trie changes, resetting all internal flags with the new state as the base. 1127 func (s *StateDB) commit(deleteEmptyObjects bool, noStorageWiping bool) (*stateUpdate, error) { 1128 // Short circuit in case any database failure occurred earlier. 1129 if s.dbErr != nil { 1130 return nil, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr) 1131 } 1132 // Finalize any pending changes and merge everything into the tries 1133 s.IntermediateRoot(deleteEmptyObjects) 1134 1135 // Short circuit if any error occurs within the IntermediateRoot. 1136 if s.dbErr != nil { 1137 return nil, fmt.Errorf("commit aborted due to database error: %v", s.dbErr) 1138 } 1139 // Commit objects to the trie, measuring the elapsed time 1140 var ( 1141 accountTrieNodesUpdated int 1142 accountTrieNodesDeleted int 1143 storageTrieNodesUpdated int 1144 storageTrieNodesDeleted int 1145 1146 lock sync.Mutex // protect two maps below 1147 nodes = trienode.NewMergedNodeSet() // aggregated trie nodes 1148 updates = make(map[common.Hash]*accountUpdate, len(s.mutations)) // aggregated account updates 1149 1150 // merge aggregates the dirty trie nodes into the global set. 1151 // 1152 // Given that some accounts may be destroyed and then recreated within 1153 // the same block, it's possible that a node set with the same owner 1154 // may already exists. In such cases, these two sets are combined, with 1155 // the later one overwriting the previous one if any nodes are modified 1156 // or deleted in both sets. 1157 // 1158 // merge run concurrently across all the state objects and account trie. 1159 merge = func(set *trienode.NodeSet) error { 1160 if set == nil { 1161 return nil 1162 } 1163 lock.Lock() 1164 defer lock.Unlock() 1165 1166 updates, deletes := set.Size() 1167 if set.Owner == (common.Hash{}) { 1168 accountTrieNodesUpdated += updates 1169 accountTrieNodesDeleted += deletes 1170 } else { 1171 storageTrieNodesUpdated += updates 1172 storageTrieNodesDeleted += deletes 1173 } 1174 return nodes.Merge(set) 1175 } 1176 ) 1177 // Given that some accounts could be destroyed and then recreated within 1178 // the same block, account deletions must be processed first. This ensures 1179 // that the storage trie nodes deleted during destruction and recreated 1180 // during subsequent resurrection can be combined correctly. 1181 deletes, delNodes, err := s.handleDestruction(noStorageWiping) 1182 if err != nil { 1183 return nil, err 1184 } 1185 for _, set := range delNodes { 1186 if err := merge(set); err != nil { 1187 return nil, err 1188 } 1189 } 1190 // Handle all state updates afterwards, concurrently to one another to shave 1191 // off some milliseconds from the commit operation. Also accumulate the code 1192 // writes to run in parallel with the computations. 1193 var ( 1194 start = time.Now() 1195 root common.Hash 1196 workers errgroup.Group 1197 ) 1198 // Schedule the account trie first since that will be the biggest, so give 1199 // it the most time to crunch. 1200 // 1201 // TODO(karalabe): This account trie commit is *very* heavy. 5-6ms at chain 1202 // heads, which seems excessive given that it doesn't do hashing, it just 1203 // shuffles some data. For comparison, the *hashing* at chain head is 2-3ms. 1204 // We need to investigate what's happening as it seems something's wonky. 1205 // Obviously it's not an end of the world issue, just something the original 1206 // code didn't anticipate for. 1207 workers.Go(func() error { 1208 // Write the account trie changes, measuring the amount of wasted time 1209 newroot, set := s.trie.Commit(true) 1210 root = newroot 1211 1212 if err := merge(set); err != nil { 1213 return err 1214 } 1215 s.AccountCommits = time.Since(start) 1216 return nil 1217 }) 1218 // Schedule each of the storage tries that need to be updated, so they can 1219 // run concurrently to one another. 1220 // 1221 // TODO(karalabe): Experimentally, the account commit takes approximately the 1222 // same time as all the storage commits combined, so we could maybe only have 1223 // 2 threads in total. But that kind of depends on the account commit being 1224 // more expensive than it should be, so let's fix that and revisit this todo. 1225 for addr, op := range s.mutations { 1226 if op.isDelete() { 1227 continue 1228 } 1229 // Write any contract code associated with the state object 1230 obj := s.stateObjects[addr] 1231 if obj == nil { 1232 return nil, errors.New("missing state object") 1233 } 1234 // Run the storage updates concurrently to one another 1235 workers.Go(func() error { 1236 // Write any storage changes in the state object to its storage trie 1237 update, set, err := obj.commit() 1238 if err != nil { 1239 return err 1240 } 1241 if err := merge(set); err != nil { 1242 return err 1243 } 1244 lock.Lock() 1245 updates[obj.addrHash] = update 1246 s.StorageCommits = time.Since(start) // overwrite with the longest storage commit runtime 1247 lock.Unlock() 1248 return nil 1249 }) 1250 } 1251 // Wait for everything to finish and update the metrics 1252 if err := workers.Wait(); err != nil { 1253 return nil, err 1254 } 1255 accountReadMeters.Mark(int64(s.AccountLoaded)) 1256 storageReadMeters.Mark(int64(s.StorageLoaded)) 1257 accountUpdatedMeter.Mark(int64(s.AccountUpdated)) 1258 storageUpdatedMeter.Mark(s.StorageUpdated.Load()) 1259 accountDeletedMeter.Mark(int64(s.AccountDeleted)) 1260 storageDeletedMeter.Mark(s.StorageDeleted.Load()) 1261 accountTrieUpdatedMeter.Mark(int64(accountTrieNodesUpdated)) 1262 accountTrieDeletedMeter.Mark(int64(accountTrieNodesDeleted)) 1263 storageTriesUpdatedMeter.Mark(int64(storageTrieNodesUpdated)) 1264 storageTriesDeletedMeter.Mark(int64(storageTrieNodesDeleted)) 1265 1266 // Clear the metric markers 1267 s.AccountLoaded, s.AccountUpdated, s.AccountDeleted = 0, 0, 0 1268 s.StorageLoaded = 0 1269 s.StorageUpdated.Store(0) 1270 s.StorageDeleted.Store(0) 1271 1272 // Clear all internal flags and update state root at the end. 1273 s.mutations = make(map[common.Address]*mutation) 1274 s.stateObjectsDestruct = make(map[common.Address]*stateObject) 1275 1276 origin := s.originalRoot 1277 s.originalRoot = root 1278 1279 return newStateUpdate(noStorageWiping, origin, root, deletes, updates, nodes), nil 1280 } 1281 1282 // commitAndFlush is a wrapper of commit which also commits the state mutations 1283 // to the configured data stores. 1284 func (s *StateDB) commitAndFlush(block uint64, deleteEmptyObjects bool, noStorageWiping bool) (*stateUpdate, error) { 1285 ret, err := s.commit(deleteEmptyObjects, noStorageWiping) 1286 if err != nil { 1287 return nil, err 1288 } 1289 // Commit dirty contract code if any exists 1290 if db := s.db.TrieDB().Disk(); db != nil && len(ret.codes) > 0 { 1291 batch := db.NewBatch() 1292 for _, code := range ret.codes { 1293 rawdb.WriteCode(batch, code.hash, code.blob) 1294 } 1295 if err := batch.Write(); err != nil { 1296 return nil, err 1297 } 1298 } 1299 if !ret.empty() { 1300 // If snapshotting is enabled, update the snapshot tree with this new version 1301 if snap := s.db.Snapshot(); snap != nil && snap.Snapshot(ret.originRoot) != nil { 1302 start := time.Now() 1303 if err := snap.Update(ret.root, ret.originRoot, ret.accounts, ret.storages); err != nil { 1304 log.Warn("Failed to update snapshot tree", "from", ret.originRoot, "to", ret.root, "err", err) 1305 } 1306 // Keep 128 diff layers in the memory, persistent layer is 129th. 1307 // - head layer is paired with HEAD state 1308 // - head-1 layer is paired with HEAD-1 state 1309 // - head-127 layer(bottom-most diff layer) is paired with HEAD-127 state 1310 if err := snap.Cap(ret.root, TriesInMemory); err != nil { 1311 log.Warn("Failed to cap snapshot tree", "root", ret.root, "layers", TriesInMemory, "err", err) 1312 } 1313 s.SnapshotCommits += time.Since(start) 1314 } 1315 // If trie database is enabled, commit the state update as a new layer 1316 if db := s.db.TrieDB(); db != nil { 1317 start := time.Now() 1318 if err := db.Update(ret.root, ret.originRoot, block, ret.nodes, ret.stateSet()); err != nil { 1319 return nil, err 1320 } 1321 s.TrieDBCommits += time.Since(start) 1322 } 1323 } 1324 s.reader, _ = s.db.Reader(s.originalRoot) 1325 return ret, err 1326 } 1327 1328 // Commit writes the state mutations into the configured data stores. 1329 // 1330 // Once the state is committed, tries cached in stateDB (including account 1331 // trie, storage tries) will no longer be functional. A new state instance 1332 // must be created with new root and updated database for accessing post- 1333 // commit states. 1334 // 1335 // The associated block number of the state transition is also provided 1336 // for more chain context. 1337 // 1338 // noStorageWiping is a flag indicating whether storage wiping is permitted. 1339 // Since self-destruction was deprecated with the Cancun fork and there are 1340 // no empty accounts left that could be deleted by EIP-158, storage wiping 1341 // should not occur. 1342 func (s *StateDB) Commit(block uint64, deleteEmptyObjects bool, noStorageWiping bool) (common.Hash, error) { 1343 ret, err := s.commitAndFlush(block, deleteEmptyObjects, noStorageWiping) 1344 if err != nil { 1345 return common.Hash{}, err 1346 } 1347 return ret.root, nil 1348 } 1349 1350 // Prepare handles the preparatory steps for executing a state transition with. 1351 // This method must be invoked before state transition. 1352 // 1353 // Berlin fork: 1354 // - Add sender to access list (2929) 1355 // - Add destination to access list (2929) 1356 // - Add precompiles to access list (2929) 1357 // - Add the contents of the optional tx access list (2930) 1358 // 1359 // Potential EIPs: 1360 // - Reset access list (Berlin) 1361 // - Add coinbase to access list (EIP-3651) 1362 // - Reset transient storage (EIP-1153) 1363 func (s *StateDB) Prepare(rules params.Rules, sender, coinbase common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) { 1364 if rules.IsEIP2929 && rules.IsEIP4762 { 1365 panic("eip2929 and eip4762 are both activated") 1366 } 1367 if rules.IsEIP2929 { 1368 // Clear out any leftover from previous executions 1369 al := newAccessList() 1370 s.accessList = al 1371 1372 al.AddAddress(sender) 1373 if dst != nil { 1374 al.AddAddress(*dst) 1375 // If it's a create-tx, the destination will be added inside evm.create 1376 } 1377 for _, addr := range precompiles { 1378 al.AddAddress(addr) 1379 } 1380 for _, el := range list { 1381 al.AddAddress(el.Address) 1382 for _, key := range el.StorageKeys { 1383 al.AddSlot(el.Address, key) 1384 } 1385 } 1386 if rules.IsShanghai { // EIP-3651: warm coinbase 1387 al.AddAddress(coinbase) 1388 } 1389 } 1390 // Reset transient storage at the beginning of transaction execution 1391 s.transientStorage = newTransientStorage() 1392 } 1393 1394 // AddAddressToAccessList adds the given address to the access list 1395 func (s *StateDB) AddAddressToAccessList(addr common.Address) { 1396 if s.accessList.AddAddress(addr) { 1397 s.journal.accessListAddAccount(addr) 1398 } 1399 } 1400 1401 // AddSlotToAccessList adds the given (address, slot)-tuple to the access list 1402 func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) { 1403 addrMod, slotMod := s.accessList.AddSlot(addr, slot) 1404 if addrMod { 1405 // In practice, this should not happen, since there is no way to enter the 1406 // scope of 'address' without having the 'address' become already added 1407 // to the access list (via call-variant, create, etc). 1408 // Better safe than sorry, though 1409 s.journal.accessListAddAccount(addr) 1410 } 1411 if slotMod { 1412 s.journal.accessListAddSlot(addr, slot) 1413 } 1414 } 1415 1416 // AddressInAccessList returns true if the given address is in the access list. 1417 func (s *StateDB) AddressInAccessList(addr common.Address) bool { 1418 return s.accessList.ContainsAddress(addr) 1419 } 1420 1421 // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list. 1422 func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) { 1423 return s.accessList.Contains(addr, slot) 1424 } 1425 1426 // markDelete is invoked when an account is deleted but the deletion is 1427 // not yet committed. The pending mutation is cached and will be applied 1428 // all together 1429 func (s *StateDB) markDelete(addr common.Address) { 1430 if _, ok := s.mutations[addr]; !ok { 1431 s.mutations[addr] = &mutation{} 1432 } 1433 s.mutations[addr].applied = false 1434 s.mutations[addr].typ = deletion 1435 } 1436 1437 func (s *StateDB) markUpdate(addr common.Address) { 1438 if _, ok := s.mutations[addr]; !ok { 1439 s.mutations[addr] = &mutation{} 1440 } 1441 s.mutations[addr].applied = false 1442 s.mutations[addr].typ = update 1443 } 1444 1445 // PointCache returns the point cache used by verkle tree. 1446 func (s *StateDB) PointCache() *utils.PointCache { 1447 return s.db.PointCache() 1448 } 1449 1450 // Witness retrieves the current state witness being collected. 1451 func (s *StateDB) Witness() *stateless.Witness { 1452 return s.witness 1453 } 1454 1455 func (s *StateDB) AccessEvents() *AccessEvents { 1456 return s.accessEvents 1457 }