Skip to content

Commit 1bf508b

Browse files
committed
accounts/abi/bind: support event filtering in abigen
1 parent 02aeb3d commit 1bf508b

25 files changed

Lines changed: 2524 additions & 1463 deletions

‎accounts/abi/abi.go‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,6 @@ func (abi *ABI) UnmarshalJSON(data []byte) error {
9797
Type string
9898
Name string
9999
Constant bool
100-
Indexed bool
101100
Anonymous bool
102101
Inputs []Argument
103102
Outputs []Argument

‎accounts/abi/bind/backend.go‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,6 @@ type ContractCaller interface {
5252
CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error)
5353
}
5454

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-
6155
// PendingContractCaller defines methods to perform contract calls on the pending state.
6256
// Call will try to discover this interface when access to the pending state is requested.
6357
// If the backend does not support the pending state, Call returns ErrNoPendingState.
@@ -90,8 +84,29 @@ type ContractTransactor interface {
9084
SendTransaction(ctx context.Context, tx *types.Transaction) error
9185
}
9286

87+
// ContractFilterer defines the methods needed to access log events using one-off
88+
// queries or continuous event subscriptions.
89+
type ContractFilterer interface {
90+
// FilterLogs executes a log filter operation, blocking during execution and
91+
// returning all the results in one batch.
92+
//
93+
// TODO(karalabe): Deprecate when the subscription one can return past data too.
94+
FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error)
95+
96+
// SubscribeFilterLogs creates a background log filtering operation, returning
97+
// a subscription immediately, which can be used to stream the found events.
98+
SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error)
99+
}
100+
101+
// DeployBackend wraps the operations needed by WaitMined and WaitDeployed.
102+
type DeployBackend interface {
103+
TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
104+
CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error)
105+
}
106+
93107
// ContractBackend defines the methods needed to work with contracts on a read-write basis.
94108
type ContractBackend interface {
95109
ContractCaller
96110
ContractTransactor
111+
ContractFilterer
97112
}

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

Lines changed: 118 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,15 @@ import (
3030
"github.com/ethereum/go-ethereum/common/math"
3131
"github.com/ethereum/go-ethereum/consensus/ethash"
3232
"github.com/ethereum/go-ethereum/core"
33+
"github.com/ethereum/go-ethereum/core/bloombits"
3334
"github.com/ethereum/go-ethereum/core/state"
3435
"github.com/ethereum/go-ethereum/core/types"
3536
"github.com/ethereum/go-ethereum/core/vm"
37+
"github.com/ethereum/go-ethereum/eth/filters"
3638
"github.com/ethereum/go-ethereum/ethdb"
39+
"github.com/ethereum/go-ethereum/event"
3740
"github.com/ethereum/go-ethereum/params"
41+
"github.com/ethereum/go-ethereum/rpc"
3842
)
3943

4044
// This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend.
@@ -53,6 +57,8 @@ type SimulatedBackend struct {
5357
pendingBlock *types.Block // Currently pending block that will be imported on request
5458
pendingState *state.StateDB // Currently pending state that will be the active on on request
5559

60+
events *filters.EventSystem // Event system for filtering log events live
61+
5662
config *params.ChainConfig
5763
}
5864

@@ -63,7 +69,13 @@ func NewSimulatedBackend(alloc core.GenesisAlloc) *SimulatedBackend {
6369
genesis := core.Genesis{Config: params.AllEthashProtocolChanges, Alloc: alloc}
6470
genesis.MustCommit(database)
6571
blockchain, _ := core.NewBlockChain(database, genesis.Config, ethash.NewFaker(), vm.Config{})
66-
backend := &SimulatedBackend{database: database, blockchain: blockchain, config: genesis.Config}
72+
73+
backend := &SimulatedBackend{
74+
database: database,
75+
blockchain: blockchain,
76+
config: genesis.Config,
77+
events: filters.NewEventSystem(new(event.TypeMux), &filterBackend{database, blockchain}, false),
78+
}
6779
backend.rollback()
6880
return backend
6981
}
@@ -248,7 +260,7 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs
248260
return hi, nil
249261
}
250262

251-
// callContract implemens common code between normal and pending contract calls.
263+
// callContract implements common code between normal and pending contract calls.
252264
// state is modified during execution, make sure to copy it if necessary.
253265
func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, uint64, bool, error) {
254266
// Ensure message is initialized properly.
@@ -302,7 +314,69 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transa
302314
return nil
303315
}
304316

