-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathtrade.go
1912 lines (1731 loc) · 67 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"
"strings"
"sync"
"time"
"decred.org/dcrdex/client/asset"
"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) }
// A matchTracker is used to negotiate a match.
type matchTracker struct {
db.MetaMatch
id order.MatchID
failErr error
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
// The following fields facilitate useful logging, while not being spammy.
// 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).
counterConfirms int64
// 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 set in
// isRefundable. Initialize this to a very large value to guarantee that it
// will be logged on the first check or when 0.
lastExpireDur time.Duration
}
// parts is a getter for pointers to commonly used struct fields in the
// matchTracker.
func (match *matchTracker) parts() (*order.UserMatch, *db.MatchMetaData, *db.MatchProof, *db.MatchAuth) {
dbMatch, metaData := match.Match, match.MetaData
proof, auth := &metaData.Proof, &metaData.Proof.Auth
return dbMatch, metaData, proof, auth
}
// trackedCancel is information necessary to track a cancel order. A
// trackedCancel is always associated with a trackedTrade.
type trackedCancel struct {
order.CancelOrder
preImg order.Preimage
matches struct {
maker *msgjson.Match
taker *msgjson.Match
}
}
// trackedTrade is an order, 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 {
order.Order
// mtx protects all read-write fields of the trackedTrade and the
// matchTrackers in the matches map.
mtx sync.RWMutex
metaData *db.OrderMetaData
dc *dexConnection
db db.DB
latencyQ *wait.TickerQueue
wallets *walletSet
preImg order.Preimage
mktID string
coins map[string]asset.Coin
coinsLocked bool
lockTimeTaker time.Duration
lockTimeMaker time.Duration
change asset.Coin
changeLocked bool
cancel *trackedCancel
matches map[order.MatchID]*matchTracker
notify func(Notification)
epochLen uint64
fromAssetID uint32
}
// newTrackedTrade is a constructor for a trackedTrade.
func newTrackedTrade(dbOrder *db.MetaOrder, preImg order.Preimage, dc *dexConnection, epochLen uint64,
lockTimeTaker, lockTimeMaker time.Duration, db db.DB, latencyQ *wait.TickerQueue, wallets *walletSet,
coins asset.Coins, notify func(Notification)) *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),
coinsLocked: true,
lockTimeTaker: lockTimeTaker,
lockTimeMaker: lockTimeMaker,
matches: make(map[order.MatchID]*matchTracker),
notify: notify,
epochLen: epochLen,
fromAssetID: fromID,
}
return t
}
// 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.
func (t *trackedTrade) broadcastTimeout() time.Duration {
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, *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, *Order) {
corder := coreOrderFromTrade(t.Order, t.metaData)
corder.Epoch = t.dc.marketEpoch(t.mktID, t.Prefix().ServerTime)
for _, mt := range t.matches {
corder.Matches = append(corder.Matches, matchFromMetaMatch(&mt.MetaMatch))
}
var cancelOrder *Order
if t.cancel != nil {
cancelOrder = &Order{
Host: t.dc.acct.host,
MarketID: t.mktID,
Type: order.CancelOrderType,
Stamp: encode.UnixMilliU(t.cancel.ServerTime),
Epoch: t.dc.marketEpoch(t.mktID, t.Prefix().ServerTime),
TargetID: t.cancel.TargetOrderID[:],
}
}
return corder, cancelOrder
}
// token is a shortened representation of the order ID.
func (t *trackedTrade) token() string {
id := t.ID()
return hex.EncodeToString(id[:4])
}
// cancelTrade sets the cancellation data with the order and its preimage.
func (t *trackedTrade) cancelTrade(co *order.CancelOrder, preImg order.Preimage) error {
t.mtx.Lock()
defer t.mtx.Unlock()
t.cancel = &trackedCancel{
CancelOrder: *co,
preImg: preImg,
}
err := t.db.LinkOrder(t.ID(), co.ID())
if err != nil {
return fmt.Errorf("error linking cancel order %s for trade %s: %w", co.ID(), t.ID(), err)
}
t.metaData.LinkedOrder = co.ID()
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.
cid := t.cancel.ID()
log.Warnf("cancel order %s did not match for order %s.", cid, t.ID())
err := t.db.LinkOrder(t.ID(), order.OrderID{})
if err != nil {
log.Errorf("DB error unlinking cancel order %s for trade %s: %w", cid, t.ID(), err)
}
// Clearing the trackedCancel allows this order to be canceled again.
t.cancel = nil
t.metaData.LinkedOrder = order.OrderID{}
details := fmt.Sprintf("Cancel order did not match for order %s. This can happen if the cancel order is submitted in the same epoch as the trade or if the target order is fully executed before matching with the cancel order.", t.token())
corder, _ := t.coreOrderInternal()
t.notify(newOrderNote("Missed cancel", details, db.WarningLevel, corder))
return assets, t.db.UpdateOrderStatus(cid, 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 {
log.Infof("Standing order %s did not match and is now booked.", t.token())
t.metaData.Status = order.OrderStatusBooked
corder, _ := t.coreOrderInternal()
t.notify(newOrderNote("Order booked", "", db.Data, corder))
} else {
t.returnCoins()
assets.count(t.wallets.fromAsset.ID)
log.Infof("Non-standing order %s did not match.", t.token())
t.metaData.Status = order.OrderStatusExecuted
corder, _ := t.coreOrderInternal()
t.notify(newOrderNote("No match", "", db.Data, corder))
}
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()
isMarketBuy := t.Type() == order.MarketOrderType && !trade.Sell
// 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 {
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{
id: mid,
prefix: t.Prefix(),
trade: trade,
MetaMatch: *t.makeMetaMatch(msgMatch),
counterConfirms: -1,
lastExpireDur: 365 * 24 * time.Hour,
}
match.SetStatus(order.NewlyMatched) // these must be new matches
newTrackers = append(newTrackers, match)
}
// Record any cancel order Match and update order status.
if cancelMatch != nil {
log.Infof("Maker notification for cancel order received for order %s. 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()
}
t.cancel.matches.maker = cancelMatch // taker is stored via processCancelMatch before negotiate
// Set the order status for the canceled order.
t.db.UpdateOrderStatus(t.cancel.ID(), order.OrderStatusExecuted)
// Store a completed maker cancel match in the DB.
makerCancelMeta := t.makeMetaMatch(cancelMatch)
makerCancelMeta.SetStatus(order.MatchComplete)
err := t.db.UpdateMatch(makerCancelMeta)
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 isMarketBuy {
qty = calc.BaseToQuote(match.Match.Rate, match.Match.Quantity)
} else {
qty = match.Match.Quantity
}
newFill += qty
if trade.Filled()+newFill > trade.Quantity {
log.Errorf("Match %s would put order %s fill over quantity. Revoking the match.",
match.id, t.ID())
match.MetaData.Proof.SelfRevoked = true
}
err := t.db.UpdateMatch(&match.MetaMatch)
if err != nil {
// Don't abandon other matches because of this error, attempt
// to negotiate the other matches.
log.Errorf("failed to update match %s in db: %v", match.id, 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.id] = match
log.Infof("Starting negotiation for match %v for order %v with swap fee rate = %v, quantity = %v",
match.id, t.ID(), match.Match.FeeRateSwap, qty)
}
// Calculate and set the new filled value for the order.
var filled uint64
for _, mt := range t.matches {
if isMarketBuy {
filled += calc.BaseToQuote(mt.Match.Rate, mt.Match.Quantity)
} else {
filled += mt.Match.Quantity
}
}
// If the order has been canceled, add that to filled and newFill.
if cancelMatch != nil {
filled += cancelMatch.Quantity
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)
// 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, cancelOrder := t.coreOrderInternal()
if cancelMatch != nil {
details := fmt.Sprintf("%s order on %s-%s at %s has been canceled (%s)",
strings.Title(sellString(trade.Sell)), unbip(t.Base()), unbip(t.Quote()), t.dc.acct.host, t.token())
t.notify(newOrderNote("Order canceled", details, db.Success, corder))
// Also send out a data notification with the cancel order information.
t.notify(newOrderNote("cancel", "", db.Data, cancelOrder))
}
if len(newTrackers) > 0 {
fillPct := 100 * float64(filled) / float64(trade.Quantity)
details := fmt.Sprintf("%s order on %s-%s %.1f%% filled (%s)",
strings.Title(sellString(trade.Sell)), unbip(t.Base()), unbip(t.Quote()), fillPct, t.token())
log.Debugf("Trade order %v matched with %d orders: +%d filled, total fill %d / %d (%.1f%%)",
t.ID(), len(newTrackers), newFill, filled, trade.Quantity, fillPct)
t.notify(newOrderNote("Matches made", details, db.Poke, corder))
}
err := t.db.UpdateOrder(t.metaOrder())
if err != nil {
return fmt.Errorf("failed to update order in db: %w", err)
}
return nil
}
func (t *trackedTrade) metaOrder() *db.MetaOrder {
return &db.MetaOrder{
MetaData: t.metaData,
Order: t.Order,
}
}
func (t *trackedTrade) makeMetaMatch(msgMatch *msgjson.Match) *db.MetaMatch {
// Contract txn asset: buy means quote, sell means base. NOTE: msgjson.Match
// could instead have just FeeRateSwap for the recipient, but the other fee
// rate could be of value for auditing the counter party's contract txn.
feeRateSwap := msgMatch.FeeRateQuote
if t.Trade().Sell {
feeRateSwap = msgMatch.FeeRateBase
}
var oid order.OrderID
copy(oid[:], msgMatch.OrderID)
var mid order.MatchID
copy(mid[:], msgMatch.MatchID)
return &db.MetaMatch{
MetaData: &db.MatchMetaData{
Status: order.MatchStatus(msgMatch.Status),
Proof: db.MatchProof{
Auth: db.MatchAuth{
MatchSig: msgMatch.Sig,
MatchStamp: msgMatch.ServerTime,
},
},
DEX: t.dc.acct.host,
Base: t.Base(),
Quote: t.Quote(),
Stamp: msgMatch.ServerTime,
},
Match: &order.UserMatch{
OrderID: oid,
MatchID: mid,
Quantity: msgMatch.Quantity,
Rate: msgMatch.Rate,
Address: msgMatch.Address,
Status: order.MatchStatus(msgMatch.Status),
Side: order.MatchSide(msgMatch.Side),
FeeRateSwap: feeRateSwap,
},
}
}
// processCancelMatch should be called with the message for the match on a
// cancel order.
func (t *trackedTrade) processCancelMatch(msgMatch *msgjson.Match) error {
var oid order.OrderID
copy(oid[:], msgMatch.OrderID)
var mid order.MatchID
copy(mid[:], msgMatch.MatchID)
t.mtx.Lock()
defer t.mtx.Unlock()
if t.cancel == nil {
return fmt.Errorf("no cancel order recorded for order %v", oid)
}
if oid != t.cancel.ID() {
return fmt.Errorf("negotiate called for wrong order. %s != %s", oid, t.cancel.ID())
}
log.Infof("Taker notification for cancel order %v received. Match id = %s", oid, mid)
t.cancel.matches.taker = msgMatch
// Store the completed taker cancel match.
takerCancelMeta := t.makeMetaMatch(t.cancel.matches.taker)
takerCancelMeta.SetStatus(order.MatchComplete)
err := t.db.UpdateMatch(takerCancelMeta)
if err != nil {
return fmt.Errorf("failed to update match in db: %w", err)
}
return nil
}
// Get the required and current confirmation count on the counterparty's swap
// contract transaction for the provided match. If the count has not changed
// since the previous check, changed will be false.
//
// This method accesses match fields and MUST be called with the trackedTrade
// mutex lock held for reads.
func (t *trackedTrade) counterPartyConfirms(match *matchTracker) (have, needed uint32, changed bool) {
// Counter-party's swap is the "to" asset.
needed = t.wallets.toAsset.SwapConf
// Check the confirmations on the counter-party's swap.
coin := match.counterSwap.Coin()
var err error
have, err = coin.Confirmations()
if err != nil {
log.Errorf("Failed to get confirmations of the counter-party's swap %s (%s) for match %v, order %v",
coin, t.wallets.toAsset.Symbol, match.id, t.UID())
have = 0 // should already be
return
}
// Log the pending swap status at new heights only.
if match.counterConfirms != int64(have) {
match.counterConfirms = int64(have)
changed = true
}
return
}
// deleteStaleCancelOrder checks if this trade has an associated cancel order,
// and deletes the cancel order if the cancel order stays at Epoch status for
// more than 2 epochs. Deleting the stale cancel order from this trade makes
// it possible for the client to re- attempt cancelling the order.
//
// NOTE:
// Stale cancel orders would be Executed if their preimage was sent or Revoked
// if their preimages was not sent. We cannot currently tell whether the cancel
// order's preimage was revealed, so assume that the cancel order is Executed
// but unmatched. Consider adding a order.PreimageRevealed field to ensure that
// the correct final status is set for the cancel order; or allow the server to
// check and return status of cancel orders.
//
// This method MUST be called with the trackedTrade mutex lock held for writes.
func (t *trackedTrade) deleteStaleCancelOrder() {
if t.cancel == nil || t.metaData.Status != order.OrderStatusBooked {
return
}
stamp := t.cancel.ServerTime
epoch := order.EpochID{Idx: encode.UnixMilliU(stamp) / t.epochLen, Dur: t.epochLen}
epochEnd := epoch.End()
if time.Since(epochEnd).Milliseconds() < int64(2*t.epochLen) {
return // not stuck, yet
}
log.Infof("Cancel order %v in epoch status with server time stamp %v, epoch end %v (%v ago) considered executed and unmatched.",
t.cancel.ID(), t.cancel.ServerTime, epochEnd, time.Since(epochEnd))
err := t.db.LinkOrder(t.ID(), order.OrderID{})
if err != nil {
log.Errorf("DB error unlinking cancel order %s for trade %s: %w", t.cancel.ID(), t.ID(), err)
}
// Clearing the trackedCancel allows this order to be canceled again.
t.cancel = nil
t.metaData.LinkedOrder = order.OrderID{}
details := fmt.Sprintf("Cancel order for order %s stuck in Epoch status for 2 epochs and is now deleted.", t.token())
corder, _ := t.coreOrderInternal()
t.notify(newOrderNote("Failed cancel", details, db.WarningLevel, corder))
}
// isActive will be true if the trade is booked or epoch, or if any of the
// matches are still negotiating.
func (t *trackedTrade) isActive() bool {
t.mtx.RLock()
defer t.mtx.RUnlock()
// Status of the order itself.
if t.metaData.Status == order.OrderStatusBooked ||
t.metaData.Status == order.OrderStatusEpoch {
return true
}
// Status of all matches for the order.
for _, match := range t.matches {
proof := &match.MetaData.Proof
log.Tracef("Checking match %v (%v) in status %v. "+
"Order: %v, Refund coin: %v, Script: %x, Revoked: %v", match.id,
match.Match.Side, match.MetaData.Status, t.ID(),
proof.RefundCoin, proof.Script, proof.IsRevoked)
if match.isActive() {
return true
}
}
return false
}
// Matches are inactive if: (1) status is complete, (2) it is refunded, or (3)
// it is revoked and this side of the match requires no further action like
// refund or auto-redeem.
func (match *matchTracker) isActive() bool {
if match.MetaData.Status == order.MatchComplete {
return false
}
// Refunded matches are inactive regardless of status.
if len(match.MetaData.Proof.RefundCoin) > 0 {
return false
}
// Revoked matches may need to be refunded or auto-redeemed first.
if match.MetaData.Proof.IsRevoked() {
// - NewlyMatched requires no further action from either side
// - MakerSwapCast requires no further action from the taker
// - (TakerSwapCast requires action on both sides)
// - MakerRedeemed requires no further action from the maker
status, side := match.MetaData.Status, match.Match.Side
if status == order.NewlyMatched ||
(status == order.MakerSwapCast && side == order.Taker) ||
(status == order.MakerRedeemed && side == order.Maker) {
log.Tracef("Revoked match %v (%v) in status %v considered inactive.",
match.id, side, status)
return false
}
}
return true
}
func (t *trackedTrade) activeMatches() []*matchTracker {
var actives []*matchTracker
t.mtx.RLock()
defer t.mtx.RUnlock()
for _, match := range t.matches {
if match.isActive() {
actives = append(actives, match)
}
}
return actives
}
// unspentContractAmounts returns the total amount locked in unspent swaps.
func (t *trackedTrade) unspentContractAmounts(assetID uint32) (amount uint64) {
if t.fromAssetID != assetID {
// Only swaps sent from the specified assetID should count.
return 0
}
t.mtx.RLock()
defer t.mtx.RUnlock()
swapSentFromQuoteAsset := t.fromAssetID == t.Quote()
for _, match := range t.matches {
side, status := match.Match.Side, match.Match.Status
if status >= order.MakerRedeemed || len(match.MetaData.Proof.RefundCoin) != 0 {
// Any redemption or own refund implies our swap is spent.
// Even if we're Maker and our swap has not been redeemed
// by Taker, we should consider it spent.
continue
}
if (side == order.Maker && status >= order.MakerSwapCast) ||
(side == order.Taker && status == order.TakerSwapCast) {
swapAmount := match.Match.Quantity
if swapSentFromQuoteAsset {
swapAmount = calc.BaseToQuote(match.Match.Rate, match.Match.Quantity)
}
amount += swapAmount
}
}
return
}
// isSwappable will be true if the match is ready for a swap transaction to be
// broadcast.
//
// This method accesses match fields and MUST be called with the trackedTrade
// mutex lock held for reads.
func (t *trackedTrade) isSwappable(match *matchTracker) bool {
dbMatch, metaData, proof, _ := match.parts()
if match.failErr != nil || proof.IsRevoked() {
log.Tracef("Match %v not swappable: failErr = %v, revoked = %v",
match.id, match.failErr, proof.IsRevoked())
return false
}
wallet := t.wallets.fromWallet
if !wallet.unlocked() {
log.Errorf("cannot swap order %s, match %s, because %s wallet is not unlocked",
t.ID(), match.id, unbip(wallet.AssetID))
return false
}
if dbMatch.Side == order.Taker && metaData.Status == order.MakerSwapCast {
// Check the confirmations on the maker's swap.
confs, req, changed := t.counterPartyConfirms(match)
ready := confs >= req
if changed && !ready {
log.Debugf("Match %v not yet swappable: current confs = %d, required confs = %d",
match.id, confs, req)
}
return ready
}
if dbMatch.Side == order.Maker && metaData.Status == order.NewlyMatched {
return true
}
return false
}
// isRedeemable will be true if the match is ready for our redemption to be
// broadcast.
//
// This method accesses match fields and MUST be called with the trackedTrade
// mutex lock held for reads.
func (t *trackedTrade) isRedeemable(match *matchTracker) bool {
dbMatch, metaData, proof, _ := match.parts()
if match.failErr != nil || len(proof.RefundCoin) != 0 {
log.Tracef("Match %v not redeemable: failErr = %v, RefundCoin = %v",
match.id, match.failErr, proof.RefundCoin)
return false
}
wallet := t.wallets.toWallet
if !wallet.unlocked() {
log.Errorf("cannot redeem order %s, match %s, because %s wallet is not unlocked",
t.ID(), match.id, unbip(wallet.AssetID))
return false
}
if dbMatch.Side == order.Maker && metaData.Status == order.TakerSwapCast {
// Check the confirmations on the taker's swap.
confs, req, changed := t.counterPartyConfirms(match)
ready := confs >= req
if changed && !ready {
log.Debugf("Match %v not yet redeemable: current confs = %d, required confs = %d",
match.id, confs, req)
}
return ready
}
if dbMatch.Side == order.Taker && metaData.Status == order.MakerRedeemed {
return true
}
return false
}
// isRefundable will be true if all of the following are true:
// - We have broadcasted a swap contract (matchProof.Script != nil).
// - Neither party has redeemed (matchStatus < order.MakerRedeemed).
// For Maker, this means we've not redeemed. For Taker, this means we've
// not been notified of / we haven't yet found the Maker's redeem.
// - Our swap's locktime has expired.
//
// Those checks are skipped and isRefundable is false if we've already
// executed a refund or our refund-to wallet is locked.
//
// This method modifies match fields and MUST be called with the trackedTrade
// mutex lock held for writes.
func (t *trackedTrade) isRefundable(match *matchTracker) bool {
dbMatch, _, proof, _ := match.parts()
if match.refundErr != nil || len(proof.RefundCoin) != 0 {
log.Tracef("Match %v not refundable: refundErr = %v, RefundCoin = %v",
match.id, match.refundErr, proof.RefundCoin)
return false
}
wallet := t.wallets.fromWallet
if !wallet.unlocked() {
log.Errorf("cannot refund order %s, match %s, because %s wallet is not unlocked",
t.ID(), match.id, unbip(wallet.AssetID))
return false
}
// Return if we've NOT sent a swap OR a redeem has been
// executed by either party.
if len(proof.Script) == 0 || dbMatch.Status >= order.MakerRedeemed {
return false
}
// Issue a refund if our swap's locktime has expired.
swapLocktimeExpired, contractExpiry, err := wallet.LocktimeExpired(proof.Script)
if err != nil {
log.Errorf("error checking if locktime has expired for %s contract on order %s, match %s: %v",
dbMatch.Side, t.ID(), match.id, err)
return false
}
if swapLocktimeExpired {
return true
}
// For the first check or hourly tick, log the time until expiration.
expiresIn := time.Until(contractExpiry) // may be negative
if match.lastExpireDur-expiresIn < time.Hour {
// Logged less than an hour ago.
return false
}
// Record this log event's expiry duration.
match.lastExpireDur = expiresIn
swapCoinID := proof.TakerSwap
if dbMatch.Side == order.Maker {
swapCoinID = proof.MakerSwap
}
from := t.wallets.fromAsset
remainingTime := expiresIn.Round(time.Second)
var but string
if remainingTime <= 0 {
// Since reaching expiry time does not necessarily mean it is spendable
// by consensus rules (e.g. 11 block median time must be greater than
// lock time with BTC), include a "but" in the message.
but = "but "
}
log.Infof("Contract for match %v with swap coin %v (%s) has an expiry time of %v (%v), %snot yet expired.",
match.id, coinIDString(from.ID, swapCoinID), from.Symbol,
contractExpiry, remainingTime, but)
return false
}
// shouldBeginFindRedemption will be true if we are the Taker on this match,
// we've broadcasted a swap, our swap has gotten the required confs, the match
// was revoked without receiving a valid notification of Maker's redeem and
// we've not refunded our swap.
//
// This method accesses match fields and MUST be called with the trackedTrade
// mutex lock held for reads.
func (t *trackedTrade) shouldBeginFindRedemption(match *matchTracker) bool {
proof := &match.MetaData.Proof
if !proof.IsRevoked() {
return false // Only auto-find redemption for revoked/failed matches.
}
swapCoinID := proof.TakerSwap
if match.Match.Side != order.Taker || len(swapCoinID) == 0 || len(proof.MakerRedeem) > 0 || len(proof.RefundCoin) > 0 {
log.Tracef(
"Not finding redemption for match %v: side = %s, failErr = %v, TakerSwap = %v RefundCoin = %v",
match.id, match.Match.Side, match.failErr, proof.TakerSwap, proof.RefundCoin)
return false
}
if match.cancelRedemptionSearch != nil { // already finding redemption
return false
}
confs, err := t.wallets.fromWallet.Confirmations([]byte(swapCoinID))
if err != nil {
log.Errorf("Failed to get confirmations of the taker's swap %s (%s) for match %v, order %v",
coinIDString(t.wallets.fromAsset.ID, swapCoinID), t.wallets.fromAsset.Symbol, match.id, t.UID())
return false
}
return confs >= t.wallets.fromAsset.SwapConf
}
// tick will check for and perform any match actions necessary.
func (c *Core) tick(t *trackedTrade) (assetMap, error) {
t.mtx.Lock()
defer t.mtx.Unlock()
var swaps, redeems, refunds []*matchTracker
assets := make(assetMap)
errs := newErrorSet(t.dc.acct.host + " tick: ")
// Check all matches for and resend pending requests as necessary.
if err := c.resendPendingRequests(t); err != nil {
errs.addErr(err)
}
// Check all matches and send swap, redeem or refund as necessary.
var sent, quoteSent, received, quoteReceived uint64
for _, match := range t.matches {
side := match.Match.Side
if (side == order.Maker && match.MetaData.Status >= order.MakerRedeemed) ||
(side == order.Taker && match.MetaData.Status >= order.MatchComplete) {
continue
}
if match.Match.Address == "" {
continue // a cancel order match
}
if !match.isActive() {
continue // either refunded or revoked requiring no action on this side of the match
}
switch {
case t.isSwappable(match):
log.Debugf("Swappable match %v for order %v (%v)", match.id, t.ID(), side)
swaps = append(swaps, match)
sent += match.Match.Quantity
quoteSent += calc.BaseToQuote(match.Match.Rate, match.Match.Quantity)
case t.isRedeemable(match):
log.Debugf("Redeemable match %v for order %v (%v)", match.id, t.ID(), side)
redeems = append(redeems, match)
received += match.Match.Quantity
quoteReceived += calc.BaseToQuote(match.Match.Rate, match.Match.Quantity)
// Check refundability before checking if to start finding redemption.
// Ensures that redemption search is not started if locktime has expired.
// If we've already started redemption search for this match, the search
// will be aborted if/when auto-refund succeeds.
case t.isRefundable(match):
log.Debugf("Refundable match %v for order %v (%v)", match.id, t.ID(), side)
refunds = append(refunds, match)
case t.shouldBeginFindRedemption(match):
log.Debugf("Ready to find counter-party redemption for match %v, order %v (%v)", match.id, t.ID(), side)
t.findMakersRedemption(match)
}
}
fromID := t.wallets.fromAsset.ID
if len(swaps) > 0 || len(refunds) > 0 {
assets.count(fromID)
}
if len(swaps) > 0 {
qty := sent
if !t.Trade().Sell {
qty = quoteSent
}
err := c.swapMatches(t, swaps)
// swapMatches might modify the matches, so don't get the *Order for
// notifications before swapMatches.
corder, _ := t.coreOrderInternal()
if err != nil {
errs.addErr(err)
details := fmt.Sprintf("Error encountered sending a swap output(s) worth %.8f %s on order %s",
float64(qty)/conversionFactor, unbip(fromID), t.token())
t.notify(newOrderNote("Swap error", details, db.ErrorLevel, corder))
} else {
details := fmt.Sprintf("Sent swaps worth %.8f %s on order %s",
float64(qty)/conversionFactor, unbip(fromID), t.token())
t.notify(newOrderNote("Swaps initiated", details, db.Poke, corder))
}
}
if len(redeems) > 0 {
toAsset := t.wallets.toAsset.ID
assets.count(toAsset)
assets.count(t.fromAssetID) // update the from wallet balance to reduce contractlocked balance
qty := received
if t.Trade().Sell {
qty = quoteReceived
}
err := c.redeemMatches(t, redeems)
corder, _ := t.coreOrderInternal()
if err != nil {
errs.addErr(err)
details := fmt.Sprintf("Error encountered sending redemptions worth %.8f %s on order %s",
float64(qty)/conversionFactor, unbip(toAsset), t.token())
t.notify(newOrderNote("Redemption error", details, db.ErrorLevel, corder))
} else {
details := fmt.Sprintf("Redeemed %.8f %s on order %s",
float64(qty)/conversionFactor, unbip(toAsset), t.token())
t.notify(newOrderNote("Match complete", details, db.Poke, corder))
}
}
if len(refunds) > 0 {
refunded, err := t.refundMatches(refunds)
corder, _ := t.coreOrderInternal()
details := fmt.Sprintf("Refunded %.8f %s on order %s",
float64(refunded)/conversionFactor, unbip(fromID), t.token())
if err != nil {
errs.addErr(err)
t.notify(newOrderNote("Refund Failure", details+", with some errors", db.ErrorLevel, corder))
} else {
t.notify(newOrderNote("Matches Refunded", details, db.WarningLevel, corder))
}
}
return assets, errs.ifAny()
}
// resendPendingRequests checks all matches for this order to re-attempt
// sending the `init` or `redeem` request where necessary.
//
// This method modifies match fields and MUST be called with the trackedTrade
// mutex lock held for writes.
func (c *Core) resendPendingRequests(t *trackedTrade) error {
errs := newErrorSet("resendPendingRequest: order %s - ", t.ID())
for _, match := range t.matches {
dbMatch, _, proof, auth := match.parts()
// Do not resend pending requests for revoked matches.
// Matches where we've refunded our swap or we auto-redeemed maker's
// swap will be set to revoked and will be skipped as well.
if match.failErr != nil || proof.IsRevoked() {
continue
}
side, status := dbMatch.Side, dbMatch.Status
var swapCoinID, redeemCoinID []byte
switch {
case side == order.Maker && status == order.MakerSwapCast:
swapCoinID = proof.MakerSwap
case side == order.Taker && status == order.TakerSwapCast:
swapCoinID = proof.TakerSwap
case side == order.Maker && status == order.MakerRedeemed:
redeemCoinID = proof.MakerRedeem
case side == order.Taker && status == order.MatchComplete:
redeemCoinID = proof.TakerRedeem
}
var err error