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