305-
// JumpTimeInSeconds adds skip seconds to the clock
317+
// FilterLogs executes a log filter operation, blocking during execution and
318+
// returning all the results in one batch.
319+
//
320+
// TODO(karalabe): Deprecate when the subscription one can return past data too.
321+
func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) {
322+
// Initialize unset filter boundaried to run from genesis to chain head
323+
from := int64(0)
324+
if query.FromBlock != nil {
325+
from = query.FromBlock.Int64()
326+
}
327+
to := int64(-1)
328+
if query.ToBlock != nil {
329+
to = query.ToBlock.Int64()
330+
}
331+
// Construct and execute the filter
332+
filter := filters.New(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics)
333+
334+
logs, err := filter.Logs(ctx)
335+
if err != nil {
336+
return nil, err
337+
}
338+
res := make([]types.Log, len(logs))
339+
for i, log := range logs {
340+
res[i] = *log
341+
}
342+
return res, nil
343+
}
344+
345+
// SubscribeFilterLogs creates a background log filtering operation, returning a
346+
// subscription immediately, which can be used to stream the found events.
347+
func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) {
348+
// Subscribe to contract events
349+
sink := make(chan []*types.Log)
350+
351+
sub, err := b.events.SubscribeLogs(query, sink)
352+
if err != nil {
353+
return nil, err
354+
}
355+
// Since we're getting logs in batches, we need to flatten them into a plain stream
356+
return event.NewSubscription(func(quit <-chan struct{}) error {
357+
defer sub.Unsubscribe()
358+
for {
359+
select {
360+
case logs := <-sink:
361+
for _, log := range logs {
362+
select {
363+
case ch <- *log:
364+
case err := <-sub.Err():
365+
return err
366+
case <-quit:
367+
return nil
368+
}
369+
}
370+
case err := <-sub.Err():
371+
return err
372+
case <-quit:
373+
return nil
374+
}
375+
}
376+
}), nil
377+
}
378+
379+
// AdjustTime adds a time shift to the simulated clock.
306380
func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error {
307381
b.mu.Lock()
308382
defer b.mu.Unlock()
@@ -331,3 +405,44 @@ func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice }
331405
func (m callmsg) Gas() uint64 { return m.CallMsg.Gas }
332406
func (m callmsg) Value() *big.Int { return m.CallMsg.Value }
333407
func (m callmsg) Data() []byte { return m.CallMsg.Data }
408+
409+
// filterBackend implements filters.Backend to support filtering for logs without
410+
// taking bloom-bits acceleration structures into account.
411+
type filterBackend struct {
412+
db ethdb.Database
413+
bc *core.BlockChain
414+
}
415+
416+
func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db }
417+
func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") }
418+
419+
func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) {
420+
if block == rpc.LatestBlockNumber {
421+
return fb.bc.CurrentHeader(), nil
422+
}
423+
return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil
424+
}
425+
func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) {
426+
return core.GetBlockReceipts(fb.db, hash, core.GetBlockNumber(fb.db, hash)), nil
427+
}
428+
429+
func (fb *filterBackend) SubscribeTxPreEvent(ch chan<- core.TxPreEvent) event.Subscription {
430+
return event.NewSubscription(func(quit <-chan struct{}) error {
431+
<-quit
432+
return nil
433+
})
434+
}
435+
func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription {
436+
return fb.bc.SubscribeChainEvent(ch)
437+
}
438+
func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
439+
return fb.bc.SubscribeRemovedLogsEvent(ch)
440+
}
441+
func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
442+
return fb.bc.SubscribeLogsEvent(ch)
443+
}
444+
445+
func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 }
446+
func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) {
447+
panic("not supported")
448+
}

‎accounts/abi/bind/base.go‎

Lines changed: 119 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727
"github.com/ethereum/go-ethereum/common"
2828
"github.com/ethereum/go-ethereum/core/types"
2929
"github.com/ethereum/go-ethereum/crypto"
30+
"github.com/ethereum/go-ethereum/event"
3031
)
3132

3233
// SignerFn is a signer function callback when a contract requires a method to
@@ -55,6 +56,22 @@ type TransactOpts struct {
5556
Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
5657
}
5758

59+
// FilterOpts is the collection of options to fine tune filtering for events
60+
// within a bound contract.
61+
type FilterOpts struct {
62+
Start uint64 // Start of the queried range
63+
End *uint64 // End of the range (nil = latest)
64+
65+
Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
66+
}
67+
68+
// WatchOpts is the collection of options to fine tune subscribing for events
69+
// within a bound contract.
70+
type WatchOpts struct {
71+
Start *uint64 // Start of the queried range (nil = latest)
72+
Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
73+
}
74+
5875
// BoundContract is the base wrapper object that reflects a contract on the
5976
// Ethereum network. It contains a collection of methods that are used by the
6077
// higher level contract bindings to operate.
@@ -63,24 +80,26 @@ type BoundContract struct {
6380
abi abi.ABI // Reflect based ABI to access the correct Ethereum methods
6481
caller ContractCaller // Read interface to interact with the blockchain
6582
transactor ContractTransactor // Write interface to interact with the blockchain
83+
filterer ContractFilterer // Event filtering to interact with the blockchain
6684
}
6785

