Rename state.StateDB to state.DB (#255)

This fixes a golint “name stutter” warning.
pull/263/head
Eugene Kim 6 years ago
parent 92161a2f2d
commit 0ec8fa1548
  1. 4
      api/client/service/server.go
  2. 4
      api/client/service/server_test.go
  3. 4
      consensus/consensus.go
  4. 2
      consensus/consensus_engine.go
  5. 2
      core/block_validator.go
  6. 6
      core/blockchain.go
  7. 6
      core/chain_makers.go
  8. 6
      core/state/dump.go
  9. 26
      core/state/journal.go
  10. 14
      core/state/managed_state.go
  11. 10
      core/state/managed_state_test.go
  12. 8
      core/state/state_object.go
  13. 2
      core/state/state_test.go
  14. 108
      core/state/statedb.go
  15. 26
      core/state/statedb_test.go
  16. 4
      core/state_processor.go
  17. 4
      core/tx_pool.go
  18. 6
      core/tx_pool_test.go
  19. 4
      core/types.go
  20. 2
      core/vm/logger_test.go
  21. 4
      core/vm/runtime/runtime.go
  22. 6
      node/worker/worker.go

@ -15,7 +15,7 @@ import (
// Server is the Server struct for client service package. // Server is the Server struct for client service package.
type Server struct { type Server struct {
stateReader func() (*state.StateDB, error) stateReader func() (*state.DB, error)
callFaucetContract func(common.Address) common.Hash callFaucetContract func(common.Address) common.Hash
} }
@ -55,7 +55,7 @@ func (s *Server) Start(ip, port string) (*grpc.Server, error) {
} }
// NewServer creates new Server which implements ClientServiceServer interface. // NewServer creates new Server which implements ClientServiceServer interface.
func NewServer(stateReader func() (*state.StateDB, error), callFaucetContract func(common.Address) common.Hash) *Server { func NewServer(stateReader func() (*state.DB, error), callFaucetContract func(common.Address) common.Hash) *Server {
s := &Server{stateReader: stateReader, callFaucetContract: callFaucetContract} s := &Server{stateReader: stateReader, callFaucetContract: callFaucetContract}
return s return s
} }

@ -29,7 +29,7 @@ var (
func TestGetFreeToken(test *testing.T) { func TestGetFreeToken(test *testing.T) {
hash := common.Hash{} hash := common.Hash{}
hash.SetBytes([]byte("hello")) hash.SetBytes([]byte("hello"))
server := NewServer(func() (*state.StateDB, error) { server := NewServer(func() (*state.DB, error) {
return nil, nil return nil, nil
}, func(common.Address) common.Hash { }, func(common.Address) common.Hash {
return hash return hash
@ -63,7 +63,7 @@ func TestFetchAccountState(test *testing.T) {
hash := common.Hash{} hash := common.Hash{}
hash.SetBytes([]byte("hello")) hash.SetBytes([]byte("hello"))
server := NewServer(func() (*state.StateDB, error) { server := NewServer(func() (*state.DB, error) {
return chain.State() return chain.State()
}, func(common.Address) common.Hash { }, func(common.Address) common.Hash {
return hash return hash

@ -426,7 +426,7 @@ func (consensus *Consensus) VerifySeal(chain ChainReader, header *types.Header)
// Finalize implements consensus.Engine, accumulating the block and uncle rewards, // Finalize implements consensus.Engine, accumulating the block and uncle rewards,
// setting the final state and assembling the block. // setting the final state and assembling the block.
func (consensus *Consensus) Finalize(chain ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, receipts []*types.Receipt) (*types.Block, error) { func (consensus *Consensus) Finalize(chain ChainReader, header *types.Header, state *state.DB, txs []*types.Transaction, receipts []*types.Receipt) (*types.Block, error) {
// Accumulate any block and uncle rewards and commit the final state root // Accumulate any block and uncle rewards and commit the final state root
// Header seems complete, assemble into a block and return // Header seems complete, assemble into a block and return
accumulateRewards(chain.Config(), state, header) accumulateRewards(chain.Config(), state, header)
@ -472,7 +472,7 @@ func (consensus *Consensus) Prepare(chain ChainReader, header *types.Header) err
// AccumulateRewards credits the coinbase of the given block with the mining // AccumulateRewards credits the coinbase of the given block with the mining
// reward. The total reward consists of the static block reward and rewards for // reward. The total reward consists of the static block reward and rewards for
// included uncles. The coinbase of each uncle block is also rewarded. // included uncles. The coinbase of each uncle block is also rewarded.
func accumulateRewards(config *params.ChainConfig, state *state.StateDB, header *types.Header) { func accumulateRewards(config *params.ChainConfig, state *state.DB, header *types.Header) {
// TODO: implement mining rewards // TODO: implement mining rewards
} }

@ -60,7 +60,7 @@ type Engine interface {
// and assembles the final block. // and assembles the final block.
// Note: The block header and state database might be updated to reflect any // Note: The block header and state database might be updated to reflect any
// consensus rules that happen at finalization (e.g. block rewards). // consensus rules that happen at finalization (e.g. block rewards).
Finalize(chain ChainReader, header *types.Header, state *state.StateDB, txs []*types.Transaction, Finalize(chain ChainReader, header *types.Header, state *state.DB, txs []*types.Transaction,
receipts []*types.Receipt) (*types.Block, error) receipts []*types.Receipt) (*types.Block, error)
// Seal generates a new sealing request for the given input block and pushes // Seal generates a new sealing request for the given input block and pushes

@ -74,7 +74,7 @@ func (v *BlockValidator) ValidateBody(block *types.Block) error {
// transition, such as amount of used gas, the receipt roots and the state root // transition, such as amount of used gas, the receipt roots and the state root
// itself. ValidateState returns a database batch if the validation was a success // itself. ValidateState returns a database batch if the validation was a success
// otherwise nil and an error is returned. // otherwise nil and an error is returned.
func (v *BlockValidator) ValidateState(block, parent *types.Block, statedb *state.StateDB, receipts types.Receipts, usedGas uint64) error { func (v *BlockValidator) ValidateState(block, parent *types.Block, statedb *state.DB, receipts types.Receipts, usedGas uint64) error {
header := block.Header() header := block.Header()
if block.GasUsed() != usedGas { if block.GasUsed() != usedGas {
return fmt.Errorf("invalid gas used (remote: %d local: %d)", block.GasUsed(), usedGas) return fmt.Errorf("invalid gas used (remote: %d local: %d)", block.GasUsed(), usedGas)

@ -401,12 +401,12 @@ func (bc *BlockChain) Processor() Processor {
} }
// State returns a new mutable state based on the current HEAD block. // State returns a new mutable state based on the current HEAD block.
func (bc *BlockChain) State() (*state.StateDB, error) { func (bc *BlockChain) State() (*state.DB, error) {
return bc.StateAt(bc.CurrentBlock().Root()) return bc.StateAt(bc.CurrentBlock().Root())
} }
// StateAt returns a new mutable state based on a particular point in time. // StateAt returns a new mutable state based on a particular point in time.
func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) { func (bc *BlockChain) StateAt(root common.Hash) (*state.DB, error) {
return state.New(root, bc.stateCache) return state.New(root, bc.stateCache)
} }
@ -913,7 +913,7 @@ func (bc *BlockChain) WriteBlockWithoutState(block *types.Block, td *big.Int) (e
} }
// WriteBlockWithState writes the block and all associated state to the database. // WriteBlockWithState writes the block and all associated state to the database.
func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) { func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.DB) (status WriteStatus, err error) {
bc.wg.Add(1) bc.wg.Add(1)
defer bc.wg.Done() defer bc.wg.Done()

@ -36,7 +36,7 @@ type BlockGen struct {
parent *types.Block parent *types.Block
chain []*types.Block chain []*types.Block
header *types.Header header *types.Header
statedb *state.StateDB statedb *state.DB
gasPool *GasPool gasPool *GasPool
txs []*types.Transaction txs []*types.Transaction
@ -167,7 +167,7 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse
} }
blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n) blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
chainreader := &fakeChainReader{config: config} chainreader := &fakeChainReader{config: config}
genblock := func(i int, parent *types.Block, statedb *state.StateDB) (*types.Block, types.Receipts) { genblock := func(i int, parent *types.Block, statedb *state.DB) (*types.Block, types.Receipts) {
b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine} b := &BlockGen{i: i, chain: blocks, parent: parent, statedb: statedb, config: config, engine: engine}
b.header = makeHeader(chainreader, parent, statedb, b.engine) b.header = makeHeader(chainreader, parent, statedb, b.engine)
@ -216,7 +216,7 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse
return blocks, receipts return blocks, receipts
} }
func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header { func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.DB, engine consensus.Engine) *types.Header {
var time *big.Int var time *big.Int
if parent.Time() == nil { if parent.Time() == nil {
time = big.NewInt(10) time = big.NewInt(10)

@ -41,8 +41,8 @@ type Dump struct {
Accounts map[string]DumpAccount `json:"accounts"` Accounts map[string]DumpAccount `json:"accounts"`
} }
// RawDump returns Dump from given StateDB. // RawDump returns Dump from given DB.
func (stateDB *StateDB) RawDump() Dump { func (stateDB *DB) RawDump() Dump {
dump := Dump{ dump := Dump{
Root: fmt.Sprintf("%x", stateDB.trie.Hash()), Root: fmt.Sprintf("%x", stateDB.trie.Hash()),
Accounts: make(map[string]DumpAccount), Accounts: make(map[string]DumpAccount),
@ -75,7 +75,7 @@ func (stateDB *StateDB) RawDump() Dump {
} }
// Dump dumps into []byte. // Dump dumps into []byte.
func (stateDB *StateDB) Dump() []byte { func (stateDB *DB) Dump() []byte {
json, err := json.MarshalIndent(stateDB.RawDump(), "", " ") json, err := json.MarshalIndent(stateDB.RawDump(), "", " ")
if err != nil { if err != nil {
fmt.Println("dump err", err) fmt.Println("dump err", err)

@ -26,7 +26,7 @@ import (
// reverted on demand. // reverted on demand.
type journalEntry interface { type journalEntry interface {
// revert undoes the changes introduced by this journal entry. // revert undoes the changes introduced by this journal entry.
revert(*StateDB) revert(*DB)
// dirtied returns the Ethereum address modified by this journal entry. // dirtied returns the Ethereum address modified by this journal entry.
dirtied() *common.Address dirtied() *common.Address
@ -57,7 +57,7 @@ func (j *journal) append(entry journalEntry) {
// revert undoes a batch of journalled modifications along with any reverted // revert undoes a batch of journalled modifications along with any reverted
// dirty handling too. // dirty handling too.
func (j *journal) revert(statedb *StateDB, snapshot int) { func (j *journal) revert(statedb *DB, snapshot int) {
for i := len(j.entries) - 1; i >= snapshot; i-- { for i := len(j.entries) - 1; i >= snapshot; i-- {
// Undo the changes made by the operation // Undo the changes made by the operation
j.entries[i].revert(statedb) j.entries[i].revert(statedb)
@ -133,7 +133,7 @@ type (
} }
) )
func (ch createObjectChange) revert(s *StateDB) { func (ch createObjectChange) revert(s *DB) {
delete(s.stateObjects, *ch.account) delete(s.stateObjects, *ch.account)
delete(s.stateObjectsDirty, *ch.account) delete(s.stateObjectsDirty, *ch.account)
} }
@ -142,7 +142,7 @@ func (ch createObjectChange) dirtied() *common.Address {
return ch.account return ch.account
} }
func (ch resetObjectChange) revert(s *StateDB) { func (ch resetObjectChange) revert(s *DB) {
s.setStateObject(ch.prev) s.setStateObject(ch.prev)
} }
@ -150,7 +150,7 @@ func (ch resetObjectChange) dirtied() *common.Address {
return nil return nil
} }
func (ch suicideChange) revert(s *StateDB) { func (ch suicideChange) revert(s *DB) {
obj := s.getStateObject(*ch.account) obj := s.getStateObject(*ch.account)
if obj != nil { if obj != nil {
obj.suicided = ch.prev obj.suicided = ch.prev
@ -164,14 +164,14 @@ func (ch suicideChange) dirtied() *common.Address {
var ripemd = common.HexToAddress("0000000000000000000000000000000000000003") var ripemd = common.HexToAddress("0000000000000000000000000000000000000003")
func (ch touchChange) revert(s *StateDB) { func (ch touchChange) revert(s *DB) {
} }
func (ch touchChange) dirtied() *common.Address { func (ch touchChange) dirtied() *common.Address {
return ch.account return ch.account
} }
func (ch balanceChange) revert(s *StateDB) { func (ch balanceChange) revert(s *DB) {
s.getStateObject(*ch.account).setBalance(ch.prev) s.getStateObject(*ch.account).setBalance(ch.prev)
} }
@ -179,7 +179,7 @@ func (ch balanceChange) dirtied() *common.Address {
return ch.account return ch.account
} }
func (ch nonceChange) revert(s *StateDB) { func (ch nonceChange) revert(s *DB) {
s.getStateObject(*ch.account).setNonce(ch.prev) s.getStateObject(*ch.account).setNonce(ch.prev)
} }
@ -187,7 +187,7 @@ func (ch nonceChange) dirtied() *common.Address {
return ch.account return ch.account
} }
func (ch codeChange) revert(s *StateDB) { func (ch codeChange) revert(s *DB) {
s.getStateObject(*ch.account).setCode(common.BytesToHash(ch.prevhash), ch.prevcode) s.getStateObject(*ch.account).setCode(common.BytesToHash(ch.prevhash), ch.prevcode)
} }
@ -195,7 +195,7 @@ func (ch codeChange) dirtied() *common.Address {
return ch.account return ch.account
} }
func (ch storageChange) revert(s *StateDB) { func (ch storageChange) revert(s *DB) {
s.getStateObject(*ch.account).setState(ch.key, ch.prevalue) s.getStateObject(*ch.account).setState(ch.key, ch.prevalue)
} }
@ -203,7 +203,7 @@ func (ch storageChange) dirtied() *common.Address {
return ch.account return ch.account
} }
func (ch refundChange) revert(s *StateDB) { func (ch refundChange) revert(s *DB) {
s.refund = ch.prev s.refund = ch.prev
} }
@ -211,7 +211,7 @@ func (ch refundChange) dirtied() *common.Address {
return nil return nil
} }
func (ch addLogChange) revert(s *StateDB) { func (ch addLogChange) revert(s *DB) {
logs := s.logs[ch.txhash] logs := s.logs[ch.txhash]
if len(logs) == 1 { if len(logs) == 1 {
delete(s.logs, ch.txhash) delete(s.logs, ch.txhash)
@ -225,7 +225,7 @@ func (ch addLogChange) dirtied() *common.Address {
return nil return nil
} }
func (ch addPreimageChange) revert(s *StateDB) { func (ch addPreimageChange) revert(s *DB) {
delete(s.preimages, ch.hash) delete(s.preimages, ch.hash)
} }

@ -30,7 +30,7 @@ type account struct {
// ManagedState is the managed state. // ManagedState is the managed state.
type ManagedState struct { type ManagedState struct {
*StateDB *DB
mu sync.RWMutex mu sync.RWMutex
@ -38,18 +38,18 @@ type ManagedState struct {
} }
// ManageState returns a new managed state with the statedb as it's backing layer // ManageState returns a new managed state with the statedb as it's backing layer
func ManageState(statedb *StateDB) *ManagedState { func ManageState(statedb *DB) *ManagedState {
return &ManagedState{ return &ManagedState{
StateDB: statedb.Copy(), DB: statedb.Copy(),
accounts: make(map[common.Address]*account), accounts: make(map[common.Address]*account),
} }
} }
// SetState sets the backing layer of the managed state // SetState sets the backing layer of the managed state
func (ms *ManagedState) SetState(statedb *StateDB) { func (ms *ManagedState) SetState(statedb *DB) {
ms.mu.Lock() ms.mu.Lock()
defer ms.mu.Unlock() defer ms.mu.Unlock()
ms.StateDB = statedb ms.DB = statedb
} }
// RemoveNonce removed the nonce from the managed state and all future pending nonces // RemoveNonce removed the nonce from the managed state and all future pending nonces
@ -94,7 +94,7 @@ func (ms *ManagedState) GetNonce(addr common.Address) uint64 {
account := ms.getAccount(addr) account := ms.getAccount(addr)
return uint64(len(account.nonces)) + account.nstart return uint64(len(account.nonces)) + account.nstart
} }
return ms.StateDB.GetNonce(addr) return ms.DB.GetNonce(addr)
} }
// SetNonce sets the new canonical nonce for the managed state // SetNonce sets the new canonical nonce for the managed state
@ -128,7 +128,7 @@ func (ms *ManagedState) getAccount(addr common.Address) *account {
} else { } else {
// Always make sure the state account nonce isn't actually higher // Always make sure the state account nonce isn't actually higher
// than the tracked one. // than the tracked one.
so := ms.StateDB.getStateObject(addr) so := ms.DB.getStateObject(addr)
if so != nil && uint64(len(account.nonces))+account.nstart < so.Nonce() { if so != nil && uint64(len(account.nonces))+account.nstart < so.Nonce() {
ms.accounts[addr] = newAccount(so) ms.accounts[addr] = newAccount(so)
} }

@ -28,8 +28,8 @@ var addr = common.BytesToAddress([]byte("test"))
func create() (*ManagedState, *account) { func create() (*ManagedState, *account) {
statedb, _ := New(common.Hash{}, NewDatabase(ethdb.NewMemDatabase())) statedb, _ := New(common.Hash{}, NewDatabase(ethdb.NewMemDatabase()))
ms := ManageState(statedb) ms := ManageState(statedb)
ms.StateDB.SetNonce(addr, 100) ms.DB.SetNonce(addr, 100)
ms.accounts[addr] = newAccount(ms.StateDB.getStateObject(addr)) ms.accounts[addr] = newAccount(ms.DB.getStateObject(addr))
return ms, ms.accounts[addr] return ms, ms.accounts[addr]
} }
@ -89,7 +89,7 @@ func TestRemoteNonceChange(t *testing.T) {
account.nonces = append(account.nonces, nn...) account.nonces = append(account.nonces, nn...)
ms.NewNonce(addr) ms.NewNonce(addr)
ms.StateDB.stateObjects[addr].data.Nonce = 200 ms.DB.stateObjects[addr].data.Nonce = 200
nonce := ms.NewNonce(addr) nonce := ms.NewNonce(addr)
if nonce != 200 { if nonce != 200 {
t.Error("expected nonce after remote update to be", 200, "got", nonce) t.Error("expected nonce after remote update to be", 200, "got", nonce)
@ -97,7 +97,7 @@ func TestRemoteNonceChange(t *testing.T) {
ms.NewNonce(addr) ms.NewNonce(addr)
ms.NewNonce(addr) ms.NewNonce(addr)
ms.NewNonce(addr) ms.NewNonce(addr)
ms.StateDB.stateObjects[addr].data.Nonce = 200 ms.DB.stateObjects[addr].data.Nonce = 200
nonce = ms.NewNonce(addr) nonce = ms.NewNonce(addr)
if nonce != 204 { if nonce != 204 {
t.Error("expected nonce after remote update to be", 204, "got", nonce) t.Error("expected nonce after remote update to be", 204, "got", nonce)
@ -115,7 +115,7 @@ func TestSetNonce(t *testing.T) {
} }
addr[0] = 1 addr[0] = 1
ms.StateDB.SetNonce(addr, 1) ms.DB.SetNonce(addr, 1)
if ms.GetNonce(addr) != 1 { if ms.GetNonce(addr) != 1 {
t.Error("Expected nonce of 1, got", ms.GetNonce(addr)) t.Error("Expected nonce of 1, got", ms.GetNonce(addr))

@ -66,13 +66,13 @@ type stateObject struct {
address common.Address address common.Address
addrHash common.Hash // hash of ethereum address of the account addrHash common.Hash // hash of ethereum address of the account
data Account data Account
db *StateDB db *DB
// DB error. // DB error.
// State objects are used by the consensus core and VM which are // State objects are used by the consensus core and VM which are
// unable to deal with database-level errors. Any error that occurs // unable to deal with database-level errors. Any error that occurs
// during a database read is memoized here and will eventually be returned // during a database read is memoized here and will eventually be returned
// by StateDB.Commit. // by DB.Commit.
dbErr error dbErr error
// Write caches. // Write caches.
@ -105,7 +105,7 @@ type Account struct {
} }
// newObject creates a state object. // newObject creates a state object.
func newObject(db *StateDB, address common.Address, data Account) *stateObject { func newObject(db *DB, address common.Address, data Account) *stateObject {
if data.Balance == nil { if data.Balance == nil {
data.Balance = new(big.Int) data.Balance = new(big.Int)
} }
@ -298,7 +298,7 @@ func (s *stateObject) setBalance(amount *big.Int) {
// Return the gas back to the origin. Used by the Virtual machine or Closures // Return the gas back to the origin. Used by the Virtual machine or Closures
func (s *stateObject) ReturnGas(gas *big.Int) {} func (s *stateObject) ReturnGas(gas *big.Int) {}
func (s *stateObject) deepCopy(db *StateDB) *stateObject { func (s *stateObject) deepCopy(db *DB) *stateObject {
stateObject := newObject(db, s.address, s.data) stateObject := newObject(db, s.address, s.data)
if s.trie != nil { if s.trie != nil {
stateObject.trie = db.db.CopyTrie(s.trie) stateObject.trie = db.db.CopyTrie(s.trie)

@ -29,7 +29,7 @@ import (
type StateSuite struct { type StateSuite struct {
db *ethdb.MemDatabase db *ethdb.MemDatabase
state *StateDB state *DB
} }
var _ = checker.Suite(&StateSuite{}) var _ = checker.Suite(&StateSuite{})

@ -52,12 +52,12 @@ func (n *proofList) Put(key []byte, value []byte) error {
return nil return nil
} }
// StateDB within the ethereum protocol are used to store anything // DB within the ethereum protocol are used to store anything
// within the merkle trie. StateDBs take care of caching and storing // within the merkle trie. StateDBs take care of caching and storing
// nested states. It's the general query interface to retrieve: // nested states. It's the general query interface to retrieve:
// * Contracts // * Contracts
// * Accounts // * Accounts
type StateDB struct { type DB struct {
db Database db Database
trie Trie trie Trie
@ -69,7 +69,7 @@ type StateDB struct {
// State objects are used by the consensus core and VM which are // State objects are used by the consensus core and VM which are
// unable to deal with database-level errors. Any error that occurs // unable to deal with database-level errors. Any error that occurs
// during a database read is memoized here and will eventually be returned // during a database read is memoized here and will eventually be returned
// by StateDB.Commit. // by DB.Commit.
dbErr error dbErr error
// The refund counter, also used by state transitioning. // The refund counter, also used by state transitioning.
@ -92,12 +92,12 @@ type StateDB struct {
} }
// New creates a new state from a given trie. // New creates a new state from a given trie.
func New(root common.Hash, db Database) (*StateDB, error) { func New(root common.Hash, db Database) (*DB, error) {
tr, err := db.OpenTrie(root) tr, err := db.OpenTrie(root)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &StateDB{ return &DB{
db: db, db: db,
trie: tr, trie: tr,
stateObjects: make(map[common.Address]*stateObject), stateObjects: make(map[common.Address]*stateObject),
@ -109,19 +109,19 @@ func New(root common.Hash, db Database) (*StateDB, error) {
} }
// setError remembers the first non-nil error it is called with. // setError remembers the first non-nil error it is called with.
func (stateDB *StateDB) setError(err error) { func (stateDB *DB) setError(err error) {
if stateDB.dbErr == nil { if stateDB.dbErr == nil {
stateDB.dbErr = err stateDB.dbErr = err
} }
} }
func (stateDB *StateDB) Error() error { func (stateDB *DB) Error() error {
return stateDB.dbErr return stateDB.dbErr
} }
// Reset clears out all ephemeral state objects from the state db, but keeps // Reset clears out all ephemeral state objects from the state db, but keeps
// the underlying state trie to avoid reloading data for the next operations. // the underlying state trie to avoid reloading data for the next operations.
func (stateDB *StateDB) Reset(root common.Hash) error { func (stateDB *DB) Reset(root common.Hash) error {
tr, err := stateDB.db.OpenTrie(root) tr, err := stateDB.db.OpenTrie(root)
if err != nil { if err != nil {
return err return err
@ -140,7 +140,7 @@ func (stateDB *StateDB) Reset(root common.Hash) error {
} }
// AddLog adds logs into stateDB // AddLog adds logs into stateDB
func (stateDB *StateDB) AddLog(log *types.Log) { func (stateDB *DB) AddLog(log *types.Log) {
stateDB.journal.append(addLogChange{txhash: stateDB.thash}) stateDB.journal.append(addLogChange{txhash: stateDB.thash})
log.TxHash = stateDB.thash log.TxHash = stateDB.thash
@ -152,12 +152,12 @@ func (stateDB *StateDB) AddLog(log *types.Log) {
} }
// GetLogs gets logs from stateDB given a hash // GetLogs gets logs from stateDB given a hash
func (stateDB *StateDB) GetLogs(hash common.Hash) []*types.Log { func (stateDB *DB) GetLogs(hash common.Hash) []*types.Log {
return stateDB.logs[hash] return stateDB.logs[hash]
} }
// Logs returns a list of Log. // Logs returns a list of Log.
func (stateDB *StateDB) Logs() []*types.Log { func (stateDB *DB) Logs() []*types.Log {
var logs []*types.Log var logs []*types.Log
for _, lgs := range stateDB.logs { for _, lgs := range stateDB.logs {
logs = append(logs, lgs...) logs = append(logs, lgs...)
@ -166,7 +166,7 @@ func (stateDB *StateDB) Logs() []*types.Log {
} }
// AddPreimage records a SHA3 preimage seen by the VM. // AddPreimage records a SHA3 preimage seen by the VM.
func (stateDB *StateDB) AddPreimage(hash common.Hash, preimage []byte) { func (stateDB *DB) AddPreimage(hash common.Hash, preimage []byte) {
if _, ok := stateDB.preimages[hash]; !ok { if _, ok := stateDB.preimages[hash]; !ok {
stateDB.journal.append(addPreimageChange{hash: hash}) stateDB.journal.append(addPreimageChange{hash: hash})
pi := make([]byte, len(preimage)) pi := make([]byte, len(preimage))
@ -176,19 +176,19 @@ func (stateDB *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
} }
// Preimages returns a list of SHA3 preimages that have been submitted. // Preimages returns a list of SHA3 preimages that have been submitted.
func (stateDB *StateDB) Preimages() map[common.Hash][]byte { func (stateDB *DB) Preimages() map[common.Hash][]byte {
return stateDB.preimages return stateDB.preimages
} }
// AddRefund adds gas to the refund counter // AddRefund adds gas to the refund counter
func (stateDB *StateDB) AddRefund(gas uint64) { func (stateDB *DB) AddRefund(gas uint64) {
stateDB.journal.append(refundChange{prev: stateDB.refund}) stateDB.journal.append(refundChange{prev: stateDB.refund})
stateDB.refund += gas stateDB.refund += gas
} }
// SubRefund removes gas from the refund counter. // SubRefund removes gas from the refund counter.
// This method will panic if the refund counter goes below zero // This method will panic if the refund counter goes below zero
func (stateDB *StateDB) SubRefund(gas uint64) { func (stateDB *DB) SubRefund(gas uint64) {
stateDB.journal.append(refundChange{prev: stateDB.refund}) stateDB.journal.append(refundChange{prev: stateDB.refund})
if gas > stateDB.refund { if gas > stateDB.refund {
panic("Refund counter below zero") panic("Refund counter below zero")
@ -198,19 +198,19 @@ func (stateDB *StateDB) SubRefund(gas uint64) {
// Exist reports whether the given account address exists in the state. // Exist reports whether the given account address exists in the state.
// Notably this also returns true for suicided accounts. // Notably this also returns true for suicided accounts.
func (stateDB *StateDB) Exist(addr common.Address) bool { func (stateDB *DB) Exist(addr common.Address) bool {
return stateDB.getStateObject(addr) != nil return stateDB.getStateObject(addr) != nil
} }
// Empty returns whether the state object is either non-existent // Empty returns whether the state object is either non-existent
// or empty according to the EIP161 specification (balance = nonce = code = 0) // or empty according to the EIP161 specification (balance = nonce = code = 0)
func (stateDB *StateDB) Empty(addr common.Address) bool { func (stateDB *DB) Empty(addr common.Address) bool {
so := stateDB.getStateObject(addr) so := stateDB.getStateObject(addr)
return so == nil || so.empty() return so == nil || so.empty()
} }
// GetBalance retrieves the balance from the given address or 0 if object not found // GetBalance retrieves the balance from the given address or 0 if object not found
func (stateDB *StateDB) GetBalance(addr common.Address) *big.Int { func (stateDB *DB) GetBalance(addr common.Address) *big.Int {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.Balance() return stateObject.Balance()
@ -219,7 +219,7 @@ func (stateDB *StateDB) GetBalance(addr common.Address) *big.Int {
} }
// GetNonce returns the nonce of the given address. // GetNonce returns the nonce of the given address.
func (stateDB *StateDB) GetNonce(addr common.Address) uint64 { func (stateDB *DB) GetNonce(addr common.Address) uint64 {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.Nonce() return stateObject.Nonce()
@ -229,7 +229,7 @@ func (stateDB *StateDB) GetNonce(addr common.Address) uint64 {
} }
// GetCode returns code of a given address. // GetCode returns code of a given address.
func (stateDB *StateDB) GetCode(addr common.Address) []byte { func (stateDB *DB) GetCode(addr common.Address) []byte {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.Code(stateDB.db) return stateObject.Code(stateDB.db)
@ -238,7 +238,7 @@ func (stateDB *StateDB) GetCode(addr common.Address) []byte {
} }
// GetCodeSize returns code size of a given address in stateDB. // GetCodeSize returns code size of a given address in stateDB.
func (stateDB *StateDB) GetCodeSize(addr common.Address) int { func (stateDB *DB) GetCodeSize(addr common.Address) int {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return 0 return 0
@ -254,7 +254,7 @@ func (stateDB *StateDB) GetCodeSize(addr common.Address) int {
} }
// GetCodeHash returns code hash of a given address. // GetCodeHash returns code hash of a given address.
func (stateDB *StateDB) GetCodeHash(addr common.Address) common.Hash { func (stateDB *DB) GetCodeHash(addr common.Address) common.Hash {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return common.Hash{} return common.Hash{}
@ -263,7 +263,7 @@ func (stateDB *StateDB) GetCodeHash(addr common.Address) common.Hash {
} }
// GetState retrieves a value from the given account's storage trie. // GetState retrieves a value from the given account's storage trie.
func (stateDB *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash { func (stateDB *DB) GetState(addr common.Address, hash common.Hash) common.Hash {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.GetState(stateDB.db, hash) return stateObject.GetState(stateDB.db, hash)
@ -272,14 +272,14 @@ func (stateDB *StateDB) GetState(addr common.Address, hash common.Hash) common.H
} }
// GetProof returns the MerkleProof for a given Account // GetProof returns the MerkleProof for a given Account
func (stateDB *StateDB) GetProof(a common.Address) ([][]byte, error) { func (stateDB *DB) GetProof(a common.Address) ([][]byte, error) {
var proof proofList var proof proofList
err := stateDB.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof) err := stateDB.trie.Prove(crypto.Keccak256(a.Bytes()), 0, &proof)
return [][]byte(proof), err return [][]byte(proof), err
} }
// GetStorageProof returns the StorageProof for given key // GetStorageProof returns the StorageProof for given key
func (stateDB *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) { func (stateDB *DB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
var proof proofList var proof proofList
trie := stateDB.StorageTrie(a) trie := stateDB.StorageTrie(a)
if trie == nil { if trie == nil {
@ -290,7 +290,7 @@ func (stateDB *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]
} }
// GetCommittedState retrieves a value from the given account's committed storage trie. // GetCommittedState retrieves a value from the given account's committed storage trie.
func (stateDB *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash { func (stateDB *DB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.GetCommittedState(stateDB.db, hash) return stateObject.GetCommittedState(stateDB.db, hash)
@ -299,13 +299,13 @@ func (stateDB *StateDB) GetCommittedState(addr common.Address, hash common.Hash)
} }
// Database retrieves the low level database supporting the lower level trie ops. // Database retrieves the low level database supporting the lower level trie ops.
func (stateDB *StateDB) Database() Database { func (stateDB *DB) Database() Database {
return stateDB.db return stateDB.db
} }
// StorageTrie returns the storage trie of an account. // StorageTrie returns the storage trie of an account.
// The return value is a copy and is nil for non-existent accounts. // The return value is a copy and is nil for non-existent accounts.
func (stateDB *StateDB) StorageTrie(addr common.Address) Trie { func (stateDB *DB) StorageTrie(addr common.Address) Trie {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return nil return nil
@ -315,7 +315,7 @@ func (stateDB *StateDB) StorageTrie(addr common.Address) Trie {
} }
// HasSuicided checks if the state object of the given addr is suicided. // HasSuicided checks if the state object of the given addr is suicided.
func (stateDB *StateDB) HasSuicided(addr common.Address) bool { func (stateDB *DB) HasSuicided(addr common.Address) bool {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject != nil { if stateObject != nil {
return stateObject.suicided return stateObject.suicided
@ -328,7 +328,7 @@ func (stateDB *StateDB) HasSuicided(addr common.Address) bool {
*/ */
// AddBalance adds amount to the account associated with addr. // AddBalance adds amount to the account associated with addr.
func (stateDB *StateDB) AddBalance(addr common.Address, amount *big.Int) { func (stateDB *DB) AddBalance(addr common.Address, amount *big.Int) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := stateDB.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.AddBalance(amount) stateObject.AddBalance(amount)
@ -336,7 +336,7 @@ func (stateDB *StateDB) AddBalance(addr common.Address, amount *big.Int) {
} }
// SubBalance subtracts amount from the account associated with addr. // SubBalance subtracts amount from the account associated with addr.
func (stateDB *StateDB) SubBalance(addr common.Address, amount *big.Int) { func (stateDB *DB) SubBalance(addr common.Address, amount *big.Int) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := stateDB.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SubBalance(amount) stateObject.SubBalance(amount)
@ -344,7 +344,7 @@ func (stateDB *StateDB) SubBalance(addr common.Address, amount *big.Int) {
} }
// SetBalance sets balance of an address. // SetBalance sets balance of an address.
func (stateDB *StateDB) SetBalance(addr common.Address, amount *big.Int) { func (stateDB *DB) SetBalance(addr common.Address, amount *big.Int) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := stateDB.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetBalance(amount) stateObject.SetBalance(amount)
@ -352,7 +352,7 @@ func (stateDB *StateDB) SetBalance(addr common.Address, amount *big.Int) {
} }
// SetNonce sets nonce of a given address. // SetNonce sets nonce of a given address.
func (stateDB *StateDB) SetNonce(addr common.Address, nonce uint64) { func (stateDB *DB) SetNonce(addr common.Address, nonce uint64) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := stateDB.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetNonce(nonce) stateObject.SetNonce(nonce)
@ -360,7 +360,7 @@ func (stateDB *StateDB) SetNonce(addr common.Address, nonce uint64) {
} }
// SetCode sets code of a given address. // SetCode sets code of a given address.
func (stateDB *StateDB) SetCode(addr common.Address, code []byte) { func (stateDB *DB) SetCode(addr common.Address, code []byte) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := stateDB.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetCode(crypto.Keccak256Hash(code), code) stateObject.SetCode(crypto.Keccak256Hash(code), code)
@ -368,7 +368,7 @@ func (stateDB *StateDB) SetCode(addr common.Address, code []byte) {
} }
// SetState sets hash value of a given address. // SetState sets hash value of a given address.
func (stateDB *StateDB) SetState(addr common.Address, key, value common.Hash) { func (stateDB *DB) SetState(addr common.Address, key, value common.Hash) {
stateObject := stateDB.GetOrNewStateObject(addr) stateObject := stateDB.GetOrNewStateObject(addr)
if stateObject != nil { if stateObject != nil {
stateObject.SetState(stateDB.db, key, value) stateObject.SetState(stateDB.db, key, value)
@ -380,7 +380,7 @@ func (stateDB *StateDB) SetState(addr common.Address, key, value common.Hash) {
// //
// The account's state object is still available until the state is committed, // The account's state object is still available until the state is committed,
// getStateObject will return a non-nil account after Suicide. // getStateObject will return a non-nil account after Suicide.
func (stateDB *StateDB) Suicide(addr common.Address) bool { func (stateDB *DB) Suicide(addr common.Address) bool {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject == nil { if stateObject == nil {
return false return false
@ -401,7 +401,7 @@ func (stateDB *StateDB) Suicide(addr common.Address) bool {
// //
// updateStateObject writes the given object to the trie. // updateStateObject writes the given object to the trie.
func (stateDB *StateDB) updateStateObject(stateObject *stateObject) { func (stateDB *DB) updateStateObject(stateObject *stateObject) {
addr := stateObject.Address() addr := stateObject.Address()
data, err := rlp.EncodeToBytes(stateObject) data, err := rlp.EncodeToBytes(stateObject)
if err != nil { if err != nil {
@ -411,14 +411,14 @@ func (stateDB *StateDB) updateStateObject(stateObject *stateObject) {
} }
// deleteStateObject removes the given object from the state trie. // deleteStateObject removes the given object from the state trie.
func (stateDB *StateDB) deleteStateObject(stateObject *stateObject) { func (stateDB *DB) deleteStateObject(stateObject *stateObject) {
stateObject.deleted = true stateObject.deleted = true
addr := stateObject.Address() addr := stateObject.Address()
stateDB.setError(stateDB.trie.TryDelete(addr[:])) stateDB.setError(stateDB.trie.TryDelete(addr[:]))
} }
// Retrieve a state object given by the address. Returns nil if not found. // Retrieve a state object given by the address. Returns nil if not found.
func (stateDB *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) { func (stateDB *DB) getStateObject(addr common.Address) (stateObject *stateObject) {
// Prefer 'live' objects. // Prefer 'live' objects.
if obj := stateDB.stateObjects[addr]; obj != nil { if obj := stateDB.stateObjects[addr]; obj != nil {
if obj.deleted { if obj.deleted {
@ -444,12 +444,12 @@ func (stateDB *StateDB) getStateObject(addr common.Address) (stateObject *stateO
return obj return obj
} }
func (stateDB *StateDB) setStateObject(object *stateObject) { func (stateDB *DB) setStateObject(object *stateObject) {
stateDB.stateObjects[object.Address()] = object stateDB.stateObjects[object.Address()] = object
} }
// GetOrNewStateObject retrieves a state object or create a new state object if nil. // GetOrNewStateObject retrieves a state object or create a new state object if nil.
func (stateDB *StateDB) GetOrNewStateObject(addr common.Address) *stateObject { func (stateDB *DB) GetOrNewStateObject(addr common.Address) *stateObject {
stateObject := stateDB.getStateObject(addr) stateObject := stateDB.getStateObject(addr)
if stateObject == nil || stateObject.deleted { if stateObject == nil || stateObject.deleted {
stateObject, _ = stateDB.createObject(addr) stateObject, _ = stateDB.createObject(addr)
@ -459,7 +459,7 @@ func (stateDB *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
// createObject creates a new state object. If there is an existing account with // createObject creates a new state object. If there is an existing account with
// the given address, it is overwritten and returned as the second return value. // the given address, it is overwritten and returned as the second return value.
func (stateDB *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) { func (stateDB *DB) createObject(addr common.Address) (newobj, prev *stateObject) {
prev = stateDB.getStateObject(addr) prev = stateDB.getStateObject(addr)
newobj = newObject(stateDB, addr, Account{}) newobj = newObject(stateDB, addr, Account{})
newobj.setNonce(0) // sets the object to dirty newobj.setNonce(0) // sets the object to dirty
@ -482,7 +482,7 @@ func (stateDB *StateDB) createObject(addr common.Address) (newobj, prev *stateOb
// 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1) // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
// //
// Carrying over the balance ensures that Ether doesn't disappear. // Carrying over the balance ensures that Ether doesn't disappear.
func (stateDB *StateDB) CreateAccount(addr common.Address) { func (stateDB *DB) CreateAccount(addr common.Address) {
new, prev := stateDB.createObject(addr) new, prev := stateDB.createObject(addr)
if prev != nil { if prev != nil {
new.setBalance(prev.data.Balance) new.setBalance(prev.data.Balance)
@ -490,7 +490,7 @@ func (stateDB *StateDB) CreateAccount(addr common.Address) {
} }
// ForEachStorage runs a function on every item in state DB. // ForEachStorage runs a function on every item in state DB.
func (stateDB *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) { func (stateDB *DB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) {
so := stateDB.getStateObject(addr) so := stateDB.getStateObject(addr)
if so == nil { if so == nil {
return return
@ -508,12 +508,12 @@ func (stateDB *StateDB) ForEachStorage(addr common.Address, cb func(key, value c
// Copy creates a deep, independent copy of the state. // Copy creates a deep, independent copy of the state.
// Snapshots of the copied state cannot be applied to the copy. // Snapshots of the copied state cannot be applied to the copy.
func (stateDB *StateDB) Copy() *StateDB { func (stateDB *DB) Copy() *DB {
stateDB.lock.Lock() stateDB.lock.Lock()
defer stateDB.lock.Unlock() defer stateDB.lock.Unlock()
// Copy all the basic fields, initialize the memory ones // Copy all the basic fields, initialize the memory ones
state := &StateDB{ state := &DB{
db: stateDB.db, db: stateDB.db,
trie: stateDB.db.CopyTrie(stateDB.trie), trie: stateDB.db.CopyTrie(stateDB.trie),
stateObjects: make(map[common.Address]*stateObject, len(stateDB.journal.dirties)), stateObjects: make(map[common.Address]*stateObject, len(stateDB.journal.dirties)),
@ -559,7 +559,7 @@ func (stateDB *StateDB) Copy() *StateDB {
} }
// Snapshot returns an identifier for the current revision of the state. // Snapshot returns an identifier for the current revision of the state.
func (stateDB *StateDB) Snapshot() int { func (stateDB *DB) Snapshot() int {
id := stateDB.nextRevisionID id := stateDB.nextRevisionID
stateDB.nextRevisionID++ stateDB.nextRevisionID++
stateDB.validRevisions = append(stateDB.validRevisions, revision{id, stateDB.journal.length()}) stateDB.validRevisions = append(stateDB.validRevisions, revision{id, stateDB.journal.length()})
@ -567,7 +567,7 @@ func (stateDB *StateDB) Snapshot() int {
} }
// RevertToSnapshot reverts all state changes made since the given revision. // RevertToSnapshot reverts all state changes made since the given revision.
func (stateDB *StateDB) RevertToSnapshot(revid int) { func (stateDB *DB) RevertToSnapshot(revid int) {
// Find the snapshot in the stack of valid snapshots. // Find the snapshot in the stack of valid snapshots.
idx := sort.Search(len(stateDB.validRevisions), func(i int) bool { idx := sort.Search(len(stateDB.validRevisions), func(i int) bool {
return stateDB.validRevisions[i].id >= revid return stateDB.validRevisions[i].id >= revid
@ -583,13 +583,13 @@ func (stateDB *StateDB) RevertToSnapshot(revid int) {
} }
// GetRefund returns the current value of the refund counter. // GetRefund returns the current value of the refund counter.
func (stateDB *StateDB) GetRefund() uint64 { func (stateDB *DB) GetRefund() uint64 {
return stateDB.refund return stateDB.refund
} }
// Finalise finalises the state by removing the self destructed objects // Finalise finalises the state by removing the self destructed objects
// and clears the journal as well as the refunds. // and clears the journal as well as the refunds.
func (stateDB *StateDB) Finalise(deleteEmptyObjects bool) { func (stateDB *DB) Finalise(deleteEmptyObjects bool) {
for addr := range stateDB.journal.dirties { for addr := range stateDB.journal.dirties {
stateObject, exist := stateDB.stateObjects[addr] stateObject, exist := stateDB.stateObjects[addr]
if !exist { if !exist {
@ -617,27 +617,27 @@ func (stateDB *StateDB) Finalise(deleteEmptyObjects bool) {
// IntermediateRoot computes the current root hash of the state trie. // IntermediateRoot computes the current root hash of the state trie.
// It is called in between transactions to get the root hash that // It is called in between transactions to get the root hash that
// goes into transaction receipts. // goes into transaction receipts.
func (stateDB *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash { func (stateDB *DB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
stateDB.Finalise(deleteEmptyObjects) stateDB.Finalise(deleteEmptyObjects)
return stateDB.trie.Hash() return stateDB.trie.Hash()
} }
// Prepare sets the current transaction hash and index and block hash which is // Prepare sets the current transaction hash and index and block hash which is
// used when the EVM emits new state logs. // used when the EVM emits new state logs.
func (stateDB *StateDB) Prepare(thash, bhash common.Hash, ti int) { func (stateDB *DB) Prepare(thash, bhash common.Hash, ti int) {
stateDB.thash = thash stateDB.thash = thash
stateDB.bhash = bhash stateDB.bhash = bhash
stateDB.txIndex = ti stateDB.txIndex = ti
} }
func (stateDB *StateDB) clearJournalAndRefund() { func (stateDB *DB) clearJournalAndRefund() {
stateDB.journal = newJournal() stateDB.journal = newJournal()
stateDB.validRevisions = stateDB.validRevisions[:0] stateDB.validRevisions = stateDB.validRevisions[:0]
stateDB.refund = 0 stateDB.refund = 0
} }
// Commit writes the state to the underlying in-memory trie database. // Commit writes the state to the underlying in-memory trie database.
func (stateDB *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) { func (stateDB *DB) Commit(deleteEmptyObjects bool) (root common.Hash, err error) {
defer stateDB.clearJournalAndRefund() defer stateDB.clearJournalAndRefund()
for addr := range stateDB.journal.dirties { for addr := range stateDB.journal.dirties {

@ -71,7 +71,7 @@ func TestIntermediateLeaks(t *testing.T) {
transState, _ := New(common.Hash{}, NewDatabase(transDb)) transState, _ := New(common.Hash{}, NewDatabase(transDb))
finalState, _ := New(common.Hash{}, NewDatabase(finalDb)) finalState, _ := New(common.Hash{}, NewDatabase(finalDb))
modify := func(state *StateDB, addr common.Address, i, tweak byte) { modify := func(state *DB, addr common.Address, i, tweak byte) {
state.SetBalance(addr, big.NewInt(int64(11*i)+int64(tweak))) state.SetBalance(addr, big.NewInt(int64(11*i)+int64(tweak)))
state.SetNonce(addr, uint64(42*i+tweak)) state.SetNonce(addr, uint64(42*i+tweak))
if i%2 == 0 { if i%2 == 0 {
@ -178,7 +178,7 @@ func TestSnapshotRandom(t *testing.T) {
} }
} }
// A snapshotTest checks that reverting StateDB snapshots properly undoes all changes // A snapshotTest checks that reverting DB snapshots properly undoes all changes
// captured by the snapshot. Instances of this test with pseudorandom content are created // captured by the snapshot. Instances of this test with pseudorandom content are created
// by Generate. // by Generate.
// //
@ -198,7 +198,7 @@ type snapshotTest struct {
type testAction struct { type testAction struct {
name string name string
fn func(testAction, *StateDB) fn func(testAction, *DB)
args []int64 args []int64
noAddr bool noAddr bool
} }
@ -208,28 +208,28 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction {
actions := []testAction{ actions := []testAction{
{ {
name: "SetBalance", name: "SetBalance",
fn: func(a testAction, s *StateDB) { fn: func(a testAction, s *DB) {
s.SetBalance(addr, big.NewInt(a.args[0])) s.SetBalance(addr, big.NewInt(a.args[0]))
}, },
args: make([]int64, 1), args: make([]int64, 1),
}, },
{ {
name: "AddBalance", name: "AddBalance",
fn: func(a testAction, s *StateDB) { fn: func(a testAction, s *DB) {
s.AddBalance(addr, big.NewInt(a.args[0])) s.AddBalance(addr, big.NewInt(a.args[0]))
}, },
args: make([]int64, 1), args: make([]int64, 1),
}, },
{ {
name: "SetNonce", name: "SetNonce",
fn: func(a testAction, s *StateDB) { fn: func(a testAction, s *DB) {
s.SetNonce(addr, uint64(a.args[0])) s.SetNonce(addr, uint64(a.args[0]))
}, },
args: make([]int64, 1), args: make([]int64, 1),
}, },
{ {
name: "SetState", name: "SetState",
fn: func(a testAction, s *StateDB) { fn: func(a testAction, s *DB) {
var key, val common.Hash var key, val common.Hash
binary.BigEndian.PutUint16(key[:], uint16(a.args[0])) binary.BigEndian.PutUint16(key[:], uint16(a.args[0]))
binary.BigEndian.PutUint16(val[:], uint16(a.args[1])) binary.BigEndian.PutUint16(val[:], uint16(a.args[1]))
@ -239,7 +239,7 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction {
}, },
{ {
name: "SetCode", name: "SetCode",
fn: func(a testAction, s *StateDB) { fn: func(a testAction, s *DB) {
code := make([]byte, 16) code := make([]byte, 16)
binary.BigEndian.PutUint64(code, uint64(a.args[0])) binary.BigEndian.PutUint64(code, uint64(a.args[0]))
binary.BigEndian.PutUint64(code[8:], uint64(a.args[1])) binary.BigEndian.PutUint64(code[8:], uint64(a.args[1]))
@ -249,19 +249,19 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction {
}, },
{ {
name: "CreateAccount", name: "CreateAccount",
fn: func(a testAction, s *StateDB) { fn: func(a testAction, s *DB) {
s.CreateAccount(addr) s.CreateAccount(addr)
}, },
}, },
{ {
name: "Suicide", name: "Suicide",
fn: func(a testAction, s *StateDB) { fn: func(a testAction, s *DB) {
s.Suicide(addr) s.Suicide(addr)
}, },
}, },
{ {
name: "AddRefund", name: "AddRefund",
fn: func(a testAction, s *StateDB) { fn: func(a testAction, s *DB) {
s.AddRefund(uint64(a.args[0])) s.AddRefund(uint64(a.args[0]))
}, },
args: make([]int64, 1), args: make([]int64, 1),
@ -269,7 +269,7 @@ func newTestAction(addr common.Address, r *rand.Rand) testAction {
}, },
{ {
name: "AddLog", name: "AddLog",
fn: func(a testAction, s *StateDB) { fn: func(a testAction, s *DB) {
data := make([]byte, 2) data := make([]byte, 2)
binary.BigEndian.PutUint16(data, uint16(a.args[0])) binary.BigEndian.PutUint16(data, uint16(a.args[0]))
s.AddLog(&types.Log{Address: addr, Data: data}) s.AddLog(&types.Log{Address: addr, Data: data})
@ -361,7 +361,7 @@ func (test *snapshotTest) run() bool {
} }
// checkEqual checks that methods of state and checkstate return the same values. // checkEqual checks that methods of state and checkstate return the same values.
func (test *snapshotTest) checkEqual(state, checkstate *StateDB) error { func (test *snapshotTest) checkEqual(state, checkstate *DB) error {
for _, addr := range test.addrs { for _, addr := range test.addrs {
var err error var err error
checkeq := func(op string, a, b interface{}) bool { checkeq := func(op string, a, b interface{}) bool {

@ -52,7 +52,7 @@ func NewStateProcessor(config *params.ChainConfig, bc *BlockChain, engine consen
// Process returns the receipts and logs accumulated during the process and // Process returns the receipts and logs accumulated during the process and
// returns the amount of gas that was used in the process. If any of the // returns the amount of gas that was used in the process. If any of the
// transactions failed to execute due to insufficient gas it will return an error. // transactions failed to execute due to insufficient gas it will return an error.
func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) { func (p *StateProcessor) Process(block *types.Block, statedb *state.DB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) {
var ( var (
receipts types.Receipts receipts types.Receipts
usedGas = new(uint64) usedGas = new(uint64)
@ -84,7 +84,7 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
// and uses the input parameters for its environment. It returns the receipt // and uses the input parameters for its environment. It returns the receipt
// for the transaction, gas used and an error if the transaction failed, // for the transaction, gas used and an error if the transaction failed,
// indicating the block was invalid. // indicating the block was invalid.
func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.StateDB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, error) { func ApplyTransaction(config *params.ChainConfig, bc ChainContext, author *common.Address, gp *GasPool, statedb *state.DB, header *types.Header, tx *types.Transaction, usedGas *uint64, cfg vm.Config) (*types.Receipt, uint64, error) {
msg, err := tx.AsMessage(types.MakeSigner(config, header.Number)) msg, err := tx.AsMessage(types.MakeSigner(config, header.Number))
if err != nil { if err != nil {
return nil, 0, err return nil, 0, err

@ -117,7 +117,7 @@ const (
type blockChain interface { type blockChain interface {
CurrentBlock() *types.Block CurrentBlock() *types.Block
GetBlock(hash common.Hash, number uint64) *types.Block GetBlock(hash common.Hash, number uint64) *types.Block
StateAt(root common.Hash) (*state.StateDB, error) StateAt(root common.Hash) (*state.DB, error)
SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription
} }
@ -195,7 +195,7 @@ type TxPool struct {
signer types.Signer signer types.Signer
mu sync.RWMutex mu sync.RWMutex
currentState *state.StateDB // Current state in the blockchain head currentState *state.DB // Current state in the blockchain head
pendingState *state.ManagedState // Pending state tracking virtual nonces pendingState *state.ManagedState // Pending state tracking virtual nonces
currentMaxGas uint64 // Current gas limit for transaction caps currentMaxGas uint64 // Current gas limit for transaction caps

@ -45,7 +45,7 @@ func init() {
} }
type testBlockChain struct { type testBlockChain struct {
statedb *state.StateDB statedb *state.DB
gasLimit uint64 gasLimit uint64
chainHeadFeed *event.Feed chainHeadFeed *event.Feed
} }
@ -60,7 +60,7 @@ func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *types.Block
return bc.CurrentBlock() return bc.CurrentBlock()
} }
func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, error) { func (bc *testBlockChain) StateAt(common.Hash) (*state.DB, error) {
return bc.statedb, nil return bc.statedb, nil
} }
@ -157,7 +157,7 @@ type testChain struct {
// testChain.State() is used multiple times to reset the pending state. // testChain.State() is used multiple times to reset the pending state.
// when simulate is true it will create a state that indicates // when simulate is true it will create a state that indicates
// that tx0 and tx1 are included in the chain. // that tx0 and tx1 are included in the chain.
func (c *testChain) State() (*state.StateDB, error) { func (c *testChain) State() (*state.DB, error) {
// delay "state change" by one. The tx pool fetches the // delay "state change" by one. The tx pool fetches the
// state multiple times and by delaying it a bit we simulate // state multiple times and by delaying it a bit we simulate
// a state change between those fetches. // a state change between those fetches.

@ -32,7 +32,7 @@ type Validator interface {
// ValidateState validates the given statedb and optionally the receipts and // ValidateState validates the given statedb and optionally the receipts and
// gas used. // gas used.
ValidateState(block, parent *types.Block, state *state.StateDB, receipts types.Receipts, usedGas uint64) error ValidateState(block, parent *types.Block, state *state.DB, receipts types.Receipts, usedGas uint64) error
} }
// Processor is an interface for processing blocks using a given initial state. // Processor is an interface for processing blocks using a given initial state.
@ -42,5 +42,5 @@ type Validator interface {
// of gas used in the process and return an error if any of the internal rules // of gas used in the process and return an error if any of the internal rules
// failed. // failed.
type Processor interface { type Processor interface {
Process(block *types.Block, statedb *state.StateDB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error) Process(block *types.Block, statedb *state.DB, cfg vm.Config) (types.Receipts, []*types.Log, uint64, error)
} }

@ -43,7 +43,7 @@ func (d *dummyContractRef) SetNonce(uint64) {}
func (d *dummyContractRef) Balance() *big.Int { return new(big.Int) } func (d *dummyContractRef) Balance() *big.Int { return new(big.Int) }
type dummyStatedb struct { type dummyStatedb struct {
state.StateDB state.DB
} }
// GetRefund ... // GetRefund ...

@ -44,7 +44,7 @@ type Config struct {
Debug bool Debug bool
EVMConfig vm.Config EVMConfig vm.Config
State *state.StateDB State *state.DB
GetHashFn func(n uint64) common.Hash GetHashFn func(n uint64) common.Hash
} }
@ -92,7 +92,7 @@ func setDefaults(cfg *Config) {
// //
// Executes sets up a in memory, temporarily, environment for the execution of // Executes sets up a in memory, temporarily, environment for the execution of
// the given code. It makes sure that it's restored to it's original state afterwards. // the given code. It makes sure that it's restored to it's original state afterwards.
func Execute(code, input []byte, cfg *Config) ([]byte, *state.StateDB, error) { func Execute(code, input []byte, cfg *Config) ([]byte, *state.DB, error) {
if cfg == nil { if cfg == nil {
cfg = new(Config) cfg = new(Config)
} }

@ -17,8 +17,8 @@ import (
// environment is the worker's current environment and holds all of the current state information. // environment is the worker's current environment and holds all of the current state information.
type environment struct { type environment struct {
state *state.StateDB // apply state changes here state *state.DB // apply state changes here
gasPool *core.GasPool // available gas used to pack transactions gasPool *core.GasPool // available gas used to pack transactions
header *types.Header header *types.Header
txs []*types.Transaction txs []*types.Transaction
@ -136,7 +136,7 @@ func (w *Worker) makeCurrent(parent *types.Block, header *types.Header) error {
} }
// GetCurrentState gets the current state. // GetCurrentState gets the current state.
func (w *Worker) GetCurrentState() *state.StateDB { func (w *Worker) GetCurrentState() *state.DB {
return w.current.state return w.current.state
} }

Loading…
Cancel
Save