github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/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 "bytes" 22 "fmt" 23 "github.com/PlatONnetwork/PlatON-Go/crypto/sha3" 24 "math/big" 25 "sort" 26 "sync" 27 28 "github.com/PlatONnetwork/PlatON-Go/common" 29 "github.com/PlatONnetwork/PlatON-Go/core/ppos_storage" 30 "github.com/PlatONnetwork/PlatON-Go/core/types" 31 "github.com/PlatONnetwork/PlatON-Go/crypto" 32 "github.com/PlatONnetwork/PlatON-Go/log" 33 "github.com/PlatONnetwork/PlatON-Go/rlp" 34 "github.com/PlatONnetwork/PlatON-Go/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 emptyStorage = crypto.Keccak256Hash(nil) 50 ) 51 52 // StateDBs within the ethereum protocol are used to store anything 53 // within the merkle trie. StateDBs take care of caching and storing 54 // nested states. It's the general query interface to retrieve: 55 // * Contracts 56 // * Accounts 57 type StateDB struct { 58 db Database 59 trie Trie 60 61 // This map holds 'live' objects, which will get modified while processing a state transition. 62 stateObjects map[common.Address]*stateObject 63 stateObjectsDirty map[common.Address]struct{} 64 // DB error. 65 // State objects are used by the consensus core and VM which are 66 // unable to deal with database-level errors. Any error that occurs 67 // during a database read is memoized here and will eventually be returned 68 // by StateDB.Commit. 69 dbErr error 70 71 // The refund counter, also used by state transitioning. 72 refund uint64 73 74 thash, bhash common.Hash 75 txIndex int 76 logs map[common.Hash][]*types.Log 77 logSize uint 78 79 preimages map[common.Hash][]byte 80 81 // Journal of state modifications. This is the backbone of 82 // Snapshot and RevertToSnapshot. 83 journal *journal 84 validRevisions []revision 85 nextRevisionId int 86 87 lock sync.Mutex 88 89 //ppos add -> Current ppos cache object 90 pposCache *ppos_storage.Ppos_storage 91 tclock sync.RWMutex 92 } 93 94 // Create a new state from a given trie. 95 //func New(root common.Hash, db Database) (*StateDB, error) { 96 func New(root common.Hash, db Database, blocknumber *big.Int, blockhash common.Hash) (*StateDB, error) { 97 tr, err := db.OpenTrie(root) 98 if err != nil { 99 return nil, err 100 } 101 return &StateDB{ 102 db: db, 103 trie: tr, 104 stateObjects: make(map[common.Address]*stateObject), 105 stateObjectsDirty: make(map[common.Address]struct{}), 106 logs: make(map[common.Hash][]*types.Log), 107 preimages: make(map[common.Hash][]byte), 108 journal: newJournal(), 109 pposCache: ppos_storage.BuildPposCache(blocknumber, blockhash), 110 }, nil 111 } 112 113 // setError remembers the first non-nil error it is called with. 114 func (self *StateDB) setError(err error) { 115 if self.dbErr == nil { 116 self.dbErr = err 117 } 118 } 119 120 func (self *StateDB) Error() error { 121 return self.dbErr 122 } 123 124 // Reset clears out all ephemeral state objects from the state db, but keeps 125 // the underlying state trie to avoid reloading data for the next operations. 126 func (self *StateDB) Reset(root common.Hash) error { 127 tr, err := self.db.OpenTrie(root) 128 if err != nil { 129 return err 130 } 131 self.trie = tr 132 self.stateObjects = make(map[common.Address]*stateObject) 133 self.stateObjectsDirty = make(map[common.Address]struct{}) 134 self.thash = common.Hash{} 135 self.bhash = common.Hash{} 136 self.txIndex = 0 137 self.logs = make(map[common.Hash][]*types.Log) 138 self.logSize = 0 139 self.preimages = make(map[common.Hash][]byte) 140 self.clearJournalAndRefund() 141 return nil 142 } 143 144 func (self *StateDB) AddLog(logInfo *types.Log) { 145 self.journal.append(addLogChange{txhash: self.thash}) 146 logInfo.TxHash = self.thash 147 logInfo.BlockHash = self.bhash 148 logInfo.TxIndex = uint(self.txIndex) 149 logInfo.Index = self.logSize 150 self.logs[self.thash] = append(self.logs[self.thash], logInfo) 151 self.logSize++ 152 } 153 154 func (self *StateDB) GetLogs(hash common.Hash) []*types.Log { 155 return self.logs[hash] 156 } 157 158 func (self *StateDB) Logs() []*types.Log { 159 var logs []*types.Log 160 for _, lgs := range self.logs { 161 logs = append(logs, lgs...) 162 } 163 return logs 164 } 165 166 // AddPreimage records a SHA3 preimage seen by the VM. 167 func (self *StateDB) AddPreimage(hash common.Hash, preimage []byte) { 168 if _, ok := self.preimages[hash]; !ok { 169 self.journal.append(addPreimageChange{hash: hash}) 170 pi := make([]byte, len(preimage)) 171 copy(pi, preimage) 172 self.preimages[hash] = pi 173 } 174 } 175 176 // Preimages returns a list of SHA3 preimages that have been submitted. 177 func (self *StateDB) Preimages() map[common.Hash][]byte { 178 return self.preimages 179 } 180 181 // AddRefund adds gas to the refund counter 182 func (self *StateDB) AddRefund(gas uint64) { 183 self.journal.append(refundChange{prev: self.refund}) 184 self.refund += gas 185 } 186 187 // SubRefund removes gas from the refund counter. 188 // This method will panic if the refund counter goes below zero 189 func (self *StateDB) SubRefund(gas uint64) { 190 self.journal.append(refundChange{prev: self.refund}) 191 if gas > self.refund { 192 panic("Refund counter below zero") 193 } 194 self.refund -= gas 195 } 196 197 // Exist reports whether the given account address exists in the state. 198 // Notably this also returns true for suicided accounts. 199 func (self *StateDB) Exist(addr common.Address) bool { 200 return self.getStateObject(addr) != nil 201 } 202 203 // Empty returns whether the state object is either non-existent 204 // or empty according to the EIP161 specification (balance = nonce = code = 0) 205 func (self *StateDB) Empty(addr common.Address) bool { 206 so := self.getStateObject(addr) 207 return so == nil || so.empty() 208 } 209 210 // Retrieve the balance from the given address or 0 if object not found 211 func (self *StateDB) GetBalance(addr common.Address) *big.Int { 212 stateObject := self.getStateObject(addr) 213 if stateObject != nil { 214 return stateObject.Balance() 215 } 216 return common.Big0 217 } 218 219 func (self *StateDB) GetNonce(addr common.Address) uint64 { 220 stateObject := self.getStateObject(addr) 221 if stateObject != nil { 222 return stateObject.Nonce() 223 } 224 225 return 0 226 } 227 228 func (self *StateDB) GetCode(addr common.Address) []byte { 229 stateObject := self.getStateObject(addr) 230 if stateObject != nil { 231 return stateObject.Code(self.db) 232 } 233 return nil 234 } 235 236 func (self *StateDB) GetCodeSize(addr common.Address) int { 237 stateObject := self.getStateObject(addr) 238 if stateObject == nil { 239 return 0 240 } 241 if stateObject.code != nil { 242 return len(stateObject.code) 243 } 244 size, err := self.db.ContractCodeSize(stateObject.addrHash, common.BytesToHash(stateObject.CodeHash())) 245 if err != nil { 246 self.setError(err) 247 } 248 return size 249 } 250 251 func (self *StateDB) GetCodeHash(addr common.Address) common.Hash { 252 stateObject := self.getStateObject(addr) 253 if stateObject == nil { 254 return common.Hash{} 255 } 256 return common.BytesToHash(stateObject.CodeHash()) 257 } 258 259 // GetState retrieves a value from the given account's storage trie. 260 func (self *StateDB) GetState(addr common.Address, key []byte) []byte { 261 self.lock.Lock() 262 defer self.lock.Unlock() 263 stateObject := self.getStateObject(addr) 264 keyTrie, _, _ := getKeyValue(addr, key, nil) 265 if stateObject != nil { 266 return stateObject.GetState(self.db, keyTrie) 267 } 268 return []byte{} 269 } 270 271 // GetCommittedState retrieves a value from the given account's committed storage trie. 272 func (self *StateDB) GetCommittedState(addr common.Address, key []byte) []byte { 273 stateObject := self.getStateObject(addr) 274 if stateObject != nil { 275 var buffer bytes.Buffer 276 buffer.WriteString(addr.String()) 277 buffer.WriteString(string(key)) 278 key := buffer.String() 279 value := stateObject.GetCommittedState(self.db, key) 280 return value 281 } 282 return []byte{} 283 } 284 285 // Database retrieves the low level database supporting the lower level trie ops. 286 func (self *StateDB) Database() Database { 287 return self.db 288 } 289 290 // StorageTrie returns the storage trie of an account. 291 // The return value is a copy and is nil for non-existent accounts. 292 func (self *StateDB) StorageTrie(addr common.Address) Trie { 293 stateObject := self.getStateObject(addr) 294 if stateObject == nil { 295 return nil 296 } 297 cpy := stateObject.deepCopy(self) 298 return cpy.updateTrie(self.db) 299 } 300 301 func (self *StateDB) HasSuicided(addr common.Address) bool { 302 stateObject := self.getStateObject(addr) 303 if stateObject != nil { 304 return stateObject.suicided 305 } 306 return false 307 } 308 309 /* 310 * SETTERS 311 */ 312 313 // AddBalance adds amount to the account associated with addr. 314 func (self *StateDB) AddBalance(addr common.Address, amount *big.Int) { 315 stateObject := self.GetOrNewStateObject(addr) 316 if stateObject != nil { 317 stateObject.AddBalance(amount) 318 } 319 } 320 321 // SubBalance subtracts amount from the account associated with addr. 322 func (self *StateDB) SubBalance(addr common.Address, amount *big.Int) { 323 stateObject := self.GetOrNewStateObject(addr) 324 if stateObject != nil { 325 stateObject.SubBalance(amount) 326 } 327 } 328 329 func (self *StateDB) SetBalance(addr common.Address, amount *big.Int) { 330 stateObject := self.GetOrNewStateObject(addr) 331 if stateObject != nil { 332 stateObject.SetBalance(amount) 333 } 334 } 335 336 func (self *StateDB) SetNonce(addr common.Address, nonce uint64) { 337 stateObject := self.GetOrNewStateObject(addr) 338 if stateObject != nil { 339 stateObject.SetNonce(nonce) 340 } 341 } 342 343 func (self *StateDB) SetCode(addr common.Address, code []byte) { 344 stateObject := self.GetOrNewStateObject(addr) 345 if stateObject != nil { 346 stateObject.SetCode(crypto.Keccak256Hash(code), code) 347 } 348 } 349 350 func (self *StateDB) SetState(address common.Address, key, value []byte) { 351 self.lock.Lock() 352 stateObject := self.GetOrNewStateObject(address) 353 keyTrie, valueKey, value := getKeyValue(address, key, value) 354 if stateObject != nil { 355 stateObject.SetState(self.db, keyTrie, valueKey, value) 356 } 357 self.lock.Unlock() 358 } 359 360 func getKeyValue(address common.Address, key []byte, value []byte) (string, common.Hash, []byte) { 361 var buffer bytes.Buffer 362 buffer.Write(address.Bytes()) 363 buffer.WriteString(string(key)) 364 keyTrie := buffer.String() 365 366 //if value != nil && !bytes.Equal(value,[]byte{}){ 367 buffer.Reset() 368 buffer.WriteString(string(value)) 369 370 valueKey := common.Hash{} 371 keccak := sha3.NewKeccak256() 372 keccak.Write(buffer.Bytes()) 373 keccak.Sum(valueKey[:0]) 374 375 return keyTrie, valueKey, value 376 //} 377 //return keyTrie, common.Hash{}, value 378 } 379 380 // Suicide marks the given account as suicided. 381 // This clears the account balance. 382 // 383 // The account's state object is still available until the state is committed, 384 // getStateObject will return a non-nil account after Suicide. 385 func (self *StateDB) Suicide(addr common.Address) bool { 386 stateObject := self.getStateObject(addr) 387 if stateObject == nil { 388 return false 389 } 390 self.journal.append(suicideChange{ 391 account: &addr, 392 prev: stateObject.suicided, 393 prevbalance: new(big.Int).Set(stateObject.Balance()), 394 }) 395 stateObject.markSuicided() 396 stateObject.data.Balance = new(big.Int) 397 398 return true 399 } 400 401 // 402 // Setting, updating & deleting state object methods. 403 // 404 405 // updateStateObject writes the given object to the trie. 406 func (self *StateDB) updateStateObject(stateObject *stateObject) { 407 addr := stateObject.Address() 408 data, err := rlp.EncodeToBytes(stateObject) 409 if err != nil { 410 panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err)) 411 } 412 self.setError(self.trie.TryUpdate(addr[:], data)) 413 } 414 415 // deleteStateObject removes the given object from the state trie. 416 func (self *StateDB) deleteStateObject(stateObject *stateObject) { 417 stateObject.deleted = true 418 addr := stateObject.Address() 419 self.setError(self.trie.TryDelete(addr[:])) 420 } 421 422 // Retrieve a state object given by the address. Returns nil if not found. 423 func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) { 424 // Prefer 'live' objects. 425 if obj := self.stateObjects[addr]; obj != nil { 426 if obj.deleted { 427 return nil 428 } 429 return obj 430 } 431 log.Debug("getStateObject", "stateDB addr", fmt.Sprintf("%p", self), "state root", self.Root().Hex()) 432 // Load the object from the database. 433 enc, err := self.trie.TryGet(addr[:]) 434 if len(enc) == 0 { 435 self.setError(err) 436 return nil 437 } 438 var data Account 439 if err := rlp.DecodeBytes(enc, &data); err != nil { 440 log.Error("Failed to decode state object", "addr", addr, "err", err) 441 return nil 442 } 443 // Insert into the live set. 444 obj := newObject(self, addr, data) 445 self.setStateObject(obj) 446 return obj 447 } 448 449 func (self *StateDB) setStateObject(object *stateObject) { 450 self.stateObjects[object.Address()] = object 451 } 452 453 // Retrieve a state object or create a new state object if nil. 454 func (self *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { 455 log.Debug("GetOrNewStateObject", "stateDB addr", fmt.Sprintf("%p", self), "state root", self.Root().Hex()) 456 stateObject := self.getStateObject(addr) 457 if stateObject == nil || stateObject.deleted { 458 stateObject, _ = self.createObject(addr) 459 } 460 return stateObject 461 } 462 463 // createObject creates a new state object. If there is an existing account with 464 // the given address, it is overwritten and returned as the second return value. 465 func (self *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { 466 prev = self.getStateObject(addr) 467 newobj = newObject(self, addr, Account{}) 468 newobj.setNonce(0) // sets the object to dirty 469 if prev == nil { 470 self.journal.append(createObjectChange{account: &addr}) 471 } else { 472 self.journal.append(resetObjectChange{prev: prev}) 473 } 474 self.setStateObject(newobj) 475 return newobj, prev 476 } 477 478 // CreateAccount explicitly creates a state object. If a state object with the address 479 // already exists the balance is carried over to the new account. 480 // 481 // CreateAccount is called during the EVM CREATE operation. The situation might arise that 482 // a contract does the following: 483 // 484 // 1. sends funds to sha(account ++ (nonce + 1)) 485 // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) 486 // 487 // Carrying over the balance ensures that Ether doesn't disappear. 488 func (self *StateDB) CreateAccount(addr common.Address) { 489 new, prev := self.createObject(addr) 490 if prev != nil { 491 new.setBalance(prev.data.Balance) 492 } 493 } 494 495 func (self *StateDB) TxHash() common.Hash { 496 return self.thash 497 } 498 499 func (self *StateDB) TxIdx() uint32 { 500 return uint32(self.txIndex) 501 } 502 503 func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { 504 so := db.getStateObject(addr) 505 if so == nil { 506 return 507 } 508 it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil)) 509 for it.Next() { 510 key := common.BytesToHash(db.trie.GetKey(it.Key)) 511 if value, dirty := so.dirtyValueStorage[key]; dirty { 512 cb(key, common.BytesToHash(value)) 513 continue 514 } 515 cb(key, common.BytesToHash(it.Value)) 516 } 517 } 518 519 // Copy creates a deep, independent copy of the state. 520 // Snapshots of the copied state cannot be applied to the copy. 521 func (self *StateDB) Copy() *StateDB { 522 self.lock.Lock() 523 defer self.lock.Unlock() 524 525 // Copy all the basic fields, initialize the memory ones 526 state := &StateDB{ 527 db: self.db, 528 trie: self.db.CopyTrie(self.trie), 529 stateObjects: make(map[common.Address]*stateObject, len(self.journal.dirties)), 530 stateObjectsDirty: make(map[common.Address]struct{}, len(self.journal.dirties)), 531 refund: self.refund, 532 logs: make(map[common.Hash][]*types.Log, len(self.logs)), 533 logSize: self.logSize, 534 preimages: make(map[common.Hash][]byte), 535 journal: newJournal(), 536 pposCache: self.SnapShotPPOSCache(), 537 } 538 // Copy the dirty states, logs, and preimages 539 for addr := range self.journal.dirties { 540 // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527), 541 // and in the Finalise-method, there is a case where an object is in the journal but not 542 // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for 543 // nil 544 if object, exist := self.stateObjects[addr]; exist { 545 state.stateObjects[addr] = object.deepCopy(state) 546 state.stateObjectsDirty[addr] = struct{}{} 547 } 548 } 549 // Above, we don't copy the actual journal. This means that if the copy is copied, the 550 // loop above will be a no-op, since the copy's journal is empty. 551 // Thus, here we iterate over stateObjects, to enable copies of copies 552 for addr := range self.stateObjectsDirty { 553 if _, exist := state.stateObjects[addr]; !exist { 554 state.stateObjects[addr] = self.stateObjects[addr].deepCopy(state) 555 state.stateObjectsDirty[addr] = struct{}{} 556 } 557 } 558 for hash, logs := range self.logs { 559 cpy := make([]*types.Log, len(logs)) 560 for i, l := range logs { 561 cpy[i] = new(types.Log) 562 *cpy[i] = *l 563 } 564 state.logs[hash] = cpy 565 } 566 for hash, preimage := range self.preimages { 567 state.preimages[hash] = preimage 568 } 569 570 return state 571 } 572 573 // Snapshot returns an identifier for the current revision of the state. 574 func (self *StateDB) Snapshot() int { 575 id := self.nextRevisionId 576 self.nextRevisionId++ 577 self.validRevisions = append(self.validRevisions, revision{id, self.journal.length()}) 578 return id 579 } 580 581 // RevertToSnapshot reverts all state changes made since the given revision. 582 func (self *StateDB) RevertToSnapshot(revid int) { 583 // Find the snapshot in the stack of valid snapshots. 584 idx := sort.Search(len(self.validRevisions), func(i int) bool { 585 return self.validRevisions[i].id >= revid 586 }) 587 if idx == len(self.validRevisions) || self.validRevisions[idx].id != revid { 588 panic(fmt.Errorf("revision id %v cannot be reverted", revid)) 589 } 590 snapshot := self.validRevisions[idx].journalIndex 591 592 // Replay the journal to undo changes and remove invalidated snapshots 593 self.journal.revert(self, snapshot) 594 self.validRevisions = self.validRevisions[:idx] 595 } 596 597 // GetRefund returns the current value of the refund counter. 598 func (self *StateDB) GetRefund() uint64 { 599 return self.refund 600 } 601 602 // Finalise finalises the state by removing the self destructed objects 603 // and clears the journal as well as the refunds. 604 func (s *StateDB) Finalise(deleteEmptyObjects bool) { 605 for addr := range s.journal.dirties { 606 stateObject, exist := s.stateObjects[addr] 607 if !exist { 608 // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2 609 // That tx goes out of gas, and although the notion of 'touched' does not exist there, the 610 // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake, 611 // it will persist in the journal even though the journal is reverted. In this special circumstance, 612 // it may exist in `s.journal.dirties` but not in `s.stateObjects`. 613 // Thus, we can safely ignore it here 614 continue 615 } 616 617 if stateObject.suicided || (deleteEmptyObjects && stateObject.empty()) { 618 s.deleteStateObject(stateObject) 619 } else { 620 stateObject.updateRoot(s.db) 621 s.updateStateObject(stateObject) 622 } 623 s.stateObjectsDirty[addr] = struct{}{} 624 } 625 // Invalidate journal because reverting across transactions is not allowed. 626 s.clearJournalAndRefund() 627 } 628 629 // IntermediateRoot computes the current root hash of the state trie. 630 // It is called in between transactions to get the root hash that 631 // goes into transaction receipts. 632 func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { 633 s.Finalise(deleteEmptyObjects) 634 return s.trie.Hash() 635 } 636 637 func (s *StateDB) Root() common.Hash { 638 return s.trie.Hash() 639 } 640 641 // Prepare sets the current transaction hash and index and block hash which is 642 // used when the EVM emits new state logs. 643 func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) { 644 log.Debug("Prepare", "thash", thash.String()) 645 self.thash = thash 646 self.bhash = bhash 647 self.txIndex = ti 648 } 649 650 func (s *StateDB) clearJournalAndRefund() { 651 s.journal = newJournal() 652 s.validRevisions = s.validRevisions[:0] 653 s.refund = 0 654 } 655 656 // Commit writes the state to the underlying in-memory trie database. 657 func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { 658 s.lock.Lock() 659 defer s.lock.Unlock() 660 661 defer s.clearJournalAndRefund() 662 663 for addr := range s.journal.dirties { 664 s.stateObjectsDirty[addr] = struct{}{} 665 } 666 // Commit objects to the trie. 667 for addr, stateObject := range s.stateObjects { 668 _, isDirty := s.stateObjectsDirty[addr] 669 switch { 670 case stateObject.suicided || (isDirty && deleteEmptyObjects && stateObject.empty()): 671 // If the object has been removed, don't bother syncing it 672 // and just mark it for deletion in the trie. 673 s.deleteStateObject(stateObject) 674 case isDirty: 675 // Write any contract code associated with the state object 676 if stateObject.code != nil && stateObject.dirtyCode { 677 s.db.TrieDB().InsertBlob(common.BytesToHash(stateObject.CodeHash()), stateObject.code) 678 stateObject.dirtyCode = false 679 } 680 // Write any storage changes in the state object to its storage trie. 681 if err := stateObject.CommitTrie(s.db); err != nil { 682 return common.Hash{}, err 683 } 684 // Update the object in the main account trie. 685 s.updateStateObject(stateObject) 686 } 687 delete(s.stateObjectsDirty, addr) 688 } 689 // Write trie changes. 690 root, err = s.trie.Commit(func(leaf []byte, parent common.Hash) error { 691 var account Account 692 if err := rlp.DecodeBytes(leaf, &account); err != nil { 693 return nil 694 } 695 if account.Root != emptyState { 696 s.db.TrieDB().Reference(account.Root, parent) 697 } 698 code := common.BytesToHash(account.CodeHash) 699 if code != emptyCode { 700 s.db.TrieDB().Reference(code, parent) 701 } 702 return nil 703 }) 704 705 log.Debug("Trie cache stats after commit", "misses", trie.CacheMisses(), "unloads", trie.CacheUnloads()) 706 return root, err 707 } 708 709 func (self *StateDB) SetInt32(addr common.Address, key []byte, value int32) { 710 self.SetState(addr, key, common.Int32ToBytes(value)) 711 } 712 func (self *StateDB) SetInt64(addr common.Address, key []byte, value int64) { 713 self.SetState(addr, key, common.Int64ToBytes(value)) 714 } 715 func (self *StateDB) SetFloat32(addr common.Address, key []byte, value float32) { 716 self.SetState(addr, key, common.Float32ToBytes(value)) 717 } 718 func (self *StateDB) SetFloat64(addr common.Address, key []byte, value float64) { 719 self.SetState(addr, key, common.Float64ToBytes(value)) 720 } 721 func (self *StateDB) SetString(addr common.Address, key []byte, value string) { 722 self.SetState(addr, key, []byte(value)) 723 } 724 func (self *StateDB) SetByte(addr common.Address, key []byte, value byte) { 725 self.SetState(addr, key, []byte{value}) 726 } 727 728 func (self *StateDB) GetInt32(addr common.Address, key []byte) int32 { 729 return common.BytesToInt32(self.GetState(addr, key)) 730 } 731 func (self *StateDB) GetInt64(addr common.Address, key []byte) int64 { 732 return common.BytesToInt64(self.GetState(addr, key)) 733 } 734 func (self *StateDB) GetFloat32(addr common.Address, key []byte) float32 { 735 return common.BytesToFloat32(self.GetState(addr, key)) 736 } 737 func (self *StateDB) GetFloat64(addr common.Address, key []byte) float64 { 738 return common.BytesToFloat64(self.GetState(addr, key)) 739 } 740 func (self *StateDB) GetString(addr common.Address, key []byte) string { 741 return string(self.GetState(addr, key)) 742 } 743 func (self *StateDB) GetByte(addr common.Address, key []byte) byte { 744 ret := self.GetState(addr, key) 745 //if len(ret) != 1{ 746 // return byte('') 747 //} 748 return ret[0] 749 } 750 751 // todo: new method -> GetAbiHash 752 func (s *StateDB) GetAbiHash(addr common.Address) common.Hash { 753 stateObject := s.getStateObject(addr) 754 if stateObject == nil { 755 return common.Hash{} 756 } 757 return common.BytesToHash(stateObject.AbiHash()) 758 } 759 760 // todo: new method -> GetAbi 761 func (s *StateDB) GetAbi(addr common.Address) []byte { 762 stateObject := s.getStateObject(addr) 763 if stateObject != nil { 764 return stateObject.Abi(s.db) 765 } 766 return nil 767 } 768 769 // todo: new method -> SetAbi 770 func (s *StateDB) SetAbi(addr common.Address, abi []byte) { 771 stateObject := s.GetOrNewStateObject(addr) 772 if stateObject != nil { 773 stateObject.SetAbi(crypto.Keccak256Hash(abi), abi) 774 } 775 } 776 777 //ppos add 778 func (self *StateDB) GetPPOSCache() *ppos_storage.Ppos_storage { 779 return self.pposCache 780 } 781 782 func (self *StateDB) SnapShotPPOSCache() *ppos_storage.Ppos_storage { 783 return self.pposCache.Copy() 784 } 785