forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
utxo_tests.rs
4665 lines (4154 loc) · 224 KB
/
utxo_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::*;
use crate::coin_balance::HDAddressBalance;
use crate::coin_errors::ValidatePaymentError;
use crate::hd_confirm_address::for_tests::MockableConfirmAddress;
use crate::hd_confirm_address::{HDConfirmAddress, HDConfirmAddressError};
use crate::hd_wallet::HDAccountsMap;
use crate::hd_wallet_storage::{HDWalletMockStorage, HDWalletStorageInternalOps};
use crate::my_tx_history_v2::for_tests::init_storage_for;
use crate::my_tx_history_v2::CoinWithTxHistoryV2;
use crate::rpc_command::account_balance::{AccountBalanceParams, AccountBalanceRpcOps, HDAccountBalanceResponse};
use crate::rpc_command::get_new_address::{GetNewAddressParams, GetNewAddressRpcError, GetNewAddressRpcOps};
use crate::rpc_command::init_scan_for_new_addresses::{InitScanAddressesRpcOps, ScanAddressesParams,
ScanAddressesResponse};
use crate::utxo::qtum::{qtum_coin_with_priv_key, QtumCoin, QtumDelegationOps, QtumDelegationRequest};
#[cfg(not(target_arch = "wasm32"))]
use crate::utxo::rpc_clients::{BlockHashOrHeight, NativeUnspent};
use crate::utxo::rpc_clients::{ElectrumBalance, ElectrumClient, ElectrumClientImpl, GetAddressInfoRes,
ListSinceBlockRes, NativeClient, NativeClientImpl, NetworkInfo, UtxoRpcClientOps,
ValidateAddressRes, VerboseBlock};
use crate::utxo::spv::SimplePaymentVerification;
#[cfg(not(target_arch = "wasm32"))]
use crate::utxo::utxo_block_header_storage::{BlockHeaderStorage, SqliteBlockHeadersStorage};
use crate::utxo::utxo_builder::{UtxoArcBuilder, UtxoCoinBuilder, UtxoCoinBuilderCommonOps};
use crate::utxo::utxo_common::UtxoTxBuilder;
#[cfg(not(target_arch = "wasm32"))]
use crate::utxo::utxo_common_tests::TEST_COIN_DECIMALS;
use crate::utxo::utxo_common_tests::{self, utxo_coin_fields_for_test, utxo_coin_from_fields, TEST_COIN_NAME};
use crate::utxo::utxo_standard::{utxo_standard_coin_with_priv_key, UtxoStandardCoin};
use crate::utxo::utxo_tx_history_v2::{UtxoTxDetailsParams, UtxoTxHistoryOps};
#[cfg(not(target_arch = "wasm32"))] use crate::WithdrawFee;
use crate::{BlockHeightAndTime, CoinBalance, ConfirmPaymentInput, IguanaPrivKey, PrivKeyBuildPolicy,
SearchForSwapTxSpendInput, SpendPaymentArgs, StakingInfosDetails, SwapOps, TradePreimageValue,
TxFeeDetails, TxMarshalingErr, ValidateFeeArgs, WaitForHTLCTxSpendArgs, INVALID_SENDER_ERR_LOG};
use chain::{BlockHeader, BlockHeaderBits, OutPoint};
use common::executor::Timer;
use common::{block_on, wait_until_sec, OrdRange, PagingOptionsEnum, DEX_FEE_ADDR_RAW_PUBKEY};
use crypto::{privkey::key_pair_from_seed, Bip44Chain, RpcDerivationPath, Secp256k1Secret};
#[cfg(not(target_arch = "wasm32"))]
use db_common::sqlite::rusqlite::Connection;
use futures::channel::mpsc::channel;
use futures::future::join_all;
use futures::TryFutureExt;
use mm2_core::mm_ctx::MmCtxBuilder;
use mm2_number::bigdecimal::{BigDecimal, Signed};
use mm2_test_helpers::for_tests::{mm_ctx_with_custom_db, MORTY_ELECTRUM_ADDRS, RICK_ELECTRUM_ADDRS};
use mocktopus::mocking::*;
use rpc::v1::types::H256 as H256Json;
use serialization::{deserialize, CoinVariant};
use spv_validation::conf::{BlockHeaderValidationParams, SPVBlockHeader};
use spv_validation::storage::BlockHeaderStorageOps;
use spv_validation::work::DifficultyAlgorithm;
#[cfg(not(target_arch = "wasm32"))] use std::convert::TryFrom;
use std::iter;
use std::mem::discriminant;
use std::num::NonZeroUsize;
#[cfg(not(target_arch = "wasm32"))]
const TAKER_PAYMENT_SPEND_SEARCH_INTERVAL: f64 = 1.;
pub fn electrum_client_for_test(servers: &[&str]) -> ElectrumClient {
let ctx = MmCtxBuilder::default().into_mm_arc();
let servers: Vec<_> = servers.iter().map(|server| json!({ "url": server })).collect();
let req = json!({
"method": "electrum",
"servers": servers,
});
let params = UtxoActivationParams::from_legacy_req(&req).unwrap();
let priv_key_policy = PrivKeyBuildPolicy::IguanaPrivKey(IguanaPrivKey::default());
let builder = UtxoArcBuilder::new(
&ctx,
TEST_COIN_NAME,
&Json::Null,
¶ms,
priv_key_policy,
UtxoStandardCoin::from,
);
let args = ElectrumBuilderArgs {
spawn_ping: false,
negotiate_version: true,
collect_metrics: false,
};
let servers = servers.into_iter().map(|s| json::from_value(s).unwrap()).collect();
let abortable_system = AbortableQueue::default();
block_on(builder.electrum_client(abortable_system, args, servers)).unwrap()
}
/// Returned client won't work by default, requires some mocks to be usable
#[cfg(not(target_arch = "wasm32"))]
fn native_client_for_test() -> NativeClient { NativeClient(Arc::new(NativeClientImpl::default())) }
fn utxo_coin_for_test(
rpc_client: UtxoRpcClientEnum,
force_seed: Option<&str>,
is_segwit_coin: bool,
) -> UtxoStandardCoin {
utxo_coin_from_fields(utxo_coin_fields_for_test(rpc_client, force_seed, is_segwit_coin))
}
/// Returns `TransactionDetails` of the given `tx_hash` via [`UtxoStandardOps::tx_details_by_hash`].
#[track_caller]
fn get_tx_details_by_hash<Coin: UtxoStandardOps>(coin: &Coin, tx_hash: &str) -> TransactionDetails {
let hash = hex::decode(tx_hash).unwrap();
let mut input_transactions = HistoryUtxoTxMap::new();
block_on(UtxoStandardOps::tx_details_by_hash(
coin,
&hash,
&mut input_transactions,
))
.unwrap()
}
/// Returns `TransactionDetails` of the given `tx_hash` via [`UtxoTxHistoryOps::tx_details_by_hash`].
fn get_tx_details_by_hash_v2<Coin>(coin: &Coin, tx_hash: &str, height: u64, timestamp: u64) -> Vec<TransactionDetails>
where
Coin: CoinWithTxHistoryV2 + UtxoTxHistoryOps,
{
let my_addresses = block_on(coin.my_addresses()).unwrap();
let (_ctx, storage) = init_storage_for(coin);
let params = UtxoTxDetailsParams {
hash: &hex::decode(tx_hash).unwrap().as_slice().into(),
block_height_and_time: Some(BlockHeightAndTime { height, timestamp }),
storage: &storage,
my_addresses: &my_addresses,
};
block_on(UtxoTxHistoryOps::tx_details_by_hash(coin, params)).unwrap()
}
/// Returns `TransactionDetails` of the given `tx_hash` and checks that
/// [`UtxoTxHistoryOps::tx_details_by_hash`] and [`UtxoStandardOps::tx_details_by_hash`] return the same TX details.
#[track_caller]
fn get_tx_details_eq_for_both_versions<Coin>(coin: &Coin, tx_hash: &str) -> TransactionDetails
where
Coin: CoinWithTxHistoryV2 + UtxoTxHistoryOps + UtxoStandardOps,
{
let tx_details_v1 = get_tx_details_by_hash(coin, tx_hash);
let tx_details_v2 = get_tx_details_by_hash_v2(coin, tx_hash, tx_details_v1.block_height, tx_details_v1.timestamp);
assert_eq!(vec![tx_details_v1.clone()], tx_details_v2);
tx_details_v1
}
#[test]
fn test_extract_secret() {
let client = electrum_client_for_test(RICK_ELECTRUM_ADDRS);
let coin = utxo_coin_for_test(client.into(), None, false);
let tx_hex = hex::decode("0100000001de7aa8d29524906b2b54ee2e0281f3607f75662cbc9080df81d1047b78e21dbc00000000d7473044022079b6c50820040b1fbbe9251ced32ab334d33830f6f8d0bf0a40c7f1336b67d5b0220142ccf723ddabb34e542ed65c395abc1fbf5b6c3e730396f15d25c49b668a1a401209da937e5609680cb30bff4a7661364ca1d1851c2506fa80c443f00a3d3bf7365004c6b6304f62b0e5cb175210270e75970bb20029b3879ec76c4acd320a8d0589e003636264d01a7d566504bfbac6782012088a9142fb610d856c19fd57f2d0cffe8dff689074b3d8a882103f368228456c940ac113e53dad5c104cf209f2f102a409207269383b6ab9b03deac68ffffffff01d0dc9800000000001976a9146d9d2b554d768232320587df75c4338ecc8bf37d88ac40280e5c").unwrap();
let expected_secret = hex::decode("9da937e5609680cb30bff4a7661364ca1d1851c2506fa80c443f00a3d3bf7365").unwrap();
let secret_hash = &*dhash160(&expected_secret);
let secret = block_on(coin.extract_secret(secret_hash, &tx_hex, false)).unwrap();
assert_eq!(secret, expected_secret);
}
#[test]
fn test_send_maker_spends_taker_payment_recoverable_tx() {
let client = electrum_client_for_test(RICK_ELECTRUM_ADDRS);
let coin = utxo_coin_for_test(client.into(), None, false);
let tx_hex = hex::decode("0100000001de7aa8d29524906b2b54ee2e0281f3607f75662cbc9080df81d1047b78e21dbc00000000d7473044022079b6c50820040b1fbbe9251ced32ab334d33830f6f8d0bf0a40c7f1336b67d5b0220142ccf723ddabb34e542ed65c395abc1fbf5b6c3e730396f15d25c49b668a1a401209da937e5609680cb30bff4a7661364ca1d1851c2506fa80c443f00a3d3bf7365004c6b6304f62b0e5cb175210270e75970bb20029b3879ec76c4acd320a8d0589e003636264d01a7d566504bfbac6782012088a9142fb610d856c19fd57f2d0cffe8dff689074b3d8a882103f368228456c940ac113e53dad5c104cf209f2f102a409207269383b6ab9b03deac68ffffffff01d0dc9800000000001976a9146d9d2b554d768232320587df75c4338ecc8bf37d88ac40280e5c").unwrap();
let secret = hex::decode("9da937e5609680cb30bff4a7661364ca1d1851c2506fa80c443f00a3d3bf7365").unwrap();
let maker_spends_payment_args = SpendPaymentArgs {
other_payment_tx: &tx_hex,
time_lock: 777,
other_pubkey: coin.my_public_key().unwrap(),
secret: &secret,
secret_hash: &*dhash160(&secret),
swap_contract_address: &coin.swap_contract_address(),
swap_unique_data: &[],
watcher_reward: false,
};
let tx_err = coin
.send_maker_spends_taker_payment(maker_spends_payment_args)
.wait()
.unwrap_err();
let tx: UtxoTx = deserialize(tx_hex.as_slice()).unwrap();
// The error variant should equal to `TxRecoverable`
assert_eq!(
discriminant(&tx_err),
discriminant(&TransactionErr::TxRecoverable(TransactionEnum::from(tx), String::new()))
);
}
#[test]
fn test_generate_transaction() {
let client = electrum_client_for_test(RICK_ELECTRUM_ADDRS);
let coin = utxo_coin_for_test(client.into(), None, false);
let unspents = vec![UnspentInfo {
value: 10000000000,
outpoint: OutPoint::default(),
height: Default::default(),
}];
let outputs = vec![TransactionOutput {
script_pubkey: vec![].into(),
value: 999,
}];
let builder = UtxoTxBuilder::new(&coin)
.add_available_inputs(unspents)
.add_outputs(outputs);
let generated = block_on(builder.build());
// must not allow to use output with value < dust
generated.unwrap_err();
let unspents = vec![UnspentInfo {
value: 100000,
outpoint: OutPoint::default(),
height: Default::default(),
}];
let outputs = vec![TransactionOutput {
script_pubkey: vec![].into(),
value: 98001,
}];
let builder = UtxoTxBuilder::new(&coin)
.add_available_inputs(unspents)
.add_outputs(outputs);
let generated = block_on(builder.build()).unwrap();
// the change that is less than dust must be included to miner fee
// so no extra outputs should appear in generated transaction
assert_eq!(generated.0.outputs.len(), 1);
assert_eq!(generated.1.fee_amount, 1000);
assert_eq!(generated.1.unused_change, Some(999));
assert_eq!(generated.1.received_by_me, 0);
assert_eq!(generated.1.spent_by_me, 100000);
let unspents = vec![UnspentInfo {
value: 100000,
outpoint: OutPoint::default(),
height: Default::default(),
}];
let outputs = vec![TransactionOutput {
script_pubkey: Builder::build_p2pkh(&coin.as_ref().derivation_method.unwrap_single_addr().hash).to_bytes(),
value: 100000,
}];
// test that fee is properly deducted from output amount equal to input amount (max withdraw case)
let builder = UtxoTxBuilder::new(&coin)
.add_available_inputs(unspents)
.add_outputs(outputs)
.with_fee_policy(FeePolicy::DeductFromOutput(0));
let generated = block_on(builder.build()).unwrap();
assert_eq!(generated.0.outputs.len(), 1);
assert_eq!(generated.1.fee_amount, 1000);
assert_eq!(generated.1.unused_change, None);
assert_eq!(generated.1.received_by_me, 99000);
assert_eq!(generated.1.spent_by_me, 100000);
assert_eq!(generated.0.outputs[0].value, 99000);
let unspents = vec![UnspentInfo {
value: 100000,
outpoint: OutPoint::default(),
height: Default::default(),
}];
let outputs = vec![TransactionOutput {
script_pubkey: vec![].into(),
value: 100000,
}];
// test that generate_transaction returns an error when input amount is not sufficient to cover output + fee
let builder = UtxoTxBuilder::new(&coin)
.add_available_inputs(unspents)
.add_outputs(outputs);
block_on(builder.build()).unwrap_err();
}
#[test]
fn test_addresses_from_script() {
let client = electrum_client_for_test(RICK_ELECTRUM_ADDRS);
let coin = utxo_coin_for_test(client.into(), None, false);
// P2PKH
let script: Script = "76a91405aab5342166f8594baf17a7d9bef5d56744332788ac".into();
let expected_addr: Vec<Address> = vec!["R9o9xTocqr6CeEDGDH6mEYpwLoMz6jNjMW".into()];
let actual_addr = coin.addresses_from_script(&script).unwrap();
assert_eq!(expected_addr, actual_addr);
// P2SH
let script: Script = "a914e71a6120653ebd526e0f9d7a29cde5969db362d487".into();
let expected_addr: Vec<Address> = vec!["bZoEPR7DjTqSDiQTeRFNDJuQPTRY2335LD".into()];
let actual_addr = coin.addresses_from_script(&script).unwrap();
assert_eq!(expected_addr, actual_addr);
}
#[test]
fn test_kmd_interest() {
let height = Some(1000001);
let value = 64605500822;
let lock_time = 1556623906;
let current_time = 1556623906 + 3600 + 300;
let expected = 36870;
let actual = kmd_interest(height, value, lock_time, current_time).unwrap();
assert_eq!(expected, actual);
// UTXO amount must be at least 10 KMD to be eligible for interest
let actual = kmd_interest(height, 999999999, lock_time, current_time);
assert_eq!(actual, Err(KmdRewardsNotAccruedReason::UtxoAmountLessThanTen));
// Transaction is not mined yet (height is None)
let actual = kmd_interest(None, value, lock_time, current_time);
assert_eq!(actual, Err(KmdRewardsNotAccruedReason::TransactionInMempool));
// Locktime is not set
let actual = kmd_interest(height, value, 0, current_time);
assert_eq!(actual, Err(KmdRewardsNotAccruedReason::LocktimeNotSet));
// interest will stop accrue after block 7_777_777
let actual = kmd_interest(Some(7_777_778), value, lock_time, current_time);
assert_eq!(actual, Err(KmdRewardsNotAccruedReason::UtxoHeightGreaterThanEndOfEra));
// interest doesn't accrue for lock_time < 500_000_000
let actual = kmd_interest(height, value, 499_999_999, current_time);
assert_eq!(actual, Err(KmdRewardsNotAccruedReason::LocktimeLessThanThreshold));
// current time must be greater than tx lock_time
let actual = kmd_interest(height, value, lock_time, lock_time - 1);
assert_eq!(actual, Err(KmdRewardsNotAccruedReason::OneHourNotPassedYet));
// at least 1 hour should pass
let actual = kmd_interest(height, value, lock_time, lock_time + 30);
assert_eq!(actual, Err(KmdRewardsNotAccruedReason::OneHourNotPassedYet));
}
#[test]
fn test_kmd_interest_accrue_stop_at() {
let lock_time = 1595845640;
let height = 1000001;
let expected = lock_time + 31 * 24 * 60 * 60;
let actual = kmd_interest_accrue_stop_at(height, lock_time);
assert_eq!(expected, actual);
let height = 999999;
let expected = lock_time + 365 * 24 * 60 * 60;
let actual = kmd_interest_accrue_stop_at(height, lock_time);
assert_eq!(expected, actual);
}
#[test]
// Test case taken from this PR: https://github.com/KomodoPlatform/komodo/pull/584
fn test_kmd_interest_kip_0001_reduction() {
let height = Some(7777776);
let value = 64605500822;
let lock_time = 1663839248;
let current_time = 1663839248 + (31 * 24 * 60 - 1) * 60 + 3600;
// Starting from dPoW 7th season, according to KIP0001 AUR should be reduced from 5% to 0.01%, i.e. div by 500
let expected = value / 10512000 * (31 * 24 * 60 - 59) / 500;
println!("expected: {}", expected);
let actual = kmd_interest(height, value, lock_time, current_time).unwrap();
assert_eq!(expected, actual);
}
#[test]
fn test_sat_from_big_decimal() {
let amount = "0.000001".parse().unwrap();
let sat = sat_from_big_decimal(&amount, 18).unwrap();
let expected_sat = 1000000000000;
assert_eq!(expected_sat, sat);
let amount = "0.12345678".parse().unwrap();
let sat = sat_from_big_decimal(&amount, 8).unwrap();
let expected_sat = 12345678;
assert_eq!(expected_sat, sat);
let amount = "1.000001".parse().unwrap();
let sat = sat_from_big_decimal(&amount, 18).unwrap();
let expected_sat = 1000001000000000000;
assert_eq!(expected_sat, sat);
let amount = 1.into();
let sat = sat_from_big_decimal(&amount, 18).unwrap();
let expected_sat = 1000000000000000000;
assert_eq!(expected_sat, sat);
let amount = "0.000000000000000001".parse().unwrap();
let sat = sat_from_big_decimal(&amount, 18).unwrap();
let expected_sat = 1u64;
assert_eq!(expected_sat, sat);
let amount = 1234.into();
let sat = sat_from_big_decimal(&amount, 9).unwrap();
let expected_sat = 1234000000000;
assert_eq!(expected_sat, sat);
let amount = 1234.into();
let sat = sat_from_big_decimal(&amount, 0).unwrap();
let expected_sat = 1234;
assert_eq!(expected_sat, sat);
let amount = 1234.into();
let sat = sat_from_big_decimal(&amount, 1).unwrap();
let expected_sat = 12340;
assert_eq!(expected_sat, sat);
let amount = "1234.12345".parse().unwrap();
let sat = sat_from_big_decimal(&amount, 1).unwrap();
let expected_sat = 12341;
assert_eq!(expected_sat, sat);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_wait_for_payment_spend_timeout_native() {
let client = NativeClientImpl::default();
static mut OUTPUT_SPEND_CALLED: bool = false;
NativeClient::find_output_spend.mock_safe(|_, _, _, _, _| {
unsafe { OUTPUT_SPEND_CALLED = true };
MockResult::Return(Box::new(futures01::future::ok(None)))
});
let client = UtxoRpcClientEnum::Native(NativeClient(Arc::new(client)));
let coin = utxo_coin_for_test(client, None, false);
let transaction = hex::decode("01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac000247304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee0121025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee635711000000")
.unwrap();
let wait_until = now_sec() - 1;
let from_block = 1000;
assert!(coin
.wait_for_htlc_tx_spend(WaitForHTLCTxSpendArgs {
tx_bytes: &transaction,
secret_hash: &[],
wait_until,
from_block,
swap_contract_address: &None,
check_every: TAKER_PAYMENT_SPEND_SEARCH_INTERVAL,
watcher_reward: false
})
.wait()
.is_err());
assert!(unsafe { OUTPUT_SPEND_CALLED });
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn test_wait_for_payment_spend_timeout_electrum() {
static mut OUTPUT_SPEND_CALLED: bool = false;
ElectrumClient::find_output_spend.mock_safe(|_, _, _, _, _| {
unsafe { OUTPUT_SPEND_CALLED = true };
MockResult::Return(Box::new(futures01::future::ok(None)))
});
let block_headers_storage = BlockHeaderStorage {
inner: Box::new(SqliteBlockHeadersStorage {
ticker: TEST_COIN_NAME.into(),
conn: Arc::new(Mutex::new(Connection::open_in_memory().unwrap())),
}),
};
let abortable_system = AbortableQueue::default();
let client = ElectrumClientImpl::new(
TEST_COIN_NAME.into(),
Default::default(),
block_headers_storage,
abortable_system,
true,
);
let client = UtxoRpcClientEnum::Electrum(ElectrumClient(Arc::new(client)));
let coin = utxo_coin_for_test(client, None, false);
let transaction = hex::decode("01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac000247304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee0121025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee635711000000")
.unwrap();
let wait_until = now_sec() - 1;
let from_block = 1000;
assert!(coin
.wait_for_htlc_tx_spend(WaitForHTLCTxSpendArgs {
tx_bytes: &transaction,
secret_hash: &[],
wait_until,
from_block,
swap_contract_address: &None,
check_every: TAKER_PAYMENT_SPEND_SEARCH_INTERVAL,
watcher_reward: false
})
.wait()
.is_err());
assert!(unsafe { OUTPUT_SPEND_CALLED });
}
#[test]
fn test_search_for_swap_tx_spend_electrum_was_spent() {
let secret = [0; 32];
let client = electrum_client_for_test(RICK_ELECTRUM_ADDRS);
let coin = utxo_coin_for_test(
client.into(),
Some("spice describe gravity federal blast come thank unfair canal monkey style afraid"),
false,
);
// raw tx bytes of https://rick.kmd.dev/tx/ba881ecca15b5d4593f14f25debbcdfe25f101fd2e9cf8d0b5d92d19813d4424
let payment_tx_bytes = hex::decode("0400008085202f8902e115acc1b9e26a82f8403c9f81785445cc1285093b63b6246cf45aabac5e0865000000006b483045022100ca578f2d6bae02f839f71619e2ced54538a18d7aa92bd95dcd86ac26479ec9f802206552b6c33b533dd6fc8985415a501ebec89d1f5c59d0c923d1de5280e9827858012102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ffffffffb0721bf69163f7a5033fb3d18ba5768621d8c1347ebaa2fddab0d1f63978ea78020000006b483045022100a3309f99167982e97644dbb5cd7279b86630b35fc34855e843f2c5c0cafdc66d02202a8c3257c44e832476b2e2a723dad1bb4ec1903519502a49b936c155cae382ee012102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ffffffff0300e1f5050000000017a91443fde927a77b3c1d104b78155dc389078c4571b0870000000000000000166a14b8bcb07f6344b42ab04250c86a6e8b75d3fdbbc64b8cd736000000001976a91405aab5342166f8594baf17a7d9bef5d56744332788acba0ce35e000000000000000000000000000000")
.unwrap();
// raw tx bytes of https://rick.kmd.dev/tx/cea8028f93f7556ce0ef96f14b8b5d88ef2cd29f428df5936e02e71ca5b0c795
let spend_tx_bytes = hex::decode("0400008085202f890124443d81192dd9b5d0f89c2efd01f125fecdbbde254ff193455d5ba1cc1e88ba00000000d74730440220519d3eed69815a16357ff07bf453b227654dc85b27ffc22a77abe077302833ec02205c27f439ddc542d332504112871ecac310ea710b99e1922f48eb179c045e44ee01200000000000000000000000000000000000000000000000000000000000000000004c6b6304a9e5e25eb1752102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ac6782012088a914b8bcb07f6344b42ab04250c86a6e8b75d3fdbbc6882102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ac68ffffffff0118ddf505000000001976a91405aab5342166f8594baf17a7d9bef5d56744332788acbffee25e000000000000000000000000000000")
.unwrap();
let spend_tx = TransactionEnum::UtxoTx(deserialize(spend_tx_bytes.as_slice()).unwrap());
let search_input = SearchForSwapTxSpendInput {
time_lock: 1591928233,
other_pub: coin.my_public_key().unwrap(),
secret_hash: &*dhash160(&secret),
tx: &payment_tx_bytes,
search_from_block: 0,
swap_contract_address: &None,
swap_unique_data: &[],
watcher_reward: false,
};
let found = block_on(coin.search_for_swap_tx_spend_my(search_input))
.unwrap()
.unwrap();
assert_eq!(FoundSwapTxSpend::Spent(spend_tx), found);
}
#[test]
fn test_search_for_swap_tx_spend_electrum_was_refunded() {
let secret_hash = [0; 20];
let client = electrum_client_for_test(RICK_ELECTRUM_ADDRS);
let coin = utxo_coin_for_test(
client.into(),
Some("spice describe gravity federal blast come thank unfair canal monkey style afraid"),
false,
);
// raw tx bytes of https://rick.kmd.dev/tx/78ea7839f6d1b0dafda2ba7e34c1d8218676a58bd1b33f03a5f76391f61b72b0
let payment_tx_bytes = hex::decode("0400008085202f8902bf17bf7d1daace52e08f732a6b8771743ca4b1cb765a187e72fd091a0aabfd52000000006a47304402203eaaa3c4da101240f80f9c5e9de716a22b1ec6d66080de6a0cca32011cd77223022040d9082b6242d6acf9a1a8e658779e1c655d708379862f235e8ba7b8ca4e69c6012102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ffffffffff023ca13c0e9e085dd13f481f193e8a3e8fd609020936e98b5587342d994f4d020000006b483045022100c0ba56adb8de923975052312467347d83238bd8d480ce66e8b709a7997373994022048507bcac921fdb2302fa5224ce86e41b7efc1a2e20ae63aa738dfa99b7be826012102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ffffffff0300e1f5050000000017a9141ee6d4c38a3c078eab87ad1a5e4b00f21259b10d870000000000000000166a1400000000000000000000000000000000000000001b94d736000000001976a91405aab5342166f8594baf17a7d9bef5d56744332788ac2d08e35e000000000000000000000000000000")
.unwrap();
// raw tx bytes of https://rick.kmd.dev/tx/65085eacab5af46c24b6633b098512cc455478819f3c40f8826ae2b9c1ac15e1
let refund_tx_bytes = hex::decode("0400008085202f8901b0721bf69163f7a5033fb3d18ba5768621d8c1347ebaa2fddab0d1f63978ea7800000000b6473044022052e06c1abf639148229a3991fdc6da15fe51c97577f4fda351d9c606c7cf53670220780186132d67d354564cae710a77d94b6bb07dcbd7162a13bebee261ffc0963601514c6b63041dfae25eb1752102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ac6782012088a9140000000000000000000000000000000000000000882102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ac68feffffff0118ddf505000000001976a91405aab5342166f8594baf17a7d9bef5d56744332788ace6fae25e000000000000000000000000000000")
.unwrap();
let refund_tx = TransactionEnum::UtxoTx(deserialize(refund_tx_bytes.as_slice()).unwrap());
let search_input = SearchForSwapTxSpendInput {
time_lock: 1591933469,
other_pub: coin.as_ref().priv_key_policy.key_pair_or_err().unwrap().public(),
secret_hash: &secret_hash,
tx: &payment_tx_bytes,
search_from_block: 0,
swap_contract_address: &None,
swap_unique_data: &[],
watcher_reward: false,
};
let found = block_on(coin.search_for_swap_tx_spend_my(search_input))
.unwrap()
.unwrap();
assert_eq!(FoundSwapTxSpend::Refunded(refund_tx), found);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_impl_set_fixed_fee() {
UtxoStandardCoin::get_unspent_ordered_list.mock_safe(|coin, _| {
let cache = block_on(coin.as_ref().recently_spent_outpoints.lock());
let unspents = vec![UnspentInfo {
outpoint: OutPoint {
hash: 1.into(),
index: 0,
},
value: 1000000000,
height: Default::default(),
}];
MockResult::Return(Box::pin(futures::future::ok((unspents, cache))))
});
let client = NativeClient(Arc::new(NativeClientImpl::default()));
let coin = utxo_coin_for_test(UtxoRpcClientEnum::Native(client), None, false);
let withdraw_req = WithdrawRequest {
amount: 1u64.into(),
from: None,
to: "RQq6fWoy8aGGMLjvRfMY5mBNVm2RQxJyLa".to_string(),
coin: TEST_COIN_NAME.into(),
max: false,
fee: Some(WithdrawFee::UtxoFixed {
amount: "0.1".parse().unwrap(),
}),
memo: None,
};
let expected = Some(
UtxoFeeDetails {
coin: Some(TEST_COIN_NAME.into()),
amount: "0.1".parse().unwrap(),
}
.into(),
);
let tx_details = coin.withdraw(withdraw_req).wait().unwrap();
assert_eq!(expected, tx_details.fee_details);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_impl_sat_per_kb_fee() {
UtxoStandardCoin::get_unspent_ordered_list.mock_safe(|coin, _| {
let cache = block_on(coin.as_ref().recently_spent_outpoints.lock());
let unspents = vec![UnspentInfo {
outpoint: OutPoint {
hash: 1.into(),
index: 0,
},
value: 1000000000,
height: Default::default(),
}];
MockResult::Return(Box::pin(futures::future::ok((unspents, cache))))
});
let client = NativeClient(Arc::new(NativeClientImpl::default()));
let coin = utxo_coin_for_test(UtxoRpcClientEnum::Native(client), None, false);
let withdraw_req = WithdrawRequest {
amount: 1u64.into(),
from: None,
to: "RQq6fWoy8aGGMLjvRfMY5mBNVm2RQxJyLa".to_string(),
coin: TEST_COIN_NAME.into(),
max: false,
fee: Some(WithdrawFee::UtxoPerKbyte {
amount: "0.1".parse().unwrap(),
}),
memo: None,
};
// The resulting transaction size might be 244 or 245 bytes depending on signature size
// MM2 always expects the worst case during fee calculation
// 0.1 * 245 / 1000 ~ 0.0245
let expected = Some(
UtxoFeeDetails {
coin: Some(TEST_COIN_NAME.into()),
amount: "0.0245".parse().unwrap(),
}
.into(),
);
let tx_details = coin.withdraw(withdraw_req).wait().unwrap();
assert_eq!(expected, tx_details.fee_details);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_impl_sat_per_kb_fee_amount_equal_to_max() {
UtxoStandardCoin::get_unspent_ordered_list.mock_safe(|coin, _| {
let cache = block_on(coin.as_ref().recently_spent_outpoints.lock());
let unspents = vec![UnspentInfo {
outpoint: OutPoint {
hash: 1.into(),
index: 0,
},
value: 1000000000,
height: Default::default(),
}];
MockResult::Return(Box::pin(futures::future::ok((unspents, cache))))
});
let client = NativeClient(Arc::new(NativeClientImpl::default()));
let coin = utxo_coin_for_test(UtxoRpcClientEnum::Native(client), None, false);
let withdraw_req = WithdrawRequest {
amount: "9.9789".parse().unwrap(),
from: None,
to: "RQq6fWoy8aGGMLjvRfMY5mBNVm2RQxJyLa".to_string(),
coin: TEST_COIN_NAME.into(),
max: false,
fee: Some(WithdrawFee::UtxoPerKbyte {
amount: "0.1".parse().unwrap(),
}),
memo: None,
};
let tx_details = coin.withdraw(withdraw_req).wait().unwrap();
// The resulting transaction size might be 210 or 211 bytes depending on signature size
// MM2 always expects the worst case during fee calculation
// 0.1 * 211 / 1000 = 0.0211
let expected_fee = Some(
UtxoFeeDetails {
coin: Some(TEST_COIN_NAME.into()),
amount: "0.0211".parse().unwrap(),
}
.into(),
);
assert_eq!(expected_fee, tx_details.fee_details);
let expected_balance_change = BigDecimal::from(-10i32);
assert_eq!(expected_balance_change, tx_details.my_balance_change);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_impl_sat_per_kb_fee_amount_equal_to_max_dust_included_to_fee() {
UtxoStandardCoin::get_unspent_ordered_list.mock_safe(|coin, _| {
let cache = block_on(coin.as_ref().recently_spent_outpoints.lock());
let unspents = vec![UnspentInfo {
outpoint: OutPoint {
hash: 1.into(),
index: 0,
},
value: 1000000000,
height: Default::default(),
}];
MockResult::Return(Box::pin(futures::future::ok((unspents, cache))))
});
let client = NativeClient(Arc::new(NativeClientImpl::default()));
let coin = utxo_coin_for_test(UtxoRpcClientEnum::Native(client), None, false);
let withdraw_req = WithdrawRequest {
amount: "9.9789".parse().unwrap(),
from: None,
to: "RQq6fWoy8aGGMLjvRfMY5mBNVm2RQxJyLa".to_string(),
coin: TEST_COIN_NAME.into(),
max: false,
fee: Some(WithdrawFee::UtxoPerKbyte {
amount: "0.09999999".parse().unwrap(),
}),
memo: None,
};
let tx_details = coin.withdraw(withdraw_req).wait().unwrap();
// The resulting transaction size might be 210 or 211 bytes depending on signature size
// MM2 always expects the worst case during fee calculation
// 0.1 * 211 / 1000 = 0.0211
let expected_fee = Some(
UtxoFeeDetails {
coin: Some(TEST_COIN_NAME.into()),
amount: "0.0211".parse().unwrap(),
}
.into(),
);
assert_eq!(expected_fee, tx_details.fee_details);
let expected_balance_change = BigDecimal::from(-10i32);
assert_eq!(expected_balance_change, tx_details.my_balance_change);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_impl_sat_per_kb_fee_amount_over_max() {
UtxoStandardCoin::get_unspent_ordered_list.mock_safe(|coin, _| {
let cache = block_on(coin.as_ref().recently_spent_outpoints.lock());
let unspents = vec![UnspentInfo {
outpoint: OutPoint {
hash: 1.into(),
index: 0,
},
value: 1000000000,
height: Default::default(),
}];
MockResult::Return(Box::pin(futures::future::ok((unspents, cache))))
});
let client = NativeClient(Arc::new(NativeClientImpl::default()));
let coin = utxo_coin_for_test(UtxoRpcClientEnum::Native(client), None, false);
let withdraw_req = WithdrawRequest {
amount: "9.97939455".parse().unwrap(),
from: None,
to: "RQq6fWoy8aGGMLjvRfMY5mBNVm2RQxJyLa".to_string(),
coin: TEST_COIN_NAME.into(),
max: false,
fee: Some(WithdrawFee::UtxoPerKbyte {
amount: "0.1".parse().unwrap(),
}),
memo: None,
};
coin.withdraw(withdraw_req).wait().unwrap_err();
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_impl_sat_per_kb_fee_max() {
UtxoStandardCoin::get_unspent_ordered_list.mock_safe(|coin, _| {
let cache = block_on(coin.as_ref().recently_spent_outpoints.lock());
let unspents = vec![UnspentInfo {
outpoint: OutPoint {
hash: 1.into(),
index: 0,
},
value: 1000000000,
height: Default::default(),
}];
MockResult::Return(Box::pin(futures::future::ok((unspents, cache))))
});
let client = NativeClient(Arc::new(NativeClientImpl::default()));
let coin = utxo_coin_for_test(UtxoRpcClientEnum::Native(client), None, false);
let withdraw_req = WithdrawRequest {
amount: 0u64.into(),
from: None,
to: "RQq6fWoy8aGGMLjvRfMY5mBNVm2RQxJyLa".to_string(),
coin: TEST_COIN_NAME.into(),
max: true,
fee: Some(WithdrawFee::UtxoPerKbyte {
amount: "0.1".parse().unwrap(),
}),
memo: None,
};
// The resulting transaction size might be 210 or 211 bytes depending on signature size
// MM2 always expects the worst case during fee calculation
// 0.1 * 211 / 1000 = 0.0211
let expected = Some(
UtxoFeeDetails {
coin: Some(TEST_COIN_NAME.into()),
amount: "0.0211".parse().unwrap(),
}
.into(),
);
let tx_details = coin.withdraw(withdraw_req).wait().unwrap();
assert_eq!(expected, tx_details.fee_details);
}
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_kmd_rewards_impl(
tx_hash: &'static str,
tx_hex: &'static str,
verbose_serialized: &str,
current_mtp: u32,
expected_rewards: Option<BigDecimal>,
) {
let verbose: RpcTransaction = json::from_str(verbose_serialized).unwrap();
let unspent_height = verbose.height;
UtxoStandardCoin::get_unspent_ordered_list.mock_safe(move |coin, _| {
let tx: UtxoTx = tx_hex.into();
let unspents = vec![UnspentInfo {
outpoint: OutPoint {
hash: tx.hash(),
index: 0,
},
value: tx.outputs[0].value,
height: unspent_height,
}];
let cache = block_on(coin.as_ref().recently_spent_outpoints.lock());
MockResult::Return(Box::pin(futures::future::ok((unspents, cache))))
});
UtxoStandardCoin::get_current_mtp
.mock_safe(move |_fields| MockResult::Return(Box::pin(futures::future::ok(current_mtp))));
NativeClient::get_verbose_transaction.mock_safe(move |_coin, txid| {
let expected: H256Json = hex::decode(tx_hash).unwrap().as_slice().into();
assert_eq!(*txid, expected);
MockResult::Return(Box::new(futures01::future::ok(verbose.clone())))
});
let client = NativeClient(Arc::new(NativeClientImpl::default()));
let mut fields = utxo_coin_fields_for_test(UtxoRpcClientEnum::Native(client), None, false);
fields.conf.ticker = "KMD".to_owned();
let coin = utxo_coin_from_fields(fields);
let withdraw_req = WithdrawRequest {
amount: BigDecimal::from_str("0.00001").unwrap(),
from: None,
to: "RQq6fWoy8aGGMLjvRfMY5mBNVm2RQxJyLa".to_string(),
coin: "KMD".to_owned(),
max: false,
fee: None,
memo: None,
};
let expected_fee = TxFeeDetails::Utxo(UtxoFeeDetails {
coin: Some("KMD".into()),
amount: "0.00001".parse().unwrap(),
});
let tx_details = coin.withdraw(withdraw_req).wait().unwrap();
assert_eq!(tx_details.fee_details, Some(expected_fee));
let expected_rewards = expected_rewards.map(|amount| KmdRewardsDetails {
amount,
claimed_by_me: true,
});
assert_eq!(tx_details.kmd_rewards, expected_rewards);
}
/// https://kmdexplorer.io/tx/535ffa3387d3fca14f4a4d373daf7edf00e463982755afce89bc8c48d8168024
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_kmd_rewards() {
const TX_HASH: &str = "535ffa3387d3fca14f4a4d373daf7edf00e463982755afce89bc8c48d8168024";
const TX_HEX: &str = "0400008085202f8901afcadb73880bc1c9e7ce96b8274c2e2a4547415e649f425f98791685be009b73020000006b483045022100b8fbb77efea482b656ad16fc53c5a01d289054c2e429bf1d7bab16c3e822a83602200b87368a95c046b2ce6d0d092185138a3f234a7eb0d7f8227b196ef32358b93f012103b1e544ce2d860219bc91314b5483421a553a7b33044659eff0be9214ed58adddffffffff01dd15c293000000001976a91483762a373935ca241d557dfce89171d582b486de88ac99fe9960000000000000000000000000000000";
const VERBOSE_SERIALIZED: &str = r#"{"hex":"0400008085202f8901afcadb73880bc1c9e7ce96b8274c2e2a4547415e649f425f98791685be009b73020000006b483045022100b8fbb77efea482b656ad16fc53c5a01d289054c2e429bf1d7bab16c3e822a83602200b87368a95c046b2ce6d0d092185138a3f234a7eb0d7f8227b196ef32358b93f012103b1e544ce2d860219bc91314b5483421a553a7b33044659eff0be9214ed58adddffffffff01dd15c293000000001976a91483762a373935ca241d557dfce89171d582b486de88ac99fe9960000000000000000000000000000000","txid":"535ffa3387d3fca14f4a4d373daf7edf00e463982755afce89bc8c48d8168024","hash":null,"size":null,"vsize":null,"version":4,"locktime":1620704921,"vin":[{"txid":"739b00be851679985f429f645e4147452a2e4c27b896cee7c9c10b8873dbcaaf","vout":2,"scriptSig":{"asm":"3045022100b8fbb77efea482b656ad16fc53c5a01d289054c2e429bf1d7bab16c3e822a83602200b87368a95c046b2ce6d0d092185138a3f234a7eb0d7f8227b196ef32358b93f[ALL] 03b1e544ce2d860219bc91314b5483421a553a7b33044659eff0be9214ed58addd","hex":"483045022100b8fbb77efea482b656ad16fc53c5a01d289054c2e429bf1d7bab16c3e822a83602200b87368a95c046b2ce6d0d092185138a3f234a7eb0d7f8227b196ef32358b93f012103b1e544ce2d860219bc91314b5483421a553a7b33044659eff0be9214ed58addd"},"sequence":4294967295,"txinwitness":null}],"vout":[{"value":24.78970333,"n":0,"scriptPubKey":{"asm":"OP_DUP OP_HASH160 83762a373935ca241d557dfce89171d582b486de OP_EQUALVERIFY OP_CHECKSIG","hex":"76a91483762a373935ca241d557dfce89171d582b486de88ac","reqSigs":1,"type":"pubkeyhash","addresses":["RMGJ9tRST45RnwEKHPGgBLuY3moSYP7Mhk"]}}],"blockhash":"0b438a8e50afddb38fb1c7be4536ffc7f7723b76bbc5edf7c28f2c17924dbdfa","confirmations":33186,"rawconfirmations":33186,"time":1620705483,"blocktime":1620705483,"height":2387532}"#;
const CURRENT_MTP: u32 = 1622724281;
let expected_rewards = BigDecimal::from_str("0.07895295").unwrap();
test_withdraw_kmd_rewards_impl(TX_HASH, TX_HEX, VERBOSE_SERIALIZED, CURRENT_MTP, Some(expected_rewards));
}
/// If the ticker is `KMD` AND no rewards were accrued due to a value less than 10 or for any other reasons,
/// then `TransactionDetails::kmd_rewards` has to be `Some(0)`, not `None`.
/// https://kmdexplorer.io/tx/8c43e5a0402648faa5d0ae3550137544507ab1553425fa1b6f481a66a53f7a2d
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_kmd_rewards_zero() {
const TX_HASH: &str = "8c43e5a0402648faa5d0ae3550137544507ab1553425fa1b6f481a66a53f7a2d";
const TX_HEX: &str = "0400008085202f8901c3651b6fb9ddf372e7a9d4d829c27eeea6cdfaab4f2e6e3527905c2a14f3702b010000006a47304402206819b3e51f076841ed5946bc9a48b9d75024b60abd8e854bfe50cbdfae8a268e022001a3648d2a4b33a761090676e4a8c676ee67cb602f29fef74ea5bbb8b516a178012103832b54342019dd5ecc08f1143757fbcf4ac6c8696653d456a84b40f34653c9a8ffffffff0200e1f505000000001976a91483762a373935ca241d557dfce89171d582b486de88ac60040c35000000001976a9142b33504039790fde428e4ab084aa1baf6aee209288acb0edd45f000000000000000000000000000000";
const VERBOSE_SERIALIZED: &str = r#"{"hex":"0400008085202f8901c3651b6fb9ddf372e7a9d4d829c27eeea6cdfaab4f2e6e3527905c2a14f3702b010000006a47304402206819b3e51f076841ed5946bc9a48b9d75024b60abd8e854bfe50cbdfae8a268e022001a3648d2a4b33a761090676e4a8c676ee67cb602f29fef74ea5bbb8b516a178012103832b54342019dd5ecc08f1143757fbcf4ac6c8696653d456a84b40f34653c9a8ffffffff0200e1f505000000001976a91483762a373935ca241d557dfce89171d582b486de88ac60040c35000000001976a9142b33504039790fde428e4ab084aa1baf6aee209288acb0edd45f000000000000000000000000000000","txid":"8c43e5a0402648faa5d0ae3550137544507ab1553425fa1b6f481a66a53f7a2d","hash":null,"size":null,"vsize":null,"version":4,"locktime":1607790000,"vin":[{"txid":"2b70f3142a5c9027356e2e4fabfacda6ee7ec229d8d4a9e772f3ddb96f1b65c3","vout":1,"scriptSig":{"asm":"304402206819b3e51f076841ed5946bc9a48b9d75024b60abd8e854bfe50cbdfae8a268e022001a3648d2a4b33a761090676e4a8c676ee67cb602f29fef74ea5bbb8b516a178[ALL] 03832b54342019dd5ecc08f1143757fbcf4ac6c8696653d456a84b40f34653c9a8","hex":"47304402206819b3e51f076841ed5946bc9a48b9d75024b60abd8e854bfe50cbdfae8a268e022001a3648d2a4b33a761090676e4a8c676ee67cb602f29fef74ea5bbb8b516a178012103832b54342019dd5ecc08f1143757fbcf4ac6c8696653d456a84b40f34653c9a8"},"sequence":4294967295,"txinwitness":null}],"vout":[{"value":1.0,"n":0,"scriptPubKey":{"asm":"OP_DUP OP_HASH160 83762a373935ca241d557dfce89171d582b486de OP_EQUALVERIFY OP_CHECKSIG","hex":"76a91483762a373935ca241d557dfce89171d582b486de88ac","reqSigs":1,"type":"pubkeyhash","addresses":["RMGJ9tRST45RnwEKHPGgBLuY3moSYP7Mhk"]}},{"value":8.8998,"n":1,"scriptPubKey":{"asm":"OP_DUP OP_HASH160 2b33504039790fde428e4ab084aa1baf6aee2092 OP_EQUALVERIFY OP_CHECKSIG","hex":"76a9142b33504039790fde428e4ab084aa1baf6aee209288ac","reqSigs":1,"type":"pubkeyhash","addresses":["RDDcc63q27t6k95LrysuDwtwrxuAXqNiXe"]}}],"blockhash":"0000000054ed9fc7a4316430659e127eac5776ebc2d2382db0cb9be3eb970d7b","confirmations":243859,"rawconfirmations":243859,"time":1607790977,"blocktime":1607790977,"height":2177114}"#;
const CURRENT_MTP: u32 = 1622724281;
let expected_rewards = BigDecimal::from(0);
test_withdraw_kmd_rewards_impl(TX_HASH, TX_HEX, VERBOSE_SERIALIZED, CURRENT_MTP, Some(expected_rewards));
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn test_withdraw_rick_rewards_none() {
// https://rick.explorer.dexstats.info/tx/7181400be323acc6b5f3164240e6c4601ff4c252f40ce7649f87e81634330209
const TX_HEX: &str = "0400008085202f8901df8119c507aa61d32332cd246dbfeb3818a4f96e76492454c1fbba5aa097977e000000004847304402205a7e229ea6929c97fd6dde254c19e4eb890a90353249721701ae7a1c477d99c402206a8b7c5bf42b5095585731d6b4c589ce557f63c20aed69ff242eca22ecfcdc7a01feffffff02d04d1bffbc050000232102afdbba3e3c90db5f0f4064118f79cf308f926c68afd64ea7afc930975663e4c4ac402dd913000000001976a9143e17014eca06281ee600adffa34b4afb0922a22288ac2bdab86035a00e000000000000000000000000";
UtxoStandardCoin::get_unspent_ordered_list.mock_safe(move |coin, _| {
let tx: UtxoTx = TX_HEX.into();
let unspents = vec![UnspentInfo {
outpoint: OutPoint {
hash: tx.hash(),
index: 0,
},
value: tx.outputs[0].value,
height: Some(1431628),
}];
let cache = block_on(coin.as_ref().recently_spent_outpoints.lock());
MockResult::Return(Box::pin(futures::future::ok((unspents, cache))))
});
let client = NativeClient(Arc::new(NativeClientImpl::default()));
let coin = utxo_coin_for_test(UtxoRpcClientEnum::Native(client), None, false);
let withdraw_req = WithdrawRequest {
amount: BigDecimal::from_str("0.00001").unwrap(),
from: None,
to: "RQq6fWoy8aGGMLjvRfMY5mBNVm2RQxJyLa".to_string(),
coin: "RICK".to_owned(),
max: false,
fee: None,
memo: None,
};
let expected_fee = TxFeeDetails::Utxo(UtxoFeeDetails {
coin: Some(TEST_COIN_NAME.into()),
amount: "0.00001".parse().unwrap(),
});
let tx_details = coin.withdraw(withdraw_req).wait().unwrap();
assert_eq!(tx_details.fee_details, Some(expected_fee));
assert_eq!(tx_details.kmd_rewards, None);
}
#[test]
fn test_utxo_lock() {
// send several transactions concurrently to check that they are not using same inputs
let client = electrum_client_for_test(RICK_ELECTRUM_ADDRS);
let coin = utxo_coin_for_test(client.into(), None, false);
let output = TransactionOutput {
value: 1000000,
script_pubkey: Builder::build_p2pkh(&coin.as_ref().derivation_method.unwrap_single_addr().hash).to_bytes(),
};
let mut futures = vec![];
for _ in 0..5 {
futures.push(send_outputs_from_my_address_impl(coin.clone(), vec![output.clone()]));
}
let results = block_on(join_all(futures));
for result in results {
result.unwrap();
}
}
#[test]
fn test_spv_proof() {
let client = electrum_client_for_test(RICK_ELECTRUM_ADDRS);
// https://rick.explorer.dexstats.info/tx/78ea7839f6d1b0dafda2ba7e34c1d8218676a58bd1b33f03a5f76391f61b72b0
let tx_str = "0400008085202f8902bf17bf7d1daace52e08f732a6b8771743ca4b1cb765a187e72fd091a0aabfd52000000006a47304402203eaaa3c4da101240f80f9c5e9de716a22b1ec6d66080de6a0cca32011cd77223022040d9082b6242d6acf9a1a8e658779e1c655d708379862f235e8ba7b8ca4e69c6012102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ffffffffff023ca13c0e9e085dd13f481f193e8a3e8fd609020936e98b5587342d994f4d020000006b483045022100c0ba56adb8de923975052312467347d83238bd8d480ce66e8b709a7997373994022048507bcac921fdb2302fa5224ce86e41b7efc1a2e20ae63aa738dfa99b7be826012102031d4256c4bc9f99ac88bf3dba21773132281f65f9bf23a59928bce08961e2f3ffffffff0300e1f5050000000017a9141ee6d4c38a3c078eab87ad1a5e4b00f21259b10d870000000000000000166a1400000000000000000000000000000000000000001b94d736000000001976a91405aab5342166f8594baf17a7d9bef5d56744332788ac2d08e35e000000000000000000000000000000";
let tx: UtxoTx = tx_str.into();
let header: BlockHeader = deserialize(
block_on(client.blockchain_block_header(452248).compat())
.unwrap()
.as_slice(),
)
.unwrap();
let mut headers = HashMap::new();
headers.insert(452248, header);
let storage = client.block_headers_storage();
block_on(storage.add_block_headers_to_storage(headers)).unwrap();
let res = block_on(client.validate_spv_proof(&tx, wait_until_sec(30)));
res.unwrap();
}
#[test]
fn list_since_block_btc_serde() {
// https://github.com/KomodoPlatform/atomicDEX-API/issues/563
let input = r#"{"lastblock":"000000000000000000066f896cca2a6c667ca85fff28ed6731d64e3c39ecb119","removed":[],"transactions":[{"abandoned":false,"address":"1Q3kQ1jsB2VyH83PJT1NXJqEaEcR6Yuknn","amount":-0.01788867,"bip125-replaceable":"no","blockhash":"0000000000000000000db4be4c2df08790e1027326832cc90889554bbebc69b7","blockindex":437,"blocktime":1572174214,"category":"send","confirmations":197,"fee":-0.00012924,"involvesWatchonly":true,"time":1572173721,"timereceived":1572173721,"txid":"29606e6780c69a39767b56dc758e6af31ced5232491ad62dcf25275684cb7701","vout":0,"walletconflicts":[]},{"address":"1JsAjr6d21j9T8EMsYnQ6GXf1mM523JAv1","amount":0.1995,"bip125-replaceable":"no","blockhash":"0000000000000000000e75b33bbb27e6af2fc3898108c93c03c293fd72a86c6f","blockindex":157,"blocktime":1572179171,"category":"receive","confirmations":190,"label":"","time":1572178251,"timereceived":1572178251,"txid":"da651c6addc8da7c4b2bec21d43022852a93a9f2882a827704b318eb2966b82e","vout":19,"walletconflicts":[]},{"abandoned":false,"address":"14RXkMTyH4NyK48DbhTQyMBoMb2UkbBEPr","amount":-0.0208,"bip125-replaceable":"no","blockhash":"0000000000000000000611bfe0b3f7612239264459f4f6e7169f8d1a67e1b08f","blockindex":286,"blocktime":1572189657,"category":"send","confirmations":178,"fee":-0.0002,"involvesWatchonly":true,"time":1572189100,"timereceived":1572189100,"txid":"8d10920ce70aeb6c7e61c8d47f3cd903fb69946edd08d8907472a90761965943","vout":0,"walletconflicts":[]},{"abandoned":false,"address":"361JVximBAqkLZERT7XB1rykgLePEHAP7B","amount":-0.01801791,"bip125-replaceable":"no","blockhash":"00000000000000000011e9293c1f07f9711e677389ac101b93116d239ac38c33","blockindex":274,"blocktime":1572173649,"category":"send","confirmations":198,"fee":-0.0000965,"involvesWatchonly":true,"label":"361JVximBAqkLZERT7XB1rykgLePEHAP7B","time":1572173458,"timereceived":1572173458,"txid":"7983cae1afeb7fe58e020878aaedea0fee15be9319bc49c81f3b9ad466782950","vout":0,"walletconflicts":[]},{"abandoned":false,"address":"1JsAjr6d21j9T8EMsYnQ6GXf1mM523JAv1","amount":-0.0003447,"bip125-replaceable":"no","blockhash":"00000000000000000011e9293c1f07f9711e677389ac101b93116d239ac38c33","blockindex":274,"blocktime":1572173649,"category":"send","confirmations":198,"fee":-0.0000965,"label":"","time":1572173458,"timereceived":1572173458,"txid":"7983cae1afeb7fe58e020878aaedea0fee15be9319bc49c81f3b9ad466782950","vout":1,"walletconflicts":[]},{"address":"361JVximBAqkLZERT7XB1rykgLePEHAP7B","amount":0.01801791,"bip125-replaceable":"no","blockhash":"00000000000000000011e9293c1f07f9711e677389ac101b93116d239ac38c33","blockindex":274,"blocktime":1572173649,"category":"receive","confirmations":198,"involvesWatchonly":true,"label":"361JVximBAqkLZERT7XB1rykgLePEHAP7B","time":1572173458,"timereceived":1572173458,"txid":"7983cae1afeb7fe58e020878aaedea0fee15be9319bc49c81f3b9ad466782950","vout":0,"walletconflicts":[]},{"address":"1JsAjr6d21j9T8EMsYnQ6GXf1mM523JAv1","amount":0.0003447,"bip125-replaceable":"no","blockhash":"00000000000000000011e9293c1f07f9711e677389ac101b93116d239ac38c33","blockindex":274,"blocktime":1572173649,"category":"receive","confirmations":198,"label":"","time":1572173458,"timereceived":1572173458,"txid":"7983cae1afeb7fe58e020878aaedea0fee15be9319bc49c81f3b9ad466782950","vout":1,"walletconflicts":[]},{"abandoned":false,"address":"3B3q1GTLQQ7Fspo6ATy3cd3tg5yu97hkve","amount":-0.021,"bip125-replaceable":"no","blockhash":"0000000000000000000debf11962f89e2ae08f8ff75803b0da6170af6c5c346b","blockindex":2618,"blocktime":1572188894,"category":"send","confirmations":179,"fee":-0.00016026,"involvesWatchonly":true,"label":"3B3q1GTLQQ7Fspo6ATy3cd3tg5yu97hkve","time":1572186009,"timereceived":1572186009,"txid":"54b159ac3a656bbaaf3bf0263b8deafad03b376ec0c2e9c715d0cf1caaf3495e","vout":0,"walletconflicts":[]},{"abandoned":false,"address":"1JsAjr6d21j9T8EMsYnQ6GXf1mM523JAv1","amount":-0.17868444,"bip125-replaceable":"no","blockhash":"0000000000000000000debf11962f89e2ae08f8ff75803b0da6170af6c5c346b","blockindex":2618,"blocktime":1572188894,"category":"send","confirmations":179,"fee":-0.00016026,"label":"","time":1572186009,"timereceived":1572186009,"txid":"54b159ac3a656bbaaf3bf0263b8deafad03b376ec0c2e9c715d0cf1caaf3495e","vout":1,"walletconflicts":[]},{"address":"3B3q1GTLQQ7Fspo6ATy3cd3tg5yu97hkve","amount":0.021,"bip125-replaceable":"no","blockhash":"0000000000000000000debf11962f89e2ae08f8ff75803b0da6170af6c5c346b","blockindex":2618,"blocktime":1572188894,"category":"receive","confirmations":179,"involvesWatchonly":true,"label":"3B3q1GTLQQ7Fspo6ATy3cd3tg5yu97hkve","time":1572186009,"timereceived":1572186009,"txid":"54b159ac3a656bbaaf3bf0263b8deafad03b376ec0c2e9c715d0cf1caaf3495e","vout":0,"walletconflicts":[]},{"address":"1JsAjr6d21j9T8EMsYnQ6GXf1mM523JAv1","amount":0.17868444,"bip125-replaceable":"no","blockhash":"0000000000000000000debf11962f89e2ae08f8ff75803b0da6170af6c5c346b","blockindex":2618,"blocktime":1572188894,"category":"receive","confirmations":179,"label":"","time":1572186009,"timereceived":1572186009,"txid":"54b159ac3a656bbaaf3bf0263b8deafad03b376ec0c2e9c715d0cf1caaf3495e","vout":1,"walletconflicts":[]},{"abandoned":false,"address":"3AC6k1Y54knEdkgWjX3TjmWGjDHtJCNZZY","amount":-0.17822795,"bip125-replaceable":"no","blockhash":"00000000000000000009a60478f29f4910e29224ea5ed63d77321ac8c624ec45","blockindex":2377,"blocktime":1572190637,"category":"send","confirmations":177,"fee":-0.00009985,"involvesWatchonly":true,"label":"3AC6k1Y54knEdkgWjX3TjmWGjDHtJCNZZY","time":1572189626,"timereceived":1572189626,"txid":"eabc01e45db89ea8cf623f8e22847e4023c69bed3c7d396d573b89dec3fe17a7","vout":0,"walletconflicts":[]},{"abandoned":false,"address":"1JsAjr6d21j9T8EMsYnQ6GXf1mM523JAv1","amount":-0.00035664,"bip125-replaceable":"no","blockhash":"00000000000000000009a60478f29f4910e29224ea5ed63d77321ac8c624ec45","blockindex":2377,"blocktime":1572190637,"category":"send","confirmations":177,"fee":-0.00009985,"label":"","time":1572189626,"timereceived":1572189626,"txid":"eabc01e45db89ea8cf623f8e22847e4023c69bed3c7d396d573b89dec3fe17a7","vout":1,"walletconflicts":[]},{"address":"3AC6k1Y54knEdkgWjX3TjmWGjDHtJCNZZY","amount":0.17822795,"bip125-replaceable":"no","blockhash":"00000000000000000009a60478f29f4910e29224ea5ed63d77321ac8c624ec45","blockindex":2377,"blocktime":1572190637,"category":"receive","confirmations":177,"involvesWatchonly":true,"label":"3AC6k1Y54knEdkgWjX3TjmWGjDHtJCNZZY","time":1572189626,"timereceived":1572189626,"txid":"eabc01e45db89ea8cf623f8e22847e4023c69bed3c7d396d573b89dec3fe17a7","vout":0,"walletconflicts":[]},{"address":"1JsAjr6d21j9T8EMsYnQ6GXf1mM523JAv1","amount":0.00035664,"bip125-replaceable":"no","blockhash":"00000000000000000009a60478f29f4910e29224ea5ed63d77321ac8c624ec45","blockindex":2377,"blocktime":1572190637,"category":"receive","confirmations":177,"label":"","time":1572189626,"timereceived":1572189626,"txid":"eabc01e45db89ea8cf623f8e22847e4023c69bed3c7d396d573b89dec3fe17a7","vout":1,"walletconflicts":[]},{"abandoned":false,"address":"1Q3kQ1jsB2VyH83PJT1NXJqEaEcR6Yuknn","amount":-0.17809412,"bip125-replaceable":"no","blockhash":"000000000000000000125e17a9540ac901d70e92e987d59a1cf87ca36ebca830","blockindex":1680,"blocktime":1572191122,"category":"send","confirmations":176,"fee":-0.00013383,"involvesWatchonly":true,"time":1572190821,"timereceived":1572190821,"txid":"d3579f7be169ea8fd1358d0eda85bad31ce8080a6020dcd224eac8a663dc9bf7","vout":0,"walletconflicts":[]},{"abandoned":false,"address":"326VCyLKV1w4SxeYs81jQU1SC11njcL1eG","amount":-0.039676,"bip125-replaceable":"no","blockhash":"0000000000000000000d61630db06ed5d3054a39bf71a706efeaa9e86866b9d4","blockindex":2193,"blocktime":1572053656,"category":"send","confirmations":380,"fee":-0.00005653,"involvesWatchonly":true,"label":"326VCyLKV1w4SxeYs81jQU1SC11njcL1eG","time":1572052431,"timereceived":1572052431,"txid":"37b57fb36312e21ec7d069a55ab9bffc6abc7fe3731ed38502c5329025a9edf9","vout":0,"walletconflicts":[]},{"abandoned":false,"address":"1JsAjr6d21j9T8EMsYnQ6GXf1mM523JAv1","amount":-0.01845911,"bip125-replaceable":"no","blockhash":"0000000000000000000d61630db06ed5d3054a39bf71a706efeaa9e86866b9d4","blockindex":2193,"blocktime":1572053656,"category":"send","confirmations":380,"fee":-0.00005653,"label":"","time":1572052431,"timereceived":1572052431,"txid":"37b57fb36312e21ec7d069a55ab9bffc6abc7fe3731ed38502c5329025a9edf9","vout":1,"walletconflicts":[]},{"address":"326VCyLKV1w4SxeYs81jQU1SC11njcL1eG","amount":0.039676,"bip125-replaceable":"no","blockhash":"0000000000000000000d61630db06ed5d3054a39bf71a706efeaa9e86866b9d4","blockindex":2193,"blocktime":1572053656,"category":"receive","confirmations":380,"involvesWatchonly":true,"label":"326VCyLKV1w4SxeYs81jQU1SC11njcL1eG","time":1572052431,"timereceived":1572052431,"txid":"37b57fb36312e21ec7d069a55ab9bffc6abc7fe3731ed38502c5329025a9edf9","vout":0,"walletconflicts":[]},{"address":"1JsAjr6d21j9T8EMsYnQ6GXf1mM523JAv1","amount":0.01845911,"bip125-replaceable":"no","blockhash":"0000000000000000000d61630db06ed5d3054a39bf71a706efeaa9e86866b9d4","blockindex":2193,"blocktime":1572053656,"category":"receive","confirmations":380,"label":"","time":1572052431,"timereceived":1572052431,"txid":"37b57fb36312e21ec7d069a55ab9bffc6abc7fe3731ed38502c5329025a9edf9","vout":1,"walletconflicts":[]}]}"#;
let _res: ListSinceBlockRes = json::from_str(input).unwrap();
}