github.com/insight-chain/inb-go@v1.1.3-0.20191221022159-da049980ae38/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 MiningReward, 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 "errors" 22 "fmt" 23 "github.com/insight-chain/inb-go/params" 24 "math/big" 25 "sort" 26 27 "github.com/insight-chain/inb-go/common" 28 "github.com/insight-chain/inb-go/core/types" 29 "github.com/insight-chain/inb-go/crypto" 30 "github.com/insight-chain/inb-go/log" 31 "github.com/insight-chain/inb-go/rlp" 32 "github.com/insight-chain/inb-go/trie" 33 ) 34 35 type revision struct { 36 id int 37 journalIndex int 38 } 39 40 var ( 41 // emptyState is the known hash of an empty state trie entry. 42 emptyState = crypto.Keccak256Hash(nil) 43 44 // emptyCode is the known hash of the empty EVM bytecode. 45 emptyCode = crypto.Keccak256Hash(nil) 46 47 //Resource by zc 48 PrivilegedSateObject *stateObject 49 //Resource by zc 50 ) 51 52 //Resource by zc 53 const ( 54 MasterAccount string = "0x9510000000000000000000000000000000000000" // account record value of circulation 55 MiningReward uint = 110 // account record value of MiningReward 56 AllianceReward uint = 131 // account record value of Alliance 57 MarketingReward uint = 133 // account record value of Marketing 58 SealReward uint = 135 // account record value of Seal 59 TeamReward uint = 150 // account record value of Team 60 61 ) 62 63 //Resource by zc 64 type proofList [][]byte 65 66 //Resource by zc 67 //func (self *StateDB) GetMortgageStateObject() (s *stateObject) { 68 // PrivilegedSateObject = self.GetOrNewStateObject(common.HexToAddress(totalAddress)) 69 // return PrivilegedSateObject 70 //} 71 func (self *StateDB) GetPrivilegedSateObject() (s *stateObject) { 72 73 return self.GetOrNewStateObject(common.HexToAddress(common.MortgageAccount)) 74 } 75 76 //achilles0709 add accounts 77 func (self *StateDB) GetMortgageStateObject() (s *stateObject) { 78 return self.GetOrNewStateObject(common.HexToAddress(common.MortgageAccount)) 79 } 80 81 // GetMortgagePreviousStateObject get last block state of mortgageAccount 82 func (self *StateDB) GetMortgagePreviousStateObject() (s *stateObject) { 83 84 addr := common.HexToAddress(common.MortgageAccount) 85 enc, err := self.trie.TryGet(addr[:]) 86 if len(enc) == 0 || err != nil { 87 return nil 88 } 89 var data Account 90 if err = rlp.DecodeBytes(enc, &data); err != nil { 91 return nil 92 } 93 return newObject(self, addr, data) 94 } 95 96 func (self *StateDB) GetMasterStateObject() (s *stateObject) { 97 return self.GetOrNewStateObject(common.HexToAddress(MasterAccount)) 98 99 } 100 101 //func (self *StateDB) GetStateObject(address common.Address, num *big.Int, variety int) { 102 // newStateObject := self.getStateObject(address) 103 // if variety == mortgageCpu { 104 // newStateObject.MortgageCpu(num) 105 // } else if variety == mortgageNet { 106 // newStateObject.MortgageNet(num) 107 // } else if variety == unMortgageCpu { 108 // newStateObject.UnMortgageCpu(num) 109 // } else if variety == unMortgageNet { 110 // newStateObject.UnMortgageNet(num) 111 // } 112 //} 113 114 //Resource by zc 115 116 func (n *proofList) Put(key []byte, value []byte) error { 117 *n = append(*n, value) 118 return nil 119 } 120 121 // StateDBs within the ethereum protocol are used to store anything 122 // within the merkle trie. StateDBs take care of caching and storing 123 // nested states. It's the general query interface to retrieve: 124 // * Contracts 125 // * Accounts 126 type StateDB struct { 127 db Database 128 trie Trie 129 130 // This map holds 'live' objects, which will get modified while processing a state transition. 131 stateObjects map[common.Address]*stateObject 132 stateObjectsDirty map[common.Address]struct{} 133 134 // DB error. 135 // State objects are used by the consensus core and VM which are 136 // unable to deal with database-level errors. Any error that occurs 137 // during a database read is memoized here and will eventually be returned 138 // by StateDB.Commit. 139 dbErr error 140 141 // The refund counter, also used by state transitioning. 142 refund uint64 143 144 thash, bhash common.Hash 145 txIndex int 146 logs map[common.Hash][]*types.Log 147 logSize uint 148 149 preimages map[common.Hash][]byte 150 151 // Journal of state modifications. This is the backbone of 152 // Snapshot and RevertToSnapshot. 153 journal *journal 154 validRevisions []revision 155 nextRevisionId int 156 } 157 158 // Create a new state from a given trie. 159 func New(root common.Hash, db Database) (*StateDB, error) { 160 tr, err := db.OpenTrie(root) 161 if err != nil { 162 return nil, err 163 } 164 return &StateDB{ 165 db: db, 166 trie: tr, 167 stateObjects: make(map[common.Address]*stateObject), 168 stateObjectsDirty: make(map[common.Address]struct{}), 169 logs: make(map[common.Hash][]*types.Log), 170 preimages: make(map[common.Hash][]byte), 171 journal: newJournal(), 172 }, nil 173 } 174 175 // setError remembers the first non-nil error it is called with. 176 func (self *StateDB) setError(err error) { 177 if self.dbErr == nil { 178 self.dbErr = err 179 } 180 } 181 182 func (self *StateDB) Error() error { 183 return self.dbErr 184 } 185 186 // Reset clears out all ephemeral state objects from the state db, but keeps 187 // the underlying state trie to avoid reloading data for the next operations. 188 func (self *StateDB) Reset(root common.Hash) error { 189 tr, err := self.db.OpenTrie(root) 190 if err != nil { 191 return err 192 } 193 self.trie = tr 194 self.stateObjects = make(map[common.Address]*stateObject) 195 self.stateObjectsDirty = make(map[common.Address]struct{}) 196 self.thash = common.Hash{} 197 self.bhash = common.Hash{} 198 self.txIndex = 0 199 self.logs = make(map[common.Hash][]*types.Log) 200 self.logSize = 0 201 self.preimages = make(map[common.Hash][]byte) 202 self.clearJournalAndRefund() 203 return nil 204 } 205 206 func (self *StateDB) AddLog(log *types.Log) { 207 self.journal.append(addLogChange{txhash: self.thash}) 208 209 log.TxHash = self.thash 210 log.BlockHash = self.bhash 211 log.TxIndex = uint(self.txIndex) 212 log.Index = self.logSize 213 self.logs[self.thash] = append(self.logs[self.thash], log) 214 self.logSize++ 215 } 216 217 func (self *StateDB) GetLogs(hash common.Hash) []*types.Log { 218 return self.logs[hash] 219 } 220 221 func (self *StateDB) Logs() []*types.Log { 222 var logs []*types.Log 223 for _, lgs := range self.logs { 224 logs = append(logs, lgs...) 225 } 226 return logs 227 } 228 229 // AddPreimage records a SHA3 preimage seen by the VM. 230 func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 231 if _, ok := self.preimages[hash]; !ok { 232 self.journal.append(addPreimageChange{hash: hash}) 233 pi := make([]byte, len(preimage)) 234 copy(pi, preimage) 235 self.preimages[hash] = pi 236 } 237 } 238 239 // Preimages returns a list of SHA3 preimages that have been submitted. 240 func (self *StateDB) Preimages() map[common.Hash][]byte { 241 return self.preimages 242 } 243 244 // AddRefund adds gas to the refund counter 245 func (self *StateDB) AddRefund(gas uint64) { 246 self.journal.append(refundChange{prev: self.refund}) 247 self.refund += gas 248 } 249 250 // SubRefund removes gas from the refund counter. 251 // This method will panic if the refund counter goes below zero 252 func (self *StateDB) SubRefund(gas uint64) { 253 self.journal.append(refundChange{prev: self.refund}) 254 if gas > self.refund { 255 panic("Refund counter below zero") 256 } 257 self.refund -= gas 258 } 259 260 // Exist reports whether the given account address exists in the state. 261 // Notably this also returns true for suicided accounts. 262 func (self *StateDB) Exist(addr common.Address) bool { 263 return self.getStateObject(addr) != nil 264 } 265 266 // Empty returns whether the state object is either non-existent 267 // or empty according to the EIP161 specification (balance = nonce = code = 0) 268 func (self *StateDB) Empty(addr common.Address) bool { 269 so := self.getStateObject(addr) 270 return so == nil || so.empty() 271 } 272 273 // Retrieve the balance from the given address or 0 if object not found 274 func (self *StateDB) GetBalance(addr common.Address) *big.Int { 275 stateObject := self.getStateObject(addr) 276 if stateObject != nil { 277 return stateObject.Balance() 278 } 279 return common.Big0 280 } 281 282 func (self *StateDB) GetTotalStaking(addr common.Address) *big.Int { 283 stateObject := self.getStateObject(addr) 284 if stateObject != nil { 285 return stateObject.GetTotalStaking() 286 } 287 return common.Big0 288 } 289 290 func (self *StateDB) GetTotalStakingYear(addr common.Address) *big.Int { 291 stateObject := self.getStateObject(addr) 292 if stateObject != nil { 293 return stateObject.GetTotalStakingYear() 294 } 295 return common.Big0 296 } 297 298 func (self *StateDB) GetUnStaking(addr common.Address) *big.Int { 299 stateObject := self.getStateObject(addr) 300 if stateObject != nil { 301 return stateObject.GetUnStaking() 302 } 303 return common.Big0 304 } 305 306 func (self *StateDB) GetUnStakingHeight(addr common.Address) *big.Int { 307 stateObject := self.getStateObject(addr) 308 if stateObject != nil { 309 return stateObject.GetUnStakingHeight() 310 } 311 return common.Big0 312 } 313 314 //Resource by zc 315 func (self *StateDB) GetNet(addr common.Address) *big.Int { 316 stateObject := self.getStateObject(addr) 317 if stateObject != nil { 318 return stateObject.Net() 319 } 320 return common.Big0 321 } 322 323 //2019.6.28 inb by ghy begin 324 func (self *StateDB) GetAccountInfo(addr common.Address) *Account { 325 stateObject := self.getStateObject(addr) 326 if stateObject != nil { 327 return &stateObject.data 328 } 329 return nil 330 } 331 332 func (c *StateDB) ConvertToNets(value *big.Int) *big.Int { 333 exchangeRatio := c.UnitConvertNet() 334 temp := big.NewInt(1).Div(value, params.TxConfig.WeiOfUseNet) 335 if exchangeRatio == big.NewInt(0) { 336 return big.NewInt(0) 337 } else { 338 if value != nil { 339 return new(big.Int).Mul(exchangeRatio, temp) 340 } 341 return big.NewInt(0) 342 } 343 } 344 345 func (self *StateDB) GetUsedNet(addr common.Address) *big.Int { 346 stateObject := self.getStateObject(addr) 347 if stateObject != nil { 348 return stateObject.UsedNet() 349 } 350 return common.Big0 351 } 352 353 // 354 //func (self *StateDB) GetMortgage(addr common.Address) *big.Int { 355 // stateObject := self.getStateObject(addr) 356 // if stateObject != nil { 357 // return stateObject.MortgageOfRes() 358 // } 359 // return common.Big0 360 //} 361 362 //2019.6.28 inb by ghy end 363 func (self *StateDB) GetStakingValue(addr common.Address) *big.Int { 364 stateObject := self.getStateObject(addr) 365 if stateObject != nil { 366 return stateObject.StakingValue() 367 } 368 return common.Big0 369 } 370 371 func (self *StateDB) GetDate(addr common.Address) *big.Int { 372 stateObject := self.getStateObject(addr) 373 if stateObject != nil { 374 return stateObject.Date() 375 } 376 return common.Big0 377 } 378 379 //Resource by zc 380 func (self *StateDB) GetNonce(addr common.Address) uint64 { 381 stateObject := self.getStateObject(addr) 382 if stateObject != nil { 383 return stateObject.Nonce() 384 } 385 386 return 0 387 } 388 389 func (self *StateDB) GetCode(addr common.Address) []byte { 390 stateObject := self.getStateObject(addr) 391 if stateObject != nil { 392 return stateObject.Code(self.db) 393 } 394 return nil 395 } 396 397 func (self *StateDB) GetCodeSize(addr common.Address) int { 398 stateObject := self.getStateObject(addr) 399 if stateObject == nil { 400 return 0 401 } 402 if stateObject.code != nil { 403 return len(stateObject.code) 404 } 405 size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash())) 406 if err != nil { 407 self.setError(err) 408 } 409 return size 410 } 411 412 func (self *StateDB) GetCodeHash(addr common.Address) common.Hash { 413 stateObject := self.getStateObject(addr) 414 if stateObject == nil { 415 return common.Hash{} 416 } 417 return common.BytesToHash(stateObject.CodeHash()) 418 } 419 420 // GetState retrieves a value from the given account's storage trie. 421 func (self *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { 422 stateObject := self.getStateObject(addr) 423 if stateObject != nil { 424 return stateObject.GetState(self.db, hash) 425 } 426 return common.Hash{} 427 } 428 429 // GetProof returns the MerkleProof for a given Account 430 func (self *StateDB) GetProof(a common.Address) ([][]byte, error) { 431 var proof proofList 432 err := self.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof) 433 return [][]byte(proof), err 434 } 435 436 // GetProof returns the StorageProof for given key 437 func (self *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) { 438 var proof proofList 439 trie := self.StorageTrie(a) 440 if trie == nil { 441 return proof, errors.New("storage trie for requested address does not exist") 442 } 443 err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof) 444 return [][]byte(proof), err 445 } 446 447 // GetCommittedState retrieves a value from the given account's committed storage trie. 448 func (self *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { 449 stateObject := self.getStateObject(addr) 450 if stateObject != nil { 451 return stateObject.GetCommittedState(self.db, hash) 452 } 453 return common.Hash{} 454 } 455 456 // Database retrieves the low level database supporting the lower level trie ops. 457 func (self *StateDB) Database() Database { 458 return self.db 459 } 460 461 // StorageTrie returns the storage trie of an account. 462 // The return value is a copy and is nil for non-existent accounts. 463 func (self *StateDB) StorageTrie(addr common.Address) Trie { 464 stateObject := self.getStateObject(addr) 465 if stateObject == nil { 466 return nil 467 } 468 cpy := stateObject.deepCopy(self) 469 return cpy.updateTrie(self.db) 470 } 471 472 func (self *StateDB) HasSuicided(addr common.Address) bool { 473 stateObject := self.getStateObject(addr) 474 if stateObject != nil { 475 return stateObject.suicided 476 } 477 return false 478 } 479 480 /* 481 * SETTERS 482 */ 483 484 // AddBalance adds amount to the account associated with addr. 485 func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) { 486 stateObject := self.GetOrNewStateObject(addr) 487 if stateObject != nil { 488 stateObject.AddBalance(amount) 489 } 490 } 491 492 func (self *StateDB) AddVoteRecord(addr common.Address, amount *big.Int) { 493 stateObject := self.GetOrNewStateObject(addr) 494 if stateObject != nil { 495 stateObject.AddVoteRecord(amount) 496 } 497 } 498 499 // SubBalance subtracts amount from the account associated with addr. 500 func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) { 501 stateObject := self.GetOrNewStateObject(addr) 502 if stateObject != nil { 503 stateObject.SubBalance(amount) 504 } 505 } 506 507 func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) { 508 stateObject := self.GetOrNewStateObject(addr) 509 if stateObject != nil { 510 stateObject.SetBalance(amount) 511 } 512 } 513 514 //achilles set nets for mortgaging 515 func (self *StateDB) MortgageNet(addr common.Address, amount *big.Int, duration *big.Int, sTime big.Int, hash common.Hash) *big.Int { 516 stateObject := self.GetOrNewStateObject(addr) 517 if stateObject != nil { 518 return stateObject.MortgageNet(amount, duration, sTime, hash) 519 } 520 return nil 521 } 522 523 func (self *StateDB) ResetNet(addr common.Address, update *big.Int) *big.Int { 524 stateObject := self.GetOrNewStateObject(addr) 525 if stateObject != nil { 526 return stateObject.ResetNet(update) 527 } 528 return nil 529 } 530 531 //2019.7.22 inb by ghy begin 532 533 func (self *StateDB) CanReceiveLockedAward(addr common.Address, nonce common.Hash, height *big.Int, consensus types.SpecialConsensus) (err error, value *big.Int, is bool, toAddress common.Address) { 534 //stateObject := self.GetOrNewStateObject(addr) 535 //if stateObject != nil { 536 // for _, v := range consensus.SpecialConsensusAddress { 537 // if v.SpecialType == OnlineMarketing { 538 // err, value, is = stateObject.CanReceiveLockedAward(nonce, height, consensus) 539 // toAddress = v.ToAddress 540 // totalBalance := self.GetBalance(v.ToAddress) 541 // if totalBalance.Cmp(value) != 1 { 542 // return errors.New("there are not enough inb in the online account"), big.NewInt(0), false, common.Address{} 543 // } 544 // return err, value, is, toAddress 545 // } 546 // } 547 //} 548 return errors.New("errors of address"), big.NewInt(0), false, common.Address{} 549 } 550 551 func (self *StateDB) ReceiveLockedAward(addr common.Address, nonce common.Hash, value *big.Int, isAll bool, time *big.Int, toAddress common.Address) { 552 stateObject := self.GetOrNewStateObject(addr) 553 if stateObject != nil { 554 self.SubBalance(toAddress, value) 555 stateObject.ReceiveLockedAward(nonce, value, isAll, time) 556 } 557 } 558 559 func (self *StateDB) CanReceiveVoteAward(addr common.Address, height *big.Int, consensus types.SpecialConsensus) (err error, value *big.Int, toAddress common.Address) { 560 stateObject := self.GetOrNewStateObject(addr) 561 if stateObject != nil { 562 for _, v := range consensus.SpecialConsensusAddress { 563 if v.SpecialType == SealReward { 564 err, value = stateObject.CanReceiveVoteAward(height) 565 toAddress = v.ToAddress 566 totalBalance := self.GetBalance(v.ToAddress) 567 if totalBalance.Cmp(value) != 1 { 568 569 return errors.New("there are not enough inb in the voting account"), big.NewInt(0), common.Address{} 570 } 571 572 return err, value, toAddress 573 } 574 } 575 } 576 return errors.New("errors of address"), big.NewInt(0), common.Address{} 577 } 578 579 func (self *StateDB) ReceiveVoteAward(addr common.Address, value *big.Int, height *big.Int, toAddress common.Address) { 580 stateObject := self.GetOrNewStateObject(addr) 581 582 if stateObject != nil { 583 self.SubBalance(toAddress, value) 584 stateObject.ReceiveVoteAward(value, height) 585 } 586 } 587 588 func (self *StateDB) Vote(addr common.Address, time *big.Int) { 589 stateObject := self.GetOrNewStateObject(addr) 590 if stateObject != nil { 591 stateObject.Vote(time) 592 } 593 } 594 595 //2019.7.22 inb by ghy end 596 597 func (self *StateDB) Receive(addr common.Address, sTime *big.Int) *big.Int { 598 stateObject := self.GetOrNewStateObject(addr) 599 if stateObject != nil { 600 return stateObject.Receive(sTime) 601 } 602 return nil 603 } 604 605 //achilles0722 redeem t+3 606 func (self *StateDB) Redeem(addr common.Address, amount *big.Int, sTime *big.Int) { 607 stateObject := self.GetOrNewStateObject(addr) 608 if stateObject != nil { 609 stateObject.Redeem(amount, sTime) 610 } 611 } 612 613 func (self *StateDB) StoreLength(addr common.Address) int { 614 stateObject := self.GetOrNewStateObject(addr) 615 if stateObject != nil { 616 return stateObject.StoreLength() 617 } 618 return 0 619 } 620 621 //achilles addnet subnet 622 func (self *StateDB) AddNet(addr common.Address, amount *big.Int) { 623 stateObject := self.GetOrNewStateObject(addr) 624 if stateObject != nil { 625 stateObject.AddNet(amount) 626 } 627 } 628 func (self *StateDB) UseRes(addr common.Address, amount *big.Int) { 629 stateObject := self.GetOrNewStateObject(addr) 630 if stateObject != nil { 631 stateObject.UserRes(amount) 632 } 633 } 634 635 func (self *StateDB) SetNonce(addr common.Address, nonce uint64) { 636 stateObject := self.GetOrNewStateObject(addr) 637 if stateObject != nil { 638 stateObject.SetNonce(nonce) 639 } 640 } 641 642 func (self *StateDB) SetCode(addr common.Address, code []byte) { 643 stateObject := self.GetOrNewStateObject(addr) 644 if stateObject != nil { 645 stateObject.SetCode(crypto.Keccak256Hash(code), code) 646 } 647 } 648 649 func (self *StateDB) SetState(addr common.Address, key, value common.Hash) { 650 stateObject := self.GetOrNewStateObject(addr) 651 if stateObject != nil { 652 stateObject.SetState(self.db, key, value) 653 } 654 } 655 656 // Suicide marks the given account as suicided. 657 // This clears the account balance. 658 // 659 // The account's state object is still available until the state is committed, 660 // getStateObject will return a non-nil account after Suicide. 661 func (self *StateDB) Suicide(addr common.Address) bool { 662 stateObject := self.getStateObject(addr) 663 if stateObject == nil { 664 return false 665 } 666 self.journal.append(suicideChange{ 667 account: &addr, 668 prev: stateObject.suicided, 669 prevbalance: new(big.Int).Set(stateObject.Balance()), 670 }) 671 stateObject.markSuicided() 672 stateObject.data.Balance = new(big.Int) 673 674 return true 675 } 676 677 // 678 // Setting, updating & deleting state object methods. 679 // 680 681 // updateStateObject writes the given object to the trie. 682 func (self *StateDB) updateStateObject(stateObject *stateObject) { 683 addr := stateObject.Address() 684 data, err := rlp.EncodeToBytes(stateObject) 685 if err != nil { 686 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 687 } 688 self.setError(self.trie.TryUpdate(addr[:], data)) 689 } 690 691 // deleteStateObject removes the given object from the state trie. 692 func (self *StateDB) deleteStateObject(stateObject *stateObject) { 693 stateObject.deleted = true 694 addr := stateObject.Address() 695 self.setError(self.trie.TryDelete(addr[:])) 696 } 697 698 // Retrieve a state object given by the address. Returns nil if not found. 699 func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) { 700 // Prefer 'live' objects. 701 if obj := self.stateObjects[addr]; obj != nil { 702 if obj.deleted { 703 return nil 704 } 705 return obj 706 } 707 708 // Load the object from the database. 709 enc, err := self.trie.TryGet(addr[:]) 710 if len(enc) == 0 { 711 self.setError(err) 712 return nil 713 } 714 var data Account 715 if err := rlp.DecodeBytes(enc, &data); err != nil { 716 log.Error("Failed to decode state object", "addr", addr, "err", err) 717 return nil 718 } 719 // Insert into the live set. 720 obj := newObject(self, addr, data) 721 self.setStateObject(obj) 722 return obj 723 } 724 725 func (self *StateDB) setStateObject(object *stateObject) { 726 self.stateObjects[object.Address()] = object 727 } 728 729 // Retrieve a state object or create a new state object if nil. 730 func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { 731 stateObject := self.getStateObject(addr) 732 if stateObject == nil || stateObject.deleted { 733 stateObject, _ = self.createObject(addr) 734 } 735 return stateObject 736 } 737 738 // createObject creates a new state object. If there is an existing account with 739 // the given address, it is overwritten and returned as the second return value. 740 func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { 741 prev = self.getStateObject(addr) 742 newobj = newObject(self, addr, Account{}) 743 newobj.setNonce(0) // sets the object to dirty 744 if prev == nil { 745 self.journal.append(createObjectChange{account: &addr}) 746 } else { 747 self.journal.append(resetObjectChange{prev: prev}) 748 } 749 self.setStateObject(newobj) 750 return newobj, prev 751 } 752 753 // CreateAccount explicitly creates a state object. If a state object with the address 754 // already exists the balance is carried over to the new account. 755 // 756 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 757 // a contract does the following: 758 // 759 // 1. sends funds to sha(account ++ (nonce + 1)) 760 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 761 // 762 // Carrying over the balance ensures that Inber doesn't disappear. 763 func (self *StateDB) CreateAccount(addr common.Address) { 764 new, prev := self.createObject(addr) 765 if prev != nil { 766 new.setBalance(prev.data.Balance) 767 } 768 } 769 770 func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { 771 so := db.getStateObject(addr) 772 if so == nil { 773 return 774 } 775 it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) 776 for it.Next() { 777 key := common.BytesToHash(db.trie.GetKey(it.Key)) 778 if value, dirty := so.dirtyStorage[key]; dirty { 779 cb(key, value) 780 continue 781 } 782 cb(key, common.BytesToHash(it.Value)) 783 } 784 } 785 786 // Copy creates a deep, independent copy of the state. 787 // Snapshots of the copied state cannot be applied to the copy. 788 func (self *StateDB) Copy() *StateDB { 789 // Copy all the basic fields, initialize the memory ones 790 state := &StateDB{ 791 db: self.db, 792 trie: self.db.CopyTrie(self.trie), 793 stateObjects: make(map[common.Address]*stateObject, len(self.journal.dirties)), 794 stateObjectsDirty: make(map[common.Address]struct{}, len(self.journal.dirties)), 795 refund: self.refund, 796 logs: make(map[common.Hash][]*types.Log, len(self.logs)), 797 logSize: self.logSize, 798 preimages: make(map[common.Hash][]byte), 799 journal: newJournal(), 800 } 801 // Copy the dirty states, logs, and preimages 802 for addr := range self.journal.dirties { 803 // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527), 804 // and in the Finalise-method, there is a case where an object is in the journal but not 805 // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for 806 // nil 807 if object, exist := self.stateObjects[addr]; exist { 808 state.stateObjects[addr] = object.deepCopy(state) 809 state.stateObjectsDirty[addr] = struct{}{} 810 } 811 } 812 // Above, we don't copy the actual journal. This means that if the copy is copied, the 813 // loop above will be a no-op, since the copy's journal is empty. 814 // Thus, here we iterate over stateObjects, to enable copies of copies 815 for addr := range self.stateObjectsDirty { 816 if _, exist := state.stateObjects[addr]; !exist { 817 state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state) 818 state.stateObjectsDirty[addr] = struct{}{} 819 } 820 } 821 for hash, logs := range self.logs { 822 cpy := make([]*types.Log, len(logs)) 823 for i, l := range logs { 824 cpy[i] = new(types.Log) 825 *cpy[i] = *l 826 } 827 state.logs[hash] = cpy 828 } 829 for hash, preimage := range self.preimages { 830 state.preimages[hash] = preimage 831 } 832 return state 833 } 834 835 // Snapshot returns an identifier for the current revision of the state. 836 func (self *StateDB) Snapshot() int { 837 id := self.nextRevisionId 838 self.nextRevisionId++ 839 self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()}) 840 return id 841 } 842 843 // RevertToSnapshot reverts all state changes made since the given revision. 844 func (self *StateDB) RevertToSnapshot(revid int) { 845 // Find the snapshot in the stack of valid snapshots. 846 idx := sort.Search(len(self.validRevisions), func(i int) bool { 847 return self.validRevisions[i].id >= revid 848 }) 849 if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid { 850 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 851 } 852 snapshot := self.validRevisions[idx].journalIndex 853 854 // Replay the journal to undo changes and remove invalidated snapshots 855 self.journal.revert(self, snapshot) 856 self.validRevisions = self.validRevisions[:idx] 857 } 858 859 // GetRefund returns the current value of the refund counter. 860 func (self *StateDB) GetRefund() uint64 { 861 return self.refund 862 } 863 864 // Finalise finalises the state by removing the self destructed objects 865 // and clears the journal as well as the refunds. 866 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 867 //fmt.Println(s.journal.dirties) 868 for addr := range s.journal.dirties { 869 870 stateObject, exist := s.stateObjects[addr] 871 //fmt.Println(stateObject.address.String()) 872 //fmt.Println(stateObject.data.Balance) 873 if !exist { 874 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 875 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 876 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 877 // it will persist in the journal even though the journal is reverted. In this special circumstance, 878 // it may exist in `s.journal.dirties` but not in `s.stateObjects`. 879 // Thus, we can safely ignore it here 880 continue 881 } 882 883 if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { 884 s.deleteStateObject(stateObject) 885 } else { 886 stateObject.updateRoot(s.db) 887 s.updateStateObject(stateObject) 888 } 889 s.stateObjectsDirty[addr] = struct{}{} 890 } 891 // Invalidate journal because reverting across transactions is not allowed. 892 s.clearJournalAndRefund() 893 } 894 895 // IntermediateRoot computes the current root hash of the state trie. 896 // It is called in between transactions to get the root hash that 897 // goes into transaction receipts. 898 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 899 s.Finalise(deleteEmptyObjects) 900 return s.trie.Hash() 901 } 902 903 // Prepare sets the current transaction hash and index and block hash which is 904 // used when the EVM emits new state logs. 905 func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) { 906 self.thash = thash 907 self.bhash = bhash 908 self.txIndex = ti 909 } 910 911 func (s *StateDB) clearJournalAndRefund() { 912 s.journal = newJournal() 913 s.validRevisions = s.validRevisions[:0] 914 s.refund = 0 915 } 916 917 // Commit writes the state to the underlying in-memory trie database. 918 func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { 919 defer s.clearJournalAndRefund() 920 921 for addr := range s.journal.dirties { 922 s.stateObjectsDirty[addr] = struct{}{} 923 } 924 // Commit objects to the trie. 925 for addr, stateObject := range s.stateObjects { 926 _, isDirty := s.stateObjectsDirty[addr] 927 switch { 928 case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()): 929 // If the object has been removed, don't bother syncing it 930 // and just mark it for deletion in the trie. 931 s.deleteStateObject(stateObject) 932 case isDirty: 933 // Write any contract code associated with the state object 934 if stateObject.code != nil && stateObject.dirtyCode { 935 s.db.TrieDB().InsertBlob(common.BytesToHash(stateObject.CodeHash()), stateObject.code) 936 stateObject.dirtyCode = false 937 } 938 // Write any storage changes in the state object to its storage trie. 939 if err := stateObject.CommitTrie(s.db); err != nil { 940 return common.Hash{}, err 941 } 942 // Update the object in the main account trie. 943 s.updateStateObject(stateObject) 944 } 945 delete(s.stateObjectsDirty, addr) 946 } 947 // Write trie changes. 948 root, err = s.trie.Commit(func(leaf []byte, parent common.Hash) error { 949 var account Account 950 if err := rlp.DecodeBytes(leaf, &account); err != nil { 951 return nil 952 } 953 if account.Root != emptyState { 954 s.db.TrieDB().Reference(account.Root, parent) 955 } 956 code := common.BytesToHash(account.CodeHash) 957 if code != emptyCode { 958 s.db.TrieDB().Reference(code, parent) 959 } 960 return nil 961 }) 962 log.Debug("Trie cache stats after commit", "misses", trie.CacheMisses(), "unloads", trie.CacheUnloads()) 963 return root, err 964 }