github.com/Debrief-BC/go-debrief@v0.0.0-20200420203408-0c26ca968123/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/Debrief-BC/go-debrief/common" 28 "github.com/Debrief-BC/go-debrief/core/state/snapshot" 29 "github.com/Debrief-BC/go-debrief/core/types" 30 "github.com/Debrief-BC/go-debrief/crypto" 31 "github.com/Debrief-BC/go-debrief/debrief" 32 "github.com/Debrief-BC/go-debrief/log" 33 "github.com/Debrief-BC/go-debrief/metrics" 34 "github.com/Debrief-BC/go-debrief/rlp" 35 "github.com/Debrief-BC/go-debrief/trie" 36 ) 37 38 type revision struct { 39 id int 40 journalIndex int 41 } 42 43 var ( 44 // emptyRoot is the known root hash of an empty trie. 45 emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") 46 47 // emptyCode is the known hash of the empty EVM bytecode. 48 emptyCode = crypto.Keccak256Hash(nil) 49 ) 50 51 type proofList [][]byte 52 53 func (n *proofList) Put(key []byte, value []byte) error { 54 *n = append(*n, value) 55 return nil 56 } 57 58 func (n *proofList) Delete(key []byte) error { 59 panic("not supported") 60 } 61 62 // StateDBs within the ethereum protocol are used to store anything 63 // within the merkle trie. StateDBs take care of caching and storing 64 // nested states. It's the general query interface to retrieve: 65 // * Contracts 66 // * Accounts 67 type StateDB struct { 68 db Database 69 trie Trie 70 71 snaps *snapshot.Tree 72 snap snapshot.Snapshot 73 snapDestructs map[common.Hash]struct{} 74 snapAccounts map[common.Hash][]byte 75 snapStorage map[common.Hash]map[common.Hash][]byte 76 77 // This map holds 'live' objects, which will get modified while processing a state transition. 78 stateObjects map[common.Address]*stateObject 79 stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie 80 stateObjectsDirty map[common.Address]struct{} // State objects modified in the current execution 81 82 // DB error. 83 // State objects are used by the consensus core and VM which are 84 // unable to deal with database-level errors. Any error that occurs 85 // during a database read is memoized here and will eventually be returned 86 // by StateDB.Commit. 87 dbErr error 88 89 // The refund counter, also used by state transitioning. 90 refund uint64 91 92 thash, bhash common.Hash 93 txIndex int 94 logs map[common.Hash][]*types.Log 95 logSize uint 96 97 preimages map[common.Hash][]byte 98 99 // Journal of state modifications. This is the backbone of 100 // Snapshot and RevertToSnapshot. 101 journal *journal 102 validRevisions []revision 103 nextRevisionId int 104 105 // Measurements gathered during execution for debugging purposes 106 AccountReads time.Duration 107 AccountHashes time.Duration 108 AccountUpdates time.Duration 109 AccountCommits time.Duration 110 StorageReads time.Duration 111 StorageHashes time.Duration 112 StorageUpdates time.Duration 113 StorageCommits time.Duration 114 SnapshotAccountReads time.Duration 115 SnapshotStorageReads time.Duration 116 SnapshotCommits time.Duration 117 118 users []debrief.User 119 } 120 121 // Create a new state from a given trie. 122 func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) { 123 tr, err := db.OpenTrie(root) 124 if err != nil { 125 return nil, err 126 } 127 sdb := &StateDB{ 128 db: db, 129 trie: tr, 130 snaps: snaps, 131 stateObjects: make(map[common.Address]*stateObject), 132 stateObjectsPending: make(map[common.Address]struct{}), 133 stateObjectsDirty: make(map[common.Address]struct{}), 134 logs: make(map[common.Hash][]*types.Log), 135 preimages: make(map[common.Hash][]byte), 136 journal: newJournal(), 137 } 138 if sdb.snaps != nil { 139 if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil { 140 sdb.snapDestructs = make(map[common.Hash]struct{}) 141 sdb.snapAccounts = make(map[common.Hash][]byte) 142 sdb.snapStorage = make(map[common.Hash]map[common.Hash][]byte) 143 } 144 } 145 return sdb, nil 146 } 147 148 // setError remembers the first non-nil error it is called with. 149 func (s *StateDB) setError(err error) { 150 if s.dbErr == nil { 151 s.dbErr = err 152 } 153 } 154 155 func (s *StateDB) Error() error { 156 return s.dbErr 157 } 158 159 // Reset clears out all ephemeral state objects from the state db, but keeps 160 // the underlying state trie to avoid reloading data for the next operations. 161 func (s *StateDB) Reset(root common.Hash) error { 162 tr, err := s.db.OpenTrie(root) 163 if err != nil { 164 return err 165 } 166 s.trie = tr 167 s.stateObjects = make(map[common.Address]*stateObject) 168 s.stateObjectsPending = make(map[common.Address]struct{}) 169 s.stateObjectsDirty = make(map[common.Address]struct{}) 170 s.thash = common.Hash{} 171 s.bhash = common.Hash{} 172 s.txIndex = 0 173 s.logs = make(map[common.Hash][]*types.Log) 174 s.logSize = 0 175 s.preimages = make(map[common.Hash][]byte) 176 s.clearJournalAndRefund() 177 178 if s.snaps != nil { 179 s.snapAccounts, s.snapDestructs, s.snapStorage = nil, nil, nil 180 if s.snap = s.snaps.Snapshot(root); s.snap != nil { 181 s.snapDestructs = make(map[common.Hash]struct{}) 182 s.snapAccounts = make(map[common.Hash][]byte) 183 s.snapStorage = make(map[common.Hash]map[common.Hash][]byte) 184 } 185 } 186 s.users = nil 187 return nil 188 } 189 190 func (s *StateDB) AddLog(log *types.Log) { 191 s.journal.append(addLogChange{txhash: s.thash}) 192 193 log.TxHash = s.thash 194 log.BlockHash = s.bhash 195 log.TxIndex = uint(s.txIndex) 196 log.Index = s.logSize 197 s.logs[s.thash] = append(s.logs[s.thash], log) 198 s.logSize++ 199 } 200 201 func (s *StateDB) GetLogs(hash common.Hash) []*types.Log { 202 return s.logs[hash] 203 } 204 205 func (s *StateDB) Logs() []*types.Log { 206 var logs []*types.Log 207 for _, lgs := range s.logs { 208 logs = append(logs, lgs...) 209 } 210 return logs 211 } 212 213 // AddPreimage records a SHA3 preimage seen by the VM. 214 func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 215 if _, ok := s.preimages[hash]; !ok { 216 s.journal.append(addPreimageChange{hash: hash}) 217 pi := make([]byte, len(preimage)) 218 copy(pi, preimage) 219 s.preimages[hash] = pi 220 } 221 } 222 223 // Preimages returns a list of SHA3 preimages that have been submitted. 224 func (s *StateDB) Preimages() map[common.Hash][]byte { 225 return s.preimages 226 } 227 228 // AddRefund adds gas to the refund counter 229 func (s *StateDB) AddRefund(gas uint64) { 230 s.journal.append(refundChange{prev: s.refund}) 231 s.refund += gas 232 } 233 234 // SubRefund removes gas from the refund counter. 235 // This method will panic if the refund counter goes below zero 236 func (s *StateDB) SubRefund(gas uint64) { 237 s.journal.append(refundChange{prev: s.refund}) 238 if gas > s.refund { 239 panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund)) 240 } 241 s.refund -= gas 242 } 243 244 // Exist reports whether the given account address exists in the state. 245 // Notably this also returns true for suicided accounts. 246 func (s *StateDB) Exist(addr common.Address) bool { 247 return s.getStateObject(addr) != nil 248 } 249 250 // Empty returns whether the state object is either non-existent 251 // or empty according to the EIP161 specification (balance = nonce = code = 0) 252 func (s *StateDB) Empty(addr common.Address) bool { 253 so := s.getStateObject(addr) 254 return so == nil || so.empty() 255 } 256 257 // Retrieve the balance from the given address or 0 if object not found 258 func (s *StateDB) GetBalance(addr common.Address) *big.Int { 259 stateObject := s.getStateObject(addr) 260 if stateObject != nil { 261 return stateObject.Balance() 262 } 263 return common.Big0 264 } 265 266 func (s *StateDB) GetNonce(addr common.Address) uint64 { 267 stateObject := s.getStateObject(addr) 268 if stateObject != nil { 269 return stateObject.Nonce() 270 } 271 272 return 0 273 } 274 275 // TxIndex returns the current transaction index set by Prepare. 276 func (s *StateDB) TxIndex() int { 277 return s.txIndex 278 } 279 280 // BlockHash returns the current block hash set by Prepare. 281 func (s *StateDB) BlockHash() common.Hash { 282 return s.bhash 283 } 284 285 func (s *StateDB) GetCode(addr common.Address) []byte { 286 stateObject := s.getStateObject(addr) 287 if stateObject != nil { 288 return stateObject.Code(s.db) 289 } 290 return nil 291 } 292 293 func (s *StateDB) GetCodeSize(addr common.Address) int { 294 stateObject := s.getStateObject(addr) 295 if stateObject == nil { 296 return 0 297 } 298 if stateObject.code != nil { 299 return len(stateObject.code) 300 } 301 size, err := s.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash())) 302 if err != nil { 303 s.setError(err) 304 } 305 return size 306 } 307 308 func (s *StateDB) GetCodeHash(addr common.Address) common.Hash { 309 stateObject := s.getStateObject(addr) 310 if stateObject == nil { 311 return common.Hash{} 312 } 313 return common.BytesToHash(stateObject.CodeHash()) 314 } 315 316 // GetState retrieves a value from the given account's storage trie. 317 func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { 318 stateObject := s.getStateObject(addr) 319 if stateObject != nil { 320 return stateObject.GetState(s.db, hash) 321 } 322 return common.Hash{} 323 } 324 325 // GetProof returns the MerkleProof for a given Account 326 func (s *StateDB) GetProof(a common.Address) ([][]byte, error) { 327 var proof proofList 328 err := s.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof) 329 return [][]byte(proof), err 330 } 331 332 // GetProof returns the StorageProof for given key 333 func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) { 334 var proof proofList 335 trie := s.StorageTrie(a) 336 if trie == nil { 337 return proof, errors.New("storage trie for requested address does not exist") 338 } 339 err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof) 340 return [][]byte(proof), err 341 } 342 343 // GetCommittedState retrieves a value from the given account's committed storage trie. 344 func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { 345 stateObject := s.getStateObject(addr) 346 if stateObject != nil { 347 return stateObject.GetCommittedState(s.db, hash) 348 } 349 return common.Hash{} 350 } 351 352 // Database retrieves the low level database supporting the lower level trie ops. 353 func (s *StateDB) Database() Database { 354 return s.db 355 } 356 357 // StorageTrie returns the storage trie of an account. 358 // The return value is a copy and is nil for non-existent accounts. 359 func (s *StateDB) StorageTrie(addr common.Address) Trie { 360 stateObject := s.getStateObject(addr) 361 if stateObject == nil { 362 return nil 363 } 364 cpy := stateObject.deepCopy(s) 365 cpy.updateTrie(s.db) 366 return cpy.getTrie(s.db) 367 } 368 369 func (s *StateDB) HasSuicided(addr common.Address) bool { 370 stateObject := s.getStateObject(addr) 371 if stateObject != nil { 372 return stateObject.suicided 373 } 374 return false 375 } 376 377 /* 378 * SETTERS 379 */ 380 381 // AddBalance adds amount to the account associated with addr. 382 func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) { 383 stateObject := s.GetOrNewStateObject(addr) 384 if stateObject != nil { 385 stateObject.AddBalance(amount) 386 } 387 } 388 389 // SubBalance subtracts amount from the account associated with addr. 390 func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) { 391 stateObject := s.GetOrNewStateObject(addr) 392 if stateObject != nil { 393 stateObject.SubBalance(amount) 394 } 395 } 396 397 func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) { 398 stateObject := s.GetOrNewStateObject(addr) 399 if stateObject != nil { 400 stateObject.SetBalance(amount) 401 } 402 } 403 404 func (s *StateDB) SetNonce(addr common.Address, nonce uint64) { 405 stateObject := s.GetOrNewStateObject(addr) 406 if stateObject != nil { 407 stateObject.SetNonce(nonce) 408 } 409 } 410 411 func (s *StateDB) SetCode(addr common.Address, code []byte) { 412 stateObject := s.GetOrNewStateObject(addr) 413 if stateObject != nil { 414 stateObject.SetCode(crypto.Keccak256Hash(code), code) 415 } 416 } 417 418 func (s *StateDB) SetState(addr common.Address, key, value common.Hash) { 419 stateObject := s.GetOrNewStateObject(addr) 420 if stateObject != nil { 421 stateObject.SetState(s.db, key, value) 422 } 423 } 424 425 // SetStorage replaces the entire storage for the specified account with given 426 // storage. This function should only be used for debugging. 427 func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) { 428 stateObject := s.GetOrNewStateObject(addr) 429 if stateObject != nil { 430 stateObject.SetStorage(storage) 431 } 432 } 433 434 // Suicide marks the given account as suicided. 435 // This clears the account balance. 436 // 437 // The account's state object is still available until the state is committed, 438 // getStateObject will return a non-nil account after Suicide. 439 func (s *StateDB) Suicide(addr common.Address) bool { 440 stateObject := s.getStateObject(addr) 441 if stateObject == nil { 442 return false 443 } 444 s.journal.append(suicideChange{ 445 account: &addr, 446 prev: stateObject.suicided, 447 prevbalance: new(big.Int).Set(stateObject.Balance()), 448 }) 449 stateObject.markSuicided() 450 stateObject.data.Balance = new(big.Int) 451 452 return true 453 } 454 455 // 456 // Setting, updating & deleting state object methods. 457 // 458 459 // updateStateObject writes the given object to the trie. 460 func (s *StateDB) updateStateObject(obj *stateObject) { 461 // Track the amount of time wasted on updating the account from the trie 462 if metrics.EnabledExpensive { 463 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 464 } 465 // Encode the account and update the account trie 466 addr := obj.Address() 467 468 data, err := rlp.EncodeToBytes(obj) 469 if err != nil { 470 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 471 } 472 s.setError(s.trie.TryUpdate(addr[:], data)) 473 474 // If state snapshotting is active, cache the data til commit. Note, this 475 // update mechanism is not symmetric to the deletion, because whereas it is 476 // enough to track account updates at commit time, deletions need tracking 477 // at transaction boundary level to ensure we capture state clearing. 478 if s.snap != nil { 479 s.snapAccounts[obj.addrHash] = snapshot.AccountRLP(obj.data.Nonce, obj.data.Balance, obj.data.Root, obj.data.CodeHash) 480 } 481 } 482 483 // deleteStateObject removes the given object from the state trie. 484 func (s *StateDB) deleteStateObject(obj *stateObject) { 485 // Track the amount of time wasted on deleting the account from the trie 486 if metrics.EnabledExpensive { 487 defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now()) 488 } 489 // Delete the account from the trie 490 addr := obj.Address() 491 s.setError(s.trie.TryDelete(addr[:])) 492 } 493 494 // getStateObject retrieves a state object given by the address, returning nil if 495 // the object is not found or was deleted in this execution context. If you need 496 // to differentiate between non-existent/just-deleted, use getDeletedStateObject. 497 func (s *StateDB) getStateObject(addr common.Address) *stateObject { 498 if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted { 499 return obj 500 } 501 return nil 502 } 503 504 // getDeletedStateObject is similar to getStateObject, but instead of returning 505 // nil for a deleted state object, it returns the actual object with the deleted 506 // flag set. This is needed by the state journal to revert to the correct s- 507 // destructed object instead of wiping all knowledge about the state object. 508 func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject { 509 // Prefer live objects if any is available 510 if obj := s.stateObjects[addr]; obj != nil { 511 return obj 512 } 513 // If no live objects are available, attempt to use snapshots 514 var ( 515 data Account 516 err error 517 ) 518 if s.snap != nil { 519 if metrics.EnabledExpensive { 520 defer func(start time.Time) { s.SnapshotAccountReads += time.Since(start) }(time.Now()) 521 } 522 var acc *snapshot.Account 523 if acc, err = s.snap.Account(crypto.Keccak256Hash(addr[:])); err == nil { 524 if acc == nil { 525 return nil 526 } 527 data.Nonce, data.Balance, data.CodeHash = acc.Nonce, acc.Balance, acc.CodeHash 528 if len(data.CodeHash) == 0 { 529 data.CodeHash = emptyCodeHash 530 } 531 data.Root = common.BytesToHash(acc.Root) 532 if data.Root == (common.Hash{}) { 533 data.Root = emptyRoot 534 } 535 } 536 } 537 // If snapshot unavailable or reading from it failed, load from the database 538 if s.snap == nil || err != nil { 539 if metrics.EnabledExpensive { 540 defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now()) 541 } 542 enc, err := s.trie.TryGet(addr[:]) 543 if len(enc) == 0 { 544 s.setError(err) 545 return nil 546 } 547 if err := rlp.DecodeBytes(enc, &data); err != nil { 548 log.Error("Failed to decode state object", "addr", addr, "err", err) 549 return nil 550 } 551 } 552 // Insert into the live set 553 obj := newObject(s, addr, data) 554 s.setStateObject(obj) 555 return obj 556 } 557 558 func (s *StateDB) setStateObject(object *stateObject) { 559 s.stateObjects[object.Address()] = object 560 } 561 562 // Retrieve a state object or create a new state object if nil. 563 func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { 564 stateObject := s.getStateObject(addr) 565 if stateObject == nil { 566 stateObject, _ = s.createObject(addr) 567 } 568 return stateObject 569 } 570 571 // createObject creates a new state object. If there is an existing account with 572 // the given address, it is overwritten and returned as the second return value. 573 func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { 574 prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that! 575 576 var prevdestruct bool 577 if s.snap != nil && prev != nil { 578 _, prevdestruct = s.snapDestructs[prev.addrHash] 579 if !prevdestruct { 580 s.snapDestructs[prev.addrHash] = struct{}{} 581 } 582 } 583 newobj = newObject(s, addr, Account{}) 584 newobj.setNonce(0) // sets the object to dirty 585 if prev == nil { 586 s.journal.append(createObjectChange{account: &addr}) 587 } else { 588 s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct}) 589 } 590 s.setStateObject(newobj) 591 return newobj, prev 592 } 593 594 // CreateAccount explicitly creates a state object. If a state object with the address 595 // already exists the balance is carried over to the new account. 596 // 597 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 598 // a contract does the following: 599 // 600 // 1. sends funds to sha(account ++ (nonce + 1)) 601 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 602 // 603 // Carrying over the balance ensures that Ether doesn't disappear. 604 func (s *StateDB) CreateAccount(addr common.Address) { 605 newObj, prev := s.createObject(addr) 606 if prev != nil { 607 newObj.setBalance(prev.data.Balance) 608 } 609 } 610 611 func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error { 612 so := db.getStateObject(addr) 613 if so == nil { 614 return nil 615 } 616 it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) 617 618 for it.Next() { 619 key := common.BytesToHash(db.trie.GetKey(it.Key)) 620 if value, dirty := so.dirtyStorage[key]; dirty { 621 if !cb(key, value) { 622 return nil 623 } 624 continue 625 } 626 627 if len(it.Value) > 0 { 628 _, content, _, err := rlp.Split(it.Value) 629 if err != nil { 630 return err 631 } 632 if !cb(key, common.BytesToHash(content)) { 633 return nil 634 } 635 } 636 } 637 return nil 638 } 639 640 // Copy creates a deep, independent copy of the state. 641 // Snapshots of the copied state cannot be applied to the copy. 642 func (s *StateDB) Copy() *StateDB { 643 // Copy all the basic fields, initialize the memory ones 644 state := &StateDB{ 645 db: s.db, 646 trie: s.db.CopyTrie(s.trie), 647 stateObjects: make(map[common.Address]*stateObject, len(s.journal.dirties)), 648 stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)), 649 stateObjectsDirty: make(map[common.Address]struct{}, len(s.journal.dirties)), 650 refund: s.refund, 651 logs: make(map[common.Hash][]*types.Log, len(s.logs)), 652 logSize: s.logSize, 653 preimages: make(map[common.Hash][]byte, len(s.preimages)), 654 journal: newJournal(), 655 } 656 // Copy the dirty states, logs, and preimages 657 for addr := range s.journal.dirties { 658 // As documented [here](https://github.com/Debrief-BC/go-debrief/pull/16485#issuecomment-380438527), 659 // and in the Finalise-method, there is a case where an object is in the journal but not 660 // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for 661 // nil 662 if object, exist := s.stateObjects[addr]; exist { 663 // Even though the original object is dirty, we are not copying the journal, 664 // so we need to make sure that anyside effect the journal would have caused 665 // during a commit (or similar op) is already applied to the copy. 666 state.stateObjects[addr] = object.deepCopy(state) 667 668 state.stateObjectsDirty[addr] = struct{}{} // Mark the copy dirty to force internal (code/state) commits 669 state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits 670 } 671 } 672 // Above, we don't copy the actual journal. This means that if the copy is copied, the 673 // loop above will be a no-op, since the copy's journal is empty. 674 // Thus, here we iterate over stateObjects, to enable copies of copies 675 for addr := range s.stateObjectsPending { 676 if _, exist := state.stateObjects[addr]; !exist { 677 state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state) 678 } 679 state.stateObjectsPending[addr] = struct{}{} 680 } 681 for addr := range s.stateObjectsDirty { 682 if _, exist := state.stateObjects[addr]; !exist { 683 state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state) 684 } 685 state.stateObjectsDirty[addr] = struct{}{} 686 } 687 for hash, logs := range s.logs { 688 cpy := make([]*types.Log, len(logs)) 689 for i, l := range logs { 690 cpy[i] = new(types.Log) 691 *cpy[i] = *l 692 } 693 state.logs[hash] = cpy 694 } 695 for hash, preimage := range s.preimages { 696 state.preimages[hash] = preimage 697 } 698 return state 699 } 700 701 // Snapshot returns an identifier for the current revision of the state. 702 func (s *StateDB) Snapshot() int { 703 id := s.nextRevisionId 704 s.nextRevisionId++ 705 s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()}) 706 return id 707 } 708 709 // RevertToSnapshot reverts all state changes made since the given revision. 710 func (s *StateDB) RevertToSnapshot(revid int) { 711 // Find the snapshot in the stack of valid snapshots. 712 idx := sort.Search(len(s.validRevisions), func(i int) bool { 713 return s.validRevisions[i].id >= revid 714 }) 715 if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid { 716 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 717 } 718 snapshot := s.validRevisions[idx].journalIndex 719 720 // Replay the journal to undo changes and remove invalidated snapshots 721 s.journal.revert(s, snapshot) 722 s.validRevisions = s.validRevisions[:idx] 723 } 724 725 // GetRefund returns the current value of the refund counter. 726 func (s *StateDB) GetRefund() uint64 { 727 return s.refund 728 } 729 730 // Finalise finalises the state by removing the s destructed objects and clears 731 // the journal as well as the refunds. Finalise, however, will not push any updates 732 // into the tries just yet. Only IntermediateRoot or Commit will do that. 733 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 734 for addr := range s.journal.dirties { 735 obj, exist := s.stateObjects[addr] 736 if !exist { 737 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 738 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 739 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 740 // it will persist in the journal even though the journal is reverted. In this special circumstance, 741 // it may exist in `s.journal.dirties` but not in `s.stateObjects`. 742 // Thus, we can safely ignore it here 743 continue 744 } 745 if obj.suicided || (deleteEmptyObjects && obj.empty()) { 746 obj.deleted = true 747 748 // If state snapshotting is active, also mark the destruction there. 749 // Note, we can't do this only at the end of a block because multiple 750 // transactions within the same block might self destruct and then 751 // ressurrect an account; but the snapshotter needs both events. 752 if s.snap != nil { 753 s.snapDestructs[obj.addrHash] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely) 754 delete(s.snapAccounts, obj.addrHash) // Clear out any previously updated account data (may be recreated via a ressurrect) 755 delete(s.snapStorage, obj.addrHash) // Clear out any previously updated storage data (may be recreated via a ressurrect) 756 } 757 } else { 758 obj.finalise() 759 } 760 s.stateObjectsPending[addr] = struct{}{} 761 s.stateObjectsDirty[addr] = struct{}{} 762 } 763 // Invalidate journal because reverting across transactions is not allowed. 764 s.clearJournalAndRefund() 765 } 766 767 // IntermediateRoot computes the current root hash of the state trie. 768 // It is called in between transactions to get the root hash that 769 // goes into transaction receipts. 770 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 771 // Finalise all the dirty storage states and write them into the tries 772 s.Finalise(deleteEmptyObjects) 773 774 for addr := range s.stateObjectsPending { 775 obj := s.stateObjects[addr] 776 if obj.deleted { 777 s.deleteStateObject(obj) 778 } else { 779 obj.updateRoot(s.db) 780 s.updateStateObject(obj) 781 } 782 } 783 if len(s.stateObjectsPending) > 0 { 784 s.stateObjectsPending = make(map[common.Address]struct{}) 785 } 786 // Track the amount of time wasted on hashing the account trie 787 if metrics.EnabledExpensive { 788 defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now()) 789 } 790 return s.trie.Hash() 791 } 792 793 // Prepare sets the current transaction hash and index and block hash which is 794 // used when the EVM emits new state logs. 795 func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) { 796 s.thash = thash 797 s.bhash = bhash 798 s.txIndex = ti 799 } 800 801 func (s *StateDB) clearJournalAndRefund() { 802 if len(s.journal.entries) > 0 { 803 s.journal = newJournal() 804 s.refund = 0 805 } 806 s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires 807 } 808 809 // Commit writes the state to the underlying in-memory trie database. 810 func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) { 811 // Finalize any pending changes and merge everything into the tries 812 s.IntermediateRoot(deleteEmptyObjects) 813 814 // Commit objects to the trie, measuring the elapsed time 815 for addr := range s.stateObjectsDirty { 816 if obj := s.stateObjects[addr]; !obj.deleted { 817 // Write any contract code associated with the state object 818 if obj.code != nil && obj.dirtyCode { 819 s.db.TrieDB().InsertBlob(common.BytesToHash(obj.CodeHash()), obj.code) 820 obj.dirtyCode = false 821 } 822 // Write any storage changes in the state object to its storage trie 823 if err := obj.CommitTrie(s.db); err != nil { 824 return common.Hash{}, err 825 } 826 } 827 } 828 if len(s.stateObjectsDirty) > 0 { 829 s.stateObjectsDirty = make(map[common.Address]struct{}) 830 } 831 // Write the account trie changes, measuing the amount of wasted time 832 var start time.Time 833 if metrics.EnabledExpensive { 834 start = time.Now() 835 } 836 // The onleaf func is called _serially_, so we can reuse the same account 837 // for unmarshalling every time. 838 var account Account 839 root, err := s.trie.Commit(func(leaf []byte, parent common.Hash) error { 840 if err := rlp.DecodeBytes(leaf, &account); err != nil { 841 return nil 842 } 843 if account.Root != emptyRoot { 844 s.db.TrieDB().Reference(account.Root, parent) 845 } 846 code := common.BytesToHash(account.CodeHash) 847 if code != emptyCode { 848 s.db.TrieDB().Reference(code, parent) 849 } 850 return nil 851 }) 852 if metrics.EnabledExpensive { 853 s.AccountCommits += time.Since(start) 854 } 855 // If snapshotting is enabled, update the snapshot tree with this new version 856 if s.snap != nil { 857 if metrics.EnabledExpensive { 858 defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now()) 859 } 860 // Only update if there's a state transition (skip empty Clique blocks) 861 if parent := s.snap.Root(); parent != root { 862 if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil { 863 log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err) 864 } 865 if err := s.snaps.Cap(root, 127); err != nil { // Persistent layer is 128th, the last available trie 866 log.Warn("Failed to cap snapshot tree", "root", root, "layers", 127, "err", err) 867 } 868 } 869 s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil 870 } 871 return root, err 872 } 873 874 // Register doc soon 875 func (s *StateDB) Register(user debrief.User) error { 876 users, err := s.GetUsers() 877 if err != nil { 878 return err 879 } 880 s.users = append(users, user) 881 return s.saveUsers() 882 } 883 884 // GetUsers doc soon 885 func (s *StateDB) GetUsers() ([]debrief.User, error) { 886 if s.users == nil { 887 err := s.loadUsers() 888 if err != nil { 889 return nil, err 890 } 891 } 892 return s.users, nil 893 } 894 895 // GetUser doc soon 896 func (s *StateDB) GetUser(address common.Address) (*debrief.User, error) { 897 users, err := s.GetUsers() 898 if err != nil { 899 return nil, err 900 } 901 for _, user := range users { 902 if user.Address == address { 903 return &user, nil 904 } 905 } 906 return nil, nil 907 } 908 909 func (s *StateDB) loadUsers() error { 910 if s.GetCodeSize(debrief.RegisterStoreAddress) == 0 { 911 s.users = make([]debrief.User, 0) 912 return nil 913 } 914 data := s.GetCode(debrief.RegisterStoreAddress) 915 return rlp.DecodeBytes(data, &s.users) 916 } 917 918 func (s *StateDB) saveUsers() error { 919 data, err := rlp.EncodeToBytes(s.users) 920 if err != nil { 921 return err 922 } 923 s.SetCode(debrief.RegisterStoreAddress, data) 924 return nil 925 }