Skip to content

Commit d62d5fe

Browse files
committed
accounts/abi/bind: use ethereum interfaces
In this commit, contract bindings and their backend start using the Ethereum Go API interfaces offered by ethclient. This makes ethclient a suitable replacement for the old remote backend and gets us one step closer to the final stable Go API that is planned for go-ethereum 1.5. The changes in detail: * Pending state is optional for read only contract bindings. BoundContract attempts to discover the Pending* methods via an interface assertion. There are a couple of advantages to this: ContractCaller is just two methods and can be implemented on top of pretty much anything that provides Ethereum data. Since the backend interfaces are now disjoint, ContractBackend can simply be declared as a union of the reader and writer side. * Caching of HasCode is removed. The caching could go wrong in case of chain reorganisations and removing it simplifies the code a lot. We'll figure out a performant way of providing ErrNoCode before the 1.5 release. * BoundContract now ensures that the backend receives a non-nil context with every call.
1 parent 056f15a commit d62d5fe

4 files changed

Lines changed: 204 additions & 220 deletions

File tree

‎accounts/abi/bind/backend.go‎

Lines changed: 35 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -20,93 +20,68 @@ import (
2020
"errors"
2121
"math/big"
2222

23+
"github.com/ethereum/go-ethereum"
2324
"github.com/ethereum/go-ethereum/common"
2425
"github.com/ethereum/go-ethereum/core/types"
2526
"golang.org/x/net/context"
2627
)
2728

28-
// ErrNoCode is returned by call and transact operations for which the requested
29-
// recipient contract to operate on does not exist in the state db or does not
30-
// have any code associated with it (i.e. suicided).
31-
var ErrNoCode = errors.New("no contract code at given address")
29+
var (
30+
// ErrNoCode is returned by call and transact operations for which the requested
31+
// recipient contract to operate on does not exist in the state db or does not
32+
// have any code associated with it (i.e. suicided).
33+
ErrNoCode = errors.New("no contract code at given address")
34+
35+
// This error is raised when attempting to perform a pending state action
36+
// on a backend that doesn't implement PendingContractCaller.
37+
ErrNoPendingState = errors.New("backend does not support pending state")
38+
)
3239

3340
// ContractCaller defines the methods needed to allow operating with contract on a read
3441
// only basis.
3542
type ContractCaller interface {
36-
// HasCode checks if the contract at the given address has any code associated
37-
// with it or not. This is needed to differentiate between contract internal
38-
// errors and the local chain being out of sync.
39-
HasCode(ctx context.Context, contract common.Address, pending bool) (bool, error)
43+
// CodeAt returns the code of the given account. This is needed to differentiate
44+
// between contract internal errors and the local chain being out of sync.
45+
CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error)
46+
// ContractCall executes an Ethereum contract call with the specified data as the
47+
// input.
48+
CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error)
49+
}
4050

41-
// ContractCall executes an Ethereum contract call with the specified data as
42-
// the input. The pending flag requests execution against the pending block, not
43-
// the stable head of the chain.
44-
ContractCall(ctx context.Context, contract common.Address, data []byte, pending bool) ([]byte, error)
51+
// PendingContractCaller defines methods to perform contract calls on the pending state.
52+
// Call will try to discover this interface when access to the pending state is requested.
53+
// If the backend does not support the pending state, Call returns ErrNoPendingState.
54+
type PendingContractCaller interface {
55+
// PendingCodeAt returns the code of the given account in the pending state.
56+
PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error)
57+
// PendingCallContract executes an Ethereum contract call against the pending state.
58+
PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error)
4559
}
4660

