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