github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/core/state/state_object.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 18 19 import ( 20 "bytes" 21 "fmt" 22 "io" 23 "math/big" 24 "time" 25 26 "github.com/scroll-tech/go-ethereum/common" 27 "github.com/scroll-tech/go-ethereum/core/types" 28 "github.com/scroll-tech/go-ethereum/crypto" 29 "github.com/scroll-tech/go-ethereum/crypto/codehash" 30 "github.com/scroll-tech/go-ethereum/metrics" 31 "github.com/scroll-tech/go-ethereum/rlp" 32 ) 33 34 var emptyPoseidonCodeHash = codehash.EmptyPoseidonCodeHash.Bytes() 35 var emptyKeccakCodeHash = codehash.EmptyKeccakCodeHash.Bytes() 36 37 type Code []byte 38 39 func (c Code) String() string { 40 return string(c) //strings.Join(Disassemble(c), " ") 41 } 42 43 type Storage map[common.Hash]common.Hash 44 45 func (s Storage) String() (str string) { 46 for key, value := range s { 47 str += fmt.Sprintf("%X : %X\n", key, value) 48 } 49 50 return 51 } 52 53 func (s Storage) Copy() Storage { 54 cpy := make(Storage) 55 for key, value := range s { 56 cpy[key] = value 57 } 58 59 return cpy 60 } 61 62 // stateObject represents an Ethereum account which is being modified. 63 // 64 // The usage pattern is as follows: 65 // First you need to obtain a state object. 66 // Account values can be accessed and modified through the object. 67 // Finally, call CommitTrie to write the modified storage trie into a database. 68 type stateObject struct { 69 address common.Address 70 addrHash common.Hash // hash of ethereum address of the account 71 data types.StateAccount 72 db *StateDB 73 74 // DB error. 75 // State objects are used by the consensus core and VM which are 76 // unable to deal with database-level errors. Any error that occurs 77 // during a database read is memoized here and will eventually be returned 78 // by StateDB.Commit. 79 dbErr error 80 81 // Write caches. 82 trie Trie // storage trie, which becomes non-nil on first access 83 code Code // contract bytecode, which gets set when code is loaded 84 85 originStorage Storage // Storage cache of original entries to dedup rewrites, reset for every transaction 86 pendingStorage Storage // Storage entries that need to be flushed to disk, at the end of an entire block 87 dirtyStorage Storage // Storage entries that have been modified in the current transaction execution 88 fakeStorage Storage // Fake storage which constructed by caller for debugging purpose. 89 90 // Cache flags. 91 // When an object is marked suicided it will be delete from the trie 92 // during the "update" phase of the state transition. 93 dirtyCode bool // true if the code was updated 94 suicided bool 95 deleted bool 96 } 97 98 // empty returns whether the account is considered empty. 99 func (s *stateObject) empty() bool { 100 // note: if KeccakCodeHash is empty then PoseidonCodeHash and CodeSize will also be empty 101 return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.KeccakCodeHash, emptyKeccakCodeHash) 102 } 103 104 // newObject creates a state object. 105 func newObject(db *StateDB, address common.Address, data types.StateAccount) *stateObject { 106 if data.Balance == nil { 107 data.Balance = new(big.Int) 108 } 109 if data.KeccakCodeHash == nil { 110 data.KeccakCodeHash = emptyKeccakCodeHash 111 data.PoseidonCodeHash = emptyPoseidonCodeHash 112 data.CodeSize = 0 113 } 114 if data.Root == (common.Hash{}) { 115 data.Root = db.db.TrieDB().EmptyRoot() 116 } 117 return &stateObject{ 118 db: db, 119 address: address, 120 addrHash: crypto.Keccak256Hash(address[:]), 121 data: data, 122 originStorage: make(Storage), 123 pendingStorage: make(Storage), 124 dirtyStorage: make(Storage), 125 } 126 } 127 128 // EncodeRLP implements rlp.Encoder. 129 func (s *stateObject) EncodeRLP(w io.Writer) error { 130 return rlp.Encode(w, &s.data) 131 } 132 133 // setError remembers the first non-nil error it is called with. 134 func (s *stateObject) setError(err error) { 135 if s.dbErr == nil { 136 s.dbErr = err 137 } 138 } 139 140 func (s *stateObject) markSuicided() { 141 s.suicided = true 142 } 143 144 func (s *stateObject) touch() { 145 s.db.journal.append(touchChange{ 146 account: &s.address, 147 }) 148 if s.address == ripemd { 149 // Explicitly put it in the dirty-cache, which is otherwise generated from 150 // flattened journals. 151 s.db.journal.dirty(s.address) 152 } 153 } 154 155 func (s *stateObject) getTrie(db Database) Trie { 156 if s.trie == nil { 157 // Try fetching from prefetcher first 158 // We don't prefetch empty tries 159 if s.data.Root != s.db.db.TrieDB().EmptyRoot() && s.db.prefetcher != nil { 160 // When the miner is creating the pending state, there is no 161 // prefetcher 162 s.trie = s.db.prefetcher.trie(s.data.Root) 163 } 164 if s.trie == nil { 165 var err error 166 s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root) 167 if err != nil { 168 s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{}) 169 s.setError(fmt.Errorf("can't create storage trie: %v", err)) 170 } 171 } 172 } 173 return s.trie 174 } 175 176 // GetState retrieves a value from the account storage trie. 177 func (s *stateObject) GetState(db Database, key common.Hash) common.Hash { 178 // If the fake storage is set, only lookup the state here(in the debugging mode) 179 if s.fakeStorage != nil { 180 return s.fakeStorage[key] 181 } 182 // If we have a dirty value for this state entry, return it 183 value, dirty := s.dirtyStorage[key] 184 if dirty { 185 return value 186 } 187 // Otherwise return the entry's original value 188 return s.GetCommittedState(db, key) 189 } 190 191 // GetCommittedState retrieves a value from the committed account storage trie. 192 func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash { 193 // If the fake storage is set, only lookup the state here(in the debugging mode) 194 if s.fakeStorage != nil { 195 return s.fakeStorage[key] 196 } 197 // If we have a pending write or clean cached, return that 198 if value, pending := s.pendingStorage[key]; pending { 199 return value 200 } 201 if value, cached := s.originStorage[key]; cached { 202 return value 203 } 204 // If no live objects are available, attempt to use snapshots 205 var ( 206 enc []byte 207 err error 208 meter *time.Duration 209 ) 210 readStart := time.Now() 211 if metrics.EnabledExpensive { 212 // If the snap is 'under construction', the first lookup may fail. If that 213 // happens, we don't want to double-count the time elapsed. Thus this 214 // dance with the metering. 215 defer func() { 216 if meter != nil { 217 *meter += time.Since(readStart) 218 } 219 }() 220 } 221 if s.db.snap != nil { 222 if metrics.EnabledExpensive { 223 meter = &s.db.SnapshotStorageReads 224 } 225 // If the object was destructed in *this* block (and potentially resurrected), 226 // the storage has been cleared out, and we should *not* consult the previous 227 // snapshot about any storage values. The only possible alternatives are: 228 // 1) resurrect happened, and new slot values were set -- those should 229 // have been handles via pendingStorage above. 230 // 2) we don't have new values, and can deliver empty response back 231 if _, destructed := s.db.snapDestructs[s.addrHash]; destructed { 232 return common.Hash{} 233 } 234 enc, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key.Bytes())) 235 } 236 // If the snapshot is unavailable or reading from it fails, load from the database. 237 if s.db.snap == nil || err != nil { 238 if meter != nil { 239 // If we already spent time checking the snapshot, account for it 240 // and reset the readStart 241 *meter += time.Since(readStart) 242 readStart = time.Now() 243 } 244 if metrics.EnabledExpensive { 245 meter = &s.db.StorageReads 246 } 247 if enc, err = s.getTrie(db).TryGet(key.Bytes()); err != nil { 248 s.setError(err) 249 return common.Hash{} 250 } 251 } 252 var value common.Hash 253 if db.TrieDB().Zktrie { 254 value = common.BytesToHash(enc) 255 } else { 256 if len(enc) > 0 { 257 _, content, _, err := rlp.Split(enc) 258 if err != nil { 259 s.setError(err) 260 } 261 value.SetBytes(content) 262 } 263 } 264 s.originStorage[key] = value 265 return value 266 } 267 268 // SetState updates a value in account storage. 269 func (s *stateObject) SetState(db Database, key, value common.Hash) { 270 // If the fake storage is set, put the temporary state update here. 271 if s.fakeStorage != nil { 272 s.fakeStorage[key] = value 273 return 274 } 275 // If the new value is the same as old, don't set 276 prev := s.GetState(db, key) 277 if prev == value { 278 return 279 } 280 // New value is different, update and journal the change 281 s.db.journal.append(storageChange{ 282 account: &s.address, 283 key: key, 284 prevalue: prev, 285 }) 286 s.setState(key, value) 287 } 288 289 // SetStorage replaces the entire state storage with the given one. 290 // 291 // After this function is called, all original state will be ignored and state 292 // lookup only happens in the fake state storage. 293 // 294 // Note this function should only be used for debugging purpose. 295 func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) { 296 // Allocate fake storage if it's nil. 297 if s.fakeStorage == nil { 298 s.fakeStorage = make(Storage) 299 } 300 for key, value := range storage { 301 s.fakeStorage[key] = value 302 } 303 // Don't bother journal since this function should only be used for 304 // debugging and the `fake` storage won't be committed to database. 305 } 306 307 func (s *stateObject) setState(key, value common.Hash) { 308 s.dirtyStorage[key] = value 309 } 310 311 // finalise moves all dirty storage slots into the pending area to be hashed or 312 // committed later. It is invoked at the end of every transaction. 313 func (s *stateObject) finalise(prefetch bool) { 314 slotsToPrefetch := make([][]byte, 0, len(s.dirtyStorage)) 315 for key, value := range s.dirtyStorage { 316 s.pendingStorage[key] = value 317 if value != s.originStorage[key] { 318 slotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure 319 } 320 } 321 if s.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && s.data.Root != s.db.db.TrieDB().EmptyRoot() { 322 s.db.prefetcher.prefetch(s.data.Root, slotsToPrefetch) 323 } 324 if len(s.dirtyStorage) > 0 { 325 s.dirtyStorage = make(Storage) 326 } 327 } 328 329 // updateTrie writes cached storage modifications into the object's storage trie. 330 // It will return nil if the trie has not been loaded and no changes have been made 331 func (s *stateObject) updateTrie(db Database) Trie { 332 // Make sure all dirty slots are finalized into the pending storage area 333 s.finalise(false) // Don't prefetch anymore, pull directly if need be 334 if len(s.pendingStorage) == 0 { 335 return s.trie 336 } 337 // Track the amount of time wasted on updating the storage trie 338 if metrics.EnabledExpensive { 339 defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now()) 340 } 341 // The snapshot storage map for the object 342 var storage map[common.Hash][]byte 343 // Insert all the pending updates into the trie 344 tr := s.getTrie(db) 345 hasher := s.db.hasher 346 347 usedStorage := make([][]byte, 0, len(s.pendingStorage)) 348 for key, value := range s.pendingStorage { 349 // Skip noop changes, persist actual changes 350 if value == s.originStorage[key] { 351 continue 352 } 353 s.originStorage[key] = value 354 355 var v []byte 356 if (value == common.Hash{}) { 357 s.setError(tr.TryDelete(key[:])) 358 s.db.StorageDeleted += 1 359 } else { 360 if db.TrieDB().Zktrie { 361 v = common.CopyBytes(value[:]) 362 } else { 363 // Encoding []byte cannot fail, ok to ignore the error. 364 v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:])) 365 } 366 s.setError(tr.TryUpdate(key[:], v)) 367 s.db.StorageUpdated += 1 368 } 369 // If state snapshotting is active, cache the data til commit 370 if s.db.snap != nil { 371 if storage == nil { 372 // Retrieve the old storage map, if available, create a new one otherwise 373 if storage = s.db.snapStorage[s.addrHash]; storage == nil { 374 storage = make(map[common.Hash][]byte) 375 s.db.snapStorage[s.addrHash] = storage 376 } 377 } 378 storage[crypto.HashData(hasher, key[:])] = v // v will be nil if it's deleted 379 } 380 usedStorage = append(usedStorage, common.CopyBytes(key[:])) // Copy needed for closure 381 } 382 if s.db.prefetcher != nil { 383 s.db.prefetcher.used(s.data.Root, usedStorage) 384 } 385 if len(s.pendingStorage) > 0 { 386 s.pendingStorage = make(Storage) 387 } 388 return tr 389 } 390 391 // UpdateRoot sets the trie root to the current root hash of 392 func (s *stateObject) updateRoot(db Database) { 393 // If nothing changed, don't bother with hashing anything 394 if s.updateTrie(db) == nil { 395 return 396 } 397 // Track the amount of time wasted on hashing the storage trie 398 if metrics.EnabledExpensive { 399 defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now()) 400 } 401 s.data.Root = s.trie.Hash() 402 } 403 404 // CommitTrie the storage trie of the object to db. 405 // This updates the trie root. 406 func (s *stateObject) CommitTrie(db Database) (int, error) { 407 // If nothing changed, don't bother with hashing anything 408 if s.updateTrie(db) == nil { 409 return 0, nil 410 } 411 if s.dbErr != nil { 412 return 0, s.dbErr 413 } 414 // Track the amount of time wasted on committing the storage trie 415 if metrics.EnabledExpensive { 416 defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now()) 417 } 418 root, committed, err := s.trie.Commit(nil) 419 if err == nil { 420 s.data.Root = root 421 } 422 return committed, err 423 } 424 425 // AddBalance adds amount to s's balance. 426 // It is used to add funds to the destination account of a transfer. 427 func (s *stateObject) AddBalance(amount *big.Int) { 428 // EIP161: We must check emptiness for the objects such that the account 429 // clearing (0,0,0 objects) can take effect. 430 if amount.Sign() == 0 { 431 if s.empty() { 432 s.touch() 433 } 434 return 435 } 436 s.SetBalance(new(big.Int).Add(s.Balance(), amount)) 437 } 438 439 // SubBalance removes amount from s's balance. 440 // It is used to remove funds from the origin account of a transfer. 441 func (s *stateObject) SubBalance(amount *big.Int) { 442 if amount.Sign() == 0 { 443 return 444 } 445 s.SetBalance(new(big.Int).Sub(s.Balance(), amount)) 446 } 447 448 func (s *stateObject) SetBalance(amount *big.Int) { 449 s.db.journal.append(balanceChange{ 450 account: &s.address, 451 prev: new(big.Int).Set(s.data.Balance), 452 }) 453 s.setBalance(amount) 454 } 455 456 func (s *stateObject) setBalance(amount *big.Int) { 457 s.data.Balance = amount 458 } 459 460 func (s *stateObject) deepCopy(db *StateDB) *stateObject { 461 stateObject := newObject(db, s.address, s.data) 462 if s.trie != nil { 463 stateObject.trie = db.db.CopyTrie(s.trie) 464 } 465 stateObject.code = s.code 466 stateObject.dirtyStorage = s.dirtyStorage.Copy() 467 stateObject.originStorage = s.originStorage.Copy() 468 stateObject.pendingStorage = s.pendingStorage.Copy() 469 stateObject.suicided = s.suicided 470 stateObject.dirtyCode = s.dirtyCode 471 stateObject.deleted = s.deleted 472 return stateObject 473 } 474 475 // 476 // Attribute accessors 477 // 478 479 // Returns the address of the contract/account 480 func (s *stateObject) Address() common.Address { 481 return s.address 482 } 483 484 // Code returns the contract code associated with this object, if any. 485 func (s *stateObject) Code(db Database) []byte { 486 if s.code != nil { 487 return s.code 488 } 489 if bytes.Equal(s.KeccakCodeHash(), emptyKeccakCodeHash) { 490 return nil 491 } 492 code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.KeccakCodeHash())) 493 if err != nil { 494 s.setError(fmt.Errorf("can't load code hash %x: %v", s.KeccakCodeHash(), err)) 495 } 496 s.code = code 497 return code 498 } 499 500 // CodeSize returns the size of the contract code associated with this object, 501 // or zero if none. This method is an almost mirror of Code, but uses a cache 502 // inside the database to avoid loading codes seen recently. 503 func (s *stateObject) CodeSize() uint64 { 504 return s.data.CodeSize 505 } 506 507 func (s *stateObject) SetCode(code []byte) { 508 prevcode := s.Code(s.db.db) 509 s.db.journal.append(codeChange{ 510 account: &s.address, 511 prevcode: prevcode, 512 }) 513 s.setCode(code) 514 } 515 516 func (s *stateObject) setCode(code []byte) { 517 s.code = code 518 s.data.KeccakCodeHash = codehash.KeccakCodeHash(code).Bytes() 519 s.data.PoseidonCodeHash = codehash.PoseidonCodeHash(code).Bytes() 520 s.data.CodeSize = uint64(len(code)) 521 s.dirtyCode = true 522 } 523 524 func (s *stateObject) SetNonce(nonce uint64) { 525 s.db.journal.append(nonceChange{ 526 account: &s.address, 527 prev: s.data.Nonce, 528 }) 529 s.setNonce(nonce) 530 } 531 532 func (s *stateObject) setNonce(nonce uint64) { 533 s.data.Nonce = nonce 534 } 535 536 func (s *stateObject) PoseidonCodeHash() []byte { 537 return s.data.PoseidonCodeHash 538 } 539 540 func (s *stateObject) KeccakCodeHash() []byte { 541 return s.data.KeccakCodeHash 542 } 543 544 func (s *stateObject) Balance() *big.Int { 545 return s.data.Balance 546 } 547 548 func (s *stateObject) Nonce() uint64 { 549 return s.data.Nonce 550 } 551 552 // Never called, but must be present to allow stateObject to be used 553 // as a vm.Account interface that also satisfies the vm.ContractRef 554 // interface. Interfaces are awesome. 555 func (s *stateObject) Value() *big.Int { 556 panic("Value on stateObject should never be called") 557 }