/
bot.go
1310 lines (1140 loc) · 40 KB
/
bot.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 bot
import (
"bytes"
"crypto/ecdsa"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"math/big"
"strings"
"time"
gethcmn "github.com/ethereum/go-ethereum/common"
gethtypes "github.com/ethereum/go-ethereum/core/types"
gethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/gcash/bchd/bchec"
"github.com/gcash/bchd/btcjson"
"github.com/gcash/bchd/chaincfg"
"github.com/gcash/bchd/wire"
"github.com/gcash/bchutil"
log "github.com/sirupsen/logrus"
"github.com/smartbch/atomic-swap-bot/htlcbch"
"github.com/smartbch/atomic-swap-bot/htlcsbch"
)
/*
action & state:
+--------+ +========+
| action | | state |
+--------+ +========+
BCH=>SBCH, normal flow:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+----------+ +----------+ +-------------+ +-----------+ +------------+ +-----------+
| user | | bot | | bot(master) | | user | | bot | | bot |
+----------+ => +----------+ => +-------------+ => +-----------+ => +------------+ => +-----------+
| send BCH | | find BCH | | send sBCH | | send sBCH | | find sBCH | | send BCH |
| lock tx | | lock tx | | lock tx | | unlock tx | | unlock log | | unlock tx |
+----------+ +----------+ +-------------+ +-----------+ +------------+ +-----------+
/ / _______________/ __________/
/ / / /
+=====+ +============+ +================+ +==============+
| New | ---> | SbchLocked | ---> | SecretRevealed | ---> | BchUnlocked |
+=====+ +============+ +================+ +==============+
\
\
+-------------+
| bot(slave) |
+-------------+
| find sBCH |
| lock log |
+-------------+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BCH=>SBCH, refund:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+----------+ +----------+ +-------------+ +-----------+
| user | | bot | | bot(master) | | bot |
+----------+ => +----------+ => +-------------+ ===> +-----------+
| send BCH | | find BCH | | send sBCH | | send sBCH |
| lock tx | | lock tx | | lock tx | | refund tx |
+----------+ +----------+ +-------------+ +-----------+
/ / /
/ / /
+=====+ +============+ +==============+
| New | ---> | SbchLocked | ---> | SbchRefunded |
+=====+ +============+ +==============+
\
\
+-------------+
| bot(slave) |
+-------------+
| find sBCH |
| lock log |
+-------------+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SBCH=>BCH, normal flow:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+----------+ +----------+ +-------------+ +-----------+ +------------+ +-----------+
| user | | bot | | bot(master) | | user | | bot | | bot |
+----------+ => +----------+ => +-------------+ => +-----------+ => +------------+ => +-----------+
| send sBCH| | find sBCH| | send BCH | | send BCH | | find BCH | | send sBCH |
| lock tx | | lock log | | lock tx | | unlock tx | | unlock tx | | unlock tx |
+----------+ +----------+ +-------------+ +-----------+ +------------+ +-----------+
/ / _______________/ __________/
/ / / /
+=====+ +============+ +================+ +==============+
| New | ---> | BchLocked | ---> | SecretRevealed | ---> | SbchUnlocked |
+=====+ +============+ +================+ +==============+
\
\
+-------------+
| bot(slave) |
+-------------+
| find BCH |
| lock tx |
+-------------+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SBCH=>BCH, refund:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+----------+ +----------+ +-------------+ +-----------+
| user | | bot | | bot(master) | | bot |
+----------+ => +----------+ => +-------------+ ===> +-----------+
| send sBCH| | find sBCH| | send BCH | | send BCH |
| lock tx | | lock log | | lock tx | | refund tx |
+----------+ +----------+ +-------------+ +-----------+
/ / /
/ / /
+=====+ +============+ +==============+
| New | ---> | BchLocked | ---> | BchRefunded |
+=====+ +============+ +==============+
\
\
+-------------+
| bot(slave) |
+-------------+
| find BCH |
| lock tx |
+-------------+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/*
M: master, S: slave
+-------------------------+-+-+----------------+----------------+
| BCH2SBCH: normal |M|S| old status | new status |
+-------------------------+-+-+----------------+----------------+
| handleBchDepositTxB2S |✓|✓| | New |
| handleBchUserDeposits |✓| | New | SbchLocked |
| handleSbchLockEventB2S | |✓| New | SbchLocked |
| handleSbchUnlockEvent |✓|✓| SbchLocked | SecretRevealed |
| unlockBchUserDeposits |✓|✓| SecretRevealed | BchUnlocked |
+-------------------------+-+-+----------------+----------------+
+-------------------------+-+-+----------------+----------------+
| BCH2SBCH: refund |M|S| old status | new status |
+-------------------------+-+-+----------------+----------------+
| handleBchDepositTxB2S |✓|✓| | New |
| handleBchUserDeposits |✓| | New | SbchLocked |
| handleSbchLockEventB2S | |✓| New | SbchLocked |
| refundLockedSbch |✓|✓| SbchLocked | SbchRefunded |
+-------------------------+-+-+----------------+----------------+
+-------------------------+-+-+----------------+----------------+
| BCH2SBCH: too late |M|S| old status | new status |
+-------------------------+-+-+----------------+----------------+
| handleBchDepositTxB2S |✓|✓| | New |
| handleBchUserDeposits |✓| | New | TooLate |
+-------------------------+-+-+----------------+----------------+
+-------------------------+-+-+----------------+----------------+
| SBCH2BCH: normal |M|S| old status | new status |
+-------------------------+-+-+----------------+----------------+
| handleSbchLockEventS2B |✓|✓| | New |
| handleSbchUserDeposits |✓| | New | BchLocked |
| handleBchDepositTxS2B | |✓| New | BchLocked |
| handleBchReceiptTx |✓|✓| BchLocked | SecretRevealed |
| unlockSbchUserDeposits |✓|✓| SecretRevealed | SbchUnlocked |
+-------------------------+-+-+----------------+----------------+
+-------------------------+-+-+----------------+----------------+
| SBCH2BCH: refund |M|S| old status | new status |
+-------------------------+-+-+----------------+----------------+
| handleSbchLockEventS2B |✓|✓| | New |
| handleSbchUserDeposits |✓| | New | BchLocked |
| handleBchDepositTxS2B | |✓| New | BchLocked |
| refundLockedBCH |✓|✓| BchLocked | BchRefunded |
+-------------------------+-+-+----------------+----------------+
+-------------------------+-+-+----------------+----------------+
| SBCH2BCH: too late |M|S| old status | new status |
+-------------------------+-+-+----------------+----------------+
| handleSbchLockEventS2B |✓|✓| | New |
| handleSbchUserDeposits |✓| | New | TooLate |
+-------------------------+-+-+----------------+----------------+
*/
const (
slaveDelayBchBlocks = 1
slaveDelaySeconds = 600 // 10m
)
type MarketMakerBot struct {
db DB
bchCli IBchClient
sbchCli ISbchClient
// BCH key
bchPrivKey *bchec.PrivateKey
bchPkh []byte
bchAddr bchutil.Address // P2PKH
// sBCH key
sbchPrivKey *ecdsa.PrivateKey
sbchAddr gethcmn.Address
// HTLC params
bchTimeLock uint16 // in blocks
sbchTimeLock uint32 // in seconds
penaltyRatio uint16 // in BPS
// bot params
serviceFeeRatio uint16 // in BPS
minSwapVal uint64 // in sats
maxSwapVal uint64 // in sats
bchConfirmations uint8
bchSendMinerFeeRate uint64 // sats/byte
bchReceiveMinerFeeRate uint64 // sats/byte
bchRefundMinerFeeRate uint64 // sats/byte
dbQueryLimit int
isSlaveMode bool
lazyMaster bool // debug only
}
func NewBot(
dbFile string,
bchPrivKeyWIF, sbchPrivKeyHex string, // master mode
bchMasterAddr, sbchMasterAddr string, // slave mode
bchRpcUrl, sbchRpcUrl string,
sbchHtlcAddr gethcmn.Address,
sbchGasPrice *big.Int,
bchConfirmations uint8,
bchSendMinerFeeRate, bchReceiveMinerFeeRate, bchRefundMinerFeeRate uint64,
sbchLockGasLimit, sbchUnlockGasLimit, sbchRefundGasLimit uint64,
dbQueryLimit int,
debugMode bool,
slaveMode bool,
lazyMaster bool, // debug only
) (*MarketMakerBot, error) {
// load BCH key
bchPrivKey, bchPbk, bchPkh, bchAddr, err := loadBchKey(
bchPrivKeyWIF, bchMasterAddr, debugMode, slaveMode)
if err != nil {
return nil, fmt.Errorf("failed to load BCH private key: %w", err)
}
// load sBCH key
sbchPrivKey, sbchAddr, err := loadSbchKey(sbchPrivKeyHex, sbchMasterAddr, slaveMode)
if err != nil {
return nil, fmt.Errorf("failed to load sBCH private key: %w", err)
}
// create RPC clients
bchCli, err := NewBchClient(bchRpcUrl, bchAddr)
if err != nil {
return nil, fmt.Errorf("faield to create BCH RPC client: %w", err)
}
sbchCli, err := newSbchClient(sbchRpcUrl, 5*time.Second, sbchPrivKey, sbchAddr, sbchHtlcAddr,
sbchGasPrice, sbchLockGasLimit, sbchUnlockGasLimit, sbchRefundGasLimit)
if err != nil {
return nil, fmt.Errorf("failed to create sBCH RPC client: %w", err)
}
botInfo, err := sbchCli.getMarketMakerInfo(sbchAddr)
if err != nil {
return nil, fmt.Errorf("failed to query bot info: %w", err)
}
if !bytes.Equal(bchPkh, botInfo.BchPkh[:]) {
return nil, fmt.Errorf("BCH PKH mismatch: %s != %s",
toHex(bchPkh), toHex(botInfo.BchPkh[:]))
}
// open DB
db, err := OpenDB(dbFile)
if err != nil {
return nil, fmt.Errorf("failed to open DB file: %w", err)
}
// print bot info
log.Info("BCH pubkey : ", "0x"+hex.EncodeToString(bchPbk))
log.Info("BCH PKH : ", "0x"+hex.EncodeToString(bchPkh))
log.Info("BCH address : ", bchAddr.String())
log.Info("sBCH address: ", sbchAddr.String())
return &MarketMakerBot{
db: db,
bchCli: bchCli,
bchPrivKey: bchPrivKey,
bchPkh: bchPkh,
bchAddr: bchAddr,
sbchCli: sbchCli,
sbchPrivKey: sbchPrivKey,
sbchAddr: sbchAddr,
bchTimeLock: botInfo.BchLockTime,
sbchTimeLock: botInfo.SbchLockTime,
penaltyRatio: botInfo.PenaltyBPS,
serviceFeeRatio: botInfo.FeeBPS,
minSwapVal: weiToSats(botInfo.MinSwapAmt),
maxSwapVal: weiToSats(botInfo.MaxSwapAmt),
bchSendMinerFeeRate: bchSendMinerFeeRate,
bchReceiveMinerFeeRate: bchReceiveMinerFeeRate,
bchRefundMinerFeeRate: bchRefundMinerFeeRate,
bchConfirmations: bchConfirmations,
dbQueryLimit: dbQueryLimit,
isSlaveMode: slaveMode,
lazyMaster: debugMode && lazyMaster,
}, nil
}
func loadBchKey(privKeyWIF, masterAddr string, debugMode, slaveMode bool,
) (privKey *bchec.PrivateKey, pubKey, pkh []byte, addr *bchutil.AddressPubKeyHash, err error) {
params := getBchParams(debugMode)
if !slaveMode {
// master mode
var wif *bchutil.WIF
wif, err = bchutil.DecodeWIF(privKeyWIF)
if err != nil {
err = fmt.Errorf("failed to decode WIF: %w", err)
return
}
privKey = wif.PrivKey
pubKey = privKey.PubKey().SerializeCompressed()
pkh = bchutil.Hash160(pubKey)
addr, err = bchutil.NewAddressPubKeyHash(pkh, params)
if err != nil {
err = fmt.Errorf("failed to derive BCH address: %w", err)
}
return
}
// slave mode
if masterAddr == "" {
err = fmt.Errorf("missing bchMasterAddr")
return
}
_addr, _err := bchutil.DecodeAddress(masterAddr, params)
if _err != nil {
err = fmt.Errorf("failed to decode master address: %w", _err)
return
}
ok := false
addr, ok = _addr.(*bchutil.AddressPubKeyHash)
if !ok {
err = fmt.Errorf("failed to cast master address")
return
}
pkh = addr.Hash160()[:]
privKey = nil
pubKey = nil
return
}
func loadSbchKey(privKeyHex, masterAddr string, slaveMode bool,
) (privKey *ecdsa.PrivateKey, addr gethcmn.Address, err error) {
privKey, err = gethcrypto.HexToECDSA(privKeyHex)
if err != nil {
err = fmt.Errorf("failed to load sBCH private key: %w", err)
return
}
if !slaveMode {
// master mode
addr = gethcrypto.PubkeyToAddress(privKey.PublicKey)
return
}
// slave mode
if masterAddr == "" {
err = fmt.Errorf("missing sbchMasterAddr")
return
}
addr = gethcmn.HexToAddress(masterAddr)
return
}
func getBchParams(debugMode bool) *chaincfg.Params {
if debugMode {
return &chaincfg.TestNet3Params
}
return &chaincfg.MainNetParams
}
func (bot *MarketMakerBot) PrepareDB() {
_, err := bot.db.getLastHeights()
if err == nil || !strings.HasPrefix(err.Error(), "no such table") {
return
}
log.Info("init DB, sync schemas ...")
if err = bot.db.syncSchemas(); err != nil {
log.Fatal(err)
}
log.Info("init last BCH & sBCH heights ...")
if err = bot.db.initLastHeights(0, 0); err != nil {
log.Fatal(err)
}
}
func (bot *MarketMakerBot) GetUTXOs() ([]btcjson.ListUnspentResult, error) {
return bot.bchCli.getAllUTXOs()
}
func (bot *MarketMakerBot) Loop() {
for {
log.Info("---------- ", time.Now(), "' ----------")
bot.refundLockedSbch()
gotNewBlocks := bot.scanBchBlocks()
bot.refundLockedBCH(gotNewBlocks)
bot.handleBchUserDeposits()
bot.unlockBchUserDeposits()
bot.scanSbchEvents()
bot.handleSbchUserDeposits()
bot.unlockSbchUserDeposits()
time.Sleep(2 * time.Second)
}
}
// scan & handle BCH blocks
func (bot *MarketMakerBot) scanBchBlocks() (gotNewBlocks bool) {
log.Info("scan BCH blocks ...")
lastBlockNum, err := bot.db.getLastBchHeight()
if err != nil {
log.Fatal("DB error, failed to get last BCH height: ", err)
return
}
log.Info("last BCH height: ", lastBlockNum)
latestBlockNum, err := bot.bchCli.getBlockCount()
if err != nil {
log.Error("RPC error, failed to get BCH height: ", err)
return
}
log.Info("latest BCH height: ", latestBlockNum)
safeNewBlockNum := latestBlockNum - int64(bot.bchConfirmations)
if lastBlockNum == 0 {
lastBlockNum = uint64(safeNewBlockNum) - 1
log.Info("init last BCH height: ", lastBlockNum)
}
for h := int64(lastBlockNum) + 1; h <= safeNewBlockNum; h++ {
if !bot.handleBchBlock(h) {
break
}
}
gotNewBlocks = safeNewBlockNum > int64(lastBlockNum)
return gotNewBlocks
}
// handle BCH lock|unlock|refund txs
func (bot *MarketMakerBot) handleBchBlock(h int64) bool {
//log.Info("get BCH block#", h, " ...")
block, err := bot.bchCli.getBlock(h)
if err != nil {
log.Error("RPC error, failed to get BCH block#", h, " : ", err)
return false
}
log.Info("got BCH block#", h)
bot.handleBchDepositTxs(uint64(h), block)
bot.handleBchReceiptTxs(block)
err = bot.db.setLastBchHeight(uint64(h))
if err != nil {
log.Fatal("DB error, failed to update last BCH height: ", err)
}
return true
}
// find and handle BCH lock txs
func (bot *MarketMakerBot) handleBchDepositTxs(h uint64, block *wire.MsgBlock) {
deposits := htlcbch.GetHtlcLocksInfo(block)
log.Info("HTLC deposits: ", len(deposits))
for _, deposit := range deposits {
log.Info("HTLC deposit: ", toJSON(deposit))
bot.handleBchDepositTxB2S(h, deposit)
bot.handleBchDepositTxS2B(h, deposit)
}
}
// create bch2sbch records (status=new)
func (bot *MarketMakerBot) handleBchDepositTxB2S(h uint64, deposit *htlcbch.HtlcLockInfo) {
log.Info("handleBchDepositTxB2S")
if !bytes.Equal(deposit.RecipientPkh, bot.bchPkh) {
log.Info("not send to me, recipientPkh: ",
toHex(deposit.RecipientPkh))
return
}
if deposit.Expiration != bot.bchTimeLock {
log.Infof("invalid expiration: %d != %d",
deposit.Expiration, bot.bchTimeLock)
return
}
if deposit.PenaltyBPS != bot.penaltyRatio {
log.Infof("invalid penaltyRatio: %d != %d",
deposit.PenaltyBPS, bot.penaltyRatio)
return
}
if deposit.Value < bot.minSwapVal ||
(bot.maxSwapVal > 0 && deposit.Value > bot.maxSwapVal) {
log.Infof("value out of range: %d ∉ [%d, %d]",
deposit.Value, bot.minSwapVal, bot.maxSwapVal)
return
}
err := bot.db.addBch2SbchRecord(&Bch2SbchRecord{
BchLockHeight: h,
BchLockTxHash: deposit.TxHash,
Value: deposit.Value,
RecipientPkh: toHex(deposit.RecipientPkh),
SenderPkh: toHex(deposit.SenderPkh),
HashLock: toHex(deposit.HashLock),
TimeLock: uint32(deposit.Expiration),
PenaltyBPS: deposit.PenaltyBPS,
SenderEvmAddr: toHex(deposit.SenderEvmAddr),
HtlcScriptHash: toHex(deposit.ScriptHash),
})
if err != nil {
log.Error("DB error, failed to save BCH2SBCH record: ", err)
}
}
// for sbch2bch record, change status from New to BchLocked
func (bot *MarketMakerBot) handleBchDepositTxS2B(h uint64, deposit *htlcbch.HtlcLockInfo) {
if !bot.isSlaveMode {
return
}
log.Info("handleBchDepositTxS2B")
if !bytes.Equal(deposit.SenderPkh, bot.bchPkh) {
log.Info("not locked by me, senderPkh: ",
toHex(deposit.SenderPkh))
return
}
hashLock := toHex(deposit.HashLock)
record, err := bot.db.getSbch2BchRecordByHashLock(hashLock)
if err != nil {
log.Info("DB error, Sbch2BchRecord not found, hashLock: ", hashLock)
}
// TODO: add more checks
record.UpdateStatusToBchLocked(deposit.TxHash)
err = bot.db.updateSbch2BchRecord(record)
if err != nil {
log.Error("DB error, failed to update status of SBCH2BCH record: ", err)
}
}
// find and handle BCH unlock txs
func (bot *MarketMakerBot) handleBchReceiptTxs(block *wire.MsgBlock) {
receipts := htlcbch.GetHtlcUnlocksInfo(block)
log.Info("HTLC receipts: ", len(receipts))
for _, receipt := range receipts {
log.Info("HTLC receipt:", toJSON(receipt))
bot.handleBchReceiptTx(receipt)
}
}
// for sbch2bch records, change status from BchLocked to SecretRevealed
func (bot *MarketMakerBot) handleBchReceiptTx(receipt *htlcbch.HtlcUnlockInfo) {
log.Info("handleBchReceiptTx")
record, err := bot.db.getSbch2BchRecordByBchLockTxHash(receipt.PrevTxHash)
if err != nil {
log.Infof("can not get Sbch2BchRecord, BchLockTxHash=%s",
receipt.TxHash)
return
}
//log.Info(record)
hashLock := secretToHashLock(gethcmn.FromHex(receipt.Secret))
if hashLock != record.HashLock {
log.Warnf("hashLock not match! secret: %s => hashLock: %s, DB hashLock: %s, ",
receipt.Secret, hashLock, record.HashLock)
return
}
//if record.Status != Sbch2BchStatusBchLocked {
// log.Infof("wrong status: %s", toJSON(record))
// continue
//}
record.UpdateStatusToSecretRevealed(receipt.Secret, receipt.TxHash)
err = bot.db.updateSbch2BchRecord(record)
if err != nil {
log.Error("DB error, failed to update status of SBCH2BCH record: ", err)
}
}
func (bot *MarketMakerBot) scanSbchEvents() {
log.Info("scan sBCH events ...")
lastBlockNum, err := bot.db.getLastSbchHeight()
if err != nil {
log.Fatal("failed to get last height of smartBCH from DB: ", err)
return
}
log.Info("last sBCH height: ", lastBlockNum)
newBlockNum, err := bot.sbchCli.getBlockNumber()
if err != nil {
log.Error("failed to get height of smartBCH: ", err)
return
}
log.Info("latest sBCH height: ", newBlockNum)
if lastBlockNum == 0 {
lastBlockNum = newBlockNum - 1
log.Info("init last sBCH height: ", lastBlockNum)
}
blockBatch := uint64(200)
for fromH := lastBlockNum + 1; fromH <= newBlockNum; fromH += blockBatch {
toH := fromH + blockBatch - 1
if toH > newBlockNum {
toH = newBlockNum
}
if !bot.handleSbchEvents(fromH, toH) {
break
}
}
}
func (bot *MarketMakerBot) handleSbchEvents(fromH, toH uint64) bool {
logs, err := bot.sbchCli.getHtlcLogs(fromH, toH)
if err != nil {
log.Error("failed to get smartBCH logs: ", err)
return false
}
log.Infof("sBCH logs (block#%d ~ block#%d): %d",
fromH, toH, len(logs))
for _, ethLog := range logs {
log.Info("sBCH log: ", toJSON(ethLog))
switch ethLog.Topics[0] {
case htlcsbch.LockEventId:
bot.handleSbchLockEventS2B(ethLog)
bot.handleSbchLockEventB2S(ethLog)
case htlcsbch.UnlockEventId:
bot.handleSbchUnlockEvent(ethLog)
}
}
err = bot.db.setLastSbchHeight(toH)
if err != nil {
log.Fatal("DB error, failed to update last sBCH height: ", err)
}
return true
}
// find sBCH lock events, create sbch2bch records (status = new)
func (bot *MarketMakerBot) handleSbchLockEventS2B(ethLog gethtypes.Log) {
lockLog := htlcsbch.ParseHtlcLockLog(ethLog)
if lockLog == nil {
return
}
if lockLog.UnlockerAddr != bot.sbchAddr {
log.Info("not locked to me",
", unlockerAddr: ", lockLog.UnlockerAddr.String(),
//", botAddr: ", bot.sbchAddr.String(),
)
return
}
zeroAddr := gethcmn.Address{}
if lockLog.BchRecipientPkh == zeroAddr {
log.Info("BchRecipientPkh is zero, skip")
return
}
penaltyBPS := lockLog.PenaltyBPS
if penaltyBPS != bot.penaltyRatio {
log.Infof("invalid penaltyRatio: %d != %d",
penaltyBPS, bot.penaltyRatio)
return
}
sbchTimeLock := uint32(lockLog.UnlockTime - lockLog.CreatedTime)
if sbchTimeLock != bot.sbchTimeLock {
log.Infof("invalid TimeLock: %d != %d",
sbchTimeLock, bot.sbchTimeLock)
return
}
valSats := weiToSats(lockLog.Value)
if valSats < bot.minSwapVal ||
(bot.maxSwapVal > 0 && valSats > bot.maxSwapVal) {
log.Infof("value out of range: %d ∉ [%d, %d]",
valSats, bot.minSwapVal, bot.maxSwapVal)
return
}
log.Info("got a sBCH Lock log: ", toJSON(lockLog))
bchTimeLock := sbchTimeLockToBlocks(sbchTimeLock) / 2
covenant, err := htlcbch.NewMainnetCovenant(bot.bchPkh,
lockLog.BchRecipientPkh[:], lockLog.HashLock[:], bchTimeLock, 0)
if err != nil {
log.Error("failed to create HTLC covenant: ", err)
return
}
scriptHash, err := covenant.GetRedeemScriptHash()
if err != nil {
log.Error("failed to get script hash: ", err)
return
}
err = bot.db.addSbch2BchRecord(&Sbch2BchRecord{
SbchLockTime: lockLog.CreatedTime,
SbchLockTxHash: toHex(ethLog.TxHash[:]),
Value: valSats,
SbchSenderAddr: toHex(lockLog.LockerAddr[:]),
BchRecipientPkh: toHex(lockLog.BchRecipientPkh[:]),
HashLock: toHex(lockLog.HashLock[:]),
TimeLock: sbchTimeLock,
PenaltyBPS: penaltyBPS,
HtlcScriptHash: toHex(scriptHash),
})
if err != nil {
log.Error("DB error, failed to save SBCH2BCH record: ", err)
}
}
// bch2sbch record: New => SbchLocked
func (bot *MarketMakerBot) handleSbchLockEventB2S(ethLog gethtypes.Log) {
if !bot.isSlaveMode {
return
}
lockLog := htlcsbch.ParseHtlcLockLog(ethLog)
if lockLog == nil {
return
}
if lockLog.LockerAddr != bot.sbchAddr {
log.Info("not opened by master",
", lockerAddr: ", lockLog.LockerAddr.String(),
//", botAddr: ", bot.sbchAddr.String(),
)
return
}
log.Info("got a sBCH Lock log (slave): ", toJSON(lockLog))
record, err := bot.db.getBch2SbchRecordByHashLock(toHex(lockLog.HashLock[:]))
if err != nil {
log.Error("DB error:", err)
return
}
if record.Status != Bch2SbchStatusNew {
return
}
txTime, err := bot.sbchCli.getTxTime(ethLog.TxHash)
if err != nil {
log.Error("RPC error, failed to get sBCH tx time:", err)
txTime = uint64(time.Now().Unix())
}
record.UpdateStatusToSbchLocked(toHex(ethLog.TxHash[:]), txTime)
err = bot.db.updateBch2SbchRecord(record)
if err != nil {
log.Error("DB error, failed to update status of BCH2SBCH record: ", err)
}
}
// bch2sbch records: SbchLocked => SecretRevealed
func (bot *MarketMakerBot) handleSbchUnlockEvent(ethLog gethtypes.Log) {
unlockLog := htlcsbch.ParseHtlcUnlockLog(ethLog)
if unlockLog == nil {
return
}
log.Info("got a sBCH Unlock log: ", toJSON(unlockLog))
hashLock := toHex(unlockLog.HashLock[:])
record, err := bot.db.getBch2SbchRecordByHashLock(hashLock)
//log.Info(record)
if err != nil {
log.Infof("can not get Bch2SbchRecord, hashLock=%s", hashLock)
return
}
hashLock2 := secretToHashLock(unlockLog.Secret[:])
if hashLock2 != hashLock {
log.Warnf("hashLock not match! secret: %s => hashLock: %s, DB hashLock: %s, ",
toHex(unlockLog.Secret[:]), hashLock2, hashLock)
return
}
if record.Status != Bch2SbchStatusSbchLocked {
return
}
record.UpdateStatusToSecretRevealed(toHex(unlockLog.Secret[:]), toHex(unlockLog.TxHash[:]))
err = bot.db.updateBch2SbchRecord(record)
if err != nil {
log.Error("DB error, failed to update status of BCH2SBCH record: ", err)
return
}
}
// bch2sbch records: New => SbchLocked|TooLateToLockSbch
func (bot *MarketMakerBot) handleBchUserDeposits() {
if bot.isSlaveMode {
return
}
log.Info("handle BCH user deposits ...")
records, err := bot.db.getBch2SbchRecordsByStatus(Bch2SbchStatusNew, bot.dbQueryLimit)
if err != nil {
log.Error("DB error, failed to get BCH2SBCH records: ", err)
return
}
log.Info("unhandled BCH user deposits: ", len(records))
for _, record := range records {
log.Info("handle BCH user deposit: ", toJSON(record))
//confirmations := currBlockNum - int64(record.BchLockHeight) + 1
confirmations, err := bot.bchCli.getTxConfirmations(record.BchLockTxHash)
if err != nil {
log.Error("RPC error, failed to get tx confirmations: ", err)
continue
}
// do not send sBCH to user if it's too late!
if confirmations > int64(bot.bchTimeLock)/3 {
log.Info("too late to lock sBCH",
", confirmations: ", confirmations,
", timeLock: ", record.TimeLock)
record.Status = Bch2SbchStatusTooLateToLockSbch
err = bot.db.updateBch2SbchRecord(record)
if err != nil {
log.Error("DB error, failed to update status of BCH2SBCH record: ", err)
}
continue
}
sbchTimeLock := bchTimeLockToSeconds(record.TimeLock) / 2
bchValMinusFee := record.Value * (10000 - uint64(bot.serviceFeeRatio)) / 10000
log.Info("sbchTimeLock: ", sbchTimeLock, " , bchValMinusFee: ", bchValMinusFee)
txHash, err := bot.sbchCli.lockSbchToHtlc(
gethcmn.HexToAddress(record.SenderEvmAddr),
gethcmn.HexToHash(record.HashLock),
sbchTimeLock,
satsToWei(bchValMinusFee),
)
if err != nil {
log.Error("RPC error, failed to lock sBCH to HTLC: ", err)
continue
}
log.Info("lock sBCH successful",
", hashLock: ", record.HashLock,
", txHash: ", txHash.String())
txTime, err := bot.sbchCli.getTxTime(*txHash)
if err != nil {
log.Error("RPC error, failed to get sBCH tx time:", err)
txTime = uint64(time.Now().Unix())
}
record.UpdateStatusToSbchLocked(toHex(txHash[:]), txTime)
err = bot.db.updateBch2SbchRecord(record)
if err != nil {
log.Error("DB error, failed to update status of BCH2SBCH record: ", err)
}
}
}
// sbch2bch records: New => BchLocked|TooLateToLockSbch
func (bot *MarketMakerBot) handleSbchUserDeposits() {
if bot.isSlaveMode {
return
}
log.Info("handle sBCH user deposits ...")
lastBlockNum, err := bot.db.getLastBchHeight()
if err != nil {
log.Fatal("DB error, failed to get last BCH height: ", err)
return
}
log.Info("last BCH height: ", lastBlockNum)
records, err := bot.db.getSbch2BchRecordsByStatus(Sbch2BchStatusNew, bot.dbQueryLimit)
if err != nil {
log.Error("DB error, failed to get unhandled sBCH user deposits: ", err)
return
}
log.Info("unhandled sBCH user deposits: ", len(records))
for _, record := range records {
log.Info("SBCH2BCH record: ", toJSON(record))
bchValMinusFee := int64(record.Value) * (10000 - int64(bot.serviceFeeRatio)) / 10000
utxos, err := bot.bchCli.getUTXOs(bchValMinusFee+5000, 10)
if err != nil {
log.Error("failed to get UTXOs: ", err)
continue
}
log.Info("bchValMinusFee: ", bchValMinusFee, ", UTXOs:", toJSON(utxos))
inputs := make([]htlcbch.InputInfo, len(utxos))
for i, utxo := range utxos {
inputs[i] = htlcbch.InputInfo{
TxID: gethcmn.FromHex(utxo.TxID),
Vout: utxo.Vout,
Amount: utxoAmtToSats(utxo.Amount),
}
}
currTime, err := bot.sbchCli.getBlockTimeLatest()
if err != nil {
log.Error("RPC error, failed to get sBCH time: ", err)
continue
}
// do not send BCH to user if its too late!
timeElapsed := currTime - record.SbchLockTime
if uint32(timeElapsed) > bot.sbchTimeLock/3 {
log.Info("too late to lock BCH, time elapsed: ", timeElapsed, ", timeLock: ", record.TimeLock)
record.Status = Sbch2BchStatusTooLateToLockBch
err = bot.db.updateSbch2BchRecord(record)
if err != nil {
log.Error("DB error, failed to update status of SBCH2BCH record: ", err)
}
continue
} else {
log.Info("time elapsed: ", timeElapsed, ", timeLock: ", record.TimeLock)
}
bchTimeLock := sbchTimeLockToBlocks(record.TimeLock) / 2
log.Info("BCH timeLock: ", bchTimeLock)
covenant, err := htlcbch.NewMainnetCovenant(
bot.bchPkh,
gethcmn.FromHex(record.BchRecipientPkh),
gethcmn.FromHex(record.HashLock),
bchTimeLock,
0,
)
if err != nil {
log.Error("failed to create HTLC covenant: ", err)
continue
}
tx, err := covenant.MakeLockTx(
bot.bchPrivKey,
inputs,
bchValMinusFee,
bot.bchSendMinerFeeRate,
)
if err != nil {
log.Error("failed to create BCH tx: ", err)
continue
}
log.Info("BCH tx hex: ", htlcbch.MsgTxToHex(tx))
txHash, err := bot.bchCli.SendTx(tx)
if err != nil {
log.Error("failed to send BCH tx: ", err)
// more debug info
//prevPkScript, _ := htlcbch.PayToPubKeyHashPkScript(bot.bchPkh)
//log.Infof("meep debug --tx=%s --idx=%d --amt=%d --pkscript=%s",
// htlcbch.MsgTxToHex(tx), 0, utxoAmtToSats(utxo.Amount), toHex(prevPkScript))
continue
}
log.Info("BCH tx sent, hash: ", txHash.String())
record.UpdateStatusToBchLocked(txHash.String())
err = bot.db.updateSbch2BchRecord(record)
if err != nil {
log.Error("DB error, failed to update status of SBCH2BCH record: ", err)
}
}
}
// bch2sbch records: SecretRevealed => BchUnlocked
func (bot *MarketMakerBot) unlockBchUserDeposits() {
log.Info("unlock BCH user deposits ...")