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