github.com/digdeepmining/go-atheios@v1.5.13-0.20180902133602-d5687a2e6f43/core/state/statedb.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 // Package state provides a caching layer atop the Ethereum state trie. 18 package state 19 20 import ( 21 "fmt" 22 "math/big" 23 "sort" 24 "sync" 25 26 lru "github.com/hashicorp/golang-lru" 27 "github.com/atheioschain/go-atheios/common" 28 "github.com/atheioschain/go-atheios/core/types" 29 "github.com/atheioschain/go-atheios/core/vm" 30 "github.com/atheioschain/go-atheios/crypto" 31 "github.com/atheioschain/go-atheios/ethdb" 32 "github.com/atheioschain/go-atheios/logger" 33 "github.com/atheioschain/go-atheios/logger/glog" 34 "github.com/atheioschain/go-atheios/rlp" 35 "github.com/atheioschain/go-atheios/trie" 36 ) 37 38 // Trie cache generation limit after which to evic trie nodes from memory. 39 var MaxTrieCacheGen = uint16(120) 40 41 const ( 42 // Number of past tries to keep. This value is chosen such that 43 // reasonable chain reorg depths will hit an existing trie. 44 maxPastTries = 12 45 46 // Number of codehash->size associations to keep. 47 codeSizeCacheSize = 100000 48 ) 49 50 type revision struct { 51 id int 52 journalIndex int 53 } 54 55 // StateDBs within the atheios protocol are used to store anything 56 // within the merkle trie. StateDBs take care of caching and storing 57 // nested states. It's the general query interface to retrieve: 58 // * Contracts 59 // * Accounts 60 type StateDB struct { 61 db ethdb.Database 62 trie *trie.SecureTrie 63 pastTries []*trie.SecureTrie 64 codeSizeCache *lru.Cache 65 66 // This map holds 'live' objects, which will get modified while processing a state transition. 67 stateObjects map[common.Address]*StateObject 68 stateObjectsDirty map[common.Address]struct{} 69 70 // The refund counter, also used by state transitioning. 71 refund *big.Int 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 ethdb.Database) (*StateDB, error) { 91 tr, err := trie.NewSecure(root, db, MaxTrieCacheGen) 92 if err != nil { 93 return nil, err 94 } 95 csc, _ := lru.New(codeSizeCacheSize) 96 return &StateDB{ 97 db: db, 98 trie: tr, 99 codeSizeCache: csc, 100 stateObjects: make(map[common.Address]*StateObject), 101 stateObjectsDirty: make(map[common.Address]struct{}), 102 refund: new(big.Int), 103 logs: make(map[common.Hash][]*types.Log), 104 preimages: make(map[common.Hash][]byte), 105 }, nil 106 } 107 108 // New creates a new statedb by reusing any journalled tries to avoid costly 109 // disk io. 110 func (self *StateDB) New(root common.Hash) (*StateDB, error) { 111 self.lock.Lock() 112 defer self.lock.Unlock() 113 114 tr, err := self.openTrie(root) 115 if err != nil { 116 return nil, err 117 } 118 return &StateDB{ 119 db: self.db, 120 trie: tr, 121 codeSizeCache: self.codeSizeCache, 122 stateObjects: make(map[common.Address]*StateObject), 123 stateObjectsDirty: make(map[common.Address]struct{}), 124 refund: new(big.Int), 125 logs: make(map[common.Hash][]*types.Log), 126 preimages: make(map[common.Hash][]byte), 127 }, nil 128 } 129 130 // Reset clears out all emphemeral state objects from the state db, but keeps 131 // the underlying state trie to avoid reloading data for the next operations. 132 func (self *StateDB) Reset(root common.Hash) error { 133 self.lock.Lock() 134 defer self.lock.Unlock() 135 136 tr, err := self.openTrie(root) 137 if err != nil { 138 return err 139 } 140 self.trie = tr 141 self.stateObjects = make(map[common.Address]*StateObject) 142 self.stateObjectsDirty = make(map[common.Address]struct{}) 143 self.thash = common.Hash{} 144 self.bhash = common.Hash{} 145 self.txIndex = 0 146 self.logs = make(map[common.Hash][]*types.Log) 147 self.logSize = 0 148 self.preimages = make(map[common.Hash][]byte) 149 self.clearJournalAndRefund() 150 151 return nil 152 } 153 154 // openTrie creates a trie. It uses an existing trie if one is available 155 // from the journal if available. 156 func (self *StateDB) openTrie(root common.Hash) (*trie.SecureTrie, error) { 157 for i := len(self.pastTries) - 1; i >= 0; i-- { 158 if self.pastTries[i].Hash() == root { 159 tr := *self.pastTries[i] 160 return &tr, nil 161 } 162 } 163 return trie.NewSecure(root, self.db, MaxTrieCacheGen) 164 } 165 166 func (self *StateDB) pushTrie(t *trie.SecureTrie) { 167 self.lock.Lock() 168 defer self.lock.Unlock() 169 170 if len(self.pastTries) >= maxPastTries { 171 copy(self.pastTries, self.pastTries[1:]) 172 self.pastTries[len(self.pastTries)-1] = t 173 } else { 174 self.pastTries = append(self.pastTries, t) 175 } 176 } 177 178 func (self *StateDB) StartRecord(thash, bhash common.Hash, ti int) { 179 self.thash = thash 180 self.bhash = bhash 181 self.txIndex = ti 182 } 183 184 func (self *StateDB) AddLog(log *types.Log) { 185 self.journal = append(self.journal, addLogChange{txhash: self.thash}) 186 187 log.TxHash = self.thash 188 log.BlockHash = self.bhash 189 log.TxIndex = uint(self.txIndex) 190 log.Index = self.logSize 191 self.logs[self.thash] = append(self.logs[self.thash], log) 192 self.logSize++ 193 } 194 195 func (self *StateDB) GetLogs(hash common.Hash) []*types.Log { 196 return self.logs[hash] 197 } 198 199 func (self *StateDB) Logs() []*types.Log { 200 var logs []*types.Log 201 for _, lgs := range self.logs { 202 logs = append(logs, lgs...) 203 } 204 return logs 205 } 206 207 // AddPreimage records a SHA3 preimage seen by the VM. 208 func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 209 if _, ok := self.preimages[hash]; !ok { 210 self.journal = append(self.journal, addPreimageChange{hash: hash}) 211 pi := make([]byte, len(preimage)) 212 copy(pi, preimage) 213 self.preimages[hash] = pi 214 } 215 } 216 217 // Preimages returns a list of SHA3 preimages that have been submitted. 218 func (self *StateDB) Preimages() map[common.Hash][]byte { 219 return self.preimages 220 } 221 222 func (self *StateDB) AddRefund(gas *big.Int) { 223 self.journal = append(self.journal, refundChange{prev: new(big.Int).Set(self.refund)}) 224 self.refund.Add(self.refund, gas) 225 } 226 227 // Exist reports whether the given account address exists in the state. 228 // Notably this also returns true for suicided accounts. 229 func (self *StateDB) Exist(addr common.Address) bool { 230 return self.GetStateObject(addr) != nil 231 } 232 233 // Empty returns whether the state object is either non-existent 234 // or empty according to the EIP161 specification (balance = nonce = code = 0) 235 func (self *StateDB) Empty(addr common.Address) bool { 236 so := self.GetStateObject(addr) 237 return so == nil || so.empty() 238 } 239 240 func (self *StateDB) GetAccount(addr common.Address) vm.Account { 241 return self.GetStateObject(addr) 242 } 243 244 // Retrieve the balance from the given address or 0 if object not found 245 func (self *StateDB) GetBalance(addr common.Address) *big.Int { 246 stateObject := self.GetStateObject(addr) 247 if stateObject != nil { 248 return stateObject.Balance() 249 } 250 return common.Big0 251 } 252 253 func (self *StateDB) GetNonce(addr common.Address) uint64 { 254 stateObject := self.GetStateObject(addr) 255 if stateObject != nil { 256 return stateObject.Nonce() 257 } 258 259 return 0 260 } 261 262 func (self *StateDB) GetCode(addr common.Address) []byte { 263 stateObject := self.GetStateObject(addr) 264 if stateObject != nil { 265 code := stateObject.Code(self.db) 266 key := common.BytesToHash(stateObject.CodeHash()) 267 self.codeSizeCache.Add(key, len(code)) 268 return code 269 } 270 return nil 271 } 272 273 func (self *StateDB) GetCodeSize(addr common.Address) int { 274 stateObject := self.GetStateObject(addr) 275 if stateObject == nil { 276 return 0 277 } 278 key := common.BytesToHash(stateObject.CodeHash()) 279 if cached, ok := self.codeSizeCache.Get(key); ok { 280 return cached.(int) 281 } 282 size := len(stateObject.Code(self.db)) 283 if stateObject.dbErr == nil { 284 self.codeSizeCache.Add(key, size) 285 } 286 return size 287 } 288 289 func (self *StateDB) GetCodeHash(addr common.Address) common.Hash { 290 stateObject := self.GetStateObject(addr) 291 if stateObject == nil { 292 return common.Hash{} 293 } 294 return common.BytesToHash(stateObject.CodeHash()) 295 } 296 297 func (self *StateDB) GetState(a common.Address, b common.Hash) common.Hash { 298 stateObject := self.GetStateObject(a) 299 if stateObject != nil { 300 return stateObject.GetState(self.db, b) 301 } 302 return common.Hash{} 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 return true 379 } 380 381 // 382 // Setting, updating & deleting state object methods 383 // 384 385 // updateStateObject writes the given object to the trie. 386 func (self *StateDB) updateStateObject(stateObject *StateObject) { 387 addr := stateObject.Address() 388 data, err := rlp.EncodeToBytes(stateObject) 389 if err != nil { 390 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 391 } 392 self.trie.Update(addr[:], data) 393 } 394 395 // deleteStateObject removes the given object from the state trie. 396 func (self *StateDB) deleteStateObject(stateObject *StateObject) { 397 stateObject.deleted = true 398 addr := stateObject.Address() 399 self.trie.Delete(addr[:]) 400 } 401 402 // Retrieve a state object given my the address. Returns nil if not found. 403 func (self *StateDB) GetStateObject(addr common.Address) (stateObject *StateObject) { 404 // Prefer 'live' objects. 405 if obj := self.stateObjects[addr]; obj != nil { 406 if obj.deleted { 407 return nil 408 } 409 return obj 410 } 411 412 // Load the object from the database. 413 enc := self.trie.Get(addr[:]) 414 if len(enc) == 0 { 415 return nil 416 } 417 var data Account 418 if err := rlp.DecodeBytes(enc, &data); err != nil { 419 glog.Errorf("can't decode object at %x: %v", addr[:], err) 420 return nil 421 } 422 // Insert into the live set. 423 obj := newObject(self, addr, data, self.MarkStateObjectDirty) 424 self.setStateObject(obj) 425 return obj 426 } 427 428 func (self *StateDB) setStateObject(object *StateObject) { 429 self.stateObjects[object.Address()] = object 430 } 431 432 // Retrieve a state object or create a new state object if nil 433 func (self *StateDB) GetOrNewStateObject(addr common.Address) *StateObject { 434 stateObject := self.GetStateObject(addr) 435 if stateObject == nil || stateObject.deleted { 436 stateObject, _ = self.createObject(addr) 437 } 438 return stateObject 439 } 440 441 // MarkStateObjectDirty adds the specified object to the dirty map to avoid costly 442 // state object cache iteration to find a handful of modified ones. 443 func (self *StateDB) MarkStateObjectDirty(addr common.Address) { 444 self.stateObjectsDirty[addr] = struct{}{} 445 } 446 447 // createObject creates a new state object. If there is an existing account with 448 // the given address, it is overwritten and returned as the second return value. 449 func (self *StateDB) createObject(addr common.Address) (newobj, prev *StateObject) { 450 prev = self.GetStateObject(addr) 451 newobj = newObject(self, addr, Account{}, self.MarkStateObjectDirty) 452 newobj.setNonce(0) // sets the object to dirty 453 if prev == nil { 454 if glog.V(logger.Core) { 455 glog.Infof("(+) %x\n", addr) 456 } 457 self.journal = append(self.journal, createObjectChange{account: &addr}) 458 } else { 459 self.journal = append(self.journal, resetObjectChange{prev: prev}) 460 } 461 self.setStateObject(newobj) 462 return newobj, prev 463 } 464 465 // CreateAccount explicitly creates a state object. If a state object with the address 466 // already exists the balance is carried over to the new account. 467 // 468 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 469 // a contract does the following: 470 // 471 // 1. sends funds to sha(account ++ (nonce + 1)) 472 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 473 // 474 // Carrying over the balance ensures that Ether doesn't disappear. 475 func (self *StateDB) CreateAccount(addr common.Address) vm.Account { 476 new, prev := self.createObject(addr) 477 if prev != nil { 478 new.setBalance(prev.data.Balance) 479 } 480 return new 481 } 482 483 // Copy creates a deep, independent copy of the state. 484 // Snapshots of the copied state cannot be applied to the copy. 485 func (self *StateDB) Copy() *StateDB { 486 self.lock.Lock() 487 defer self.lock.Unlock() 488 489 // Copy all the basic fields, initialize the memory ones 490 state := &StateDB{ 491 db: self.db, 492 trie: self.trie, 493 pastTries: self.pastTries, 494 codeSizeCache: self.codeSizeCache, 495 stateObjects: make(map[common.Address]*StateObject, len(self.stateObjectsDirty)), 496 stateObjectsDirty: make(map[common.Address]struct{}, len(self.stateObjectsDirty)), 497 refund: new(big.Int).Set(self.refund), 498 logs: make(map[common.Hash][]*types.Log, len(self.logs)), 499 logSize: self.logSize, 500 preimages: make(map[common.Hash][]byte), 501 } 502 // Copy the dirty states, logs, and preimages 503 for addr := range self.stateObjectsDirty { 504 state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state, state.MarkStateObjectDirty) 505 state.stateObjectsDirty[addr] = struct{}{} 506 } 507 for hash, logs := range self.logs { 508 state.logs[hash] = make([]*types.Log, len(logs)) 509 copy(state.logs[hash], logs) 510 } 511 for hash, preimage := range self.preimages { 512 state.preimages[hash] = preimage 513 } 514 return state 515 } 516 517 // Snapshot returns an identifier for the current revision of the state. 518 func (self *StateDB) Snapshot() int { 519 id := self.nextRevisionId 520 self.nextRevisionId++ 521 self.validRevisions = append(self.validRevisions, revision{id, len(self.journal)}) 522 return id 523 } 524 525 // RevertToSnapshot reverts all state changes made since the given revision. 526 func (self *StateDB) RevertToSnapshot(revid int) { 527 // Find the snapshot in the stack of valid snapshots. 528 idx := sort.Search(len(self.validRevisions), func(i int) bool { 529 return self.validRevisions[i].id >= revid 530 }) 531 if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid { 532 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 533 } 534 snapshot := self.validRevisions[idx].journalIndex 535 536 // Replay the journal to undo changes. 537 for i := len(self.journal) - 1; i >= snapshot; i-- { 538 self.journal[i].undo(self) 539 } 540 self.journal = self.journal[:snapshot] 541 542 // Remove invalidated snapshots from the stack. 543 self.validRevisions = self.validRevisions[:idx] 544 } 545 546 // GetRefund returns the current value of the refund counter. 547 // The return value must not be modified by the caller and will become 548 // invalid at the next call to AddRefund. 549 func (self *StateDB) GetRefund() *big.Int { 550 return self.refund 551 } 552 553 // IntermediateRoot computes the current root hash of the state trie. 554 // It is called in between transactions to get the root hash that 555 // goes into transaction receipts. 556 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 557 for addr := range s.stateObjectsDirty { 558 stateObject := s.stateObjects[addr] 559 if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { 560 s.deleteStateObject(stateObject) 561 } else { 562 stateObject.updateRoot(s.db) 563 s.updateStateObject(stateObject) 564 } 565 } 566 // Invalidate journal because reverting across transactions is not allowed. 567 s.clearJournalAndRefund() 568 return s.trie.Hash() 569 } 570 571 // DeleteSuicides flags the suicided objects for deletion so that it 572 // won't be referenced again when called / queried up on. 573 // 574 // DeleteSuicides should not be used for consensus related updates 575 // under any circumstances. 576 func (s *StateDB) DeleteSuicides() { 577 // Reset refund so that any used-gas calculations can use this method. 578 s.clearJournalAndRefund() 579 580 for addr := range s.stateObjectsDirty { 581 stateObject := s.stateObjects[addr] 582 583 // If the object has been removed by a suicide 584 // flag the object as deleted. 585 if stateObject.suicided { 586 stateObject.deleted = true 587 } 588 delete(s.stateObjectsDirty, addr) 589 } 590 } 591 592 // Commit commits all state changes to the database. 593 func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { 594 root, batch := s.CommitBatch(deleteEmptyObjects) 595 return root, batch.Write() 596 } 597 598 // CommitBatch commits all state changes to a write batch but does not 599 // execute the batch. It is used to validate state changes against 600 // the root hash stored in a block. 601 func (s *StateDB) CommitBatch(deleteEmptyObjects bool) (root common.Hash, batch ethdb.Batch) { 602 batch = s.db.NewBatch() 603 root, _ = s.commit(batch, deleteEmptyObjects) 604 605 glog.V(logger.Debug).Infof("Trie cache stats: %d misses, %d unloads", trie.CacheMisses(), trie.CacheUnloads()) 606 return root, batch 607 } 608 609 func (s *StateDB) clearJournalAndRefund() { 610 s.journal = nil 611 s.validRevisions = s.validRevisions[:0] 612 s.refund = new(big.Int) 613 } 614 615 func (s *StateDB) commit(dbw trie.DatabaseWriter, deleteEmptyObjects bool) (root common.Hash, err error) { 616 defer s.clearJournalAndRefund() 617 618 // Commit objects to the trie. 619 for addr, stateObject := range s.stateObjects { 620 _, isDirty := s.stateObjectsDirty[addr] 621 switch { 622 case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()): 623 // If the object has been removed, don't bother syncing it 624 // and just mark it for deletion in the trie. 625 s.deleteStateObject(stateObject) 626 case isDirty: 627 // Write any contract code associated with the state object 628 if stateObject.code != nil && stateObject.dirtyCode { 629 if err := dbw.Put(stateObject.CodeHash(), stateObject.code); err != nil { 630 return common.Hash{}, err 631 } 632 stateObject.dirtyCode = false 633 } 634 // Write any storage changes in the state object to its storage trie. 635 if err := stateObject.CommitTrie(s.db, dbw); err != nil { 636 return common.Hash{}, err 637 } 638 // Update the object in the main account trie. 639 s.updateStateObject(stateObject) 640 } 641 delete(s.stateObjectsDirty, addr) 642 } 643 // Write trie changes. 644 root, err = s.trie.CommitTo(dbw) 645 if err == nil { 646 s.pushTrie(s.trie) 647 } 648 return root, err 649 }