-
Notifications
You must be signed in to change notification settings - Fork 84
/
market.go
2668 lines (2386 loc) · 86.7 KB
/
market.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 market
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"sync"
"sync/atomic"
"time"
"decred.org/dcrdex/dex"
"decred.org/dcrdex/dex/calc"
"decred.org/dcrdex/dex/encode"
"decred.org/dcrdex/dex/msgjson"
"decred.org/dcrdex/dex/order"
"decred.org/dcrdex/dex/ws"
"decred.org/dcrdex/server/account"
"decred.org/dcrdex/server/asset"
"decred.org/dcrdex/server/auth"
"decred.org/dcrdex/server/book"
"decred.org/dcrdex/server/coinlock"
"decred.org/dcrdex/server/comms"
"decred.org/dcrdex/server/db"
"decred.org/dcrdex/server/matcher"
)
// Error is just a basic error.
type Error string
// Error satisfies the error interface.
func (e Error) Error() string {
return string(e)
}
const (
ErrMarketNotRunning = Error("market not running")
ErrInvalidOrder = Error("order failed validation")
ErrInvalidCommitment = Error("order commitment invalid")
ErrEpochMissed = Error("order unexpectedly missed its intended epoch")
ErrDuplicateOrder = Error("order already in epoch") // maybe remove since this is ill defined
ErrQuantityTooHigh = Error("order quantity exceeds user limit")
ErrDuplicateCancelOrder = Error("equivalent cancel order already in epoch")
ErrTooManyCancelOrders = Error("too many cancel orders in current epoch")
ErrCancelNotPermitted = Error("cancel order account does not match targeted order account")
ErrTargetNotActive = Error("target order not active on this market")
ErrTargetNotCancelable = Error("targeted order is not a limit order with standing time-in-force")
ErrSuspendedAccount = Error("suspended account")
ErrMalformedOrderResponse = Error("malformed order response")
ErrInternalServer = Error("internal server error")
)
// Swapper coordinates atomic swaps for one or more matchsets.
type Swapper interface {
Negotiate(matchSets []*order.MatchSet)
CheckUnspent(ctx context.Context, asset uint32, coinID []byte) error
UserSwappingAmt(user account.AccountID, base, quote uint32) (amt, count uint64)
ChainsSynced(base, quote uint32) (bool, error)
}
type DataCollector interface {
ReportEpoch(base, quote uint32, epochIdx uint64, stats *matcher.MatchCycleStats) (*msgjson.Spot, error)
}
// FeeFetcher is a fee fetcher for fetching fees. Fees are fickle, so fetch fees
// with FeeFetcher fairly frequently.
type FeeFetcher interface {
FeeRate(context.Context) uint64
LastRate() uint64
MaxFeeRate() uint64
}
type Balancer interface {
CheckBalance(acctAddr string, assetID uint32, qty, lots uint64, redeems int) bool
}
// Config is the Market configuration.
type Config struct {
MarketInfo *dex.MarketInfo
Storage Storage
Swapper Swapper
AuthManager AuthManager
FeeFetcherBase FeeFetcher
CoinLockerBase coinlock.CoinLocker
FeeFetcherQuote FeeFetcher
CoinLockerQuote coinlock.CoinLocker
DataCollector DataCollector
Balancer Balancer
}
// Market is the market manager. It should not be overly involved with details
// of accounts and authentication. Via the account package it should request
// account status with new orders, verification of order signatures. The Market
// should also perform various account package callbacks such as order status
// updates so that the account package code can keep various data up-to-date,
// including order status, history, cancellation statistics, etc.
//
// The Market performs the following:
// - Receiving and validating new order data (amounts vs. lot size, check fees,
// utxos, sufficient market buy buffer, etc.).
// - Putting incoming orders into the current epoch queue.
// - Maintain an order book, which must also implement matcher.Booker.
// - Initiate order matching via matcher.Match(book, currentQueue)
// - During and/or after matching:
// * update the book (remove orders, add new standing orders, etc.)
// * retire/archive the epoch queue
// * publish the matches (and order book changes?)
// * initiate swaps for each match (possibly groups of related matches)
// - Cycle the epochs.
// - Recording all events with the archivist
type Market struct {
marketInfo *dex.MarketInfo
tasks sync.WaitGroup // for lazy asynchronous tasks e.g. revoke ntfns
// Communications.
orderRouter chan *orderUpdateSignal // incoming orders, via SubmitOrderAsync
orderFeedMtx sync.RWMutex // guards orderFeeds and running
orderFeeds []chan *updateSignal // all outgoing notification consumers
runMtx sync.RWMutex
running chan struct{} // closed when running (accepting new orders)
up uint32 // Run is called, either waiting for first epoch or running
bookMtx sync.Mutex // guards book and bookEpochIdx
book *book.Book
bookEpochIdx int64 // next epoch from the point of view of the book
settling map[order.OrderID]uint64
epochMtx sync.RWMutex
startEpochIdx int64
activeEpochIdx int64
suspendEpochIdx int64
persistBook bool
epochCommitments map[order.Commitment]order.OrderID
epochOrders map[order.OrderID]order.Order
matcher *matcher.Matcher
swapper Swapper
auth AuthManager
feeScalesMtx sync.RWMutex
feeScales struct {
base float64
quote float64
}
coinLockerBase coinlock.CoinLocker
coinLockerQuote coinlock.CoinLocker
baseFeeFetcher FeeFetcher
quoteFeeFetcher FeeFetcher
// Persistent data storage
storage Storage
// Data API
dataCollector DataCollector
}
// Storage is the DB interface required by Market.
type Storage interface {
db.OrderArchiver
LastErr() error
Fatal() <-chan struct{}
Close() error
InsertEpoch(ed *db.EpochResults) error
MarketMatches(base, quote uint32) ([]*db.MatchDataWithCoins, error)
InsertMatch(match *order.Match) error
}
// NewMarket creates a new Market for the provided base and quote assets, with
// an epoch cycling at given duration in milliseconds.
func NewMarket(cfg *Config) (*Market, error) {
// Make sure the DEXArchivist is healthy before taking orders.
storage, mktInfo, swapper := cfg.Storage, cfg.MarketInfo, cfg.Swapper
if err := storage.LastErr(); err != nil {
return nil, err
}
log.Infof("Allowing %d lots on the book per user.", mktInfo.BookedLotLimit)
// Load existing book orders from the DB.
base, quote := mktInfo.Base, mktInfo.Quote
bookOrders, err := storage.BookOrders(base, quote)
if err != nil {
return nil, err
}
log.Infof("Loaded %d stored book orders.", len(bookOrders))
baseIsAcctBased := cfg.CoinLockerBase == nil
quoteIsAcctBased := cfg.CoinLockerQuote == nil
// Put the book orders in a map so orders that no longer have funding coins
// can be removed easily.
bookOrdersByID := make(map[order.OrderID]*order.LimitOrder, len(bookOrders))
for _, lo := range bookOrders {
// Limit order amount requirements are simple unlike market buys.
if lo.Quantity%mktInfo.LotSize != 0 || lo.FillAmt%mktInfo.LotSize != 0 {
// To change market configuration, the operator should suspended the
// market with persist=false, but that may not have happened, or
// maybe a revoke failed.
log.Errorf("Not rebooking order %v with amount (%v/%v) incompatible with current lot size (%v)",
lo.ID(), lo.FillAmt, lo.Quantity, mktInfo.LotSize)
// Revoke the order, but do not count this against the user.
if _, _, err = storage.RevokeOrderUncounted(lo); err != nil {
log.Errorf("Failed to revoke order %v: %v", lo, err)
// But still not added back on the book.
}
continue
}
bookOrdersByID[lo.ID()] = lo
}
// "execute" any epoch orders in DB that may be left over from unclean
// shutdown. Whatever epoch they were in will not be seen again.
epochOrders, err := storage.EpochOrders(base, quote)
if err != nil {
return nil, err
}
for _, ord := range epochOrders {
oid := ord.ID()
log.Infof("Dropping old epoch order %v", oid)
if co, ok := ord.(*order.CancelOrder); ok {
if err := storage.FailCancelOrder(co); err != nil {
log.Errorf("Failed to set orphaned epoch cancel order %v as executed: %v", oid, err)
}
continue
}
if err := storage.ExecuteOrder(ord); err != nil {
log.Errorf("Failed to set orphaned epoch trade order %v as executed: %v", oid, err)
}
}
// Set up tracking. Which of these are actually used depend on whether the
// assets are account- or utxo-based.
// utxo-based
var baseCoins, quoteCoins map[order.OrderID][]order.CoinID
var missingCoinFails map[order.OrderID]struct{}
// account-based
var quoteAcctStats, baseAcctStats accountCounter
var failedBaseAccts, failedQuoteAccts map[string]bool
var failedAcctOrders map[order.OrderID]struct{}
var acctTracking book.AccountTracking
if baseIsAcctBased {
acctTracking |= book.AccountTrackingBase
baseAcctStats = make(accountCounter)
failedBaseAccts = make(map[string]bool)
failedAcctOrders = make(map[order.OrderID]struct{})
} else {
baseCoins = make(map[order.OrderID][]order.CoinID)
missingCoinFails = make(map[order.OrderID]struct{})
}
if quoteIsAcctBased {
acctTracking |= book.AccountTrackingQuote
quoteAcctStats = make(accountCounter)
failedQuoteAccts = make(map[string]bool)
if failedAcctOrders == nil {
failedAcctOrders = make(map[order.OrderID]struct{})
}
} else {
quoteCoins = make(map[order.OrderID][]order.CoinID)
if missingCoinFails == nil {
missingCoinFails = make(map[order.OrderID]struct{})
}
}
ordersLoop:
for id, lo := range bookOrdersByID {
if lo.FillAmt > 0 {
// Order already matched with another trade, so it is expected that
// the funding coins are spent in a swap.
//
// In general, our position is that the server is not ultimately
// responsible for verifying that all orders have locked coins since
// the client will be penalized if they cannot complete the swap.
// The least the server can do is ensure funding coins for NEW
// orders are unspent and owned by the user.
// On to the next order. Do not lock coins that are spent or should
// be spent in a swap contract.
continue
}
// Verify all funding coins for this order.
assetID := quote
if lo.Sell {
assetID = base
}
for i := range lo.Coins {
err = swapper.CheckUnspent(context.Background(), assetID, lo.Coins[i]) // no timeout
if err == nil {
continue
}
if errors.Is(err, asset.CoinNotFoundError) {
// spent, exclude this order
coin, _ := asset.DecodeCoinID(dex.BipIDSymbol(assetID), lo.Coins[i]) // coin decoding succeeded in CheckUnspent
log.Warnf("Coin %s not unspent for unfilled order %v. "+
"Revoking the order.", coin, lo)
} else {
// other failure (coinID decode, RPC, etc.)
return nil, fmt.Errorf("unexpected error checking coinID %v for order %v: %w",
lo.Coins[i], lo, err)
// NOTE: This does not revoke orders from storage since this is
// likely to be a configuration or node issue.
}
delete(bookOrdersByID, id)
// Revoke the order, but do not count this against the user.
if _, _, err = storage.RevokeOrderUncounted(lo); err != nil {
log.Errorf("Failed to revoke order %v: %v", lo, err)
}
// No penalization here presently since the market was down, but if
// a suspend message with persist=true was sent, the users should
// have kept their coins locked. (TODO)
continue ordersLoop
}
if baseIsAcctBased {
var addr string
var qty, lots uint64
var redeems int
if lo.Sell {
// address is zeroth coin
if len(lo.Coins) != 1 {
log.Errorf("rejecting account-based-base-asset order %s that has no coins ¯\\_(ツ)_/¯", lo.ID())
continue ordersLoop
}
addr = string(lo.Coins[0])
qty = lo.Quantity
lots = qty / mktInfo.LotSize
} else {
addr = lo.Address
redeems = int((lo.Quantity - lo.FillAmt) / mktInfo.LotSize)
}
baseAcctStats.add(addr, qty, lots, redeems)
} else if lo.Sell {
baseCoins[id] = lo.Coins
}
if quoteIsAcctBased {
var addr string
var qty, lots uint64
var redeems int
if lo.Sell {
addr = lo.Address
redeems = int((lo.Quantity - lo.FillAmt) / mktInfo.LotSize)
} else {
// address is zeroth coin
if len(lo.Coins) != 1 {
log.Errorf("rejecting account-based-base-asset order %s that has no coins ¯\\_(ツ)_/¯", lo.ID())
continue ordersLoop
}
addr = string(lo.Coins[0])
qty = lo.Quantity
lots = qty / mktInfo.LotSize
}
quoteAcctStats.add(addr, qty, lots, redeems)
} else if !lo.Sell {
quoteCoins[id] = lo.Coins
}
}
if baseIsAcctBased {
log.Debugf("Checking %d base asset (%d) balances.", len(baseAcctStats), base)
for acctAddr, stats := range baseAcctStats {
if !cfg.Balancer.CheckBalance(acctAddr, mktInfo.Base, stats.qty, stats.lots, stats.redeems) {
log.Info("%s base asset account failed the startup balance check on the %s market", acctAddr, mktInfo.Name)
failedBaseAccts[acctAddr] = true
}
}
} else {
log.Debugf("Locking %d base asset (%d) coins.", len(baseCoins), base)
if log.Level() <= dex.LevelTrace {
for oid, coins := range baseCoins {
log.Tracef(" - order %v: %v", oid, coins)
}
}
for oid := range cfg.CoinLockerBase.LockCoins(baseCoins) {
missingCoinFails[oid] = struct{}{}
}
}
if quoteIsAcctBased {
log.Debugf("Checking %d quote asset (%d) balances.", len(quoteAcctStats), quote)
for acctAddr, stats := range quoteAcctStats { // quoteAcctStats is nil for utxo-based quote assets
if !cfg.Balancer.CheckBalance(acctAddr, mktInfo.Quote, stats.qty, stats.lots, stats.redeems) {
log.Errorf("%s quote asset account failed the startup balance check on the %s market", acctAddr, mktInfo.Name)
failedQuoteAccts[acctAddr] = true
}
}
} else {
log.Debugf("Locking %d quote asset (%d) coins.", len(quoteCoins), quote)
if log.Level() <= dex.LevelTrace {
for oid, coins := range quoteCoins {
log.Tracef(" - order %v: %v", oid, coins)
}
}
for oid := range cfg.CoinLockerQuote.LockCoins(quoteCoins) {
missingCoinFails[oid] = struct{}{}
}
}
for oid := range missingCoinFails {
log.Warnf("Revoking book order %v with already locked coins.", oid)
bad := bookOrdersByID[oid]
delete(bookOrdersByID, oid)
// Revoke the order, but do not count this against the user.
if _, _, err = storage.RevokeOrderUncounted(bad); err != nil {
log.Errorf("Failed to revoke order %v: %v", bad, err)
// But still not added back on the book.
}
}
Book := book.New(mktInfo.LotSize, acctTracking)
for _, lo := range bookOrdersByID {
// Catch account-based asset low-balance rejections here.
if baseIsAcctBased && failedBaseAccts[lo.BaseAccount()] {
failedAcctOrders[lo.ID()] = struct{}{}
log.Warnf("Skipping insert of order %s into %s book because base asset "+
"account failed the balance check", lo.ID(), mktInfo.Name)
continue
}
if quoteIsAcctBased && failedQuoteAccts[lo.QuoteAccount()] {
failedAcctOrders[lo.ID()] = struct{}{}
log.Warnf("Skipping insert of order %s into %s book because quote asset "+
"account failed the balance check", lo.ID(), mktInfo.Name)
continue
}
if ok := Book.Insert(lo); !ok {
// This can only happen if one of the loaded orders has an
// incompatible lot size for the current market config, which was
// already checked above.
log.Errorf("Failed to insert order %v into %v book.", mktInfo.Name, lo)
}
}
// Revoke the low-balance rejections in the database.
for oid := range failedAcctOrders {
// Already logged in the Book.Insert loop.
if _, _, err = storage.RevokeOrderUncounted(bookOrdersByID[oid]); err != nil {
log.Errorf("Failed to revoke order with insufficient account balance %v: %v", bookOrdersByID[oid], err)
}
}
// Populate the order settling amount map from the active matches in DB.
activeMatches, err := storage.MarketMatches(base, quote)
if err != nil {
return nil, fmt.Errorf("failed to load active matches for market %v: %w", mktInfo.Name, err)
}
settling := make(map[order.OrderID]uint64)
for _, match := range activeMatches {
settling[match.Taker] += match.Quantity
settling[match.Maker] += match.Quantity
// Note: we actually don't want to bother with matches for orders that
// were canceled or had at-fault match failures, since including them
// give that user another shot to get a successfully "completed" order
// if they complete these remaining matches, but it's OK. We'd have to
// query these order statuses, and look for at-fault match failures
// involving them, so just give the user the benefit of the doubt.
}
log.Infof("Tracking %d orders with %d active matches.", len(settling), len(activeMatches))
return &Market{
running: make(chan struct{}), // closed on market start
marketInfo: mktInfo,
book: Book,
settling: settling,
matcher: matcher.New(),
persistBook: true,
epochCommitments: make(map[order.Commitment]order.OrderID),
epochOrders: make(map[order.OrderID]order.Order),
swapper: swapper,
auth: cfg.AuthManager,
storage: storage,
coinLockerBase: cfg.CoinLockerBase,
coinLockerQuote: cfg.CoinLockerQuote,
baseFeeFetcher: cfg.FeeFetcherBase,
quoteFeeFetcher: cfg.FeeFetcherQuote,
dataCollector: cfg.DataCollector,
}, nil
}
// SuspendASAP suspends requests the market to gracefully suspend epoch cycling
// as soon as possible, always allowing an active epoch to close. See also
// Suspend.
func (m *Market) SuspendASAP(persistBook bool) (finalEpochIdx int64, finalEpochEnd time.Time) {
return m.Suspend(time.Now(), persistBook)
}
// Suspend requests the market to gracefully suspend epoch cycling as soon as
// the given time, always allowing the epoch including that time to complete. If
// the time is before the current epoch, the current epoch will be the last.
func (m *Market) Suspend(asSoonAs time.Time, persistBook bool) (finalEpochIdx int64, finalEpochEnd time.Time) {
// epochMtx guards activeEpochIdx, startEpochIdx, suspendEpochIdx, and
// persistBook.
m.epochMtx.Lock()
defer m.epochMtx.Unlock()
dur := int64(m.EpochDuration())
epochEnd := func(idx int64) time.Time {
start := encode.UnixTimeMilli(idx * dur)
return start.Add(time.Duration(dur) * time.Millisecond)
}
// Determine which epoch includes asSoonAs, and compute its end time. If
// asSoonAs is in a past epoch, suspend at the end of the active epoch.
soonestFinalIdx := m.activeEpochIdx
if soonestFinalIdx == 0 {
// Cannot schedule a suspend if Run isn't running.
if m.startEpochIdx == 0 {
return -1, time.Time{}
}
// Not yet started. Soonest suspend idx is the start epoch idx - 1.
soonestFinalIdx = m.startEpochIdx - 1
}
if soonestEnd := epochEnd(soonestFinalIdx); asSoonAs.Before(soonestEnd) {
// Suspend at the end of the active epoch or the one prior to start.
finalEpochIdx = soonestFinalIdx
finalEpochEnd = soonestEnd
} else {
// Suspend at the end of the epoch that includes the target time.
ms := encode.UnixMilli(asSoonAs)
finalEpochIdx = ms / dur
// Allow stopping at boundary, prior to the epoch starting at this time.
if ms%dur == 0 {
finalEpochIdx--
}
finalEpochEnd = epochEnd(finalEpochIdx)
}
m.suspendEpochIdx = finalEpochIdx
m.persistBook = persistBook
return
}
// ResumeEpoch gets the next available resume epoch index for the currently
// configured epoch duration for the market and the provided earliest allowable
// start time. The market must be running, otherwise the zero index is returned.
func (m *Market) ResumeEpoch(asSoonAs time.Time) (startEpochIdx int64) {
// Only allow scheduling a resume if the market is not running.
if m.Running() {
return
}
dur := int64(m.EpochDuration())
now := encode.UnixMilli(time.Now())
nextEpochIdx := 1 + now/dur
ms := encode.UnixMilli(asSoonAs)
startEpochIdx = 1 + ms/dur
if startEpochIdx < nextEpochIdx {
startEpochIdx = nextEpochIdx
}
return
}
// SetStartEpochIdx sets the starting epoch index. This should generally be
// called before Run, or Start used to specify the index at the same time.
func (m *Market) SetStartEpochIdx(startEpochIdx int64) {
m.epochMtx.Lock()
m.startEpochIdx = startEpochIdx
m.epochMtx.Unlock()
}
// Start begins order processing with a starting epoch index. See also
// SetStartEpochIdx and Run. Stop the Market by cancelling the context.
func (m *Market) Start(ctx context.Context, startEpochIdx int64) {
m.SetStartEpochIdx(startEpochIdx)
m.Run(ctx)
}
// waitForEpochOpen waits until the start of epoch processing.
func (m *Market) waitForEpochOpen() {
m.runMtx.RLock()
c := m.running // the field may be rewritten, but only after close
m.runMtx.RUnlock()
<-c
}
// Status describes the operation state of the Market.
type Status struct {
Running bool
EpochDuration uint64 // to compute times from epoch inds
ActiveEpoch int64
StartEpoch int64
SuspendEpoch int64
PersistBook bool
Base, Quote uint32
}
// Status returns the current operating state of the Market.
func (m *Market) Status() *Status {
m.epochMtx.Lock()
defer m.epochMtx.Unlock()
return &Status{
Running: m.Running(),
EpochDuration: m.marketInfo.EpochDuration,
ActiveEpoch: m.activeEpochIdx,
StartEpoch: m.startEpochIdx,
SuspendEpoch: m.suspendEpochIdx,
PersistBook: m.persistBook,
Base: m.marketInfo.Base,
Quote: m.marketInfo.Quote,
}
}
// Running indicates is the market is accepting new orders. This will return
// false when suspended, but false does not necessarily mean Run has stopped
// since a start epoch may be set. Note that this method is of limited use and
// communicating subsystems shouldn't rely on the result for correct operation
// since a market could start or stop. Rather, they should infer or be informed
// of market status rather than rely on this.
//
// TODO: Instead of using Running in OrderRouter and DEX, these types should
// track statuses (known suspend times).
func (m *Market) Running() bool {
m.runMtx.RLock()
defer m.runMtx.RUnlock()
select {
case <-m.running:
return true
default:
return false
}
}
// EpochDuration returns the Market's epoch duration in milliseconds.
func (m *Market) EpochDuration() uint64 {
return m.marketInfo.EpochDuration
}
// MarketBuyBuffer returns the Market's market-buy buffer.
func (m *Market) MarketBuyBuffer() float64 {
return m.marketInfo.MarketBuyBuffer
}
// LotSize returns the market's lot size in units of the base asset.
func (m *Market) LotSize() uint64 {
return m.marketInfo.LotSize
}
// RateStep returns the market's rate step in units of the quote asset.
func (m *Market) RateStep() uint64 {
return m.marketInfo.RateStep
}
// Base is the base asset ID.
func (m *Market) Base() uint32 {
return m.marketInfo.Base
}
// Quote is the quote asset ID.
func (m *Market) Quote() uint32 {
return m.marketInfo.Quote
}
// OrderFeed provides a new order book update channel. Channels provided before
// the market starts and while a market is running are both valid. When the
// market stops, channels are closed (invalidated), and new channels should be
// requested if the market starts again.
func (m *Market) OrderFeed() <-chan *updateSignal {
bookUpdates := make(chan *updateSignal, 1)
m.orderFeedMtx.Lock()
m.orderFeeds = append(m.orderFeeds, bookUpdates)
m.orderFeedMtx.Unlock()
return bookUpdates
}
// FeedDone informs the market that the caller is finished receiving from the
// given channel, which should have been obtained from OrderFeed. If the channel
// was a registered order feed channel from OrderFeed, it is closed and removed
// so that no further signals will be send on the channel.
func (m *Market) FeedDone(feed <-chan *updateSignal) bool {
m.orderFeedMtx.Lock()
defer m.orderFeedMtx.Unlock()
for i := range m.orderFeeds {
if m.orderFeeds[i] == feed {
close(m.orderFeeds[i])
// Order is not important to delete the channel without allocation.
m.orderFeeds[i] = m.orderFeeds[len(m.orderFeeds)-1]
m.orderFeeds[len(m.orderFeeds)-1] = nil // chan is a pointer
m.orderFeeds = m.orderFeeds[:len(m.orderFeeds)-1]
return true
}
}
return false
}
// sendToFeeds sends an *updateSignal to all order feed channels created with
// OrderFeed().
func (m *Market) sendToFeeds(sig *updateSignal) {
m.orderFeedMtx.RLock()
for _, s := range m.orderFeeds {
s <- sig
}
m.orderFeedMtx.RUnlock()
}
type orderUpdateSignal struct {
rec *orderRecord
errChan chan error // should be buffered
}
func newOrderUpdateSignal(ord *orderRecord) *orderUpdateSignal {
return &orderUpdateSignal{ord, make(chan error, 1)}
}
// SubmitOrder submits a new order for inclusion into the current epoch. This is
// the synchronous version of SubmitOrderAsync.
func (m *Market) SubmitOrder(rec *orderRecord) error {
return <-m.SubmitOrderAsync(rec)
}
// processCancelOrderWhileSuspended is called when cancelling an order while
// the market is suspended and Run is not running. The error sent on errChan
// is returned to the client.
//
// This function:
// 1. Removes the target order from the book.
// 2. Unlocks the order coins.
// 3. Updates the storage with the new cancel order and cancels the existing limit order.
// 4. Responds to the client that the order was received.
// 5. Sends the unbooked order to the order feeds.
// 6. Creates a match object, stores it, and notifies the client of the match.
func (m *Market) processCancelOrderWhileSuspended(rec *orderRecord, errChan chan<- error) {
co, ok := rec.order.(*order.CancelOrder)
if !ok {
errChan <- ErrInvalidOrder
return
}
if cancelable, err := m.CancelableBy(co.TargetOrderID, co.AccountID); !cancelable {
errChan <- err
return
}
m.bookMtx.Lock()
delete(m.settling, co.TargetOrderID)
lo, ok := m.book.Remove(co.TargetOrderID)
m.bookMtx.Unlock()
if !ok {
errChan <- ErrTargetNotCancelable
return
}
m.unlockOrderCoins(lo)
sTime := time.Now().Truncate(time.Millisecond).UTC()
co.SetTime(sTime)
// Create the client response here, but don't send it until the order has been
// committed to the storage.
respMsg, err := m.orderResponse(rec)
if err != nil {
errChan <- fmt.Errorf("failed to create order response: %w", err)
return
}
dur := int64(m.EpochDuration())
now := encode.UnixMilli(time.Now())
epochIdx := now / dur
if err := m.storage.NewArchivedCancel(co, epochIdx, dur); err != nil {
errChan <- err
return
}
if err := m.storage.CancelOrder(lo); err != nil {
errChan <- err
return
}
err = m.auth.Send(rec.order.User(), respMsg)
if err != nil {
log.Errorf("Failed to send cancel order response: %v", err)
}
sig := &updateSignal{
action: unbookAction,
data: sigDataUnbookedOrder{
order: lo,
epochIdx: 0,
},
}
m.sendToFeeds(sig)
match := order.Match{
Taker: co,
Maker: lo,
Quantity: lo.Remaining(),
Rate: lo.Rate,
Epoch: order.EpochID{
Idx: uint64(epochIdx),
Dur: m.EpochDuration(),
},
FeeRateBase: m.getFeeRate(m.Base(), m.baseFeeFetcher),
FeeRateQuote: m.getFeeRate(m.Quote(), m.quoteFeeFetcher),
}
// insertMatchErr is sent on errChan at the end of the function. We
// want to send the match request to the client even if this insertion
// fails.
insertMatchErr := m.storage.InsertMatch(&match)
makerMsg, takerMsg := matchNotifications(&match)
m.auth.Sign(makerMsg)
m.auth.Sign(takerMsg)
msgs := []msgjson.Signable{makerMsg, takerMsg}
req, err := msgjson.NewRequest(comms.NextID(), msgjson.MatchRoute, msgs)
if err != nil {
log.Errorf("Failed to create match request: %v", err)
} else {
err = m.auth.Request(rec.order.User(), req, func(_ comms.Link, resp *msgjson.Message) {
m.processMatchAcksForCancel(rec.order.User(), resp)
})
if err != nil {
log.Errorf("Failed to send match request: %v", err)
}
}
errChan <- insertMatchErr
}
// matchNotifications creates a pair of msgjson.Match from a match.
func matchNotifications(match *order.Match) (makerMsg *msgjson.Match, takerMsg *msgjson.Match) {
stamp := encode.UnixMilliU(time.Now())
return &msgjson.Match{
OrderID: idToBytes(match.Maker.ID()),
MatchID: idToBytes(match.ID()),
Quantity: match.Quantity,
Rate: match.Rate,
Address: order.ExtractAddress(match.Taker),
ServerTime: stamp,
FeeRateBase: match.FeeRateBase,
FeeRateQuote: match.FeeRateQuote,
Side: uint8(order.Maker),
}, &msgjson.Match{
OrderID: idToBytes(match.Taker.ID()),
MatchID: idToBytes(match.ID()),
Quantity: match.Quantity,
Rate: match.Rate,
Address: order.ExtractAddress(match.Maker),
ServerTime: stamp,
FeeRateBase: match.FeeRateBase,
FeeRateQuote: match.FeeRateQuote,
Side: uint8(order.Taker),
}
}
// processMatchAcksForCancel is called when receiving a response to a match
// request for a cancel order. Nothing is done other than logging and verifying
// that the response is in the correct format.
//
// This is currently only used for cancel orders that happen while the market is
// suspended, but may be later used for all cancel orders.
func (m *Market) processMatchAcksForCancel(user account.AccountID, msg *msgjson.Message) {
var acks []msgjson.Acknowledgement
err := msg.UnmarshalResult(&acks)
if err != nil {
m.respondError(msg.ID, user, msgjson.RPCParseError,
"error parsing match request acknowledgment")
return
}
// The acknowledgment for both the taker and maker should come from the same user
expectedNumAcks := 2
if len(acks) != expectedNumAcks {
m.respondError(msg.ID, user, msgjson.AckCountError,
fmt.Sprintf("expected %d acknowledgements, got %d", len(acks), expectedNumAcks))
return
}
log.Debugf("processMatchAcksForCancel: 'match' ack received from %v", user)
}
// SubmitOrderAsync submits a new order for inclusion into the current epoch.
// When submission is completed, an error value will be sent on the channel.
// This is the asynchronous version of SubmitOrder.
func (m *Market) SubmitOrderAsync(rec *orderRecord) <-chan error {
sendErr := func(err error) <-chan error {
errChan := make(chan error, 1)
errChan <- err // i.e. ErrInvalidOrder, ErrInvalidCommitment
return errChan
}
// Validate the order. The order router must do it's own validation, but do
// a second validation for (1) this Market and (2) epoch status, before
// putting it on the queue.
if err := m.validateOrder(rec.order); err != nil {
// Order ID cannot be computed since ServerTime has not been set.
log.Debugf("SubmitOrderAsync: Invalid order received from user %v with commitment %v: %v",
rec.order.User(), rec.order.Commitment(), err)
return sendErr(err)
}
// Only submit orders while market is running.
m.runMtx.RLock()
defer m.runMtx.RUnlock()
select {
case <-m.running:
default:
if rec.order.Type() == order.CancelOrderType {
errChan := make(chan error, 1)
go m.processCancelOrderWhileSuspended(rec, errChan)
return errChan
}
// m.orderRouter is closed
log.Infof("SubmitOrderAsync: Market stopped with an order in submission (commitment %v).",
rec.order.Commitment()) // The order is not time stamped, so no OrderID.
return sendErr(ErrMarketNotRunning)
}
sig := newOrderUpdateSignal(rec)
// The lock is still held, so there is a receiver: either Run's main loop or
// the drain in Run's defer that runs until m.running starts blocking.
m.orderRouter <- sig
return sig.errChan
}
// MidGap returns the mid-gap market rate, which is ths rate halfway between the
// best buy order and the best sell order in the order book. If one side has no
// orders, the best order rate on other side is returned. If both sides have no
// orders, 0 is returned.
func (m *Market) MidGap() uint64 {
_, mid, _ := m.rates()
return mid
}
func (m *Market) rates() (bestBuyRate, mid, bestSellRate uint64) {
bestBuy, bestSell := m.book.Best()
if bestBuy == nil {
if bestSell == nil {
return
}
return 0, bestSell.Rate, bestSell.Rate
} else if bestSell == nil {
return bestBuy.Rate, bestBuy.Rate, math.MaxUint64
}
mid = (bestBuy.Rate + bestSell.Rate) / 2 // note downward bias on truncate
return bestBuy.Rate, mid, bestSell.Rate
}
// CoinLocked checks if a coin is locked. The asset is specified since we should
// not assume that a CoinID for one asset cannot be made to match another
// asset's CoinID.
func (m *Market) CoinLocked(asset uint32, coin coinlock.CoinID) bool {
switch {
case asset == m.marketInfo.Base && m.coinLockerBase != nil:
return m.coinLockerBase.CoinLocked(coin)
case asset == m.marketInfo.Quote && m.coinLockerQuote != nil:
return m.coinLockerQuote.CoinLocked(coin)
default:
panic(fmt.Sprintf("invalid utxo-based asset %d for market %s", asset, m.marketInfo.Name))
}
}
// Cancelable determines if an order is a limit order with time-in-force
// standing that is in either the epoch queue or in the order book.
func (m *Market) Cancelable(oid order.OrderID) bool {
// All book orders are standing limit orders.
if m.book.HaveOrder(oid) {
return true
}
// Check the active epochs (includes current and next).
m.epochMtx.RLock()
ord := m.epochOrders[oid]
m.epochMtx.RUnlock()
if lo, ok := ord.(*order.LimitOrder); ok {
return lo.Force == order.StandingTiF
}
return false
}
// CancelableBy determines if an order is cancelable by a certain account. This
// means: (1) an order in the book or epoch queue, (2) type limit with
// time-in-force standing (implied for book orders), and (3) AccountID field
// matching the provided account ID.
func (m *Market) CancelableBy(oid order.OrderID, aid account.AccountID) (bool, error) {
// All book orders are standing limit orders.
if lo := m.book.Order(oid); lo != nil {
if lo.AccountID == aid {
return true, nil
}
return false, ErrCancelNotPermitted
}