4761
// ContractTransactor defines the methods needed to allow operating with contract
4862
// on a write only basis. Beside the transacting method, the remainder are helpers
4963
// used when the user does not provide some needed values, but rather leaves it up
5064
// to the transactor to decide.
5165
type ContractTransactor interface {
52-
// PendingAccountNonce retrieves the current pending nonce associated with an
53-
// account.
54-
PendingAccountNonce(ctx context.Context, account common.Address) (uint64, error)
55-
66+
// PendingCodeAt returns the code of the given account in the pending state.
67+
PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
68+
// PendingNonceAt retrieves the current pending nonce associated with an account.
69+
PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
5670
// SuggestGasPrice retrieves the currently suggested gas price to allow a timely
5771
// execution of a transaction.
5872
SuggestGasPrice(ctx context.Context) (*big.Int, error)
59-
60-
// HasCode checks if the contract at the given address has any code associated
61-
// with it or not. This is needed to differentiate between contract internal
62-
// errors and the local chain being out of sync.
63-
HasCode(ctx context.Context, contract common.Address, pending bool) (bool, error)
64-
65-
// EstimateGasLimit tries to estimate the gas needed to execute a specific
73+
// EstimateGas tries to estimate the gas needed to execute a specific
6674
// transaction based on the current pending state of the backend blockchain.
6775
// There is no guarantee that this is the true gas limit requirement as other
6876
// transactions may be added or removed by miners, but it should provide a basis
6977
// for setting a reasonable default.
70-
EstimateGasLimit(ctx context.Context, sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error)
71-
78+
EstimateGas(ctx context.Context, call ethereum.CallMsg) (usedGas *big.Int, err error)
7279
// SendTransaction injects the transaction into the pending pool for execution.
7380
SendTransaction(ctx context.Context, tx *types.Transaction) error
7481
}
7582

76-
// ContractBackend defines the methods needed to allow operating with contract
77-
// on a read-write basis.
78-
//
79-
// This interface is essentially the union of ContractCaller and ContractTransactor
80-
// but due to a bug in the Go compiler (https://github.com/golang/go/issues/6977),
81-
// we cannot simply list it as the two interfaces. The other solution is to add a
82-
// third interface containing the common methods, but that convolutes the user API
83-
// as it introduces yet another parameter to require for initialization.
83+
// ContractBackend defines the methods needed to work with contracts on a read-write basis.
8484
type ContractBackend interface {
85-
// HasCode checks if the contract at the given address has any code associated
86-
// with it or not. This is needed to differentiate between contract internal
87-
// errors and the local chain being out of sync.
88-
HasCode(ctx context.Context, contract common.Address, pending bool) (bool, error)
89-
90-
// ContractCall executes an Ethereum contract call with the specified data as
91-
// the input. The pending flag requests execution against the pending block, not
92-
// the stable head of the chain.
93-
ContractCall(ctx context.Context, contract common.Address, data []byte, pending bool) ([]byte, error)
94-
95-
// PendingAccountNonce retrieves the current pending nonce associated with an
96-
// account.
97-
PendingAccountNonce(ctx context.Context, account common.Address) (uint64, error)
98-
99-
// SuggestGasPrice retrieves the currently suggested gas price to allow a timely
100-
// execution of a transaction.
101-
SuggestGasPrice(ctx context.Context) (*big.Int, error)
102-
103-
// EstimateGasLimit tries to estimate the gas needed to execute a specific
104-
// transaction based on the current pending state of the backend blockchain.
105-
// There is no guarantee that this is the true gas limit requirement as other
106-
// transactions may be added or removed by miners, but it should provide a basis
107-
// for setting a reasonable default.
108-
EstimateGasLimit(ctx context.Context, sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error)
109-
110-
// SendTransaction injects the transaction into the pending pool for execution.
111-
SendTransaction(ctx context.Context, tx *types.Transaction) error
85+
ContractCaller
86+
ContractTransactor
11287
}

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

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

