github.com/fxsjy/go-ethereum@v1.8.4-0.20180410143526-2e247705cd27/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 state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state) 475 state.stateObjectsDirty[addr] = struct{}{} 476 } 477 for hash, logs := range self.logs { 478 state.logs[hash] = make([]*types.Log, len(logs)) 479 copy(state.logs[hash], logs) 480 } 481 for hash, preimage := range self.preimages { 482 state.preimages[hash] = preimage 483 } 484 return state 485 } 486 487 // Snapshot returns an identifier for the current revision of the state. 488 func (self *StateDB) Snapshot() int { 489 id := self.nextRevisionId 490 self.nextRevisionId++ 491 self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()}) 492 return id 493 } 494 495 // RevertToSnapshot reverts all state changes made since the given revision. 496 func (self *StateDB) RevertToSnapshot(revid int) { 497 // Find the snapshot in the stack of valid snapshots. 498 idx := sort.Search(len(self.validRevisions), func(i int) bool { 499 return self.validRevisions[i].id >= revid 500 }) 501 if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid { 502 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 503 } 504 snapshot := self.validRevisions[idx].journalIndex 505 506 // Replay the journal to undo changes and remove invalidated snapshots 507 self.journal.revert(self, snapshot) 508 self.validRevisions = self.validRevisions[:idx] 509 } 510 511 // GetRefund returns the current value of the refund counter. 512 func (self *StateDB) GetRefund() uint64 { 513 return self.refund 514 } 515 516 // Finalise finalises the state by removing the self destructed objects 517 // and clears the journal as well as the refunds. 518 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 519 for addr := range s.journal.dirties { 520 stateObject, exist := s.stateObjects[addr] 521 if !exist { 522 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 523 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 524 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 525 // it will persist in the journal even though the journal is reverted. In this special circumstance, 526 // it may exist in `s.journal.dirties` but not in `s.stateObjects`. 527 // Thus, we can safely ignore it here 528 continue 529 } 530 531 if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { 532 s.deleteStateObject(stateObject) 533 } else { 534 stateObject.updateRoot(s.db) 535 s.updateStateObject(stateObject) 536 } 537 s.stateObjectsDirty[addr] = struct{}{} 538 } 539 // Invalidate journal because reverting across transactions is not allowed. 540 s.clearJournalAndRefund() 541 } 542 543 // IntermediateRoot computes the current root hash of the state trie. 544 // It is called in between transactions to get the root hash that 545 // goes into transaction receipts. 546 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 547 s.Finalise(deleteEmptyObjects) 548 return s.trie.Hash() 549 } 550 551 // Prepare sets the current transaction hash and index and block hash which is 552 // used when the EVM emits new state logs. 553 func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) { 554 self.thash = thash 555 self.bhash = bhash 556 self.txIndex = ti 557 } 558 559 // DeleteSuicides flags the suicided objects for deletion so that it 560 // won't be referenced again when called / queried up on. 561 // 562 // DeleteSuicides should not be used for consensus related updates 563 // under any circumstances. 564 func (s *StateDB) DeleteSuicides() { 565 // Reset refund so that any used-gas calculations can use this method. 566 s.clearJournalAndRefund() 567 568 for addr := range s.stateObjectsDirty { 569 stateObject := s.stateObjects[addr] 570 571 // If the object has been removed by a suicide 572 // flag the object as deleted. 573 if stateObject.suicided { 574 stateObject.deleted = true 575 } 576 delete(s.stateObjectsDirty, addr) 577 } 578 } 579 580 func (s *StateDB) clearJournalAndRefund() { 581 s.journal = newJournal() 582 s.validRevisions = s.validRevisions[:0] 583 s.refund = 0 584 } 585 586 // Commit writes the state to the underlying in-memory trie database. 587 func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { 588 defer s.clearJournalAndRefund() 589 590 for addr := range s.journal.dirties { 591 s.stateObjectsDirty[addr] = struct{}{} 592 } 593 // Commit objects to the trie. 594 for addr, stateObject := range s.stateObjects { 595 _, isDirty := s.stateObjectsDirty[addr] 596 switch { 597 case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()): 598 // If the object has been removed, don't bother syncing it 599 // and just mark it for deletion in the trie. 600 s.deleteStateObject(stateObject) 601 case isDirty: 602 // Write any contract code associated with the state object 603 if stateObject.code != nil && stateObject.dirtyCode { 604 s.db.TrieDB().Insert(common.BytesToHash(stateObject.CodeHash()), stateObject.code) 605 stateObject.dirtyCode = false 606 } 607 // Write any storage changes in the state object to its storage trie. 608 if err := stateObject.CommitTrie(s.db); err != nil { 609 return common.Hash{}, err 610 } 611 // Update the object in the main account trie. 612 s.updateStateObject(stateObject) 613 } 614 delete(s.stateObjectsDirty, addr) 615 } 616 // Write trie changes. 617 root, err = s.trie.Commit(func(leaf []byte, parent common.Hash) error { 618 var account Account 619 if err := rlp.DecodeBytes(leaf, &account); err != nil { 620 return nil 621 } 622 if account.Root != emptyState { 623 s.db.TrieDB().Reference(account.Root, parent) 624 } 625 code := common.BytesToHash(account.CodeHash) 626 if code != emptyCode { 627 s.db.TrieDB().Reference(code, parent) 628 } 629 return nil 630 }) 631 log.Debug("Trie cache stats after commit", "misses", trie.CacheMisses(), "unloads", trie.CacheUnloads()) 632 return root, err 633 }