github.com/klaytn/klaytn@v1.12.1/blockchain/state/statedb.go (about) 1 // Modifications Copyright 2018 The klaytn Authors 2 // Copyright 2015 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // This file is derived from core/state/statedb.go (2018/06/04). 19 // Modified and improved for the klaytn development. 20 21 package state 22 23 import ( 24 "fmt" 25 "math/big" 26 "sort" 27 "sync/atomic" 28 "time" 29 30 "github.com/klaytn/klaytn/blockchain/types" 31 "github.com/klaytn/klaytn/blockchain/types/account" 32 "github.com/klaytn/klaytn/blockchain/types/accountkey" 33 "github.com/klaytn/klaytn/common" 34 "github.com/klaytn/klaytn/crypto" 35 "github.com/klaytn/klaytn/log" 36 "github.com/klaytn/klaytn/params" 37 "github.com/klaytn/klaytn/rlp" 38 "github.com/klaytn/klaytn/snapshot" 39 "github.com/klaytn/klaytn/storage/statedb" 40 ) 41 42 type revision struct { 43 id int 44 journalIndex int 45 } 46 47 var ( 48 // emptyState is the known hash of an empty state trie entry. 49 emptyState = crypto.Keccak256Hash(nil) 50 51 // emptyCode is the known hash of the empty EVM bytecode. 52 emptyCode = crypto.Keccak256Hash(nil) 53 54 logger = log.NewModuleLogger(log.BlockchainState) 55 56 // TODO-Klaytn EnabledExpensive and DBConfig.EnableDBPerfMetrics will be merged 57 EnabledExpensive = false 58 ) 59 60 // StateDBs within the Klaytn protocol are used to cache stateObjects from Merkle Patricia Trie 61 // and mediate the operations to them. 62 type StateDB struct { 63 db Database 64 trie Trie 65 trieOpts *statedb.TrieOpts 66 67 snaps *snapshot.Tree 68 snap snapshot.Snapshot 69 snapDestructs map[common.Hash]struct{} 70 snapAccounts map[common.Hash][]byte 71 snapStorage map[common.Hash]map[common.Hash][]byte 72 73 // This map holds 'live' objects, which will get modified while processing a state transition. 74 stateObjects map[common.Address]*stateObject 75 stateObjectsDirty map[common.Address]struct{} 76 stateObjectsDirtyStorage map[common.Address]struct{} 77 78 // DB error. 79 // State objects are used by the consensus core and VM which are 80 // unable to deal with database-level errors. Any error that occurs 81 // during a database read is memoized here and will eventually be returned 82 // by StateDB.Commit. 83 dbErr error 84 85 // The refund counter, also used by state transitioning. 86 refund uint64 87 88 thash, bhash common.Hash 89 txIndex int 90 logs map[common.Hash][]*types.Log 91 logSize uint 92 93 preimages map[common.Hash][]byte 94 95 // Per-transaction access list 96 accessList *accessList 97 98 // Transient storage 99 transientStorage transientStorage 100 101 // Journal of state modifications. This is the backbone of 102 // Snapshot and RevertToSnapshot. 103 journal *journal 104 validRevisions []revision 105 nextRevisionId int 106 107 prefetching bool 108 109 // Measurements gathered during execution for debugging purposes 110 AccountReads time.Duration 111 AccountHashes time.Duration 112 AccountUpdates time.Duration 113 AccountCommits time.Duration 114 StorageReads time.Duration 115 StorageHashes time.Duration 116 StorageUpdates time.Duration 117 StorageCommits time.Duration 118 SnapshotAccountReads time.Duration 119 SnapshotStorageReads time.Duration 120 SnapshotCommits time.Duration 121 } 122 123 // Create a new state from a given trie. 124 func New(root common.Hash, db Database, snaps *snapshot.Tree, opts *statedb.TrieOpts) (*StateDB, error) { 125 tr, err := db.OpenTrie(root, opts) 126 if err != nil { 127 return nil, err 128 } 129 sdb := &StateDB{ 130 db: db, 131 trie: tr, 132 trieOpts: opts, 133 snaps: snaps, 134 stateObjects: make(map[common.Address]*stateObject), 135 stateObjectsDirtyStorage: make(map[common.Address]struct{}), 136 stateObjectsDirty: make(map[common.Address]struct{}), 137 logs: make(map[common.Hash][]*types.Log), 138 preimages: make(map[common.Hash][]byte), 139 accessList: newAccessList(), 140 transientStorage: newTransientStorage(), 141 journal: newJournal(), 142 } 143 if sdb.snaps != nil { 144 if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil { 145 sdb.snapDestructs = make(map[common.Hash]struct{}) 146 sdb.snapAccounts = make(map[common.Hash][]byte) 147 sdb.snapStorage = make(map[common.Hash]map[common.Hash][]byte) 148 } 149 } 150 if opts != nil && opts.Prefetching { 151 sdb.prefetching = true 152 } 153 return sdb, nil 154 } 155 156 // RLockGCCachedNode locks the GC lock of CachedNode. 157 func (s *StateDB) LockGCCachedNode() { 158 s.db.RLockGCCachedNode() 159 } 160 161 // RUnlockGCCachedNode unlocks the GC lock of CachedNode. 162 func (s *StateDB) UnlockGCCachedNode() { 163 s.db.RUnlockGCCachedNode() 164 } 165 166 // setError remembers the first non-nil error it is called with. 167 func (s *StateDB) setError(err error) { 168 if s.dbErr == nil { 169 s.dbErr = err 170 } 171 } 172 173 func (s *StateDB) Error() error { 174 return s.dbErr 175 } 176 177 // Reset clears out all ephemeral state objects from the state db, but keeps 178 // the underlying state trie to avoid reloading data for the next operations. 179 func (s *StateDB) Reset(root common.Hash) error { 180 tr, err := s.db.OpenTrie(root, s.trieOpts) 181 if err != nil { 182 return err 183 } 184 s.trie = tr 185 s.stateObjects = make(map[common.Address]*stateObject) 186 s.stateObjectsDirty = make(map[common.Address]struct{}) 187 s.thash = common.Hash{} 188 s.bhash = common.Hash{} 189 s.txIndex = 0 190 s.logs = make(map[common.Hash][]*types.Log) 191 s.logSize = 0 192 s.preimages = make(map[common.Hash][]byte) 193 s.clearJournalAndRefund() 194 s.accessList = newAccessList() 195 return nil 196 } 197 198 func (s *StateDB) AddLog(log *types.Log) { 199 s.journal.append(addLogChange{txhash: s.thash}) 200 201 log.TxHash = s.thash 202 log.BlockHash = s.bhash 203 log.TxIndex = uint(s.txIndex) 204 log.Index = s.logSize 205 s.logs[s.thash] = append(s.logs[s.thash], log) 206 s.logSize++ 207 } 208 209 func (s *StateDB) GetLogs(hash common.Hash) []*types.Log { 210 return s.logs[hash] 211 } 212 213 func (s *StateDB) Logs() []*types.Log { 214 var logs []*types.Log 215 for _, lgs := range s.logs { 216 logs = append(logs, lgs...) 217 } 218 return logs 219 } 220 221 // AddPreimage records a SHA3 preimage seen by the VM. 222 func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 223 if _, ok := s.preimages[hash]; !ok { 224 s.journal.append(addPreimageChange{hash: hash}) 225 pi := make([]byte, len(preimage)) 226 copy(pi, preimage) 227 s.preimages[hash] = pi 228 } 229 } 230 231 // Preimages returns a list of SHA3 preimages that have been submitted. 232 func (s *StateDB) Preimages() map[common.Hash][]byte { 233 return s.preimages 234 } 235 236 // AddRefund adds gas to the refund counter 237 func (s *StateDB) AddRefund(gas uint64) { 238 s.journal.append(refundChange{prev: s.refund}) 239 s.refund += gas 240 } 241 242 // SubRefund removes gas from the refund counter. 243 // This method will panic if the refund counter goes below zero 244 func (s *StateDB) SubRefund(gas uint64) { 245 s.journal.append(refundChange{prev: s.refund}) 246 if gas > s.refund { 247 panic("Refund counter below zero") 248 } 249 s.refund -= gas 250 } 251 252 // Exist reports whether the given account address exists in the state. 253 // Notably this also returns true for self-destructed accounts. 254 func (s *StateDB) Exist(addr common.Address) bool { 255 return s.getStateObject(addr) != nil 256 } 257 258 // Empty returns whether the state object is either non-existent 259 // or empty according to the EIP161 specification (balance = nonce = code = 0) 260 func (s *StateDB) Empty(addr common.Address) bool { 261 so := s.getStateObject(addr) 262 return so == nil || so.empty() 263 } 264 265 // Retrieve the balance from the given address or 0 if object not found 266 func (s *StateDB) GetBalance(addr common.Address) *big.Int { 267 stateObject := s.getStateObject(addr) 268 if stateObject != nil { 269 return stateObject.Balance() 270 } 271 return common.Big0 272 } 273 274 func (s *StateDB) GetNonce(addr common.Address) uint64 { 275 stateObject := s.getStateObject(addr) 276 if stateObject != nil { 277 return stateObject.Nonce() 278 } 279 return 0 280 } 281 282 func (s *StateDB) GetCode(addr common.Address) []byte { 283 stateObject := s.getStateObject(addr) 284 if stateObject != nil { 285 return stateObject.Code(s.db) 286 } 287 return nil 288 } 289 290 func (s *StateDB) GetAccount(addr common.Address) account.Account { 291 stateObject := s.getStateObject(addr) 292 if stateObject != nil { 293 return stateObject.account 294 } 295 return nil 296 } 297 298 func (s *StateDB) IsContractAccount(addr common.Address) bool { 299 stateObject := s.getStateObject(addr) 300 if stateObject != nil { 301 return stateObject.IsContractAccount() 302 } 303 return false 304 } 305 306 //func (self *StateDB) IsHumanReadable(addr common.Address) bool { 307 // stateObject := self.getStateObject(addr) 308 // if stateObject != nil { 309 // return stateObject.HumanReadable() 310 // } 311 // return false 312 //} 313 314 func (s *StateDB) GetCodeSize(addr common.Address) int { 315 stateObject := s.getStateObject(addr) 316 if stateObject != nil { 317 return stateObject.CodeSize(s.db) 318 } 319 return 0 320 } 321 322 func (s *StateDB) GetCodeHash(addr common.Address) common.Hash { 323 stateObject := s.getStateObject(addr) 324 if stateObject == nil { 325 return common.BytesToHash(emptyCodeHash) 326 } 327 return common.BytesToHash(stateObject.CodeHash()) 328 } 329 330 // GetState retrieves a value from the given account's storage trie. 331 func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { 332 stateObject := s.getStateObject(addr) 333 if stateObject != nil { 334 return stateObject.GetState(s.db, hash) 335 } 336 return common.Hash{} 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 // IsContractAvailable returns true if the account corresponding to the given address implements ProgramAccount. 349 func (s *StateDB) IsContractAvailable(addr common.Address) bool { 350 stateObject := s.getStateObject(addr) 351 if stateObject != nil { 352 return stateObject.IsContractAvailable() 353 } 354 return false 355 } 356 357 // IsProgramAccount returns true if the account corresponding to the given address implements ProgramAccount. 358 func (s *StateDB) IsProgramAccount(addr common.Address) bool { 359 stateObject := s.getStateObject(addr) 360 if stateObject != nil { 361 return stateObject.IsProgramAccount() 362 } 363 return false 364 } 365 366 func (s *StateDB) IsValidCodeFormat(addr common.Address) bool { 367 stateObject := s.getStateObject(addr) 368 if stateObject != nil { 369 pa := account.GetProgramAccount(stateObject.account) 370 if pa != nil { 371 return pa.GetCodeFormat().Validate() 372 } 373 return false 374 } 375 return false 376 } 377 378 // GetVmVersion return false when getStateObject(addr) or GetProgramAccount(stateObject.account) is failed. 379 func (s *StateDB) GetVmVersion(addr common.Address) (params.VmVersion, bool) { 380 stateObject := s.getStateObject(addr) 381 if stateObject != nil { 382 pa := account.GetProgramAccount(stateObject.account) 383 if pa != nil { 384 return pa.GetVmVersion(), true 385 } 386 return params.VmVersion0, false 387 } 388 return params.VmVersion0, false 389 } 390 391 func (s *StateDB) GetKey(addr common.Address) accountkey.AccountKey { 392 stateObject := s.getStateObject(addr) 393 if stateObject != nil { 394 return stateObject.GetKey() 395 } 396 return accountkey.NewAccountKeyLegacy() 397 } 398 399 // Database retrieves the low level database supporting the lower level trie ops. 400 func (s *StateDB) Database() Database { 401 return s.db 402 } 403 404 // StorageTrie returns the storage trie of an account. 405 // The return value is a copy and is nil for non-existent accounts. 406 func (s *StateDB) StorageTrie(addr common.Address) Trie { 407 stateObject := s.getStateObject(addr) 408 if stateObject == nil { 409 return nil 410 } 411 cpy := stateObject.deepCopy(s) 412 return cpy.updateStorageTrie(s.db) 413 } 414 415 func (s *StateDB) HasSelfDestructed(addr common.Address) bool { 416 stateObject := s.getStateObject(addr) 417 if stateObject != nil { 418 return stateObject.selfDestructed 419 } 420 return false 421 } 422 423 /* 424 * SETTERS 425 */ 426 427 // AddBalance adds amount to the account associated with addr. 428 func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) { 429 stateObject := s.GetOrNewStateObject(addr) 430 if stateObject != nil { 431 stateObject.AddBalance(amount) 432 } 433 } 434 435 // SubBalance subtracts amount from the account associated with addr. 436 func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) { 437 stateObject := s.GetOrNewStateObject(addr) 438 if stateObject != nil { 439 stateObject.SubBalance(amount) 440 } 441 } 442 443 func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) { 444 stateObject := s.GetOrNewStateObject(addr) 445 if stateObject != nil { 446 stateObject.SetBalance(amount) 447 } 448 } 449 450 // IncNonce increases the nonce of the account of the given address by one. 451 func (s *StateDB) IncNonce(addr common.Address) { 452 stateObject := s.GetOrNewStateObject(addr) 453 if stateObject != nil { 454 stateObject.IncNonce() 455 } 456 } 457 458 func (s *StateDB) SetNonce(addr common.Address, nonce uint64) { 459 stateObject := s.GetOrNewStateObject(addr) 460 if stateObject != nil { 461 stateObject.SetNonce(nonce) 462 } 463 } 464 465 func (s *StateDB) SetCode(addr common.Address, code []byte) error { 466 stateObject := s.GetOrNewSmartContract(addr) 467 if stateObject != nil { 468 return stateObject.SetCode(crypto.Keccak256Hash(code), code) 469 } 470 471 return nil 472 } 473 474 func (s *StateDB) SetState(addr common.Address, key, value common.Hash) { 475 stateObject := s.GetOrNewSmartContract(addr) 476 if stateObject != nil { 477 stateObject.SetState(s.db, key, value) 478 } 479 } 480 481 // SetStorage replaces the entire storage for the specified account with given 482 // storage. This function should only be used for debugging. 483 func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) { 484 stateObject := s.GetOrNewStateObject(addr) 485 if stateObject != nil { 486 stateObject.SetStorage(storage) 487 } 488 } 489 490 // UpdateKey updates the account's key with the given key. 491 func (s *StateDB) UpdateKey(addr common.Address, newKey accountkey.AccountKey, currentBlockNumber uint64) error { 492 stateObject := s.getStateObject(addr) 493 if stateObject != nil { 494 return stateObject.UpdateKey(newKey, currentBlockNumber) 495 } 496 497 return errAccountDoesNotExist 498 } 499 500 // SelfDestruct marks the given account as self-destructed. 501 // This clears the account balance. 502 // 503 // The account's state object is still available until the state is committed, 504 // getStateObject will return a non-nil account after SelfDestruct. 505 func (s *StateDB) SelfDestruct(addr common.Address) { 506 stateObject := s.getStateObject(addr) 507 if stateObject == nil { 508 return 509 } 510 s.journal.append(selfDestructChange{ 511 account: &addr, 512 prev: stateObject.selfDestructed, 513 prevbalance: new(big.Int).Set(stateObject.Balance()), 514 }) 515 stateObject.markSelfdestructed() 516 stateObject.account.SetBalance(new(big.Int)) 517 } 518 519 func (s *StateDB) SelfDestruct6780(addr common.Address) { 520 stateObject := s.getStateObject(addr) 521 if stateObject == nil { 522 return 523 } 524 525 if stateObject.created { 526 s.SelfDestruct(addr) 527 } 528 } 529 530 // SetTransientState sets transient storage for a given account. It 531 // adds the change to the journal so that it can be rolled back 532 // to its previous value if there is a revert. 533 func (s *StateDB) SetTransientState(addr common.Address, key, value common.Hash) { 534 prev := s.GetTransientState(addr, key) 535 if prev == value { 536 return 537 } 538 539 s.journal.append(transientStorageChange{ 540 account: &addr, 541 key: key, 542 prevalue: prev, 543 }) 544 545 s.setTransientState(addr, key, value) 546 } 547 548 // setTransientState is a lower level setter for transient storage. It 549 // is called during a revert to prevent modifications to the journal. 550 func (s *StateDB) setTransientState(addr common.Address, key, value common.Hash) { 551 s.transientStorage.Set(addr, key, value) 552 } 553 554 // GetTransientState gets transient storage for a given account. 555 func (s *StateDB) GetTransientState(addr common.Address, key common.Hash) common.Hash { 556 return s.transientStorage.Get(addr, key) 557 } 558 559 // 560 // Setting, updating & deleting state object methods. 561 // 562 563 // updateStateObject writes the given object to the statedb. 564 func (s *StateDB) updateStateObject(stateObject *stateObject) { 565 // Track the amount of time wasted on updating the account from the trie 566 if EnabledExpensive { 567 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 568 } 569 addr := stateObject.Address() 570 var snapshotData []byte 571 if data := stateObject.encoded.Load(); data != nil { 572 encodedData := data.(*encodedData) 573 if encodedData.err != nil { 574 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], encodedData.err)) 575 } 576 s.setError(s.trie.TryUpdateWithKeys(addr[:], 577 encodedData.trieHashKey, encodedData.trieHexKey, encodedData.data)) 578 stateObject.encoded = atomic.Value{} 579 snapshotData = encodedData.data 580 } else { 581 data, err := rlp.EncodeToBytes(stateObject) 582 if err != nil { 583 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 584 } 585 s.setError(s.trie.TryUpdate(addr[:], data)) 586 snapshotData = data 587 } 588 589 // If state snapshotting is active, cache the data til commit. Note, this 590 // update mechanism is not symmetric to the deletion, because whereas it is 591 // enough to track account updates at commit time, deletions need tracking 592 // at transaction boundary level to ensure we capture state clearing. 593 if s.snap != nil { 594 s.snapAccounts[stateObject.addrHash] = snapshotData 595 } 596 } 597 598 // deleteStateObject removes the given object from the state trie. 599 func (s *StateDB) deleteStateObject(stateObject *stateObject) { 600 // Track the amount of time wasted on deleting the account from the trie 601 if EnabledExpensive { 602 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 603 } 604 stateObject.deleted = true 605 addr := stateObject.Address() 606 s.setError(s.trie.TryDelete(addr[:])) 607 } 608 609 // getStateObject retrieves a state object given by the address, returning nil if 610 // the object is not found or was deleted in this execution context. If you need 611 // to differentiate between non-existent/just-deleted, use getDeletedStateObject. 612 func (s *StateDB) getStateObject(addr common.Address) *stateObject { 613 if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted { 614 return obj 615 } 616 return nil 617 } 618 619 // getDeletedStateObject is similar to getStateObject, but instead of returning 620 // nil for a deleted state object, it returns the actual object with the deleted 621 // flag set. This is needed by the state journal to revert to the correct s- 622 // destructed object instead of wiping all knowledge about the state object. 623 func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject { 624 // First, check stateObjects if there is "live" object. 625 if obj := s.stateObjects[addr]; obj != nil { 626 return obj 627 } 628 // If no live objects are available, attempt to use snapshots 629 var ( 630 acc account.Account 631 err error 632 ) 633 if s.snap != nil { 634 if EnabledExpensive { 635 defer func(start time.Time) { s.SnapshotAccountReads += time.Since(start) }(time.Now()) 636 } 637 if acc, err = s.snap.Account(crypto.Keccak256Hash(addr.Bytes())); err == nil { 638 if acc == nil { 639 return nil 640 } 641 } 642 } 643 // If snapshot unavailable or reading from it failed, load from the database 644 if s.snap == nil || err != nil { 645 // Track the amount of time wasted on loading the object from the database 646 if EnabledExpensive { 647 defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now()) 648 } 649 // Second, the object for given address is not cached. 650 // Load the object from the database. 651 enc, err := s.trie.TryGet(addr[:]) 652 if len(enc) == 0 { 653 s.setError(err) 654 return nil 655 } 656 serializer := account.NewAccountSerializer() 657 if err := rlp.DecodeBytes(enc, serializer); err != nil { 658 logger.Error("Failed to decode state object", "addr", addr, "err", err) 659 return nil 660 } 661 acc = serializer.GetAccount() 662 } 663 // Insert into the live set. 664 obj := newObject(s, addr, acc) 665 s.setStateObject(obj) 666 667 return obj 668 } 669 670 func (s *StateDB) setStateObject(object *stateObject) { 671 s.stateObjects[object.Address()] = object 672 } 673 674 // Retrieve a state object or create a new state object if nil. 675 func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { 676 stateObject := s.getStateObject(addr) 677 if stateObject == nil || stateObject.deleted { 678 stateObject, _ = s.createObject(addr) 679 } 680 return stateObject 681 } 682 683 // Retrieve a state object or create a new state object if nil. 684 func (s *StateDB) GetOrNewSmartContract(addr common.Address) *stateObject { 685 stateObject := s.getStateObject(addr) 686 if stateObject == nil || stateObject.deleted { 687 stateObject, _ = s.createObjectWithMap(addr, account.SmartContractAccountType, map[account.AccountValueKeyType]interface{}{ 688 account.AccountValueKeyNonce: uint64(1), 689 account.AccountValueKeyHumanReadable: false, 690 account.AccountValueKeyAccountKey: accountkey.NewAccountKeyFail(), 691 }) 692 } 693 return stateObject 694 } 695 696 // createObject creates a new state object. If there is an existing account with 697 // the given address, it is overwritten and returned as the second return value. 698 func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { 699 prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that! 700 701 var prevdestruct bool 702 if s.snap != nil && prev != nil { 703 _, prevdestruct = s.snapDestructs[prev.addrHash] 704 if !prevdestruct { 705 s.snapDestructs[prev.addrHash] = struct{}{} 706 } 707 } 708 acc, err := account.NewAccountWithType(account.ExternallyOwnedAccountType) 709 if err != nil { 710 logger.Error("An error occurred on call NewAccountWithType", "err", err) 711 } 712 newobj = newObject(s, addr, acc) 713 newobj.setNonce(0) // sets the object to dirty 714 if prev == nil { 715 s.journal.append(createObjectChange{account: &addr}) 716 } else { 717 s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct}) 718 } 719 720 newobj.created = true 721 722 s.setStateObject(newobj) 723 if prev != nil && !prev.deleted { 724 return newobj, prev 725 } 726 return newobj, nil 727 } 728 729 // createObjectWithMap creates a new state object with the given parameters (accountType and values). 730 // If there is an existing account with the given address, it is overwritten and 731 // returned as the second return value. 732 func (s *StateDB) createObjectWithMap(addr common.Address, accountType account.AccountType, 733 values map[account.AccountValueKeyType]interface{}, 734 ) (newobj, prev *stateObject) { 735 prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that! 736 737 var prevdestruct bool 738 if s.snap != nil && prev != nil { 739 _, prevdestruct = s.snapDestructs[prev.addrHash] 740 if !prevdestruct { 741 s.snapDestructs[prev.addrHash] = struct{}{} 742 } 743 } 744 acc, err := account.NewAccountWithMap(accountType, values) 745 if err != nil { 746 logger.Error("An error occurred on call NewAccountWithMap", "err", err) 747 } 748 newobj = newObject(s, addr, acc) 749 newobj.setNonce(0) // sets the object to dirty 750 if prev == nil { 751 s.journal.append(createObjectChange{account: &addr}) 752 } else { 753 s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct}) 754 } 755 756 newobj.created = true 757 758 s.setStateObject(newobj) 759 if prev != nil && !prev.deleted { 760 return newobj, prev 761 } 762 return newobj, nil 763 } 764 765 // CreateAccount explicitly creates a state object. If a state object with the address 766 // already exists, the balance is carried over to the new account. 767 // Carrying over the balance ensures that Ether doesn't disappear. 768 // 769 // CreateAccount is currently used for test code only. Instead, 770 // use CreateEOA, CreateSmartContractAccount, or CreateSmartContractAccountWithKey to create a typed account. 771 func (s *StateDB) CreateAccount(addr common.Address) { 772 new, prev := s.createObject(addr) 773 if prev != nil { 774 new.setBalance(prev.account.GetBalance()) 775 } 776 } 777 778 func (s *StateDB) CreateEOA(addr common.Address, humanReadable bool, key accountkey.AccountKey) { 779 values := map[account.AccountValueKeyType]interface{}{ 780 account.AccountValueKeyHumanReadable: humanReadable, 781 account.AccountValueKeyAccountKey: key, 782 } 783 new, prev := s.createObjectWithMap(addr, account.ExternallyOwnedAccountType, values) 784 if prev != nil { 785 new.setBalance(prev.account.GetBalance()) 786 } 787 } 788 789 func (s *StateDB) CreateSmartContractAccount(addr common.Address, format params.CodeFormat, r params.Rules) { 790 s.CreateSmartContractAccountWithKey(addr, false, accountkey.NewAccountKeyFail(), format, r) 791 } 792 793 func (s *StateDB) CreateSmartContractAccountWithKey(addr common.Address, humanReadable bool, key accountkey.AccountKey, format params.CodeFormat, r params.Rules) { 794 values := map[account.AccountValueKeyType]interface{}{ 795 account.AccountValueKeyNonce: uint64(1), 796 account.AccountValueKeyHumanReadable: humanReadable, 797 account.AccountValueKeyAccountKey: key, 798 account.AccountValueKeyCodeInfo: params.NewCodeInfoWithRules(format, r), 799 } 800 new, prev := s.createObjectWithMap(addr, account.SmartContractAccountType, values) 801 if prev != nil { 802 new.setBalance(prev.account.GetBalance()) 803 } 804 } 805 806 func (s *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { 807 so := s.getStateObject(addr) 808 if so == nil { 809 return 810 } 811 it := statedb.NewIterator(so.getStorageTrie(s.db).NodeIterator(nil)) 812 for it.Next() { 813 key := common.BytesToHash(s.trie.GetKey(it.Key)) 814 if value, dirty := so.dirtyStorage[key]; dirty { 815 cb(key, value) 816 continue 817 } 818 enc := it.Value 819 if len(enc) > 0 { 820 _, content, _, _ := rlp.Split(enc) 821 cb(key, common.BytesToHash(content)) 822 } else { 823 cb(key, common.Hash{}) 824 } 825 } 826 } 827 828 // Copy creates a deep, independent copy of the state. 829 // Snapshots of the copied state cannot be applied to the copy. 830 func (s *StateDB) Copy() *StateDB { 831 // Copy all the basic fields, initialize the memory ones 832 state := &StateDB{ 833 db: s.db, 834 trie: s.db.CopyTrie(s.trie), 835 stateObjects: make(map[common.Address]*stateObject, len(s.journal.dirties)), 836 stateObjectsDirty: make(map[common.Address]struct{}, len(s.journal.dirties)), 837 refund: s.refund, 838 logs: make(map[common.Hash][]*types.Log, len(s.logs)), 839 logSize: s.logSize, 840 preimages: make(map[common.Hash][]byte), 841 journal: newJournal(), 842 } 843 // Copy the dirty states, logs, and preimages 844 for addr := range s.journal.dirties { 845 // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527), 846 // and in the Finalise-method, there is a case where an object is in the journal but not 847 // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for 848 // nil 849 if object, exist := s.stateObjects[addr]; exist { 850 state.stateObjects[addr] = object.deepCopy(state) 851 state.stateObjectsDirty[addr] = struct{}{} 852 } 853 } 854 // Above, we don't copy the actual journal. This means that if the copy is copied, the 855 // loop above will be a no-op, since the copy's journal is empty. 856 // Thus, here we iterate over stateObjects, to enable copies of copies 857 for addr := range s.stateObjectsDirty { 858 if _, exist := state.stateObjects[addr]; !exist { 859 state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state) 860 state.stateObjectsDirty[addr] = struct{}{} 861 } 862 } 863 864 deepCopyLogs(s, state) 865 866 for hash, preimage := range s.preimages { 867 state.preimages[hash] = preimage 868 } 869 870 // Do we need to copy the access list? In practice: No. At the start of a 871 // transaction, the access list is empty. In practice, we only ever copy state 872 // _between_ transactions/blocks, never in the middle of a transaction. 873 // However, it doesn't cost us much to copy an empty list, so we do it anyway 874 // to not blow up if we ever decide copy it in the middle of a transaction 875 state.accessList = s.accessList.Copy() 876 state.transientStorage = s.transientStorage.Copy() 877 if s.snaps != nil { 878 // In order for the miner to be able to use and make additions 879 // to the snapshot tree, we need to copy that aswell. 880 // Otherwise, any block mined by ourselves will cause gaps in the tree, 881 // and force the miner to operate trie-backed only 882 state.snaps = s.snaps 883 state.snap = s.snap 884 // deep copy needed 885 state.snapDestructs = make(map[common.Hash]struct{}) 886 for k, v := range s.snapDestructs { 887 state.snapDestructs[k] = v 888 } 889 state.snapAccounts = make(map[common.Hash][]byte) 890 for k, v := range s.snapAccounts { 891 state.snapAccounts[k] = v 892 } 893 state.snapStorage = make(map[common.Hash]map[common.Hash][]byte) 894 for k, v := range s.snapStorage { 895 temp := make(map[common.Hash][]byte) 896 for kk, vv := range v { 897 temp[kk] = vv 898 } 899 state.snapStorage[k] = temp 900 } 901 } 902 return state 903 } 904 905 // deepCopyLogs deep-copies StateDB.logs from the left to the right. 906 func deepCopyLogs(from, to *StateDB) { 907 for hash, logs := range from.logs { 908 copied := make([]*types.Log, len(logs)) 909 for i, log := range logs { 910 copied[i] = new(types.Log) 911 *copied[i] = *log 912 } 913 to.logs[hash] = copied 914 } 915 } 916 917 // Snapshot returns an identifier for the current revision of the state. 918 func (s *StateDB) Snapshot() int { 919 id := s.nextRevisionId 920 s.nextRevisionId++ 921 s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()}) 922 return id 923 } 924 925 // RevertToSnapshot reverts all state changes made since the given revision. 926 func (s *StateDB) RevertToSnapshot(revid int) { 927 // Find the snapshot in the stack of valid snapshots. 928 idx := sort.Search(len(s.validRevisions), func(i int) bool { 929 return s.validRevisions[i].id >= revid 930 }) 931 if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid { 932 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 933 } 934 snapshot := s.validRevisions[idx].journalIndex 935 936 // Replay the journal to undo changes and remove invalidated snapshots 937 s.journal.revert(s, snapshot) 938 s.validRevisions = s.validRevisions[:idx] 939 } 940 941 // GetRefund returns the current value of the refund counter. 942 func (s *StateDB) GetRefund() uint64 { 943 return s.refund 944 } 945 946 // Finalise finalises the state by removing the self destructed objects 947 // and clears the journal as well as the refunds. 948 func (stateDB *StateDB) Finalise(deleteEmptyObjects bool, setStorageRoot bool) { 949 for addr := range stateDB.journal.dirties { 950 so, exist := stateDB.stateObjects[addr] 951 if !exist { 952 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 953 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 954 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 955 // it will persist in the journal even though the journal is reverted. In this special circumstance, 956 // it may exist in `stateDB.journal.dirties` but not in `stateDB.stateObjects`. 957 // Thus, we can safely ignore it here 958 continue 959 } 960 961 if so.selfDestructed || (deleteEmptyObjects && so.empty()) { 962 stateDB.deleteStateObject(so) 963 964 // If state snapshotting is active, also mark the destruction there. 965 // Note, we can't do this only at the end of a block because multiple 966 // transactions within the same block might self destruct and then 967 // ressurrect an account; but the snapshotter needs both events. 968 if stateDB.snap != nil { 969 stateDB.snapDestructs[so.addrHash] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely) 970 delete(stateDB.snapAccounts, so.addrHash) // Clear out any previously updated account data (may be recreated via a ressurrect) 971 delete(stateDB.snapStorage, so.addrHash) // Clear out any previously updated storage data (may be recreated via a ressurrect) 972 } 973 } else { 974 so.updateStorageTrie(stateDB.db) 975 so.setStorageRoot(setStorageRoot, stateDB.stateObjectsDirtyStorage) 976 stateDB.updateStateObject(so) 977 } 978 so.created = false 979 stateDB.stateObjectsDirty[addr] = struct{}{} 980 } 981 // Invalidate journal because reverting across transactions is not allowed. 982 stateDB.clearJournalAndRefund() 983 984 if setStorageRoot && len(stateDB.stateObjectsDirtyStorage) > 0 { 985 for addr := range stateDB.stateObjectsDirtyStorage { 986 so, exist := stateDB.stateObjects[addr] 987 if exist { 988 so.updateStorageRoot(stateDB.db) 989 stateDB.updateStateObject(so) 990 } 991 } 992 stateDB.stateObjectsDirtyStorage = make(map[common.Address]struct{}) 993 } 994 } 995 996 // IntermediateRoot computes the current root hash of the state statedb. 997 // It is called in between transactions to get the root hash that 998 // goes into transaction receipts. 999 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 1000 s.Finalise(deleteEmptyObjects, true) 1001 // Track the amount of time wasted on hashing the account trie 1002 if EnabledExpensive { 1003 defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now()) 1004 } 1005 return s.trie.Hash() 1006 } 1007 1008 // SetTxContext sets the current transaction hash and index and block hash which is 1009 // used when the EVM emits new state logs. 1010 func (s *StateDB) SetTxContext(thash, bhash common.Hash, ti int) { 1011 s.thash = thash 1012 s.bhash = bhash 1013 s.txIndex = ti 1014 } 1015 1016 func (s *StateDB) clearJournalAndRefund() { 1017 s.journal = newJournal() 1018 s.validRevisions = s.validRevisions[:0] 1019 s.refund = 0 1020 } 1021 1022 // Commit writes the state to the underlying in-memory trie database. 1023 func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { 1024 if s.dbErr != nil { 1025 return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr) 1026 } 1027 1028 defer s.clearJournalAndRefund() 1029 1030 for addr := range s.journal.dirties { 1031 s.stateObjectsDirty[addr] = struct{}{} 1032 } 1033 1034 objectEncoder := getStateObjectEncoder(len(s.stateObjects)) 1035 var stateObjectsToUpdate []*stateObject 1036 // Commit objects to the trie. 1037 for addr, stateObject := range s.stateObjects { 1038 _, isDirty := s.stateObjectsDirty[addr] 1039 switch { 1040 case stateObject.selfDestructed || (isDirty && deleteEmptyObjects && stateObject.empty()): 1041 // If the object has been removed, don't bother syncing it 1042 // and just mark it for deletion in the trie. 1043 s.deleteStateObject(stateObject) 1044 case isDirty: 1045 if stateObject.IsProgramAccount() { 1046 // Write any contract code associated with the state object. 1047 if stateObject.code != nil && stateObject.dirtyCode { 1048 s.db.TrieDB().DiskDB().WriteCode(common.BytesToHash(stateObject.CodeHash()), stateObject.code) 1049 stateObject.dirtyCode = false 1050 } 1051 // Write any storage changes in the state object to its storage trie. 1052 if err := stateObject.CommitStorageTrie(s.db); err != nil { 1053 return common.Hash{}, err 1054 } 1055 } 1056 // Update the object in the main account trie. 1057 stateObjectsToUpdate = append(stateObjectsToUpdate, stateObject) 1058 objectEncoder.encode(stateObject) 1059 } 1060 delete(s.stateObjectsDirty, addr) 1061 } 1062 1063 for _, so := range stateObjectsToUpdate { 1064 s.updateStateObject(so) 1065 } 1066 1067 // Write the account trie changes, measuring the amount of wasted time 1068 if EnabledExpensive { 1069 defer func(start time.Time) { s.AccountCommits += time.Since(start) }(time.Now()) 1070 } 1071 root, err = s.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.ExtHash, parentDepth int) error { 1072 serializer := account.NewAccountSerializer() 1073 if err := rlp.DecodeBytes(leaf, serializer); err != nil { 1074 logger.Warn("RLP decode failed", "err", err, "leaf", string(leaf)) 1075 return nil 1076 } 1077 acc := serializer.GetAccount() 1078 if pa := account.GetProgramAccount(acc); pa != nil { 1079 if pa.GetStorageRoot().Unextend() != emptyState { 1080 s.db.TrieDB().Reference(pa.GetStorageRoot(), parent) 1081 } 1082 } 1083 return nil 1084 }) 1085 1086 // If snapshotting is enabled, update the snapshot tree with this new version 1087 if s.snap != nil { 1088 if EnabledExpensive { 1089 defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now()) 1090 } 1091 // Only update if there's a state transition (skip empty Clique blocks) 1092 if parent := s.snap.Root(); parent != root { 1093 if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil { 1094 logger.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err) 1095 } 1096 // Keep 128 diff layers in the memory, persistent layer is 129th. 1097 // - head layer is paired with HEAD state 1098 // - head-1 layer is paired with HEAD-1 state 1099 // - head-127 layer(bottom-most diff layer) is paired with HEAD-127 state 1100 if err := s.snaps.Cap(root, 128); err != nil { 1101 logger.Warn("Failed to cap snapshot tree", "root", root, "layers", 128, "err", err) 1102 } 1103 } 1104 s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil 1105 } 1106 1107 return root, err 1108 } 1109 1110 // GetTxHash returns the hash of current running transaction. 1111 func (s *StateDB) GetTxHash() common.Hash { 1112 return s.thash 1113 } 1114 1115 var ( 1116 errNotExistingAddress = fmt.Errorf("there is no account corresponding to the given address") 1117 errNotContractAddress = fmt.Errorf("given address is not a contract address") 1118 ) 1119 1120 func (s *StateDB) GetContractStorageRoot(contractAddr common.Address) (common.ExtHash, error) { 1121 acc := s.GetAccount(contractAddr) 1122 if acc == nil { 1123 return common.ExtHash{}, errNotExistingAddress 1124 } 1125 if acc.Type() != account.SmartContractAccountType { 1126 return common.ExtHash{}, errNotContractAddress 1127 } 1128 contract, true := acc.(*account.SmartContractAccount) 1129 if !true { 1130 return common.ExtHash{}, errNotContractAddress 1131 } 1132 return contract.GetStorageRoot(), nil 1133 } 1134 1135 // Prepare handles the preparatory steps for executing a state transition with. 1136 // This method must be invoked before state transition. 1137 // 1138 // Kore fork: 1139 // - Add sender to access list (2929) 1140 // - Add feepayer to access list (only for klaytn) 1141 // - Add destination to access list (2929) 1142 // - Add precompiles to access list (2929) 1143 // 1144 // Shanghai fork: 1145 // - Add coinbase to access list (EIP-3651) 1146 // Potential EIPs: 1147 // - Reset transient storage(1153) 1148 func (s *StateDB) Prepare(rules params.Rules, sender, feepayer, coinbase common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) { 1149 if rules.IsKore { 1150 // Clear out any leftover from previous executions 1151 s.accessList = newAccessList() 1152 1153 s.AddAddressToAccessList(sender) 1154 if !common.EmptyAddress(feepayer) { 1155 s.AddAddressToAccessList(feepayer) 1156 } 1157 if dst != nil { 1158 s.AddAddressToAccessList(*dst) 1159 // If it's a create-tx, the destination will be added inside evm.create 1160 } 1161 for _, addr := range precompiles { 1162 s.AddAddressToAccessList(addr) 1163 } 1164 } 1165 if rules.IsShanghai { 1166 s.AddAddressToAccessList(coinbase) 1167 } 1168 if rules.IsCancun { 1169 // Optional accessList is the accessList mentioned through tx args. 1170 for _, el := range list { 1171 s.AddAddressToAccessList(el.Address) 1172 for _, key := range el.StorageKeys { 1173 s.AddSlotToAccessList(el.Address, key) 1174 } 1175 } 1176 } 1177 // Reset transient storage at the beginning of transaction execution 1178 s.transientStorage = newTransientStorage() 1179 } 1180 1181 // AddAddressToAccessList adds the given address to the access list 1182 func (s *StateDB) AddAddressToAccessList(addr common.Address) { 1183 if s.accessList.AddAddress(addr) { 1184 s.journal.append(accessListAddAccountChange{&addr}) 1185 } 1186 } 1187 1188 // AddSlotToAccessList adds the given (address, slot)-tuple to the access list 1189 func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) { 1190 addrMod, slotMod := s.accessList.AddSlot(addr, slot) 1191 if addrMod { 1192 // In practice, this should not happen, since there is no way to enter the 1193 // scope of 'address' without having the 'address' become already added 1194 // to the access list (via call-variant, create, etc). 1195 // Better safe than sorry, though 1196 s.journal.append(accessListAddAccountChange{&addr}) 1197 } 1198 if slotMod { 1199 s.journal.append(accessListAddSlotChange{ 1200 address: &addr, 1201 slot: &slot, 1202 }) 1203 } 1204 } 1205 1206 // AddressInAccessList returns true if the given address is in the access list. 1207 func (s *StateDB) AddressInAccessList(addr common.Address) bool { 1208 return s.accessList.ContainsAddress(addr) 1209 } 1210 1211 // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list. 1212 func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) { 1213 return s.accessList.Contains(addr, slot) 1214 }