-
Notifications
You must be signed in to change notification settings - Fork 62
/
claimtxman.go
527 lines (487 loc) · 18 KB
/
claimtxman.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
package claimtxman
import (
"context"
"errors"
"fmt"
"math/big"
"strings"
"time"
ctmtypes "github.com/0xPolygonHermez/zkevm-bridge-service/claimtxman/types"
"github.com/0xPolygonHermez/zkevm-bridge-service/etherman"
"github.com/0xPolygonHermez/zkevm-bridge-service/log"
"github.com/0xPolygonHermez/zkevm-bridge-service/utils"
"github.com/0xPolygonHermez/zkevm-node/state/runtime"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
lru "github.com/hashicorp/golang-lru/v2"
"github.com/jackc/pgx/v4"
)
const (
maxHistorySize = 10
keyLen = 32
mtHeight = 32
cacheSize = 1000
LeafTypeMessage = uint8(1)
)
// ClaimTxManager is the claim transaction manager for L2.
type ClaimTxManager struct {
ctx context.Context
cancel context.CancelFunc
// client is the ethereum client
l2Node *utils.Client
l2NetworkID uint
bridgeService bridgeServiceInterface
cfg Config
chExitRootEvent chan *etherman.GlobalExitRoot
chSynced chan uint
storage storageInterface
auth *bind.TransactOpts
rollupID uint
nonceCache *lru.Cache[string, uint64]
synced bool
}
// NewClaimTxManager creates a new claim transaction manager.
func NewClaimTxManager(cfg Config, chExitRootEvent chan *etherman.GlobalExitRoot, chSynced chan uint, l2NodeURL string, l2NetworkID uint, l2BridgeAddr common.Address, bridgeService bridgeServiceInterface, storage interface{}, rollupID uint) (*ClaimTxManager, error) {
ctx := context.Background()
client, err := utils.NewClient(ctx, l2NodeURL, l2BridgeAddr)
if err != nil {
return nil, err
}
cache, err := lru.New[string, uint64](int(cacheSize))
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(ctx)
auth, err := client.GetSignerFromKeystore(ctx, cfg.PrivateKey)
return &ClaimTxManager{
ctx: ctx,
cancel: cancel,
l2Node: client,
l2NetworkID: l2NetworkID,
bridgeService: bridgeService,
cfg: cfg,
chExitRootEvent: chExitRootEvent,
chSynced: chSynced,
storage: storage.(storageInterface),
auth: auth,
rollupID: rollupID,
nonceCache: cache,
}, err
}
// Start will start the tx management, reading txs from storage,
// send then to the blockchain and keep monitoring them until they
// get mined
func (tm *ClaimTxManager) Start() {
ticker := time.NewTicker(tm.cfg.FrequencyToMonitorTxs.Duration)
for {
select {
case <-tm.ctx.Done():
return
case netID := <-tm.chSynced:
if netID == tm.l2NetworkID && !tm.synced {
log.Info("NetworkID synced: ", netID)
tm.synced = true
}
case ger := <-tm.chExitRootEvent:
if tm.synced {
log.Debug("UpdateDepositsStatus for ger: ", ger.GlobalExitRoot)
go func() {
err := tm.updateDepositsStatus(ger)
if err != nil {
log.Errorf("failed to update deposits status: %v", err)
}
}()
} else {
log.Infof("Waiting for networkID %d to be synced before processing deposits", tm.l2NetworkID)
}
case <-ticker.C:
err := tm.monitorTxs(tm.ctx)
if err != nil {
log.Errorf("failed to monitor txs: %v", err)
}
}
}
}
func (tm *ClaimTxManager) updateDepositsStatus(ger *etherman.GlobalExitRoot) error {
dbTx, err := tm.storage.BeginDBTransaction(tm.ctx)
if err != nil {
return err
}
err = tm.processDepositStatus(ger, dbTx)
if err != nil {
log.Errorf("error processing ger. Error: %v", err)
rollbackErr := tm.storage.Rollback(tm.ctx, dbTx)
if rollbackErr != nil {
log.Errorf("claimtxman error rolling back state. RollbackErr: %v, err: %s", rollbackErr, err.Error())
return rollbackErr
}
return err
}
err = tm.storage.Commit(tm.ctx, dbTx)
if err != nil {
log.Errorf("AddClaimTx committing dbTx. Err: %v", err)
rollbackErr := tm.storage.Rollback(tm.ctx, dbTx)
if rollbackErr != nil {
log.Fatalf("claimtxman error rolling back state. RollbackErr: %s, err: %s", rollbackErr.Error(), err.Error())
}
log.Fatalf("AddClaimTx committing dbTx, err: %s", err.Error())
}
return nil
}
func (tm *ClaimTxManager) processDepositStatus(ger *etherman.GlobalExitRoot, dbTx pgx.Tx) error {
if ger.BlockID != 0 { // L2 exit root is updated
log.Infof("Rollup exitroot %v is updated", ger.ExitRoots[1])
if err := tm.storage.UpdateL2DepositsStatus(tm.ctx, ger.ExitRoots[1][:], tm.rollupID, tm.l2NetworkID, dbTx); err != nil {
log.Errorf("error updating L2DepositsStatus. Error: %v", err)
return err
}
} else { // L1 exit root is updated in the trusted state
log.Infof("Mainnet exitroot %v is updated", ger.ExitRoots[0])
deposits, err := tm.storage.UpdateL1DepositsStatus(tm.ctx, ger.ExitRoots[0][:], dbTx)
if err != nil {
log.Errorf("error getting and updating L1DepositsStatus. Error: %v", err)
return err
}
for _, deposit := range deposits {
if tm.l2NetworkID != deposit.DestinationNetwork {
log.Infof("Ignoring deposit: %d: dest_net: %d, we are:%d", deposit.DepositCount, deposit.DestinationNetwork, tm.l2NetworkID)
continue
}
claimHash, err := tm.bridgeService.GetDepositStatus(tm.ctx, deposit.DepositCount, deposit.DestinationNetwork)
if err != nil {
log.Errorf("error getting deposit status for deposit %d. Error: %v", deposit.DepositCount, err)
return err
}
if len(claimHash) > 0 || deposit.LeafType == LeafTypeMessage && !tm.isDepositMessageAllowed(deposit) {
log.Infof("Ignoring deposit: %d, leafType: %d, claimHash: %s, deposit.OriginalAddress: %s", deposit.DepositCount, deposit.LeafType, claimHash, deposit.OriginalAddress.String())
continue
}
log.Infof("create the claim tx for the deposit %d", deposit.DepositCount)
ger, proof, rollupProof, err := tm.bridgeService.GetClaimProof(deposit.DepositCount, deposit.NetworkID, dbTx)
if err != nil {
log.Errorf("error getting Claim Proof for deposit %d. Error: %v", deposit.DepositCount, err)
return err
}
var (
mtProof [mtHeight][keyLen]byte
mtRollupProof [mtHeight][keyLen]byte
)
for i := 0; i < mtHeight; i++ {
mtProof[i] = proof[i]
mtRollupProof[i] = rollupProof[i]
}
tx, err := tm.l2Node.BuildSendClaim(tm.ctx, deposit, mtProof, mtRollupProof,
ðerman.GlobalExitRoot{
ExitRoots: []common.Hash{
ger.ExitRoots[0],
ger.ExitRoots[1],
}}, 1, 1, 1, tm.rollupID,
tm.auth)
if err != nil {
log.Errorf("error BuildSendClaim tx for deposit %d. Error: %v", deposit.DepositCount, err)
return err
}
if err = tm.addClaimTx(deposit.DepositCount, tm.auth.From, tx.To(), nil, tx.Data(), dbTx); err != nil {
log.Errorf("error adding claim tx for deposit %d. Error: %v", deposit.DepositCount, err)
return err
}
}
}
return nil
}
func (tm *ClaimTxManager) isDepositMessageAllowed(deposit *etherman.Deposit) bool {
for _, addr := range tm.cfg.AuthorizedClaimMessageAddresses {
if deposit.OriginalAddress == addr {
log.Infof("MessageBridge from authorized account detected: %+v, account: %s", deposit, addr.String())
return true
}
}
log.Infof("MessageBridge Not authorized. DepositCount: %d", deposit.DepositCount)
return false
}
func (tm *ClaimTxManager) getNextNonce(from common.Address) (uint64, error) {
nonce, err := tm.l2Node.NonceAt(tm.ctx, from, nil)
if err != nil {
return 0, err
}
if tempNonce, found := tm.nonceCache.Get(from.Hex()); found {
if tempNonce >= nonce {
nonce = tempNonce + 1
}
}
tm.nonceCache.Add(from.Hex(), nonce)
return nonce, nil
}
func (tm *ClaimTxManager) addClaimTx(depositCount uint, from common.Address, to *common.Address, value *big.Int, data []byte, dbTx pgx.Tx) error {
// get gas
tx := ethereum.CallMsg{
From: from,
To: to,
Value: value,
Data: data,
}
gas, err := tm.l2Node.EstimateGas(tm.ctx, tx)
for i := 1; err != nil && err.Error() != runtime.ErrExecutionReverted.Error() && i < tm.cfg.RetryNumber; i++ {
log.Warnf("error while doing gas estimation. Retrying... Error: %v, Data: %s", err, common.Bytes2Hex(data))
time.Sleep(tm.cfg.RetryInterval.Duration)
gas, err = tm.l2Node.EstimateGas(tm.ctx, tx)
}
if err != nil {
log.Errorf("failed to estimate gas. Ignoring tx... Error: %v, data: %s", err, common.Bytes2Hex(data))
return nil
}
// get next nonce
nonce, err := tm.getNextNonce(from)
if err != nil {
err := fmt.Errorf("failed to get current nonce: %v", err)
log.Errorf("error getting next nonce. Error: %s", err.Error())
return err
}
// create monitored tx
mTx := ctmtypes.MonitoredTx{
DepositID: depositCount, From: from, To: to,
Nonce: nonce, Value: value, Data: data,
Gas: gas, Status: ctmtypes.MonitoredTxStatusCreated,
}
// add to storage
err = tm.storage.AddClaimTx(tm.ctx, mTx, dbTx)
if err != nil {
err := fmt.Errorf("failed to add tx to get monitored: %v", err)
log.Errorf("error adding claim tx to db. Error: %s", err.Error())
return err
}
return nil
}
// monitorTxs process all pending monitored tx
func (tm *ClaimTxManager) monitorTxs(ctx context.Context) error {
dbTx, err := tm.storage.BeginDBTransaction(tm.ctx)
if err != nil {
return err
}
statusesFilter := []ctmtypes.MonitoredTxStatus{ctmtypes.MonitoredTxStatusCreated}
mTxs, err := tm.storage.GetClaimTxsByStatus(ctx, statusesFilter, dbTx)
if err != nil {
log.Errorf("failed to get created monitored txs: %v", err)
rollbackErr := tm.storage.Rollback(tm.ctx, dbTx)
if rollbackErr != nil {
log.Errorf("claimtxman error rolling back state. RollbackErr: %s, err: %v", rollbackErr.Error(), err)
return rollbackErr
}
return fmt.Errorf("failed to get created monitored txs: %v", err)
}
isResetNonce := false // it will reset the nonce in one cycle
log.Infof("found %v monitored tx to process", len(mTxs))
for _, mTx := range mTxs {
mTx := mTx // force variable shadowing to avoid pointer conflicts
mTxLog := log.WithFields("monitoredTx", mTx.DepositID)
mTxLog.Infof("processing tx with nonce %d", mTx.Nonce)
// check if any of the txs in the history was mined
mined := false
var receipt *types.Receipt
hasFailedReceipts := false
allHistoryTxMined := true
receiptSuccessful := false
for txHash := range mTx.History {
mTxLog.Infof("Checking if tx %s is mined", txHash.String())
mined, receipt, err = tm.l2Node.CheckTxWasMined(ctx, txHash)
if err != nil {
mTxLog.Errorf("failed to check if tx %s was mined: %v", txHash.String(), err)
continue
}
// if the tx is not mined yet, check that not all the tx were mined and go to the next
if !mined {
// check if the tx is in the pending pool
_, _, err = tm.l2Node.TransactionByHash(ctx, txHash)
if err != nil {
mTxLog.Errorf("error getting txByHash %s. Error: %v", txHash.String(), err)
// Retry if the tx has not appeared in the pool yet.
for i := 0; i < tm.cfg.RetryNumber && err != nil; i++ {
mTxLog.Warn("waiting and retrying to find the tx in the pool. TxHash: %s. Error: %v", txHash.String(), err)
time.Sleep(tm.cfg.RetryInterval.Duration)
_, _, err = tm.l2Node.TransactionByHash(ctx, txHash)
}
if errors.Is(err, ethereum.NotFound) {
mTxLog.Error("maximum retries and the tx is still missing in the pool. TxHash: ", txHash.String())
hasFailedReceipts = true
continue
} else if err != nil {
mTxLog.Errorf("failed to retry to get tx %s: %v", txHash.String(), err)
continue
}
}
log.Infof("tx: %s not mined yet", txHash.String())
allHistoryTxMined = false
continue
}
// if the tx was mined successfully we can break the loop and proceed
if receipt.Status == types.ReceiptStatusSuccessful {
mTxLog.Infof("tx %s was mined successfully", txHash.String())
receiptSuccessful = true
mTx.Status = ctmtypes.MonitoredTxStatusConfirmed
// update monitored tx changes into storage
err = tm.storage.UpdateClaimTx(ctx, mTx, dbTx)
if err != nil {
mTxLog.Errorf("failed to update monitored tx when confirmed: %v", err)
}
break
}
// if the tx was mined but failed, we continue to consider it was not mined
// and store the failed receipt to be used to check if nonce needs to be reviewed
mined = false
hasFailedReceipts = true
}
if receiptSuccessful {
continue
}
// if the history size reaches the max history size, this means something is really wrong with
// this Tx and we are not able to identify automatically, so we mark this as failed to let the
// caller know something is not right and needs to be review and to avoid to monitor this
// tx infinitely
if allHistoryTxMined && len(mTx.History) >= maxHistorySize {
mTx.Status = ctmtypes.MonitoredTxStatusFailed
mTxLog.Infof("marked as failed because reached the history size limit (%d)", maxHistorySize)
// update monitored tx changes into storage
err = tm.storage.UpdateClaimTx(ctx, mTx, dbTx)
if err != nil {
mTxLog.Errorf("failed to update monitored tx when max history size limit reached: %v", err)
}
continue
}
// if we have failed receipts, this means at least one of the generated txs was mined
// so maybe the current nonce was already consumed, then we need to check if there are
// tx that were not mined yet, if so, we just need to wait, because maybe one of them
// will get mined successfully
if allHistoryTxMined {
// in case of all tx were mined and none of them were mined successfully, we need to
// review the tx information
if hasFailedReceipts {
mTxLog.Infof("monitored tx needs to be updated")
err := tm.ReviewMonitoredTx(ctx, &mTx, true)
if err != nil {
mTxLog.Errorf("failed to review monitored tx: %v", err)
continue
}
}
// GasPrice is set here to use always the proper and most accurate value right before sending it to L2
gasPrice, err := tm.l2Node.SuggestGasPrice(ctx)
if err != nil {
mTxLog.Errorf("failed to get suggested gasPrice. Error: %v", err)
continue
}
//Multiply gasPrice by 10 to increase the efficiency of the tx in the sequence
mTx.GasPrice = big.NewInt(0).Mul(gasPrice, big.NewInt(10)) //nolint:gomnd
log.Infof("Using gasPrice: %s. The gasPrice suggested by the network is %s", mTx.GasPrice.String(), gasPrice.String())
// rebuild transaction
tx := mTx.Tx()
mTxLog.Debugf("unsigned tx created for monitored tx")
var signedTx *types.Transaction
// sign tx
signedTx, err = tm.auth.Signer(mTx.From, tx)
if err != nil {
mTxLog.Errorf("failed to sign tx %v created from monitored tx: %v", tx.Hash().String(), err)
continue
}
mTxLog.Debugf("signed tx %v created using gasPrice: %s", signedTx.Hash().String(), signedTx.GasPrice().String())
// add tx to monitored tx history
err = mTx.AddHistory(signedTx)
if errors.Is(err, ctmtypes.ErrAlreadyExists) {
mTxLog.Infof("signed tx already existed in the history")
} else if err != nil {
mTxLog.Errorf("failed to add signed tx to monitored tx history: %v", err)
continue
}
// check if the tx is already in the network, if not, send it
_, _, err = tm.l2Node.TransactionByHash(ctx, signedTx.Hash())
if errors.Is(err, ethereum.NotFound) {
err := tm.l2Node.SendTransaction(ctx, signedTx)
if err != nil {
mTxLog.Errorf("failed to send tx %s to network: %v", signedTx.Hash().String(), err)
var reviewNonce bool
if strings.Contains(err.Error(), "nonce") {
mTxLog.Infof("nonce error detected, Nonce used: %d", signedTx.Nonce())
if !isResetNonce {
isResetNonce = true
tm.nonceCache.Remove(mTx.From.Hex())
mTxLog.Infof("nonce cache cleared for address %v", mTx.From.Hex())
}
reviewNonce = true
}
mTx.RemoveHistory(signedTx)
// we should rebuild the monitored tx to fix the nonce
err := tm.ReviewMonitoredTx(ctx, &mTx, reviewNonce)
if err != nil {
mTxLog.Errorf("failed to review monitored tx: %v", err)
}
}
} else if err != nil && !errors.Is(err, ethereum.NotFound) {
mTxLog.Error("unexpected error getting TransactionByHash. Error: ", err)
} else {
mTxLog.Infof("signed tx %v already found in the network for the monitored tx.", signedTx.Hash().String())
}
// update monitored tx changes into storage
err = tm.storage.UpdateClaimTx(ctx, mTx, dbTx)
if err != nil {
mTxLog.Errorf("failed to update monitored tx: %v", err)
continue
}
mTxLog.Infof("signed tx %s added to the monitored tx history", signedTx.Hash().String())
}
}
err = tm.storage.Commit(tm.ctx, dbTx)
if err != nil {
log.Errorf("UpdateClaimTx committing dbTx, err: %v", err)
rollbackErr := tm.storage.Rollback(tm.ctx, dbTx)
if rollbackErr != nil {
log.Errorf("claimtxman error rolling back state. RollbackErr: %s, err: %v", rollbackErr.Error(), err)
return rollbackErr
}
return err
}
return nil
}
// ReviewMonitoredTx checks if tx needs to be updated
// accordingly to the current information stored and the current
// state of the blockchain
func (tm *ClaimTxManager) ReviewMonitoredTx(ctx context.Context, mTx *ctmtypes.MonitoredTx, reviewNonce bool) error {
mTxLog := log.WithFields("monitoredTx", mTx.DepositID)
mTxLog.Debug("reviewing")
// get gas
tx := ethereum.CallMsg{
From: mTx.From,
To: mTx.To,
Value: mTx.Value,
Data: mTx.Data,
}
gas, err := tm.l2Node.EstimateGas(ctx, tx)
for i := 1; err != nil && err.Error() != runtime.ErrExecutionReverted.Error() && i < tm.cfg.RetryNumber; i++ {
mTxLog.Warnf("error during gas estimation. Retrying... Error: %v, Data: %s", err, common.Bytes2Hex(tx.Data))
time.Sleep(tm.cfg.RetryInterval.Duration)
gas, err = tm.l2Node.EstimateGas(tm.ctx, tx)
}
if err != nil {
err := fmt.Errorf("failed to estimate gas. Error: %v, Data: %s", err, common.Bytes2Hex(tx.Data))
mTxLog.Errorf("error: %s", err.Error())
return err
}
// check gas
if gas > mTx.Gas {
mTxLog.Infof("monitored tx gas updated from %v to %v", mTx.Gas, gas)
mTx.Gas = gas
}
if reviewNonce {
// check nonce
nonce, err := tm.getNextNonce(mTx.From)
if err != nil {
err := fmt.Errorf("failed to get nonce: %v", err)
mTxLog.Errorf(err.Error())
return err
}
if nonce > mTx.Nonce {
mTxLog.Infof("monitored tx nonce updated from %v to %v", mTx.Nonce, nonce)
mTx.Nonce = nonce
}
}
return nil
}