1919
import (
20+
"fmt"
2021
"math/big"
2122

23+
"github.com/ethereum/go-ethereum"
2224
"github.com/ethereum/go-ethereum/accounts/abi/bind"
2325
"github.com/ethereum/go-ethereum/common"
2426
"github.com/ethereum/go-ethereum/core"
@@ -79,58 +81,44 @@ func (b *SimulatedBackend) Rollback() {
7981
b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
8082
}
8183

82-
// HasCode implements ContractVerifier.HasCode, checking whether there is any
83-
// code associated with a certain account in the blockchain.
84-
func (b *SimulatedBackend) HasCode(ctx context.Context, contract common.Address, pending bool) (bool, error) {
85-
if pending {
86-
return len(b.pendingState.GetCode(contract)) > 0, nil
84+
// CodeAt implements ChainStateReader.CodeAt, returning the code associated with
85+
// a certain account at a given block number in the blockchain.
86+
func (b *SimulatedBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) {
87+
if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
88+
return nil, fmt.Errorf("SimulatedBackend cannot access blocks other than the latest block")
8789
}
8890
statedb, _ := b.blockchain.State()
89-
return len(statedb.GetCode(contract)) > 0, nil
91+
return statedb.GetCode(contract), nil
9092
}
9193

92-
// ContractCall implements ContractCaller.ContractCall, executing the specified
93-
// contract with the given input data.
94-
func (b *SimulatedBackend) ContractCall(ctx context.Context, contract common.Address, data []byte, pending bool) ([]byte, error) {
95-
// Create a copy of the current state db to screw around with
96-
var (
97-
block *types.Block
98-
statedb *state.StateDB
99-
)
100-
if pending {
101-
block, statedb = b.pendingBlock, b.pendingState.Copy()
102-
} else {
103-
block = b.blockchain.CurrentBlock()
104-
statedb, _ = b.blockchain.State()
105-
}
106-
// If there's no code to interact with, respond with an appropriate error
107-
if code := statedb.GetCode(contract); len(code) == 0 {
108-
return nil, bind.ErrNoCode
109-
}
110-
// Set infinite balance to the a fake caller account
111-
from := statedb.GetOrNewStateObject(common.Address{})
112-
from.SetBalance(common.MaxBig)
94+
// PendingCodeAt implements PendingStateReader.PendingCodeAt, returning the
95+
// code associated with a certain account in the pending state of the blockchain.
96+
func (b *SimulatedBackend) PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) {
97+
return b.pendingState.GetCode(contract), nil
98+
}
11399

114-
// Assemble the call invocation to measure the gas usage
115-
msg := callmsg{
116-
from: from,
117-
to: &contract,
118-
gasPrice: new(big.Int),
119-
gasLimit: common.MaxBig,
120-
value: new(big.Int),
121-
data: data,
100+
// CallContract executes a contract call.
101+
func (b *SimulatedBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) {
102+
if blockNumber != nil && blockNumber.Cmp(b.blockchain.CurrentBlock().Number()) != 0 {
103+
return nil, fmt.Errorf("SimulatedBackend cannot access blocks other than the latest block")
122104
}
123-
// Execute the call and return
124-
vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
125-
gaspool := new(core.GasPool).AddGas(common.MaxBig)
105+
state, err := b.blockchain.State()
106+
if err != nil {
107+
return nil, err
108+
}
109+
rval, _, err := b.callContract(ctx, call, b.blockchain.CurrentBlock(), state)
110+
return rval, err
111+
}
126112

127-
out, _, err := core.ApplyMessage(vmenv, msg, gaspool)
128-
return out, err
113+
// PendingCallContract executes a contract call on the pending state.
114+
func (b *SimulatedBackend) PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) {
115+
rval, _, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState.Copy())
116+
return rval, err
129117
}
130118

131-
// PendingAccountNonce implements ContractTransactor.PendingAccountNonce, retrieving
119+
// PendingNonceAt implements PendingStateReader.PendingNonceAt, retrieving
132120
// the nonce currently pending for the account.
133-
func (b *SimulatedBackend) PendingAccountNonce(ctx context.Context, account common.Address) (uint64, error) {
121+
func (b *SimulatedBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) {
134122
return b.pendingState.GetOrNewStateObject(account).Nonce(), nil
135123
}
136124

@@ -140,45 +128,49 @@ func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error
140128
return big.NewInt(1), nil
141129
}
142130

143-
// EstimateGasLimit implements ContractTransactor.EstimateGasLimit, executing the
144-
// requested code against the currently pending block/state and returning the used
145-
// gas.
146-
func (b *SimulatedBackend) EstimateGasLimit(ctx context.Context, sender common.Address, contract *common.Address, value *big.Int, data []byte) (*big.Int, error) {
147-
// Create a copy of the currently pending state db to screw around with
148-
var (
149-
block = b.pendingBlock
150-
statedb = b.pendingState.Copy()
151-
)
152-
// If there's no code to interact with, respond with an appropriate error
153-
if contract != nil {
154-
if code := statedb.GetCode(*contract); len(code) == 0 {
155-
return nil, bind.ErrNoCode
156-
}
157-
}
158-
// Set infinite balance to the a fake caller account
159-
from := statedb.GetOrNewStateObject(sender)
160-
from.SetBalance(common.MaxBig)
131+
// EstimateGas executes the requested code against the currently pending block/state and
132+
// returns the used amount of gas.
133+
func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (*big.Int, error) {
134+
_, gas, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState.Copy())
135+
return gas, err
136+
}
161137

162-
// Assemble the call invocation to measure the gas usage
163-
msg := callmsg{
164-
from: from,
165-
to: contract,
166-
gasPrice: new(big.Int),
167-
gasLimit: common.MaxBig,
168-
value: value,
169-
data: data,
138+
// callContract implemens common code between normal and pending contract calls.
139+
// state is modified during execution, make sure to copy it if necessary.
140+
func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, *big.Int, error) {
141+
// Ensure message is initialized properly.
142+
if call.GasPrice == nil {
143+
call.GasPrice = big.NewInt(1)
144+
}
145+
if call.Gas == nil || call.Gas.BitLen() == 0 {
146+
call.Gas = big.NewInt(50000000)
170147
}
171-
// Execute the call and return
148+
if call.Value == nil {
149+
call.Value = new(big.Int)
150+
}
151+
// Set infinite balance to the fake caller account.
152+
from := statedb.GetOrNewStateObject(call.From)
153+
from.SetBalance(common.MaxBig)
154+
// Execute the call.
155+
msg := callmsg{call}
172156
vmenv := core.NewEnv(statedb, chainConfig, b.blockchain, msg, block.Header(), vm.Config{})
173157
gaspool := new(core.GasPool).AddGas(common.MaxBig)
174-
175-
_, gas, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
176-
return gas, err
158+
ret, gasUsed, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
159+
return ret, gasUsed, err
177160
}
178161

179-
// SendTransaction implements ContractTransactor.SendTransaction, delegating the raw
180-
// transaction injection to the remote node.
162+
// SendTransaction updates the pending block to include the given transaction.
163+
// It panics if the transaction is invalid.
181164
func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transaction) error {
165+
sender, err := tx.From()
166+
if err != nil {
167+
panic(fmt.Errorf("invalid transaction: %v", err))
168+
}
169+
nonce := b.pendingState.GetNonce(sender)
170+
if tx.Nonce() != nonce {
171+
panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce))
172+
}
173+
182174
blocks, _ := core.GenerateChain(nil, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) {
183175
for _, tx := range b.pendingBlock.Transactions() {
184176
block.AddTx(tx)
@@ -187,26 +179,20 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transa
187179
})
188180
b.pendingBlock = blocks[0]
189181
b.pendingState, _ = state.New(b.pendingBlock.Root(), b.database)
190-
191182
return nil
192183
}
193184

