-
Notifications
You must be signed in to change notification settings - Fork 713
/
wait.go
346 lines (304 loc) · 9.42 KB
/
wait.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package operations
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"os"
"os/signal"
"time"
"github.com/0xPolygonHermez/zkevm-node/hex"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/client"
"github.com/0xPolygonHermez/zkevm-node/log"
"github.com/0xPolygonHermez/zkevm-node/state"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health/grpc_health_v1"
)
const (
// DefaultInterval is a time interval
DefaultInterval = 2 * time.Millisecond
// DefaultDeadline is a time interval
DefaultDeadline = 2 * time.Minute
// DefaultTxMinedDeadline is a time interval
DefaultTxMinedDeadline = 5 * time.Second
)
var (
// ErrTimeoutReached is thrown when the timeout is reached and
// because the condition is not matched
ErrTimeoutReached = fmt.Errorf("timeout has been reached")
)
// Wait handles polliing until conditions are met.
type Wait struct{}
// NewWait is the Wait constructor.
func NewWait() *Wait {
return &Wait{}
}
// Poll retries the given condition with the given interval until it succeeds
// or the given deadline expires.
func Poll(interval, deadline time.Duration, condition ConditionFunc) error {
timeout := time.After(deadline)
tick := time.NewTicker(interval)
for {
select {
case <-timeout:
return ErrTimeoutReached
case <-tick.C:
ok, err := condition()
if err != nil {
return err
}
if ok {
return nil
}
}
}
}
type ethClienter interface {
ethereum.TransactionReader
ethereum.ContractCaller
bind.DeployBackend
}
// WaitTxToBeMined waits until a tx has been mined or the given timeout expires.
func WaitTxToBeMined(parentCtx context.Context, client ethClienter, tx *types.Transaction, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(parentCtx, timeout)
defer cancel()
receipt, err := bind.WaitMined(ctx, client, tx)
if errors.Is(err, context.DeadlineExceeded) {
return err
} else if err != nil {
log.Errorf("error waiting tx %s to be mined: %w", tx.Hash(), err)
return err
}
if receipt.Status == types.ReceiptStatusFailed {
// Get revert reason
reason, reasonErr := RevertReason(ctx, client, tx, receipt.BlockNumber)
if reasonErr != nil {
reason = reasonErr.Error()
}
return fmt.Errorf("transaction has failed, reason: %s, receipt: %+v. tx: %+v, gas: %v", reason, receipt, tx, tx.Gas())
}
log.Debug("Transaction successfully mined: ", tx.Hash())
return nil
}
// RevertReason returns the revert reason for a tx that has a receipt with failed status
func RevertReason(ctx context.Context, c ethClienter, tx *types.Transaction, blockNumber *big.Int) (string, error) {
if tx == nil {
return "", nil
}
from, err := types.Sender(types.NewEIP155Signer(tx.ChainId()), tx)
if err != nil {
signer := types.LatestSignerForChainID(tx.ChainId())
from, err = types.Sender(signer, tx)
if err != nil {
return "", err
}
}
msg := ethereum.CallMsg{
From: from,
To: tx.To(),
Gas: tx.Gas(),
Value: tx.Value(),
Data: tx.Data(),
}
hex, err := c.CallContract(ctx, msg, blockNumber)
if err != nil {
return "", err
}
unpackedMsg, err := abi.UnpackRevert(hex)
if err != nil {
log.Warnf("failed to get the revert message for tx %v: %v", tx.Hash(), err)
return "", errors.New("execution reverted")
}
return unpackedMsg, nil
}
// WaitGRPCHealthy waits for a gRPC endpoint to be responding according to the
// health standard in package grpc.health.v1
func WaitGRPCHealthy(address string) error {
return Poll(DefaultInterval, DefaultDeadline, func() (bool, error) {
return grpcHealthyCondition(address)
})
}
// WaitL2BlockToBeConsolidated waits until a L2 Block has been consolidated or the given timeout expires.
func WaitL2BlockToBeConsolidated(l2Block *big.Int, timeout time.Duration) error {
return Poll(DefaultInterval, timeout, func() (bool, error) {
return l2BlockConsolidationCondition(l2Block)
})
}
// WaitL2BlockToBeVirtualized waits until a L2 Block has been virtualized or the given timeout expires.
func WaitL2BlockToBeVirtualized(l2Block *big.Int, timeout time.Duration) error {
l2NetworkURL := "http://localhost:8123"
return Poll(DefaultInterval, timeout, func() (bool, error) {
return l2BlockVirtualizationCondition(l2Block, l2NetworkURL)
})
}
// WaitL2BlockToBeVirtualizedCustomRPC waits until a L2 Block has been virtualized or the given timeout expires.
func WaitL2BlockToBeVirtualizedCustomRPC(l2Block *big.Int, timeout time.Duration, l2NetworkURL string) error {
return Poll(DefaultInterval, timeout, func() (bool, error) {
return l2BlockVirtualizationCondition(l2Block, l2NetworkURL)
})
}
// WaitBatchToBeVirtualized waits until a Batch has been virtualized or the given timeout expires.
func WaitBatchToBeVirtualized(batchNum uint64, timeout time.Duration, state *state.State) error {
ctx := context.Background()
return Poll(DefaultInterval, timeout, func() (bool, error) {
return state.IsBatchVirtualized(ctx, batchNum, nil)
})
}
// WaitBatchToBeConsolidated waits until a Batch has been consolidated/verified or the given timeout expires.
func WaitBatchToBeConsolidated(batchNum uint64, timeout time.Duration, state *state.State) error {
ctx := context.Background()
return Poll(DefaultInterval, timeout, func() (bool, error) {
return state.IsBatchConsolidated(ctx, batchNum, nil)
})
}
func WaitTxReceipt(ctx context.Context, txHash common.Hash, timeout time.Duration, client *ethclient.Client) (*types.Receipt, error) {
if client == nil {
return nil, fmt.Errorf("client is nil")
}
var receipt *types.Receipt
pollErr := Poll(DefaultInterval, timeout, func() (bool, error) {
var err error
receipt, err = client.TransactionReceipt(ctx, txHash)
if err != nil {
if errors.Is(err, ethereum.NotFound) {
time.Sleep(time.Second)
return false, nil
} else {
return false, err
}
}
return true, nil
})
if pollErr != nil {
return nil, pollErr
}
return receipt, nil
}
// NodeUpCondition check if the container is up and running
func NodeUpCondition(target string) (bool, error) {
var jsonStr = []byte(`{"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}`)
req, err := http.NewRequest(
"POST", target,
bytes.NewBuffer(jsonStr))
if err != nil {
return false, err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
// we allow connection errors to wait for the container up
return false, nil
}
if res.Body != nil {
defer func() {
err = res.Body.Close()
}()
}
body, err := io.ReadAll(res.Body)
if err != nil {
return false, err
}
r := struct {
Result bool
}{
Result: true,
}
err = json.Unmarshal(body, &r)
if err != nil {
return false, err
}
done := !r.Result
return done, nil
}
// ConditionFunc is a generic function
type ConditionFunc func() (done bool, err error)
func networkUpCondition() (bool, error) {
return NodeUpCondition(DefaultL1NetworkURL)
}
func nodeUpCondition() (done bool, err error) {
return NodeUpCondition(DefaultL2NetworkURL)
}
func grpcHealthyCondition(address string) (bool, error) {
opts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
}
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
conn, err := grpc.DialContext(ctx, address, opts...)
if err != nil {
// we allow connection errors to wait for the container up
return false, nil
}
defer func() {
err = conn.Close()
}()
healthClient := grpc_health_v1.NewHealthClient(conn)
state, err := healthClient.Check(context.Background(), &grpc_health_v1.HealthCheckRequest{})
if err != nil {
// we allow connection errors to wait for the container up
return false, nil
}
done := state.Status == grpc_health_v1.HealthCheckResponse_SERVING
return done, nil
}
// l2BlockConsolidationCondition
func l2BlockConsolidationCondition(l2Block *big.Int) (bool, error) {
l2NetworkURL := "http://localhost:8123"
response, err := client.JSONRPCCall(l2NetworkURL, "zkevm_isBlockConsolidated", hex.EncodeBig(l2Block))
if err != nil {
return false, err
}
if response.Error != nil {
return false, fmt.Errorf("%d - %s", response.Error.Code, response.Error.Message)
}
var result bool
err = json.Unmarshal(response.Result, &result)
if err != nil {
return false, err
}
return result, nil
}
// l2BlockVirtualizationCondition
func l2BlockVirtualizationCondition(l2Block *big.Int, l2NetworkURL string) (bool, error) {
response, err := client.JSONRPCCall(l2NetworkURL, "zkevm_isBlockVirtualized", hex.EncodeBig(l2Block))
if err != nil {
return false, err
}
if response.Error != nil {
return false, fmt.Errorf("%d - %s", response.Error.Code, response.Error.Message)
}
var result bool
err = json.Unmarshal(response.Result, &result)
if err != nil {
return false, err
}
return result, nil
}
// WaitSignal blocks until an Interrupt or Kill signal is received, then it
// executes the given cleanup functions and returns.
func WaitSignal(cleanupFuncs ...func()) {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
for sig := range signals {
switch sig {
case os.Interrupt, os.Kill:
log.Info("terminating application gracefully...")
for _, cleanup := range cleanupFuncs {
cleanup()
}
return
}
}
}