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