github.com/ethxdao/go-ethereum@v0.0.0-20221218102228-5ae34a9cc189/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/ethxdao/go-ethereum/common" 27 "github.com/ethxdao/go-ethereum/core/types" 28 "github.com/ethxdao/go-ethereum/crypto" 29 "github.com/ethxdao/go-ethereum/metrics" 30 "github.com/ethxdao/go-ethereum/rlp" 31 "github.com/ethxdao/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 func (s *stateObject) getTrie(db Database) Trie { 152 if s.trie == nil { 153 // Try fetching from prefetcher first 154 // We don't prefetch empty tries 155 if s.data.Root != emptyRoot && s.db.prefetcher != nil { 156 // When the miner is creating the pending state, there is no 157 // prefetcher 158 s.trie = s.db.prefetcher.trie(s.addrHash, s.data.Root) 159 } 160 if s.trie == nil { 161 var err error 162 s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root) 163 if err != nil { 164 s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{}) 165 s.setError(fmt.Errorf("can't create storage trie: %v", err)) 166 } 167 } 168 } 169 return s.trie 170 } 171 172 // GetState retrieves a value from the account storage trie. 173 func (s *stateObject) GetState(db Database, key common.Hash) common.Hash { 174 // If the fake storage is set, only lookup the state here(in the debugging mode) 175 if s.fakeStorage != nil { 176 return s.fakeStorage[key] 177 } 178 // If we have a dirty value for this state entry, return it 179 value, dirty := s.dirtyStorage[key] 180 if dirty { 181 return value 182 } 183 // Otherwise return the entry's original value 184 return s.GetCommittedState(db, key) 185 } 186 187 // GetCommittedState retrieves a value from the committed account storage trie. 188 func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash { 189 // If the fake storage is set, only lookup the state here(in the debugging mode) 190 if s.fakeStorage != nil { 191 return s.fakeStorage[key] 192 } 193 // If we have a pending write or clean cached, return that 194 if value, pending := s.pendingStorage[key]; pending { 195 return value 196 } 197 if value, cached := s.originStorage[key]; cached { 198 return value 199 } 200 // If no live objects are available, attempt to use snapshots 201 var ( 202 enc []byte 203 err error 204 ) 205 if s.db.snap != nil { 206 // If the object was destructed in *this* block (and potentially resurrected), 207 // the storage has been cleared out, and we should *not* consult the previous 208 // snapshot about any storage values. The only possible alternatives are: 209 // 1) resurrect happened, and new slot values were set -- those should 210 // have been handles via pendingStorage above. 211 // 2) we don't have new values, and can deliver empty response back 212 if _, destructed := s.db.snapDestructs[s.addrHash]; destructed { 213 return common.Hash{} 214 } 215 start := time.Now() 216 enc, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key.Bytes())) 217 if metrics.EnabledExpensive { 218 s.db.SnapshotStorageReads += time.Since(start) 219 } 220 } 221 // If the snapshot is unavailable or reading from it fails, load from the database. 222 if s.db.snap == nil || err != nil { 223 start := time.Now() 224 enc, err = s.getTrie(db).TryGet(key.Bytes()) 225 if metrics.EnabledExpensive { 226 s.db.StorageReads += time.Since(start) 227 } 228 if err != nil { 229 s.setError(err) 230 return common.Hash{} 231 } 232 } 233 var value common.Hash 234 if len(enc) > 0 { 235 _, content, _, err := rlp.Split(enc) 236 if err != nil { 237 s.setError(err) 238 } 239 value.SetBytes(content) 240 } 241 s.originStorage[key] = value 242 return value 243 } 244 245 // SetState updates a value in account storage. 246 func (s *stateObject) SetState(db Database, key, value common.Hash) { 247 // If the fake storage is set, put the temporary state update here. 248 if s.fakeStorage != nil { 249 s.fakeStorage[key] = value 250 return 251 } 252 // If the new value is the same as old, don't set 253 prev := s.GetState(db, key) 254 if prev == value { 255 return 256 } 257 // New value is different, update and journal the change 258 s.db.journal.append(storageChange{ 259 account: &s.address, 260 key: key, 261 prevalue: prev, 262 }) 263 s.setState(key, value) 264 } 265 266 // SetStorage replaces the entire state storage with the given one. 267 // 268 // After this function is called, all original state will be ignored and state 269 // lookup only happens in the fake state storage. 270 // 271 // Note this function should only be used for debugging purpose. 272 func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) { 273 // Allocate fake storage if it's nil. 274 if s.fakeStorage == nil { 275 s.fakeStorage = make(Storage) 276 } 277 for key, value := range storage { 278 s.fakeStorage[key] = value 279 } 280 // Don't bother journal since this function should only be used for 281 // debugging and the `fake` storage won't be committed to database. 282 } 283 284 func (s *stateObject) setState(key, value common.Hash) { 285 s.dirtyStorage[key] = value 286 } 287 288 // finalise moves all dirty storage slots into the pending area to be hashed or 289 // committed later. It is invoked at the end of every transaction. 290 func (s *stateObject) finalise(prefetch bool) { 291 slotsToPrefetch := make([][]byte, 0, len(s.dirtyStorage)) 292 for key, value := range s.dirtyStorage { 293 s.pendingStorage[key] = value 294 if value != s.originStorage[key] { 295 slotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure 296 } 297 } 298 if s.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && s.data.Root != emptyRoot { 299 s.db.prefetcher.prefetch(s.addrHash, s.data.Root, slotsToPrefetch) 300 } 301 if len(s.dirtyStorage) > 0 { 302 s.dirtyStorage = make(Storage) 303 } 304 } 305 306 // updateTrie writes cached storage modifications into the object's storage trie. 307 // It will return nil if the trie has not been loaded and no changes have been made 308 func (s *stateObject) updateTrie(db Database) Trie { 309 // Make sure all dirty slots are finalized into the pending storage area 310 s.finalise(false) // Don't prefetch anymore, pull directly if need be 311 if len(s.pendingStorage) == 0 { 312 return s.trie 313 } 314 // Track the amount of time wasted on updating the storage trie 315 if metrics.EnabledExpensive { 316 defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now()) 317 } 318 // The snapshot storage map for the object 319 var storage map[common.Hash][]byte 320 // Insert all the pending updates into the trie 321 tr := s.getTrie(db) 322 hasher := s.db.hasher 323 324 usedStorage := make([][]byte, 0, len(s.pendingStorage)) 325 for key, value := range s.pendingStorage { 326 // Skip noop changes, persist actual changes 327 if value == s.originStorage[key] { 328 continue 329 } 330 s.originStorage[key] = value 331 332 var v []byte 333 if (value == common.Hash{}) { 334 s.setError(tr.TryDelete(key[:])) 335 s.db.StorageDeleted += 1 336 } else { 337 // Encoding []byte cannot fail, ok to ignore the error. 338 v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:])) 339 s.setError(tr.TryUpdate(key[:], v)) 340 s.db.StorageUpdated += 1 341 } 342 // If state snapshotting is active, cache the data til commit 343 if s.db.snap != nil { 344 if storage == nil { 345 // Retrieve the old storage map, if available, create a new one otherwise 346 if storage = s.db.snapStorage[s.addrHash]; storage == nil { 347 storage = make(map[common.Hash][]byte) 348 s.db.snapStorage[s.addrHash] = storage 349 } 350 } 351 storage[crypto.HashData(hasher, key[:])] = v // v will be nil if it's deleted 352 } 353 usedStorage = append(usedStorage, common.CopyBytes(key[:])) // Copy needed for closure 354 } 355 if s.db.prefetcher != nil { 356 s.db.prefetcher.used(s.addrHash, s.data.Root, usedStorage) 357 } 358 if len(s.pendingStorage) > 0 { 359 s.pendingStorage = make(Storage) 360 } 361 return tr 362 } 363 364 // UpdateRoot sets the trie root to the current root hash of 365 func (s *stateObject) updateRoot(db Database) { 366 // If nothing changed, don't bother with hashing anything 367 if s.updateTrie(db) == nil { 368 return 369 } 370 // Track the amount of time wasted on hashing the storage trie 371 if metrics.EnabledExpensive { 372 defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now()) 373 } 374 s.data.Root = s.trie.Hash() 375 } 376 377 // CommitTrie the storage trie of the object to db. 378 // This updates the trie root. 379 func (s *stateObject) CommitTrie(db Database) (*trie.NodeSet, error) { 380 // If nothing changed, don't bother with hashing anything 381 if s.updateTrie(db) == nil { 382 return nil, nil 383 } 384 if s.dbErr != nil { 385 return nil, s.dbErr 386 } 387 // Track the amount of time wasted on committing the storage trie 388 if metrics.EnabledExpensive { 389 defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now()) 390 } 391 root, nodes, err := s.trie.Commit(false) 392 if err == nil { 393 s.data.Root = root 394 } 395 return nodes, err 396 } 397 398 // AddBalance adds amount to s's balance. 399 // It is used to add funds to the destination account of a transfer. 400 func (s *stateObject) AddBalance(amount *big.Int) { 401 // EIP161: We must check emptiness for the objects such that the account 402 // clearing (0,0,0 objects) can take effect. 403 if amount.Sign() == 0 { 404 if s.empty() { 405 s.touch() 406 } 407 return 408 } 409 s.SetBalance(new(big.Int).Add(s.Balance(), amount)) 410 } 411 412 // SubBalance removes amount from s's balance. 413 // It is used to remove funds from the origin account of a transfer. 414 func (s *stateObject) SubBalance(amount *big.Int) { 415 if amount.Sign() == 0 { 416 return 417 } 418 s.SetBalance(new(big.Int).Sub(s.Balance(), amount)) 419 } 420 421 func (s *stateObject) SetBalance(amount *big.Int) { 422 s.db.journal.append(balanceChange{ 423 account: &s.address, 424 prev: new(big.Int).Set(s.data.Balance), 425 }) 426 s.setBalance(amount) 427 } 428 429 func (s *stateObject) setBalance(amount *big.Int) { 430 s.data.Balance = amount 431 } 432 433 func (s *stateObject) deepCopy(db *StateDB) *stateObject { 434 stateObject := newObject(db, s.address, s.data) 435 if s.trie != nil { 436 stateObject.trie = db.db.CopyTrie(s.trie) 437 } 438 stateObject.code = s.code 439 stateObject.dirtyStorage = s.dirtyStorage.Copy() 440 stateObject.originStorage = s.originStorage.Copy() 441 stateObject.pendingStorage = s.pendingStorage.Copy() 442 stateObject.suicided = s.suicided 443 stateObject.dirtyCode = s.dirtyCode 444 stateObject.deleted = s.deleted 445 return stateObject 446 } 447 448 // 449 // Attribute accessors 450 // 451 452 // Returns the address of the contract/account 453 func (s *stateObject) Address() common.Address { 454 return s.address 455 } 456 457 // Code returns the contract code associated with this object, if any. 458 func (s *stateObject) Code(db Database) []byte { 459 if s.code != nil { 460 return s.code 461 } 462 if bytes.Equal(s.CodeHash(), emptyCodeHash) { 463 return nil 464 } 465 code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash())) 466 if err != nil { 467 s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err)) 468 } 469 s.code = code 470 return code 471 } 472 473 // CodeSize returns the size of the contract code associated with this object, 474 // or zero if none. This method is an almost mirror of Code, but uses a cache 475 // inside the database to avoid loading codes seen recently. 476 func (s *stateObject) CodeSize(db Database) int { 477 if s.code != nil { 478 return len(s.code) 479 } 480 if bytes.Equal(s.CodeHash(), emptyCodeHash) { 481 return 0 482 } 483 size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash())) 484 if err != nil { 485 s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err)) 486 } 487 return size 488 } 489 490 func (s *stateObject) SetCode(codeHash common.Hash, code []byte) { 491 prevcode := s.Code(s.db.db) 492 s.db.journal.append(codeChange{ 493 account: &s.address, 494 prevhash: s.CodeHash(), 495 prevcode: prevcode, 496 }) 497 s.setCode(codeHash, code) 498 } 499 500 func (s *stateObject) setCode(codeHash common.Hash, code []byte) { 501 s.code = code 502 s.data.CodeHash = codeHash[:] 503 s.dirtyCode = true 504 } 505 506 func (s *stateObject) SetNonce(nonce uint64) { 507 s.db.journal.append(nonceChange{ 508 account: &s.address, 509 prev: s.data.Nonce, 510 }) 511 s.setNonce(nonce) 512 } 513 514 func (s *stateObject) setNonce(nonce uint64) { 515 s.data.Nonce = nonce 516 } 517 518 func (s *stateObject) CodeHash() []byte { 519 return s.data.CodeHash 520 } 521 522 func (s *stateObject) Balance() *big.Int { 523 return s.data.Balance 524 } 525 526 func (s *stateObject) Nonce() uint64 { 527 return s.data.Nonce 528 } 529 530 // Never called, but must be present to allow stateObject to be used 531 // as a vm.Account interface that also satisfies the vm.ContractRef 532 // interface. Interfaces are awesome. 533 func (s *stateObject) Value() *big.Int { 534 panic("Value on stateObject should never be called") 535 }