-
Notifications
You must be signed in to change notification settings - Fork 84
/
swap.go
2400 lines (2158 loc) · 82 KB
/
swap.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
// This code is available on the terms of the project LICENSE.md file,
// also available online at https://blueoakcouncil.org/license/1.0.0.
package swap
import (
"bytes"
"context"
"errors"
"fmt"
"sync"
"time"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/calc"
"decred.org/dcrdex/dex/encode"
"decred.org/dcrdex/dex/msgjson"
"decred.org/dcrdex/dex/order"
"decred.org/dcrdex/dex/wait"
"decred.org/dcrdex/server/account"
"decred.org/dcrdex/server/asset"
"decred.org/dcrdex/server/auth"
"decred.org/dcrdex/server/coinlock"
"decred.org/dcrdex/server/comms"
"decred.org/dcrdex/server/db"
"decred.org/dcrdex/server/matcher"
)
var (
// The coin waiter will query for transaction data every recheckInterval.
recheckInterval = time.Second * 3
// txWaitExpiration is the longest the Swapper will wait for a coin waiter.
// This could be thought of as the maximum allowable backend latency.
txWaitExpiration = 2 * time.Minute
)
func unixMsNow() time.Time {
return time.Now().Truncate(time.Millisecond).UTC()
}
func makerTaker(isMaker bool) string {
if isMaker {
return "maker"
}
return "taker"
}
// AuthManager handles client-related actions, including authorization and
// communications.
type AuthManager interface {
Route(string, func(account.AccountID, *msgjson.Message) *msgjson.Error)
Auth(user account.AccountID, msg, sig []byte) error
Sign(...msgjson.Signable)
Send(account.AccountID, *msgjson.Message) error
Request(account.AccountID, *msgjson.Message, func(comms.Link, *msgjson.Message)) error
RequestWithTimeout(user account.AccountID, req *msgjson.Message, handlerFunc func(comms.Link, *msgjson.Message),
expireTimeout time.Duration, expireFunc func()) error
SwapSuccess(user account.AccountID, mmid db.MarketMatchID, value uint64, refTime time.Time)
Inaction(user account.AccountID, misstep auth.NoActionStep, mmid db.MarketMatchID, matchValue uint64, refTime time.Time, oid order.OrderID)
}
// Storage updates match data in what is presumably a database.
type Storage interface {
db.SwapArchiver
LastErr() error
Fatal() <-chan struct{}
Order(oid order.OrderID, base, quote uint32) (order.Order, order.OrderStatus, error)
CancelOrder(*order.LimitOrder) error
InsertMatch(match *order.Match) error
}
// swapStatus is information related to the completion or incompletion of each
// sequential step of the atomic swap negotiation process. Each user has their
// own swapStatus.
type swapStatus struct {
// The asset to which the user broadcasts their swap transaction.
swapAsset uint32
redeemAsset uint32
mtx sync.RWMutex
// The time that the swap coordinator sees the transaction.
swapTime time.Time
swap *asset.Contract
// The time that the transaction receives its SwapConf'th confirmation.
swapConfirmed time.Time
// The time that the swap coordinator sees the user's redemption
// transaction.
redeemTime time.Time
redemption asset.Coin
}
// String satisfies the Stringer interface for pretty printing. The swapStatus
// RWMutex should be held for reads when using.
func (ss *swapStatus) String() string {
return fmt.Sprintf("swapAsset: %d, redeemAsset: %d, swapTime: %v, swap: %v, swapConfirmed: %v, redeemTime: %v, redemption: %v",
ss.swapAsset, ss.redeemAsset, ss.swapTime, ss.swap, ss.swapConfirmed, ss.redeemTime, ss.redemption)
}
func (ss *swapStatus) swapConfTime() time.Time {
ss.mtx.RLock()
defer ss.mtx.RUnlock()
return ss.swapConfirmed
}
func (ss *swapStatus) redeemSeenTime() time.Time {
ss.mtx.RLock()
defer ss.mtx.RUnlock()
return ss.redeemTime
}
// matchTracker embeds an order.Match and adds some data necessary for tracking
// the match negotiation.
type matchTracker struct {
mtx sync.RWMutex // Match.Sigs and Match.Status
*order.Match
time time.Time // the match request time, not epoch close
matchTime time.Time // epoch close time
makerStatus *swapStatus
takerStatus *swapStatus
}
// expiredBy returns true if the lock time of either party's *known* swap is
// before the reference time e.g. time.Now().
func (mt *matchTracker) expiredBy(ref time.Time) bool {
mSwap, tSwap := mt.makerStatus.swap, mt.takerStatus.swap
return (tSwap != nil && tSwap.LockTime.Before(ref)) ||
(mSwap != nil && mSwap.LockTime.Before(ref))
}
// A blockNotification is used internally when an asset.Backend reports a new
// block.
type blockNotification struct {
time time.Time
assetID uint32
err error
}
// A stepActor is a structure holding information about one party of a match.
// stepActor is used with the stepInformation structure, which is used for
// sequencing swap negotiation.
type stepActor struct {
user account.AccountID
// swapAsset is the asset to which this actor broadcasts their swap tx.
swapAsset uint32
isMaker bool
order order.Order
// The swapStatus from the Match. Could be either the
// (matchTracker).makerStatus or (matchTracker).takerStatus, depending on who
// this actor is.
status *swapStatus
}
// String satisfies the Stringer interface for pretty printing. The swapStatus
// RWMutex should be held for reads when using for a.status reads.
func (a stepActor) String() string {
return fmt.Sprintf("user: %v, swapAsset: %v, isMaker: %v, order: %v, status: {%v}",
a.user, a.swapAsset, a.isMaker, a.order, a.status)
}
// stepInformation holds information about the current state of the swap
// negotiation. A new stepInformation should be generated with (Swapper).step at
// every step of the negotiation process.
type stepInformation struct {
match *matchTracker
// The actor is the user info for the user who is expected to be broadcasting
// a swap or redemption transaction next.
actor stepActor
// counterParty is the user that is not expected to be acting next.
counterParty stepActor
// asset is the asset backend for swapAsset.
asset *asset.BackedAsset
// isBaseAsset will be true if the current step involves a transaction on the
// match market's base asset blockchain, false if on quote asset's blockchain.
isBaseAsset bool
step order.MatchStatus
nextStep order.MatchStatus
// checkVal holds the trade amount in units of the currently acting asset,
// and is used to validate the swap transaction details.
checkVal uint64
}
// SwapperAsset is a BackedAsset with an optional CoinLocker.
type SwapperAsset struct {
*asset.BackedAsset
Locker coinlock.CoinLocker // should be *coinlock.AssetCoinLocker
}
// Swapper handles order matches by handling authentication and inter-party
// communications between clients, or 'users'. The Swapper authenticates users
// (vua AuthManager) and validates transactions as they are reported.
type Swapper struct {
// coins is a map to all the Asset information, including the asset backends,
// used by this Swapper.
coins map[uint32]*SwapperAsset
// storage is a Database backend.
storage Storage
// authMgr is an AuthManager for client messaging and authentication.
authMgr AuthManager
// swapDone is callback for reporting a swap outcome.
swapDone func(oid order.Order, match *order.Match, fail bool)
// The matches maps and the contained matches are protected by the matchMtx.
matchMtx sync.RWMutex
matches map[order.MatchID]*matchTracker
userMatches map[account.AccountID]map[order.MatchID]*matchTracker
acctMatches map[uint32]map[string]map[order.MatchID]*matchTracker
// The broadcast timeout.
bTimeout time.Duration
// Expected locktimes for maker and taker swaps.
lockTimeTaker time.Duration
lockTimeMaker time.Duration
// latencyQ is a queue for coin waiters to deal with network latency.
latencyQ *wait.TickerQueue
// handlerMtx should be read-locked for the duration of the comms route
// handlers (handleInit and handleRedeem) and Negotiate. This blocks
// shutdown until any coin waiters are registered with latencyQ. It should
// be write-locked before setting the stop flag.
handlerMtx sync.RWMutex
// stop is used to prevent new handlers from starting coin waiters. It is
// set to true during shutdown of Run.
stop bool
}
// Config is the swapper configuration settings. A Config instance is the only
// argument to the Swapper constructor.
type Config struct {
// Assets is a map to all the asset information, including the asset backends,
// used by this Swapper.
Assets map[uint32]*SwapperAsset
// AuthManager is the auth manager for client messaging and authentication.
AuthManager AuthManager
// A database backend.
Storage Storage
// BroadcastTimeout is how long the Swapper will wait for expected swap
// transactions following new blocks.
BroadcastTimeout time.Duration
// LockTimeTaker is the locktime Swapper will use for auditing taker swaps.
LockTimeTaker time.Duration
// LockTimeMaker is the locktime Swapper will use for auditing maker swaps.
LockTimeMaker time.Duration
// NoResume indicates that the swapper should not resume active swaps.
NoResume bool
// AllowPartialRestore indicates if it is acceptable to load only some of
// the active swaps if the Swapper's asset configuration lacks assets
// required to load them all.
AllowPartialRestore bool
// SwapDone registers a match with the DEX manager (or other consumer) for a
// given order as being finished.
SwapDone func(oid order.Order, match *order.Match, fail bool)
}
// NewSwapper is a constructor for a Swapper.
func NewSwapper(cfg *Config) (*Swapper, error) {
for _, asset := range cfg.Assets {
if asset.MaxFeeRate == 0 {
return nil, fmt.Errorf("max fee rate of 0 is invalid for asset %q", asset.Symbol)
}
}
acctMatches := make(map[uint32]map[string]map[order.MatchID]*matchTracker)
for _, a := range cfg.Assets {
if _, ok := a.Backend.(asset.AccountBalancer); ok {
acctMatches[a.ID] = make(map[string]map[order.MatchID]*matchTracker)
}
}
authMgr := cfg.AuthManager
swapper := &Swapper{
coins: cfg.Assets,
storage: cfg.Storage,
authMgr: authMgr,
swapDone: cfg.SwapDone,
latencyQ: wait.NewTickerQueue(recheckInterval),
matches: make(map[order.MatchID]*matchTracker),
userMatches: make(map[account.AccountID]map[order.MatchID]*matchTracker),
acctMatches: acctMatches,
bTimeout: cfg.BroadcastTimeout,
lockTimeTaker: cfg.LockTimeTaker,
lockTimeMaker: cfg.LockTimeMaker,
}
// Ensure txWaitExpiration is not greater than broadcast timeout setting.
if sensible := swapper.bTimeout; txWaitExpiration > sensible {
txWaitExpiration = sensible
}
if !cfg.NoResume {
err := swapper.restoreActiveSwaps(cfg.AllowPartialRestore)
if err != nil {
return nil, err
}
}
// The swapper is only concerned with two types of client-originating
// method requests.
authMgr.Route(msgjson.InitRoute, swapper.handleInit)
authMgr.Route(msgjson.RedeemRoute, swapper.handleRedeem)
return swapper, nil
}
// addMatch registers a match. The matchMtx must be locked.
func (s *Swapper) addMatch(mt *matchTracker) {
mid := mt.ID()
s.matches[mid] = mt
// Add the match to both maker's and taker's match maps.
maker, taker := mt.Maker.User(), mt.Taker.User()
for _, user := range []account.AccountID{maker, taker} {
userMatches, found := s.userMatches[user]
if !found {
s.userMatches[user] = map[order.MatchID]*matchTracker{
mid: mt,
}
} else {
userMatches[mid] = mt // may overwrite for self-match (ok)
}
if maker == taker {
break
}
}
addAcctMatch := func(matches map[string]map[order.MatchID]*matchTracker, acctAddr string, mt *matchTracker) {
acctMatches := matches[acctAddr]
if acctMatches == nil {
acctMatches = make(map[order.MatchID]*matchTracker, 1)
matches[acctAddr] = acctMatches
}
acctMatches[mt.ID()] = mt
}
if s.acctMatches[mt.Maker.Base()] != nil {
acctMatches := s.acctMatches[mt.Maker.Base()]
addAcctMatch(acctMatches, mt.Maker.BaseAccount(), mt)
addAcctMatch(acctMatches, mt.Taker.Trade().BaseAccount(), mt)
}
if s.acctMatches[mt.Maker.Quote()] != nil {
acctMatches := s.acctMatches[mt.Maker.Quote()]
addAcctMatch(acctMatches, mt.Maker.QuoteAccount(), mt)
addAcctMatch(acctMatches, mt.Taker.Trade().QuoteAccount(), mt)
}
}
// deleteMatch unregisters a match. The matchMtx must be locked.
func (s *Swapper) deleteMatch(mt *matchTracker) {
mid := mt.ID()
delete(s.matches, mid)
// Remove the match from both maker's and taker's match maps.
maker, taker := mt.Maker.User(), mt.Taker.User()
for _, user := range []account.AccountID{maker, taker} {
userMatches, found := s.userMatches[user]
if !found {
// Should not happen if consistently using addMatch.
log.Errorf("deleteMatch: No matches for user %v found!", user)
continue
}
delete(userMatches, mid)
if len(userMatches) == 0 {
delete(s.userMatches, user)
}
if maker == taker {
break
}
}
deleteAcctMatch := func(matches map[string]map[order.MatchID]*matchTracker, acctAddr string, mt *matchTracker) {
acctMatches := matches[acctAddr]
if acctMatches == nil {
return
}
delete(acctMatches, mt.ID())
if len(acctMatches) == 0 {
delete(matches, acctAddr)
}
}
if s.acctMatches[mt.Maker.Base()] != nil {
acctMatches := s.acctMatches[mt.Maker.Base()]
deleteAcctMatch(acctMatches, mt.Maker.BaseAccount(), mt)
deleteAcctMatch(acctMatches, mt.Taker.Trade().BaseAccount(), mt)
}
if s.acctMatches[mt.Maker.Quote()] != nil {
acctMatches := s.acctMatches[mt.Maker.Quote()]
deleteAcctMatch(acctMatches, mt.Maker.QuoteAccount(), mt)
deleteAcctMatch(acctMatches, mt.Taker.Trade().QuoteAccount(), mt)
}
}
// UserSwappingAmt gets the total amount in active swaps for a user in a
// specified market. This helps the market compute a user's order size limit.
func (s *Swapper) UserSwappingAmt(user account.AccountID, base, quote uint32) (amt, count uint64) {
s.matchMtx.RLock()
defer s.matchMtx.RUnlock()
um, found := s.userMatches[user]
if !found {
return
}
for _, mt := range um {
if mt.Maker.BaseAsset == base && mt.Maker.QuoteAsset == quote {
amt += mt.Quantity
count++
}
}
return
}
// pendingAccountStats is used to sum in-process match stats for the
// AccountStats method.
type pendingAccountStats struct {
acctAddr string
assetID uint32
swaps uint64
qty uint64
redeems int
}
func newPendingAccountStats(acctAddr string, assetID uint32) *pendingAccountStats {
return &pendingAccountStats{
acctAddr: acctAddr,
assetID: assetID,
}
}
func (p *pendingAccountStats) addMatch(mt *matchTracker) {
p.addOrder(mt, mt.Maker, order.MakerSwapCast, order.MakerRedeemed)
p.addOrder(mt, mt.Taker, order.TakerSwapCast, order.MatchComplete)
}
func (p *pendingAccountStats) addOrder(mt *matchTracker, ord order.Order, swappedStatus, redeemedStatus order.MatchStatus) {
trade := ord.Trade()
if ord.Base() == p.assetID && trade.BaseAccount() == p.acctAddr {
if trade.Sell {
if mt.Status < swappedStatus {
p.qty += mt.Quantity
p.swaps++
}
} else if mt.Status < redeemedStatus {
p.redeems++
}
}
if ord.Quote() == p.assetID && trade.QuoteAccount() == p.acctAddr {
if !trade.Sell {
if mt.Status < swappedStatus {
p.qty += calc.BaseToQuote(mt.Rate, mt.Quantity)
p.swaps++ // The swap is expected to occur in 1 transaction.
}
} else if mt.Status < redeemedStatus {
p.redeems++
}
}
}
// AccountStats is part of the MatchNegotiator interface to report in-process
// match information for a asset account address.
func (s *Swapper) AccountStats(acctAddr string, assetID uint32) (qty, swaps uint64, redeems int) {
stats := newPendingAccountStats(acctAddr, assetID)
s.matchMtx.RLock()
defer s.matchMtx.RUnlock()
acctMatches := s.acctMatches[assetID]
if acctMatches == nil {
return // How?
}
for _, mt := range acctMatches[acctAddr] {
stats.addMatch(mt)
}
return stats.qty, stats.swaps, stats.redeems
}
// ChainsSynced will return true if both specified asset's backends are synced.
func (s *Swapper) ChainsSynced(base, quote uint32) (bool, error) {
b, found := s.coins[base]
if !found {
return false, fmt.Errorf("no backend found for %d", base)
}
baseSynced, err := b.Backend.Synced()
if err != nil {
return false, fmt.Errorf("error checking sync status for %d: %w", base, err)
}
if !baseSynced {
return false, nil
}
q, found := s.coins[quote]
if !found {
return false, fmt.Errorf("no backend found for %d", base)
}
quoteSynced, err := q.Backend.Synced()
if err != nil {
return false, fmt.Errorf("error checking sync status for %d: %w", quote, err)
}
return quoteSynced, nil
}
func (s *Swapper) restoreActiveSwaps(allowPartial bool) error {
// Load active swap data from DB.
swapData, err := s.storage.ActiveSwaps()
if err != nil {
return err
}
log.Infof("Loaded swap data for %d active swaps.", len(swapData))
if len(swapData) == 0 {
return nil
}
// Check that the required assets backends are available.
missingAssets := make(map[uint32]bool)
checkAsset := func(id uint32) {
if s.coins[id] == nil && !missingAssets[id] {
log.Warnf("Unable to find backend for asset %d with active swaps.", id)
missingAssets[id] = true
}
}
for _, sd := range swapData {
checkAsset(sd.Base)
checkAsset(sd.Quote)
}
if len(missingAssets) > 0 && !allowPartial {
return fmt.Errorf("missing backend for asset with active swaps")
}
// Load the matchTrackers, calling the Contract and Redemption asset.Backend
// methods as needed.
type swapStatusData struct {
SwapAsset uint32 // from market schema and takerSell bool
RedeemAsset uint32
SwapTime int64 // {a,b}ContractTime
ContractCoinOut []byte // {a,b}ContractCoinID
ContractScript []byte // {a,b}Contract
RedeemTime int64 // {a,b}RedeemTime
RedeemCoinIn []byte // {a,b}aRedeemCoinID
// SwapConfirmTime is not stored in the DB, so use time.Now() if the
// contract has reached SwapConf.
}
translateSwapStatus := func(ss *swapStatus, ssd *swapStatusData, cpSwapCoin []byte) error {
ss.swapAsset, ss.redeemAsset = ssd.SwapAsset, ssd.RedeemAsset
swapCoin := ssd.ContractCoinOut
if len(swapCoin) > 0 {
assetID := ssd.SwapAsset
swapAsset := s.coins[assetID]
swap, err := swapAsset.Backend.Contract(swapCoin, ssd.ContractScript)
if err != nil {
return fmt.Errorf("unable to find swap out coin %x for asset %d: %w", swapCoin, assetID, err)
}
ss.swap = swap
ss.swapTime = encode.UnixTimeMilli(ssd.SwapTime)
swapConfs, err := swap.Confirmations(context.Background())
if err != nil {
log.Warnf("No swap confirmed time for %v: %v", swap, err)
} else if swapConfs >= int64(swapAsset.SwapConf) {
// We don't record the time at which we saw the block that got
// the swap to SwapConf, so give the user extra time.
ss.swapConfirmed = time.Now().UTC()
}
}
if redeemCoin := ssd.RedeemCoinIn; len(redeemCoin) > 0 {
assetID := ssd.RedeemAsset
redeem, err := s.coins[assetID].Backend.Redemption(redeemCoin, cpSwapCoin, ssd.ContractScript)
if err != nil {
return fmt.Errorf("unable to find redeem in coin %x for asset %d: %w", redeemCoin, assetID, err)
}
ss.redemption = redeem
ss.redeemTime = encode.UnixTimeMilli(ssd.RedeemTime)
}
return nil
}
s.matches = make(map[order.MatchID]*matchTracker, len(swapData))
s.userMatches = make(map[account.AccountID]map[order.MatchID]*matchTracker)
for _, sd := range swapData {
if missingAssets[sd.Base] {
log.Warnf("Dropping match %v with no backend available for base asset %d", sd.ID, sd.Base)
continue
}
if missingAssets[sd.Quote] {
log.Warnf("Dropping match %v with no backend available for quote asset %d", sd.ID, sd.Quote)
continue
}
// Load the maker's order.LimitOrder and taker's order.Order. WARNING:
// This is a different Order instance from whatever Market or other
// subsystems might have. As such, the mutable fields or accessors of
// mutable data should not be used.
taker, _, err := s.storage.Order(sd.MatchData.Taker, sd.Base, sd.Quote)
if err != nil {
log.Errorf("Failed to load taker order: %v", err)
continue
}
if taker.ID() != sd.MatchData.Taker {
log.Errorf("Failed to load order %v, computed ID %v instead", sd.MatchData.Taker, taker.ID())
continue
}
maker, _, err := s.storage.Order(sd.MatchData.Maker, sd.Base, sd.Quote)
if err != nil {
log.Errorf("Failed to load taker order: %v", err)
continue
}
if maker.ID() != sd.MatchData.Maker {
log.Errorf("Failed to load order %v, computed ID %v instead", sd.MatchData.Maker, maker.ID())
continue
}
makerLO, ok := maker.(*order.LimitOrder)
if !ok {
log.Errorf("Maker order was not a limit order: %T", maker)
continue
}
match := &order.Match{
Taker: taker,
Maker: makerLO,
Quantity: sd.Quantity,
Rate: sd.Rate,
FeeRateBase: sd.BaseRate,
FeeRateQuote: sd.QuoteRate,
Epoch: sd.Epoch,
Status: sd.Status,
Sigs: order.Signatures{ // not really needed
MakerMatch: sd.SwapData.SigMatchAckMaker,
TakerMatch: sd.SwapData.SigMatchAckTaker,
MakerAudit: sd.SwapData.ContractAAckSig,
TakerAudit: sd.SwapData.ContractBAckSig,
TakerRedeem: sd.SwapData.RedeemAAckSig,
},
}
mid := sd.MatchData.ID
if mid != match.ID() { // serialization is order IDs, qty, and rate
log.Errorf("Failed to load Match %v, computed ID %v instead", mid, match.ID())
continue
}
// Check and skip matches for missing assets.
makerSwapAsset, makerRedeemAsset := sd.Base, sd.Quote // maker selling -> their swap asset is base
if sd.TakerSell { // maker buying -> their swap asset is quote
makerSwapAsset, makerRedeemAsset = sd.Quote, sd.Base
}
if missingAssets[makerSwapAsset] {
log.Infof("Skipping match %v with missing asset %d backend", mid, makerSwapAsset)
continue
}
if missingAssets[makerRedeemAsset] {
log.Infof("Skipping match %v with missing asset %d backend", mid, makerRedeemAsset)
continue
}
epochCloseTime := match.Epoch.End()
mt := &matchTracker{
Match: match,
time: epochCloseTime.Add(time.Minute), // not quite, just be generous
matchTime: epochCloseTime,
makerStatus: &swapStatus{}, // populated by translateSwapStatus
takerStatus: &swapStatus{},
}
makerStatus := &swapStatusData{
SwapAsset: makerSwapAsset,
RedeemAsset: makerRedeemAsset,
SwapTime: sd.SwapData.ContractATime,
ContractCoinOut: sd.SwapData.ContractACoinID,
ContractScript: sd.SwapData.ContractA,
RedeemTime: sd.SwapData.RedeemATime,
RedeemCoinIn: sd.SwapData.RedeemACoinID,
}
takerStatus := &swapStatusData{
SwapAsset: makerRedeemAsset,
RedeemAsset: makerSwapAsset,
SwapTime: sd.SwapData.ContractBTime,
ContractCoinOut: sd.SwapData.ContractBCoinID,
ContractScript: sd.SwapData.ContractB,
RedeemTime: sd.SwapData.RedeemBTime,
RedeemCoinIn: sd.SwapData.RedeemBCoinID,
}
if err := translateSwapStatus(mt.makerStatus, makerStatus, takerStatus.ContractCoinOut); err != nil {
log.Errorf("Loading match %v failed: %v", mid, err)
continue
}
if err := translateSwapStatus(mt.takerStatus, takerStatus, makerStatus.ContractCoinOut); err != nil {
log.Errorf("Loading match %v failed: %v", mid, err)
continue
}
log.Infof("Resuming swap %v in status %v", mid, mt.Status)
s.addMatch(mt)
}
// Live coin waiters are abandoned on Swapper shutdown. When a client
// reconnects or their init request times out, they will resend it.
return nil
}
// Run is the main Swapper loop. It's primary purpose is to update transaction
// confirmations when new blocks are mined, and to trigger inaction checks.
func (s *Swapper) Run(ctx context.Context) {
// Permit internal cancel on anomaly such as storage failure.
ctxMaster, cancel := context.WithCancel(ctx)
// Graceful shutdown first allows active incoming messages to be handled,
// blocks more incoming messages in the handler functions, stops the helper
// goroutines (latency queue used by the handlers, and the block ntfn
// receiver), and finally the main loop via the mainLoop channel.
var wgHelpers, wgMain sync.WaitGroup
ctxHelpers, cancelHelpers := context.WithCancel(context.Background())
mainLoop := make(chan struct{}) // close after helpers stop for graceful shutdown
defer func() {
// Stop handlers receiving messages and queueing latency Waiters.
s.handlerMtx.Lock() // block until active handlers return
s.stop = true // prevent new handlers from starting waiters
// NOTE: could also do authMgr.Route(msgjson.{InitRoute,RedeemRoute}, shuttingDownHandler)
s.handlerMtx.Unlock()
// Stop the latencyQ of Waiters and the block update goroutines that
// send to the main loop.
cancelHelpers()
wgHelpers.Wait()
// Now that handlers AND the coin waiter queue are stopped, the
// liveWaiters can be accessed without locking.
// Stop the main loop if if there was no internal error.
close(mainLoop)
wgMain.Wait()
}()
// Start a listen loop for each asset's block channel. Normal shutdown stops
// this before the main loop since this sends to the main loop.
blockNotes := make(chan *blockNotification, 32*len(s.coins))
for assetID, lockable := range s.coins {
wgHelpers.Add(1)
go func(assetID uint32, blockSource <-chan *asset.BlockUpdate) {
defer wgHelpers.Done()
for {
select {
case blk, ok := <-blockSource:
if !ok {
log.Errorf("Asset %d has closed the block channel.", assetID)
// Should not happen. Keep running until cancel.
continue
}
// Do not block on anomalous return of main loop, which is
// the s.block receiver.
select {
case <-mainLoop:
return // ctxHelpers is being canceled anyway
case blockNotes <- &blockNotification{
time: time.Now().UTC(),
assetID: assetID,
err: blk.Err,
}:
}
case <-ctxHelpers.Done():
return
}
}
}(assetID, lockable.Backend.BlockChannel(32))
}
// Start the queue of coinwaiters for the init and redeem handlers. The
// handlers must be stopped/blocked before stopping this.
wgHelpers.Add(1)
go func() {
s.latencyQ.Run(ctxHelpers)
wgHelpers.Done()
}()
log.Debugf("Swapper started with %v broadcast timeout.", s.bTimeout)
// Block-based inaction checks are started with Timers, and run in the main
// loop to avoid locks and WaitGroups.
bcastBlockTrigger := make(chan uint32, 32*len(s.coins))
scheduleInactionCheck := func(assetID uint32) {
time.AfterFunc(s.bTimeout, func() {
select {
case bcastBlockTrigger <- assetID: // all checks run in main loop
case <-ctxMaster.Done():
}
})
}
// On startup, schedule an inaction check for each asset. Ideally these
// would start bTimeout after the best block times.
for assetID := range s.coins {
scheduleInactionCheck(assetID)
}
// Event-based action checks are started with a single ticker. Each of the
// events, e.g. match request, could start a timer, but this is simpler and
// allows batching the match checks.
bcastEventTrigger := bufferedTicker(ctxMaster, s.bTimeout/4)
processBlockWithTimeout := func(block *blockNotification) {
ctxTime, cancelTimeCtx := context.WithTimeout(ctxMaster, 5*time.Second)
defer cancelTimeCtx()
s.processBlock(ctxTime, block)
}
// Main loop can stop on internal error via cancel(), or when the caller
// cancels the parent context triggering graceful shutdown.
wgMain.Add(1)
go func() {
defer wgMain.Done()
defer cancel() // ctxMaster for anomalous return
for {
select {
case <-s.storage.Fatal():
return
case block := <-blockNotes:
if block.err != nil {
var connectionErr asset.ConnectionError
if errors.As(block.err, &connectionErr) {
// Connection issues handling can be triggered here.
log.Errorf("connection error detected for %d: %v", block.assetID, block.err)
} else {
log.Errorf("asset %d is reporting a block notification error: %v", block.assetID, block.err)
}
continue
}
// processBlock will update confirmation times in the swapStatus
// structs.
processBlockWithTimeout(block)
// Schedule an inaction check for matches that involve this
// asset, as they could be expecting user action within bTimeout
// of this event.
scheduleInactionCheck(block.assetID)
case assetID := <-bcastBlockTrigger:
// There was a new block for this asset bTimeout ago.
s.checkInactionBlockBased(assetID)
case <-bcastEventTrigger:
// Inaction checks that are not relative to blocks.
s.checkInactionEventBased()
case <-mainLoop:
return
}
}
}()
// Wait for caller cancel or anomalous return from main loop.
<-ctxMaster.Done()
}
// bufferedTicker creates a "ticker" that periodically sends on the returned
// channel, which has a buffer of length 1 and thus suitable for use in a select
// with other events that might cause a regular Ticker send to be dropped.
func bufferedTicker(ctx context.Context, dur time.Duration) chan struct{} {
buffered := make(chan struct{}, 1) // only need 1 since back-to-back is pointless
go func() {
ticker := time.NewTicker(dur)
defer ticker.Stop()
for {
select {
case <-ticker.C:
buffered <- struct{}{}
case <-ctx.Done():
return
}
}
}()
return buffered
}
func (s *Swapper) tryConfirmSwap(ctx context.Context, status *swapStatus, confTime time.Time) (final bool) {
status.mtx.Lock()
defer status.mtx.Unlock()
if status.swapTime.IsZero() || !status.swapConfirmed.IsZero() {
return
}
confs, err := status.swap.Confirmations(ctx)
if err != nil {
log.Warnf("Unable to get confirmations for swap tx %v: %v", status.swap.TxID(), err)
return
}
// If a swapStatus was created, the asset.Asset is already known to be in
// the map.
swapConf := s.coins[status.swapAsset].SwapConf
if confs >= int64(swapConf) {
log.Debugf("Swap %v (%s) has reached %d confirmations (%d required)",
status.swap, dex.BipIDSymbol(status.swapAsset), confs, swapConf)
status.swapConfirmed = confTime.UTC()
final = true
}
return
}
// processBlock scans the matches and updates match status based on number of
// confirmations. Once a relevant transaction has the requisite number of
// confirmations, the next-to-act has only duration (Swapper).bTimeout to
// broadcast the next transaction in the settlement sequence. The timeout is
// not evaluated here, but in (Swapper).checkInaction. This method simply sets
// the appropriate flags in the swapStatus structures.
func (s *Swapper) processBlock(ctx context.Context, block *blockNotification) {
checkMatch := func(match *matchTracker) {
// If it's neither of the match assets, nothing to do.
if match.makerStatus.swapAsset != block.assetID &&
match.takerStatus.swapAsset != block.assetID {
return
}
// Lock the matchTracker so the following checks and updates are atomic
// with respect to Status.
match.mtx.RLock()
defer match.mtx.RUnlock()
switch match.Status {
case order.MakerSwapCast:
if match.makerStatus.swapAsset != block.assetID {
break
}
// If the maker has broadcast their transaction, the taker's broadcast
// timeout starts once the maker's swap has SwapConf confs.
if s.tryConfirmSwap(ctx, match.makerStatus, block.time) {
s.unlockOrderCoins(match.Maker)
}
case order.TakerSwapCast:
if match.takerStatus.swapAsset != block.assetID {
break
}
// If the taker has broadcast their transaction, the maker's broadcast
// timeout (for redemption) starts once the maker's swap has SwapConf
// confs.
if s.tryConfirmSwap(ctx, match.takerStatus, block.time) {
s.unlockOrderCoins(match.Taker)
}
}
}
s.matchMtx.Lock()
defer s.matchMtx.Unlock()
for _, match := range s.matches {
checkMatch(match)
}
}
// failMatch revokes the match and marks the swap as done for accounting
// purposes. If userFault is false, there will be no penalty, such as if the
// failure is because a swap tx lock time expired before required confirmations
// were reached.
func (s *Swapper) failMatch(match *matchTracker, userFault bool) {
// From the match status, determine maker/taker fault and the corresponding
// auth.NoActionStep.
var makerFault bool
var misstep auth.NoActionStep
var refTime time.Time // a reference time found in the DB for reproducibly sorting outcomes
switch match.Status {
case order.NewlyMatched:
misstep = auth.NoSwapAsMaker
refTime = match.Epoch.End()
makerFault = true
case order.MakerSwapCast:
misstep = auth.NoSwapAsTaker
refTime = match.makerStatus.swapTime // swapConfirmed time is not in the DB
case order.TakerSwapCast:
misstep = auth.NoRedeemAsMaker
refTime = match.takerStatus.swapTime // swapConfirmed time is not in the DB
makerFault = true
case order.MakerRedeemed:
misstep = auth.NoRedeemAsTaker
refTime = match.makerStatus.redeemTime
default:
log.Errorf("Invalid failMatch status %v for match %v", match.Status, match.ID())
return
}
orderAtFault, otherOrder := match.Taker, order.Order(match.Maker) // an order.Order
if makerFault {
orderAtFault, otherOrder = match.Maker, match.Taker
}
log.Debugf("failMatch: swap %v failing at %v (%v), user fault = %v",
match.ID(), match.Status, misstep, userFault)
// Record the end of this match's processing.
s.storage.SetMatchInactive(db.MatchID(match.Match), !userFault)
// Cancellation rate accounting
s.swapDone(orderAtFault, match.Match, userFault) // will also unbook/revoke order if needed
// Accounting for the maker has already taken place if they have redeemed.
if match.Status != order.MakerRedeemed {
s.swapDone(otherOrder, match.Match, false)
}
// Register the failure to act violation, adjusting the user's score.
if userFault {
s.authMgr.Inaction(orderAtFault.User(), misstep, db.MatchID(match.Match),
match.Quantity, refTime, orderAtFault.ID())
}
// Send the revoke_match messages, and solicit acks.