-
Notifications
You must be signed in to change notification settings - Fork 17
/
migration_source_tx.go
379 lines (329 loc) · 10.3 KB
/
migration_source_tx.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
package migration
import (
"context"
"errors"
"strings"
"sync"
"time"
txtrackerProcessVaa "github.com/wormhole-foundation/wormhole-explorer/common/client/txtracker"
sdk "github.com/wormhole-foundation/wormhole/sdk/vaa"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.uber.org/zap"
)
// MigrateSourceChainTx is the job to migrate vaa txHash and timestamp from vaa collection to globalTx collection.
type MigrateSourceChainTx struct {
db *mongo.Database
pageSize int
chainID sdk.ChainID
FromDate time.Time
ToDate time.Time
txTrackerAPIClient txtrackerProcessVaa.TxTrackerAPIClient
sleepTime time.Duration
collections struct {
vaas *mongo.Collection
globalTransactions *mongo.Collection
}
logger *zap.Logger
}
// NewMigrationSourceChainTx creates a new migration job.
func NewMigrationSourceChainTx(
db *mongo.Database,
pageSize int,
chainID sdk.ChainID,
FromDate time.Time,
ToDate time.Time,
txTrackerAPIClient txtrackerProcessVaa.TxTrackerAPIClient,
sleepTime time.Duration,
logger *zap.Logger) *MigrateSourceChainTx {
return &MigrateSourceChainTx{
db: db,
pageSize: pageSize,
chainID: chainID,
FromDate: FromDate,
ToDate: ToDate,
txTrackerAPIClient: txTrackerAPIClient,
sleepTime: sleepTime,
collections: struct {
vaas *mongo.Collection
globalTransactions *mongo.Collection
}{
vaas: db.Collection("vaas"),
globalTransactions: db.Collection("globalTransactions"),
},
logger: logger}
}
// VAASourceChain defines the structure of vaa fields needed for migration.
type VAASourceChain struct {
ID string `bson:"_id"`
EmitterChain sdk.ChainID `bson:"emitterChain" json:"emitterChain"`
Timestamp *time.Time `bson:"timestamp" json:"timestamp"`
TxHash *string `bson:"txHash" json:"txHash,omitempty"`
}
// GlobalTransaction represents a global transaction.
type GlobalTransaction struct {
ID string `bson:"_id" json:"id"`
OriginTx *OriginTx `bson:"originTx" json:"originTx"`
}
// OriginTx represents a origin transaction.
type OriginTx struct {
TxHash string `bson:"nativeTxHash" json:"txHash"`
From string `bson:"from" json:"from"`
Status string `bson:"status" json:"status"`
}
func (m *MigrateSourceChainTx) Run(ctx context.Context) error {
if m.chainID == sdk.ChainIDSolana || m.chainID == sdk.ChainIDAptos {
return m.runComplexMigration(ctx)
} else {
return m.runMigration(ctx)
}
}
// runComplexMigration runs the migration job for solana and aptos chains calling the txtracker endpoint.
func (m *MigrateSourceChainTx) runComplexMigration(ctx context.Context) error {
if sdk.ChainIDSolana != m.chainID && sdk.ChainIDAptos != m.chainID {
return errors.New("invalid chainID")
}
var page int64 = 0
for {
// get vaas to migrate by page and pageSize.
vaas, err := m.getVaasToMigrate(ctx, m.chainID, m.FromDate, m.ToDate, page, int64(m.pageSize))
if err != nil {
m.logger.Error("failed to get vaas", zap.Error(err), zap.Int64("page", page))
break
}
if len(vaas) == 0 {
break
}
for _, v := range vaas {
// check if global transaction exists and nested originTx exists
filter := bson.D{
{Key: "_id", Value: v.ID},
{Key: "originTx", Value: bson.D{{Key: "$exists", Value: true}}},
}
var globalTransacations GlobalTransaction
err := m.collections.globalTransactions.FindOne(ctx, filter).Decode(&globalTransacations)
// if global transaction exists, skip
if err == nil {
m.logger.Info("global transaction already exists", zap.String("id", v.ID))
continue
}
// if exist and error getting global transaction, log error
if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
m.logger.Error("failed to get global transaction", zap.Error(err), zap.String("id", v.ID))
continue
}
// if not exist txhash, skip
if v.TxHash == nil {
m.logger.Error("txHash is nil", zap.String("id", v.ID))
continue
}
_, err = m.txTrackerAPIClient.Process(v.ID)
if err != nil {
m.logger.Error("failed to process vaa", zap.Error(err), zap.String("id", v.ID))
continue
}
time.Sleep(100 * time.Microsecond)
}
}
return nil
}
// Run runs the migration job.
func (m *MigrateSourceChainTx) runMigration(ctx context.Context) error {
var page int64 = 0
var wg sync.WaitGroup
workerLimit := m.pageSize
jobs := make(chan VAASourceChain, workerLimit)
for i := 1; i <= workerLimit; i++ {
wg.Add(1)
go worker(ctx, &wg, jobs, m.collections.globalTransactions, m.logger)
}
for {
// get vaas to migrate by page and pageSize.
vaas, err := m.getVaasToMigrate(ctx, m.chainID, m.FromDate, m.ToDate, page, int64(m.pageSize))
if err != nil {
m.logger.Error("failed to get vaas", zap.Error(err), zap.Int64("page", page))
break
}
if len(vaas) == 0 {
break
}
for _, v := range vaas {
jobs <- v
}
}
close(jobs)
wg.Wait()
return nil
}
func worker(ctx context.Context, wg *sync.WaitGroup, jobs <-chan VAASourceChain, collection *mongo.Collection, logger *zap.Logger) {
defer wg.Done()
for v := range jobs {
if v.EmitterChain == sdk.ChainIDSolana || v.EmitterChain == sdk.ChainIDAptos {
logger.Debug("skip migration", zap.String("id", v.ID), zap.String("chain", v.EmitterChain.String()))
continue
}
// check if global transaction exists and nested originTx exists
filter := bson.D{
{Key: "_id", Value: v.ID},
{Key: "originTx", Value: bson.D{{Key: "$exists", Value: true}}},
}
var globalTransacations GlobalTransaction
err := collection.FindOne(ctx, filter).Decode(&globalTransacations)
// if global transaction exists, skip
if err == nil {
logger.Info("global transaction already exists", zap.String("id", v.ID))
continue
}
// if exist and error getting global transaction, log error
if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
logger.Error("failed to get global transaction", zap.Error(err), zap.String("id", v.ID))
continue
}
// if not exist txhash, skip
if v.TxHash == nil {
logger.Error("txHash is nil", zap.String("id", v.ID))
continue
}
// set txHash format by chain
var txHash string
switch v.EmitterChain {
case sdk.ChainIDAcala,
sdk.ChainIDArbitrum,
sdk.ChainIDAvalanche,
sdk.ChainIDBase,
sdk.ChainIDBSC,
sdk.ChainIDCelo,
sdk.ChainIDEthereum,
sdk.ChainIDFantom,
sdk.ChainIDKarura,
sdk.ChainIDKlaytn,
sdk.ChainIDMoonbeam,
sdk.ChainIDOasis,
sdk.ChainIDOptimism,
sdk.ChainIDPolygon:
txHash = txHashLowerCaseWith0x(*v.TxHash)
default:
txHash = *v.TxHash
}
// update global transaction
update := bson.D{
{Key: "$set", Value: bson.D{{Key: "originTx.timestamp", Value: v.Timestamp}}},
{Key: "$set", Value: bson.D{{Key: "originTx.nativeTxHash", Value: txHash}}},
{Key: "$set", Value: bson.D{{Key: "originTx.status", Value: "confirmed"}}},
}
opts := options.Update().SetUpsert(true)
result, err := collection.UpdateByID(ctx, v.ID, update, opts)
if err != nil {
logger.Error("failed to update global transaction", zap.Error(err), zap.String("id", v.ID))
break
}
if result.UpsertedCount == 1 {
logger.Info("inserted global transaction", zap.String("id", v.ID))
} else {
logger.Debug("global transaction already exists", zap.String("id", v.ID))
}
}
}
func txHashLowerCaseWith0x(v string) string {
if strings.HasPrefix(v, "0x") {
return strings.ToLower(v)
}
return "0x" + strings.ToLower(v)
}
func (m *MigrateSourceChainTx) getVaasToMigrate(ctx context.Context, chainID sdk.ChainID, from time.Time, to time.Time, page int64, pageSize int64) ([]VAASourceChain, error) {
skip := page * pageSize
limit := pageSize
sort := bson.D{{Key: "timestamp", Value: 1}}
// add match step by chain
var matchStage1 bson.D
if chainID != sdk.ChainIDUnset {
matchStage1 = bson.D{{Key: "$match", Value: bson.D{
{Key: "emitterChain", Value: chainID},
}}}
} else {
// get all the vaas without solana and aptos
solanaAndAptosIds := []sdk.ChainID{sdk.ChainIDSolana, sdk.ChainIDAptos}
matchStage1 = bson.D{{Key: "$match", Value: bson.D{
{Key: "emitterChain", Value: bson.M{"$nin": solanaAndAptosIds}},
}}}
}
// add match step by range date
var matchStage2 bson.D
if from.IsZero() && to.IsZero() {
matchStage2 = bson.D{{Key: "$match", Value: bson.D{}}}
}
if from.IsZero() && !to.IsZero() {
matchStage2 = bson.D{{Key: "$match", Value: bson.D{
{Key: "timestamp", Value: bson.M{
"$lt": to,
}},
}}}
}
if !from.IsZero() && to.IsZero() {
matchStage2 = bson.D{{Key: "$match", Value: bson.D{
{Key: "timestamp", Value: bson.M{
"$gte": from,
}},
}}}
}
if !from.IsZero() && !to.IsZero() {
matchStage2 = bson.D{{Key: "$match", Value: bson.D{
{Key: "timestamp", Value: bson.M{
"$gte": from,
"$lt": to,
}},
}}}
}
// add match step that txHash exists
var matchStage3 bson.D
matchStage3 = bson.D{{Key: "$match", Value: bson.D{
{Key: "txHash", Value: bson.D{{Key: "$exists", Value: true}}},
}}}
// add lookup step with globalTransactions collection
lookupStage := bson.D{{Key: "$lookup", Value: bson.D{
{Key: "from", Value: "globalTransactions"},
{Key: "localField", Value: "_id"},
{Key: "foreignField", Value: "_id"},
{Key: "as", Value: "globalTransactions"},
}}}
matchStage4 := bson.D{{Key: "$match", Value: bson.D{
{Key: "globalTransactions.originTx", Value: bson.D{{Key: "$exists", Value: false}}},
}}}
// add project step
projectStage := bson.D{{Key: "$project", Value: bson.D{
{Key: "_id", Value: 1},
{Key: "emitterChain", Value: 1},
{Key: "timestamp", Value: 1},
{Key: "txHash", Value: 1},
}}}
// add skip step
skipStage := bson.D{{Key: "$skip", Value: skip}}
// add limit step
limitStage := bson.D{{Key: "$limit", Value: limit}}
// add sort step
sortStage := bson.D{{Key: "$sort", Value: sort}}
// define pipeline
pipeline := mongo.Pipeline{
matchStage1,
matchStage2,
matchStage3,
lookupStage,
matchStage4,
projectStage,
skipStage,
limitStage,
sortStage,
}
// find vaas
cur, err := m.collections.vaas.Aggregate(ctx, pipeline)
if err != nil {
return []VAASourceChain{}, err
}
// decode vaas
vaas := make([]VAASourceChain, pageSize)
if err := cur.All(ctx, &vaas); err != nil {
return []VAASourceChain{}, err
}
return vaas, nil
}