github.com/snowblossomcoin/go-ethereum@v1.9.25/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 "sort" 25 "time" 26 27 "github.com/ethereum/go-ethereum/common" 28 "github.com/ethereum/go-ethereum/core/rawdb" 29 "github.com/ethereum/go-ethereum/core/state/snapshot" 30 "github.com/ethereum/go-ethereum/core/types" 31 "github.com/ethereum/go-ethereum/crypto" 32 "github.com/ethereum/go-ethereum/log" 33 "github.com/ethereum/go-ethereum/metrics" 34 "github.com/ethereum/go-ethereum/rlp" 35 "github.com/ethereum/go-ethereum/trie" 36 ) 37 38 type revision struct { 39 id int 40 journalIndex int 41 } 42 43 var ( 44 // emptyRoot is the known root hash of an empty trie. 45 emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") 46 ) 47 48 type proofList [][]byte 49 50 func (n *proofList) Put(key []byte, value []byte) error { 51 *n = append(*n, value) 52 return nil 53 } 54 55 func (n *proofList) Delete(key []byte) error { 56 panic("not supported") 57 } 58 59 // StateDB structs within the ethereum protocol are used to store anything 60 // within the merkle trie. StateDBs take care of caching and storing 61 // nested states. It's the general query interface to retrieve: 62 // * Contracts 63 // * Accounts 64 type StateDB struct { 65 db Database 66 trie Trie 67 68 snaps *snapshot.Tree 69 snap snapshot.Snapshot 70 snapDestructs map[common.Hash]struct{} 71 snapAccounts map[common.Hash][]byte 72 snapStorage map[common.Hash]map[common.Hash][]byte 73 74 // This map holds 'live' objects, which will get modified while processing a state transition. 75 stateObjects map[common.Address]*stateObject 76 stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie 77 stateObjectsDirty map[common.Address]struct{} // State objects modified in the current execution 78 79 // DB error. 80 // State objects are used by the consensus core and VM which are 81 // unable to deal with database-level errors. Any error that occurs 82 // during a database read is memoized here and will eventually be returned 83 // by StateDB.Commit. 84 dbErr error 85 86 // The refund counter, also used by state transitioning. 87 refund uint64 88 89 thash, bhash common.Hash 90 txIndex int 91 logs map[common.Hash][]*types.Log 92 logSize uint 93 94 preimages map[common.Hash][]byte 95 96 // Per-transaction access list 97 accessList *accessList 98 99 // Journal of state modifications. This is the backbone of 100 // Snapshot and RevertToSnapshot. 101 journal *journal 102 validRevisions []revision 103 nextRevisionId int 104 105 // Measurements gathered during execution for debugging purposes 106 AccountReads time.Duration 107 AccountHashes time.Duration 108 AccountUpdates time.Duration 109 AccountCommits time.Duration 110 StorageReads time.Duration 111 StorageHashes time.Duration 112 StorageUpdates time.Duration 113 StorageCommits time.Duration 114 SnapshotAccountReads time.Duration 115 SnapshotStorageReads time.Duration 116 SnapshotCommits time.Duration 117 } 118 119 // New creates a new state from a given trie. 120 func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) { 121 tr, err := db.OpenTrie(root) 122 if err != nil { 123 return nil, err 124 } 125 sdb := &StateDB{ 126 db: db, 127 trie: tr, 128 snaps: snaps, 129 stateObjects: make(map[common.Address]*stateObject), 130 stateObjectsPending: make(map[common.Address]struct{}), 131 stateObjectsDirty: make(map[common.Address]struct{}), 132 logs: make(map[common.Hash][]*types.Log), 133 preimages: make(map[common.Hash][]byte), 134 journal: newJournal(), 135 accessList: newAccessList(), 136 } 137 if sdb.snaps != nil { 138 if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil { 139 sdb.snapDestructs = make(map[common.Hash]struct{}) 140 sdb.snapAccounts = make(map[common.Hash][]byte) 141 sdb.snapStorage = make(map[common.Hash]map[common.Hash][]byte) 142 } 143 } 144 return sdb, nil 145 } 146 147 // setError remembers the first non-nil error it is called with. 148 func (s *StateDB) setError(err error) { 149 if s.dbErr == nil { 150 s.dbErr = err 151 } 152 } 153 154 func (s *StateDB) Error() error { 155 return s.dbErr 156 } 157 158 // Reset clears out all ephemeral state objects from the state db, but keeps 159 // the underlying state trie to avoid reloading data for the next operations. 160 func (s *StateDB) Reset(root common.Hash) error { 161 tr, err := s.db.OpenTrie(root) 162 if err != nil { 163 return err 164 } 165 s.trie = tr 166 s.stateObjects = make(map[common.Address]*stateObject) 167 s.stateObjectsPending = make(map[common.Address]struct{}) 168 s.stateObjectsDirty = make(map[common.Address]struct{}) 169 s.thash = common.Hash{} 170 s.bhash = common.Hash{} 171 s.txIndex = 0 172 s.logs = make(map[common.Hash][]*types.Log) 173 s.logSize = 0 174 s.preimages = make(map[common.Hash][]byte) 175 s.clearJournalAndRefund() 176 177 if s.snaps != nil { 178 s.snapAccounts, s.snapDestructs, s.snapStorage = nil, nil, nil 179 if s.snap = s.snaps.Snapshot(root); s.snap != nil { 180 s.snapDestructs = make(map[common.Hash]struct{}) 181 s.snapAccounts = make(map[common.Hash][]byte) 182 s.snapStorage = make(map[common.Hash]map[common.Hash][]byte) 183 } 184 } 185 s.accessList = newAccessList() 186 return nil 187 } 188 189 func (s *StateDB) AddLog(log *types.Log) { 190 s.journal.append(addLogChange{txhash: s.thash}) 191 192 log.TxHash = s.thash 193 log.BlockHash = s.bhash 194 log.TxIndex = uint(s.txIndex) 195 log.Index = s.logSize 196 s.logs[s.thash] = append(s.logs[s.thash], log) 197 s.logSize++ 198 } 199 200 func (s *StateDB) GetLogs(hash common.Hash) []*types.Log { 201 return s.logs[hash] 202 } 203 204 func (s *StateDB) Logs() []*types.Log { 205 var logs []*types.Log 206 for _, lgs := range s.logs { 207 logs = append(logs, lgs...) 208 } 209 return logs 210 } 211 212 // AddPreimage records a SHA3 preimage seen by the VM. 213 func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 214 if _, ok := s.preimages[hash]; !ok { 215 s.journal.append(addPreimageChange{hash: hash}) 216 pi := make([]byte, len(preimage)) 217 copy(pi, preimage) 218 s.preimages[hash] = pi 219 } 220 } 221 222 // Preimages returns a list of SHA3 preimages that have been submitted. 223 func (s *StateDB) Preimages() map[common.Hash][]byte { 224 return s.preimages 225 } 226 227 // AddRefund adds gas to the refund counter 228 func (s *StateDB) AddRefund(gas uint64) { 229 s.journal.append(refundChange{prev: s.refund}) 230 s.refund += gas 231 } 232 233 // SubRefund removes gas from the refund counter. 234 // This method will panic if the refund counter goes below zero 235 func (s *StateDB) SubRefund(gas uint64) { 236 s.journal.append(refundChange{prev: s.refund}) 237 if gas > s.refund { 238 panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund)) 239 } 240 s.refund -= gas 241 } 242 243 // Exist reports whether the given account address exists in the state. 244 // Notably this also returns true for suicided accounts. 245 func (s *StateDB) Exist(addr common.Address) bool { 246 return s.getStateObject(addr) != nil 247 } 248 249 // Empty returns whether the state object is either non-existent 250 // or empty according to the EIP161 specification (balance = nonce = code = 0) 251 func (s *StateDB) Empty(addr common.Address) bool { 252 so := s.getStateObject(addr) 253 return so == nil || so.empty() 254 } 255 256 // GetBalance retrieves the balance from the given address or 0 if object not found 257 func (s *StateDB) GetBalance(addr common.Address) *big.Int { 258 stateObject := s.getStateObject(addr) 259 if stateObject != nil { 260 return stateObject.Balance() 261 } 262 return common.Big0 263 } 264 265 func (s *StateDB) GetNonce(addr common.Address) uint64 { 266 stateObject := s.getStateObject(addr) 267 if stateObject != nil { 268 return stateObject.Nonce() 269 } 270 271 return 0 272 } 273 274 // TxIndex returns the current transaction index set by Prepare. 275 func (s *StateDB) TxIndex() int { 276 return s.txIndex 277 } 278 279 // BlockHash returns the current block hash set by Prepare. 280 func (s *StateDB) BlockHash() common.Hash { 281 return s.bhash 282 } 283 284 func (s *StateDB) GetCode(addr common.Address) []byte { 285 stateObject := s.getStateObject(addr) 286 if stateObject != nil { 287 return stateObject.Code(s.db) 288 } 289 return nil 290 } 291 292 func (s *StateDB) GetCodeSize(addr common.Address) int { 293 stateObject := s.getStateObject(addr) 294 if stateObject != nil { 295 return stateObject.CodeSize(s.db) 296 } 297 return 0 298 } 299 300 func (s *StateDB) GetCodeHash(addr common.Address) common.Hash { 301 stateObject := s.getStateObject(addr) 302 if stateObject == nil { 303 return common.Hash{} 304 } 305 return common.BytesToHash(stateObject.CodeHash()) 306 } 307 308 // GetState retrieves a value from the given account's storage trie. 309 func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { 310 stateObject := s.getStateObject(addr) 311 if stateObject != nil { 312 return stateObject.GetState(s.db, hash) 313 } 314 return common.Hash{} 315 } 316 317 // GetProof returns the MerkleProof for a given Account 318 func (s *StateDB) GetProof(a common.Address) ([][]byte, error) { 319 var proof proofList 320 err := s.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof) 321 return [][]byte(proof), err 322 } 323 324 // GetStorageProof returns the StorageProof for given key 325 func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) { 326 var proof proofList 327 trie := s.StorageTrie(a) 328 if trie == nil { 329 return proof, errors.New("storage trie for requested address does not exist") 330 } 331 err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof) 332 return [][]byte(proof), err 333 } 334 335 // GetCommittedState retrieves a value from the given account's committed storage trie. 336 func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { 337 stateObject := s.getStateObject(addr) 338 if stateObject != nil { 339 return stateObject.GetCommittedState(s.db, hash) 340 } 341 return common.Hash{} 342 } 343 344 // Database retrieves the low level database supporting the lower level trie ops. 345 func (s *StateDB) Database() Database { 346 return s.db 347 } 348 349 // StorageTrie returns the storage trie of an account. 350 // The return value is a copy and is nil for non-existent accounts. 351 func (s *StateDB) StorageTrie(addr common.Address) Trie { 352 stateObject := s.getStateObject(addr) 353 if stateObject == nil { 354 return nil 355 } 356 cpy := stateObject.deepCopy(s) 357 cpy.updateTrie(s.db) 358 return cpy.getTrie(s.db) 359 } 360 361 func (s *StateDB) HasSuicided(addr common.Address) bool { 362 stateObject := s.getStateObject(addr) 363 if stateObject != nil { 364 return stateObject.suicided 365 } 366 return false 367 } 368 369 /* 370 * SETTERS 371 */ 372 373 // AddBalance adds amount to the account associated with addr. 374 func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) { 375 stateObject := s.GetOrNewStateObject(addr) 376 if stateObject != nil { 377 stateObject.AddBalance(amount) 378 } 379 } 380 381 // SubBalance subtracts amount from the account associated with addr. 382 func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) { 383 stateObject := s.GetOrNewStateObject(addr) 384 if stateObject != nil { 385 stateObject.SubBalance(amount) 386 } 387 } 388 389 func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) { 390 stateObject := s.GetOrNewStateObject(addr) 391 if stateObject != nil { 392 stateObject.SetBalance(amount) 393 } 394 } 395 396 func (s *StateDB) SetNonce(addr common.Address, nonce uint64) { 397 stateObject := s.GetOrNewStateObject(addr) 398 if stateObject != nil { 399 stateObject.SetNonce(nonce) 400 } 401 } 402 403 func (s *StateDB) SetCode(addr common.Address, code []byte) { 404 stateObject := s.GetOrNewStateObject(addr) 405 if stateObject != nil { 406 stateObject.SetCode(crypto.Keccak256Hash(code), code) 407 } 408 } 409 410 func (s *StateDB) SetState(addr common.Address, key, value common.Hash) { 411 stateObject := s.GetOrNewStateObject(addr) 412 if stateObject != nil { 413 stateObject.SetState(s.db, key, value) 414 } 415 } 416 417 // SetStorage replaces the entire storage for the specified account with given 418 // storage. This function should only be used for debugging. 419 func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) { 420 stateObject := s.GetOrNewStateObject(addr) 421 if stateObject != nil { 422 stateObject.SetStorage(storage) 423 } 424 } 425 426 // Suicide marks the given account as suicided. 427 // This clears the account balance. 428 // 429 // The account's state object is still available until the state is committed, 430 // getStateObject will return a non-nil account after Suicide. 431 func (s *StateDB) Suicide(addr common.Address) bool { 432 stateObject := s.getStateObject(addr) 433 if stateObject == nil { 434 return false 435 } 436 s.journal.append(suicideChange{ 437 account: &addr, 438 prev: stateObject.suicided, 439 prevbalance: new(big.Int).Set(stateObject.Balance()), 440 }) 441 stateObject.markSuicided() 442 stateObject.data.Balance = new(big.Int) 443 444 return true 445 } 446 447 // 448 // Setting, updating & deleting state object methods. 449 // 450 451 // updateStateObject writes the given object to the trie. 452 func (s *StateDB) updateStateObject(obj *stateObject) { 453 // Track the amount of time wasted on updating the account from the trie 454 if metrics.EnabledExpensive { 455 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 456 } 457 // Encode the account and update the account trie 458 addr := obj.Address() 459 460 data, err := rlp.EncodeToBytes(obj) 461 if err != nil { 462 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 463 } 464 if err = s.trie.TryUpdate(addr[:], data); err != nil { 465 s.setError(fmt.Errorf("updateStateObject (%x) error: %v", addr[:], err)) 466 } 467 468 // If state snapshotting is active, cache the data til commit. Note, this 469 // update mechanism is not symmetric to the deletion, because whereas it is 470 // enough to track account updates at commit time, deletions need tracking 471 // at transaction boundary level to ensure we capture state clearing. 472 if s.snap != nil { 473 s.snapAccounts[obj.addrHash] = snapshot.SlimAccountRLP(obj.data.Nonce, obj.data.Balance, obj.data.Root, obj.data.CodeHash) 474 } 475 } 476 477 // deleteStateObject removes the given object from the state trie. 478 func (s *StateDB) deleteStateObject(obj *stateObject) { 479 // Track the amount of time wasted on deleting the account from the trie 480 if metrics.EnabledExpensive { 481 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 482 } 483 // Delete the account from the trie 484 addr := obj.Address() 485 if err := s.trie.TryDelete(addr[:]); err != nil { 486 s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err)) 487 } 488 } 489 490 // getStateObject retrieves a state object given by the address, returning nil if 491 // the object is not found or was deleted in this execution context. If you need 492 // to differentiate between non-existent/just-deleted, use getDeletedStateObject. 493 func (s *StateDB) getStateObject(addr common.Address) *stateObject { 494 if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted { 495 return obj 496 } 497 return nil 498 } 499 500 // getDeletedStateObject is similar to getStateObject, but instead of returning 501 // nil for a deleted state object, it returns the actual object with the deleted 502 // flag set. This is needed by the state journal to revert to the correct s- 503 // destructed object instead of wiping all knowledge about the state object. 504 func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject { 505 // Prefer live objects if any is available 506 if obj := s.stateObjects[addr]; obj != nil { 507 return obj 508 } 509 // If no live objects are available, attempt to use snapshots 510 var ( 511 data *Account 512 err error 513 ) 514 if s.snap != nil { 515 if metrics.EnabledExpensive { 516 defer func(start time.Time) { s.SnapshotAccountReads += time.Since(start) }(time.Now()) 517 } 518 var acc *snapshot.Account 519 if acc, err = s.snap.Account(crypto.Keccak256Hash(addr.Bytes())); err == nil { 520 if acc == nil { 521 return nil 522 } 523 data = &Account{ 524 Nonce: acc.Nonce, 525 Balance: acc.Balance, 526 CodeHash: acc.CodeHash, 527 Root: common.BytesToHash(acc.Root), 528 } 529 if len(data.CodeHash) == 0 { 530 data.CodeHash = emptyCodeHash 531 } 532 if data.Root == (common.Hash{}) { 533 data.Root = emptyRoot 534 } 535 } 536 } 537 // If snapshot unavailable or reading from it failed, load from the database 538 if s.snap == nil || err != nil { 539 if metrics.EnabledExpensive { 540 defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now()) 541 } 542 enc, err := s.trie.TryGet(addr.Bytes()) 543 if err != nil { 544 s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %v", addr.Bytes(), err)) 545 return nil 546 } 547 if len(enc) == 0 { 548 return nil 549 } 550 data = new(Account) 551 if err := rlp.DecodeBytes(enc, data); err != nil { 552 log.Error("Failed to decode state object", "addr", addr, "err", err) 553 return nil 554 } 555 } 556 // Insert into the live set 557 obj := newObject(s, addr, *data) 558 s.setStateObject(obj) 559 return obj 560 } 561 562 func (s *StateDB) setStateObject(object *stateObject) { 563 s.stateObjects[object.Address()] = object 564 } 565 566 // GetOrNewStateObject retrieves a state object or create a new state object if nil. 567 func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { 568 stateObject := s.getStateObject(addr) 569 if stateObject == nil { 570 stateObject, _ = s.createObject(addr) 571 } 572 return stateObject 573 } 574 575 // createObject creates a new state object. If there is an existing account with 576 // the given address, it is overwritten and returned as the second return value. 577 func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { 578 prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that! 579 580 var prevdestruct bool 581 if s.snap != nil && prev != nil { 582 _, prevdestruct = s.snapDestructs[prev.addrHash] 583 if !prevdestruct { 584 s.snapDestructs[prev.addrHash] = struct{}{} 585 } 586 } 587 newobj = newObject(s, addr, Account{}) 588 newobj.setNonce(0) // sets the object to dirty 589 if prev == nil { 590 s.journal.append(createObjectChange{account: &addr}) 591 } else { 592 s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct}) 593 } 594 s.setStateObject(newobj) 595 if prev != nil && !prev.deleted { 596 return newobj, prev 597 } 598 return newobj, nil 599 } 600 601 // CreateAccount explicitly creates a state object. If a state object with the address 602 // already exists the balance is carried over to the new account. 603 // 604 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 605 // a contract does the following: 606 // 607 // 1. sends funds to sha(account ++ (nonce + 1)) 608 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 609 // 610 // Carrying over the balance ensures that Ether doesn't disappear. 611 func (s *StateDB) CreateAccount(addr common.Address) { 612 newObj, prev := s.createObject(addr) 613 if prev != nil { 614 newObj.setBalance(prev.data.Balance) 615 } 616 } 617 618 func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error { 619 so := db.getStateObject(addr) 620 if so == nil { 621 return nil 622 } 623 it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) 624 625 for it.Next() { 626 key := common.BytesToHash(db.trie.GetKey(it.Key)) 627 if value, dirty := so.dirtyStorage[key]; dirty { 628 if !cb(key, value) { 629 return nil 630 } 631 continue 632 } 633 634 if len(it.Value) > 0 { 635 _, content, _, err := rlp.Split(it.Value) 636 if err != nil { 637 return err 638 } 639 if !cb(key, common.BytesToHash(content)) { 640 return nil 641 } 642 } 643 } 644 return nil 645 } 646 647 // Copy creates a deep, independent copy of the state. 648 // Snapshots of the copied state cannot be applied to the copy. 649 func (s *StateDB) Copy() *StateDB { 650 // Copy all the basic fields, initialize the memory ones 651 state := &StateDB{ 652 db: s.db, 653 trie: s.db.CopyTrie(s.trie), 654 stateObjects: make(map[common.Address]*stateObject, len(s.journal.dirties)), 655 stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)), 656 stateObjectsDirty: make(map[common.Address]struct{}, len(s.journal.dirties)), 657 refund: s.refund, 658 logs: make(map[common.Hash][]*types.Log, len(s.logs)), 659 logSize: s.logSize, 660 preimages: make(map[common.Hash][]byte, len(s.preimages)), 661 journal: newJournal(), 662 } 663 // Copy the dirty states, logs, and preimages 664 for addr := range s.journal.dirties { 665 // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527), 666 // and in the Finalise-method, there is a case where an object is in the journal but not 667 // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for 668 // nil 669 if object, exist := s.stateObjects[addr]; exist { 670 // Even though the original object is dirty, we are not copying the journal, 671 // so we need to make sure that anyside effect the journal would have caused 672 // during a commit (or similar op) is already applied to the copy. 673 state.stateObjects[addr] = object.deepCopy(state) 674 675 state.stateObjectsDirty[addr] = struct{}{} // Mark the copy dirty to force internal (code/state) commits 676 state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits 677 } 678 } 679 // Above, we don't copy the actual journal. This means that if the copy is copied, the 680 // loop above will be a no-op, since the copy's journal is empty. 681 // Thus, here we iterate over stateObjects, to enable copies of copies 682 for addr := range s.stateObjectsPending { 683 if _, exist := state.stateObjects[addr]; !exist { 684 state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state) 685 } 686 state.stateObjectsPending[addr] = struct{}{} 687 } 688 for addr := range s.stateObjectsDirty { 689 if _, exist := state.stateObjects[addr]; !exist { 690 state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state) 691 } 692 state.stateObjectsDirty[addr] = struct{}{} 693 } 694 for hash, logs := range s.logs { 695 cpy := make([]*types.Log, len(logs)) 696 for i, l := range logs { 697 cpy[i] = new(types.Log) 698 *cpy[i] = *l 699 } 700 state.logs[hash] = cpy 701 } 702 for hash, preimage := range s.preimages { 703 state.preimages[hash] = preimage 704 } 705 // Do we need to copy the access list? In practice: No. At the start of a 706 // transaction, the access list is empty. In practice, we only ever copy state 707 // _between_ transactions/blocks, never in the middle of a transaction. 708 // However, it doesn't cost us much to copy an empty list, so we do it anyway 709 // to not blow up if we ever decide copy it in the middle of a transaction 710 state.accessList = s.accessList.Copy() 711 return state 712 } 713 714 // Snapshot returns an identifier for the current revision of the state. 715 func (s *StateDB) Snapshot() int { 716 id := s.nextRevisionId 717 s.nextRevisionId++ 718 s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()}) 719 return id 720 } 721 722 // RevertToSnapshot reverts all state changes made since the given revision. 723 func (s *StateDB) RevertToSnapshot(revid int) { 724 // Find the snapshot in the stack of valid snapshots. 725 idx := sort.Search(len(s.validRevisions), func(i int) bool { 726 return s.validRevisions[i].id >= revid 727 }) 728 if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid { 729 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 730 } 731 snapshot := s.validRevisions[idx].journalIndex 732 733 // Replay the journal to undo changes and remove invalidated snapshots 734 s.journal.revert(s, snapshot) 735 s.validRevisions = s.validRevisions[:idx] 736 } 737 738 // GetRefund returns the current value of the refund counter. 739 func (s *StateDB) GetRefund() uint64 { 740 return s.refund 741 } 742 743 // Finalise finalises the state by removing the s destructed objects and clears 744 // the journal as well as the refunds. Finalise, however, will not push any updates 745 // into the tries just yet. Only IntermediateRoot or Commit will do that. 746 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 747 for addr := range s.journal.dirties { 748 obj, exist := s.stateObjects[addr] 749 if !exist { 750 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 751 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 752 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 753 // it will persist in the journal even though the journal is reverted. In this special circumstance, 754 // it may exist in `s.journal.dirties` but not in `s.stateObjects`. 755 // Thus, we can safely ignore it here 756 continue 757 } 758 if obj.suicided || (deleteEmptyObjects && obj.empty()) { 759 obj.deleted = true 760 761 // If state snapshotting is active, also mark the destruction there. 762 // Note, we can't do this only at the end of a block because multiple 763 // transactions within the same block might self destruct and then 764 // ressurrect an account; but the snapshotter needs both events. 765 if s.snap != nil { 766 s.snapDestructs[obj.addrHash] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely) 767 delete(s.snapAccounts, obj.addrHash) // Clear out any previously updated account data (may be recreated via a ressurrect) 768 delete(s.snapStorage, obj.addrHash) // Clear out any previously updated storage data (may be recreated via a ressurrect) 769 } 770 } else { 771 obj.finalise() 772 } 773 s.stateObjectsPending[addr] = struct{}{} 774 s.stateObjectsDirty[addr] = struct{}{} 775 } 776 // Invalidate journal because reverting across transactions is not allowed. 777 s.clearJournalAndRefund() 778 } 779 780 // IntermediateRoot computes the current root hash of the state trie. 781 // It is called in between transactions to get the root hash that 782 // goes into transaction receipts. 783 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 784 // Finalise all the dirty storage states and write them into the tries 785 s.Finalise(deleteEmptyObjects) 786 787 for addr := range s.stateObjectsPending { 788 obj := s.stateObjects[addr] 789 if obj.deleted { 790 s.deleteStateObject(obj) 791 } else { 792 obj.updateRoot(s.db) 793 s.updateStateObject(obj) 794 } 795 } 796 if len(s.stateObjectsPending) > 0 { 797 s.stateObjectsPending = make(map[common.Address]struct{}) 798 } 799 // Track the amount of time wasted on hashing the account trie 800 if metrics.EnabledExpensive { 801 defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now()) 802 } 803 return s.trie.Hash() 804 } 805 806 // Prepare sets the current transaction hash and index and block hash which is 807 // used when the EVM emits new state logs. 808 func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) { 809 s.thash = thash 810 s.bhash = bhash 811 s.txIndex = ti 812 s.accessList = newAccessList() 813 } 814 815 func (s *StateDB) clearJournalAndRefund() { 816 if len(s.journal.entries) > 0 { 817 s.journal = newJournal() 818 s.refund = 0 819 } 820 s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires 821 } 822 823 // Commit writes the state to the underlying in-memory trie database. 824 func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) { 825 if s.dbErr != nil { 826 return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr) 827 } 828 // Finalize any pending changes and merge everything into the tries 829 s.IntermediateRoot(deleteEmptyObjects) 830 831 // Commit objects to the trie, measuring the elapsed time 832 codeWriter := s.db.TrieDB().DiskDB().NewBatch() 833 for addr := range s.stateObjectsDirty { 834 if obj := s.stateObjects[addr]; !obj.deleted { 835 // Write any contract code associated with the state object 836 if obj.code != nil && obj.dirtyCode { 837 rawdb.WriteCode(codeWriter, common.BytesToHash(obj.CodeHash()), obj.code) 838 obj.dirtyCode = false 839 } 840 // Write any storage changes in the state object to its storage trie 841 if err := obj.CommitTrie(s.db); err != nil { 842 return common.Hash{}, err 843 } 844 } 845 } 846 if len(s.stateObjectsDirty) > 0 { 847 s.stateObjectsDirty = make(map[common.Address]struct{}) 848 } 849 if codeWriter.ValueSize() > 0 { 850 if err := codeWriter.Write(); err != nil { 851 log.Crit("Failed to commit dirty codes", "error", err) 852 } 853 } 854 // Write the account trie changes, measuing the amount of wasted time 855 var start time.Time 856 if metrics.EnabledExpensive { 857 start = time.Now() 858 } 859 // The onleaf func is called _serially_, so we can reuse the same account 860 // for unmarshalling every time. 861 var account Account 862 root, err := s.trie.Commit(func(path []byte, leaf []byte, parent common.Hash) error { 863 if err := rlp.DecodeBytes(leaf, &account); err != nil { 864 return nil 865 } 866 if account.Root != emptyRoot { 867 s.db.TrieDB().Reference(account.Root, parent) 868 } 869 return nil 870 }) 871 if metrics.EnabledExpensive { 872 s.AccountCommits += time.Since(start) 873 } 874 // If snapshotting is enabled, update the snapshot tree with this new version 875 if s.snap != nil { 876 if metrics.EnabledExpensive { 877 defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now()) 878 } 879 // Only update if there's a state transition (skip empty Clique blocks) 880 if parent := s.snap.Root(); parent != root { 881 if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil { 882 log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err) 883 } 884 // Keep 128 diff layers in the memory, persistent layer is 129th. 885 // - head layer is paired with HEAD state 886 // - head-1 layer is paired with HEAD-1 state 887 // - head-127 layer(bottom-most diff layer) is paired with HEAD-127 state 888 if err := s.snaps.Cap(root, 128); err != nil { 889 log.Warn("Failed to cap snapshot tree", "root", root, "layers", 128, "err", err) 890 } 891 } 892 s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil 893 } 894 return root, err 895 } 896 897 // AddAddressToAccessList adds the given address to the access list 898 func (s *StateDB) AddAddressToAccessList(addr common.Address) { 899 if s.accessList.AddAddress(addr) { 900 s.journal.append(accessListAddAccountChange{&addr}) 901 } 902 } 903 904 // AddSlotToAccessList adds the given (address, slot)-tuple to the access list 905 func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) { 906 addrMod, slotMod := s.accessList.AddSlot(addr, slot) 907 if addrMod { 908 // In practice, this should not happen, since there is no way to enter the 909 // scope of 'address' without having the 'address' become already added 910 // to the access list (via call-variant, create, etc). 911 // Better safe than sorry, though 912 s.journal.append(accessListAddAccountChange{&addr}) 913 } 914 if slotMod { 915 s.journal.append(accessListAddSlotChange{ 916 address: &addr, 917 slot: &slot, 918 }) 919 } 920 } 921 922 // AddressInAccessList returns true if the given address is in the access list. 923 func (s *StateDB) AddressInAccessList(addr common.Address) bool { 924 return s.accessList.ContainsAddress(addr) 925 } 926 927 // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list. 928 func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) { 929 return s.accessList.Contains(addr, slot) 930 }