194185
// callmsg implements core.Message to allow passing it as a transaction simulator.
195186
type callmsg struct {
196-
from *state.StateObject
197-
to *common.Address
198-
gasLimit *big.Int
199-
gasPrice *big.Int
200-
value *big.Int
201-
data []byte
187+
ethereum.CallMsg
202188
}
203189

204-
func (m callmsg) From() (common.Address, error) { return m.from.Address(), nil }
205-
func (m callmsg) FromFrontier() (common.Address, error) { return m.from.Address(), nil }
190+
func (m callmsg) From() (common.Address, error) { return m.CallMsg.From, nil }
191+
func (m callmsg) FromFrontier() (common.Address, error) { return m.CallMsg.From, nil }
206192
func (m callmsg) Nonce() uint64 { return 0 }
207193
func (m callmsg) CheckNonce() bool { return false }
208-
func (m callmsg) To() *common.Address { return m.to }
209-
func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
210-
func (m callmsg) Gas() *big.Int { return m.gasLimit }
211-
func (m callmsg) Value() *big.Int { return m.value }
212-
func (m callmsg) Data() []byte { return m.data }
194+
func (m callmsg) To() *common.Address { return m.CallMsg.To }
195+
func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
196+
func (m callmsg) Gas() *big.Int { return m.CallMsg.Gas }
197+
func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
198+
func (m callmsg) Data() []byte { return m.CallMsg.Data }

0 commit comments

Comments
 (0)