forked from decred/dcrdex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.go
9149 lines (8159 loc) · 295 KB
/
core.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/binary"
"encoding/csv"
"encoding/hex"
"errors"
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"decred.org/dcrdex/client/asset"
"decred.org/dcrdex/client/comms"
"decred.org/dcrdex/client/db"
"decred.org/dcrdex/client/db/bolt"
"decred.org/dcrdex/client/orderbook"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/calc"
"decred.org/dcrdex/dex/config"
"decred.org/dcrdex/dex/encode"
"decred.org/dcrdex/dex/encrypt"
"decred.org/dcrdex/dex/msgjson"
"decred.org/dcrdex/dex/order"
"decred.org/dcrdex/dex/wait"
"decred.org/dcrdex/server/account"
serverdex "decred.org/dcrdex/server/dex"
"github.com/decred/dcrd/crypto/blake256"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa"
"github.com/decred/go-socks/socks"
"golang.org/x/text/language"
"golang.org/x/text/message"
)
const (
keyParamsKey = "keyParams"
// tickCheckDivisions is how many times to tick trades per broadcast timeout
// interval. e.g. 12 min btimeout / 8 divisions = 90 sec between checks.
tickCheckDivisions = 8
// defaultTickInterval is the tick interval used before the broadcast
// timeout is known (e.g. startup with down server).
defaultTickInterval = 30 * time.Second
marketBuyRedemptionSlippageBuffer = 2
// preimageReqTimeout the server's preimage request timeout period. When
// considered with a market's epoch duration, this is used to detect when an
// order should have gone through matching for a certain epoch. TODO:
// consider sharing const for the preimage timeout with the server packages,
// or a config response field if it should be considered variable.
preimageReqTimeout = 20 * time.Second
)
var (
unbip = dex.BipIDSymbol
// The coin waiters will query for transaction data every recheckInterval.
recheckInterval = time.Second * 5
// When waiting for a wallet to sync, a SyncStatus check will be performed
// every syncTickerPeriod. var instead of const for testing purposes.
syncTickerPeriod = 3 * time.Second
// supportedAPIVers are the DEX server API versions this client is capable
// of communicating with.
//
// NOTE: API version may change at any time. Keep this in mind when
// updating the API. Long-running operations may start and end with
// differing versions.
supportedAPIVers = []int32{serverdex.PreAPIVersion, serverdex.BondAPIVersion}
// ActiveOrdersLogoutErr is returned from logout when there are active
// orders.
ActiveOrdersLogoutErr = errors.New("cannot log out with active orders")
// walletDisabledErrStr is the error message returned when trying to use a
// disabled wallet.
walletDisabledErrStr = "%s wallet is disabled"
errTimeout = errors.New("timeout")
)
type dexTicker struct {
dur int64 // atomic
*time.Ticker
}
func newDexTicker(dur time.Duration) *dexTicker {
return &dexTicker{
dur: int64(dur),
Ticker: time.NewTicker(dur),
}
}
func (dt *dexTicker) Reset(dur time.Duration) {
atomic.StoreInt64(&dt.dur, int64(dur))
dt.Ticker.Reset(dur)
}
func (dt *dexTicker) Dur() time.Duration {
return time.Duration(atomic.LoadInt64(&dt.dur))
}
type pendingFeeState struct {
confs uint32
asset uint32
}
// dexConnection is the websocket connection and the DEX configuration.
type dexConnection struct {
comms.WsConn
connMaster *dex.ConnectionMaster
log dex.Logger
acct *dexAccount
notify func(Notification)
ticker *dexTicker
// apiVer is an atomic. An uninitiated connection should be set to -1.
apiVer int32
assetsMtx sync.RWMutex
assets map[uint32]*dex.Asset
cfgMtx sync.RWMutex
cfg *msgjson.ConfigResult
booksMtx sync.RWMutex
books map[string]*bookie
// tradeMtx is used to synchronize access to the trades map.
tradeMtx sync.RWMutex
// trades tracks outstanding orders issued by this client.
trades map[order.OrderID]*trackedTrade
// inFlightOrders tracks orders issued by this client that have not been
// processed by a dex server.
inFlightOrders map[uint64]*InFlightOrder
epochMtx sync.RWMutex
epoch map[string]uint64
// connectionStatus is a best guess on the ws connection status.
connectionStatus uint32
// pendingFee is deprecated, and will be removed when v0 API support is
// dropped in favor of v1 with bonds. (V0PURGE)
pendingFeeMtx sync.RWMutex
pendingFee *pendingFeeState
reportingConnects uint32
spotsMtx sync.RWMutex
spots map[string]*msgjson.Spot
}
// DefaultResponseTimeout is the default timeout for responses after a request is
// successfully sent.
const (
DefaultResponseTimeout = comms.DefaultResponseTimeout
fundingTxWait = time.Minute // TODO: share var with server/market or put in config
)
// running returns the status of the provided market.
func (dc *dexConnection) running(mkt string) bool {
dc.cfgMtx.RLock()
defer dc.cfgMtx.RUnlock()
mktCfg := dc.findMarketConfig(mkt)
if mktCfg == nil {
return false // not found means not running
}
return mktCfg.Running()
}
// status returns the status of the connection to the dex.
func (dc *dexConnection) status() comms.ConnectionStatus {
return comms.ConnectionStatus(atomic.LoadUint32(&dc.connectionStatus))
}
func (dc *dexConnection) feeAsset(assetID uint32) *msgjson.FeeAsset {
dc.cfgMtx.RLock()
defer dc.cfgMtx.RUnlock()
if dc.cfg == nil {
return nil
}
symb := unbip(assetID)
return dc.cfg.RegFees[symb]
}
// marketConfig is the market's configuration, as returned by the server in the
// 'config' response.
func (dc *dexConnection) marketConfig(mktID string) *msgjson.Market {
dc.cfgMtx.RLock()
defer dc.cfgMtx.RUnlock()
return dc.findMarketConfig(mktID)
}
func (dc *dexConnection) assetConfig(assetID uint32) *dex.Asset {
dc.assetsMtx.RLock()
defer dc.assetsMtx.RUnlock()
return dc.assets[assetID]
}
// marketMap creates a map of this DEX's *Market keyed by name/ID,
// [base]_[quote].
func (dc *dexConnection) marketMap() map[string]*Market {
dc.cfgMtx.RLock()
cfg := dc.cfg
dc.cfgMtx.RUnlock()
if cfg == nil {
return nil
}
mktConfigs := cfg.Markets
marketMap := make(map[string]*Market, len(mktConfigs))
for _, msgMkt := range mktConfigs {
mkt := coreMarketFromMsgMarket(dc, msgMkt)
marketMap[mkt.marketName()] = mkt
}
// Populate spots.
dc.spotsMtx.RLock()
for mktID, mkt := range marketMap {
mkt.SpotPrice = dc.spots[mktID]
}
dc.spotsMtx.RUnlock()
return marketMap
}
// marketMap creates a map of this DEX's *Market keyed by name/ID,
// [base]_[quote].
func (dc *dexConnection) coreMarket(mktName string) *Market {
dc.cfgMtx.RLock()
cfg := dc.cfg
dc.cfgMtx.RUnlock()
if cfg == nil {
return nil
}
var mkt *Market
for _, m := range cfg.Markets {
if m.Name == mktName {
mkt = coreMarketFromMsgMarket(dc, m)
break
}
}
if mkt == nil {
return nil
}
// Populate spots.
dc.spotsMtx.RLock()
mkt.SpotPrice = dc.spots[mktName]
dc.spotsMtx.RUnlock()
return mkt
}
func coreMarketFromMsgMarket(dc *dexConnection, msgMkt *msgjson.Market) *Market {
// The presence of the asset for every market was already verified when the
// dexConnection was created in connectDEX.
dc.assetsMtx.RLock()
base, quote := dc.assets[msgMkt.Base], dc.assets[msgMkt.Quote]
dc.assetsMtx.RUnlock()
bconv, qconv := base.UnitInfo.Conventional.ConversionFactor, quote.UnitInfo.Conventional.ConversionFactor
mkt := &Market{
Name: msgMkt.Name,
BaseID: base.ID,
BaseSymbol: base.Symbol,
QuoteID: quote.ID,
QuoteSymbol: quote.Symbol,
LotSize: msgMkt.LotSize,
RateStep: msgMkt.RateStep,
EpochLen: msgMkt.EpochLen,
StartEpoch: msgMkt.StartEpoch,
MarketBuyBuffer: msgMkt.MarketBuyBuffer,
AtomToConv: float64(qconv) / float64(bconv),
}
trades, inFlight := dc.marketTrades(mkt.marketName())
mkt.InFlightOrders = inFlight
for _, trade := range trades {
mkt.Orders = append(mkt.Orders, trade.coreOrder())
}
return mkt
}
// temporaryOrderIDCounter is used for inflight orders and must never be zero
// when used for an inflight order.
var temporaryOrderIDCounter uint64
// storeInFlightOrder stores an inflight order and returns a generated ID.
func (dc *dexConnection) storeInFlightOrder(ord *Order) uint64 {
tempID := atomic.AddUint64(&temporaryOrderIDCounter, 1)
dc.tradeMtx.Lock()
dc.inFlightOrders[tempID] = &InFlightOrder{
Order: ord,
TemporaryID: tempID,
}
dc.tradeMtx.Unlock()
return tempID
}
func (dc *dexConnection) deleteInFlightOrder(tempID uint64) {
dc.tradeMtx.Lock()
delete(dc.inFlightOrders, tempID)
dc.tradeMtx.Unlock()
}
func (dc *dexConnection) trackedTrades() []*trackedTrade {
dc.tradeMtx.RLock()
defer dc.tradeMtx.RUnlock()
allTrades := make([]*trackedTrade, 0, len(dc.trades))
for _, trade := range dc.trades {
allTrades = append(allTrades, trade)
}
return allTrades
}
// marketTrades returns a slice of active trades in the trades map and a slice
// of inflight orders in the inFlightOrders map.
func (dc *dexConnection) marketTrades(mktID string) ([]*trackedTrade, []*InFlightOrder) {
// Copy trades to avoid locking both tradeMtx and trackedTrade.mtx.
allTrades := dc.trackedTrades()
trades := make([]*trackedTrade, 0, len(allTrades)) // may over-allocate
for _, trade := range allTrades {
if trade.mktID == mktID && trade.isActive() {
trades = append(trades, trade)
}
// Retiring inactive orders is presently the responsibility of ticker.
}
dc.tradeMtx.RLock()
inFlight := make([]*InFlightOrder, 0, len(dc.inFlightOrders)) // may over-allocate
for _, ord := range dc.inFlightOrders {
if ord.MarketID == mktID {
inFlight = append(inFlight, ord)
}
}
dc.tradeMtx.RUnlock()
return trades, inFlight
}
func (dc *dexConnection) setPendingFee(asset, confs uint32) {
dc.pendingFeeMtx.Lock()
dc.pendingFee = &pendingFeeState{asset: asset, confs: confs}
dc.pendingFeeMtx.Unlock()
}
func (dc *dexConnection) clearPendingFee() {
dc.pendingFeeMtx.Lock()
dc.pendingFee = nil
dc.pendingFeeMtx.Unlock()
}
// getPendingFee returns the PendingFeeState for the dex registration or nil if
// no registration fee is pending.
func (dc *dexConnection) getPendingFee() *PendingFeeState {
dc.pendingFeeMtx.RLock()
defer dc.pendingFeeMtx.RUnlock()
pf := dc.pendingFee
if pf == nil {
return nil
}
return &PendingFeeState{
AssetID: pf.asset,
Symbol: unbip(pf.asset),
Confs: pf.confs,
}
}
func (dc *dexConnection) exchangeInfo() *Exchange {
// Set AcctID to empty string if not registered.
acctID := dc.acct.ID().String()
var emptyAcctID account.AccountID
if dc.acct.ID() == emptyAcctID {
acctID = ""
}
dc.cfgMtx.RLock()
cfg := dc.cfg
dc.cfgMtx.RUnlock()
if cfg == nil { // no config, assets, or markets data
return &Exchange{
Host: dc.acct.host,
AcctID: acctID,
ConnectionStatus: dc.status(),
PendingFee: dc.getPendingFee(), // V0PURGE - deprecated with bonds in v1
}
}
bondAssets := make(map[string]*BondAsset, len(cfg.BondAssets))
for symb, bondAsset := range cfg.BondAssets {
coreBondAsset := BondAsset(*bondAsset) // convert msgjson.BondAsset to core.BondAsset
bondAssets[symb] = &coreBondAsset
}
dc.assetsMtx.RLock()
assets := make(map[uint32]*dex.Asset, len(dc.assets))
for assetID, dexAsset := range dc.assets {
assets[assetID] = dexAsset
}
dc.assetsMtx.RUnlock()
feeAssets := make(map[string]*FeeAsset, len(cfg.RegFees))
for symb, asset := range cfg.RegFees {
feeAssets[symb] = &FeeAsset{
ID: asset.ID,
Confs: asset.Confs,
Amt: asset.Amt,
}
}
dcrAsset := feeAssets["dcr"]
if dcrAsset == nil { // should have happened in refreshServerConfig
// V0PURGE
dcrAsset = &FeeAsset{
ID: 42,
Amt: cfg.Fee,
Confs: uint32(cfg.RegFeeConfirms),
}
feeAssets["dcr"] = dcrAsset
}
dc.acct.authMtx.RLock()
// TODO: List bonds in core.Exchange. For now, just tier.
// bondsPending := len(dc.acct.pendingBonds) > 0
tier := dc.acct.tier
dc.acct.authMtx.RUnlock()
return &Exchange{
Host: dc.acct.host,
AcctID: acctID,
Markets: dc.marketMap(),
Assets: assets,
BondExpiry: cfg.BondExpiry,
BondAssets: bondAssets,
ConnectionStatus: dc.status(),
CandleDurs: cfg.BinSizes,
Tier: tier,
BondsPending: false,
// TODO: Bonds
// Legacy reg fee (V0PURGE)
Fee: dcrAsset,
RegFees: feeAssets,
PendingFee: dc.getPendingFee(),
}
}
// assetFamily prepares a map of asset IDs for asset that share a parent asset
// with the specified assetID. The assetID and the parent asset's ID both have
// entries, as well as any tokens.
func assetFamily(assetID uint32) map[uint32]bool {
assetFamily := make(map[uint32]bool, 1)
var parentAsset *asset.RegisteredAsset
if parentAsset = asset.Asset(assetID); parentAsset == nil {
if tkn := asset.TokenInfo(assetID); tkn != nil {
parentAsset = asset.Asset(tkn.ParentID)
}
}
if parentAsset != nil {
assetFamily[parentAsset.ID] = true
for tokenID := range parentAsset.Tokens {
assetFamily[tokenID] = true
}
}
return assetFamily
}
// hasActiveAssetOrders checks whether there are any active orders or negotiating
// matches for the specified asset.
func (dc *dexConnection) hasActiveAssetOrders(assetID uint32) bool {
familial := assetFamily(assetID)
dc.tradeMtx.RLock()
defer dc.tradeMtx.RUnlock()
for _, inFlight := range dc.inFlightOrders {
if familial[inFlight.BaseID] || familial[inFlight.QuoteID] {
return true
}
}
for _, trade := range dc.trades {
if (familial[trade.Base()] || familial[trade.Quote()]) &&
trade.isActive() {
return true
}
}
return false
}
// hasActiveOrders checks whether there are any active orders for the dexConnection.
func (dc *dexConnection) hasActiveOrders() bool {
dc.tradeMtx.RLock()
defer dc.tradeMtx.RUnlock()
if len(dc.inFlightOrders) > 0 {
return true
}
for _, trade := range dc.trades {
if trade.isActive() {
return true
}
}
return false
}
// findOrder returns the tracker and preimage for an order ID, and a boolean
// indicating whether this is a cancel order.
func (dc *dexConnection) findOrder(oid order.OrderID) (tracker *trackedTrade, preImg order.Preimage, isCancel bool) {
dc.tradeMtx.RLock()
defer dc.tradeMtx.RUnlock()
// Try to find the order as a trade.
if tracker, found := dc.trades[oid]; found {
return tracker, tracker.preImg, false
}
// Search the cancel order IDs.
for _, tracker := range dc.trades {
if tracker.cancel != nil && tracker.cancel.ID() == oid {
return tracker, tracker.cancel.preImg, true
}
}
return
}
// tryCancel will look for an order with the specified order ID, and attempt to
// cancel the order. It is not an error if the order is not found.
func (c *Core) tryCancel(dc *dexConnection, oid order.OrderID) (found bool, err error) {
tracker, _, _ := dc.findOrder(oid)
if tracker == nil {
return // false, nil
}
return true, c.tryCancelTrade(dc, tracker)
}
// tryCancelTrade attempts to cancel the order.
func (c *Core) tryCancelTrade(dc *dexConnection, tracker *trackedTrade) error {
oid := tracker.ID()
if lo, ok := tracker.Order.(*order.LimitOrder); !ok || lo.Force != order.StandingTiF {
return fmt.Errorf("cannot cancel %s order %s that is not a standing limit order", tracker.Type(), oid)
}
mktConf := dc.marketConfig(tracker.mktID)
if mktConf == nil {
return newError(marketErr, "unknown market %q", tracker.mktID)
}
tracker.mtx.Lock()
defer tracker.mtx.Unlock()
if status := tracker.metaData.Status; status != order.OrderStatusEpoch && status != order.OrderStatusBooked {
return fmt.Errorf("order %v not cancellable in status %v", oid, status)
}
if tracker.cancel != nil {
// Existing cancel might be stale. Deleting it now allows this
// cancel attempt to proceed.
tracker.deleteStaleCancelOrder()
if tracker.cancel != nil {
return fmt.Errorf("order %s - only one cancel order can be submitted per order per epoch. "+
"still waiting on cancel order %s to match", oid, tracker.cancel.ID())
}
}
// Construct the order.
prefix := tracker.Prefix()
preImg := newPreimage()
co := &order.CancelOrder{
P: order.Prefix{
AccountID: prefix.AccountID,
BaseAsset: prefix.BaseAsset,
QuoteAsset: prefix.QuoteAsset,
OrderType: order.CancelOrderType,
ClientTime: time.Now(),
Commit: preImg.Commit(),
},
TargetOrderID: oid,
}
err := order.ValidateOrder(co, order.OrderStatusEpoch, 0)
if err != nil {
return err
}
commitSig := make(chan struct{})
defer close(commitSig) // signals on both success and failure, unlike syncOrderPlaced/piSyncers
c.sentCommitsMtx.Lock()
c.sentCommits[co.Commit] = commitSig
c.sentCommitsMtx.Unlock()
// Create and send the order message. Check the response before using it.
route, msgOrder, _ := messageOrder(co, nil)
var result = new(msgjson.OrderResult)
err = dc.signAndRequest(msgOrder, route, result, DefaultResponseTimeout)
if err != nil {
// At this point there is a possibility that the server got the request
// and created the cancel order, but we lost the connection before
// receiving the response with the cancel's order ID. Any preimage
// request will be unrecognized. This order is ABANDONED.
return fmt.Errorf("failed to submit cancel order targeting trade %v: %w", oid, err)
}
err = validateOrderResponse(dc, result, co, msgOrder)
if err != nil {
return fmt.Errorf("Abandoning order. preimage: %x, server time: %d: %w",
preImg[:], result.ServerTime, err)
}
// Store the cancel order with the tracker.
err = tracker.cancelTrade(co, preImg, mktConf.EpochLen)
if err != nil {
return fmt.Errorf("error storing cancel order info %s: %w", co.ID(), err)
}
// Now that the trackedTrade is updated, sync with the preimage request.
c.syncOrderPlaced(co.ID())
// Store the cancel order.
err = c.db.UpdateOrder(&db.MetaOrder{
MetaData: &db.OrderMetaData{
Status: order.OrderStatusEpoch,
Host: dc.acct.host,
Proof: db.OrderProof{
DEXSig: result.Sig,
Preimage: preImg[:],
},
EpochDur: mktConf.EpochLen, // epochIndex := result.ServerTime / mktConf.EpochLen
LinkedOrder: oid,
},
Order: co,
})
if err != nil {
return fmt.Errorf("failed to store order in database: %w", err)
}
c.log.Infof("Cancel order %s targeting order %s at %s has been placed",
co.ID(), oid, dc.acct.host)
subject, details := c.formatDetails(TopicCancellingOrder, tracker.token())
c.notify(newOrderNote(TopicCancellingOrder, subject, details, db.Poke, tracker.coreOrderInternal()))
return nil
}
// Synchronize with the preimage request, in case that request came before
// we had an order ID and added this order to the trades map or cancel field.
func (c *Core) syncOrderPlaced(oid order.OrderID) {
c.piSyncMtx.Lock()
syncChan, found := c.piSyncers[oid]
if found {
// If we found the channel, the preimage request is already waiting.
// Close the channel to allow that request to proceed.
close(syncChan)
delete(c.piSyncers, oid)
} else {
// If there is no channel, the preimage request hasn't come yet. Add a
// channel to signal readiness. Could insert nil unless syncOrderPlaced
// is erroneously called twice for the same order ID.
c.piSyncers[oid] = make(chan struct{})
}
c.piSyncMtx.Unlock()
}
// signAndRequest signs and sends the request, unmarshaling the response into
// the provided interface.
func (dc *dexConnection) signAndRequest(signable msgjson.Signable, route string, result interface{}, timeout time.Duration) error {
if dc.acct.locked() {
return fmt.Errorf("cannot sign: %s account locked", dc.acct.host)
}
sign(dc.acct.privKey, signable)
return sendRequest(dc.WsConn, route, signable, result, timeout)
}
// ack sends an Acknowledgement for a match-related request.
func (dc *dexConnection) ack(msgID uint64, matchID order.MatchID, signable msgjson.Signable) (err error) {
ack := &msgjson.Acknowledgement{
MatchID: matchID[:],
}
sigMsg := signable.Serialize()
ack.Sig, err = dc.acct.sign(sigMsg)
if err != nil {
return fmt.Errorf("sign error - %w", err)
}
msg, err := msgjson.NewResponse(msgID, ack, nil)
if err != nil {
return fmt.Errorf("NewResponse error - %w", err)
}
err = dc.Send(msg)
if err != nil {
return fmt.Errorf("Send error - %w", err)
}
return nil
}
// serverMatches are an intermediate structure used by the dexConnection to
// sort incoming match notifications.
type serverMatches struct {
tracker *trackedTrade
msgMatches []*msgjson.Match
cancel *msgjson.Match
}
// parseMatches sorts the list of matches and associates them with a trade. This
// may be called from handleMatchRoute on receipt of a new 'match' request, or
// by authDEX with the list of active matches returned by the 'connect' request.
func (dc *dexConnection) parseMatches(msgMatches []*msgjson.Match, checkSigs bool) (map[order.OrderID]*serverMatches, []msgjson.Acknowledgement, error) {
var acks []msgjson.Acknowledgement
matches := make(map[order.OrderID]*serverMatches)
var errs []string
for _, msgMatch := range msgMatches {
var oid order.OrderID
copy(oid[:], msgMatch.OrderID)
tracker, _, isCancel := dc.findOrder(oid)
if tracker == nil {
errs = append(errs, "order "+oid.String()+" not found")
continue
}
// Check the fee rate against the maxfeerate recorded at order time.
swapRate := msgMatch.FeeRateQuote
if tracker.Trade().Sell {
swapRate = msgMatch.FeeRateBase
}
if !isCancel && swapRate > tracker.metaData.MaxFeeRate {
errs = append(errs, fmt.Sprintf("rejecting match %s for order %s because assigned rate (%d) is > MaxFeeRate (%d)",
msgMatch.MatchID, msgMatch.OrderID, swapRate, tracker.metaData.MaxFeeRate))
continue
}
sigMsg := msgMatch.Serialize()
if checkSigs {
err := dc.acct.checkSig(sigMsg, msgMatch.Sig)
if err != nil {
// If the caller (e.g. handleMatchRoute) requests signature
// verification, this is fatal.
return nil, nil, fmt.Errorf("parseMatches: match signature verification failed: %w", err)
}
}
sig, err := dc.acct.sign(sigMsg)
if err != nil {
errs = append(errs, err.Error())
continue
}
// Success. Add the serverMatch and the Acknowledgement.
acks = append(acks, msgjson.Acknowledgement{
MatchID: msgMatch.MatchID,
Sig: sig,
})
trackerID := tracker.ID()
match := matches[trackerID]
if match == nil {
match = &serverMatches{
tracker: tracker,
}
matches[trackerID] = match
}
if isCancel {
match.cancel = msgMatch // taker match
} else {
match.msgMatches = append(match.msgMatches, msgMatch)
}
status := order.MatchStatus(msgMatch.Status)
dc.log.Debugf("Registering match %v for order %v (%v) in status %v",
msgMatch.MatchID, oid, order.MatchSide(msgMatch.Side), status)
}
var err error
if len(errs) > 0 {
err = fmt.Errorf("parseMatches errors: %s", strings.Join(errs, ", "))
}
// A non-nil error only means that at least one match failed to parse, so we
// must return the successful matches and acks for further processing.
return matches, acks, err
}
// matchDiscreps specifies a trackedTrades's missing and extra matches compared
// to the server's list of active matches as returned in the connect response.
type matchDiscreps struct {
trade *trackedTrade
missing []*matchTracker
extra []*msgjson.Match
}
// matchStatusConflict is a conflict between our status, and the status returned
// by the server in the connect response.
type matchStatusConflict struct {
trade *trackedTrade
matches []*matchTracker
}
// compareServerMatches resolves the matches reported by the server in the
// 'connect' response against those marked incomplete in the matchTracker map
// for each serverMatch.
// Reported matches with missing trackers are already checked by parseMatches,
// but we also must check for incomplete matches that the server is not
// reporting.
func (dc *dexConnection) compareServerMatches(srvMatches map[order.OrderID]*serverMatches) (
exceptions map[order.OrderID]*matchDiscreps, statusConflicts map[order.OrderID]*matchStatusConflict) {
exceptions = make(map[order.OrderID]*matchDiscreps)
statusConflicts = make(map[order.OrderID]*matchStatusConflict)
// Identify extra matches named by the server response that we do not
// recognize.
for oid, match := range srvMatches {
var extra []*msgjson.Match
match.tracker.mtx.RLock()
for _, msgMatch := range match.msgMatches {
var matchID order.MatchID
copy(matchID[:], msgMatch.MatchID)
mt := match.tracker.matches[matchID]
if mt == nil {
extra = append(extra, msgMatch)
continue
}
mt.exceptionMtx.Lock()
mt.checkServerRevoke = false
mt.exceptionMtx.Unlock()
if mt.Status != order.MatchStatus(msgMatch.Status) {
conflict := statusConflicts[oid]
if conflict == nil {
conflict = &matchStatusConflict{trade: match.tracker}
statusConflicts[oid] = conflict
}
conflict.matches = append(conflict.matches, mt)
}
}
match.tracker.mtx.RUnlock()
if len(extra) > 0 {
exceptions[match.tracker.ID()] = &matchDiscreps{
trade: match.tracker,
extra: extra,
}
}
}
in := func(matches []*msgjson.Match, mid []byte) bool {
for _, m := range matches {
if bytes.Equal(m.MatchID, mid) {
return true
}
}
return false
}
setMissing := func(trade *trackedTrade, missing []*matchTracker) {
if tt, found := exceptions[trade.ID()]; found {
tt.missing = missing
} else {
exceptions[trade.ID()] = &matchDiscreps{
trade: trade,
missing: missing,
}
}
}
// Identify active matches that are missing from server's response.
dc.tradeMtx.RLock()
defer dc.tradeMtx.RUnlock()
for oid, trade := range dc.trades {
var activeMatches []*matchTracker
for _, m := range trade.activeMatches() {
// Server is not expected to report matches that have been fully
// redeemed or are revoked. Only client cares about redeem confs.
if m.Status >= order.MatchComplete || m.MetaData.Proof.IsRevoked() {
continue
}
activeMatches = append(activeMatches, m)
}
if len(activeMatches) == 0 {
continue
}
tradeMatches, found := srvMatches[oid]
if !found {
// ALL of this trade's active matches are missing.
setMissing(trade, activeMatches)
continue // check next local trade
}
// Check this local trade's active matches against server's reported
// matches for this trade.
var missing []*matchTracker
for _, match := range activeMatches { // each local match
if !in(tradeMatches.msgMatches, match.MatchID[:]) { // against reported matches
missing = append(missing, match)
}
}
if len(missing) > 0 {
setMissing(trade, missing)
}
}
return
}
// updateOrderStatus updates the order's status, cleaning up any associated
// cancel orders, unlocking funding coins and refund/redemption reserves, and
// updating the order in the DB. The trackedTrade's mutex must be write locked.
func (dc *dexConnection) updateOrderStatus(trade *trackedTrade, newStatus order.OrderStatus) {
oid := trade.ID()
previousStatus := trade.metaData.Status
if previousStatus == newStatus { // may be expected if no srvOrderStatuses provided
return
}
trade.metaData.Status = newStatus
// If there is an associated cancel order, and we are revising the
// status of the targeted order to anything other than canceled, we can
// infer the cancel order is done. Update the status of the cancel order
// and unlink it from the trade. If the targeted order is reported as
// canceled, that indicates we submitted a cancel order preimage but
// missed the match notification, so the cancel order is executed.
if newStatus != order.OrderStatusCanceled {
trade.deleteCancelOrder()
} else if trade.cancel != nil {
cid := trade.cancel.ID()
err := trade.db.UpdateOrderStatus(cid, order.OrderStatusExecuted)
if err != nil {
dc.log.Errorf("Failed to update status of executed cancel order %v: %v", cid, err)
}
}
// If we're updating an order from an active state to executed,
// canceled, or revoked, and there are no active matches, return the
// locked funding coins and any refund/redeem reserves.
trade.maybeReturnCoins()
if newStatus >= order.OrderStatusExecuted && trade.Trade().Remaining() > 0 &&
(!trade.isMarketBuy() || len(trade.matches) == 0) {
if trade.isMarketBuy() {
trade.unlockRedemptionFraction(1, 1)
trade.unlockRefundFraction(1, 1)
} else {
trade.unlockRedemptionFraction(trade.Trade().Remaining(), trade.Trade().Quantity)
trade.unlockRefundFraction(trade.Trade().Remaining(), trade.Trade().Quantity)
}
}
// Now update the trade.
if err := trade.db.UpdateOrder(trade.metaOrder()); err != nil {
dc.log.Errorf("Error updating status in db for order %v from %v to %v", oid, previousStatus, newStatus)
} else {
dc.log.Warnf("Order %v updated from recorded status %q to new status %q reported by DEX %s",
oid, previousStatus, newStatus, dc.acct.host)
}
subject, details := trade.formatDetails(TopicOrderStatusUpdate, trade.token(), previousStatus, newStatus)
dc.notify(newOrderNote(TopicOrderStatusUpdate, subject, details, db.WarningLevel, trade.coreOrderInternal()))
}
// syncOrderStatuses requests and updates the status for each of the trades.
func (dc *dexConnection) syncOrderStatuses(orders []*trackedTrade) (reconciledOrdersCount int) {
orderStatusRequests := make([]*msgjson.OrderStatusRequest, len(orders))
tradeMap := make(map[order.OrderID]*trackedTrade, len(orders))
for i, trade := range orders {
oid := trade.ID()
tradeMap[oid] = trade
orderStatusRequests[i] = &msgjson.OrderStatusRequest{
Base: trade.Base(),
Quote: trade.Quote(),
OrderID: oid.Bytes(),
}
}
dc.log.Debugf("Requesting statuses for %d orders from DEX %s", len(orderStatusRequests), dc.acct.host)
// Send the 'order_status' request.
var orderStatusResults []*msgjson.OrderStatus
err := sendRequest(dc.WsConn, msgjson.OrderStatusRoute, orderStatusRequests,
&orderStatusResults, DefaultResponseTimeout)
if err != nil {
dc.log.Errorf("Error retrieving order statuses from DEX %s: %v", dc.acct.host, err)
return
}
if len(orderStatusResults) != len(orderStatusRequests) {
dc.log.Errorf("Retrieved statuses for %d out of %d orders from order_status route",
len(orderStatusResults), len(orderStatusRequests))
}
// Update the orders with the statuses received.
for _, srvOrderStatus := range orderStatusResults {
var oid order.OrderID
copy(oid[:], srvOrderStatus.ID)
trade := tradeMap[oid] // no need to lock dc.tradeMtx
if trade == nil {
dc.log.Warnf("Server reported status for order %v that we did not request.", oid)
continue
}
reconciledOrdersCount++