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