forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
mm2_tests.rs
7530 lines (6838 loc) · 268 KB
/
mm2_tests.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
use super::{lp_main, LpMainParams};
use crate::mm2::lp_ordermatch::MIN_ORDER_KEEP_ALIVE_INTERVAL;
use common::executor::Timer;
use common::log::LogLevel;
use common::now_ms;
use crypto::privkey::key_pair_from_seed;
use http::{HeaderMap, StatusCode};
use mm2_metrics::{MetricType, MetricsJson};
use mm2_number::{BigDecimal, BigRational, Fraction, MmNumber};
use mm2_test_helpers::for_tests::{check_my_swap_status, check_recent_swaps, check_stats_swap_status,
enable_native as enable_native_impl, enable_qrc20, find_metrics_in_json,
from_env_file, init_z_coin_light, init_z_coin_status, mm_spat, morty_conf,
rick_conf, sign_message, verify_message, wait_till_history_has_records, LocalStart,
MarketMakerIt, Mm2TestConf, RaiiDump, MAKER_ERROR_EVENTS, MAKER_SUCCESS_EVENTS,
MORTY, RICK, TAKER_ERROR_EVENTS, TAKER_SUCCESS_EVENTS};
use serde_json::{self as json, Value as Json};
use std::collections::HashMap;
use std::convert::{identity, TryFrom};
use std::env::{self, var};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::thread;
use std::time::Duration;
use uuid::Uuid;
#[cfg(all(feature = "zhtlc-native-tests", not(target_arch = "wasm32")))]
use mm2_test_helpers::for_tests::init_z_coin_native;
#[cfg(all(feature = "zhtlc-native-tests", not(target_arch = "wasm32")))]
async fn enable_z_coin(mm: &MarketMakerIt, coin: &str) -> ZcoinActivationResult {
let init = init_z_coin_native(mm, coin).await;
let init: RpcV2Response<InitTaskResult> = json::from_value(init).unwrap();
let timeout = now_ms() + 120000;
loop {
if gstuff::now_ms() > timeout {
panic!("{} initialization timed out", coin);
}
let status = init_z_coin_status(mm, init.result.task_id).await;
let status: RpcV2Response<InitZcoinStatus> = json::from_value(status).unwrap();
if let InitZcoinStatus::Ready(rpc_result) = status.result {
match rpc_result {
MmRpcResult::Ok { result } => break result,
MmRpcResult::Err(e) => panic!("{} initialization error {:?}", coin, e),
}
}
Timer::sleep(1.).await;
}
}
cfg_native! {
use common::block_on;
use mm2_test_helpers::for_tests::{get_passphrase, new_mm2_temp_folder_path};
use mm2_io::fs::slurp;
use hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN;
}
cfg_wasm32! {
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
}
#[cfg(not(target_arch = "wasm32"))]
macro_rules! local_start {
($who: expr) => {
match var("LOCAL_THREAD_MM") {
Ok(ref e) if e == $who => Some(local_start()),
_ => None,
}
};
}
#[cfg(target_arch = "wasm32")]
macro_rules! local_start {
($who: expr) => {
Some(local_start())
};
}
#[path = "mm2_tests/bch_and_slp_tests.rs"] mod bch_and_slp_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "mm2_tests/best_orders_tests.rs"]
mod best_orders_tests;
#[path = "mm2_tests/electrums.rs"] pub mod electrums;
use electrums::*;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "mm2_tests/lightning_tests.rs"]
mod lightning_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "mm2_tests/lp_bot_tests.rs"]
mod lp_bot_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "mm2_tests/orderbook_sync_tests.rs"]
mod orderbook_sync_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "mm2_tests/tendermint_tests.rs"]
mod tendermint_tests;
#[cfg(all(test, not(target_arch = "wasm32")))]
#[path = "mm2_tests/z_coin_tests.rs"]
mod z_coin_tests;
#[path = "mm2_tests/structs.rs"] pub mod structs;
use structs::*;
// TODO: Consider and/or try moving the integration tests into separate Rust files.
// "Tests in your src files should be unit tests, and tests in tests/ should be integration-style tests."
// - https://doc.rust-lang.org/cargo/guide/tests.html
/// Ideally, this function should be replaced everywhere with `enable_electrum_json`.
async fn enable_electrum(mm: &MarketMakerIt, coin: &str, tx_history: bool, urls: &[&str]) -> EnableElectrumResponse {
use mm2_test_helpers::for_tests::enable_electrum as enable_electrum_impl;
let value = enable_electrum_impl(mm, coin, tx_history, urls).await;
json::from_value(value).unwrap()
}
async fn enable_electrum_json(
mm: &MarketMakerIt,
coin: &str,
tx_history: bool,
servers: Vec<Json>,
) -> EnableElectrumResponse {
use mm2_test_helpers::for_tests::enable_electrum_json as enable_electrum_impl;
let value = enable_electrum_impl(mm, coin, tx_history, servers).await;
json::from_value(value).unwrap()
}
async fn enable_native(mm: &MarketMakerIt, coin: &str, urls: &[&str]) -> EnableElectrumResponse {
let value = enable_native_impl(mm, coin, urls).await;
json::from_value(value).unwrap()
}
async fn enable_coins_rick_morty_electrum(mm: &MarketMakerIt) -> HashMap<&'static str, EnableElectrumResponse> {
let mut replies = HashMap::new();
replies.insert("RICK", enable_electrum_json(mm, "RICK", false, rick_electrums()).await);
replies.insert(
"MORTY",
enable_electrum_json(mm, "MORTY", false, morty_electrums()).await,
);
replies
}
async fn enable_coins_eth_electrum(
mm: &MarketMakerIt,
eth_urls: &[&str],
) -> HashMap<&'static str, EnableElectrumResponse> {
let mut replies = HashMap::new();
replies.insert("RICK", enable_electrum_json(mm, "RICK", false, rick_electrums()).await);
replies.insert(
"MORTY",
enable_electrum_json(mm, "MORTY", false, morty_electrums()).await,
);
replies.insert("ETH", enable_native(mm, "ETH", eth_urls).await);
replies.insert("JST", enable_native(mm, "JST", eth_urls).await);
replies
}
fn addr_from_enable<'a>(enable_response: &'a HashMap<&str, EnableElectrumResponse>, coin: &str) -> &'a str {
&enable_response.get(coin).unwrap().address
}
fn rmd160_from_passphrase(passphrase: &str) -> [u8; 20] {
key_pair_from_seed(passphrase).unwrap().public().address_hash().take()
}
async fn enable_z_coin_light(
mm: &MarketMakerIt,
coin: &str,
electrums: &[&str],
lightwalletd_urls: &[&str],
) -> ZcoinActivationResult {
let init = init_z_coin_light(mm, coin, electrums, lightwalletd_urls).await;
let init: RpcV2Response<InitTaskResult> = json::from_value(init).unwrap();
let timeout = now_ms() + 12000000;
loop {
if now_ms() > timeout {
panic!("{} initialization timed out", coin);
}
let status = init_z_coin_status(mm, init.result.task_id).await;
println!("Status {}", json::to_string(&status).unwrap());
let status: RpcV2Response<InitZcoinStatus> = json::from_value(status).unwrap();
if let InitZcoinStatus::Ready(rpc_result) = status.result {
match rpc_result {
MmRpcResult::Ok { result } => {
break result;
},
MmRpcResult::Err(e) => panic!("{} initialization error {:?}", coin, e),
}
}
Timer::sleep(1.).await;
}
}
/// Integration test for RPC server.
/// Check that MM doesn't crash in case of invalid RPC requests
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_rpc() {
let (_, mm, _dump_log, _dump_dashboard) = mm_spat(local_start(), &identity);
let no_method = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"coin": "RICK",
"ipaddr": "electrum1.cipig.net",
"port": 10017
})))
.unwrap();
assert!(no_method.0.is_server_error());
assert_eq!((no_method.2)[ACCESS_CONTROL_ALLOW_ORIGIN], "http://localhost:4000");
let not_json = mm.rpc_str("It's just a string").unwrap();
assert!(not_json.0.is_server_error());
assert_eq!((not_json.2)[ACCESS_CONTROL_ALLOW_ORIGIN], "http://localhost:4000");
let unknown_method = block_on(mm.rpc(&json! ({
"method": "unknown_method",
})))
.unwrap();
assert!(unknown_method.0.is_server_error());
assert_eq!((unknown_method.2)[ACCESS_CONTROL_ALLOW_ORIGIN], "http://localhost:4000");
let version = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"method": "version",
})))
.unwrap();
assert_eq!(version.0, StatusCode::OK);
assert_eq!((version.2)[ACCESS_CONTROL_ALLOW_ORIGIN], "http://localhost:4000");
let _version: MmVersion = json::from_str(&version.1).unwrap();
let help = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"method": "help",
})))
.unwrap();
assert_eq!(help.0, StatusCode::OK);
assert_eq!((help.2)[ACCESS_CONTROL_ALLOW_ORIGIN], "http://localhost:4000");
block_on(mm.stop()).unwrap();
// unwrap! (mm.wait_for_log (9., &|log| log.contains ("on_stop] firing shutdown_tx!")));
// TODO (workaround libtorrent hanging in delete) // unwrap! (mm.wait_for_log (9., &|log| log.contains ("LogState] Bye!")));
}
/// This is not a separate test but a helper used by `MarketMakerIt` to run the MarketMaker from the test binary.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_mm_start() {
if let Ok(conf) = var("_MM2_TEST_CONF") {
if let Ok(log_var) = var("RUST_LOG") {
if let Ok(filter) = LogLevel::from_str(&log_var) {
log!("test_mm_start] Starting the MarketMaker...");
let conf: Json = json::from_str(&conf).unwrap();
let params = LpMainParams::with_conf(conf).log_filter(Some(filter));
block_on(lp_main(params, &|_ctx| ())).unwrap()
}
}
}
}
#[allow(unused_variables)]
fn chdir(dir: &Path) {
#[cfg(not(target_arch = "wasm32"))]
{
#[cfg(not(windows))]
{
use std::ffi::CString;
let dir_s = dir.to_str().unwrap();
let dir_c = CString::new(dir_s).unwrap();
let rc = unsafe { libc::chdir(dir_c.as_ptr()) };
assert_eq!(rc, 0, "Can not chdir to {:?}", dir);
}
#[cfg(windows)]
{
use std::ffi::CString;
use winapi::um::processenv::SetCurrentDirectoryA;
let dir = dir.to_str().unwrap();
let dir = CString::new(dir).unwrap();
// https://docs.microsoft.com/en-us/windows/desktop/api/WinBase/nf-winbase-setcurrentdirectory
let rc = unsafe { SetCurrentDirectoryA(dir.as_ptr()) };
assert_ne!(rc, 0);
}
}
}
/// Typically used when the `LOCAL_THREAD_MM` env is set, helping debug the tested MM.
/// NB: Accessing `lp_main` this function have to reside in the mm2 binary crate. We pass a pointer to it to subcrates.
#[cfg(not(target_arch = "wasm32"))]
fn local_start_impl(folder: PathBuf, log_path: PathBuf, mut conf: Json) {
thread::Builder::new()
.name("MM".into())
.spawn(move || {
if conf["log"].is_null() {
conf["log"] = log_path.to_str().unwrap().into();
} else {
let path = Path::new(conf["log"].as_str().expect("log is not a string"));
assert_eq!(log_path, path);
}
log!("local_start] MM in a thread, log {:?}.", log_path);
chdir(&folder);
let params = LpMainParams::with_conf(conf);
block_on(lp_main(params, &|_ctx| ())).unwrap()
})
.unwrap();
}
/// Starts the WASM version of MM.
#[cfg(target_arch = "wasm32")]
fn wasm_start_impl(ctx: mm2_core::mm_ctx::MmArc) {
common::executor::spawn(async move {
super::lp_init(ctx).await.unwrap();
})
}
#[cfg(not(target_arch = "wasm32"))]
fn local_start() -> LocalStart { local_start_impl }
#[cfg(target_arch = "wasm32")]
fn local_start() -> LocalStart { wasm_start_impl }
/// https://github.com/KomodoPlatform/atomicDEX-API/issues/886#issuecomment-812489844
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn orders_of_banned_pubkeys_should_not_be_displayed() {
let coins = json!([
{"coin":"RICK","asset":"RICK","rpcport":8923,"txversion":4,"overwintered":1,"protocol":{"type":"UTXO"}},
{"coin":"MORTY","asset":"MORTY","rpcport":11608,"txversion":4,"overwintered":1,"protocol":{"type":"UTXO"}}
]);
// start bob and immediately place the order
let mm_bob = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"myipaddr": env::var ("BOB_TRADE_IP") .ok(),
"rpcip": env::var ("BOB_TRADE_IP") .ok(),
"canbind": env::var ("BOB_TRADE_PORT") .ok().map (|s| s.parse::<i64>().unwrap()),
"passphrase": "bob passphrase",
"coins": coins,
"rpc_password": "pass",
"i_am_seed": true,
}),
"pass".into(),
local_start!("bob"),
)
.unwrap();
let (_bob_dump_log, _bob_dump_dashboard) = mm_bob.mm_dump();
log!("Bob log path: {}", mm_bob.log_path.display());
// Enable coins on Bob side. Print the replies in case we need the "address".
log!(
"enable_coins (bob): {:?}",
block_on(enable_coins_rick_morty_electrum(&mm_bob))
);
// issue sell request on Bob side by setting base/rel price
log!("Issue bob sell request");
let rc = block_on(mm_bob.rpc(&json! ({
"userpass": mm_bob.userpass,
"method": "setprice",
"base": "RICK",
"rel": "MORTY",
"price": 0.9,
"volume": "0.9",
})))
.unwrap();
assert!(rc.0.is_success(), "!setprice: {}", rc.1);
let mut mm_alice = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"myipaddr": env::var ("ALICE_TRADE_IP") .ok(),
"rpcip": env::var ("ALICE_TRADE_IP") .ok(),
"passphrase": "alice passphrase",
"coins": coins,
"seednodes": [mm_bob.ip.to_string()],
"rpc_password": "pass",
}),
"pass".into(),
local_start!("alice"),
)
.unwrap();
let (_alice_dump_log, _alice_dump_dashboard) = mm_alice.mm_dump();
log!("Alice log path: {}", mm_alice.log_path.display());
log!("Ban Bob pubkey on Alice side");
let rc = block_on(mm_alice.rpc(&json! ({
"userpass": mm_alice.userpass,
"method": "ban_pubkey",
"pubkey": "2cd3021a2197361fb70b862c412bc8e44cff6951fa1de45ceabfdd9b4c520420",
"reason": "test",
})))
.unwrap();
assert!(rc.0.is_success(), "!ban_pubkey: {}", rc.1);
log!("Get RICK/MORTY orderbook on Alice side");
let rc = block_on(mm_alice.rpc(&json! ({
"userpass": mm_alice.userpass,
"method": "orderbook",
"base": "RICK",
"rel": "MORTY",
})))
.unwrap();
assert!(rc.0.is_success(), "!orderbook: {}", rc.1);
let alice_orderbook: OrderbookResponse = json::from_str(&rc.1).unwrap();
log!("Alice orderbook {:?}", alice_orderbook);
assert_eq!(
alice_orderbook.asks.len(),
0,
"Alice RICK/MORTY orderbook must have no asks"
);
block_on(mm_alice.wait_for_log(22., |log| {
log.contains("Pubkey 022cd3021a2197361fb70b862c412bc8e44cff6951fa1de45ceabfdd9b4c520420 is banned")
}))
.unwrap();
block_on(mm_bob.stop()).unwrap();
block_on(mm_alice.stop()).unwrap();
}
#[test]
fn log_test_status() { common::log::tests::test_status() }
#[test]
fn log_test_printed_dashboard() { common::log::tests::test_printed_dashboard() }
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_my_balance() {
let coins = json!([
{"coin":"RICK","asset":"RICK","rpcport":8923,"txversion":4,"overwintered":1,"protocol":{"type":"UTXO"}},
]);
let mm = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"myipaddr": env::var ("BOB_TRADE_IP") .ok(),
"rpcip": env::var ("BOB_TRADE_IP") .ok(),
"passphrase": "bob passphrase",
"coins": coins,
"i_am_seed": true,
"rpc_password": "pass",
}),
"pass".into(),
local_start!("bob"),
)
.unwrap();
let (_dump_log, _dump_dashboard) = mm.mm_dump();
log!("log path: {}", mm.log_path.display());
// Enable RICK.
let json = block_on(enable_electrum(&mm, "RICK", false, &[
"electrum1.cipig.net:10017",
"electrum2.cipig.net:10017",
"electrum3.cipig.net:10017",
]));
assert_eq!(json.balance, "7.777".parse().unwrap());
let my_balance = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"method": "my_balance",
"coin": "RICK",
})))
.unwrap();
assert_eq!(
my_balance.0,
StatusCode::OK,
"RPC «my_balance» failed with status «{}»",
my_balance.0
);
let json: Json = json::from_str(&my_balance.1).unwrap();
let my_balance = json["balance"].as_str().unwrap();
assert_eq!(my_balance, "7.777");
let my_unspendable_balance = json["unspendable_balance"].as_str().unwrap();
assert_eq!(my_unspendable_balance, "0");
let my_address = json["address"].as_str().unwrap();
assert_eq!(my_address, "RRnMcSeKiLrNdbp91qNVQwwXx5azD4S4CD");
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_p2wpkh_my_balance() {
let seed = "valley embody about obey never adapt gesture trust screen tube glide bread";
let coins = json! ([
{
"coin": "tBTC",
"name": "tbitcoin",
"fname": "tBitcoin",
"rpcport": 18332,
"pubtype": 111,
"p2shtype": 196,
"wiftype": 239,
"segwit": true,
"bech32_hrp": "tb",
"txfee": 0,
"estimate_fee_mode": "ECONOMICAL",
"mm2": 1,
"required_confirmations": 0,
"protocol": {
"type": "UTXO"
},
"address_format": {
"format":"segwit"
}
}
]);
let mm = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"myipaddr": env::var ("BOB_TRADE_IP") .ok(),
"rpcip": env::var ("BOB_TRADE_IP") .ok(),
"passphrase": seed.to_string(),
"coins": coins,
"i_am_seed": true,
"rpc_password": "pass",
}),
"pass".into(),
local_start!("bob"),
)
.unwrap();
let (_dump_log, _dump_dashboard) = mm.mm_dump();
log!("log path: {}", mm.log_path.display());
let electrum = block_on(mm.rpc(&json!({
"userpass": mm.userpass,
"method": "electrum",
"coin": "tBTC",
"servers": [{"url":"electrum1.cipig.net:10068"},{"url":"electrum2.cipig.net:10068"},{"url":"electrum3.cipig.net:10068"}],
"mm2": 1,
"address_format": {
"format": "segwit",
},
}))).unwrap();
assert_eq!(
electrum.0,
StatusCode::OK,
"RPC «electrum» failed with {} {}",
electrum.0,
electrum.1
);
let my_balance = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"method": "my_balance",
"coin": "tBTC",
})))
.unwrap();
let json: Json = json::from_str(&my_balance.1).unwrap();
let my_balance = json["balance"].as_str().unwrap();
assert_eq!(my_balance, "0.002");
let my_unspendable_balance = json["unspendable_balance"].as_str().unwrap();
assert_eq!(my_unspendable_balance, "0");
let my_address = json["address"].as_str().unwrap();
assert_eq!(my_address, "tb1qssfmay8nnghx7ynlznejnjxn6m4pemz9v7fsxy");
}
#[cfg(not(target_arch = "wasm32"))]
fn check_set_price_fails(mm: &MarketMakerIt, base: &str, rel: &str) {
let rc = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"method": "setprice",
"base": base,
"rel": rel,
"price": 0.9,
"volume": 1,
})))
.unwrap();
assert!(
rc.0.is_server_error(),
"!setprice success but should be error: {}",
rc.1
);
}
#[cfg(not(target_arch = "wasm32"))]
fn check_buy_fails(mm: &MarketMakerIt, base: &str, rel: &str, vol: f64) {
let rc = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"method": "buy",
"base": base,
"rel": rel,
"volume": vol,
"price": 0.9
})))
.unwrap();
assert!(rc.0.is_server_error(), "!buy success but should be error: {}", rc.1);
}
#[cfg(not(target_arch = "wasm32"))]
fn check_sell_fails(mm: &MarketMakerIt, base: &str, rel: &str, vol: f64) {
let rc = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"method": "sell",
"base": base,
"rel": rel,
"volume": vol,
"price": 0.9
})))
.unwrap();
assert!(rc.0.is_server_error(), "!sell success but should be error: {}", rc.1);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_check_balance_on_order_post() {
let coins = json!([
{"coin":"RICK","asset":"RICK","rpcport":8923,"txversion":4,"overwintered":1,"protocol":{"type":"UTXO"}},
{"coin":"MORTY","asset":"MORTY","rpcport":11608,"txversion":4,"overwintered":1,"protocol":{"type":"UTXO"}},
{"coin":"ETH","name":"ethereum","protocol":{"type":"ETH"},"rpcport":80},
{"coin":"JST","name":"jst","protocol":{"type":"ERC20", "protocol_data":{"platform":"ETH","contract_address":"0x996a8aE0304680F6A69b8A9d7C6E37D65AB5AB56"}}}
]);
// start bob and immediately place the order
let mm = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"myipaddr": env::var ("BOB_TRADE_IP") .ok(),
"rpcip": env::var ("BOB_TRADE_IP") .ok(),
"canbind": env::var ("BOB_TRADE_PORT") .ok().map (|s| s.parse::<i64>().unwrap()),
"passphrase": "bob passphrase check balance on order post",
"coins": coins,
"i_am_seed": true,
"rpc_password": "pass",
}),
"pass".into(),
local_start!("bob"),
)
.unwrap();
let (_dump_log, _dump_dashboard) = mm.mm_dump();
log!("Log path: {}", mm.log_path.display());
// Enable coins. Print the replies in case we need the "address".
log!(
"enable_coins (bob): {:?}",
block_on(enable_coins_eth_electrum(&mm, &["http://eth1.cipig.net:8555"]))
);
// issue sell request by setting base/rel price
// Expect error as MORTY balance is 0
check_set_price_fails(&mm, "MORTY", "RICK");
// Address has enough RICK, but doesn't have ETH, so setprice call should fail because maker will not have gas to spend ETH taker payment.
check_set_price_fails(&mm, "RICK", "ETH");
// Address has enough RICK, but doesn't have ETH, so setprice call should fail because maker will not have gas to spend ERC20 taker payment.
check_set_price_fails(&mm, "RICK", "JST");
// Expect error as MORTY balance is 0
check_buy_fails(&mm, "RICK", "MORTY", 0.1);
// RICK balance is sufficient, but amount is too small, it will result to dust error from RPC
check_buy_fails(&mm, "MORTY", "RICK", 0.000001);
// Address has enough RICK, but doesn't have ETH, so buy call should fail because taker will not have gas to spend ETH maker payment.
check_buy_fails(&mm, "ETH", "RICK", 0.1);
// Address has enough RICK, but doesn't have ETH, so buy call should fail because taker will not have gas to spend ERC20 maker payment.
check_buy_fails(&mm, "JST", "RICK", 0.1);
// Expect error as MORTY balance is 0
check_sell_fails(&mm, "MORTY", "RICK", 0.1);
// RICK balance is sufficient, but amount is too small, the dex fee will result to dust error from RPC
check_sell_fails(&mm, "RICK", "MORTY", 0.000001);
// Address has enough RICK, but doesn't have ETH, so buy call should fail because taker will not have gas to spend ETH maker payment.
check_sell_fails(&mm, "RICK", "ETH", 0.1);
// Address has enough RICK, but doesn't have ETH, so buy call should fail because taker will not have gas to spend ERC20 maker payment.
check_sell_fails(&mm, "RICK", "JST", 0.1);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_rpc_password_from_json() {
let coins = json!([
{"coin":"RICK","asset":"RICK","rpcport":8923,"txversion":4,"overwintered":1,"protocol":{"type":"UTXO"}},
{"coin":"MORTY","asset":"MORTY","rpcport":8923,"txversion":4,"overwintered":1,"protocol":{"type":"UTXO"}},
]);
// do not allow empty password
let mut err_mm1 = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"passphrase": "bob passphrase",
"coins": coins,
"rpc_password": "",
"i_am_seed": true,
"skip_startup_checks": true,
}),
"password".into(),
local_start!("bob"),
)
.unwrap();
block_on(err_mm1.wait_for_log(5., |log| log.contains("rpc_password must not be empty"))).unwrap();
// do not allow empty password
let mut err_mm2 = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"passphrase": "bob passphrase",
"coins": coins,
"rpc_password": {"key":"value"},
"i_am_seed": true,
"skip_startup_checks": true,
}),
"password".into(),
local_start!("bob"),
)
.unwrap();
block_on(err_mm2.wait_for_log(5., |log| log.contains("rpc_password must be string"))).unwrap();
let mm = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"passphrase": "bob passphrase",
"coins": coins,
"rpc_password": "password",
"i_am_seed": true,
}),
"password".into(),
local_start!("bob"),
)
.unwrap();
let (_dump_log, _dump_dashboard) = mm.mm_dump();
log!("Log path: {}", mm.log_path.display());
let electrum_invalid = block_on(mm.rpc(&json! ({
"userpass": "password1",
"method": "electrum",
"coin": "RICK",
"servers": [{"url":"electrum1.cipig.net:10017"},{"url":"electrum2.cipig.net:10017"},{"url":"electrum3.cipig.net:10017"}],
"mm2": 1,
}))).unwrap();
// electrum call must fail if invalid password is provided
assert!(
electrum_invalid.0.is_server_error(),
"RPC «electrum» should have failed with server error, but got «{}», response «{}»",
electrum_invalid.0,
electrum_invalid.1
);
let electrum = block_on(mm.rpc(&json!({
"userpass": mm.userpass,
"method": "electrum",
"coin": "RICK",
"servers": [{"url":"electrum1.cipig.net:10017"},{"url":"electrum2.cipig.net:10017"},{"url":"electrum3.cipig.net:10017"}],
"mm2": 1,
}))).unwrap();
// electrum call must be successful with RPC password from config
assert_eq!(
electrum.0,
StatusCode::OK,
"RPC «electrum» failed with status «{}», response «{}»",
electrum.0,
electrum.1
);
let electrum = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"method": "electrum",
"coin": "MORTY",
"servers": [{"url":"electrum1.cipig.net:10018"},{"url":"electrum2.cipig.net:10018"},{"url":"electrum3.cipig.net:10018"}],
"mm2": 1,
}))).unwrap();
// electrum call must be successful with RPC password from config
assert_eq!(
electrum.0,
StatusCode::OK,
"RPC «electrum» failed with status «{}», response «{}»",
electrum.0,
electrum.1
);
let orderbook = block_on(mm.rpc(&json! ({
"userpass": mm.userpass,
"method": "orderbook",
"base": "RICK",
"rel": "MORTY",
})))
.unwrap();
// orderbook call must be successful with RPC password from config
assert_eq!(
orderbook.0,
StatusCode::OK,
"RPC «orderbook» failed with status «{}», response «{}»",
orderbook.0,
orderbook.1
);
}
/// Currently only `withdraw` RPC call supports V2.
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_mmrpc_v2() {
let coins = json!([
{"coin":"RICK","asset":"RICK","rpcport":8923,"txversion":4,"protocol":{"type":"UTXO"}},
]);
let mm = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"passphrase": "bob passphrase",
"coins": coins,
"rpc_password": "password",
"i_am_seed": true,
}),
"password".into(),
local_start!("bob"),
)
.unwrap();
let (_dump_log, _dump_dashboard) = mm.mm_dump();
log!("Log path: {}", mm.log_path.display());
let _electrum = block_on(enable_electrum(&mm, "RICK", false, &[
"electrum3.cipig.net:10017",
"electrum2.cipig.net:10017",
"electrum1.cipig.net:10017",
]));
// no `userpass`
let withdraw = block_on(mm.rpc(&json! ({
"mmrpc": "2.0",
"method": "withdraw",
"params": {
"coin": "RICK",
"to": "RJTYiYeJ8eVvJ53n2YbrVmxWNNMVZjDGLh",
"amount": 0.001,
},
})))
.unwrap();
assert!(
withdraw.0.is_client_error(),
"withdraw should have failed, but got: {}",
withdraw.1
);
let withdraw_error: RpcErrorResponse<()> = json::from_str(&withdraw.1).expect("Expected 'RpcErrorResponse'");
assert_eq!(withdraw_error.error_type, "UserpassIsNotSet");
assert!(withdraw_error.error_data.is_none());
// invalid `userpass`
let withdraw = block_on(mm.rpc(&json! ({
"mmrpc": "2.0",
"userpass": "another password",
"method": "withdraw",
"params": {
"coin": "RICK",
"to": "RJTYiYeJ8eVvJ53n2YbrVmxWNNMVZjDGLh",
"amount": 0.001,
},
})))
.unwrap();
assert!(
withdraw.0.is_client_error(),
"withdraw should have failed, but got: {}",
withdraw.1
);
let withdraw_error: RpcErrorResponse<Json> = json::from_str(&withdraw.1).expect("Expected 'RpcErrorResponse'");
assert_eq!(withdraw_error.error_type, "UserpassIsInvalid");
assert!(withdraw_error.error_data.is_some());
// invalid `mmrpc` version
let withdraw = block_on(mm.rpc(&json! ({
"mmrpc": "1.0",
"userpass": mm.userpass,
"method": "withdraw",
"params": {
"coin": "RICK",
"to": "RJTYiYeJ8eVvJ53n2YbrVmxWNNMVZjDGLh",
"amount": 0.001,
},
})))
.unwrap();
assert!(
withdraw.0.is_client_error(),
"withdraw should have failed, but got: {}",
withdraw.1
);
log!("{:?}", withdraw.1);
let withdraw_error: RpcErrorResponse<String> = json::from_str(&withdraw.1).expect("Expected 'RpcErrorResponse'");
assert_eq!(withdraw_error.error_type, "InvalidMmRpcVersion");
// 'id' = 3
let withdraw = block_on(mm.rpc(&json! ({
"mmrpc": "2.0",
"userpass": mm.userpass,
"method": "withdraw",
"params": {
"coin": "RICK",
"to": "RJTYiYeJ8eVvJ53n2YbrVmxWNNMVZjDGLh",
"amount": 0.001,
},
"id": 3,
})))
.unwrap();
assert!(withdraw.0.is_success(), "!withdraw: {}", withdraw.1);
let withdraw_ok: RpcSuccessResponse<TransactionDetails> =
json::from_str(&withdraw.1).expect("Expected 'RpcSuccessResponse<TransactionDetails>'");
assert_eq!(withdraw_ok.id, Some(3));
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_rpc_password_from_json_no_userpass() {
let coins = json!([
{"coin":"RICK","asset":"RICK","rpcport":8923,"txversion":4,"protocol":{"type":"UTXO"}},
]);
let mm = MarketMakerIt::start(
json! ({
"gui": "nogui",
"netid": 9998,
"passphrase": "bob passphrase",
"coins": coins,
"i_am_seed": true,
}),
"password".into(),
local_start!("bob"),
)
.unwrap();
let (_dump_log, _dump_dashboard) = mm.mm_dump();
log!("Log path: {}", mm.log_path.display());
let electrum = block_on(mm.rpc(&json! ({
"method": "electrum",
"coin": "RICK",
"urls": ["electrum2.cipig.net:10017"],
})))
.unwrap();
// electrum call must return 500 status code
assert!(
electrum.0.is_server_error(),
"RPC «electrum» should have failed with server error, but got «{}», response «{}»",
electrum.0,
electrum.1
);
}
/// Trading test using coins with remote RPC (Electrum, ETH nodes), it needs only ENV variables to be set, coins daemons are not required.
/// Trades few pairs concurrently to speed up the process and also act like "load" test
async fn trade_base_rel_electrum(
pairs: &[(&'static str, &'static str)],
maker_price: i32,
taker_price: i32,
volume: f64,
) {
use mm2_test_helpers::get_passphrase;
let bob_passphrase = get_passphrase!(".env.seed", "BOB_PASSPHRASE").unwrap();
let alice_passphrase = get_passphrase!(".env.client", "ALICE_PASSPHRASE").unwrap();
let coins = json! ([
{"coin":"RICK","asset":"RICK","required_confirmations":0,"txversion":4,"overwintered":1,"protocol":{"type":"UTXO"}},
{"coin":"MORTY","asset":"MORTY","required_confirmations":0,"txversion":4,"overwintered":1,"protocol":{"type":"UTXO"}},
{"coin":"ETH","name":"ethereum","protocol":{"type":"ETH"}},
{"coin":"ZOMBIE","asset":"ZOMBIE","fname":"ZOMBIE (TESTCOIN)","txversion":4,"overwintered":1,"mm2":1,"protocol":{"type":"ZHTLC"},"required_confirmations":0},
{"coin":"JST","name":"jst","protocol":{"type":"ERC20","protocol_data":{"platform":"ETH","contract_address":"0x2b294F029Fde858b2c62184e8390591755521d8E"}}}
]);
let mut mm_bob = MarketMakerIt::start_async(
json! ({
"gui": "nogui",
"netid": 8999,
"dht": "on", // Enable DHT without delay.
"myipaddr": env::var ("BOB_TRADE_IP") .ok(),
"rpcip": env::var ("BOB_TRADE_IP") .ok(),
"canbind": env::var ("BOB_TRADE_PORT") .ok().map (|s| s.parse::<i64>().unwrap()),
"passphrase": bob_passphrase,
"coins": coins,
"rpc_password": "password",
"i_am_seed": true,
}),
"password".into(),
local_start!("bob"),
)
.await
.unwrap();