1717package backends
1818
1919import (
20+ "errors"
2021 "fmt"
2122 "math/big"
23+ "sync"
2224
2325 "github.com/ethereum/go-ethereum"
2426 "github.com/ethereum/go-ethereum/accounts/abi/bind"
@@ -38,12 +40,15 @@ var chainConfig = &core.ChainConfig{HomesteadBlock: big.NewInt(0)}
3840// This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
3941var _ bind.ContractBackend = (* SimulatedBackend )(nil )
4042
43+ var errBlockNumberUnsupported = errors .New ("SimulatedBackend cannot access blocks other than the latest block" )
44+
4145// SimulatedBackend implements bind.ContractBackend, simulating a blockchain in
4246// the background. Its main purpose is to allow easily testing contract bindings.
4347type SimulatedBackend struct {
4448 database ethdb.Database // In memory database to store our testing data
4549 blockchain * core.BlockChain // Ethereum blockchain to handle the consensus
4650
51+ mu sync.Mutex
4752 pendingBlock * types.Block // Currently pending block that will be imported on request
4853 pendingState * state.StateDB // Currently pending state that will be the active on on request
4954}
@@ -54,53 +59,109 @@ func NewSimulatedBackend(accounts ...core.GenesisAccount) *SimulatedBackend {
5459 database , _ := ethdb .NewMemDatabase ()
5560 core .WriteGenesisBlockForTesting (database , accounts ... )
5661 blockchain , _ := core .NewBlockChain (database , chainConfig , new (core.FakePow ), new (event.TypeMux ))
57-
58- backend := & SimulatedBackend {
59- database : database ,
60- blockchain : blockchain ,
61- }
62- backend .Rollback ()
63-
62+ backend := & SimulatedBackend {database : database , blockchain : blockchain }
63+ backend .rollback ()
6464 return backend
6565}
6666
6767// Commit imports all the pending transactions as a single block and starts a
6868// fresh new state.
6969func (b * SimulatedBackend ) Commit () {
70+ b .mu .Lock ()
71+ defer b .mu .Unlock ()
72+
7073 if _ , err := b .blockchain .InsertChain ([]* types.Block {b .pendingBlock }); err != nil {
7174 panic (err ) // This cannot happen unless the simulator is wrong, fail in that case
7275 }
73- b .Rollback ()
76+ b .rollback ()
7477}
7578
7679// Rollback aborts all pending transactions, reverting to the last committed state.
7780func (b * SimulatedBackend ) Rollback () {
78- blocks , _ := core .GenerateChain (nil , b .blockchain .CurrentBlock (), b .database , 1 , func (int , * core.BlockGen ) {})
81+ b .mu .Lock ()
82+ defer b .mu .Unlock ()
83+
84+ b .rollback ()
85+ }
7986
87+ func (b * SimulatedBackend ) rollback () {
88+ blocks , _ := core .GenerateChain (nil , b .blockchain .CurrentBlock (), b .database , 1 , func (int , * core.BlockGen ) {})
8089 b .pendingBlock = blocks [0 ]
8190 b .pendingState , _ = state .New (b .pendingBlock .Root (), b .database )
8291}
8392
84- // CodeAt implements ChainStateReader.CodeAt, returning the code associated with
85- // a certain account at a given block number in the blockchain.
93+ // CodeAt returns the code associated with a certain account in the blockchain.
8694func (b * SimulatedBackend ) CodeAt (ctx context.Context , contract common.Address , blockNumber * big.Int ) ([]byte , error ) {
95+ b .mu .Lock ()
96+ defer b .mu .Unlock ()
97+
8798 if blockNumber != nil && blockNumber .Cmp (b .blockchain .CurrentBlock ().Number ()) != 0 {
88- return nil , fmt . Errorf ( "SimulatedBackend cannot access blocks other than the latest block" )
99+ return nil , errBlockNumberUnsupported
89100 }
90101 statedb , _ := b .blockchain .State ()
91102 return statedb .GetCode (contract ), nil
92103}
93104
94- // PendingCodeAt implements PendingStateReader.PendingCodeAt, returning the
95- // code associated with a certain account in the pending state of the blockchain.
105+ // BalanceAt returns the wei balance of a certain account in the blockchain.
106+ func (b * SimulatedBackend ) BalanceAt (ctx context.Context , contract common.Address , blockNumber * big.Int ) (* big.Int , error ) {
107+ b .mu .Lock ()
108+ defer b .mu .Unlock ()
109+
110+ if blockNumber != nil && blockNumber .Cmp (b .blockchain .CurrentBlock ().Number ()) != 0 {
111+ return nil , errBlockNumberUnsupported
112+ }
113+ statedb , _ := b .blockchain .State ()
114+ return statedb .GetBalance (contract ), nil
115+ }
116+
117+ // NonceAt returns the nonce of a certain account in the blockchain.
118+ func (b * SimulatedBackend ) NonceAt (ctx context.Context , contract common.Address , blockNumber * big.Int ) (uint64 , error ) {
119+ b .mu .Lock ()
120+ defer b .mu .Unlock ()
121+
122+ if blockNumber != nil && blockNumber .Cmp (b .blockchain .CurrentBlock ().Number ()) != 0 {
123+ return 0 , errBlockNumberUnsupported
124+ }
125+ statedb , _ := b .blockchain .State ()
126+ return statedb .GetNonce (contract ), nil
127+ }
128+
129+ // StorageAt returns the value of key in the storage of an account in the blockchain.
130+ func (b * SimulatedBackend ) StorageAt (ctx context.Context , contract common.Address , key common.Hash , blockNumber * big.Int ) ([]byte , error ) {
131+ b .mu .Lock ()
132+ defer b .mu .Unlock ()
133+
134+ if blockNumber != nil && blockNumber .Cmp (b .blockchain .CurrentBlock ().Number ()) != 0 {
135+ return nil , errBlockNumberUnsupported
136+ }
137+ statedb , _ := b .blockchain .State ()
138+ if obj := statedb .GetStateObject (contract ); obj != nil {
139+ val := obj .GetState (key )
140+ return val [:], nil
141+ }
142+ return nil , nil
143+ }
144+
145+ // TransactionReceipt returns the receipt of a transaction.
146+ func (b * SimulatedBackend ) TransactionReceipt (ctx context.Context , txHash common.Hash ) (* types.Receipt , error ) {
147+ return core .GetReceipt (b .database , txHash ), nil
148+ }
149+
150+ // PendingCodeAt returns the code associated with an account in the pending state.
96151func (b * SimulatedBackend ) PendingCodeAt (ctx context.Context , contract common.Address ) ([]byte , error ) {
152+ b .mu .Lock ()
153+ defer b .mu .Unlock ()
154+
97155 return b .pendingState .GetCode (contract ), nil
98156}
99157
100158// CallContract executes a contract call.
101159func (b * SimulatedBackend ) CallContract (ctx context.Context , call ethereum.CallMsg , blockNumber * big.Int ) ([]byte , error ) {
160+ b .mu .Lock ()
161+ defer b .mu .Unlock ()
162+
102163 if blockNumber != nil && blockNumber .Cmp (b .blockchain .CurrentBlock ().Number ()) != 0 {
103- return nil , fmt . Errorf ( "SimulatedBackend cannot access blocks other than the latest block" )
164+ return nil , errBlockNumberUnsupported
104165 }
105166 state , err := b .blockchain .State ()
106167 if err != nil {
@@ -112,13 +173,19 @@ func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallM
112173
113174// PendingCallContract executes a contract call on the pending state.
114175func (b * SimulatedBackend ) PendingCallContract (ctx context.Context , call ethereum.CallMsg ) ([]byte , error ) {
176+ b .mu .Lock ()
177+ defer b .mu .Unlock ()
178+
115179 rval , _ , err := b .callContract (ctx , call , b .pendingBlock , b .pendingState .Copy ())
116180 return rval , err
117181}
118182
119183// PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
120184// the nonce currently pending for the account.
121185func (b * SimulatedBackend ) PendingNonceAt (ctx context.Context , account common.Address ) (uint64 , error ) {
186+ b .mu .Lock ()
187+ defer b .mu .Unlock ()
188+
122189 return b .pendingState .GetOrNewStateObject (account ).Nonce (), nil
123190}
124191
@@ -131,6 +198,9 @@ func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error
131198// EstimateGas executes the requested code against the currently pending block/state and
132199// returns the used amount of gas.
133200func (b * SimulatedBackend ) EstimateGas (ctx context.Context , call ethereum.CallMsg ) (* big.Int , error ) {
201+ b .mu .Lock ()
202+ defer b .mu .Unlock ()
203+
134204 _ , gas , err := b .callContract (ctx , call , b .pendingBlock , b .pendingState .Copy ())
135205 return gas , err
136206}
@@ -162,6 +232,9 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM
162232// SendTransaction updates the pending block to include the given transaction.
163233// It panics if the transaction is invalid.
164234func (b * SimulatedBackend ) SendTransaction (ctx context.Context , tx * types.Transaction ) error {
235+ b .mu .Lock ()
236+ defer b .mu .Unlock ()
237+
165238 sender , err := tx .From ()
166239 if err != nil {
167240 panic (fmt .Errorf ("invalid transaction: %v" , err ))
0 commit comments