-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
1318 lines (1032 loc) · 37.4 KB
/
main.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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"math"
"math/big"
"os/user"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"github.com/AccumulateNetwork/bridge/abiutil"
"github.com/AccumulateNetwork/bridge/accumulate"
"github.com/AccumulateNetwork/bridge/api"
"github.com/AccumulateNetwork/bridge/config"
"github.com/AccumulateNetwork/bridge/evm"
"github.com/AccumulateNetwork/bridge/fees"
"github.com/AccumulateNetwork/bridge/global"
"github.com/AccumulateNetwork/bridge/gnosis"
"github.com/AccumulateNetwork/bridge/schema"
acmeurl "github.com/AccumulateNetwork/bridge/url"
"github.com/AccumulateNetwork/bridge/utils"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/go-playground/validator/v10"
"github.com/labstack/gommon/log"
)
const LEADER_MIN_DURATION = 2
const NUMBER_OF_ACCUMULATE_TOKEN_TXS = 100
const NUMBER_OF_TOKEN_REGISTRY_ENTRIES = 1000
var LatestCheckedDeposits map[string]int64
var LatestCheckedEVMHeight int64
func main() {
var err error
usr, err := user.Current()
if err != nil {
log.Error(err)
}
configFile := usr.HomeDir + "/.accumulatebridge/config.yaml"
flag.StringVar(&configFile, "c", configFile, "config.yaml path")
flag.Parse()
LatestCheckedDeposits = make(map[string]int64)
start(configFile)
}
func start(configFile string) {
for {
var err error
var conf *config.Config
var g *gnosis.Gnosis
var e *evm.EVMClient
var a *accumulate.AccumulateClient
fmt.Println("Using config:", configFile)
// init config
if conf, err = config.NewConfig(configFile); err != nil {
log.Fatal(err)
}
// set log level
log.SetLevel(log.Lvl(conf.App.LogLevel))
// init gnosis client
if g, err = gnosis.NewGnosis(conf); err != nil {
log.Fatal(err)
}
fmt.Println("Gnosis safe:", g.SafeAddress)
fmt.Println("Bridge address:", g.BridgeAddress)
fmt.Println("Gnosis API:", g.API)
// init evm client
if e, err = evm.NewEVMClient(conf); err != nil {
log.Fatal(err)
}
fmt.Println("EVM address:", e.PublicKey)
fmt.Println("EVM API:", e.API)
fmt.Println("EVM ChainId:", e.ChainId)
// init accumulate client
if a, err = accumulate.NewAccumulateClient(conf); err != nil {
log.Fatal(err)
}
// init accumulate client
fmt.Printf("Accumulate public key: %x\n", a.PublicKey)
fmt.Printf("Accumulate public key hash: %x\n", a.PublicKeyHash)
fmt.Println("Accumulate API:", a.API)
fmt.Println("Bridge ADI:", a.ADI)
// set chainId for tokens
global.Tokens.ChainID = int64(conf.EVM.ChainId)
// parse bridge fees on node start
bridgeFeesDataAccount := filepath.Join(conf.ACME.BridgeADI, accumulate.ACC_BRIDGE_FEES)
if err = getBridgeFees(bridgeFeesDataAccount, a); err != nil {
// bridge can not start without fees
log.Fatal(err)
}
fmt.Printf("Mint fee: %.2f%%\n", float64(global.BridgeFees.MintFee)/100)
fmt.Printf("Burn fee: %.2f%%\n", float64(global.BridgeFees.BurnFee)/100)
// parse token list from Accumulate
// only once – when node is started
// token list is mandatory, so return fatal error in case of error
tokensDataAccount := filepath.Join(conf.ACME.BridgeADI, accumulate.ACC_TOKEN_REGISTRY)
fmt.Println("Getting Accumulate tokens from", tokensDataAccount)
tokens, err := a.QueryDataSet(&accumulate.Params{URL: tokensDataAccount, Count: int64(NUMBER_OF_TOKEN_REGISTRY_ENTRIES), Expand: true})
if err != nil {
fmt.Println("unable to get token list from", tokensDataAccount)
log.Fatal(err)
}
fmt.Println("Got", len(tokens.Items), "data entry(s)")
for _, item := range tokens.Items {
parseToken(a, e, g, item)
}
fmt.Println("Found", len(global.Tokens.Items), "token(s)")
if len(global.Tokens.Items) == 0 {
log.Fatal("can not operate without tokens, shutting down")
}
// init interval go routines
die := make(chan bool)
// refresh bridge fees every minute
go refreshBridgeFees(bridgeFeesDataAccount, a, die)
go getStatus(a, die)
go getLeader(a, die)
// go debugLeader(die)
go processBurnEvents(a, e, conf.EVM.BridgeAddress, die)
go processNewDeposits(a, e, g, die)
go submitEVMTxs(e, g, die)
// init Accumulate Bridge API
fmt.Println("Starting Accumulate Bridge API at port", conf.App.APIPort)
log.Fatal(api.StartAPI(conf))
}
}
func getBridgeFees(bridgeFeesDataAccount string, a *accumulate.AccumulateClient) error {
fmt.Println("Getting bridge fees from", bridgeFeesDataAccount)
fees, err := a.QueryLatestDataEntry(&accumulate.Params{URL: bridgeFeesDataAccount})
if err != nil {
fmt.Println("unable to get bridge fees from", bridgeFeesDataAccount)
return err
}
feesBytes, err := hex.DecodeString(fees.Data.Entry.Data[0])
if err != nil {
log.Error("can not decode entry data")
return err
}
err = json.Unmarshal(feesBytes, &global.BridgeFees)
if err != nil {
log.Error("unable to unmarshal entry data")
return err
}
return nil
}
// refreshBridgeFees parses bridge fees and updates them every minute
func refreshBridgeFees(bridgeFeesDataAccount string, a *accumulate.AccumulateClient, die chan bool) {
for {
select {
default:
err := getBridgeFees(bridgeFeesDataAccount, a)
if err != nil {
log.Error("Unable to refresh bridge fees:", err)
}
// check fees every minute
time.Sleep(time.Duration(1) * time.Minute)
case <-die:
return
}
}
}
// getLeader parses current leader's public key hash from Accumulate data account and compares it with Accumulate key in the config to find out if this node is a leader or not
func getLeader(a *accumulate.AccumulateClient, die chan bool) {
leaderDataAccount := filepath.Join(a.ADI, accumulate.ACC_LEADER)
for {
select {
default:
leaderData, err := a.QueryLatestDataEntry(&accumulate.Params{URL: leaderDataAccount})
if err != nil {
fmt.Println("[leader] Unable to read bridge leader:", err)
global.IsLeader = false
global.IsAudit = false
global.LeaderDuration = 0
} else {
fmt.Println("[leader] Bridge leader:", leaderData.Data.Entry.Data[0])
decodedLeader, err := hex.DecodeString(leaderData.Data.Entry.Data[0])
if err != nil {
fmt.Println(err)
global.IsLeader = false
global.IsAudit = false
global.LeaderDuration = 0
}
if bytes.Equal(decodedLeader, a.PublicKeyHash) {
global.IsAudit = false
global.LeaderDuration++
if !global.IsLeader {
if global.LeaderDuration <= LEADER_MIN_DURATION {
fmt.Println("[leader] This node is leader, confirmations:", global.LeaderDuration, "of", LEADER_MIN_DURATION)
}
if global.LeaderDuration >= LEADER_MIN_DURATION {
global.IsLeader = true
}
}
} else {
global.IsLeader = false
global.IsAudit = true
global.LeaderDuration = 0
}
}
// check leader every minute
time.Sleep(time.Duration(1) * time.Minute)
case <-die:
return
}
}
}
// getStatus checks if the bridge is online
func getStatus(a *accumulate.AccumulateClient, die chan bool) {
statusDataAccount := filepath.Join(a.ADI, accumulate.ACC_BRIDGE_STATUS)
for {
select {
default:
online, err := a.QueryLatestDataEntry(&accumulate.Params{URL: statusDataAccount})
if err != nil {
fmt.Println("[status] Unable to read bridge status:", err)
global.IsOnline = false
} else {
if len(online.Data.Entry.Data[0]) > 0 {
fmt.Println("[status] Bridge is online")
global.IsOnline = true
} else {
fmt.Println("[status] Bridge is paused")
global.IsOnline = false
}
}
// check leader every minute
time.Sleep(time.Duration(1) * time.Minute)
case <-die:
return
}
}
}
// parseToken parses data entry with token information received from data account
func parseToken(a *accumulate.AccumulateClient, e *evm.EVMClient, g *gnosis.Gnosis, entry *accumulate.DataEntry) {
fmt.Println("Parsing", entry.EntryHash)
tokenEntry := &schema.TokenEntry{}
// check version
if len(entry.Entry.Data) < 2 {
log.Debug("looking for at least 2 data fields in entry, found ", len(entry.Entry.Data))
return
}
version, err := hex.DecodeString(entry.Entry.Data[0])
if err != nil {
log.Debug("can not decode entry data")
return
}
if !bytes.Equal(version, []byte(accumulate.TOKEN_REGISTRY_VERSION)) {
log.Debug("entry version is not ", accumulate.TOKEN_REGISTRY_VERSION)
return
}
// convert entry data to bytes
tokenData, err := hex.DecodeString(entry.Entry.Data[1])
if err != nil {
log.Debug("can not decode entry data")
return
}
// try to unmarshal the entry
err = json.Unmarshal(tokenData, tokenEntry)
if err != nil {
log.Debug("unable to unmarshal entry data")
return
}
// if entry is disabled, remove existing tokens / skip
if !tokenEntry.Enabled {
for i, t := range global.Tokens.Items {
if strings.EqualFold(t.URL, tokenEntry.URL) {
log.Info("remove disabled token ", tokenEntry.URL)
global.Tokens.Items = append(global.Tokens.Items[:i], global.Tokens.Items[i+1:]...)
return
}
}
log.Debug("token is disabled")
return
}
// validate token
validate := validator.New()
err = validate.Struct(tokenEntry)
if err != nil {
log.Debug(err)
return
}
token := &schema.Token{}
for _, wrappedToken := range tokenEntry.Wrapped {
// search for current chainid
if wrappedToken.ChainID == global.Tokens.ChainID {
err = validate.Struct(wrappedToken)
if err != nil {
log.Debug(err)
return
}
token.EVMAddress = wrappedToken.Address
token.EVMMintTxCost = wrappedToken.MintTxCost
}
}
// if no token address found, error
if token.EVMAddress == "" {
log.Debug("can not find token address for chainid ", global.Tokens.ChainID)
return
}
// parse token info from Accumulate
t, err := a.QueryToken(&accumulate.Params{URL: tokenEntry.URL})
if err != nil {
log.Debug("can not get token from accumulate api ", err)
return
}
token.URL = t.Data.URL
token.Symbol = t.Data.Symbol
token.Precision = t.Data.Precision
// check if bridge has token account on this chain for this token
tokenAccountUrl := accumulate.GenerateTokenAccount(a.ADI, global.Tokens.ChainID, token.Symbol)
_, err = a.QueryTokenAccount(&accumulate.Params{URL: tokenAccountUrl})
if err != nil {
log.Debug("can not get token account ", tokenAccountUrl, " from accumulate api")
return
}
// parse token info from Ethereum
evmT, err := e.GetERC20(token.EVMAddress)
if err != nil {
log.Debug("can not get token from ethereum api ", err)
return
}
if evmT.Owner != g.BridgeAddress {
log.Debug("token owner is not the bridge, but ", evmT.Owner)
return
}
token.EVMSymbol = evmT.Symbol
token.EVMDecimals = evmT.Decimals
// check for duplicates, if found override
exists := utils.SearchAccumulateToken(token.URL)
// if not found, append new token
if exists == nil {
log.Info("added token ", token.URL)
global.Tokens.Items = append(global.Tokens.Items, token)
return
}
log.Info("duplicate token ", token.URL, ", overwritten")
*exists = *token
}
// debugLeader helps to debug leader behaviour
func debugLeader(die chan bool) {
for {
select {
default:
log.Debug("isLeader=", global.IsLeader)
time.Sleep(time.Duration(5) * time.Second)
case <-die:
return
}
}
}
// processBurnEvents
func processBurnEvents(a *accumulate.AccumulateClient, e *evm.EVMClient, bridge string, die chan bool) {
for {
select {
default:
time.Sleep(time.Duration(60) * time.Second)
releaseQueue := accumulate.GenerateReleaseDataAccount(a.ADI, int64(e.ChainId), accumulate.ACC_RELEASE_QUEUE)
if global.IsOnline {
if global.IsLeader {
fmt.Println("[release] Checking pending chain of", releaseQueue)
pendingEntries, err := a.QueryPendingChain(&accumulate.Params{URL: releaseQueue})
if err != nil {
fmt.Println("[release] Stopping the process, unable to get pending chain:", err)
break
}
// if there are any pending entries, do not produce new tx
if len(pendingEntries.Items) > 0 {
fmt.Println("[release] Stopping the process, found pending entries in", releaseQueue)
break
}
fmt.Println("[release] Getting block height from the latest entry of", releaseQueue)
latestReleaseEntry, err := a.QueryLatestDataEntry(&accumulate.Params{URL: releaseQueue})
// if Accumulate does not return blockheight, shut down to prevent double spending
if err != nil {
fmt.Println("[release] Unable to get block height:", err)
break
}
// parse latest burn entry to find out evm blockHeight
burnEntry, err := schema.ParseBurnEvent(latestReleaseEntry.Data)
if err != nil {
fmt.Println("[release]", err)
break
}
// looking for evm logs starting from latest height+1
start := burnEntry.BlockHeight + 1
if LatestCheckedEVMHeight > burnEntry.BlockHeight {
start = LatestCheckedEVMHeight + 1
}
fmt.Println("[release] Parsing new EVM events for", bridge, "starting from blockHeight", start)
logs, err := e.ParseBridgeLogs("Burn", bridge, &evm.BlockRange{From: start})
if err != nil {
fmt.Println("[release]", err)
break
}
knownHeight := 0
// logs are sorted by timestamp asc
for _, l := range logs {
fmt.Println("[release] Height", l.BlockHeight, "txid", l.TxID.Hex())
// additional check in case evm node returns invalid response
if int64(l.BlockHeight) < start {
fmt.Println("[release] Invalid height, expected height >=", start)
continue
}
// process only single block height at once
// if blockheight changed = shutdown
if knownHeight > 0 && l.BlockHeight != uint64(knownHeight) {
fmt.Println("[release] Height changed, will process event in the next batch, stopping the process")
break
}
// create burnEntry
burnEntry := &schema.BurnEvent{}
burnEntry.EVMTxID = l.TxID.Hex()
burnEntry.BlockHeight = int64(l.BlockHeight)
burnEntry.TokenAddress = l.Token.String()
burnEntry.Destination = l.Destination
burnEntry.Amount = l.Amount.Int64()
// find token
token := utils.SearchEVMToken(burnEntry.TokenAddress)
// skip if no token found
if token == nil {
continue
}
operation := &fees.Operation{
Token: token,
Amount: l.Amount.Int64(),
}
outAmount, err := operation.ApplyFees(&global.BridgeFees, fees.OP_RELEASE)
// skip if output amount is invalid (too low or negative, e.g.)
if err != nil {
continue
}
outAmountHuman := float64(outAmount) / math.Pow10(int(token.Precision))
fmt.Println("[release] Sending", outAmountHuman, token.Symbol, "to", burnEntry.Destination)
// generate accumulate token tx
txhash, err := a.SendTokens(burnEntry.Destination, outAmount, token.URL, int64(e.ChainId))
if err != nil {
fmt.Println("[release] tx failed:", err)
continue
}
fmt.Println("[release] tx sent:", txhash)
burnEntry.TxHash = txhash
burnEntryBytes, err := json.Marshal(burnEntry)
if err != nil {
fmt.Println("[release] can not marshal burn entry:", err)
continue
}
var content [][]byte
content = append(content, []byte(accumulate.RELEASE_QUEUE_VERSION))
content = append(content, burnEntryBytes)
entryhash, err := a.WriteData(releaseQueue, content)
if err != nil {
fmt.Println("[release] data entry creation failed:", err)
continue
}
fmt.Println("[release] data entry created:", entryhash)
knownHeight = int(l.BlockHeight)
LatestCheckedEVMHeight = int64(l.BlockHeight)
}
} else if global.IsAudit {
fmt.Println("[release] Checking pending chain of", releaseQueue)
pending, err := a.QueryPendingChain(&accumulate.Params{URL: releaseQueue})
if err != nil {
fmt.Println("[release] can not get pending data entries:", err)
break
}
// if no pending entries, shut down
if len(pending.Items) == 0 {
fmt.Println("[release] Stopping the process, no pending entries found in", releaseQueue)
break
}
fmt.Println("[release] Getting block height from the latest entry of", releaseQueue)
latestReleaseEntry, err := a.QueryLatestDataEntry(&accumulate.Params{URL: releaseQueue})
// if Accumulate does not return blockheight, shut down to prevent double spending
if err != nil {
fmt.Println("[release] Unable to get block height:", err)
break
}
// parse latest burn entry to find out evm blockHeight
latestCompletedBurn, err := schema.ParseBurnEvent(latestReleaseEntry.Data)
if err != nil {
fmt.Println("[release]", err)
break
}
// looking for pending tx with blockheight starting from latest height+1
start := latestCompletedBurn.BlockHeight + 1
for _, entryhash := range pending.Items {
fmt.Println("[release] processing pending entry", entryhash)
entryURL := entryhash + "@" + releaseQueue
entry, err := a.QueryDataEntry(&accumulate.Params{URL: entryURL})
if err != nil {
fmt.Println("[release] Unable to get data entry", err)
continue
}
burnEntry, err := schema.ParseBurnEvent(entry.Data)
if err != nil {
fmt.Println("[release] Unable to parse burn event from data entry", err)
continue
}
fmt.Println("[release] start", start, "event blockheight", burnEntry.BlockHeight)
// check block height to avoid old txs
if int64(burnEntry.BlockHeight) < start {
fmt.Println("[release] Invalid height, expected height >=", start)
continue
}
// find token
token := utils.SearchEVMToken(burnEntry.TokenAddress)
// skip if no token found
if token == nil {
continue
}
fmt.Println("[release] Found new pending tx:", burnEntry.TxHash)
// Checking EVM tx limits the bridge to validate only txs of Accumulate Bridge smart contracts
// Valid burn txs, created by other contracts, calling Accumulate Bridge contract, are invalidated in this case
// It's safe to just validate Accumulate Bridge smart contract burn events
fmt.Println("[release] Parsing EVM events for", bridge, "at blockHeight", burnEntry.BlockHeight)
logs, err := e.ParseBridgeLogs("Burn", bridge, &evm.BlockRange{From: burnEntry.BlockHeight, To: burnEntry.BlockHeight})
if err != nil {
fmt.Println("[release]", err)
break
}
foundLog := &evm.EventLog{}
// find only one log, associated with txid
for _, l := range logs {
if l.TxID.String() == burnEntry.EVMTxID {
foundLog = l
}
}
// validate burn entry against evm log
err = utils.ValidateBurnEntry(burnEntry, foundLog)
if err != nil {
fmt.Println("[release] burn entry validation failed:", err)
continue
}
// parse accumulate txid
txid, err := acmeurl.ParseTxID(burnEntry.TxHash)
if err != nil {
fmt.Println(err)
continue
}
remoteTxHash := txid.Hash()
// parse accumulate tx
tx, err := a.QueryTokenTx(&accumulate.Params{URL: burnEntry.TxHash})
if err != nil {
fmt.Println(err)
continue
}
// validate accumulate tx against evm tx
err = utils.ValidateReleaseTx(tx.Data, foundLog)
if err != nil {
fmt.Println("[release] accumulate tx validation failed:", err)
continue
}
// sign accumulate tx
tokenAccount := accumulate.GenerateTokenAccount(a.ADI, int64(e.ChainId), token.Symbol)
txhash, err := a.RemoteTransaction(tokenAccount, hex.EncodeToString(remoteTxHash[:]))
if err != nil {
fmt.Println("[release] tx failed:", err)
continue
}
fmt.Println("[release] tx sent:", txhash)
// sign data entry
txhash, err = a.RemoteTransaction(releaseQueue, entryhash)
if err != nil {
fmt.Println("[release] tx failed:", err)
continue
}
fmt.Println("[release] tx sent:", txhash)
}
}
}
case <-die:
return
}
}
}
// processNewDeposits
func processNewDeposits(a *accumulate.AccumulateClient, e *evm.EVMClient, g *gnosis.Gnosis, die chan bool) {
for {
select {
default:
time.Sleep(time.Duration(60) * time.Second)
if global.IsOnline {
if global.IsLeader {
for _, token := range global.Tokens.Items {
// get gnosis safe
safe, err := g.GetSafe()
if err != nil {
fmt.Println("[mint] can not get gnosis safe:", err)
break
}
nonce, err := strconv.ParseInt(safe.Nonce, 10, 64)
if err != nil {
fmt.Println("[mint] can not parse int from nonce string:", err)
break
}
// check if there are pending txs at current nonce
safeTxs, err := g.GetSafeMultisigTxs()
if err != nil {
fmt.Println("[mint] can not get gnosis safe multisig txs:", err)
break
}
if len(safeTxs.Results) > 0 {
if safeTxs.Results[0].Nonce >= nonce {
fmt.Println("[mint] stopping the process, gnosis safe has unprocessed tx with nonce", safeTxs.Results[0].Nonce)
break
}
}
mintQueue := accumulate.GenerateMintDataAccount(a.ADI, int64(e.ChainId), accumulate.ACC_MINT_QUEUE, token.Symbol)
fmt.Println("[mint] Checking pending chain of", mintQueue)
pendingEntries, err := a.QueryPendingChain(&accumulate.Params{URL: mintQueue})
if err != nil {
fmt.Println("[mint] Stopping the process, unable to get pending chain:", err)
continue
}
// if there are any pending entries, do not produce new tx
if len(pendingEntries.Items) > 0 {
fmt.Println("[mint] Stopping the process, found pending entries in", mintQueue)
continue
}
fmt.Println("[mint] Getting seq number from the latest entry of", mintQueue)
latestMintEntry, err := a.QueryLatestDataEntry(&accumulate.Params{URL: mintQueue})
// if Accumulate does not return seq number, shut down to prevent double minting
if err != nil {
fmt.Println("[mint] Unable to get seq number:", err)
continue
}
// parse latest mint entry to find out seq number
mintEntry, err := schema.ParseDepositEvent(latestMintEntry.Data)
if err != nil {
fmt.Println("[mint] Unable to parse deposit event from data entry", err)
continue
}
// looking for accumulate token txs starting from latest height+1
start := mintEntry.SeqNumber + 1
if LatestCheckedDeposits[token.Symbol] > mintEntry.SeqNumber {
start = LatestCheckedDeposits[token.Symbol] + 1
}
tokenAccount := accumulate.GenerateTokenAccount(a.ADI, int64(e.ChainId), token.Symbol)
fmt.Println("[mint] Parsing new accumulate token txs in", tokenAccount, "starting from seq number", start)
count := int64(NUMBER_OF_ACCUMULATE_TOKEN_TXS)
txs, err := a.QueryTxHistory(&accumulate.Params{URL: tokenAccount, Start: start, Count: count})
if err != nil {
fmt.Println("[mint] Unable to get tx history for", tokenAccount, err)
continue
}
fmt.Println("[mint] Found", len(txs.Items), "txs in", tokenAccount, "seq number from", start, "to", start+count)
// cursor is to track seq number and update it in map in the end
cursor := start
if len(txs.Items) > 0 {
for i, tx := range txs.Items {
// cursor = current seq number
cursor = int64(i) + start
// validate tx
fmt.Println("[mint] Validating tx", tx.TxHash, "seq number", cursor)
err := utils.ValidateDepositTx(tx)
if err != nil {
fmt.Println("[mint] tx validation failed:", err)
continue
}
// query cause tx
cause, err := a.QueryTokenTx(&accumulate.Params{URL: tx.Data.Cause})
if err != nil {
fmt.Println("[mint] can not get cause tx:", err)
// if we are here, then something happened on the accumulate api side
// reset cursor and break to start over
cursor = start - 1
break
}
// validate cause tx
err = utils.ValidateCauseTx(cause)
if err != nil {
fmt.Println("[mint] cause tx validation failed:", err)
continue
}
amount := new(big.Int)
amount, ok := amount.SetString(tx.Data.Amount, 10)
if !ok {
fmt.Println("[mint] unable to convert tx amount")
// if we are here, then something unexpected happened
// reset cursor and break to start over
cursor = start - 1
break
}
// validate destination address
validate := validator.New()
err = validate.Var(cause.Transaction.Header.Memo, "required,eth_addr")
// if validation failed, skip this tx
if err != nil {
fmt.Println("[mint] can not validate destination address:", err)
continue
}
// create mintEntry
mintEntry := &schema.DepositEvent{}
mintEntry.Amount = amount.Int64()
mintEntry.Destination = cause.Transaction.Header.Memo
mintEntry.SeqNumber = cursor
mintEntry.Source = cause.Data.From
mintEntry.TokenAddress = token.EVMAddress
mintEntry.TokenURL = token.URL
mintEntry.TxID = tx.TxID
operation := &fees.Operation{
Token: token,
Amount: amount.Int64(),
}
outAmount, err := operation.ApplyFees(&global.BridgeFees, fees.OP_MINT)
// skip if output amount is invalid (too low or negative, e.g.)
if err != nil {
continue
}
// update amount
outAmountBigInt := new(big.Int)
outAmountBigInt.SetInt64(outAmount)
// outAmountHuman := float64(outAmount) / math.Pow10(int(token.Precision))
// generate mint tx data
data, err := abiutil.GenerateMintTxData(token.EVMAddress, cause.Transaction.Header.Memo, outAmountBigInt)
if err != nil {
fmt.Println("[mint] can not generate mint tx:", err)
// if we are here, then something unexpected happened
// reset cursor and break to start over
cursor = start - 1
break
}
// generate gnosis safe tx
contractHash, signature, err := g.SignMintTx(token.EVMAddress, cause.Transaction.Header.Memo, outAmountBigInt)
if err != nil {
fmt.Println("[mint] can not sign mint tx:", err)
// if we are here, then something unexpected happened
// reset cursor and break to start over
cursor = start - 1
break
}
// submit multisig tx to the gnosis safe api
safeTx := gnosis.NewMultisigTx{}
safeTx.To = g.BridgeAddress
safeTx.Data = hexutil.Encode(data)
safeTx.GasToken = abiutil.ZERO_ADDR
safeTx.RefundReceiver = abiutil.ZERO_ADDR
safeTx.Nonce = nonce
safeTx.ContractTransactionHash = hexutil.Encode(contractHash)
safeTx.Sender = g.PublicKey.Hex()
safeTx.Signature = hexutil.Encode(signature)
err = g.CreateSafeMultisigTx(&safeTx)
if err != nil {
fmt.Println("[mint] gnosis safe api error:", err)
// if we are here, then something happened on the gnosis api side
// reset cursor and break to start over
cursor = start - 1
break
}
// create accumulate data entry
mintEntry.SafeTxHash = hexutil.Encode(contractHash)
mintEntry.SafeTxNonce = nonce
mintEntryBytes, err := json.Marshal(mintEntry)
if err != nil {
fmt.Println("[mint] can not marshal mint entry:", err)
// if we are here, then something unexpected happened
// reset cursor and break to start over
cursor = start - 1
break
}
var content [][]byte
content = append(content, []byte(accumulate.MINT_QUEUE_VERSION))
content = append(content, mintEntryBytes)
entryhash, err := a.WriteData(mintQueue, content)
if err != nil {
fmt.Println("[mint] data entry creation failed:", err)
// if we are here, then something happened on the accumulate api side
// reset cursor and break to start over
cursor = start - 1
break
}
fmt.Println("[mint] data entry created:", entryhash)
break
}
} else {
// if no tx found, move cursor back by 1 to start over from the same seq number
cursor--
}
LatestCheckedDeposits[token.Symbol] = cursor