github.com/halybang/go-ethereum@v1.0.5-0.20180325041310-3b262bc1367c/core/state/statedb.go (about) 1 // Copyright 2018 Wanchain Foundation Ltd 2 // Copyright 2014 The go-ethereum Authors 3 // This file is part of the go-ethereum library. 4 // 5 // The go-ethereum library is free software: you can redistribute it and/or modify 6 // it under the terms of the GNU Lesser General Public License as published by 7 // the Free Software Foundation, either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // The go-ethereum library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public License 16 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 17 18 // Package state provides a caching layer atop the Ethereum state trie. 19 package state 20 21 import ( 22 "fmt" 23 "math/big" 24 "sort" 25 "sync" 26 27 "github.com/wanchain/go-wanchain/common" 28 "github.com/wanchain/go-wanchain/core/types" 29 "github.com/wanchain/go-wanchain/crypto" 30 "github.com/wanchain/go-wanchain/log" 31 "github.com/wanchain/go-wanchain/rlp" 32 "github.com/wanchain/go-wanchain/trie" 33 ) 34 35 const ( 36 OTA_ADDR_LEN = 128 37 ) 38 39 type revision struct { 40 id int 41 journalIndex int 42 } 43 44 // StateDBs within the ethereum protocol are used to store anything 45 // within the merkle trie. StateDBs take care of caching and storing 46 // nested states. It's the general query interface to retrieve: 47 // * Contracts 48 // * Accounts 49 type StateDB struct { 50 db Database 51 trie Trie 52 53 // This map holds 'live' objects, which will get modified while processing a state transition. 54 stateObjects map[common.Address]*stateObject 55 stateObjectsDirty map[common.Address]struct{} 56 57 // DB error. 58 // State objects are used by the consensus core and VM which are 59 // unable to deal with database-level errors. Any error that occurs 60 // during a database read is memoized here and will eventually be returned 61 // by StateDB.Commit. 62 dbErr error 63 64 // The refund counter, also used by state transitioning. 65 refund *big.Int 66 67 thash, bhash common.Hash 68 txIndex int 69 logs map[common.Hash][]*types.Log 70 logSize uint 71 72 preimages map[common.Hash][]byte 73 74 // Journal of state modifications. This is the backbone of 75 // Snapshot and RevertToSnapshot. 76 journal journal 77 validRevisions []revision 78 nextRevisionId int 79 80 lock sync.Mutex 81 } 82 83 // Create a new state from a given trie 84 func New(root common.Hash, db Database) (*StateDB, error) { 85 tr, err := db.OpenTrie(root) 86 if err != nil { 87 return nil, err 88 } 89 return &StateDB{ 90 db: db, 91 trie: tr, 92 stateObjects: make(map[common.Address]*stateObject), 93 stateObjectsDirty: make(map[common.Address]struct{}), 94 refund: new(big.Int), 95 logs: make(map[common.Hash][]*types.Log), 96 preimages: make(map[common.Hash][]byte), 97 }, nil 98 } 99 100 // setError remembers the first non-nil error it is called with. 101 func (self *StateDB) setError(err error) { 102 if self.dbErr == nil { 103 self.dbErr = err 104 } 105 } 106 107 func (self *StateDB) Error() error { 108 return self.dbErr 109 } 110 111 // Reset clears out all emphemeral state objects from the state db, but keeps 112 // the underlying state trie to avoid reloading data for the next operations. 113 func (self *StateDB) Reset(root common.Hash) error { 114 tr, err := self.db.OpenTrie(root) 115 if err != nil { 116 return err 117 } 118 self.trie = tr 119 self.stateObjects = make(map[common.Address]*stateObject) 120 self.stateObjectsDirty = make(map[common.Address]struct{}) 121 self.thash = common.Hash{} 122 self.bhash = common.Hash{} 123 self.txIndex = 0 124 self.logs = make(map[common.Hash][]*types.Log) 125 self.logSize = 0 126 self.preimages = make(map[common.Hash][]byte) 127 self.clearJournalAndRefund() 128 return nil 129 } 130 131 func (self *StateDB) AddLog(log *types.Log) { 132 self.journal = append(self.journal, addLogChange{txhash: self.thash}) 133 134 log.TxHash = self.thash 135 log.BlockHash = self.bhash 136 log.TxIndex = uint(self.txIndex) 137 log.Index = self.logSize 138 self.logs[self.thash] = append(self.logs[self.thash], log) 139 self.logSize++ 140 } 141 142 func (self *StateDB) GetLogs(hash common.Hash) []*types.Log { 143 return self.logs[hash] 144 } 145 146 func (self *StateDB) Logs() []*types.Log { 147 var logs []*types.Log 148 for _, lgs := range self.logs { 149 logs = append(logs, lgs...) 150 } 151 return logs 152 } 153 154 // AddPreimage records a SHA3 preimage seen by the VM. 155 func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 156 if _, ok := self.preimages[hash]; !ok { 157 self.journal = append(self.journal, addPreimageChange{hash: hash}) 158 pi := make([]byte, len(preimage)) 159 copy(pi, preimage) 160 self.preimages[hash] = pi 161 } 162 } 163 164 // Preimages returns a list of SHA3 preimages that have been submitted. 165 func (self *StateDB) Preimages() map[common.Hash][]byte { 166 return self.preimages 167 } 168 169 func (self *StateDB) AddRefund(gas *big.Int) { 170 self.journal = append(self.journal, refundChange{prev: new(big.Int).Set(self.refund)}) 171 self.refund.Add(self.refund, gas) 172 } 173 174 // Exist reports whether the given account address exists in the state. 175 // Notably this also returns true for suicided accounts. 176 func (self *StateDB) Exist(addr common.Address) bool { 177 return self.getStateObject(addr) != nil 178 } 179 180 // Empty returns whether the state object is either non-existent 181 // or empty according to the EIP161 specification (balance = nonce = code = 0) 182 func (self *StateDB) Empty(addr common.Address) bool { 183 so := self.getStateObject(addr) 184 return so == nil || so.empty() 185 } 186 187 // Retrieve the balance from the given address or 0 if object not found 188 func (self *StateDB) GetBalance(addr common.Address) *big.Int { 189 stateObject := self.getStateObject(addr) 190 if stateObject != nil { 191 return stateObject.Balance() 192 } 193 return common.Big0 194 } 195 196 func (self *StateDB) GetNonce(addr common.Address) uint64 { 197 stateObject := self.getStateObject(addr) 198 if stateObject != nil { 199 return stateObject.Nonce() 200 } 201 202 return 0 203 } 204 205 func (self *StateDB) GetCode(addr common.Address) []byte { 206 stateObject := self.getStateObject(addr) 207 if stateObject != nil { 208 return stateObject.Code(self.db) 209 } 210 return nil 211 } 212 213 func (self *StateDB) GetCodeSize(addr common.Address) int { 214 stateObject := self.getStateObject(addr) 215 if stateObject == nil { 216 return 0 217 } 218 if stateObject.code != nil { 219 return len(stateObject.code) 220 } 221 size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash())) 222 if err != nil { 223 self.setError(err) 224 } 225 return size 226 } 227 228 func (self *StateDB) GetCodeHash(addr common.Address) common.Hash { 229 stateObject := self.getStateObject(addr) 230 if stateObject == nil { 231 return common.Hash{} 232 } 233 return common.BytesToHash(stateObject.CodeHash()) 234 } 235 236 func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash { 237 stateObject := self.getStateObject(a) 238 if stateObject != nil { 239 return stateObject.GetState(self.db, b) 240 } 241 return common.Hash{} 242 } 243 244 func (self *StateDB) GetStateByteArray(a common.Address, b common.Hash) []byte { 245 stateObject := self.getStateObject(a) 246 if stateObject != nil { 247 return stateObject.GetStateByteArray(self.db, b) 248 } 249 return nil 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(a common.Address) Trie { 255 stateObject := self.getStateObject(a) 256 if stateObject == nil { 257 return nil 258 } 259 cpy := stateObject.deepCopy(self, nil) 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 common.Hash, value common.Hash) { 313 stateObject := self.GetOrNewStateObject(addr) 314 if stateObject != nil { 315 stateObject.SetState(self.db, key, value) 316 } 317 } 318 319 func (self *StateDB) SetStateByteArray(addr common.Address, key common.Hash, value []byte) { 320 stateObject := self.GetOrNewStateObject(addr) 321 if stateObject != nil { 322 stateObject.SetStateByteArray(self.db, key, value) 323 } 324 } 325 326 // Suicide marks the given account as suicided. 327 // This clears the account balance. 328 // 329 // The account's state object is still available until the state is committed, 330 // getStateObject will return a non-nil account after Suicide. 331 func (self *StateDB) Suicide(addr common.Address) bool { 332 stateObject := self.getStateObject(addr) 333 if stateObject == nil { 334 return false 335 } 336 self.journal = append(self.journal, suicideChange{ 337 account: &addr, 338 prev: stateObject.suicided, 339 prevbalance: new(big.Int).Set(stateObject.Balance()), 340 }) 341 stateObject.markSuicided() 342 stateObject.data.Balance = new(big.Int) 343 344 return true 345 } 346 347 // 348 // Setting, updating & deleting state object methods 349 // 350 351 // updateStateObject writes the given object to the trie. 352 func (self *StateDB) updateStateObject(stateObject *stateObject) { 353 addr := stateObject.Address() 354 data, err := rlp.EncodeToBytes(stateObject) 355 if err != nil { 356 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 357 } 358 self.setError(self.trie.TryUpdate(addr[:], data)) 359 } 360 361 // deleteStateObject removes the given object from the state trie. 362 func (self *StateDB) deleteStateObject(stateObject *stateObject) { 363 stateObject.deleted = true 364 addr := stateObject.Address() 365 self.setError(self.trie.TryDelete(addr[:])) 366 } 367 368 // Retrieve a state object given my the address. Returns nil if not found. 369 func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) { 370 // Prefer 'live' objects. 371 if obj := self.stateObjects[addr]; obj != nil { 372 if obj.deleted { 373 return nil 374 } 375 return obj 376 } 377 378 // Load the object from the database. 379 enc, err := self.trie.TryGet(addr[:]) 380 if len(enc) == 0 { 381 self.setError(err) 382 return nil 383 } 384 var data Account 385 if err := rlp.DecodeBytes(enc, &data); err != nil { 386 log.Error("Failed to decode state object", "addr", addr, "err", err) 387 return nil 388 } 389 // Insert into the live set. 390 obj := newObject(self, addr, data, self.MarkStateObjectDirty) 391 self.setStateObject(obj) 392 return obj 393 } 394 395 func (self *StateDB) setStateObject(object *stateObject) { 396 self.stateObjects[object.Address()] = object 397 } 398 399 // Retrieve a state object or create a new state object if nil 400 func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { 401 stateObject := self.getStateObject(addr) 402 if stateObject == nil || stateObject.deleted { 403 stateObject, _ = self.createObject(addr) 404 } 405 return stateObject 406 } 407 408 // MarkStateObjectDirty adds the specified object to the dirty map to avoid costly 409 // state object cache iteration to find a handful of modified ones. 410 func (self *StateDB) MarkStateObjectDirty(addr common.Address) { 411 self.stateObjectsDirty[addr] = struct{}{} 412 } 413 414 // createObject creates a new state object. If there is an existing account with 415 // the given address, it is overwritten and returned as the second return value. 416 func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { 417 prev = self.getStateObject(addr) 418 newobj = newObject(self, addr, Account{}, self.MarkStateObjectDirty) 419 newobj.setNonce(0) // sets the object to dirty 420 if prev == nil { 421 self.journal = append(self.journal, createObjectChange{account: &addr}) 422 } else { 423 self.journal = append(self.journal, resetObjectChange{prev: prev}) 424 } 425 self.setStateObject(newobj) 426 return newobj, prev 427 } 428 429 // CreateAccount explicitly creates a state object. If a state object with the address 430 // already exists the balance is carried over to the new account. 431 // 432 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 433 // a contract does the following: 434 // 435 // 1. sends funds to sha(account ++ (nonce + 1)) 436 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 437 // 438 // Carrying over the balance ensures that Ether doesn't disappear. 439 func (self *StateDB) CreateAccount(addr common.Address) { 440 new, prev := self.createObject(addr) 441 if prev != nil { 442 new.setBalance(prev.data.Balance) 443 } 444 } 445 446 func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { 447 so := db.getStateObject(addr) 448 if so == nil { 449 return 450 } 451 452 // When iterating over the storage check the cache first 453 for h, value := range so.cachedStorage { 454 cb(h, value) 455 } 456 457 it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) 458 for it.Next() { 459 // ignore cached values 460 key := common.BytesToHash(db.trie.GetKey(it.Key)) 461 if _, ok := so.cachedStorage[key]; !ok { 462 cb(key, common.BytesToHash(it.Value)) 463 } 464 } 465 } 466 467 // cb is callback function. cb return true indicating like to continue, return false indicating stop 468 func (db *StateDB) ForEachStorageByteArray(addr common.Address, cb func(key common.Hash, value []byte) bool) { 469 so := db.getStateObject(addr) 470 if so == nil { 471 return 472 } 473 474 // When iterating over the storage check the cache first 475 for h, value := range so.cachedStorageByteArray { 476 if !cb(h, value) { 477 return 478 } 479 } 480 481 it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) 482 for it.Next() { 483 // ignore cached values 484 key := common.BytesToHash(db.trie.GetKey(it.Key)) 485 if _, ok := so.cachedStorage[key]; !ok { 486 if !cb(key, it.Value) { 487 return 488 } 489 } 490 } 491 } 492 493 // Copy creates a deep, independent copy of the state. 494 // Snapshots of the copied state cannot be applied to the copy. 495 func (self *StateDB) Copy() *StateDB { 496 self.lock.Lock() 497 defer self.lock.Unlock() 498 499 // Copy all the basic fields, initialize the memory ones 500 state := &StateDB{ 501 db: self.db, 502 trie: self.trie, 503 stateObjects: make(map[common.Address]*stateObject, len(self.stateObjectsDirty)), 504 stateObjectsDirty: make(map[common.Address]struct{}, len(self.stateObjectsDirty)), 505 refund: new(big.Int).Set(self.refund), 506 logs: make(map[common.Hash][]*types.Log, len(self.logs)), 507 logSize: self.logSize, 508 preimages: make(map[common.Hash][]byte), 509 } 510 // Copy the dirty states, logs, and preimages 511 for addr := range self.stateObjectsDirty { 512 state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty) 513 state.stateObjectsDirty[addr] = struct{}{} 514 } 515 for hash, logs := range self.logs { 516 state.logs[hash] = make([]*types.Log, len(logs)) 517 copy(state.logs[hash], logs) 518 } 519 for hash, preimage := range self.preimages { 520 state.preimages[hash] = preimage 521 } 522 return state 523 } 524 525 // Snapshot returns an identifier for the current revision of the state. 526 func (self *StateDB) Snapshot() int { 527 id := self.nextRevisionId 528 self.nextRevisionId++ 529 self.validRevisions = append(self.validRevisions, revision{id, len(self.journal)}) 530 return id 531 } 532 533 // RevertToSnapshot reverts all state changes made since the given revision. 534 func (self *StateDB) RevertToSnapshot(revid int) { 535 // Find the snapshot in the stack of valid snapshots. 536 idx := sort.Search(len(self.validRevisions), func(i int) bool { 537 return self.validRevisions[i].id >= revid 538 }) 539 if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid { 540 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 541 } 542 snapshot := self.validRevisions[idx].journalIndex 543 544 // Replay the journal to undo changes. 545 for i := len(self.journal) - 1; i >= snapshot; i-- { 546 self.journal[i].undo(self) 547 } 548 self.journal = self.journal[:snapshot] 549 550 // Remove invalidated snapshots from the stack. 551 self.validRevisions = self.validRevisions[:idx] 552 } 553 554 // GetRefund returns the current value of the refund counter. 555 // The return value must not be modified by the caller and will become 556 // invalid at the next call to AddRefund. 557 func (self *StateDB) GetRefund() *big.Int { 558 return self.refund 559 } 560 561 // Finalise finalises the state by removing the self destructed objects 562 // and clears the journal as well as the refunds. 563 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 564 for addr := range s.stateObjectsDirty { 565 stateObject := s.stateObjects[addr] 566 if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { 567 s.deleteStateObject(stateObject) 568 } else { 569 stateObject.updateRoot(s.db) 570 s.updateStateObject(stateObject) 571 } 572 } 573 // Invalidate journal because reverting across transactions is not allowed. 574 s.clearJournalAndRefund() 575 } 576 577 // IntermediateRoot computes the current root hash of the state trie. 578 // It is called in between transactions to get the root hash that 579 // goes into transaction receipts. 580 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 581 s.Finalise(deleteEmptyObjects) 582 return s.trie.Hash() 583 } 584 585 // Prepare sets the current transaction hash and index and block hash which is 586 // used when the EVM emits new state logs. 587 func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) { 588 self.thash = thash 589 self.bhash = bhash 590 self.txIndex = ti 591 } 592 593 // DeleteSuicides flags the suicided objects for deletion so that it 594 // won't be referenced again when called / queried up on. 595 // 596 // DeleteSuicides should not be used for consensus related updates 597 // under any circumstances. 598 func (s *StateDB) DeleteSuicides() { 599 // Reset refund so that any used-gas calculations can use this method. 600 s.clearJournalAndRefund() 601 602 for addr := range s.stateObjectsDirty { 603 stateObject := s.stateObjects[addr] 604 605 // If the object has been removed by a suicide 606 // flag the object as deleted. 607 if stateObject.suicided { 608 stateObject.deleted = true 609 } 610 delete(s.stateObjectsDirty, addr) 611 } 612 } 613 614 func (s *StateDB) clearJournalAndRefund() { 615 s.journal = nil 616 s.validRevisions = s.validRevisions[:0] 617 s.refund = new(big.Int) 618 } 619 620 // CommitTo writes the state to the given database. 621 func (s *StateDB) CommitTo(dbw trie.DatabaseWriter, deleteEmptyObjects bool) (root common.Hash, err error) { 622 defer s.clearJournalAndRefund() 623 624 // Commit objects to the trie. 625 for addr, stateObject := range s.stateObjects { 626 _, isDirty := s.stateObjectsDirty[addr] 627 switch { 628 case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()): 629 // If the object has been removed, don't bother syncing it 630 // and just mark it for deletion in the trie. 631 s.deleteStateObject(stateObject) 632 case isDirty: 633 // Write any contract code associated with the state object 634 if stateObject.code != nil && stateObject.dirtyCode { 635 if err := dbw.Put(stateObject.CodeHash(), stateObject.code); err != nil { 636 return common.Hash{}, err 637 } 638 stateObject.dirtyCode = false 639 } 640 // Write any storage changes in the state object to its storage trie. 641 if err := stateObject.CommitTrie(s.db, dbw); err != nil { 642 return common.Hash{}, err 643 } 644 // Update the object in the main account trie. 645 s.updateStateObject(stateObject) 646 } 647 delete(s.stateObjectsDirty, addr) 648 } 649 // Write trie changes. 650 root, err = s.trie.CommitTo(dbw) 651 log.Debug("Trie cache stats after commit", "misses", trie.CacheMisses(), "unloads", trie.CacheUnloads()) 652 return root, err 653 }