forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
lp_ordermatch.rs
5577 lines (5012 loc) · 199 KB
/
lp_ordermatch.rs
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
/******************************************************************************
* Copyright © 2022 Atomic Private Limited and its contributors *
* *
* See the CONTRIBUTOR-LICENSE-AGREEMENT, COPYING, LICENSE-COPYRIGHT-NOTICE *
* and DEVELOPER-CERTIFICATE-OF-ORIGIN files in the LEGAL directory in *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* AtomicDEX software, including this file may be copied, modified, propagated*
* or distributed except according to the terms contained in the *
* LICENSE-COPYRIGHT-NOTICE file. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
//
// lp_ordermatch.rs
// marketmaker
//
use async_trait::async_trait;
use best_orders::BestOrdersAction;
use blake2::digest::{Update, VariableOutput};
use blake2::Blake2bVar;
use coins::utxo::{compressed_pub_key_from_priv_raw, ChecksumType, UtxoAddressFormat};
use coins::{coin_conf, find_pair, lp_coinfind, BalanceTradeFeeUpdatedHandler, CoinProtocol, CoinsContext,
FeeApproxStage, MmCoinEnum};
use common::executor::{spawn, Timer};
use common::log::{error, LogOnError};
use common::time_cache::TimeCache;
use common::{bits256, log, new_uuid, now_ms, spawn_abortable, AbortOnDropHandle};
use crypto::privkey::SerializableSecp256k1Keypair;
use crypto::CryptoCtx;
use derive_more::Display;
use futures::{compat::Future01CompatExt, lock::Mutex as AsyncMutex, TryFutureExt};
use hash256_std_hasher::Hash256StdHasher;
use hash_db::Hasher;
use http::Response;
use keys::{AddressFormat, KeyPair};
use mm2_core::mm_ctx::{from_ctx, MmArc, MmWeak};
use mm2_err_handle::prelude::*;
use mm2_libp2p::{decode_signed, encode_and_sign, encode_message, pub_sub_topic, TopicPrefix, TOPIC_SEPARATOR};
use mm2_number::{construct_detailed, BigDecimal, BigRational, Fraction, MmNumber, MmNumberMultiRepr};
#[cfg(test)] use mocktopus::macros::*;
use num_traits::identities::Zero;
use parking_lot::Mutex as PaMutex;
use rpc::v1::types::H256 as H256Json;
use serde_json::{self as json, Value as Json};
use sp_trie::{delta_trie_root, MemoryDB, Trie, TrieConfiguration, TrieDB, TrieDBMut, TrieHash, TrieMut};
use std::collections::hash_map::{Entry, HashMap, RawEntryMut};
use std::collections::{BTreeSet, HashSet};
use std::convert::TryInto;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use trie_db::NodeCodec as NodeCodecT;
use uuid::Uuid;
use crate::mm2::lp_network::{broadcast_p2p_msg, request_any_relay, request_one_peer, subscribe_to_topic, Libp2pPeerId,
P2PRequest};
use crate::mm2::lp_swap::{calc_max_maker_vol, check_balance_for_maker_swap, check_balance_for_taker_swap,
check_other_coin_balance_for_swap, insert_new_swap_to_db, is_pubkey_banned,
lp_atomic_locktime, run_maker_swap, run_taker_swap, AtomicLocktimeVersion, MakerSwap,
RunMakerSwapInput, RunTakerSwapInput, SwapConfirmationsSettings, TakerSwap};
pub use best_orders::{best_orders_rpc, best_orders_rpc_v2};
use my_orders_storage::{delete_my_maker_order, delete_my_taker_order, save_maker_order_on_update,
save_my_new_maker_order, save_my_new_taker_order, MyActiveOrders, MyOrdersFilteringHistory,
MyOrdersHistory, MyOrdersStorage};
pub use orderbook_depth::orderbook_depth_rpc;
pub use orderbook_rpc::{orderbook_rpc, orderbook_rpc_v2};
cfg_wasm32! {
use mm2_db::indexed_db::{ConstructibleDb, DbLocked};
use ordermatch_wasm_db::{InitDbResult, OrdermatchDb};
pub type OrdermatchDbLocked<'a> = DbLocked<'a, OrdermatchDb>;
}
#[path = "lp_ordermatch/best_orders.rs"] mod best_orders;
#[path = "lp_ordermatch/lp_bot.rs"] mod lp_bot;
pub use lp_bot::{start_simple_market_maker_bot, stop_simple_market_maker_bot, StartSimpleMakerBotRequest,
TradingBotEvent, KMD_PRICE_ENDPOINT};
#[path = "lp_ordermatch/my_orders_storage.rs"]
mod my_orders_storage;
#[path = "lp_ordermatch/new_protocol.rs"] mod new_protocol;
#[path = "lp_ordermatch/order_requests_tracker.rs"]
mod order_requests_tracker;
#[path = "lp_ordermatch/orderbook_depth.rs"] mod orderbook_depth;
#[path = "lp_ordermatch/orderbook_rpc.rs"] mod orderbook_rpc;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "ordermatch_tests.rs"]
pub mod ordermatch_tests;
#[cfg(target_arch = "wasm32")]
#[path = "lp_ordermatch/ordermatch_wasm_db.rs"]
mod ordermatch_wasm_db;
pub const ORDERBOOK_PREFIX: TopicPrefix = "orbk";
#[cfg(not(test))]
pub const MIN_ORDER_KEEP_ALIVE_INTERVAL: u64 = 30;
#[cfg(test)]
pub const MIN_ORDER_KEEP_ALIVE_INTERVAL: u64 = 5;
const BALANCE_REQUEST_INTERVAL: f64 = 30.;
const MAKER_ORDER_TIMEOUT: u64 = MIN_ORDER_KEEP_ALIVE_INTERVAL * 3;
const TAKER_ORDER_TIMEOUT: u64 = 30;
const ORDER_MATCH_TIMEOUT: u64 = 30;
const ORDERBOOK_REQUESTING_TIMEOUT: u64 = MIN_ORDER_KEEP_ALIVE_INTERVAL * 2;
const MAX_ORDERS_NUMBER_IN_ORDERBOOK_RESPONSE: usize = 1000;
#[cfg(not(test))]
const TRIE_STATE_HISTORY_TIMEOUT: u64 = 14400;
#[cfg(test)]
const TRIE_STATE_HISTORY_TIMEOUT: u64 = 3;
#[cfg(not(test))]
const TRIE_ORDER_HISTORY_TIMEOUT: u64 = 300;
#[cfg(test)]
const TRIE_ORDER_HISTORY_TIMEOUT: u64 = 3;
/// Alphabetically ordered orderbook pair
type AlbOrderedOrderbookPair = String;
type PubkeyOrders = Vec<(Uuid, OrderbookP2PItem)>;
pub type OrdermatchInitResult<T> = Result<T, MmError<OrdermatchInitError>>;
#[derive(Debug, Deserialize, Display, Serialize)]
pub enum OrdermatchInitError {
#[display(fmt = "Error deserializing '{}' config field: {}", field, error)]
ErrorDeserializingConfig {
field: String,
error: String,
},
Internal(String),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CancelAllOrdersResponse {
cancelled: Vec<Uuid>,
currently_matching: Vec<Uuid>,
}
#[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)]
#[serde(tag = "error_type", content = "error_data")]
pub enum CancelAllOrdersError {
LegacyError(String),
}
impl From<(new_protocol::MakerOrderCreated, String)> for OrderbookItem {
fn from(tuple: (new_protocol::MakerOrderCreated, String)) -> OrderbookItem {
let (order, pubkey) = tuple;
OrderbookItem {
pubkey,
base: order.base,
rel: order.rel,
price: order.price,
max_volume: order.max_volume,
min_volume: order.min_volume,
uuid: order.uuid.into(),
created_at: order.created_at,
base_protocol_info: order.base_protocol_info,
rel_protocol_info: order.rel_protocol_info,
conf_settings: Some(order.conf_settings),
}
}
}
pub fn addr_format_from_protocol_info(protocol_info: &[u8]) -> AddressFormat {
match rmp_serde::from_read_ref::<_, AddressFormat>(protocol_info) {
Ok(format) => format,
Err(_) => AddressFormat::Standard,
}
}
struct ProcessTrieParams<'a> {
pubkey: &'a str,
alb_pair: &'a str,
protocol_infos: &'a HashMap<Uuid, BaseRelProtocolInfo>,
conf_infos: &'a HashMap<Uuid, OrderConfirmationsSettings>,
}
fn process_pubkey_full_trie(
orderbook: &mut Orderbook,
new_trie_orders: PubkeyOrders,
params: ProcessTrieParams,
) -> H64 {
remove_pubkey_pair_orders(orderbook, params.pubkey, params.alb_pair);
for (uuid, order) in new_trie_orders {
orderbook.insert_or_update_order_update_trie(OrderbookItem::from_p2p_and_info(
order,
params.protocol_infos.get(&uuid).cloned().unwrap_or_default(),
params.conf_infos.get(&uuid).cloned(),
));
}
let new_root = pubkey_state_mut(&mut orderbook.pubkeys_state, params.pubkey)
.trie_roots
.get(params.alb_pair)
.copied()
.unwrap_or_default();
new_root
}
fn process_trie_delta(
orderbook: &mut Orderbook,
delta_orders: HashMap<Uuid, Option<OrderbookP2PItem>>,
params: ProcessTrieParams,
) -> H64 {
for (uuid, order) in delta_orders {
match order {
Some(order) => orderbook.insert_or_update_order_update_trie(OrderbookItem::from_p2p_and_info(
order,
params.protocol_infos.get(&uuid).cloned().unwrap_or_default(),
params.conf_infos.get(&uuid).cloned(),
)),
None => {
orderbook.remove_order_trie_update(uuid);
},
}
}
let new_root = match orderbook.pubkeys_state.get(params.pubkey) {
Some(pubkey_state) => pubkey_state
.trie_roots
.get(params.alb_pair)
.copied()
.unwrap_or_default(),
None => H64::default(),
};
new_root
}
async fn process_orders_keep_alive(
ctx: MmArc,
propagated_from_peer: String,
from_pubkey: String,
keep_alive: new_protocol::PubkeyKeepAlive,
i_am_relay: bool,
) -> bool {
let ordermatch_ctx = OrdermatchContext::from_ctx(&ctx).expect("from_ctx failed");
let to_request = ordermatch_ctx
.orderbook
.lock()
.process_keep_alive(&from_pubkey, keep_alive, i_am_relay);
let req = match to_request {
Some(req) => req,
// The message was processed, simply forward it
None => return true,
};
let resp =
request_one_peer::<SyncPubkeyOrderbookStateRes>(ctx.clone(), P2PRequest::Ordermatch(req), propagated_from_peer)
.await;
let response = match resp {
Ok(Some(resp)) => resp,
_ => return false,
};
let mut orderbook = ordermatch_ctx.orderbook.lock();
for (pair, diff) in response.pair_orders_diff {
let params = ProcessTrieParams {
pubkey: &from_pubkey,
alb_pair: &pair,
protocol_infos: &response.protocol_infos,
conf_infos: &response.conf_infos,
};
let _new_root = match diff {
DeltaOrFullTrie::Delta(delta) => process_trie_delta(&mut orderbook, delta, params),
DeltaOrFullTrie::FullTrie(values) => process_pubkey_full_trie(&mut orderbook, values, params),
};
}
true
}
fn process_maker_order_updated(ctx: MmArc, from_pubkey: String, updated_msg: new_protocol::MakerOrderUpdated) -> bool {
let ordermatch_ctx = OrdermatchContext::from_ctx(&ctx).expect("from_ctx failed");
let uuid = updated_msg.uuid();
let mut orderbook = ordermatch_ctx.orderbook.lock();
match orderbook.find_order_by_uuid_and_pubkey(&uuid, &from_pubkey) {
Some(mut order) => {
order.apply_updated(&updated_msg);
orderbook.insert_or_update_order_update_trie(order);
true
},
None => {
log::warn!(
"Couldn't find an order {}, ignoring, it will be synced upon pubkey keep alive",
uuid
);
false
},
}
}
// fn verify_pubkey_orderbook(orderbook: &GetOrderbookPubkeyItem) -> Result<(), String> {
// let keys: Vec<(_, _)> = orderbook
// .orders
// .iter()
// .map(|(uuid, order)| {
// let order_bytes = rmp_serde::to_vec(&order).expect("Serialization should never fail");
// (uuid.as_bytes(), Some(order_bytes))
// })
// .collect();
// let (orders_root, proof) = &orderbook.pair_orders_trie_root;
// verify_trie_proof::<Layout, _, _, _>(orders_root, proof, &keys)
// .map_err(|e| ERRL!("Error on pair_orders_trie_root verification: {}", e))?;
// Ok(())
// }
/// Request best asks and bids for the given `base` and `rel` coins from relays.
/// Set `asks_num` and/or `bids_num` to get corresponding number of best asks and bids or None to get all of the available orders.
///
/// # Safety
///
/// The function locks [`MmCtx::p2p_ctx`] and [`MmCtx::ordermatch_ctx`]
async fn request_and_fill_orderbook(ctx: &MmArc, base: &str, rel: &str) -> Result<(), String> {
let request = OrdermatchRequest::GetOrderbook {
base: base.to_string(),
rel: rel.to_string(),
};
let response = try_s!(request_any_relay::<GetOrderbookRes>(ctx.clone(), P2PRequest::Ordermatch(request)).await);
let (pubkey_orders, protocol_infos, conf_infos) = match response {
Some((
GetOrderbookRes {
pubkey_orders,
protocol_infos,
conf_infos,
},
_peer_id,
)) => (pubkey_orders, protocol_infos, conf_infos),
None => return Ok(()),
};
let ordermatch_ctx = OrdermatchContext::from_ctx(ctx).unwrap();
let mut orderbook = ordermatch_ctx.orderbook.lock();
let keypair = ctx.secp256k1_key_pair_as_option();
let alb_pair = alb_ordered_pair(base, rel);
for (pubkey, GetOrderbookPubkeyItem { orders, .. }) in pubkey_orders {
let pubkey_bytes = match hex::decode(&pubkey) {
Ok(b) => b,
Err(e) => {
log::warn!("Error {} decoding pubkey {}", e, pubkey);
continue;
},
};
if let Some(keypair) = keypair {
if pubkey_bytes.as_slice() == keypair.public().as_ref() {
continue;
}
}
if is_pubkey_banned(ctx, &pubkey_bytes[1..].into()) {
log::warn!("Pubkey {} is banned", pubkey);
continue;
}
let params = ProcessTrieParams {
pubkey: &pubkey,
alb_pair: &alb_pair,
protocol_infos: &protocol_infos,
conf_infos: &conf_infos,
};
let _new_root = process_pubkey_full_trie(&mut orderbook, orders, params);
}
let topic = orderbook_topic_from_base_rel(base, rel);
orderbook
.topics_subscribed_to
.insert(topic, OrderbookRequestingState::Requested);
Ok(())
}
/// Insert or update an order `req`.
/// Note this function locks the [`OrdermatchContext::orderbook`] async mutex.
fn insert_or_update_order(ctx: &MmArc, item: OrderbookItem) {
let ordermatch_ctx = OrdermatchContext::from_ctx(ctx).expect("from_ctx failed");
let mut orderbook = ordermatch_ctx.orderbook.lock();
orderbook.insert_or_update_order_update_trie(item)
}
fn delete_order(ctx: &MmArc, pubkey: &str, uuid: Uuid) {
let ordermatch_ctx = OrdermatchContext::from_ctx(ctx).expect("from_ctx failed");
let mut orderbook = ordermatch_ctx.orderbook.lock();
if let Some(order) = orderbook.order_set.get(&uuid) {
if order.pubkey == pubkey {
orderbook.remove_order_trie_update(uuid);
}
}
}
fn delete_my_order(ctx: &MmArc, uuid: Uuid) {
let ordermatch_ctx: Arc<OrdermatchContext> = OrdermatchContext::from_ctx(ctx).expect("from_ctx failed");
let mut orderbook = ordermatch_ctx.orderbook.lock();
orderbook.remove_order_trie_update(uuid);
}
fn remove_pubkey_pair_orders(orderbook: &mut Orderbook, pubkey: &str, alb_pair: &str) {
let pubkey_state = match orderbook.pubkeys_state.get_mut(pubkey) {
Some(state) => state,
None => return,
};
if pubkey_state.trie_roots.get(alb_pair).is_none() {
return;
}
pubkey_state.order_pairs_trie_state_history.remove(alb_pair.into());
let mut orders_to_remove = Vec::with_capacity(pubkey_state.orders_uuids.len());
pubkey_state.orders_uuids.retain(|(uuid, alb)| {
if alb == alb_pair {
orders_to_remove.push(*uuid);
false
} else {
true
}
});
for order in orders_to_remove {
orderbook.remove_order_trie_update(order);
}
let pubkey_state = match orderbook.pubkeys_state.get_mut(pubkey) {
Some(state) => state,
None => return,
};
pubkey_state.trie_roots.remove(alb_pair);
}
/// Attempts to decode a message and process it returning whether the message is valid and worth rebroadcasting
pub async fn process_msg(ctx: MmArc, _topics: Vec<String>, from_peer: String, msg: &[u8], i_am_relay: bool) -> bool {
match decode_signed::<new_protocol::OrdermatchMessage>(msg) {
Ok((message, _sig, pubkey)) => {
if is_pubkey_banned(&ctx, &pubkey.unprefixed().into()) {
log::warn!("Pubkey {} is banned", pubkey.to_hex());
return false;
}
match message {
new_protocol::OrdermatchMessage::MakerOrderCreated(created_msg) => {
let order: OrderbookItem = (created_msg, hex::encode(pubkey.to_bytes().as_slice())).into();
insert_or_update_order(&ctx, order);
true
},
new_protocol::OrdermatchMessage::PubkeyKeepAlive(keep_alive) => {
process_orders_keep_alive(ctx, from_peer, pubkey.to_hex(), keep_alive, i_am_relay).await
},
new_protocol::OrdermatchMessage::TakerRequest(taker_request) => {
let msg = TakerRequest::from_new_proto_and_pubkey(taker_request, pubkey.unprefixed().into());
process_taker_request(ctx, pubkey.unprefixed().into(), msg).await;
true
},
new_protocol::OrdermatchMessage::MakerReserved(maker_reserved) => {
let msg = MakerReserved::from_new_proto_and_pubkey(maker_reserved, pubkey.unprefixed().into());
// spawn because process_maker_reserved may take significant time to run
spawn(process_maker_reserved(ctx, pubkey.unprefixed().into(), msg));
true
},
new_protocol::OrdermatchMessage::TakerConnect(taker_connect) => {
process_taker_connect(ctx, pubkey.unprefixed().into(), taker_connect.into()).await;
true
},
new_protocol::OrdermatchMessage::MakerConnected(maker_connected) => {
process_maker_connected(ctx, pubkey.unprefixed().into(), maker_connected.into()).await;
true
},
new_protocol::OrdermatchMessage::MakerOrderCancelled(cancelled_msg) => {
delete_order(&ctx, &pubkey.to_hex(), cancelled_msg.uuid.into());
true
},
new_protocol::OrdermatchMessage::MakerOrderUpdated(updated_msg) => {
process_maker_order_updated(ctx, pubkey.to_hex(), updated_msg)
},
}
},
Err(e) => {
log::error!("Error {} while decoding signed message", e);
false
},
}
}
#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum OrdermatchRequest {
/// Get an orderbook for the given pair.
GetOrderbook {
base: String,
rel: String,
},
/// Sync specific pubkey orderbook state if our known Patricia trie state doesn't match the latest keep alive message
SyncPubkeyOrderbookState {
pubkey: String,
/// Request using this condition
trie_roots: HashMap<AlbOrderedOrderbookPair, H64>,
},
BestOrders {
coin: String,
action: BestOrdersAction,
volume: BigRational,
},
OrderbookDepth {
pairs: Vec<(String, String)>,
},
BestOrdersByNumber {
coin: String,
action: BestOrdersAction,
number: usize,
},
}
#[derive(Debug)]
struct TryFromBytesError(String);
impl From<String> for TryFromBytesError {
fn from(string: String) -> Self { TryFromBytesError(string) }
}
trait TryFromBytes {
fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, TryFromBytesError>
where
Self: Sized;
}
impl TryFromBytes for String {
fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, TryFromBytesError> {
String::from_utf8(bytes).map_err(|e| ERRL!("{}", e).into())
}
}
impl TryFromBytes for OrderbookP2PItem {
fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, TryFromBytesError> {
rmp_serde::from_read(bytes.as_slice()).map_err(|e| ERRL!("{}", e).into())
}
}
impl TryFromBytes for H64 {
fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, TryFromBytesError> {
bytes.try_into().map_err(|e| ERRL!("{:?}", e).into())
}
}
impl TryFromBytes for Uuid {
fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, TryFromBytesError> {
Uuid::from_slice(&bytes).map_err(|e| ERRL!("{}", e).into())
}
}
pub fn process_peer_request(ctx: MmArc, request: OrdermatchRequest) -> Result<Option<Vec<u8>>, String> {
log::debug!("Got ordermatch request {:?}", request);
match request {
OrdermatchRequest::GetOrderbook { base, rel } => process_get_orderbook_request(ctx, base, rel),
OrdermatchRequest::SyncPubkeyOrderbookState { pubkey, trie_roots } => {
let response = process_sync_pubkey_orderbook_state(ctx, pubkey, trie_roots);
response.map(|res| res.map(|r| encode_message(&r).expect("Serialization failed")))
},
OrdermatchRequest::BestOrders { coin, action, volume } => {
best_orders::process_best_orders_p2p_request(ctx, coin, action, volume)
},
OrdermatchRequest::BestOrdersByNumber { coin, action, number } => {
best_orders::process_best_orders_p2p_request_by_number(ctx, coin, action, number)
},
OrdermatchRequest::OrderbookDepth { pairs } => orderbook_depth::process_orderbook_depth_p2p_request(ctx, pairs),
}
}
type TrieProof = Vec<Vec<u8>>;
#[derive(Debug, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
struct GetOrderbookPubkeyItem {
/// Timestamp of the latest keep alive message received.
last_keep_alive: u64,
/// last signed OrdermatchMessage payload
last_signed_pubkey_payload: Vec<u8>,
/// Requested orders.
orders: PubkeyOrders,
}
/// Do not change this struct as it will break backward compatibility
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[cfg_attr(test, derive(PartialEq))]
struct BaseRelProtocolInfo {
base: Vec<u8>,
rel: Vec<u8>,
}
#[derive(Debug, Deserialize, Serialize)]
struct GetOrderbookRes {
/// Asks and bids grouped by pubkey.
pubkey_orders: HashMap<String, GetOrderbookPubkeyItem>,
#[serde(default)]
protocol_infos: HashMap<Uuid, BaseRelProtocolInfo>,
#[serde(default)]
conf_infos: HashMap<Uuid, OrderConfirmationsSettings>,
}
struct GetPubkeysOrdersRes {
total_number_of_orders: usize,
uuids_by_pubkey: HashMap<String, PubkeyOrders>,
protocol_infos: HashMap<Uuid, BaseRelProtocolInfo>,
conf_infos: HashMap<Uuid, OrderConfirmationsSettings>,
}
fn get_pubkeys_orders(orderbook: &Orderbook, base: String, rel: String) -> GetPubkeysOrdersRes {
let asks = orderbook.unordered.get(&(base.clone(), rel.clone()));
let bids = orderbook.unordered.get(&(rel, base));
let asks_num = asks.map(|x| x.len()).unwrap_or(0);
let bids_num = bids.map(|x| x.len()).unwrap_or(0);
let total_number_of_orders = asks_num + bids_num;
// flatten Option(asks) and Option(bids) to avoid cloning
let orders = asks.iter().chain(bids.iter()).copied().flatten();
let mut uuids_by_pubkey = HashMap::new();
let mut protocol_infos = HashMap::new();
let mut conf_infos = HashMap::new();
for uuid in orders {
let order = orderbook
.order_set
.get(uuid)
.expect("Orderbook::ordered contains an uuid that is not in Orderbook::order_set");
let uuids = uuids_by_pubkey.entry(order.pubkey.clone()).or_insert_with(Vec::new);
protocol_infos.insert(order.uuid, order.base_rel_proto_info());
if let Some(info) = order.conf_settings {
conf_infos.insert(order.uuid, info);
}
uuids.push((*uuid, order.clone().into()))
}
GetPubkeysOrdersRes {
total_number_of_orders,
uuids_by_pubkey,
protocol_infos,
conf_infos,
}
}
fn process_get_orderbook_request(ctx: MmArc, base: String, rel: String) -> Result<Option<Vec<u8>>, String> {
let ordermatch_ctx = OrdermatchContext::from_ctx(&ctx).unwrap();
let orderbook = ordermatch_ctx.orderbook.lock();
let pubkeys_orders = get_pubkeys_orders(&orderbook, base, rel);
if pubkeys_orders.total_number_of_orders > MAX_ORDERS_NUMBER_IN_ORDERBOOK_RESPONSE {
return ERR!("Orderbook too large");
}
let orders_to_send = pubkeys_orders
.uuids_by_pubkey
.into_iter()
.map(|(pubkey, orders)| {
let pubkey_state = orderbook.pubkeys_state.get(&pubkey).ok_or(ERRL!(
"Orderbook::pubkeys_state is expected to contain the {:?} pubkey",
pubkey
))?;
let item = GetOrderbookPubkeyItem {
last_keep_alive: pubkey_state.last_keep_alive,
orders,
// TODO save last signed payload to pubkey state
last_signed_pubkey_payload: vec![],
};
Ok((pubkey, item))
})
.collect::<Result<HashMap<_, _>, String>>()?;
let response = GetOrderbookRes {
pubkey_orders: orders_to_send,
protocol_infos: pubkeys_orders.protocol_infos,
conf_infos: pubkeys_orders.conf_infos,
};
let encoded = try_s!(encode_message(&response));
Ok(Some(encoded))
}
#[derive(Debug, Deserialize, Serialize)]
enum DeltaOrFullTrie<Key: Eq + std::hash::Hash, Value> {
Delta(HashMap<Key, Option<Value>>),
FullTrie(Vec<(Key, Value)>),
}
impl<Key: Eq + std::hash::Hash, V1> DeltaOrFullTrie<Key, V1> {
pub fn map_to<V2: From<V1>>(self, mut on_each: impl FnMut(&Key, Option<&V1>)) -> DeltaOrFullTrie<Key, V2> {
match self {
DeltaOrFullTrie::Delta(delta) => {
delta.iter().for_each(|(key, val)| on_each(key, val.as_ref()));
let new_map = delta
.into_iter()
.map(|(key, value)| (key, value.map(From::from)))
.collect();
DeltaOrFullTrie::Delta(new_map)
},
DeltaOrFullTrie::FullTrie(trie) => {
trie.iter().for_each(|(key, val)| on_each(key, Some(val)));
let new_trie = trie.into_iter().map(|(key, value)| (key, value.into())).collect();
DeltaOrFullTrie::FullTrie(new_trie)
},
}
}
}
#[derive(Debug)]
enum TrieDiffHistoryError {
TrieDbError(Box<trie_db::TrieError<H64, sp_trie::Error>>),
TryFromBytesError(TryFromBytesError),
GetterNoneForKeyFromTrie,
}
impl std::fmt::Display for TrieDiffHistoryError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "({:?})", self) }
}
impl From<TryFromBytesError> for TrieDiffHistoryError {
fn from(error: TryFromBytesError) -> TrieDiffHistoryError { TrieDiffHistoryError::TryFromBytesError(error) }
}
impl From<Box<trie_db::TrieError<H64, sp_trie::Error>>> for TrieDiffHistoryError {
fn from(error: Box<trie_db::TrieError<H64, sp_trie::Error>>) -> TrieDiffHistoryError {
TrieDiffHistoryError::TrieDbError(error)
}
}
fn get_full_trie<Key, Value>(
trie_root: &H64,
db: &MemoryDB<Blake2Hasher64>,
getter: impl Fn(&Key) -> Option<Value>,
) -> Result<Vec<(Key, Value)>, TrieDiffHistoryError>
where
Key: Clone + Eq + std::hash::Hash + TryFromBytes,
{
let trie = TrieDB::<Layout>::new(db, trie_root)?;
let trie: Result<Vec<_>, TrieDiffHistoryError> = trie
.iter()?
.map(|key_value| {
let (key, _) = key_value?;
let key = TryFromBytes::try_from_bytes(key)?;
let val = getter(&key).ok_or(TrieDiffHistoryError::GetterNoneForKeyFromTrie)?;
Ok((key, val))
})
.collect();
trie
}
impl<Key: Clone + Eq + std::hash::Hash + TryFromBytes, Value: Clone> DeltaOrFullTrie<Key, Value> {
fn from_history(
history: &TrieDiffHistory<Key, Value>,
from_hash: H64,
actual_trie_root: H64,
db: &MemoryDB<Blake2Hasher64>,
getter: impl Fn(&Key) -> Option<Value>,
) -> Result<DeltaOrFullTrie<Key, Value>, TrieDiffHistoryError> {
if let Some(delta) = history.get(&from_hash) {
let mut current_delta = delta;
let mut total_delta = HashMap::new();
total_delta.extend(delta.delta.iter().cloned());
while let Some(cur) = history.get(¤t_delta.next_root) {
current_delta = cur;
total_delta.extend(current_delta.delta.iter().cloned());
}
if current_delta.next_root == actual_trie_root {
return Ok(DeltaOrFullTrie::Delta(total_delta));
}
log::warn!(
"History started from {:?} ends with not up-to-date trie root {:?}",
from_hash,
actual_trie_root
);
}
let trie = get_full_trie(&actual_trie_root, db, getter)?;
Ok(DeltaOrFullTrie::FullTrie(trie))
}
}
#[derive(Debug, Deserialize, Serialize)]
struct SyncPubkeyOrderbookStateRes {
/// last signed OrdermatchMessage payload from pubkey
last_signed_pubkey_payload: Vec<u8>,
pair_orders_diff: HashMap<AlbOrderedOrderbookPair, DeltaOrFullTrie<Uuid, OrderbookP2PItem>>,
#[serde(default)]
protocol_infos: HashMap<Uuid, BaseRelProtocolInfo>,
#[serde(default)]
conf_infos: HashMap<Uuid, OrderConfirmationsSettings>,
}
fn process_sync_pubkey_orderbook_state(
ctx: MmArc,
pubkey: String,
trie_roots: HashMap<AlbOrderedOrderbookPair, H64>,
) -> Result<Option<SyncPubkeyOrderbookStateRes>, String> {
let ordermatch_ctx = OrdermatchContext::from_ctx(&ctx).unwrap();
let orderbook = ordermatch_ctx.orderbook.lock();
let pubkey_state = match orderbook.pubkeys_state.get(&pubkey) {
Some(s) => s,
None => return Ok(None),
};
let order_getter = |uuid: &Uuid| orderbook.order_set.get(uuid).cloned();
let pair_orders_diff: Result<HashMap<_, _>, _> = trie_roots
.into_iter()
.map(|(pair, root)| {
let actual_pair_root = pubkey_state
.trie_roots
.get(&pair)
.ok_or(ERRL!("No pair trie root for {}", pair))?;
let delta_result = match pubkey_state.order_pairs_trie_state_history.get(&pair) {
Some(history) => {
DeltaOrFullTrie::from_history(history, root, *actual_pair_root, &orderbook.memory_db, &order_getter)
},
None => {
get_full_trie(actual_pair_root, &orderbook.memory_db, &order_getter).map(DeltaOrFullTrie::FullTrie)
},
};
let delta = try_s!(delta_result);
Ok((pair, delta))
})
.collect();
let pair_orders_diff = try_s!(pair_orders_diff);
let mut protocol_infos = HashMap::new();
let mut conf_infos = HashMap::new();
let pair_orders_diff = pair_orders_diff
.into_iter()
.map(|(pair, trie)| {
let new_trie = trie.map_to(|uuid, order| match order {
Some(o) => {
protocol_infos.insert(o.uuid, BaseRelProtocolInfo {
base: o.base_protocol_info.clone(),
rel: o.rel_protocol_info.clone(),
});
if let Some(info) = o.conf_settings {
conf_infos.insert(o.uuid, info);
}
},
None => {
protocol_infos.remove(uuid);
conf_infos.remove(uuid);
},
});
(pair, new_trie)
})
.collect();
let last_signed_pubkey_payload = vec![];
let result = SyncPubkeyOrderbookStateRes {
last_signed_pubkey_payload,
pair_orders_diff,
protocol_infos,
conf_infos,
};
Ok(Some(result))
}
fn alb_ordered_pair(base: &str, rel: &str) -> AlbOrderedOrderbookPair {
let (first, second) = if base < rel { (base, rel) } else { (rel, base) };
let mut res = first.to_owned();
res.push(':');
res.push_str(second);
res
}
fn orderbook_topic_from_base_rel(base: &str, rel: &str) -> String {
pub_sub_topic(ORDERBOOK_PREFIX, &alb_ordered_pair(base, rel))
}
fn orderbook_topic_from_ordered_pair(pair: &str) -> String { pub_sub_topic(ORDERBOOK_PREFIX, pair) }
#[test]
fn test_alb_ordered_pair() {
assert_eq!("BTC:KMD", alb_ordered_pair("KMD", "BTC"));
assert_eq!("BTCH:KMD", alb_ordered_pair("KMD", "BTCH"));
assert_eq!("KMD:QTUM", alb_ordered_pair("QTUM", "KMD"));
}
#[allow(dead_code)]
fn parse_orderbook_pair_from_topic(topic: &str) -> Option<(&str, &str)> {
let mut split = topic.split(|maybe_sep| maybe_sep == TOPIC_SEPARATOR);
match split.next() {
Some(ORDERBOOK_PREFIX) => match split.next() {
Some(maybe_pair) => {
let colon = maybe_pair.find(|maybe_colon| maybe_colon == ':');
match colon {
Some(index) => {
if index + 1 < maybe_pair.len() {
Some((&maybe_pair[..index], &maybe_pair[index + 1..]))
} else {
None
}
},
None => None,
}
},
None => None,
},
_ => None,
}
}
#[test]
fn test_parse_orderbook_pair_from_topic() {
assert_eq!(Some(("BTC", "KMD")), parse_orderbook_pair_from_topic("orbk/BTC:KMD"));
assert_eq!(None, parse_orderbook_pair_from_topic("orbk/BTC:"));
}
fn maker_order_created_p2p_notify(
ctx: MmArc,
order: &MakerOrder,
base_protocol_info: Vec<u8>,
rel_protocol_info: Vec<u8>,
) {
let topic = order.orderbook_topic();
let message = new_protocol::MakerOrderCreated {
uuid: order.uuid.into(),
base: order.base_orderbook_ticker().to_owned(),
rel: order.rel_orderbook_ticker().to_owned(),
price: order.price.to_ratio(),
max_volume: order.available_amount().to_ratio(),
min_volume: order.min_base_vol.to_ratio(),
conf_settings: order.conf_settings.unwrap(),
created_at: now_ms() / 1000,
timestamp: now_ms() / 1000,
pair_trie_root: H64::default(),
base_protocol_info,
rel_protocol_info,
};
let to_broadcast = new_protocol::OrdermatchMessage::MakerOrderCreated(message.clone());
let (key_pair, peer_id) = match order.p2p_keypair() {
Some(k) => (k, Some(k.libp2p_peer_id())),
None => (ctx.secp256k1_key_pair(), None),
};
let encoded_msg = encode_and_sign(&to_broadcast, key_pair.private_ref()).unwrap();
let order: OrderbookItem = (message, hex::encode(key_pair.public_slice())).into();
insert_or_update_order(&ctx, order);
broadcast_p2p_msg(&ctx, vec![topic], encoded_msg, peer_id);
}
fn process_my_maker_order_updated(ctx: &MmArc, message: &new_protocol::MakerOrderUpdated) {
let ordermatch_ctx = OrdermatchContext::from_ctx(ctx).expect("from_ctx failed");
let mut orderbook = ordermatch_ctx.orderbook.lock();
let uuid = message.uuid();
if let Some(mut order) = orderbook.find_order_by_uuid(&uuid) {
order.apply_updated(message);
orderbook.insert_or_update_order_update_trie(order);
}
}
fn maker_order_updated_p2p_notify(
ctx: MmArc,
topic: String,
message: new_protocol::MakerOrderUpdated,
p2p_privkey: Option<&KeyPair>,
) {
let msg: new_protocol::OrdermatchMessage = message.clone().into();
let (secret, peer_id) = match p2p_privkey {
Some(k) => (k.private_bytes(), Some(k.libp2p_peer_id())),
None => (ctx.secp256k1_key_pair().private_bytes(), None),
};
let encoded_msg = encode_and_sign(&msg, &secret).unwrap();
process_my_maker_order_updated(&ctx, &message);
broadcast_p2p_msg(&ctx, vec![topic], encoded_msg, peer_id);
}
fn maker_order_cancelled_p2p_notify(ctx: MmArc, order: &MakerOrder) {
let message = new_protocol::OrdermatchMessage::MakerOrderCancelled(new_protocol::MakerOrderCancelled {
uuid: order.uuid.into(),
timestamp: now_ms() / 1000,
pair_trie_root: H64::default(),
});
delete_my_order(&ctx, order.uuid);
log::debug!("maker_order_cancelled_p2p_notify called, message {:?}", message);
broadcast_ordermatch_message(&ctx, vec![order.orderbook_topic()], message, order.p2p_keypair());
}
pub struct BalanceUpdateOrdermatchHandler {
ctx: MmWeak,
}
impl BalanceUpdateOrdermatchHandler {
pub fn new(ctx: MmArc) -> Self { BalanceUpdateOrdermatchHandler { ctx: ctx.weak() } }
}
#[async_trait]
impl BalanceTradeFeeUpdatedHandler for BalanceUpdateOrdermatchHandler {
async fn balance_updated(&self, coin: &MmCoinEnum, new_balance: &BigDecimal) {
let ctx = match MmArc::from_weak(&self.ctx) {