Skip to content

Commit c97df05

Browse files
committed
accounts/abi/bind: add utilities for waiting on transactions
The need for these functions comes up in code that actually deploys and uses contracts. As of this commit, they can be used with both SimulatedBackend and ethclient. SimulatedBackend gains some additional methods in the process and is now safe for concurrent use.
1 parent d62d5fe commit c97df05

4 files changed

Lines changed: 267 additions & 15 deletions

File tree

‎accounts/abi/bind/backend.go‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ var (
3535
// This error is raised when attempting to perform a pending state action
3636
// on a backend that doesn't implement PendingContractCaller.
3737
ErrNoPendingState = errors.New("backend does not support pending state")
38+
39+
// This error is returned by WaitDeployed if contract creation leaves an
40+
// empty contract behind.
41+
ErrNoCodeAfterDeploy = errors.New("no contract code after deployment")
3842
)
3943

4044
// ContractCaller defines the methods needed to allow operating with contract on a read
@@ -48,6 +52,12 @@ type ContractCaller interface {
4852
CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error)
4953
}
5054

55+
// DeployBackend wraps the operations needed by WaitMined and WaitDeployed.
56+
type DeployBackend interface {
57+
TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
58+
CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error)
59+
}
60+
5161
// PendingContractCaller defines methods to perform contract calls on the pending state.
5262
// Call will try to discover this interface when access to the pending state is requested.
5363
// If the backend does not support the pending state, Call returns ErrNoPendingState.

‎accounts/abi/bind/backends/simulated.go‎

Lines changed: 88 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,10 @@
1717
package backends
1818

1919
import (
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.
3941
var _ 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.
4347
type 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.
6969
func (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.
7780
func (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.
8694
func (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.
96151
func (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.
101159
func (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.
114175
func (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.
121185
func (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.
133200
func (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.
164234
func (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))

‎accounts/abi/bind/util.go‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Copyright 2016 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 bind
18+
19+
import (
20+
"fmt"
21+
"time"
22+
23+
"github.com/ethereum/go-ethereum/common"
24+
"github.com/ethereum/go-ethereum/core/types"
25+
"github.com/ethereum/go-ethereum/logger"
26+
"github.com/ethereum/go-ethereum/logger/glog"
27+
"golang.org/x/net/context"
28+
)
29+
30+
// WaitMined waits for tx to be mined on the blockchain.
31+
// It stops waiting when the context is canceled.
32+
func WaitMined(ctx context.Context, b DeployBackend, tx *types.Transaction) (*types.Receipt, error) {
33+
queryTicker := time.NewTicker(1 * time.Second)
34+
defer queryTicker.Stop()
35+
loghash := tx.Hash().Hex()[:8]
36+
for {
37+
receipt, err := b.TransactionReceipt(ctx, tx.Hash())
38+
if receipt != nil {
39+
return receipt, nil
40+
}
41+
if err != nil {
42+
glog.V(logger.Detail).Infof("tx %x error: %v", loghash, err)
43+
} else {
44+
glog.V(logger.Detail).Infof("tx %x not yet mined...", loghash)
45+
}
46+
// Wait for the next round.
47+
select {
48+
case <-ctx.Done():
49+
return nil, ctx.Err()
50+
case <-queryTicker.C:
51+
}
52+
}
53+
}
54+
55+
// WaitDeployed waits for a contract deployment transaction and returns the on-chain
56+
// contract address when it is mined. It stops waiting when ctx is canceled.
57+
func WaitDeployed(ctx context.Context, b DeployBackend, tx *types.Transaction) (common.Address, error) {
58+
if tx.To() != nil {
59+
return common.Address{}, fmt.Errorf("tx is not contract creation")
60+
}
61+
receipt, err := WaitMined(ctx, b, tx)
62+
if err != nil {
63+
return common.Address{}, err
64+
}
65+
if receipt.ContractAddress == (common.Address{}) {
66+
return common.Address{}, fmt.Errorf("zero address")
67+
}
68+
// Check that code has indeed been deployed at the address.
69+
// This matters on pre-Homestead chains: OOG in the constructor
70+
// could leave an empty account behind.
71+
code, err := b.CodeAt(ctx, receipt.ContractAddress, nil)
72+
if err == nil && len(code) == 0 {
73+
err = ErrNoCodeAfterDeploy
74+
}
75+
return receipt.ContractAddress, err
76+
}

‎accounts/abi/bind/util_test.go‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
// Copyright 2016 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 bind_test
18+
19+
import (
20+
"math/big"
21+
"testing"
22+
"time"
23+
24+
"github.com/ethereum/go-ethereum/accounts/abi/bind"
25+
"github.com/ethereum/go-ethereum/accounts/abi/bind/backends"
26+
"github.com/ethereum/go-ethereum/common"
27+
"github.com/ethereum/go-ethereum/core"
28+
"github.com/ethereum/go-ethereum/core/types"
29+
"github.com/ethereum/go-ethereum/crypto"
30+
"golang.org/x/net/context"
31+
)
32+
33+
var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
34+
35+
var waitDeployedTests = map[string]struct {
36+
code string
37+
gas *big.Int
38+
wantAddress common.Address
39+
wantErr error
40+
}{
41+
"successful deploy": {
42+
code: `6060604052600a8060106000396000f360606040526008565b00`,
43+
gas: big.NewInt(3000000),
44+
wantAddress: common.HexToAddress("0x3a220f351252089d385b29beca14e27f204c296a"),
45+
},
46+
"empty code": {
47+
code: ``,
48+
gas: big.NewInt(300000),
49+
wantErr: bind.ErrNoCodeAfterDeploy,
50+
wantAddress: common.HexToAddress("0x3a220f351252089d385b29beca14e27f204c296a"),
51+
},
52+
}
53+
54+
func TestWaitDeployed(t *testing.T) {
55+
for name, test := range waitDeployedTests {
56+
backend := backends.NewSimulatedBackend(core.GenesisAccount{
57+
Address: crypto.PubkeyToAddress(testKey.PublicKey),
58+
Balance: big.NewInt(10000000000),
59+
})
60+
61+
// Create the transaction.
62+
tx := types.NewContractCreation(0, big.NewInt(0), test.gas, big.NewInt(1), common.FromHex(test.code))
63+
tx, _ = tx.SignECDSA(testKey)
64+
65+
// Wait for it to get mined in the background.
66+
var (
67+
err error
68+
address common.Address
69+
mined = make(chan struct{})
70+
ctx = context.Background()
71+
)
72+
go func() {
73+
address, err = bind.WaitDeployed(ctx, backend, tx)
74+
close(mined)
75+
}()
76+
77+
// Send and mine the transaction.
78+
backend.SendTransaction(ctx, tx)
79+
backend.Commit()
80+
81+
select {
82+
case <-mined:
83+
if err != test.wantErr {
84+
t.Errorf("test %q: error mismatch: got %q, want %q", name, err, test.wantErr)
85+
}
86+
if address != test.wantAddress {
87+
t.Errorf("test %q: unexpected contract address %s", name, address.Hex())
88+
}
89+
case <-time.After(2 * time.Second):
90+
t.Errorf("test %q: timeout", name)
91+
}
92+
}
93+
}

0 commit comments

Comments
 (0)