6886
// NewBoundContract creates a low level contract interface through which calls
6987
// and transactions may be made through.
70-
func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor) *BoundContract {
88+
func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract {
7189
return &BoundContract{
7290
address: address,
7391
abi: abi,
7492
caller: caller,
7593
transactor: transactor,
94+
filterer: filterer,
7695
}
7796
}
7897

7998
// DeployContract deploys a contract onto the Ethereum blockchain and binds the
8099
// deployment address with a Go wrapper.
81100
func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) {
82101
// Otherwise try to deploy the contract
83-
c := NewBoundContract(common.Address{}, abi, backend, backend)
102+
c := NewBoundContract(common.Address{}, abi, backend, backend, backend)
84103

85104
input, err := c.abi.Pack("", params...)
86105
if err != nil {
@@ -225,6 +244,104 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i
225244
return signedTx, nil
226245
}
227246

247+
// FilterLogs filters contract logs for past blocks, returning the necessary
248+
// channels to construct a strongly typed bound iterator on top of them.
249+
func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
250+
// Don't crash on a lazy user
251+
if opts == nil {
252+
opts = new(FilterOpts)
253+
}
254+
// Append the event selector to the query parameters and construct the topic set
255+
query = append([][]interface{}{{c.abi.Events[name].Id()}}, query...)
256+
257+
topics, err := makeTopics(query...)
258+
if err != nil {
259+
return nil, nil, err
260+
}
261+
// Start the background filtering
262+
logs := make(chan types.Log, 128)
263+
264+
config := ethereum.FilterQuery{
265+
Addresses: []common.Address{c.address},
266+
Topics: topics,
267+
FromBlock: new(big.Int).SetUint64(opts.Start),
268+
}
269+
if opts.End != nil {
270+
config.ToBlock = new(big.Int).SetUint64(*opts.End)
271+
}
272+
/* TODO(karalabe): Replace the rest of the method below with this when supported
273+
sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
274+
*/
275+
buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
276+
if err != nil {
277+
return nil, nil, err
278+
}
279+
sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
280+
for _, log := range buff {
281+
select {
282+
case logs <- log:
283+
case <-quit:
284+
return nil
285+
}
286+
}
287+
return nil
288+
}), nil
289+
290+
if err != nil {
291+
return nil, nil, err
292+
}
293+
return logs, sub, nil
294+
}
295+
296+
// WatchLogs filters subscribes to contract logs for future blocks, returning a
297+
// subscription object that can be used to tear down the watcher.
298+
func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
299+
// Don't crash on a lazy user
300+
if opts == nil {
301+
opts = new(WatchOpts)
302+
}
303+
// Append the event selector to the query parameters and construct the topic set
304+
query = append([][]interface{}{{c.abi.Events[name].Id()}}, query...)
305+
306+
topics, err := makeTopics(query...)
307+
if err != nil {
308+
return nil, nil, err
309+
}
310+
// Start the background filtering
311+
logs := make(chan types.Log, 128)
312+
313+
config := ethereum.FilterQuery{
314+
Addresses: []common.Address{c.address},
315+
Topics: topics,
316+
}
317+
if opts.Start != nil {
318+
config.FromBlock = new(big.Int).SetUint64(*opts.Start)
319+
}
320+
sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
321+
if err != nil {
322+
return nil, nil, err
323+
}
324+
return logs, sub, nil
325+
}
326+
327+
// UnpackLog unpacks a retrieved log into the provided output structure.
328+
func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
329+
if len(log.Data) > 0 {
330+
if err := c.abi.Unpack(out, event, log.Data); err != nil {
331+
return err
332+
}
333+
}
334+
var indexed abi.Arguments
335+
for _, arg := range c.abi.Events[event].Inputs {
336+
if arg.Indexed {
337+
indexed = append(indexed, arg)
338+
}
339+
}
340+
return parseTopics(out, indexed, log.Topics[1:])
341+
}
342+
343+
// ensureContext is a helper method to ensure a context is not nil, even if the
344+
// user specified it as such.
228345
func ensureContext(ctx context.Context) context.Context {
229346
if ctx == nil {
230347
return context.TODO()

0 commit comments

Comments
 (0)