|
| 1 | +package contracts |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "github.com/ethereum/go-ethereum/core/types" |
| 6 | + "github.com/pkg/errors" |
| 7 | + "github.com/rs/zerolog/log" |
| 8 | + "github.com/smartcontractkit/integrations-framework/client" |
| 9 | + "time" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + DAGAwaitTimeout = 120 * time.Second |
| 14 | +) |
| 15 | + |
| 16 | +// AwaitMining awaits first block after DAG generation on multi-node geth networks |
| 17 | +func AwaitMining(c client.BlockchainClient) error { |
| 18 | + log.Info().Msg("Awaiting first block to be mined") |
| 19 | + key := "next_block" |
| 20 | + cf := NewNextBlockConfirmer() |
| 21 | + c.AddHeaderEventSubscription(key, cf) |
| 22 | + if err := c.WaitForEvents(); err != nil { |
| 23 | + return err |
| 24 | + } |
| 25 | + return nil |
| 26 | +} |
| 27 | + |
| 28 | +// NextBlockConfirmer await for the next block |
| 29 | +type NextBlockConfirmer struct { |
| 30 | + doneChan chan struct{} |
| 31 | + done bool |
| 32 | + ctx context.Context |
| 33 | + cancel context.CancelFunc |
| 34 | +} |
| 35 | + |
| 36 | +// NewNextBlockConfirmer generic next block confirmer |
| 37 | +func NewNextBlockConfirmer() *NextBlockConfirmer { |
| 38 | + ctx, cancel := context.WithTimeout(context.Background(), DAGAwaitTimeout) |
| 39 | + return &NextBlockConfirmer{ |
| 40 | + done: false, |
| 41 | + doneChan: make(chan struct{}), |
| 42 | + ctx: ctx, |
| 43 | + cancel: cancel, |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +func (f *NextBlockConfirmer) ReceiveBlock(_ *types.Block) error { |
| 48 | + if f.done { |
| 49 | + return nil |
| 50 | + } |
| 51 | + log.Info().Msg("First block received") |
| 52 | + f.done = true |
| 53 | + f.doneChan <- struct{}{} |
| 54 | + return nil |
| 55 | +} |
| 56 | + |
| 57 | +func (f *NextBlockConfirmer) Wait() error { |
| 58 | + for { |
| 59 | + select { |
| 60 | + case <-f.doneChan: |
| 61 | + f.cancel() |
| 62 | + return nil |
| 63 | + case <-f.ctx.Done(): |
| 64 | + return errors.New("timeout waiting for the next block to confirm") |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments