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