github.com/devfans/go-ethereum@v1.5.10-0.20170326212234-7419d0c38291/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/ethdb" 30 "github.com/ethereum/go-ethereum/log" 31 "github.com/ethereum/go-ethereum/rlp" 32 "github.com/ethereum/go-ethereum/trie" 33 lru "github.com/hashicorp/golang-lru" 34 ) 35 36 // Trie cache generation limit after which to evic trie nodes from memory. 37 var MaxTrieCacheGen = uint16(120) 38 39 const ( 40 // Number of past tries to keep. This value is chosen such that 41 // reasonable chain reorg depths will hit an existing trie. 42 maxPastTries = 12 43 44 // Number of codehash->size associations to keep. 45 codeSizeCacheSize = 100000 46 ) 47 48 type revision struct { 49 id int 50 journalIndex int 51 } 52 53 // StateDBs within the ethereum protocol are used to store anything 54 // within the merkle trie. StateDBs take care of caching and storing 55 // nested states. It's the general query interface to retrieve: 56 // * Contracts 57 // * Accounts 58 type StateDB struct { 59 db ethdb.Database 60 trie *trie.SecureTrie 61 pastTries []*trie.SecureTrie 62 codeSizeCache *lru.Cache 63 64 // This map holds 'live' objects, which will get modified while processing a state transition. 65 stateObjects map[common.Address]*stateObject 66 stateObjectsDirty map[common.Address]struct{} 67 68 // The refund counter, also used by state transitioning. 69 refund *big.Int 70 71 thash, bhash common.Hash 72 txIndex int 73 logs map[common.Hash][]*types.Log 74 logSize uint 75 76 preimages map[common.Hash][]byte 77 78 // Journal of state modifications. This is the backbone of 79 // Snapshot and RevertToSnapshot. 80 journal journal 81 validRevisions []revision 82 nextRevisionId int 83 84 lock sync.Mutex 85 } 86 87 // Create a new state from a given trie 88 func New(root common.Hash, db ethdb.Database) (*StateDB, error) { 89 tr, err := trie.NewSecure(root, db, MaxTrieCacheGen) 90 if err != nil { 91 return nil, err 92 } 93 csc, _ := lru.New(codeSizeCacheSize) 94 return &StateDB{ 95 db: db, 96 trie: tr, 97 codeSizeCache: csc, 98 stateObjects: make(map[common.Address]*stateObject), 99 stateObjectsDirty: make(map[common.Address]struct{}), 100 refund: new(big.Int), 101 logs: make(map[common.Hash][]*types.Log), 102 preimages: make(map[common.Hash][]byte), 103 }, nil 104 } 105 106 // New creates a new statedb by reusing any journalled tries to avoid costly 107 // disk io. 108 func (self *StateDB) New(root common.Hash) (*StateDB, error) { 109 self.lock.Lock() 110 defer self.lock.Unlock() 111 112 tr, err := self.openTrie(root) 113 if err != nil { 114 return nil, err 115 } 116 return &StateDB{ 117 db: self.db, 118 trie: tr, 119 codeSizeCache: self.codeSizeCache, 120 stateObjects: make(map[common.Address]*stateObject), 121 stateObjectsDirty: make(map[common.Address]struct{}), 122 refund: new(big.Int), 123 logs: make(map[common.Hash][]*types.Log), 124 preimages: make(map[common.Hash][]byte), 125 }, nil 126 } 127 128 // Reset clears out all emphemeral state objects from the state db, but keeps 129 // the underlying state trie to avoid reloading data for the next operations. 130 func (self *StateDB) Reset(root common.Hash) error { 131 self.lock.Lock() 132 defer self.lock.Unlock() 133 134 tr, err := self.openTrie(root) 135 if err != nil { 136 return err 137 } 138 self.trie = tr 139 self.stateObjects = make(map[common.Address]*stateObject) 140 self.stateObjectsDirty = make(map[common.Address]struct{}) 141 self.thash = common.Hash{} 142 self.bhash = common.Hash{} 143 self.txIndex = 0 144 self.logs = make(map[common.Hash][]*types.Log) 145 self.logSize = 0 146 self.preimages = make(map[common.Hash][]byte) 147 self.clearJournalAndRefund() 148 149 return nil 150 } 151 152 // openTrie creates a trie. It uses an existing trie if one is available 153 // from the journal if available. 154 func (self *StateDB) openTrie(root common.Hash) (*trie.SecureTrie, error) { 155 for i := len(self.pastTries) - 1; i >= 0; i-- { 156 if self.pastTries[i].Hash() == root { 157 tr := *self.pastTries[i] 158 return &tr, nil 159 } 160 } 161 return trie.NewSecure(root, self.db, MaxTrieCacheGen) 162 } 163 164 func (self *StateDB) pushTrie(t *trie.SecureTrie) { 165 self.lock.Lock() 166 defer self.lock.Unlock() 167 168 if len(self.pastTries) >= maxPastTries { 169 copy(self.pastTries, self.pastTries[1:]) 170 self.pastTries[len(self.pastTries)-1] = t 171 } else { 172 self.pastTries = append(self.pastTries, t) 173 } 174 } 175 176 func (self *StateDB) StartRecord(thash, bhash common.Hash, ti int) { 177 self.thash = thash 178 self.bhash = bhash 179 self.txIndex = ti 180 } 181 182 func (self *StateDB) AddLog(log *types.Log) { 183 self.journal = append(self.journal, addLogChange{txhash: self.thash}) 184 185 log.TxHash = self.thash 186 log.BlockHash = self.bhash 187 log.TxIndex = uint(self.txIndex) 188 log.Index = self.logSize 189 self.logs[self.thash] = append(self.logs[self.thash], log) 190 self.logSize++ 191 } 192 193 func (self *StateDB) GetLogs(hash common.Hash) []*types.Log { 194 return self.logs[hash] 195 } 196 197 func (self *StateDB) Logs() []*types.Log { 198 var logs []*types.Log 199 for _, lgs := range self.logs { 200 logs = append(logs, lgs...) 201 } 202 return logs 203 } 204 205 // AddPreimage records a SHA3 preimage seen by the VM. 206 func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 207 if _, ok := self.preimages[hash]; !ok { 208 self.journal = append(self.journal, addPreimageChange{hash: hash}) 209 pi := make([]byte, len(preimage)) 210 copy(pi, preimage) 211 self.preimages[hash] = pi 212 } 213 } 214 215 // Preimages returns a list of SHA3 preimages that have been submitted. 216 func (self *StateDB) Preimages() map[common.Hash][]byte { 217 return self.preimages 218 } 219 220 func (self *StateDB) AddRefund(gas *big.Int) { 221 self.journal = append(self.journal, refundChange{prev: new(big.Int).Set(self.refund)}) 222 self.refund.Add(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) GetCode(addr common.Address) []byte { 257 stateObject := self.getStateObject(addr) 258 if stateObject != nil { 259 code := stateObject.Code(self.db) 260 key := common.BytesToHash(stateObject.CodeHash()) 261 self.codeSizeCache.Add(key, len(code)) 262 return code 263 } 264 return nil 265 } 266 267 func (self *StateDB) GetCodeSize(addr common.Address) int { 268 stateObject := self.getStateObject(addr) 269 if stateObject == nil { 270 return 0 271 } 272 key := common.BytesToHash(stateObject.CodeHash()) 273 if cached, ok := self.codeSizeCache.Get(key); ok { 274 return cached.(int) 275 } 276 size := len(stateObject.Code(self.db)) 277 if stateObject.dbErr == nil { 278 self.codeSizeCache.Add(key, size) 279 } 280 return size 281 } 282 283 func (self *StateDB) GetCodeHash(addr common.Address) common.Hash { 284 stateObject := self.getStateObject(addr) 285 if stateObject == nil { 286 return common.Hash{} 287 } 288 return common.BytesToHash(stateObject.CodeHash()) 289 } 290 291 func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash { 292 stateObject := self.getStateObject(a) 293 if stateObject != nil { 294 return stateObject.GetState(self.db, b) 295 } 296 return common.Hash{} 297 } 298 299 func (self *StateDB) HasSuicided(addr common.Address) bool { 300 stateObject := self.getStateObject(addr) 301 if stateObject != nil { 302 return stateObject.suicided 303 } 304 return false 305 } 306 307 /* 308 * SETTERS 309 */ 310 311 // AddBalance adds amount to the account associated with addr 312 func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) { 313 stateObject := self.GetOrNewStateObject(addr) 314 if stateObject != nil { 315 stateObject.AddBalance(amount) 316 } 317 } 318 319 // SubBalance subtracts amount from the account associated with addr 320 func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) { 321 stateObject := self.GetOrNewStateObject(addr) 322 if stateObject != nil { 323 stateObject.SubBalance(amount) 324 } 325 } 326 327 func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) { 328 stateObject := self.GetOrNewStateObject(addr) 329 if stateObject != nil { 330 stateObject.SetBalance(amount) 331 } 332 } 333 334 func (self *StateDB) SetNonce(addr common.Address, nonce uint64) { 335 stateObject := self.GetOrNewStateObject(addr) 336 if stateObject != nil { 337 stateObject.SetNonce(nonce) 338 } 339 } 340 341 func (self *StateDB) SetCode(addr common.Address, code []byte) { 342 stateObject := self.GetOrNewStateObject(addr) 343 if stateObject != nil { 344 stateObject.SetCode(crypto.Keccak256Hash(code), code) 345 } 346 } 347 348 func (self *StateDB) SetState(addr common.Address, key common.Hash, value common.Hash) { 349 stateObject := self.GetOrNewStateObject(addr) 350 if stateObject != nil { 351 stateObject.SetState(self.db, key, value) 352 } 353 } 354 355 // Suicide marks the given account as suicided. 356 // This clears the account balance. 357 // 358 // The account's state object is still available until the state is committed, 359 // getStateObject will return a non-nil account after Suicide. 360 func (self *StateDB) Suicide(addr common.Address) bool { 361 stateObject := self.getStateObject(addr) 362 if stateObject == nil { 363 return false 364 } 365 self.journal = append(self.journal, suicideChange{ 366 account: &addr, 367 prev: stateObject.suicided, 368 prevbalance: new(big.Int).Set(stateObject.Balance()), 369 }) 370 stateObject.markSuicided() 371 stateObject.data.Balance = new(big.Int) 372 return true 373 } 374 375 // 376 // Setting, updating & deleting state object methods 377 // 378 379 // updateStateObject writes the given object to the trie. 380 func (self *StateDB) updateStateObject(stateObject *stateObject) { 381 addr := stateObject.Address() 382 data, err := rlp.EncodeToBytes(stateObject) 383 if err != nil { 384 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 385 } 386 self.trie.Update(addr[:], data) 387 } 388 389 // deleteStateObject removes the given object from the state trie. 390 func (self *StateDB) deleteStateObject(stateObject *stateObject) { 391 stateObject.deleted = true 392 addr := stateObject.Address() 393 self.trie.Delete(addr[:]) 394 } 395 396 // Retrieve a state object given my the address. Returns nil if not found. 397 func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) { 398 // Prefer 'live' objects. 399 if obj := self.stateObjects[addr]; obj != nil { 400 if obj.deleted { 401 return nil 402 } 403 return obj 404 } 405 406 // Load the object from the database. 407 enc := self.trie.Get(addr[:]) 408 if len(enc) == 0 { 409 return nil 410 } 411 var data Account 412 if err := rlp.DecodeBytes(enc, &data); err != nil { 413 log.Error("Failed to decode state object", "addr", addr, "err", err) 414 return nil 415 } 416 // Insert into the live set. 417 obj := newObject(self, addr, data, self.MarkStateObjectDirty) 418 self.setStateObject(obj) 419 return obj 420 } 421 422 func (self *StateDB) setStateObject(object *stateObject) { 423 self.stateObjects[object.Address()] = object 424 } 425 426 // Retrieve a state object or create a new state object if nil 427 func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { 428 stateObject := self.getStateObject(addr) 429 if stateObject == nil || stateObject.deleted { 430 stateObject, _ = self.createObject(addr) 431 } 432 return stateObject 433 } 434 435 // MarkStateObjectDirty adds the specified object to the dirty map to avoid costly 436 // state object cache iteration to find a handful of modified ones. 437 func (self *StateDB) MarkStateObjectDirty(addr common.Address) { 438 self.stateObjectsDirty[addr] = struct{}{} 439 } 440 441 // createObject creates a new state object. If there is an existing account with 442 // the given address, it is overwritten and returned as the second return value. 443 func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { 444 prev = self.getStateObject(addr) 445 newobj = newObject(self, addr, Account{}, self.MarkStateObjectDirty) 446 newobj.setNonce(0) // sets the object to dirty 447 if prev == nil { 448 self.journal = append(self.journal, createObjectChange{account: &addr}) 449 } else { 450 self.journal = append(self.journal, resetObjectChange{prev: prev}) 451 } 452 self.setStateObject(newobj) 453 return newobj, prev 454 } 455 456 // CreateAccount explicitly creates a state object. If a state object with the address 457 // already exists the balance is carried over to the new account. 458 // 459 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 460 // a contract does the following: 461 // 462 // 1. sends funds to sha(account ++ (nonce + 1)) 463 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 464 // 465 // Carrying over the balance ensures that Ether doesn't disappear. 466 func (self *StateDB) CreateAccount(addr common.Address) { 467 new, prev := self.createObject(addr) 468 if prev != nil { 469 new.setBalance(prev.data.Balance) 470 } 471 } 472 473 func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { 474 so := db.getStateObject(addr) 475 if so == nil { 476 return 477 } 478 479 // When iterating over the storage check the cache first 480 for h, value := range so.cachedStorage { 481 cb(h, value) 482 } 483 484 it := so.getTrie(db.db).Iterator() 485 for it.Next() { 486 // ignore cached values 487 key := common.BytesToHash(db.trie.GetKey(it.Key)) 488 if _, ok := so.cachedStorage[key]; !ok { 489 cb(key, common.BytesToHash(it.Value)) 490 } 491 } 492 } 493 494 // Copy creates a deep, independent copy of the state. 495 // Snapshots of the copied state cannot be applied to the copy. 496 func (self *StateDB) Copy() *StateDB { 497 self.lock.Lock() 498 defer self.lock.Unlock() 499 500 // Copy all the basic fields, initialize the memory ones 501 state := &StateDB{ 502 db: self.db, 503 trie: self.trie, 504 pastTries: self.pastTries, 505 codeSizeCache: self.codeSizeCache, 506 stateObjects: make(map[common.Address]*stateObject, len(self.stateObjectsDirty)), 507 stateObjectsDirty: make(map[common.Address]struct{}, len(self.stateObjectsDirty)), 508 refund: new(big.Int).Set(self.refund), 509 logs: make(map[common.Hash][]*types.Log, len(self.logs)), 510 logSize: self.logSize, 511 preimages: make(map[common.Hash][]byte), 512 } 513 // Copy the dirty states, logs, and preimages 514 for addr := range self.stateObjectsDirty { 515 state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty) 516 state.stateObjectsDirty[addr] = struct{}{} 517 } 518 for hash, logs := range self.logs { 519 state.logs[hash] = make([]*types.Log, len(logs)) 520 copy(state.logs[hash], logs) 521 } 522 for hash, preimage := range self.preimages { 523 state.preimages[hash] = preimage 524 } 525 return state 526 } 527 528 // Snapshot returns an identifier for the current revision of the state. 529 func (self *StateDB) Snapshot() int { 530 id := self.nextRevisionId 531 self.nextRevisionId++ 532 self.validRevisions = append(self.validRevisions, revision{id, len(self.journal)}) 533 return id 534 } 535 536 // RevertToSnapshot reverts all state changes made since the given revision. 537 func (self *StateDB) RevertToSnapshot(revid int) { 538 // Find the snapshot in the stack of valid snapshots. 539 idx := sort.Search(len(self.validRevisions), func(i int) bool { 540 return self.validRevisions[i].id >= revid 541 }) 542 if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid { 543 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 544 } 545 snapshot := self.validRevisions[idx].journalIndex 546 547 // Replay the journal to undo changes. 548 for i := len(self.journal) - 1; i >= snapshot; i-- { 549 self.journal[i].undo(self) 550 } 551 self.journal = self.journal[:snapshot] 552 553 // Remove invalidated snapshots from the stack. 554 self.validRevisions = self.validRevisions[:idx] 555 } 556 557 // GetRefund returns the current value of the refund counter. 558 // The return value must not be modified by the caller and will become 559 // invalid at the next call to AddRefund. 560 func (self *StateDB) GetRefund() *big.Int { 561 return self.refund 562 } 563 564 // IntermediateRoot computes the current root hash of the state trie. 565 // It is called in between transactions to get the root hash that 566 // goes into transaction receipts. 567 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 568 for addr := range s.stateObjectsDirty { 569 stateObject := s.stateObjects[addr] 570 if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { 571 s.deleteStateObject(stateObject) 572 } else { 573 stateObject.updateRoot(s.db) 574 s.updateStateObject(stateObject) 575 } 576 } 577 // Invalidate journal because reverting across transactions is not allowed. 578 s.clearJournalAndRefund() 579 return s.trie.Hash() 580 } 581 582 // DeleteSuicides flags the suicided objects for deletion so that it 583 // won't be referenced again when called / queried up on. 584 // 585 // DeleteSuicides should not be used for consensus related updates 586 // under any circumstances. 587 func (s *StateDB) DeleteSuicides() { 588 // Reset refund so that any used-gas calculations can use this method. 589 s.clearJournalAndRefund() 590 591 for addr := range s.stateObjectsDirty { 592 stateObject := s.stateObjects[addr] 593 594 // If the object has been removed by a suicide 595 // flag the object as deleted. 596 if stateObject.suicided { 597 stateObject.deleted = true 598 } 599 delete(s.stateObjectsDirty, addr) 600 } 601 } 602 603 // Commit commits all state changes to the database. 604 func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { 605 root, batch := s.CommitBatch(deleteEmptyObjects) 606 return root, batch.Write() 607 } 608 609 // CommitBatch commits all state changes to a write batch but does not 610 // execute the batch. It is used to validate state changes against 611 // the root hash stored in a block. 612 func (s *StateDB) CommitBatch(deleteEmptyObjects bool) (root common.Hash, batch ethdb.Batch) { 613 batch = s.db.NewBatch() 614 root, _ = s.CommitTo(batch, deleteEmptyObjects) 615 616 log.Debug("Trie cache stats after commit", "misses", trie.CacheMisses(), "unloads", trie.CacheUnloads()) 617 return root, batch 618 } 619 620 func (s *StateDB) clearJournalAndRefund() { 621 s.journal = nil 622 s.validRevisions = s.validRevisions[:0] 623 s.refund = new(big.Int) 624 } 625 626 // CommitTo writes the state to the given database. 627 func (s *StateDB) CommitTo(dbw trie.DatabaseWriter, deleteEmptyObjects bool) (root common.Hash, err error) { 628 defer s.clearJournalAndRefund() 629 630 // Commit objects to the trie. 631 for addr, stateObject := range s.stateObjects { 632 _, isDirty := s.stateObjectsDirty[addr] 633 switch { 634 case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()): 635 // If the object has been removed, don't bother syncing it 636 // and just mark it for deletion in the trie. 637 s.deleteStateObject(stateObject) 638 case isDirty: 639 // Write any contract code associated with the state object 640 if stateObject.code != nil && stateObject.dirtyCode { 641 if err := dbw.Put(stateObject.CodeHash(), stateObject.code); err != nil { 642 return common.Hash{}, err 643 } 644 stateObject.dirtyCode = false 645 } 646 // Write any storage changes in the state object to its storage trie. 647 if err := stateObject.CommitTrie(s.db, dbw); err != nil { 648 return common.Hash{}, err 649 } 650 // Update the object in the main account trie. 651 s.updateStateObject(stateObject) 652 } 653 delete(s.stateObjectsDirty, addr) 654 } 655 // Write trie changes. 656 root, err = s.trie.CommitTo(dbw) 657 if err == nil { 658 s.pushTrie(s.trie) 659 } 660 return root, err 661 }