forked from decred/dcrdex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrade.go
3904 lines (3530 loc) · 142 KB
/
trade.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 core
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"math"
"strings"
"sync"
"sync/atomic"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/client/comms"
"decred.org/dcrdex/client/db"
"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"
)
// ExpirationErr indicates that the wait.TickerQueue has expired a waiter, e.g.
// a reported coin was not found before the set expiration time.
type ExpirationErr string
// Error satisfies the error interface for ExpirationErr.
func (err ExpirationErr) Error() string { return string(err) }
// Ensure matchTracker satisfies the Stringer interface.
var _ (fmt.Stringer) = (*matchTracker)(nil)
// A matchTracker is used to negotiate a match.
type matchTracker struct {
// counterConfirms records the last known confirms of the counterparty swap.
// This is set in isSwappable for taker, isRedeemable for maker. -1 means
// the confirms have not yet been checked (or logged). swapConfirms is for
// your own swap. For safe access, use the matchTracker methods: confirms,
// setSwapConfirms, and setCounterConfirms.
counterConfirms int64 // atomic
swapConfirms int64 // atomic
// sendingInitAsync indicates if this match's init request is being sent to
// the server and awaiting a response. No attempts will be made to send
// another init request for this match while one is already active.
sendingInitAsync uint32 // atomic
// sendingRedeemAsync indicates if this match's redeem request is being sent
// to the server and awaiting a response. No attempts will be made to send
// another redeem request for this match while one is already active.
sendingRedeemAsync uint32 // atomic
// The first group of fields below should be accessed with the parent
// trackedTrade's mutex locked, excluding the atomic fields.
db.MetaMatch
// swapErr is an error set when we have given up hope on broadcasting a swap
// tx for a match. This can happen if 1) the swap has been attempted
// (repeatedly), but could not be successfully broadcast before the
// broadcast timeout, or 2) a match data was found to be in a nonsensical
// state during startup.
swapErr error
// swapErrCount counts the swap attempts. It is used in recovery.
swapErrCount int
// redeemErrCount counts the redeem attempts. It is used in recovery.
redeemErrCount int
// suspectSwap is a flag to indicate that there was a problem encountered
// trying to send a swap contract for this match. If suspectSwap is true,
// the match will not be grouped when attempting future swaps.
suspectSwap bool
// suspectRedeem is a flag to indicate that there was a problem encountered
// trying to redeem this match. If suspectRedeem is true, the match will not
// be grouped when attempting future redemptions.
suspectRedeem bool
// refundErr will be set to true if we attempt a refund and get a
// CoinNotFoundError, indicating there is nothing to refund and the
// counterparty redemption search should be attempted. Prevents retries.
refundErr error
prefix *order.Prefix
trade *order.Trade
counterSwap *asset.AuditInfo
// cancelRedemptionSearch should be set when taker starts searching for
// maker's redemption. Required to cancel a find redemption attempt if
// taker successfully executes a refund.
cancelRedemptionSearch context.CancelFunc
// confirmRedemptionNumTries is just used for logging.
confirmRedemptionNumTries int
// redemptionConfs and redemptionConfsReq are updated while the redemption
// confirmation process is running. Their values are not updated after the
// match reaches MatchConfirmed status.
redemptionConfs uint64
redemptionConfsReq uint64
// redemptionRejected will be true if a redemption tx was rejected. A
// a rejected tx may indicate a serious internal issue, so we will seek
// user approval before replacing the tx.
redemptionRejected bool
// matchCompleteSent precludes sending another redeem to the server if we
// we are retrying after rejection and they already accepted our first
// request. Additional requests will just error and they don't really care
// if we redeem as taker anyway.
matchCompleteSent bool
// The fields below need to be modified without the parent trackedTrade's
// mutex being write locked, so they have dedicated mutexes.
swapSpentTimeMtx sync.Mutex
swapSpentTime time.Time
// lastExpireDur is the most recently logged time until expiry of the
// party's own contract. This may be negative if expiry has passed, but it
// is not yet refundable due to other consensus rules. This is used only by
// isRefundable. Initialize this to a very large value to guarantee that it
// will be logged on the first check or when 0. This facilitates useful
// logging, while not being spammy.
lastExpireDurMtx sync.Mutex
lastExpireDur time.Duration
// Certain exceptions that control swap actions are commonly accessed
// together, and these share a single mutex. See the exceptions and
// delayTicks methods.
exceptionMtx sync.RWMutex
// tickGovernor can be set non-nil to prevent swaps or redeems from being
// attempted for a match. Typically, the Timer comes from an AfterFunc that
// itself nils the tickGovernor. Guarded by exceptionMtx.
tickGovernor *time.Timer
// checkServerRevoke is set to make sure that a taker will not prematurely
// send an initialization until it is confirmed with the server (see
// authDEX) that the match is not revoked. This should be set on reconnect
// for all taker matches in MakerSwapCast. Guarded by exceptionMtx.
checkServerRevoke bool
}
// matchTime returns the match's match time as a time.Time.
func (m *matchTracker) matchTime() time.Time {
return time.UnixMilli(int64(m.MetaData.Proof.Auth.MatchStamp)).UTC()
}
func (m *matchTracker) swapSpentAgo() time.Duration {
m.swapSpentTimeMtx.Lock()
defer m.swapSpentTimeMtx.Unlock()
if m.swapSpentTime.IsZero() {
return 0
}
return time.Since(m.swapSpentTime)
}
func (m *matchTracker) swapSpent() {
m.swapSpentTimeMtx.Lock()
defer m.swapSpentTimeMtx.Unlock()
if !m.swapSpentTime.IsZero() {
return // already noted
}
m.swapSpentTime = time.Now()
}
// setExpireDur records the last known duration until expiry if the difference
// from the previous recorded duration is at least the provided log interval
// threshold. The return indicates if it was updated (and should be logged by
// the caller).
func (m *matchTracker) setExpireDur(expireDur, logInterval time.Duration) (intervalPassed bool) {
m.lastExpireDurMtx.Lock()
defer m.lastExpireDurMtx.Unlock()
if m.lastExpireDur-expireDur < logInterval {
return false // too soon
}
m.lastExpireDur = expireDur
return true // ok to log
}
func (m *matchTracker) exceptions() (ticksGoverned, checkServerRevoke bool) {
m.exceptionMtx.RLock()
defer m.exceptionMtx.RUnlock()
return m.tickGovernor != nil, m.checkServerRevoke
}
// delayTicks sets the tickGovernor to prevent retrying too quickly after an
// error.
func (m *matchTracker) delayTicks(waitTime time.Duration) {
m.exceptionMtx.Lock()
m.tickGovernor = time.AfterFunc(waitTime, func() {
m.exceptionMtx.Lock()
m.tickGovernor = nil
m.exceptionMtx.Unlock()
})
m.exceptionMtx.Unlock()
}
func (m *matchTracker) confirms() (mine, theirs int64) {
return atomic.LoadInt64(&m.swapConfirms), atomic.LoadInt64(&m.counterConfirms)
}
func (m *matchTracker) setSwapConfirms(mine int64) {
atomic.StoreInt64(&m.swapConfirms, mine)
}
func (m *matchTracker) setCounterConfirms(theirs int64) (was int64) {
return atomic.SwapInt64(&m.counterConfirms, theirs)
}
// token returns a shortened representation of the match ID.
func (m *matchTracker) token() string {
return hex.EncodeToString(m.MatchID[:4])
}
// trackedCancel is information necessary to track a cancel order. A
// trackedCancel is always associated with a trackedTrade.
type trackedCancel struct {
order.CancelOrder
epochLen uint64
matches struct {
maker *msgjson.Match
taker *msgjson.Match
}
}
type feeStamped struct {
sync.RWMutex
rate uint64
stamp time.Time
}
func (fs *feeStamped) get() uint64 {
fs.RLock()
defer fs.RUnlock()
return fs.rate
}
const (
// freshRedeemFeeAge is the expiry age for cached redeem fee rates, past
// which fetchFeeFromOracle should be used to refresh the rate. See
// cacheRedemptionFeeSuggestion.
freshRedeemFeeAge = time.Minute
// spentAgoThreshNormal is how long to wait after we as taker observer our
// swap spent by the maker without receiving a redemption request from the
// server before initiating a redemption search and auto-redeem.
spentAgoThreshNormal = 10 * time.Minute
// spentAgoThreshSelfGoverned is like spentAgoThreshNormal, but for a
// self-governed trade. We are less patient if the server is down or
// lacking the market or asset configs involved.
spentAgoThreshSelfGoverned = time.Minute
)
// trackedTrade is an order (issued by this client), its matches, and its cancel
// order, if applicable. The trackedTrade has methods for handling requests
// from the DEX to progress match negotiation.
type trackedTrade struct {
// redeemFeeSuggestion is cached fee suggestion for redemption. We can't
// request a fee suggestion at redeem time because it would require making
// the full redemption routine async (TODO?). This fee suggestion is
// intentionally not stored as part of the db.OrderMetaData, and should be
// repopulated if the client is restarted.
redeemFeeSuggestion feeStamped
selfGoverned uint32 // (atomic) server either lacks this market or is down
tickLock sync.Mutex // prevent multiple concurrent ticks, but allow them to queue
order.Order
db db.DB
dc *dexConnection
latencyQ *wait.TickerQueue
mktID string // convenience for marketName(t.Base(), t.Quote())
lockTimeTaker time.Duration
lockTimeMaker time.Duration
notify func(Notification)
formatDetails func(Topic, ...any) (string, string)
fromAssetID uint32 // wallets.fromWallet.AssetID
options map[string]string // metaData.Options (immutable) for Redeem and Swap
redemptionReserves uint64 // metaData.RedemptionReserves (immutable)
refundReserves uint64 // metaData.RefundReserves (immutable)
preImg order.Preimage
csumMtx sync.RWMutex
csum dex.Bytes // the commitment checksum provided in the preimage request
cancelCsum dex.Bytes
cancelPreimg order.Preimage
// mtx protects all read-write fields of the trackedTrade and the
// matchTrackers in the matches map.
mtx sync.RWMutex
metaData *db.OrderMetaData
wallets *walletSet
coins map[string]asset.Coin
coinsLocked bool
change asset.Coin
changeLocked bool
cancel *trackedCancel
matches map[order.MatchID]*matchTracker
redemptionLocked uint64 // remaining locked of redemptionReserves
refundLocked uint64 // remaining locked of refundReserves
readyToTick bool // this will be false if either of the wallets cannot be connected and unlocked
}
// newTrackedTrade is a constructor for a trackedTrade.
func newTrackedTrade(dbOrder *db.MetaOrder, preImg order.Preimage, dc *dexConnection,
lockTimeTaker, lockTimeMaker time.Duration, db db.DB, latencyQ *wait.TickerQueue, wallets *walletSet,
coins asset.Coins, notify func(Notification), formatDetails func(Topic, ...any) (string, string)) *trackedTrade {
fromID := dbOrder.Order.Quote()
if dbOrder.Order.Trade().Sell {
fromID = dbOrder.Order.Base()
}
ord := dbOrder.Order
t := &trackedTrade{
Order: ord,
metaData: dbOrder.MetaData,
dc: dc,
db: db,
latencyQ: latencyQ,
wallets: wallets,
preImg: preImg,
mktID: marketName(ord.Base(), ord.Quote()),
coins: mapifyCoins(coins), // must not be nil even if empty
coinsLocked: len(coins) > 0,
lockTimeTaker: lockTimeTaker,
lockTimeMaker: lockTimeMaker,
matches: make(map[order.MatchID]*matchTracker),
notify: notify,
fromAssetID: fromID,
formatDetails: formatDetails,
options: dbOrder.MetaData.Options,
redemptionReserves: dbOrder.MetaData.RedemptionReserves,
refundReserves: dbOrder.MetaData.RefundReserves,
readyToTick: true,
}
return t
}
func (t *trackedTrade) isSelfGoverned() bool {
return atomic.LoadUint32(&t.selfGoverned) == 1
}
func (t *trackedTrade) spentAgoThresh() time.Duration {
if t.isSelfGoverned() {
return spentAgoThreshSelfGoverned
}
return spentAgoThreshNormal // longer
}
func (t *trackedTrade) setSelfGoverned(is bool) (changed bool) {
if is {
return atomic.CompareAndSwapUint32(&t.selfGoverned, 0, 1)
}
return atomic.CompareAndSwapUint32(&t.selfGoverned, 1, 0)
}
func (t *trackedTrade) status() order.OrderStatus {
t.mtx.RLock()
defer t.mtx.RUnlock()
return t.metaData.Status
}
// cacheRedemptionFeeSuggestion sets the redeemFeeSuggestion for the
// trackedTrade. If a request to the server for the fee suggestion must be made,
// the request will be run in a goroutine, i.e. the field is not necessarily set
// when this method returns. If there is a synced book, the estimate will always
// be updated. If there is no synced book, but a non-zero fee suggestion is
// already cached, no new requests will be made.
//
// The trackedTrade mutex should be held for reads for safe access to the
// walletSet and the readyToTick flag.
func (t *trackedTrade) cacheRedemptionFeeSuggestion() {
now := time.Now()
t.redeemFeeSuggestion.Lock()
defer t.redeemFeeSuggestion.Unlock()
if now.Sub(t.redeemFeeSuggestion.stamp) < freshRedeemFeeAge {
return
}
set := func(rate uint64) {
t.redeemFeeSuggestion.rate = rate
t.redeemFeeSuggestion.stamp = now
}
// Use the wallet's rate first. Note that this could make a costly request
// to an external fee oracle if an internal estimate is not available and
// the wallet settings permit external API requests.
toWallet := t.wallets.toWallet
if t.readyToTick && toWallet.connected() {
if feeRate, _ := toWallet.feeRate(); feeRate != 0 {
set(feeRate)
return
}
}
// Check any book that might have the fee recorded from an epoch_report note
// (requires a book subscription).
redeemAsset := toWallet.AssetID
feeSuggestion := t.dc.bestBookFeeSuggestion(redeemAsset)
if feeSuggestion > 0 {
set(feeSuggestion)
return
}
// Fetch it from the server. Last resort!
go func() {
feeSuggestion = t.dc.fetchFeeRate(redeemAsset)
if feeSuggestion > 0 {
t.redeemFeeSuggestion.Lock()
set(feeSuggestion)
t.redeemFeeSuggestion.Unlock()
}
}()
}
// accountRedeemer is equivalent to calling
// xcWallet.Wallet.(asset.AccountLocker) on the to-wallet.
func (t *trackedTrade) accountRedeemer() (asset.AccountLocker, bool) {
ar, is := t.wallets.toWallet.Wallet.(asset.AccountLocker)
return ar, is
}
// accountRefunder is equivalent to calling
// xcWallet.Wallet.(asset.AccountLocker) on the from-wallet.
func (t *trackedTrade) accountRefunder() (asset.AccountLocker, bool) {
ar, is := t.wallets.fromWallet.Wallet.(asset.AccountLocker)
return ar, is
}
// lockRefundFraction locks the specified fraction of the available
// refund reserves. Subsequent calls are additive. If a call to
// lockRefundFraction would put the locked reserves > available reserves,
// nothing will be reserved, and an error message is logged.
func (t *trackedTrade) lockRefundFraction(num, denom uint64) {
refunder, is := t.accountRefunder()
if !is {
return
}
newReserved := t.reservesToLock(num, denom, t.refundReserves, t.refundLocked)
if newReserved == 0 {
return
}
if err := refunder.ReReserveRefund(newReserved); err != nil {
t.dc.log.Errorf("error re-reserving refund %d %s for order %s: %v",
newReserved, t.wallets.fromWallet.unitInfo().AtomicUnit, t.ID(), err)
return
}
t.refundLocked += newReserved
}
// lockRedemptionFraction locks the specified fraction of the available
// redemption reserves. Subsequent calls are additive. If a call to
// lockRedemptionFraction would put the locked reserves > available reserves,
// nothing will be reserved, and an error message is logged.
func (t *trackedTrade) lockRedemptionFraction(num, denom uint64) {
redeemer, is := t.accountRedeemer()
if !is {
return
}
newReserved := t.reservesToLock(num, denom, t.redemptionReserves, t.redemptionLocked)
if newReserved == 0 {
return
}
if err := redeemer.ReReserveRedemption(newReserved); err != nil {
t.dc.log.Errorf("error re-reserving redemption %d %s for order %s: %v",
newReserved, t.wallets.toWallet.unitInfo().AtomicUnit, t.ID(), err)
return
}
t.redemptionLocked += newReserved
}
// reservesToLock is a helper function used by lockRedemptionFraction and
// lockRefundFraction to determine the amount of funds to lock.
func (t *trackedTrade) reservesToLock(num, denom, reserves, reservesLocked uint64) uint64 {
newReserved := applyFraction(num, denom, reserves)
if reservesLocked+newReserved > reserves {
t.dc.log.Errorf("attempting to mark as active more reserves than available for order %s:"+
"%d available, %d already reserved, %d requested", t.ID(), t.redemptionReserves, t.redemptionLocked, newReserved)
return 0
}
return newReserved
}
// unlockRefundFraction unlocks the specified fraction of the refund
// reserves. t.mtx should be locked if this trackedTrade is in the dc.trades
// map. If the requested unlock would put the locked reserves < 0, an error
// message is logged and the remaining locked reserves will be unlocked instead.
// If the remaining locked reserves after this unlock is determined to be
// "dust", it will be unlocked too.
func (t *trackedTrade) unlockRefundFraction(num, denom uint64) {
refunder, is := t.accountRefunder()
if !is {
return
}
unlock := t.reservesToUnlock(num, denom, t.refundReserves, t.refundLocked)
t.refundLocked -= unlock
refunder.UnlockRefundReserves(unlock)
}
// unlockRedemptionFraction unlocks the specified fraction of the redemption
// reserves. t.mtx should be locked if this trackedTrade is in the dc.trades
// map. If the requested unlock would put the locked reserves < 0, an error
// message is logged and the remaining locked reserves will be unlocked instead.
// If the remaining locked reserves after this unlock is determined to be
// "dust", it will be unlocked too.
func (t *trackedTrade) unlockRedemptionFraction(num, denom uint64) {
redeemer, is := t.accountRedeemer()
if !is {
return
}
unlock := t.reservesToUnlock(num, denom, t.redemptionReserves, t.redemptionLocked)
t.redemptionLocked -= unlock
redeemer.UnlockRedemptionReserves(unlock)
}
// reservesToUnlock is a helper function used by unlockRedemptionFraction and
// unlockRefundFraction to determine the amount of funds to unlock.
func (t *trackedTrade) reservesToUnlock(num, denom, reserves, reservesLocked uint64) uint64 {
unlock := applyFraction(num, denom, reserves)
if unlock > reservesLocked {
t.dc.log.Errorf("attempting to unlock more than is reserved for order %s. unlocking reserved amount instead: "+
"%d reserved, unlocking %d", t.ID(), reservesLocked, unlock)
unlock = reservesLocked
}
reservesLocked -= unlock
// Can be dust. Clean it up.
var isDust bool
if t.isMarketBuy() {
isDust = reservesLocked < applyFraction(1, uint64(2*len(t.matches)), reserves)
} else if t.metaData.Status > order.OrderStatusBooked && len(t.matches) > 0 {
// Order is executed, so no changes should be expected. If there were
// zero matches, the return is expected to be fraction 1 / 1, so no
// reason to add handling for that case.
mkt := t.dc.marketConfig(t.mktID)
if mkt == nil {
t.dc.log.Errorf("reservesToUnlock: could not find market: %v", t.mktID)
return 0
}
lotSize := mkt.LotSize
qty := t.Trade().Quantity
// Dust if remaining reserved is less than the amount needed to
// reserve one lot, which would be the smallest trade. Flooring
// to avoid rounding issues.
isDust = reservesLocked < uint64(math.Floor(float64(lotSize)/float64(qty)*float64(reserves)))
}
if isDust {
unlock += reservesLocked
}
return unlock
}
func (t *trackedTrade) isMarketBuy() bool {
trade := t.Trade()
if trade == nil {
return false
}
return t.Type() == order.MarketOrderType && !trade.Sell
}
func (t *trackedTrade) epochLen() uint64 {
return t.metaData.EpochDur
}
func (t *trackedTrade) epochIdx() uint64 {
// Guard against bizarre circumstances with both an old order without epoch
// duration stored, AND a server that is either down or missing the market.
if t.epochLen() == 0 {
return 0
}
return uint64(t.Prefix().ServerTime.UnixMilli()) / t.epochLen()
}
// cancelEpochIdx gives the epoch index of any cancel associated cancel order.
// The mutex must be at least read locked.
func (t *trackedTrade) cancelEpochIdx() uint64 {
if t.cancel == nil {
return 0
}
epochLen := t.cancel.epochLen
if epochLen == 0 {
epochLen = t.epochLen()
}
if epochLen == 0 {
// In these strange circumstances, the cancel should be declared stale
// anyway (see hasStaleCancelOrder).
return 0
}
return uint64(t.cancel.Prefix().ServerTime.UnixMilli()) / epochLen
}
func (t *trackedTrade) verifyCSum(vsum dex.Bytes, epochIdx uint64) error {
t.mtx.RLock()
defer t.mtx.RUnlock()
t.csumMtx.RLock()
csum, cancelCsum := t.csum, t.cancelCsum
t.csumMtx.RUnlock()
// First check the trade's recorded csum, if it is in this epoch.
if epochIdx == t.epochIdx() && !bytes.Equal(vsum, csum) {
return fmt.Errorf("checksum %s != trade order preimage request checksum %s for trade order %v",
csum, csum, t.ID())
}
if t.cancel == nil {
return nil // no linked cancel order
}
// Check the linked cancel order if it is for this epoch.
if epochIdx == t.cancelEpochIdx() && !bytes.Equal(vsum, cancelCsum) {
return fmt.Errorf("checksum %s != cancel order preimage request checksum %s for cancel order %v",
vsum, cancelCsum, t.cancel.ID())
}
return nil // includes not in epoch
}
// rate returns the order's rate, or zero if a market or cancel order.
func (t *trackedTrade) rate() uint64 {
if ord, ok := t.Order.(*order.LimitOrder); ok {
return ord.Rate
}
return 0
}
// broadcastTimeout gets associated DEX's configured broadcast timeout. If the
// trade's dexConnection was unable to be established, 0 is returned.
func (t *trackedTrade) broadcastTimeout() time.Duration {
t.dc.cfgMtx.RLock()
defer t.dc.cfgMtx.RUnlock()
// If the dexConnection was never established, we have no config.
if t.dc.cfg == nil {
return 0
}
return time.Millisecond * time.Duration(t.dc.cfg.BroadcastTimeout)
}
// coreOrder constructs a *core.Order for the tracked order.Order. If the trade
// has a cancel order associated with it, the cancel order will be returned,
// otherwise the second returned *Order will be nil.
func (t *trackedTrade) coreOrder() *Order {
t.mtx.RLock()
defer t.mtx.RUnlock()
return t.coreOrderInternal()
}
// coreOrderInternal constructs a *core.Order for the tracked order.Order. If
// the trade has a cancel order associated with it, the cancel order will be
// returned, otherwise the second returned *Order will be nil. coreOrderInternal
// should be called with the mtx >= RLocked.
func (t *trackedTrade) coreOrderInternal() *Order {
corder := coreOrderFromTrade(t.Order, t.metaData)
corder.Epoch = t.dc.marketEpoch(t.mktID, t.Prefix().ServerTime)
corder.LockedAmt = t.lockedAmount()
corder.ParentAssetLockedAmt = t.parentLockedAmt()
corder.ReadyToTick = t.readyToTick
corder.RedeemLockedAmt = t.redemptionLocked
corder.RefundLockedAmt = t.refundLocked
allFeesConfirmed := true
for _, mt := range t.matches {
if !mt.MetaData.Proof.SwapFeeConfirmed || !mt.MetaData.Proof.RedemptionFeeConfirmed {
allFeesConfirmed = false
}
swapConfs, counterConfs := mt.confirms()
corder.Matches = append(corder.Matches, matchFromMetaMatchWithConfs(t, &mt.MetaMatch,
swapConfs, int64(t.metaData.FromSwapConf),
counterConfs, int64(t.metaData.ToSwapConf),
int64(mt.redemptionConfs), int64(mt.redemptionConfsReq)))
}
corder.AllFeesConfirmed = allFeesConfirmed
return corder
}
// hasFundingCoins indicates if either funding or change coins are locked.
// This should be called with the mtx at least read locked.
func (t *trackedTrade) hasFundingCoins() bool {
return t.changeLocked || t.coinsLocked
}
// lockedAmount is the total value of all coins currently locked for this trade.
// Returns the value sum of the initial funding coins if no swap has been sent,
// otherwise, the value of the locked change coin is returned.
// NOTE: This amount only applies to the wallet from which swaps are sent. This
// is the BASE asset wallet for a SELL order and the QUOTE asset wallet for a
// BUY order.
// lockedAmount should be called with the mtx >= RLocked.
func (t *trackedTrade) lockedAmount() (locked uint64) {
if t.coinsLocked {
// This implies either no swap has been sent, or the trade has been
// resumed on restart after a swap that produced locked change (partial
// fill and still booked) since restarting loads into coins/coinsLocked.
for _, coin := range t.coins {
locked += coin.Value()
}
} else if t.changeLocked && t.change != nil { // change may be returned but unlocked if the last swap has been sent
locked = t.change.Value()
}
return
}
// parentLockedAmt returns the total amount of the parent asset locked for
// funding swaps in this order.
//
// NOTE: This amount only applies to the wallet from which swaps are sent. This
// is the BASE asset wallet for a SELL order and the QUOTE asset wallet for a
// BUY order.
// parentLockedAmt should be called with the mtx >= RLocked.
func (t *trackedTrade) parentLockedAmt() (locked uint64) {
if t.coinsLocked {
// This implies either no swap has been sent, or the trade has been
// resumed on restart after a swap that produced locked change (partial
// fill and still booked) since restarting loads into coins/coinsLocked.
for _, coin := range t.coins {
if tokenCoin, is := coin.(asset.TokenCoin); is {
locked += tokenCoin.Fees()
}
}
} else if t.changeLocked && t.change != nil { // change may be returned but unlocked if the last swap has been sent
if tokenCoin, is := t.change.(asset.TokenCoin); is {
locked += tokenCoin.Fees()
}
}
return
}
// token is a string representation of the order ID.
func (t *trackedTrade) token() string {
return (t.ID().String())
}
// clearCancel clears the unmatched cancel and deletes the cancel checksum and
// link to the trade in the dexConnection. clearCancel must be called with the
// trackedTrade.mtx locked.
func (t *trackedTrade) clearCancel(preImg order.Preimage) {
if t.cancel != nil {
t.dc.deleteCancelLink(t.cancel.ID())
t.cancel = nil
}
t.csumMtx.Lock()
t.cancelCsum = nil
t.cancelPreimg = preImg
t.csumMtx.Unlock()
}
// cancelTrade sets the cancellation data with the order and its preimage.
// cancelTrade must be called with the mtx write-locked.
func (t *trackedTrade) cancelTrade(co *order.CancelOrder, preImg order.Preimage, epochLen uint64) error {
t.clearCancel(preImg)
t.cancel = &trackedCancel{
CancelOrder: *co,
epochLen: epochLen,
}
cid := co.ID()
oid := t.ID()
t.dc.registerCancelLink(cid, oid)
err := t.db.LinkOrder(oid, cid)
if err != nil {
return fmt.Errorf("error linking cancel order %s for trade %s: %w", cid, oid, err)
}
t.metaData.LinkedOrder = cid
return nil
}
// nomatch sets the appropriate order status and returns funding coins.
func (t *trackedTrade) nomatch(oid order.OrderID) (assetMap, error) {
assets := make(assetMap)
// Check if this is the cancel order.
t.mtx.Lock()
defer t.mtx.Unlock()
if t.ID() != oid {
if t.cancel == nil || t.cancel.ID() != oid {
return assets, newError(unknownOrderErr, "nomatch order ID %s does not match trade or cancel order", oid)
}
// This is a cancel order. Cancel status goes to executed, but the trade
// status will not be canceled. Remove the trackedCancel and remove the
// DB linked order from the trade, but not the cancel.
t.dc.log.Warnf("Cancel order %s targeting trade %s did not match.", oid, t.ID())
err := t.db.LinkOrder(t.ID(), order.OrderID{})
if err != nil {
t.dc.log.Errorf("DB error unlinking cancel order %s for trade %s: %v", oid, t.ID(), err)
}
// Clearing the trackedCancel allows this order to be canceled again.
t.clearCancel(order.Preimage{})
t.metaData.LinkedOrder = order.OrderID{}
subject, details := t.formatDetails(TopicMissedCancel, makeOrderToken(t.token()))
t.notify(newOrderNote(TopicMissedCancel, subject, details, db.WarningLevel, t.coreOrderInternal()))
return assets, t.db.UpdateOrderStatus(oid, order.OrderStatusExecuted)
}
// This is the trade. Return coins and set status based on whether this is
// a standing limit order or not.
if t.metaData.Status != order.OrderStatusEpoch {
return assets, fmt.Errorf("nomatch sent for non-epoch order %s", oid)
}
if lo, ok := t.Order.(*order.LimitOrder); ok && lo.Force == order.StandingTiF {
t.dc.log.Infof("Standing order %s did not match and is now booked.", t.token())
t.metaData.Status = order.OrderStatusBooked
t.notify(newOrderNote(TopicOrderBooked, "", "", db.Data, t.coreOrderInternal()))
} else {
t.returnCoins()
t.unlockRedemptionFraction(1, 1)
t.unlockRefundFraction(1, 1)
assets.count(t.wallets.fromWallet.AssetID)
t.dc.log.Infof("Non-standing order %s did not match.", t.token())
t.metaData.Status = order.OrderStatusExecuted
t.notify(newOrderNote(TopicNoMatch, "", "", db.Data, t.coreOrderInternal()))
}
return assets, t.db.UpdateOrderStatus(t.ID(), t.metaData.Status)
}
// negotiate creates and stores matchTrackers for the []*msgjson.Match, and
// updates (UserMatch).Filled. Match negotiation can then be progressed by
// calling (*trackedTrade).tick when a relevant event occurs, such as a request
// from the DEX or a tip change.
func (t *trackedTrade) negotiate(msgMatches []*msgjson.Match) error {
trade := t.Trade()
// Validate matches and check if a cancel match is included.
// Non-cancel matches should be negotiated and are added to
// the newTrackers slice.
var cancelMatch *msgjson.Match
newTrackers := make([]*matchTracker, 0, len(msgMatches))
for _, msgMatch := range msgMatches {
if len(msgMatch.MatchID) != order.MatchIDSize {
return fmt.Errorf("match id of incorrect length. expected %d, got %d",
order.MatchIDSize, len(msgMatch.MatchID))
}
var oid order.OrderID
copy(oid[:], msgMatch.OrderID)
if oid != t.ID() {
return fmt.Errorf("negotiate called for wrong order. %s != %s", oid, t.ID())
}
var mid order.MatchID
copy(mid[:], msgMatch.MatchID)
// Do not process matches with existing matchTrackers. e.g. In case we
// start "extra" matches from the 'connect' response negotiating via
// authDEX>readConnectMatches, and a subsequent resent 'match' request
// leads us here again or vice versa. Or just duplicate match requests.
if t.matches[mid] != nil {
t.dc.log.Warnf("Skipping match %v that is already negotiating.", mid)
continue
}
// Check if this is a match with a cancel order, in which case the
// counterparty Address field would be empty. If the user placed a
// cancel order, that order will be recorded in t.cancel on cancel
// order creation via (*dexConnection).tryCancel or restored from DB
// via (*Core).dbTrackers.
if t.cancel != nil && msgMatch.Address == "" {
cancelMatch = msgMatch
continue
}
match := &matchTracker{
prefix: t.Prefix(),
trade: trade,
MetaMatch: *t.makeMetaMatch(msgMatch),
counterConfirms: -1, // initially unknown, log first check
lastExpireDur: 365 * 24 * time.Hour,
}
match.Status = order.NewlyMatched // these must be new matches
newTrackers = append(newTrackers, match)
}
// Record any cancel order Match and update order status.
var metaCancelMatch *db.MetaMatch
if cancelMatch != nil {
t.dc.log.Infof("Order %s canceled. match id = %s",
t.ID(), cancelMatch.MatchID)
// Set this order status to Canceled and unlock any locked coins
// if there are no new matches and there's no need to send swap
// for any previous match.
t.metaData.Status = order.OrderStatusCanceled
if len(newTrackers) == 0 {
t.maybeReturnCoins()
}
// Note: In TopicNewMatch later, it must be status complete to agree
// with coreOrderFromMetaOrder, which pulls match data *from the DB*.
cancelMatch.Status = uint8(order.MatchComplete) // we're completing it now
cancelMatch.Address = "" // not a trade match
t.cancel.matches.maker = cancelMatch // taker is stored via processCancelMatch before negotiate
// Set the order status for the cancel order.
err := t.db.UpdateOrderStatus(t.cancel.ID(), order.OrderStatusExecuted)
if err != nil {
t.dc.log.Errorf("Failed to update status of cancel order %v to executed: %v",
t.cancel.ID(), err)
// Try to store the match anyway.
}
// Store a completed maker cancel match in the DB.
metaCancelMatch = t.makeMetaMatch(cancelMatch)
err = t.db.UpdateMatch(metaCancelMatch)
if err != nil {
return fmt.Errorf("failed to update match in db: %w", err)
}
}
// Now that each Match in msgMatches has been validated, store them in the
// trackedTrade and the DB, and update the newFill amount.
var newFill uint64
for _, match := range newTrackers {
var qty uint64
if t.isMarketBuy() {
qty = calc.BaseToQuote(match.Rate, match.Quantity)
} else {
qty = match.Quantity
}
newFill += qty
if trade.Filled()+newFill > trade.Quantity {
t.dc.log.Errorf("Match %s would put order %s fill over quantity. Revoking the match.",
match, t.ID())
match.MetaData.Proof.SelfRevoked = true
}
// If this order has no funding coins, block swaps attempts on the new
// match. Do not revoke however since the user may be able to resolve
// wallet configuration issues and restart to restore funding coins.
// Otherwise the server will end up revoking these matches.
if !t.hasFundingCoins() {
t.dc.log.Errorf("Unable to begin swap negotiation for unfunded order %v", t.ID())
match.swapErr = errors.New("no funding coins for swap")
}
err := t.db.UpdateMatch(&match.MetaMatch)
if err != nil {
// Don't abandon other matches because of this error, attempt
// to negotiate the other matches.
t.dc.log.Errorf("failed to update match %s in db: %v", match, err)
continue
}
// Only add this match to the map if the db update succeeds, so
// funds don't get stuck if user restarts Core after sending a
// swap because negotiations will not be resumed for this match
// and auto-refund cannot be performed.
// TODO: Maybe allow? This match can be restored from the DEX's
// connect response on restart IF it is not revoked.
t.matches[match.MatchID] = match
t.dc.log.Infof("Starting negotiation for match %s for order %v with swap fee rate = %v, quantity = %v",
match, t.ID(), match.FeeRateSwap, qty)
}
// If the order has been canceled, add that to filled and newFill.
preCancelFilled, canceled := t.recalcFilled()
filled := preCancelFilled + canceled
if cancelMatch != nil {
newFill += cancelMatch.Quantity
}
// The filled amount includes all of the trackedTrade's matches, so the
// filled amount must be set, not just increased.
trade.SetFill(filled)
// Before we update any order statuses, check if this is a market sell
// order or an immediate TiF limit order which has just been executed. We
// can return reserves for the remaining part of an order which will not
// filled in the future if the order is a market sell, an immediate TiF
// limit order, or if the order was cancelled.
var completedMarketSell, completedImmediateTiF bool
completedMarketSell = trade.Sell && t.Type() == order.MarketOrderType && t.metaData.Status < order.OrderStatusExecuted
lo, ok := t.Order.(*order.LimitOrder)
if ok {
completedImmediateTiF = lo.Force == order.ImmediateTiF && t.metaData.Status < order.OrderStatusExecuted
}
if remain := trade.Quantity - preCancelFilled; remain > 0 && (completedMarketSell || completedImmediateTiF || cancelMatch != nil) {
t.unlockRedemptionFraction(remain, trade.Quantity)
t.unlockRefundFraction(remain, trade.Quantity)
}
// Set the order as executed depending on type and fill.
if t.metaData.Status != order.OrderStatusCanceled && t.metaData.Status != order.OrderStatusRevoked {
if lo, ok := t.Order.(*order.LimitOrder); ok && lo.Force == order.StandingTiF && filled < trade.Quantity {
t.metaData.Status = order.OrderStatusBooked
} else {
t.metaData.Status = order.OrderStatusExecuted
}
}
// Send notifications.
corder := t.coreOrderInternal()
if metaCancelMatch != nil {
topic := TopicBuyOrderCanceled
if trade.Sell {
topic = TopicSellOrderCanceled
}
subject, details := t.formatDetails(topic, unbip(t.Base()), unbip(t.Quote()), t.dc.acct.host, makeOrderToken(t.token()))
t.notify(newOrderNote(topic, subject, details, db.Poke, corder))