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