github.com/palisadeinc/bor@v0.0.0-20230615125219-ab7196213d15/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/blockstm" 29 "github.com/ethereum/go-ethereum/core/rawdb" 30 "github.com/ethereum/go-ethereum/core/state/snapshot" 31 "github.com/ethereum/go-ethereum/core/types" 32 "github.com/ethereum/go-ethereum/crypto" 33 "github.com/ethereum/go-ethereum/log" 34 "github.com/ethereum/go-ethereum/metrics" 35 "github.com/ethereum/go-ethereum/rlp" 36 "github.com/ethereum/go-ethereum/trie" 37 ) 38 39 type revision struct { 40 id int 41 journalIndex int 42 } 43 44 var ( 45 // emptyRoot is the known root hash of an empty trie. 46 emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") 47 ) 48 49 type proofList [][]byte 50 51 func (n *proofList) Put(key []byte, value []byte) error { 52 *n = append(*n, value) 53 return nil 54 } 55 56 func (n *proofList) Delete(key []byte) error { 57 panic("not supported") 58 } 59 60 // StateDB structs within the ethereum protocol are used to store anything 61 // within the merkle trie. StateDBs take care of caching and storing 62 // nested states. It's the general query interface to retrieve: 63 // * Contracts 64 // * Accounts 65 type StateDB struct { 66 db Database 67 prefetcher *triePrefetcher 68 originalRoot common.Hash // The pre-state root, before any changes were made 69 trie Trie 70 hasher crypto.KeccakState 71 72 snaps *snapshot.Tree 73 snap snapshot.Snapshot 74 snapDestructs map[common.Hash]struct{} 75 snapAccounts map[common.Hash][]byte 76 snapStorage map[common.Hash]map[common.Hash][]byte 77 78 // This map holds 'live' objects, which will get modified while processing a state transition. 79 stateObjects map[common.Address]*stateObject 80 stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie 81 stateObjectsDirty map[common.Address]struct{} // State objects modified in the current execution 82 83 // Block-stm related fields 84 mvHashmap *blockstm.MVHashMap 85 incarnation int 86 readMap map[blockstm.Key]blockstm.ReadDescriptor 87 writeMap map[blockstm.Key]blockstm.WriteDescriptor 88 revertedKeys map[blockstm.Key]struct{} 89 dep int 90 91 // DB error. 92 // State objects are used by the consensus core and VM which are 93 // unable to deal with database-level errors. Any error that occurs 94 // during a database read is memoized here and will eventually be returned 95 // by StateDB.Commit. 96 dbErr error 97 98 // The refund counter, also used by state transitioning. 99 refund uint64 100 101 thash common.Hash 102 txIndex int 103 logs map[common.Hash][]*types.Log 104 logSize uint 105 106 preimages map[common.Hash][]byte 107 108 // Per-transaction access list 109 accessList *accessList 110 111 // Journal of state modifications. This is the backbone of 112 // Snapshot and RevertToSnapshot. 113 journal *journal 114 validRevisions []revision 115 nextRevisionId int 116 117 // Measurements gathered during execution for debugging purposes 118 AccountReads time.Duration 119 AccountHashes time.Duration 120 AccountUpdates time.Duration 121 AccountCommits time.Duration 122 StorageReads time.Duration 123 StorageHashes time.Duration 124 StorageUpdates time.Duration 125 StorageCommits time.Duration 126 SnapshotAccountReads time.Duration 127 SnapshotStorageReads time.Duration 128 SnapshotCommits time.Duration 129 130 AccountUpdated int 131 StorageUpdated int 132 AccountDeleted int 133 StorageDeleted int 134 } 135 136 // New creates a new state from a given trie. 137 func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) { 138 tr, err := db.OpenTrie(root) 139 if err != nil { 140 return nil, err 141 } 142 sdb := &StateDB{ 143 db: db, 144 trie: tr, 145 originalRoot: root, 146 snaps: snaps, 147 stateObjects: make(map[common.Address]*stateObject), 148 stateObjectsPending: make(map[common.Address]struct{}), 149 stateObjectsDirty: make(map[common.Address]struct{}), 150 revertedKeys: make(map[blockstm.Key]struct{}), 151 logs: make(map[common.Hash][]*types.Log), 152 preimages: make(map[common.Hash][]byte), 153 journal: newJournal(), 154 accessList: newAccessList(), 155 hasher: crypto.NewKeccakState(), 156 } 157 if sdb.snaps != nil { 158 if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil { 159 sdb.snapDestructs = make(map[common.Hash]struct{}) 160 sdb.snapAccounts = make(map[common.Hash][]byte) 161 sdb.snapStorage = make(map[common.Hash]map[common.Hash][]byte) 162 } 163 } 164 return sdb, nil 165 } 166 167 func NewWithMVHashmap(root common.Hash, db Database, snaps *snapshot.Tree, mvhm *blockstm.MVHashMap) (*StateDB, error) { 168 if sdb, err := New(root, db, snaps); err != nil { 169 return nil, err 170 } else { 171 sdb.mvHashmap = mvhm 172 sdb.dep = -1 173 return sdb, nil 174 } 175 } 176 177 func (sdb *StateDB) SetMVHashmap(mvhm *blockstm.MVHashMap) { 178 sdb.mvHashmap = mvhm 179 sdb.dep = -1 180 } 181 182 func (sdb *StateDB) GetMVHashmap() *blockstm.MVHashMap { 183 return sdb.mvHashmap 184 } 185 186 func (s *StateDB) MVWriteList() []blockstm.WriteDescriptor { 187 writes := make([]blockstm.WriteDescriptor, 0, len(s.writeMap)) 188 189 for _, v := range s.writeMap { 190 if _, ok := s.revertedKeys[v.Path]; !ok { 191 writes = append(writes, v) 192 } 193 } 194 195 return writes 196 } 197 198 func (s *StateDB) MVFullWriteList() []blockstm.WriteDescriptor { 199 writes := make([]blockstm.WriteDescriptor, 0, len(s.writeMap)) 200 201 for _, v := range s.writeMap { 202 writes = append(writes, v) 203 } 204 205 return writes 206 } 207 208 func (s *StateDB) MVReadMap() map[blockstm.Key]blockstm.ReadDescriptor { 209 return s.readMap 210 } 211 212 func (s *StateDB) MVReadList() []blockstm.ReadDescriptor { 213 reads := make([]blockstm.ReadDescriptor, 0, len(s.readMap)) 214 215 for _, v := range s.MVReadMap() { 216 reads = append(reads, v) 217 } 218 219 return reads 220 } 221 222 func (s *StateDB) ensureReadMap() { 223 if s.readMap == nil { 224 s.readMap = make(map[blockstm.Key]blockstm.ReadDescriptor) 225 } 226 } 227 228 func (s *StateDB) ensureWriteMap() { 229 if s.writeMap == nil { 230 s.writeMap = make(map[blockstm.Key]blockstm.WriteDescriptor) 231 } 232 } 233 234 func (s *StateDB) ClearReadMap() { 235 s.readMap = make(map[blockstm.Key]blockstm.ReadDescriptor) 236 } 237 238 func (s *StateDB) ClearWriteMap() { 239 s.writeMap = make(map[blockstm.Key]blockstm.WriteDescriptor) 240 } 241 242 func (s *StateDB) HadInvalidRead() bool { 243 return s.dep >= 0 244 } 245 246 func (s *StateDB) DepTxIndex() int { 247 return s.dep 248 } 249 250 func (s *StateDB) SetIncarnation(inc int) { 251 s.incarnation = inc 252 } 253 254 type StorageVal[T any] struct { 255 Value *T 256 } 257 258 func MVRead[T any](s *StateDB, k blockstm.Key, defaultV T, readStorage func(s *StateDB) T) (v T) { 259 if s.mvHashmap == nil { 260 return readStorage(s) 261 } 262 263 s.ensureReadMap() 264 265 if s.writeMap != nil { 266 if _, ok := s.writeMap[k]; ok { 267 return readStorage(s) 268 } 269 } 270 271 if !k.IsAddress() { 272 // If we are reading subpath from a deleted account, return default value instead of reading from MVHashmap 273 addr := k.GetAddress() 274 if s.getStateObject(addr) == nil { 275 return defaultV 276 } 277 } 278 279 res := s.mvHashmap.Read(k, s.txIndex) 280 281 var rd blockstm.ReadDescriptor 282 283 rd.V = blockstm.Version{ 284 TxnIndex: res.DepIdx(), 285 Incarnation: res.Incarnation(), 286 } 287 288 rd.Path = k 289 290 switch res.Status() { 291 case blockstm.MVReadResultDone: 292 { 293 v = readStorage(res.Value().(*StateDB)) 294 rd.Kind = blockstm.ReadKindMap 295 } 296 case blockstm.MVReadResultDependency: 297 { 298 s.dep = res.DepIdx() 299 300 panic("Found dependency") 301 } 302 case blockstm.MVReadResultNone: 303 { 304 v = readStorage(s) 305 rd.Kind = blockstm.ReadKindStorage 306 } 307 default: 308 return defaultV 309 } 310 311 // TODO: I assume we don't want to overwrite an existing read because this could - for example - change a storage 312 // read to map if the same value is read multiple times. 313 if _, ok := s.readMap[k]; !ok { 314 s.readMap[k] = rd 315 } 316 317 return 318 } 319 320 func MVWrite(s *StateDB, k blockstm.Key) { 321 if s.mvHashmap != nil { 322 s.ensureWriteMap() 323 s.writeMap[k] = blockstm.WriteDescriptor{ 324 Path: k, 325 V: s.Version(), 326 Val: s, 327 } 328 } 329 } 330 331 func RevertWrite(s *StateDB, k blockstm.Key) { 332 s.revertedKeys[k] = struct{}{} 333 } 334 335 func MVWritten(s *StateDB, k blockstm.Key) bool { 336 if s.mvHashmap == nil || s.writeMap == nil { 337 return false 338 } 339 340 _, ok := s.writeMap[k] 341 342 return ok 343 } 344 345 // Apply entries in the write set to MVHashMap. Note that this function does not clear the write set. 346 func (s *StateDB) FlushMVWriteSet() { 347 if s.mvHashmap != nil && s.writeMap != nil { 348 s.mvHashmap.FlushMVWriteSet(s.MVFullWriteList()) 349 } 350 } 351 352 // Apply entries in a given write set to StateDB. Note that this function does not change MVHashMap nor write set 353 // of the current StateDB. 354 func (sw *StateDB) ApplyMVWriteSet(writes []blockstm.WriteDescriptor) { 355 for i := range writes { 356 path := writes[i].Path 357 sr := writes[i].Val.(*StateDB) 358 359 if path.IsState() { 360 addr := path.GetAddress() 361 stateKey := path.GetStateKey() 362 state := sr.GetState(addr, stateKey) 363 sw.SetState(addr, stateKey, state) 364 } else if path.IsAddress() { 365 continue 366 } else { 367 addr := path.GetAddress() 368 switch path.GetSubpath() { 369 case BalancePath: 370 sw.SetBalance(addr, sr.GetBalance(addr)) 371 case NoncePath: 372 sw.SetNonce(addr, sr.GetNonce(addr)) 373 case CodePath: 374 sw.SetCode(addr, sr.GetCode(addr)) 375 case SuicidePath: 376 stateObject := sr.getDeletedStateObject(addr) 377 if stateObject != nil && stateObject.deleted { 378 sw.Suicide(addr) 379 } 380 default: 381 panic(fmt.Errorf("unknown key type: %d", path.GetSubpath())) 382 } 383 } 384 } 385 } 386 387 type DumpStruct struct { 388 TxIdx int 389 TxInc int 390 VerIdx int 391 VerInc int 392 Path []byte 393 Op string 394 } 395 396 // get readMap Dump of format: "TxIdx, Inc, Path, Read" 397 func (s *StateDB) GetReadMapDump() []DumpStruct { 398 readList := s.MVReadList() 399 res := make([]DumpStruct, 0, len(readList)) 400 401 for _, val := range readList { 402 temp := &DumpStruct{ 403 TxIdx: s.txIndex, 404 TxInc: s.incarnation, 405 VerIdx: val.V.TxnIndex, 406 VerInc: val.V.Incarnation, 407 Path: val.Path[:], 408 Op: "Read\n", 409 } 410 res = append(res, *temp) 411 } 412 413 return res 414 } 415 416 // get writeMap Dump of format: "TxIdx, Inc, Path, Write" 417 func (s *StateDB) GetWriteMapDump() []DumpStruct { 418 writeList := s.MVReadList() 419 res := make([]DumpStruct, 0, len(writeList)) 420 421 for _, val := range writeList { 422 temp := &DumpStruct{ 423 TxIdx: s.txIndex, 424 TxInc: s.incarnation, 425 VerIdx: val.V.TxnIndex, 426 VerInc: val.V.Incarnation, 427 Path: val.Path[:], 428 Op: "Write\n", 429 } 430 res = append(res, *temp) 431 } 432 433 return res 434 } 435 436 // add empty MVHashMap to StateDB 437 func (s *StateDB) AddEmptyMVHashMap() { 438 mvh := blockstm.MakeMVHashMap() 439 s.mvHashmap = mvh 440 } 441 442 // StartPrefetcher initializes a new trie prefetcher to pull in nodes from the 443 // state trie concurrently while the state is mutated so that when we reach the 444 // commit phase, most of the needed data is already hot. 445 func (s *StateDB) StartPrefetcher(namespace string) { 446 if s.prefetcher != nil { 447 s.prefetcher.close() 448 s.prefetcher = nil 449 } 450 if s.snap != nil { 451 s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace) 452 } 453 } 454 455 // StopPrefetcher terminates a running prefetcher and reports any leftover stats 456 // from the gathered metrics. 457 func (s *StateDB) StopPrefetcher() { 458 if s.prefetcher != nil { 459 s.prefetcher.close() 460 s.prefetcher = nil 461 } 462 } 463 464 // setError remembers the first non-nil error it is called with. 465 func (s *StateDB) setError(err error) { 466 if s.dbErr == nil { 467 s.dbErr = err 468 } 469 } 470 471 func (s *StateDB) Error() error { 472 return s.dbErr 473 } 474 475 func (s *StateDB) AddLog(log *types.Log) { 476 s.journal.append(addLogChange{txhash: s.thash}) 477 478 log.TxHash = s.thash 479 log.TxIndex = uint(s.txIndex) 480 log.Index = s.logSize 481 s.logs[s.thash] = append(s.logs[s.thash], log) 482 s.logSize++ 483 } 484 485 func (s *StateDB) GetLogs(hash common.Hash, blockHash common.Hash) []*types.Log { 486 logs := s.logs[hash] 487 for _, l := range logs { 488 l.BlockHash = blockHash 489 } 490 return logs 491 } 492 493 func (s *StateDB) Logs() []*types.Log { 494 var logs []*types.Log 495 for _, lgs := range s.logs { 496 logs = append(logs, lgs...) 497 } 498 return logs 499 } 500 501 // AddPreimage records a SHA3 preimage seen by the VM. 502 func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 503 if _, ok := s.preimages[hash]; !ok { 504 s.journal.append(addPreimageChange{hash: hash}) 505 pi := make([]byte, len(preimage)) 506 copy(pi, preimage) 507 s.preimages[hash] = pi 508 } 509 } 510 511 // Preimages returns a list of SHA3 preimages that have been submitted. 512 func (s *StateDB) Preimages() map[common.Hash][]byte { 513 return s.preimages 514 } 515 516 // AddRefund adds gas to the refund counter 517 func (s *StateDB) AddRefund(gas uint64) { 518 s.journal.append(refundChange{prev: s.refund}) 519 s.refund += gas 520 } 521 522 // SubRefund removes gas from the refund counter. 523 // This method will panic if the refund counter goes below zero 524 func (s *StateDB) SubRefund(gas uint64) { 525 s.journal.append(refundChange{prev: s.refund}) 526 if gas > s.refund { 527 panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund)) 528 } 529 s.refund -= gas 530 } 531 532 // Exist reports whether the given account address exists in the state. 533 // Notably this also returns true for suicided accounts. 534 func (s *StateDB) Exist(addr common.Address) bool { 535 return s.getStateObject(addr) != nil 536 } 537 538 // Empty returns whether the state object is either non-existent 539 // or empty according to the EIP161 specification (balance = nonce = code = 0) 540 func (s *StateDB) Empty(addr common.Address) bool { 541 so := s.getStateObject(addr) 542 return so == nil || so.empty() 543 } 544 545 // Create a unique path for special fields (e.g. balance, code) in a state object. 546 // func subPath(prefix []byte, s uint8) [blockstm.KeyLength]byte { 547 // path := append(prefix, common.Hash{}.Bytes()...) // append a full empty hash to avoid collision with storage state 548 // path = append(path, s) // append the special field identifier 549 550 // return path 551 // } 552 553 const BalancePath = 1 554 const NoncePath = 2 555 const CodePath = 3 556 const SuicidePath = 4 557 558 // GetBalance retrieves the balance from the given address or 0 if object not found 559 func (s *StateDB) GetBalance(addr common.Address) *big.Int { 560 return MVRead(s, blockstm.NewSubpathKey(addr, BalancePath), common.Big0, func(s *StateDB) *big.Int { 561 stateObject := s.getStateObject(addr) 562 if stateObject != nil { 563 return stateObject.Balance() 564 } 565 566 return common.Big0 567 }) 568 } 569 570 func (s *StateDB) GetNonce(addr common.Address) uint64 { 571 return MVRead(s, blockstm.NewSubpathKey(addr, NoncePath), 0, func(s *StateDB) uint64 { 572 stateObject := s.getStateObject(addr) 573 if stateObject != nil { 574 return stateObject.Nonce() 575 } 576 577 return 0 578 }) 579 } 580 581 // TxIndex returns the current transaction index set by Prepare. 582 func (s *StateDB) TxIndex() int { 583 return s.txIndex 584 } 585 586 func (s *StateDB) Version() blockstm.Version { 587 return blockstm.Version{ 588 TxnIndex: s.txIndex, 589 Incarnation: s.incarnation, 590 } 591 } 592 593 func (s *StateDB) GetCode(addr common.Address) []byte { 594 return MVRead(s, blockstm.NewSubpathKey(addr, CodePath), nil, func(s *StateDB) []byte { 595 stateObject := s.getStateObject(addr) 596 if stateObject != nil { 597 return stateObject.Code(s.db) 598 } 599 return nil 600 }) 601 } 602 603 func (s *StateDB) GetCodeSize(addr common.Address) int { 604 return MVRead(s, blockstm.NewSubpathKey(addr, CodePath), 0, func(s *StateDB) int { 605 stateObject := s.getStateObject(addr) 606 if stateObject != nil { 607 return stateObject.CodeSize(s.db) 608 } 609 return 0 610 }) 611 } 612 613 func (s *StateDB) GetCodeHash(addr common.Address) common.Hash { 614 return MVRead(s, blockstm.NewSubpathKey(addr, CodePath), common.Hash{}, func(s *StateDB) common.Hash { 615 stateObject := s.getStateObject(addr) 616 if stateObject == nil { 617 return common.Hash{} 618 } 619 return common.BytesToHash(stateObject.CodeHash()) 620 }) 621 } 622 623 // GetState retrieves a value from the given account's storage trie. 624 func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { 625 return MVRead(s, blockstm.NewStateKey(addr, hash), common.Hash{}, func(s *StateDB) common.Hash { 626 stateObject := s.getStateObject(addr) 627 if stateObject != nil { 628 return stateObject.GetState(s.db, hash) 629 } 630 return common.Hash{} 631 }) 632 } 633 634 // GetProof returns the Merkle proof for a given account. 635 func (s *StateDB) GetProof(addr common.Address) ([][]byte, error) { 636 return s.GetProofByHash(crypto.Keccak256Hash(addr.Bytes())) 637 } 638 639 // GetProofByHash returns the Merkle proof for a given account. 640 func (s *StateDB) GetProofByHash(addrHash common.Hash) ([][]byte, error) { 641 var proof proofList 642 err := s.trie.Prove(addrHash[:], 0, &proof) 643 return proof, err 644 } 645 646 // GetStorageProof returns the Merkle proof for given storage slot. 647 func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) { 648 var proof proofList 649 trie := s.StorageTrie(a) 650 if trie == nil { 651 return proof, errors.New("storage trie for requested address does not exist") 652 } 653 err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof) 654 return proof, err 655 } 656 657 // GetCommittedState retrieves a value from the given account's committed storage trie. 658 func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { 659 return MVRead(s, blockstm.NewStateKey(addr, hash), common.Hash{}, func(s *StateDB) common.Hash { 660 stateObject := s.getStateObject(addr) 661 if stateObject != nil { 662 return stateObject.GetCommittedState(s.db, hash) 663 } 664 return common.Hash{} 665 }) 666 } 667 668 // Database retrieves the low level database supporting the lower level trie ops. 669 func (s *StateDB) Database() Database { 670 return s.db 671 } 672 673 // StorageTrie returns the storage trie of an account. 674 // The return value is a copy and is nil for non-existent accounts. 675 func (s *StateDB) StorageTrie(addr common.Address) Trie { 676 stateObject := s.getStateObject(addr) 677 if stateObject == nil { 678 return nil 679 } 680 cpy := stateObject.deepCopy(s) 681 cpy.updateTrie(s.db) 682 return cpy.getTrie(s.db) 683 } 684 685 func (s *StateDB) HasSuicided(addr common.Address) bool { 686 return MVRead(s, blockstm.NewSubpathKey(addr, SuicidePath), false, func(s *StateDB) bool { 687 stateObject := s.getStateObject(addr) 688 if stateObject != nil { 689 return stateObject.suicided 690 } 691 return false 692 }) 693 } 694 695 /* 696 * SETTERS 697 */ 698 699 // AddBalance adds amount to the account associated with addr. 700 func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) { 701 stateObject := s.GetOrNewStateObject(addr) 702 703 if s.mvHashmap != nil { 704 // ensure a read balance operation is recorded in mvHashmap 705 s.GetBalance(addr) 706 } 707 708 if stateObject != nil { 709 stateObject = s.mvRecordWritten(stateObject) 710 stateObject.AddBalance(amount) 711 MVWrite(s, blockstm.NewSubpathKey(addr, BalancePath)) 712 } 713 } 714 715 // SubBalance subtracts amount from the account associated with addr. 716 func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) { 717 stateObject := s.GetOrNewStateObject(addr) 718 719 if s.mvHashmap != nil { 720 // ensure a read balance operation is recorded in mvHashmap 721 s.GetBalance(addr) 722 } 723 724 if stateObject != nil { 725 stateObject = s.mvRecordWritten(stateObject) 726 stateObject.SubBalance(amount) 727 MVWrite(s, blockstm.NewSubpathKey(addr, BalancePath)) 728 } 729 } 730 731 func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) { 732 stateObject := s.GetOrNewStateObject(addr) 733 if stateObject != nil { 734 stateObject = s.mvRecordWritten(stateObject) 735 stateObject.SetBalance(amount) 736 MVWrite(s, blockstm.NewSubpathKey(addr, BalancePath)) 737 } 738 } 739 740 func (s *StateDB) SetNonce(addr common.Address, nonce uint64) { 741 stateObject := s.GetOrNewStateObject(addr) 742 if stateObject != nil { 743 stateObject = s.mvRecordWritten(stateObject) 744 stateObject.SetNonce(nonce) 745 MVWrite(s, blockstm.NewSubpathKey(addr, NoncePath)) 746 } 747 } 748 749 func (s *StateDB) SetCode(addr common.Address, code []byte) { 750 stateObject := s.GetOrNewStateObject(addr) 751 if stateObject != nil { 752 stateObject = s.mvRecordWritten(stateObject) 753 stateObject.SetCode(crypto.Keccak256Hash(code), code) 754 MVWrite(s, blockstm.NewSubpathKey(addr, CodePath)) 755 } 756 } 757 758 func (s *StateDB) SetState(addr common.Address, key, value common.Hash) { 759 stateObject := s.GetOrNewStateObject(addr) 760 if stateObject != nil { 761 stateObject = s.mvRecordWritten(stateObject) 762 stateObject.SetState(s.db, key, value) 763 MVWrite(s, blockstm.NewStateKey(addr, key)) 764 } 765 } 766 767 // SetStorage replaces the entire storage for the specified account with given 768 // storage. This function should only be used for debugging. 769 func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) { 770 stateObject := s.GetOrNewStateObject(addr) 771 if stateObject != nil { 772 stateObject.SetStorage(storage) 773 } 774 } 775 776 // Suicide marks the given account as suicided. 777 // This clears the account balance. 778 // 779 // The account's state object is still available until the state is committed, 780 // getStateObject will return a non-nil account after Suicide. 781 func (s *StateDB) Suicide(addr common.Address) bool { 782 stateObject := s.getStateObject(addr) 783 if stateObject == nil { 784 return false 785 } 786 787 stateObject = s.mvRecordWritten(stateObject) 788 s.journal.append(suicideChange{ 789 account: &addr, 790 prev: stateObject.suicided, 791 prevbalance: new(big.Int).Set(stateObject.Balance()), 792 }) 793 stateObject.markSuicided() 794 stateObject.data.Balance = new(big.Int) 795 796 MVWrite(s, blockstm.NewSubpathKey(addr, SuicidePath)) 797 MVWrite(s, blockstm.NewSubpathKey(addr, BalancePath)) 798 799 return true 800 } 801 802 // 803 // Setting, updating & deleting state object methods. 804 // 805 806 // updateStateObject writes the given object to the trie. 807 func (s *StateDB) updateStateObject(obj *stateObject) { 808 // Track the amount of time wasted on updating the account from the trie 809 if metrics.EnabledExpensive { 810 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 811 } 812 // Encode the account and update the account trie 813 addr := obj.Address() 814 if err := s.trie.TryUpdateAccount(addr[:], &obj.data); err != nil { 815 s.setError(fmt.Errorf("updateStateObject (%x) error: %v", addr[:], err)) 816 } 817 818 // If state snapshotting is active, cache the data til commit. Note, this 819 // update mechanism is not symmetric to the deletion, because whereas it is 820 // enough to track account updates at commit time, deletions need tracking 821 // at transaction boundary level to ensure we capture state clearing. 822 if s.snap != nil { 823 s.snapAccounts[obj.addrHash] = snapshot.SlimAccountRLP(obj.data.Nonce, obj.data.Balance, obj.data.Root, obj.data.CodeHash) 824 } 825 } 826 827 // deleteStateObject removes the given object from the state trie. 828 func (s *StateDB) deleteStateObject(obj *stateObject) { 829 // Track the amount of time wasted on deleting the account from the trie 830 if metrics.EnabledExpensive { 831 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 832 } 833 // Delete the account from the trie 834 addr := obj.Address() 835 if err := s.trie.TryDelete(addr[:]); err != nil { 836 s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err)) 837 } 838 } 839 840 // getStateObject retrieves a state object given by the address, returning nil if 841 // the object is not found or was deleted in this execution context. If you need 842 // to differentiate between non-existent/just-deleted, use getDeletedStateObject. 843 func (s *StateDB) getStateObject(addr common.Address) *stateObject { 844 if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted { 845 return obj 846 } 847 return nil 848 } 849 850 // getDeletedStateObject is similar to getStateObject, but instead of returning 851 // nil for a deleted state object, it returns the actual object with the deleted 852 // flag set. This is needed by the state journal to revert to the correct s- 853 // destructed object instead of wiping all knowledge about the state object. 854 func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject { 855 return MVRead(s, blockstm.NewAddressKey(addr), nil, func(s *StateDB) *stateObject { 856 // Prefer live objects if any is available 857 if obj := s.stateObjects[addr]; obj != nil { 858 return obj 859 } 860 // If no live objects are available, attempt to use snapshots 861 var data *types.StateAccount 862 if s.snap != nil { // nolint 863 start := time.Now() 864 acc, err := s.snap.Account(crypto.HashData(crypto.NewKeccakState(), addr.Bytes())) 865 if metrics.EnabledExpensive { 866 s.SnapshotAccountReads += time.Since(start) 867 } 868 if err == nil { 869 if acc == nil { 870 return nil 871 } 872 data = &types.StateAccount{ 873 Nonce: acc.Nonce, 874 Balance: acc.Balance, 875 CodeHash: acc.CodeHash, 876 Root: common.BytesToHash(acc.Root), 877 } 878 if len(data.CodeHash) == 0 { 879 data.CodeHash = emptyCodeHash 880 } 881 if data.Root == (common.Hash{}) { 882 data.Root = emptyRoot 883 } 884 } 885 } 886 // If snapshot unavailable or reading from it failed, load from the database 887 if data == nil { 888 start := time.Now() 889 enc, err := s.trie.TryGet(addr.Bytes()) 890 if metrics.EnabledExpensive { 891 s.AccountReads += time.Since(start) 892 } 893 if err != nil { 894 s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %v", addr.Bytes(), err)) 895 return nil 896 } 897 if len(enc) == 0 { 898 return nil 899 } 900 data = new(types.StateAccount) 901 if err := rlp.DecodeBytes(enc, data); err != nil { 902 log.Error("Failed to decode state object", "addr", addr, "err", err) 903 return nil 904 } 905 } 906 // Insert into the live set 907 obj := newObject(s, addr, *data) 908 s.setStateObject(obj) 909 return obj 910 }) 911 } 912 913 func (s *StateDB) setStateObject(object *stateObject) { 914 s.stateObjects[object.Address()] = object 915 } 916 917 // GetOrNewStateObject retrieves a state object or create a new state object if nil. 918 func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { 919 stateObject := s.getStateObject(addr) 920 if stateObject == nil { 921 stateObject, _ = s.createObject(addr) 922 } 923 return stateObject 924 } 925 926 // mvRecordWritten checks whether a state object is already present in the current MV writeMap. 927 // If yes, it returns the object directly. 928 // If not, it clones the object and inserts it into the writeMap before returning it. 929 func (s *StateDB) mvRecordWritten(object *stateObject) *stateObject { 930 if s.mvHashmap == nil { 931 return object 932 } 933 934 addrKey := blockstm.NewAddressKey(object.Address()) 935 936 if MVWritten(s, addrKey) { 937 return object 938 } 939 940 // Deepcopy is needed to ensure that objects are not written by multiple transactions at the same time, because 941 // the input state object can come from a different transaction. 942 s.setStateObject(object.deepCopy(s)) 943 MVWrite(s, addrKey) 944 945 return s.stateObjects[object.Address()] 946 } 947 948 // createObject creates a new state object. If there is an existing account with 949 // the given address, it is overwritten and returned as the second return value. 950 func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { 951 prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that! 952 953 var prevdestruct bool 954 if s.snap != nil && prev != nil { 955 _, prevdestruct = s.snapDestructs[prev.addrHash] 956 if !prevdestruct { 957 s.snapDestructs[prev.addrHash] = struct{}{} 958 } 959 } 960 newobj = newObject(s, addr, types.StateAccount{}) 961 if prev == nil { 962 s.journal.append(createObjectChange{account: &addr}) 963 } else { 964 s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct}) 965 } 966 s.setStateObject(newobj) 967 968 MVWrite(s, blockstm.NewAddressKey(addr)) 969 if prev != nil && !prev.deleted { 970 return newobj, prev 971 } 972 return newobj, nil 973 } 974 975 // CreateAccount explicitly creates a state object. If a state object with the address 976 // already exists the balance is carried over to the new account. 977 // 978 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 979 // a contract does the following: 980 // 981 // 1. sends funds to sha(account ++ (nonce + 1)) 982 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 983 // 984 // Carrying over the balance ensures that Ether doesn't disappear. 985 func (s *StateDB) CreateAccount(addr common.Address) { 986 newObj, prev := s.createObject(addr) 987 if prev != nil { 988 newObj.setBalance(prev.data.Balance) 989 MVWrite(s, blockstm.NewSubpathKey(addr, BalancePath)) 990 } 991 } 992 993 func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error { 994 so := db.getStateObject(addr) 995 if so == nil { 996 return nil 997 } 998 it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) 999 1000 for it.Next() { 1001 key := common.BytesToHash(db.trie.GetKey(it.Key)) 1002 if value, dirty := so.dirtyStorage[key]; dirty { 1003 if !cb(key, value) { 1004 return nil 1005 } 1006 continue 1007 } 1008 1009 if len(it.Value) > 0 { 1010 _, content, _, err := rlp.Split(it.Value) 1011 if err != nil { 1012 return err 1013 } 1014 if !cb(key, common.BytesToHash(content)) { 1015 return nil 1016 } 1017 } 1018 } 1019 return nil 1020 } 1021 1022 // Copy creates a deep, independent copy of the state. 1023 // Snapshots of the copied state cannot be applied to the copy. 1024 func (s *StateDB) Copy() *StateDB { 1025 // Copy all the basic fields, initialize the memory ones 1026 state := &StateDB{ 1027 db: s.db, 1028 trie: s.db.CopyTrie(s.trie), 1029 stateObjects: make(map[common.Address]*stateObject, len(s.journal.dirties)), 1030 stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)), 1031 stateObjectsDirty: make(map[common.Address]struct{}, len(s.journal.dirties)), 1032 revertedKeys: make(map[blockstm.Key]struct{}), 1033 refund: s.refund, 1034 logs: make(map[common.Hash][]*types.Log, len(s.logs)), 1035 logSize: s.logSize, 1036 preimages: make(map[common.Hash][]byte, len(s.preimages)), 1037 journal: newJournal(), 1038 hasher: crypto.NewKeccakState(), 1039 } 1040 // Copy the dirty states, logs, and preimages 1041 for addr := range s.journal.dirties { 1042 // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527), 1043 // and in the Finalise-method, there is a case where an object is in the journal but not 1044 // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for 1045 // nil 1046 if object, exist := s.stateObjects[addr]; exist { 1047 // Even though the original object is dirty, we are not copying the journal, 1048 // so we need to make sure that anyside effect the journal would have caused 1049 // during a commit (or similar op) is already applied to the copy. 1050 state.stateObjects[addr] = object.deepCopy(state) 1051 1052 state.stateObjectsDirty[addr] = struct{}{} // Mark the copy dirty to force internal (code/state) commits 1053 state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits 1054 } 1055 } 1056 // Above, we don't copy the actual journal. This means that if the copy is copied, the 1057 // loop above will be a no-op, since the copy's journal is empty. 1058 // Thus, here we iterate over stateObjects, to enable copies of copies 1059 for addr := range s.stateObjectsPending { 1060 if _, exist := state.stateObjects[addr]; !exist { 1061 state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state) 1062 } 1063 state.stateObjectsPending[addr] = struct{}{} 1064 } 1065 for addr := range s.stateObjectsDirty { 1066 if _, exist := state.stateObjects[addr]; !exist { 1067 state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state) 1068 } 1069 state.stateObjectsDirty[addr] = struct{}{} 1070 } 1071 for hash, logs := range s.logs { 1072 cpy := make([]*types.Log, len(logs)) 1073 for i, l := range logs { 1074 cpy[i] = new(types.Log) 1075 *cpy[i] = *l 1076 } 1077 state.logs[hash] = cpy 1078 } 1079 for hash, preimage := range s.preimages { 1080 state.preimages[hash] = preimage 1081 } 1082 // Do we need to copy the access list? In practice: No. At the start of a 1083 // transaction, the access list is empty. In practice, we only ever copy state 1084 // _between_ transactions/blocks, never in the middle of a transaction. 1085 // However, it doesn't cost us much to copy an empty list, so we do it anyway 1086 // to not blow up if we ever decide copy it in the middle of a transaction 1087 state.accessList = s.accessList.Copy() 1088 1089 // If there's a prefetcher running, make an inactive copy of it that can 1090 // only access data but does not actively preload (since the user will not 1091 // know that they need to explicitly terminate an active copy). 1092 if s.prefetcher != nil { 1093 state.prefetcher = s.prefetcher.copy() 1094 } 1095 if s.snaps != nil { 1096 // In order for the miner to be able to use and make additions 1097 // to the snapshot tree, we need to copy that aswell. 1098 // Otherwise, any block mined by ourselves will cause gaps in the tree, 1099 // and force the miner to operate trie-backed only 1100 state.snaps = s.snaps 1101 state.snap = s.snap 1102 // deep copy needed 1103 state.snapDestructs = make(map[common.Hash]struct{}) 1104 for k, v := range s.snapDestructs { 1105 state.snapDestructs[k] = v 1106 } 1107 state.snapAccounts = make(map[common.Hash][]byte) 1108 for k, v := range s.snapAccounts { 1109 state.snapAccounts[k] = v 1110 } 1111 state.snapStorage = make(map[common.Hash]map[common.Hash][]byte) 1112 for k, v := range s.snapStorage { 1113 temp := make(map[common.Hash][]byte) 1114 for kk, vv := range v { 1115 temp[kk] = vv 1116 } 1117 state.snapStorage[k] = temp 1118 } 1119 } 1120 1121 if s.mvHashmap != nil { 1122 state.mvHashmap = s.mvHashmap 1123 } 1124 return state 1125 } 1126 1127 // Snapshot returns an identifier for the current revision of the state. 1128 func (s *StateDB) Snapshot() int { 1129 id := s.nextRevisionId 1130 s.nextRevisionId++ 1131 s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()}) 1132 return id 1133 } 1134 1135 // RevertToSnapshot reverts all state changes made since the given revision. 1136 func (s *StateDB) RevertToSnapshot(revid int) { 1137 // Find the snapshot in the stack of valid snapshots. 1138 idx := sort.Search(len(s.validRevisions), func(i int) bool { 1139 return s.validRevisions[i].id >= revid 1140 }) 1141 if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid { 1142 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 1143 } 1144 snapshot := s.validRevisions[idx].journalIndex 1145 1146 // Replay the journal to undo changes and remove invalidated snapshots 1147 s.journal.revert(s, snapshot) 1148 s.validRevisions = s.validRevisions[:idx] 1149 } 1150 1151 // GetRefund returns the current value of the refund counter. 1152 func (s *StateDB) GetRefund() uint64 { 1153 return s.refund 1154 } 1155 1156 // Finalise finalises the state by removing the s destructed objects and clears 1157 // the journal as well as the refunds. Finalise, however, will not push any updates 1158 // into the tries just yet. Only IntermediateRoot or Commit will do that. 1159 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 1160 addressesToPrefetch := make([][]byte, 0, len(s.journal.dirties)) 1161 for addr := range s.journal.dirties { 1162 obj, exist := s.stateObjects[addr] 1163 if !exist { 1164 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 1165 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 1166 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 1167 // it will persist in the journal even though the journal is reverted. In this special circumstance, 1168 // it may exist in `s.journal.dirties` but not in `s.stateObjects`. 1169 // Thus, we can safely ignore it here 1170 continue 1171 } 1172 if obj.suicided || (deleteEmptyObjects && obj.empty()) { 1173 obj.deleted = true 1174 1175 // If state snapshotting is active, also mark the destruction there. 1176 // Note, we can't do this only at the end of a block because multiple 1177 // transactions within the same block might self destruct and then 1178 // ressurrect an account; but the snapshotter needs both events. 1179 if s.snap != nil { 1180 s.snapDestructs[obj.addrHash] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely) 1181 delete(s.snapAccounts, obj.addrHash) // Clear out any previously updated account data (may be recreated via a ressurrect) 1182 delete(s.snapStorage, obj.addrHash) // Clear out any previously updated storage data (may be recreated via a ressurrect) 1183 } 1184 } else { 1185 obj.finalise(true) // Prefetch slots in the background 1186 } 1187 s.stateObjectsPending[addr] = struct{}{} 1188 s.stateObjectsDirty[addr] = struct{}{} 1189 1190 // At this point, also ship the address off to the precacher. The precacher 1191 // will start loading tries, and when the change is eventually committed, 1192 // the commit-phase will be a lot faster 1193 addressesToPrefetch = append(addressesToPrefetch, common.CopyBytes(addr[:])) // Copy needed for closure 1194 } 1195 if s.prefetcher != nil && len(addressesToPrefetch) > 0 { 1196 s.prefetcher.prefetch(s.originalRoot, addressesToPrefetch) 1197 } 1198 // Invalidate journal because reverting across transactions is not allowed. 1199 s.clearJournalAndRefund() 1200 } 1201 1202 // IntermediateRoot computes the current root hash of the state trie. 1203 // It is called in between transactions to get the root hash that 1204 // goes into transaction receipts. 1205 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 1206 // Finalise all the dirty storage states and write them into the tries 1207 s.Finalise(deleteEmptyObjects) 1208 1209 // If there was a trie prefetcher operating, it gets aborted and irrevocably 1210 // modified after we start retrieving tries. Remove it from the statedb after 1211 // this round of use. 1212 // 1213 // This is weird pre-byzantium since the first tx runs with a prefetcher and 1214 // the remainder without, but pre-byzantium even the initial prefetcher is 1215 // useless, so no sleep lost. 1216 prefetcher := s.prefetcher 1217 if s.prefetcher != nil { 1218 defer func() { 1219 s.prefetcher.close() 1220 s.prefetcher = nil 1221 }() 1222 } 1223 // Although naively it makes sense to retrieve the account trie and then do 1224 // the contract storage and account updates sequentially, that short circuits 1225 // the account prefetcher. Instead, let's process all the storage updates 1226 // first, giving the account prefeches just a few more milliseconds of time 1227 // to pull useful data from disk. 1228 for addr := range s.stateObjectsPending { 1229 if obj := s.stateObjects[addr]; !obj.deleted { 1230 obj.updateRoot(s.db) 1231 } 1232 } 1233 // Now we're about to start to write changes to the trie. The trie is so far 1234 // _untouched_. We can check with the prefetcher, if it can give us a trie 1235 // which has the same root, but also has some content loaded into it. 1236 if prefetcher != nil { 1237 if trie := prefetcher.trie(s.originalRoot); trie != nil { 1238 s.trie = trie 1239 } 1240 } 1241 usedAddrs := make([][]byte, 0, len(s.stateObjectsPending)) 1242 for addr := range s.stateObjectsPending { 1243 if obj := s.stateObjects[addr]; obj.deleted { 1244 s.deleteStateObject(obj) 1245 s.AccountDeleted += 1 1246 } else { 1247 s.updateStateObject(obj) 1248 s.AccountUpdated += 1 1249 } 1250 usedAddrs = append(usedAddrs, common.CopyBytes(addr[:])) // Copy needed for closure 1251 } 1252 if prefetcher != nil { 1253 prefetcher.used(s.originalRoot, usedAddrs) 1254 } 1255 if len(s.stateObjectsPending) > 0 { 1256 s.stateObjectsPending = make(map[common.Address]struct{}) 1257 } 1258 // Track the amount of time wasted on hashing the account trie 1259 if metrics.EnabledExpensive { 1260 defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now()) 1261 } 1262 return s.trie.Hash() 1263 } 1264 1265 // Prepare sets the current transaction hash and index which are 1266 // used when the EVM emits new state logs. 1267 func (s *StateDB) Prepare(thash common.Hash, ti int) { 1268 s.thash = thash 1269 s.txIndex = ti 1270 } 1271 1272 func (s *StateDB) clearJournalAndRefund() { 1273 if len(s.journal.entries) > 0 { 1274 s.journal = newJournal() 1275 s.refund = 0 1276 } 1277 s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires 1278 } 1279 1280 // Commit writes the state to the underlying in-memory trie database. 1281 func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) { 1282 if s.dbErr != nil { 1283 return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr) 1284 } 1285 // Finalize any pending changes and merge everything into the tries 1286 s.IntermediateRoot(deleteEmptyObjects) 1287 1288 // Commit objects to the trie, measuring the elapsed time 1289 var storageCommitted int 1290 codeWriter := s.db.TrieDB().DiskDB().NewBatch() 1291 for addr := range s.stateObjectsDirty { 1292 if obj := s.stateObjects[addr]; !obj.deleted { 1293 // Write any contract code associated with the state object 1294 if obj.code != nil && obj.dirtyCode { 1295 rawdb.WriteCode(codeWriter, common.BytesToHash(obj.CodeHash()), obj.code) 1296 obj.dirtyCode = false 1297 } 1298 // Write any storage changes in the state object to its storage trie 1299 committed, err := obj.CommitTrie(s.db) 1300 if err != nil { 1301 return common.Hash{}, err 1302 } 1303 storageCommitted += committed 1304 } 1305 } 1306 if len(s.stateObjectsDirty) > 0 { 1307 s.stateObjectsDirty = make(map[common.Address]struct{}) 1308 } 1309 if codeWriter.ValueSize() > 0 { 1310 if err := codeWriter.Write(); err != nil { 1311 log.Crit("Failed to commit dirty codes", "error", err) 1312 } 1313 } 1314 // Write the account trie changes, measuing the amount of wasted time 1315 var start time.Time 1316 if metrics.EnabledExpensive { 1317 start = time.Now() 1318 } 1319 // The onleaf func is called _serially_, so we can reuse the same account 1320 // for unmarshalling every time. 1321 var account types.StateAccount 1322 root, accountCommitted, err := s.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash) error { 1323 if err := rlp.DecodeBytes(leaf, &account); err != nil { 1324 return nil 1325 } 1326 if account.Root != emptyRoot { 1327 s.db.TrieDB().Reference(account.Root, parent) 1328 } 1329 return nil 1330 }) 1331 if err != nil { 1332 return common.Hash{}, err 1333 } 1334 if metrics.EnabledExpensive { 1335 s.AccountCommits += time.Since(start) 1336 1337 accountUpdatedMeter.Mark(int64(s.AccountUpdated)) 1338 storageUpdatedMeter.Mark(int64(s.StorageUpdated)) 1339 accountDeletedMeter.Mark(int64(s.AccountDeleted)) 1340 storageDeletedMeter.Mark(int64(s.StorageDeleted)) 1341 accountCommittedMeter.Mark(int64(accountCommitted)) 1342 storageCommittedMeter.Mark(int64(storageCommitted)) 1343 s.AccountUpdated, s.AccountDeleted = 0, 0 1344 s.StorageUpdated, s.StorageDeleted = 0, 0 1345 } 1346 // If snapshotting is enabled, update the snapshot tree with this new version 1347 if s.snap != nil { 1348 if metrics.EnabledExpensive { 1349 defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now()) 1350 } 1351 // Only update if there's a state transition (skip empty Clique blocks) 1352 if parent := s.snap.Root(); parent != root { 1353 if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil { 1354 log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err) 1355 } 1356 // Keep 128 diff layers in the memory, persistent layer is 129th. 1357 // - head layer is paired with HEAD state 1358 // - head-1 layer is paired with HEAD-1 state 1359 // - head-127 layer(bottom-most diff layer) is paired with HEAD-127 state 1360 if err := s.snaps.Cap(root, 128); err != nil { 1361 log.Warn("Failed to cap snapshot tree", "root", root, "layers", 128, "err", err) 1362 } 1363 } 1364 s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil 1365 } 1366 return root, err 1367 } 1368 1369 // PrepareAccessList handles the preparatory steps for executing a state transition with 1370 // regards to both EIP-2929 and EIP-2930: 1371 // 1372 // - Add sender to access list (2929) 1373 // - Add destination to access list (2929) 1374 // - Add precompiles to access list (2929) 1375 // - Add the contents of the optional tx access list (2930) 1376 // 1377 // This method should only be called if Berlin/2929+2930 is applicable at the current number. 1378 func (s *StateDB) PrepareAccessList(sender common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) { 1379 // Clear out any leftover from previous executions 1380 s.accessList = newAccessList() 1381 1382 s.AddAddressToAccessList(sender) 1383 if dst != nil { 1384 s.AddAddressToAccessList(*dst) 1385 // If it's a create-tx, the destination will be added inside evm.create 1386 } 1387 for _, addr := range precompiles { 1388 s.AddAddressToAccessList(addr) 1389 } 1390 for _, el := range list { 1391 s.AddAddressToAccessList(el.Address) 1392 for _, key := range el.StorageKeys { 1393 s.AddSlotToAccessList(el.Address, key) 1394 } 1395 } 1396 } 1397 1398 // AddAddressToAccessList adds the given address to the access list 1399 func (s *StateDB) AddAddressToAccessList(addr common.Address) { 1400 if s.accessList.AddAddress(addr) { 1401 s.journal.append(accessListAddAccountChange{&addr}) 1402 } 1403 } 1404 1405 // AddSlotToAccessList adds the given (address, slot)-tuple to the access list 1406 func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) { 1407 addrMod, slotMod := s.accessList.AddSlot(addr, slot) 1408 if addrMod { 1409 // In practice, this should not happen, since there is no way to enter the 1410 // scope of 'address' without having the 'address' become already added 1411 // to the access list (via call-variant, create, etc). 1412 // Better safe than sorry, though 1413 s.journal.append(accessListAddAccountChange{&addr}) 1414 } 1415 if slotMod { 1416 s.journal.append(accessListAddSlotChange{ 1417 address: &addr, 1418 slot: &slot, 1419 }) 1420 } 1421 } 1422 1423 // AddressInAccessList returns true if the given address is in the access list. 1424 func (s *StateDB) AddressInAccessList(addr common.Address) bool { 1425 return s.accessList.ContainsAddress(addr) 1426 } 1427 1428 // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list. 1429 func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) { 1430 return s.accessList.Contains(addr, slot) 1431 }