github.com/xfond/eth-implementation@v1.8.9-0.20180514135602-f6bc65fc6811/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 "fmt" 22 "math/big" 23 "sort" 24 "sync" 25 26 "github.com/ethereum/go-ethereum/common" 27 "github.com/ethereum/go-ethereum/core/types" 28 "github.com/ethereum/go-ethereum/crypto" 29 "github.com/ethereum/go-ethereum/log" 30 "github.com/ethereum/go-ethereum/rlp" 31 "github.com/ethereum/go-ethereum/trie" 32 ) 33 34 type revision struct { 35 id int 36 journalIndex int 37 } 38 39 var ( 40 // emptyState is the known hash of an empty state trie entry. 41 emptyState = crypto.Keccak256Hash(nil) 42 43 // emptyCode is the known hash of the empty EVM bytecode. 44 emptyCode = crypto.Keccak256Hash(nil) 45 ) 46 47 // StateDBs within the ethereum protocol are used to store anything 48 // within the merkle trie. StateDBs take care of caching and storing 49 // nested states. It's the general query interface to retrieve: 50 // * Contracts 51 // * Accounts 52 type StateDB struct { 53 db Database 54 trie Trie 55 56 // This map holds 'live' objects, which will get modified while processing a state transition. 57 stateObjects map[common.Address]*stateObject 58 stateObjectsDirty map[common.Address]struct{} 59 60 // DB error. 61 // State objects are used by the consensus core and VM which are 62 // unable to deal with database-level errors. Any error that occurs 63 // during a database read is memoized here and will eventually be returned 64 // by StateDB.Commit. 65 dbErr error 66 67 // The refund counter, also used by state transitioning. 68 refund uint64 69 70 thash, bhash common.Hash 71 txIndex int 72 logs map[common.Hash][]*types.Log 73 logSize uint 74 75 preimages map[common.Hash][]byte 76 77 // Journal of state modifications. This is the backbone of 78 // Snapshot and RevertToSnapshot. 79 journal *journal 80 validRevisions []revision 81 nextRevisionId int 82 83 lock sync.Mutex 84 } 85 86 // Create a new state from a given trie. 87 func New(root common.Hash, db Database) (*StateDB, error) { 88 tr, err := db.OpenTrie(root) 89 if err != nil { 90 return nil, err 91 } 92 return &StateDB{ 93 db: db, 94 trie: tr, 95 stateObjects: make(map[common.Address]*stateObject), 96 stateObjectsDirty: make(map[common.Address]struct{}), 97 logs: make(map[common.Hash][]*types.Log), 98 preimages: make(map[common.Hash][]byte), 99 journal: newJournal(), 100 }, nil 101 } 102 103 // setError remembers the first non-nil error it is called with. 104 func (self *StateDB) setError(err error) { 105 if self.dbErr == nil { 106 self.dbErr = err 107 } 108 } 109 110 func (self *StateDB) Error() error { 111 return self.dbErr 112 } 113 114 // Reset clears out all ephemeral state objects from the state db, but keeps 115 // the underlying state trie to avoid reloading data for the next operations. 116 func (self *StateDB) Reset(root common.Hash) error { 117 tr, err := self.db.OpenTrie(root) 118 if err != nil { 119 return err 120 } 121 self.trie = tr 122 self.stateObjects = make(map[common.Address]*stateObject) 123 self.stateObjectsDirty = make(map[common.Address]struct{}) 124 self.thash = common.Hash{} 125 self.bhash = common.Hash{} 126 self.txIndex = 0 127 self.logs = make(map[common.Hash][]*types.Log) 128 self.logSize = 0 129 self.preimages = make(map[common.Hash][]byte) 130 self.clearJournalAndRefund() 131 return nil 132 } 133 134 func (self *StateDB) AddLog(log *types.Log) { 135 self.journal.append(addLogChange{txhash: self.thash}) 136 137 log.TxHash = self.thash 138 log.BlockHash = self.bhash 139 log.TxIndex = uint(self.txIndex) 140 log.Index = self.logSize 141 self.logs[self.thash] = append(self.logs[self.thash], log) 142 self.logSize++ 143 } 144 145 func (self *StateDB) GetLogs(hash common.Hash) []*types.Log { 146 return self.logs[hash] 147 } 148 149 func (self *StateDB) Logs() []*types.Log { 150 var logs []*types.Log 151 for _, lgs := range self.logs { 152 logs = append(logs, lgs...) 153 } 154 return logs 155 } 156 157 // AddPreimage records a SHA3 preimage seen by the VM. 158 func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 159 if _, ok := self.preimages[hash]; !ok { 160 self.journal.append(addPreimageChange{hash: hash}) 161 pi := make([]byte, len(preimage)) 162 copy(pi, preimage) 163 self.preimages[hash] = pi 164 } 165 } 166 167 // Preimages returns a list of SHA3 preimages that have been submitted. 168 func (self *StateDB) Preimages() map[common.Hash][]byte { 169 return self.preimages 170 } 171 172 func (self *StateDB) AddRefund(gas uint64) { 173 self.journal.append(refundChange{prev: self.refund}) 174 self.refund += gas 175 } 176 177 // Exist reports whether the given account address exists in the state. 178 // Notably this also returns true for suicided accounts. 179 func (self *StateDB) Exist(addr common.Address) bool { 180 return self.getStateObject(addr) != nil 181 } 182 183 // Empty returns whether the state object is either non-existent 184 // or empty according to the EIP161 specification (balance = nonce = code = 0) 185 func (self *StateDB) Empty(addr common.Address) bool { 186 so := self.getStateObject(addr) 187 return so == nil || so.empty() 188 } 189 190 // Retrieve the balance from the given address or 0 if object not found 191 func (self *StateDB) GetBalance(addr common.Address) *big.Int { 192 stateObject := self.getStateObject(addr) 193 if stateObject != nil { 194 return stateObject.Balance() 195 } 196 return common.Big0 197 } 198 199 func (self *StateDB) GetNonce(addr common.Address) uint64 { 200 stateObject := self.getStateObject(addr) 201 if stateObject != nil { 202 return stateObject.Nonce() 203 } 204 205 return 0 206 } 207 208 func (self *StateDB) GetCode(addr common.Address) []byte { 209 stateObject := self.getStateObject(addr) 210 if stateObject != nil { 211 return stateObject.Code(self.db) 212 } 213 return nil 214 } 215 216 func (self *StateDB) GetCodeSize(addr common.Address) int { 217 stateObject := self.getStateObject(addr) 218 if stateObject == nil { 219 return 0 220 } 221 if stateObject.code != nil { 222 return len(stateObject.code) 223 } 224 size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash())) 225 if err != nil { 226 self.setError(err) 227 } 228 return size 229 } 230 231 func (self *StateDB) GetCodeHash(addr common.Address) common.Hash { 232 stateObject := self.getStateObject(addr) 233 if stateObject == nil { 234 return common.Hash{} 235 } 236 return common.BytesToHash(stateObject.CodeHash()) 237 } 238 239 func (self *StateDB) GetState(addr common.Address, bhash common.Hash) common.Hash { 240 stateObject := self.getStateObject(addr) 241 if stateObject != nil { 242 return stateObject.GetState(self.db, bhash) 243 } 244 return common.Hash{} 245 } 246 247 // Database retrieves the low level database supporting the lower level trie ops. 248 func (self *StateDB) Database() Database { 249 return self.db 250 } 251 252 // StorageTrie returns the storage trie of an account. 253 // The return value is a copy and is nil for non-existent accounts. 254 func (self *StateDB) StorageTrie(addr common.Address) Trie { 255 stateObject := self.getStateObject(addr) 256 if stateObject == nil { 257 return nil 258 } 259 cpy := stateObject.deepCopy(self) 260 return cpy.updateTrie(self.db) 261 } 262 263 func (self *StateDB) HasSuicided(addr common.Address) bool { 264 stateObject := self.getStateObject(addr) 265 if stateObject != nil { 266 return stateObject.suicided 267 } 268 return false 269 } 270 271 /* 272 * SETTERS 273 */ 274 275 // AddBalance adds amount to the account associated with addr. 276 func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) { 277 stateObject := self.GetOrNewStateObject(addr) 278 if stateObject != nil { 279 stateObject.AddBalance(amount) 280 } 281 } 282 283 // SubBalance subtracts amount from the account associated with addr. 284 func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) { 285 stateObject := self.GetOrNewStateObject(addr) 286 if stateObject != nil { 287 stateObject.SubBalance(amount) 288 } 289 } 290 291 func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) { 292 stateObject := self.GetOrNewStateObject(addr) 293 if stateObject != nil { 294 stateObject.SetBalance(amount) 295 } 296 } 297 298 func (self *StateDB) SetNonce(addr common.Address, nonce uint64) { 299 stateObject := self.GetOrNewStateObject(addr) 300 if stateObject != nil { 301 stateObject.SetNonce(nonce) 302 } 303 } 304 305 func (self *StateDB) SetCode(addr common.Address, code []byte) { 306 stateObject := self.GetOrNewStateObject(addr) 307 if stateObject != nil { 308 stateObject.SetCode(crypto.Keccak256Hash(code), code) 309 } 310 } 311 312 func (self *StateDB) SetState(addr common.Address, key, value common.Hash) { 313 stateObject := self.GetOrNewStateObject(addr) 314 if stateObject != nil { 315 stateObject.SetState(self.db, key, value) 316 } 317 } 318 319 // Suicide marks the given account as suicided. 320 // This clears the account balance. 321 // 322 // The account's state object is still available until the state is committed, 323 // getStateObject will return a non-nil account after Suicide. 324 func (self *StateDB) Suicide(addr common.Address) bool { 325 stateObject := self.getStateObject(addr) 326 if stateObject == nil { 327 return false 328 } 329 self.journal.append(suicideChange{ 330 account: &addr, 331 prev: stateObject.suicided, 332 prevbalance: new(big.Int).Set(stateObject.Balance()), 333 }) 334 stateObject.markSuicided() 335 stateObject.data.Balance = new(big.Int) 336 337 return true 338 } 339 340 // 341 // Setting, updating & deleting state object methods. 342 // 343 344 // updateStateObject writes the given object to the trie. 345 func (self *StateDB) updateStateObject(stateObject *stateObject) { 346 addr := stateObject.Address() 347 data, err := rlp.EncodeToBytes(stateObject) 348 if err != nil { 349 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 350 } 351 self.setError(self.trie.TryUpdate(addr[:], data)) 352 } 353 354 // deleteStateObject removes the given object from the state trie. 355 func (self *StateDB) deleteStateObject(stateObject *stateObject) { 356 stateObject.deleted = true 357 addr := stateObject.Address() 358 self.setError(self.trie.TryDelete(addr[:])) 359 } 360 361 // Retrieve a state object given my the address. Returns nil if not found. 362 func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) { 363 // Prefer 'live' objects. 364 if obj := self.stateObjects[addr]; obj != nil { 365 if obj.deleted { 366 return nil 367 } 368 return obj 369 } 370 371 // Load the object from the database. 372 enc, err := self.trie.TryGet(addr[:]) 373 if len(enc) == 0 { 374 self.setError(err) 375 return nil 376 } 377 var data Account 378 if err := rlp.DecodeBytes(enc, &data); err != nil { 379 log.Error("Failed to decode state object", "addr", addr, "err", err) 380 return nil 381 } 382 // Insert into the live set. 383 obj := newObject(self, addr, data) 384 self.setStateObject(obj) 385 return obj 386 } 387 388 func (self *StateDB) setStateObject(object *stateObject) { 389 self.stateObjects[object.Address()] = object 390 } 391 392 // Retrieve a state object or create a new state object if nil. 393 func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { 394 stateObject := self.getStateObject(addr) 395 if stateObject == nil || stateObject.deleted { 396 stateObject, _ = self.createObject(addr) 397 } 398 return stateObject 399 } 400 401 // createObject creates a new state object. If there is an existing account with 402 // the given address, it is overwritten and returned as the second return value. 403 func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { 404 prev = self.getStateObject(addr) 405 newobj = newObject(self, addr, Account{}) 406 newobj.setNonce(0) // sets the object to dirty 407 if prev == nil { 408 self.journal.append(createObjectChange{account: &addr}) 409 } else { 410 self.journal.append(resetObjectChange{prev: prev}) 411 } 412 self.setStateObject(newobj) 413 return newobj, prev 414 } 415 416 // CreateAccount explicitly creates a state object. If a state object with the address 417 // already exists the balance is carried over to the new account. 418 // 419 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 420 // a contract does the following: 421 // 422 // 1. sends funds to sha(account ++ (nonce + 1)) 423 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 424 // 425 // Carrying over the balance ensures that Ether doesn't disappear. 426 func (self *StateDB) CreateAccount(addr common.Address) { 427 new, prev := self.createObject(addr) 428 if prev != nil { 429 new.setBalance(prev.data.Balance) 430 } 431 } 432 433 func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { 434 so := db.getStateObject(addr) 435 if so == nil { 436 return 437 } 438 439 // When iterating over the storage check the cache first 440 for h, value := range so.cachedStorage { 441 cb(h, value) 442 } 443 444 it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) 445 for it.Next() { 446 // ignore cached values 447 key := common.BytesToHash(db.trie.GetKey(it.Key)) 448 if _, ok := so.cachedStorage[key]; !ok { 449 cb(key, common.BytesToHash(it.Value)) 450 } 451 } 452 } 453 454 // Copy creates a deep, independent copy of the state. 455 // Snapshots of the copied state cannot be applied to the copy. 456 func (self *StateDB) Copy() *StateDB { 457 self.lock.Lock() 458 defer self.lock.Unlock() 459 460 // Copy all the basic fields, initialize the memory ones 461 state := &StateDB{ 462 db: self.db, 463 trie: self.db.CopyTrie(self.trie), 464 stateObjects: make(map[common.Address]*stateObject, len(self.journal.dirties)), 465 stateObjectsDirty: make(map[common.Address]struct{}, len(self.journal.dirties)), 466 refund: self.refund, 467 logs: make(map[common.Hash][]*types.Log, len(self.logs)), 468 logSize: self.logSize, 469 preimages: make(map[common.Hash][]byte), 470 journal: newJournal(), 471 } 472 // Copy the dirty states, logs, and preimages 473 for addr := range self.journal.dirties { 474 // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527), 475 // and in the Finalise-method, there is a case where an object is in the journal but not 476 // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for 477 // nil 478 if object, exist := self.stateObjects[addr]; exist { 479 state.stateObjects[addr] = object.deepCopy(state) 480 state.stateObjectsDirty[addr] = struct{}{} 481 } 482 } 483 // Above, we don't copy the actual journal. This means that if the copy is copied, the 484 // loop above will be a no-op, since the copy's journal is empty. 485 // Thus, here we iterate over stateObjects, to enable copies of copies 486 for addr := range self.stateObjectsDirty { 487 if _, exist := state.stateObjects[addr]; !exist { 488 state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state) 489 state.stateObjectsDirty[addr] = struct{}{} 490 } 491 } 492 493 for hash, logs := range self.logs { 494 state.logs[hash] = make([]*types.Log, len(logs)) 495 copy(state.logs[hash], logs) 496 } 497 for hash, preimage := range self.preimages { 498 state.preimages[hash] = preimage 499 } 500 return state 501 } 502 503 // Snapshot returns an identifier for the current revision of the state. 504 func (self *StateDB) Snapshot() int { 505 id := self.nextRevisionId 506 self.nextRevisionId++ 507 self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()}) 508 return id 509 } 510 511 // RevertToSnapshot reverts all state changes made since the given revision. 512 func (self *StateDB) RevertToSnapshot(revid int) { 513 // Find the snapshot in the stack of valid snapshots. 514 idx := sort.Search(len(self.validRevisions), func(i int) bool { 515 return self.validRevisions[i].id >= revid 516 }) 517 if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid { 518 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 519 } 520 snapshot := self.validRevisions[idx].journalIndex 521 522 // Replay the journal to undo changes and remove invalidated snapshots 523 self.journal.revert(self, snapshot) 524 self.validRevisions = self.validRevisions[:idx] 525 } 526 527 // GetRefund returns the current value of the refund counter. 528 func (self *StateDB) GetRefund() uint64 { 529 return self.refund 530 } 531 532 // Finalise finalises the state by removing the self destructed objects 533 // and clears the journal as well as the refunds. 534 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 535 for addr := range s.journal.dirties { 536 stateObject, exist := s.stateObjects[addr] 537 if !exist { 538 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 539 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 540 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 541 // it will persist in the journal even though the journal is reverted. In this special circumstance, 542 // it may exist in `s.journal.dirties` but not in `s.stateObjects`. 543 // Thus, we can safely ignore it here 544 continue 545 } 546 547 if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { 548 s.deleteStateObject(stateObject) 549 } else { 550 stateObject.updateRoot(s.db) 551 s.updateStateObject(stateObject) 552 } 553 s.stateObjectsDirty[addr] = struct{}{} 554 } 555 // Invalidate journal because reverting across transactions is not allowed. 556 s.clearJournalAndRefund() 557 } 558 559 // IntermediateRoot computes the current root hash of the state trie. 560 // It is called in between transactions to get the root hash that 561 // goes into transaction receipts. 562 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 563 s.Finalise(deleteEmptyObjects) 564 return s.trie.Hash() 565 } 566 567 // Prepare sets the current transaction hash and index and block hash which is 568 // used when the EVM emits new state logs. 569 func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) { 570 self.thash = thash 571 self.bhash = bhash 572 self.txIndex = ti 573 } 574 575 func (s *StateDB) clearJournalAndRefund() { 576 s.journal = newJournal() 577 s.validRevisions = s.validRevisions[:0] 578 s.refund = 0 579 } 580 581 // Commit writes the state to the underlying in-memory trie database. 582 func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { 583 defer s.clearJournalAndRefund() 584 585 for addr := range s.journal.dirties { 586 s.stateObjectsDirty[addr] = struct{}{} 587 } 588 // Commit objects to the trie. 589 for addr, stateObject := range s.stateObjects { 590 _, isDirty := s.stateObjectsDirty[addr] 591 switch { 592 case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()): 593 // If the object has been removed, don't bother syncing it 594 // and just mark it for deletion in the trie. 595 s.deleteStateObject(stateObject) 596 case isDirty: 597 // Write any contract code associated with the state object 598 if stateObject.code != nil && stateObject.dirtyCode { 599 s.db.TrieDB().Insert(common.BytesToHash(stateObject.CodeHash()), stateObject.code) 600 stateObject.dirtyCode = false 601 } 602 // Write any storage changes in the state object to its storage trie. 603 if err := stateObject.CommitTrie(s.db); err != nil { 604 return common.Hash{}, err 605 } 606 // Update the object in the main account trie. 607 s.updateStateObject(stateObject) 608 } 609 delete(s.stateObjectsDirty, addr) 610 } 611 // Write trie changes. 612 root, err = s.trie.Commit(func(leaf []byte, parent common.Hash) error { 613 var account Account 614 if err := rlp.DecodeBytes(leaf, &account); err != nil { 615 return nil 616 } 617 if account.Root != emptyState { 618 s.db.TrieDB().Reference(account.Root, parent) 619 } 620 code := common.BytesToHash(account.CodeHash) 621 if code != emptyCode { 622 s.db.TrieDB().Reference(code, parent) 623 } 624 return nil 625 }) 626 log.Debug("Trie cache stats after commit", "misses", trie.CacheMisses(), "unloads", trie.CacheUnloads()) 627 return root, err 628 }