/
ronin.go
416 lines (369 loc) · 11.1 KB
/
ronin.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
package task
import (
"context"
"math/big"
"runtime/debug"
"sync"
"time"
bridgeCore "github.com/axieinfinity/bridge-core"
"github.com/axieinfinity/bridge-core/metrics"
"github.com/axieinfinity/bridge-core/utils"
"github.com/axieinfinity/bridge-v2/models"
"github.com/axieinfinity/bridge-v2/stores"
bridgeUtils "github.com/axieinfinity/bridge-v2/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/log"
"gorm.io/gorm"
)
const (
defaultLimitRecords = 50
defaultMaxTry = 5
defaultMaxProcessingTasks = 200
)
var (
defaultTaskInterval = 10 * time.Second
defaultReceiptCheck = 50 * time.Second
)
type RoninTask struct {
ctx context.Context
cancelFunc context.CancelFunc
util utils.Utils
listener bridgeCore.Listener
store stores.BridgeStore
taskInterval time.Duration
txCheckInterval time.Duration
secret *bridgeCore.Secret
client *ethclient.Client
contracts map[string]string
limitQuery int
chainId *big.Int
releaseTasksCh chan int
processingIdsMap sync.Map
maxProcessingTasks int
gasLimitBumpRatio uint64
}
func NewRoninTask(listener bridgeCore.Listener, db *gorm.DB, util utils.Utils) (*RoninTask, error) {
config := listener.Config()
client, err := ethclient.Dial(config.RpcUrl)
if err != nil {
return nil, err
}
chainId, err := listener.GetChainID()
if err != nil {
return nil, err
}
var gasLimitBumpRatio uint64
if config.GasLimitBumpRatio > 0 {
gasLimitBumpRatio = config.GasLimitBumpRatio
} else {
gasLimitBumpRatio = utils.Percentage
}
newCtx, cancelFunc := context.WithCancel(listener.Context())
task := &RoninTask{
ctx: newCtx,
cancelFunc: cancelFunc,
listener: listener,
store: stores.NewBridgeStore(db),
taskInterval: defaultTaskInterval,
txCheckInterval: defaultReceiptCheck,
secret: config.Secret,
contracts: config.Contracts,
client: client,
chainId: chainId,
util: util,
limitQuery: defaultLimitRecords,
releaseTasksCh: make(chan int, defaultLimitRecords),
maxProcessingTasks: defaultMaxProcessingTasks,
gasLimitBumpRatio: gasLimitBumpRatio,
}
if config.TaskInterval > 0 {
task.taskInterval = config.TaskInterval
}
if config.TransactionCheckPeriod > 0 {
task.txCheckInterval = config.TransactionCheckPeriod
}
if config.MaxTasksQuery > 0 {
task.limitQuery = config.MaxTasksQuery
}
if config.MaxProcessingTasks > 0 {
task.maxProcessingTasks = config.MaxProcessingTasks
}
return task, nil
}
func (r *RoninTask) Start() {
log.Info("[RoninTask] starting ronin task", "taskInterval", r.taskInterval, "txCheckInterval", r.txCheckInterval, "maxProcessingTasks", r.maxProcessingTasks)
taskTicker := time.NewTicker(r.taskInterval)
processingTicker := time.NewTicker(r.txCheckInterval)
ethConfig := r.listener.GetListener(bridgeUtils.Ethereum).Config()
ethClient, _ := ethclient.Dial(ethConfig.RpcUrl)
for {
select {
case <-taskTicker.C:
go func() {
if err := r.processPending(ethClient); err != nil {
log.Error("[RoninTask] error while process tasks", "err", err)
}
}()
case <-processingTicker.C:
go func() {
if err := r.checkProcessingTasks(); err != nil {
log.Error("[RoninTask] error while checking processing tasks", "err", err)
}
}()
case id := <-r.releaseTasksCh:
r.unlockTask(id)
case <-r.ctx.Done():
r.client.Close()
return
}
}
}
func (r *RoninTask) SetLimitQuery(limit int) {
r.limitQuery = limit
}
func (r *RoninTask) Close() {
r.cancelFunc()
}
func (r *RoninTask) GetListener() bridgeCore.Listener {
return r.listener
}
// getLimitQuery gets limitQuery which makes sure total processing tasks are within maxProcessingTasks
func (r *RoninTask) getLimitQuery(numberOfExcludedIds int) int {
if numberOfExcludedIds >= r.maxProcessingTasks {
return 0
}
if r.maxProcessingTasks-numberOfExcludedIds < r.limitQuery {
return r.maxProcessingTasks - numberOfExcludedIds
}
return r.limitQuery
}
func (r *RoninTask) processPending(ethClient *ethclient.Client) error {
defer func() {
if err := recover(); err != nil {
log.Error("[RoninTask][processPending] recover from panic", "err", err, "trace", string(debug.Stack()))
}
}()
// load processing tasks into excluded list
var excludeIds []int
r.processingIdsMap.Range(func(key, value interface{}) bool {
excludeIds = append(excludeIds, key.(int))
return true
})
// get limitQuery, if limitQuery = 0 then do nothing and wait until processing tasks are released
limitQuery := r.getLimitQuery(len(excludeIds))
if limitQuery == 0 {
return nil
}
tasks, err := r.store.GetTaskStore().GetTasks(hexutil.EncodeBig(r.chainId), STATUS_PENDING, limitQuery, 10, 0, excludeIds)
if err != nil {
return err
}
if len(tasks) == 0 {
return nil
}
metrics.Pusher.IncrCounter(metrics.PendingTaskMetric, len(tasks))
bulkDepositTask := newBulkTask(
r.listener,
r.client,
r.store,
r.chainId,
r.contracts,
r.txCheckInterval,
defaultMaxTry,
DEPOSIT_TASK,
r.releaseTasksCh,
r.util,
r.gasLimitBumpRatio,
)
bulkSubmitWithdrawalSignaturesTask := newBulkTask(
r.listener,
r.client,
r.store,
r.chainId,
r.contracts,
r.txCheckInterval,
defaultMaxTry,
WITHDRAWAL_TASK,
r.releaseTasksCh,
r.util,
r.gasLimitBumpRatio,
)
ackWithdrewTasks := newBulkTask(
r.listener,
r.client,
r.store,
r.chainId,
r.contracts,
r.txCheckInterval,
defaultMaxTry,
ACK_WITHDREW_TASK,
r.releaseTasksCh,
r.util,
r.gasLimitBumpRatio,
)
singleTasks := make([]*task, 0)
for _, task := range tasks {
// lock task
r.lockTask(task)
// collect tasks for bulk deposits
bulkDepositTask.collectTask(task)
// collect tasks for bulk withdrawal signature
bulkSubmitWithdrawalSignaturesTask.collectTask(task)
// collect tasks for acknowledge withdrawal
ackWithdrewTasks.collectTask(task)
switch task.Type {
case VOTE_BRIDGE_OPERATORS_TASK:
voteBridgeOperatorsTask := newTask(
r.listener,
r.client,
ethClient,
r.store,
r.chainId,
r.contracts,
defaultMaxTry,
VOTE_BRIDGE_OPERATORS_TASK,
r.releaseTasksCh,
r.util,
r.gasLimitBumpRatio,
)
voteBridgeOperatorsTask.collectTask(task)
singleTasks = append(singleTasks, voteBridgeOperatorsTask)
case RELAY_BRIDGE_OPERATORS_TASK:
relayBridgeOperatorsTask := newTask(
r.listener,
r.client,
ethClient,
r.store,
r.chainId,
r.contracts,
defaultMaxTry,
RELAY_BRIDGE_OPERATORS_TASK,
r.releaseTasksCh,
r.util,
r.gasLimitBumpRatio,
)
relayBridgeOperatorsTask.collectTask(task)
singleTasks = append(singleTasks, relayBridgeOperatorsTask)
}
}
bulkDepositTask.send()
bulkSubmitWithdrawalSignaturesTask.send()
ackWithdrewTasks.send()
for _, task := range singleTasks {
task.send()
}
return nil
}
func (r *RoninTask) lockTask(t *models.Task) {
if t != nil {
r.processingIdsMap.Store(t.ID, struct{}{})
}
}
func (r *RoninTask) unlockTask(id int) {
r.processingIdsMap.Delete(id)
}
func (r *RoninTask) checkProcessingTasks() error {
defer func() {
if err := recover(); err != nil {
log.Error("[RoninTask][checkProcessingTask] recover from panic", "err", err, "trace", string(debug.Stack()))
}
}()
before := time.Now().Unix() - int64(r.listener.Config().SafeBlockRange*uint64(r.listener.Config().LoadInterval.Seconds()))
tasks, err := r.store.GetTaskStore().GetTasks(hexutil.EncodeBig(r.chainId), STATUS_PROCESSING, r.limitQuery, 2, before, nil)
if err != nil {
return err
}
if len(tasks) == 0 {
return nil
}
failedTasks := sync.Map{}
successTasks := sync.Map{}
processedTx := make(map[string]struct{})
var wg sync.WaitGroup
wg.Add(len(tasks))
metrics.Pusher.IncrGauge(metrics.ProcessingTaskMetric, -len(tasks))
for _, t := range tasks {
if _, ok := processedTx[t.TransactionHash]; ok {
wg.Done()
continue
}
processedTx[t.TransactionHash] = struct{}{}
go func(task *models.Task) {
defer wg.Done()
// check transaction receipt status
log.Info("[RoninTask][checkProcessingTasks] Start checking transaction status", "tx", task.TransactionHash)
receipt, err := r.listener.GetReceipt(common.HexToHash(task.TransactionHash))
if err != nil || receipt == nil {
failedTasks.Store(task, struct{}{})
return
}
// add task and transaction's status into successTasks
successTasks.Store(task, receipt.Status)
}(t)
}
wg.Wait()
var (
successTxs []string
failedTxs []string
resetToPending []string
releaseTasks []*models.Task
)
// loop through successTasks, if receipt is failed then reset to pending and retry if retry is not reached to 10
successTasks.Range(func(key interface{}, value interface{}) bool {
task := key.(*models.Task)
if value.(uint64) == 1 {
successTxs = append(successTxs, task.TransactionHash)
releaseTasks = append(releaseTasks, task)
} else {
if task.Retries+1 >= 10 {
// append to failedTxs and update all tasks with this transactionHash to failed
failedTxs = append(failedTxs, task.TransactionHash)
releaseTasks = append(releaseTasks, task)
} else {
// append to resetToPending and update all tasks with this transactionHash to pending
resetToPending = append(resetToPending, task.TransactionHash)
}
}
return true
})
// loop through failedTasksMap, reset to pending and retry if retry is not reached to 10
failedTasks.Range(func(key interface{}, value interface{}) bool {
task := key.(*models.Task)
if task.Retries+1 >= 10 {
// append to failedTxs and update all tasks with this transactionHash to failed
failedTxs = append(failedTxs, task.TransactionHash)
releaseTasks = append(releaseTasks, task)
} else {
// append to resetToPending and update all tasks with this transactionHash to pending
resetToPending = append(resetToPending, task.TransactionHash)
}
return true
})
// update success tasks with transaction's status = 1 (success)
if len(successTxs) > 0 {
metrics.Pusher.IncrCounter(metrics.SuccessTaskMetric, len(successTxs))
if err = r.store.GetTaskStore().UpdateTasksWithTransactionHash(successTxs, 1, STATUS_DONE); err != nil {
log.Error("[RoninTask][checkProcessingTasks] error while update tasks with success transactions", "err", err)
}
}
// update success tasks with transaction's status = 0 (failed)
if len(failedTxs) > 0 {
metrics.Pusher.IncrCounter(metrics.FailedTaskMetric, len(failedTxs))
if err = r.store.GetTaskStore().UpdateTasksWithTransactionHash(failedTxs, 0, STATUS_FAILED); err != nil {
log.Error("[RoninTask][checkProcessingTasks] error while update tasks with failed transactions", "err", err)
}
}
// update all tasks contain failed txs to pending
if len(resetToPending) > 0 {
log.Info("[RoninTask][checkProcessingTasks] reset tasks to pending", "transactionHash", resetToPending)
if err = r.store.GetTaskStore().ResetTo(resetToPending, STATUS_PENDING); err != nil {
log.Error("[RoninTask][checkProcessingTasks] error while reset tasks to pending", "err", err)
}
}
for _, task := range releaseTasks {
r.releaseTasksCh <- task.ID
}
return nil
}