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