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