forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathutxo_common.rs
3982 lines (3652 loc) · 150 KB
/
utxo_common.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::{AddressBalanceStatus, HDAddressBalance, HDWalletBalanceOps};
use crate::coin_errors::{MyAddressError, ValidatePaymentError};
use crate::hd_pubkey::{ExtractExtendedPubkey, HDExtractPubkeyError, HDXPubExtractor};
use crate::hd_wallet::{AccountUpdatingError, AddressDerivingResult, HDAccountMut, HDAccountsMap,
NewAccountCreatingError};
use crate::hd_wallet_storage::{HDWalletCoinWithStorageOps, HDWalletStorageResult};
use crate::rpc_command::init_withdraw::WithdrawTaskHandle;
use crate::utxo::rpc_clients::{electrum_script_hash, BlockHashOrHeight, UnspentInfo, UnspentMap, UtxoRpcClientEnum,
UtxoRpcClientOps, UtxoRpcResult};
use crate::utxo::spv::SimplePaymentVerification;
use crate::utxo::tx_cache::TxCacheResult;
use crate::utxo::utxo_withdraw::{InitUtxoWithdraw, StandardUtxoWithdraw, UtxoWithdraw};
use crate::{CanRefundHtlc, CoinBalance, CoinWithDerivationMethod, GetWithdrawSenderAddress, HDAccountAddressId,
RawTransactionError, RawTransactionRequest, RawTransactionRes, SearchForSwapTxSpendInput, SignatureError,
SignatureResult, SwapOps, TradePreimageValue, TransactionFut, TxFeeDetails, TxMarshalingErr,
ValidateAddressResult, ValidateOtherPubKeyErr, ValidatePaymentFut, ValidatePaymentInput,
VerificationError, VerificationResult, WatcherValidatePaymentInput, WithdrawFrom, WithdrawResult,
WithdrawSenderAddress};
use bitcrypto::dhash256;
pub use bitcrypto::{dhash160, sha256, ChecksumType};
use chain::constants::SEQUENCE_FINAL;
use chain::{OutPoint, TransactionOutput};
use common::executor::Timer;
use common::jsonrpc_client::JsonRpcErrorType;
use common::log::{error, warn};
use common::{now_ms, one_hundred, ten_f64};
use crypto::{Bip32DerPathOps, Bip44Chain, Bip44DerPathError, Bip44DerivationPath, RpcDerivationPath};
use futures::compat::Future01CompatExt;
use futures::future::{FutureExt, TryFutureExt};
use futures01::future::Either;
use itertools::Itertools;
use keys::bytes::Bytes;
use keys::{Address, AddressFormat as UtxoAddressFormat, AddressHashEnum, CompactSignature, Public, SegwitAddress,
Type as ScriptType};
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::*;
use mm2_number::{BigDecimal, MmNumber};
use primitives::hash::H512;
use rpc::v1::types::{Bytes as BytesJson, ToTxHash, TransactionInputEnum, H256 as H256Json};
use script::{Builder, Opcode, Script, ScriptAddress, TransactionInputSigner, UnsignedTransactionInput};
use secp256k1::{PublicKey, Signature};
use serde_json::{self as json};
use serialization::{deserialize, serialize, serialize_with_flags, CoinVariant, CompactInteger, Serializable, Stream,
SERIALIZE_TRANSACTION_WITNESS};
use std::cmp::Ordering;
use std::collections::hash_map::{Entry, HashMap};
use std::str::FromStr;
use std::sync::atomic::Ordering as AtomicOrdering;
use utxo_signer::with_key_pair::p2sh_spend;
use utxo_signer::UtxoSignerOps;
pub use chain::Transaction as UtxoTx;
pub mod utxo_tx_history_v2_common;
pub const DEFAULT_FEE_VOUT: usize = 0;
pub const DEFAULT_SWAP_TX_SPEND_SIZE: u64 = 305;
pub const DEFAULT_SWAP_VOUT: usize = 0;
const MIN_BTC_TRADING_VOL: &str = "0.00777";
macro_rules! true_or {
($cond: expr, $etype: expr) => {
if !$cond {
return Err(MmError::new($etype));
}
};
}
lazy_static! {
pub static ref HISTORY_TOO_LARGE_ERROR: Json = json!({
"code": 1,
"message": "history too large"
});
}
pub const HISTORY_TOO_LARGE_ERR_CODE: i64 = -1;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct UtxoMergeParams {
merge_at: usize,
#[serde(default = "ten_f64")]
check_every: f64,
#[serde(default = "one_hundred")]
max_merge_at_once: usize,
}
pub async fn get_tx_fee(coin: &UtxoCoinFields) -> UtxoRpcResult<ActualTxFee> {
let conf = &coin.conf;
match &coin.tx_fee {
TxFee::Dynamic(method) => {
let fee = coin
.rpc_client
.estimate_fee_sat(coin.decimals, method, &conf.estimate_fee_mode, conf.estimate_fee_blocks)
.compat()
.await?;
Ok(ActualTxFee::Dynamic(fee))
},
TxFee::FixedPerKb(satoshis) => Ok(ActualTxFee::FixedPerKb(*satoshis)),
}
}
fn derive_address_with_cache<T>(
coin: &T,
hd_account: &UtxoHDAccount,
hd_addresses_cache: &mut HashMap<HDAddressId, UtxoHDAddress>,
hd_address_id: HDAddressId,
) -> AddressDerivingResult<UtxoHDAddress>
where
T: UtxoCommonOps,
{
// Check if the given HD address has been derived already.
if let Some(hd_address) = hd_addresses_cache.get(&hd_address_id) {
return Ok(hd_address.clone());
}
let change_child = hd_address_id.chain.to_child_number();
let address_id_child = ChildNumber::from(hd_address_id.address_id);
let derived_pubkey = hd_account
.extended_pubkey
.derive_child(change_child)?
.derive_child(address_id_child)?;
let address = coin.address_from_extended_pubkey(&derived_pubkey);
let pubkey = Public::Compressed(H264::from(derived_pubkey.public_key().serialize()));
let mut derivation_path = hd_account.account_derivation_path.to_derivation_path();
derivation_path.push(change_child);
derivation_path.push(address_id_child);
let hd_address = HDAddress {
address,
pubkey,
derivation_path,
};
// Cache the derived `hd_address`.
hd_addresses_cache.insert(hd_address_id, hd_address.clone());
Ok(hd_address)
}
/// [`HDWalletCoinOps::derive_addresses`] native implementation.
///
/// # Important
///
/// The [`HDAddressesCache::cache`] mutex is locked once for the entire duration of this function.
#[cfg(not(target_arch = "wasm32"))]
pub async fn derive_addresses<T, Ids>(
coin: &T,
hd_account: &UtxoHDAccount,
address_ids: Ids,
) -> AddressDerivingResult<Vec<UtxoHDAddress>>
where
T: UtxoCommonOps,
Ids: Iterator<Item = HDAddressId>,
{
let mut hd_addresses_cache = hd_account.derived_addresses.lock().await;
address_ids
.map(|hd_address_id| derive_address_with_cache(coin, hd_account, &mut hd_addresses_cache, hd_address_id))
.collect()
}
/// [`HDWalletCoinOps::derive_addresses`] WASM implementation.
///
/// # Important
///
/// This function locks [`HDAddressesCache::cache`] mutex at each iteration.
///
/// # Performance
///
/// Locking the [`HDAddressesCache::cache`] mutex at each iteration may significantly degrade performance.
/// But this is required at least for now due the facts that:
/// 1) mm2 runs in the same thread as `KomodoPlatform/air_dex` runs;
/// 2) [`ExtendedPublicKey::derive_child`] is a synchronous operation, and it takes a long time.
/// So we need to periodically invoke Javascript runtime to handle UI events and other asynchronous tasks.
#[cfg(target_arch = "wasm32")]
pub async fn derive_addresses<T, Ids>(
coin: &T,
hd_account: &UtxoHDAccount,
address_ids: Ids,
) -> AddressDerivingResult<Vec<UtxoHDAddress>>
where
T: UtxoCommonOps,
Ids: Iterator<Item = HDAddressId>,
{
let mut result = Vec::new();
for hd_address_id in address_ids {
let mut hd_addresses_cache = hd_account.derived_addresses.lock().await;
let hd_address = derive_address_with_cache(coin, hd_account, &mut hd_addresses_cache, hd_address_id)?;
result.push(hd_address);
}
Ok(result)
}
pub async fn create_new_account<'a, Coin, XPubExtractor>(
coin: &Coin,
hd_wallet: &'a UtxoHDWallet,
xpub_extractor: &XPubExtractor,
) -> MmResult<HDAccountMut<'a, UtxoHDAccount>, NewAccountCreatingError>
where
Coin: ExtractExtendedPubkey<ExtendedPublicKey = Secp256k1ExtendedPublicKey>
+ HDWalletCoinWithStorageOps<HDWallet = UtxoHDWallet, HDAccount = UtxoHDAccount>
+ Sync,
XPubExtractor: HDXPubExtractor + Sync,
{
const INIT_ACCOUNT_ID: u32 = 0;
let new_account_id = hd_wallet
.accounts
.lock()
.await
.iter()
// The last element of the BTreeMap has the max account index.
.last()
.map(|(account_id, _account)| *account_id + 1)
.unwrap_or(INIT_ACCOUNT_ID);
let max_accounts_number = hd_wallet.account_limit();
if new_account_id >= max_accounts_number {
return MmError::err(NewAccountCreatingError::AccountLimitReached { max_accounts_number });
}
let account_child_hardened = true;
let account_child = ChildNumber::new(new_account_id, account_child_hardened)
.map_to_mm(|e| NewAccountCreatingError::Internal(e.to_string()))?;
let account_derivation_path: Bip44PathToAccount = hd_wallet.derivation_path.derive(account_child)?;
let account_pubkey = coin
.extract_extended_pubkey(xpub_extractor, account_derivation_path.to_derivation_path())
.await?;
let new_account = UtxoHDAccount {
account_id: new_account_id,
extended_pubkey: account_pubkey,
account_derivation_path,
// We don't know how many addresses are used by the user at this moment.
external_addresses_number: 0,
internal_addresses_number: 0,
derived_addresses: HDAddressesCache::default(),
};
let accounts = hd_wallet.accounts.lock().await;
if accounts.contains_key(&new_account_id) {
let error = format!(
"Account '{}' has been activated while we proceed the 'create_new_account' function",
new_account_id
);
return MmError::err(NewAccountCreatingError::Internal(error));
}
coin.upload_new_account(hd_wallet, new_account.to_storage_item())
.await?;
Ok(AsyncMutexGuard::map(accounts, |accounts| {
accounts
.entry(new_account_id)
// the `entry` method should return [`Entry::Vacant`] due to the checks above
.or_insert(new_account)
}))
}
pub async fn set_known_addresses_number<T>(
coin: &T,
hd_wallet: &UtxoHDWallet,
hd_account: &mut UtxoHDAccount,
chain: Bip44Chain,
new_known_addresses_number: u32,
) -> MmResult<(), AccountUpdatingError>
where
T: HDWalletCoinWithStorageOps<HDWallet = UtxoHDWallet, HDAccount = UtxoHDAccount> + Sync,
{
let max_addresses_number = hd_wallet.address_limit();
if new_known_addresses_number >= max_addresses_number {
return MmError::err(AccountUpdatingError::AddressLimitReached { max_addresses_number });
}
match chain {
Bip44Chain::External => {
coin.update_external_addresses_number(hd_wallet, hd_account.account_id, new_known_addresses_number)
.await?;
hd_account.external_addresses_number = new_known_addresses_number;
},
Bip44Chain::Internal => {
coin.update_internal_addresses_number(hd_wallet, hd_account.account_id, new_known_addresses_number)
.await?;
hd_account.internal_addresses_number = new_known_addresses_number;
},
}
Ok(())
}
pub async fn produce_hd_address_scanner<T>(coin: &T) -> BalanceResult<UtxoAddressScanner>
where
T: AsRef<UtxoCoinFields>,
{
Ok(UtxoAddressScanner::init(coin.as_ref().rpc_client.clone()).await?)
}
pub async fn scan_for_new_addresses<T>(
coin: &T,
hd_wallet: &T::HDWallet,
hd_account: &mut T::HDAccount,
address_scanner: &T::HDAddressScanner,
gap_limit: u32,
) -> BalanceResult<Vec<HDAddressBalance>>
where
T: HDWalletBalanceOps + Sync,
T::Address: std::fmt::Display,
{
let mut addresses = scan_for_new_addresses_impl(
coin,
hd_wallet,
hd_account,
address_scanner,
Bip44Chain::External,
gap_limit,
)
.await?;
addresses.extend(
scan_for_new_addresses_impl(
coin,
hd_wallet,
hd_account,
address_scanner,
Bip44Chain::Internal,
gap_limit,
)
.await?,
);
Ok(addresses)
}
/// Checks addresses that either had empty transaction history last time we checked or has not been checked before.
/// The checking stops at the moment when we find `gap_limit` consecutive empty addresses.
pub async fn scan_for_new_addresses_impl<T>(
coin: &T,
hd_wallet: &T::HDWallet,
hd_account: &mut T::HDAccount,
address_scanner: &T::HDAddressScanner,
chain: Bip44Chain,
gap_limit: u32,
) -> BalanceResult<Vec<HDAddressBalance>>
where
T: HDWalletBalanceOps + Sync,
T::Address: std::fmt::Display,
{
let mut balances = Vec::with_capacity(gap_limit as usize);
// Get the first unknown address id.
let mut checking_address_id = hd_account
.known_addresses_number(chain)
// A UTXO coin should support both [`Bip44Chain::External`] and [`Bip44Chain::Internal`].
.mm_err(|e| BalanceError::Internal(e.to_string()))?;
let mut unused_addresses_counter = 0;
let max_addresses_number = hd_wallet.address_limit();
while checking_address_id < max_addresses_number && unused_addresses_counter <= gap_limit {
let HDAddress {
address: checking_address,
derivation_path: checking_address_der_path,
..
} = coin.derive_address(hd_account, chain, checking_address_id).await?;
match coin.is_address_used(&checking_address, address_scanner).await? {
// We found a non-empty address, so we have to fill up the balance list
// with zeros starting from `last_non_empty_address_id = checking_address_id - unused_addresses_counter`.
AddressBalanceStatus::Used(non_empty_balance) => {
let last_non_empty_address_id = checking_address_id - unused_addresses_counter;
// First, derive all empty addresses and put it into `balances` with default balance.
let address_ids = (last_non_empty_address_id..checking_address_id)
.into_iter()
.map(|address_id| HDAddressId { chain, address_id });
let empty_addresses =
coin.derive_addresses(hd_account, address_ids)
.await?
.into_iter()
.map(|empty_address| HDAddressBalance {
address: empty_address.address.to_string(),
derivation_path: RpcDerivationPath(empty_address.derivation_path),
chain,
balance: CoinBalance::default(),
});
balances.extend(empty_addresses);
// Then push this non-empty address.
balances.push(HDAddressBalance {
address: checking_address.to_string(),
derivation_path: RpcDerivationPath(checking_address_der_path),
chain,
balance: non_empty_balance,
});
// Reset the counter of unused addresses to zero since we found a non-empty address.
unused_addresses_counter = 0;
},
AddressBalanceStatus::NotUsed => unused_addresses_counter += 1,
}
checking_address_id += 1;
}
coin.set_known_addresses_number(
hd_wallet,
hd_account,
chain,
checking_address_id - unused_addresses_counter,
)
.await?;
Ok(balances)
}
pub async fn all_known_addresses_balances<T>(
coin: &T,
hd_account: &T::HDAccount,
) -> BalanceResult<Vec<HDAddressBalance>>
where
T: HDWalletBalanceOps + Sync,
T::Address: std::fmt::Display + Clone,
{
let external_addresses = hd_account
.known_addresses_number(Bip44Chain::External)
// A UTXO coin should support both [`Bip44Chain::External`] and [`Bip44Chain::Internal`].
.mm_err(|e| BalanceError::Internal(e.to_string()))?;
let internal_addresses = hd_account
.known_addresses_number(Bip44Chain::Internal)
// A UTXO coin should support both [`Bip44Chain::External`] and [`Bip44Chain::Internal`].
.mm_err(|e| BalanceError::Internal(e.to_string()))?;
let mut balances = coin
.known_addresses_balances_with_ids(hd_account, Bip44Chain::External, 0..external_addresses)
.await?;
balances.extend(
coin.known_addresses_balances_with_ids(hd_account, Bip44Chain::Internal, 0..internal_addresses)
.await?,
);
Ok(balances)
}
pub async fn load_hd_accounts_from_storage(
hd_wallet_storage: &HDWalletCoinStorage,
derivation_path: &Bip44PathToCoin,
) -> HDWalletStorageResult<HDAccountsMap<UtxoHDAccount>> {
let accounts = hd_wallet_storage.load_all_accounts().await?;
let res: HDWalletStorageResult<HDAccountsMap<UtxoHDAccount>> = accounts
.iter()
.map(|account_info| {
let account = UtxoHDAccount::try_from_storage_item(derivation_path, account_info)?;
Ok((account.account_id, account))
})
.collect();
match res {
Ok(accounts) => Ok(accounts),
Err(e) if e.get_inner().is_deserializing_err() => {
warn!("Error loading HD accounts from the storage: '{}'. Clear accounts", e);
hd_wallet_storage.clear_accounts().await?;
Ok(HDAccountsMap::new())
},
Err(e) => Err(e),
}
}
/// Requests balance of the given `address`.
pub async fn address_balance<T>(coin: &T, address: &Address) -> BalanceResult<CoinBalance>
where
T: UtxoCommonOps + GetUtxoListOps + MarketCoinOps,
{
if coin.as_ref().check_utxo_maturity {
let (unspents, _) = coin.get_mature_unspent_ordered_list(address).await?;
return Ok(unspents.to_coin_balance(coin.as_ref().decimals));
}
let balance = coin
.as_ref()
.rpc_client
.display_balance(address.clone(), coin.as_ref().decimals)
.compat()
.await?;
Ok(CoinBalance {
spendable: balance,
unspendable: BigDecimal::from(0),
})
}
/// Requests balances of the given `addresses`.
/// The pairs `(Address, CoinBalance)` are guaranteed to be in the same order in which they were requested.
pub async fn addresses_balances<T>(coin: &T, addresses: Vec<Address>) -> BalanceResult<Vec<(Address, CoinBalance)>>
where
T: UtxoCommonOps + GetUtxoMapOps + MarketCoinOps,
{
if coin.as_ref().check_utxo_maturity {
let (unspents_map, _) = coin.get_mature_unspent_ordered_map(addresses.clone()).await?;
addresses
.into_iter()
.map(|address| {
let unspents = unspents_map.get(&address).or_mm_err(|| {
let error = format!("'get_mature_unspent_ordered_map' should have returned '{}'", address);
BalanceError::Internal(error)
})?;
let balance = unspents.to_coin_balance(coin.as_ref().decimals);
Ok((address, balance))
})
.collect()
} else {
Ok(coin
.as_ref()
.rpc_client
.display_balances(addresses.clone(), coin.as_ref().decimals)
.compat()
.await?
.into_iter()
.map(|(address, spendable)| {
let unspendable = BigDecimal::from(0);
let balance = CoinBalance { spendable, unspendable };
(address, balance)
})
.collect())
}
}
pub fn derivation_method(coin: &UtxoCoinFields) -> &DerivationMethod<Address, UtxoHDWallet> { &coin.derivation_method }
pub async fn extract_extended_pubkey<XPubExtractor>(
conf: &UtxoCoinConf,
xpub_extractor: &XPubExtractor,
derivation_path: DerivationPath,
) -> MmResult<Secp256k1ExtendedPublicKey, HDExtractPubkeyError>
where
XPubExtractor: HDXPubExtractor,
{
let trezor_coin = conf
.trezor_coin
.clone()
.or_mm_err(|| HDExtractPubkeyError::CoinDoesntSupportTrezor)?;
let xpub = xpub_extractor.extract_utxo_xpub(trezor_coin, derivation_path).await?;
Secp256k1ExtendedPublicKey::from_str(&xpub).map_to_mm(|e| HDExtractPubkeyError::InvalidXpub(e.to_string()))
}
/// returns the fee required to be paid for HTLC spend transaction
pub async fn get_htlc_spend_fee<T: UtxoCommonOps>(coin: &T, tx_size: u64) -> UtxoRpcResult<u64> {
let coin_fee = coin.get_tx_fee().await?;
let mut fee = match coin_fee {
// atomic swap payment spend transaction is slightly more than 300 bytes in average as of now
ActualTxFee::Dynamic(fee_per_kb) => (fee_per_kb * tx_size) / KILO_BYTE,
// return satoshis here as swap spend transaction size is always less than 1 kb
ActualTxFee::FixedPerKb(satoshis) => {
let tx_size_kb = if tx_size % KILO_BYTE == 0 {
tx_size / KILO_BYTE
} else {
tx_size / KILO_BYTE + 1
};
satoshis * tx_size_kb
},
};
if coin.as_ref().conf.force_min_relay_fee {
let relay_fee = coin.as_ref().rpc_client.get_relay_fee().compat().await?;
let relay_fee_sat = sat_from_big_decimal(&relay_fee, coin.as_ref().decimals)?;
if fee < relay_fee_sat {
fee = relay_fee_sat;
}
}
Ok(fee)
}
pub fn addresses_from_script<T: UtxoCommonOps>(coin: &T, script: &Script) -> Result<Vec<Address>, String> {
let destinations: Vec<ScriptAddress> = try_s!(script.extract_destinations());
let conf = &coin.as_ref().conf;
let addresses = destinations
.into_iter()
.map(|dst| {
let (prefix, t_addr_prefix, addr_format) = match dst.kind {
ScriptType::P2PKH => (
conf.pub_addr_prefix,
conf.pub_t_addr_prefix,
coin.addr_format_for_standard_scripts(),
),
ScriptType::P2SH => (
conf.p2sh_addr_prefix,
conf.p2sh_t_addr_prefix,
coin.addr_format_for_standard_scripts(),
),
ScriptType::P2WPKH => (conf.pub_addr_prefix, conf.pub_t_addr_prefix, UtxoAddressFormat::Segwit),
ScriptType::P2WSH => (conf.pub_addr_prefix, conf.pub_t_addr_prefix, UtxoAddressFormat::Segwit),
};
Address {
hash: dst.hash,
checksum_type: conf.checksum_type,
prefix,
t_addr_prefix,
hrp: conf.bech32_hrp.clone(),
addr_format,
}
})
.collect();
Ok(addresses)
}
pub fn denominate_satoshis(coin: &UtxoCoinFields, satoshi: i64) -> f64 {
satoshi as f64 / 10f64.powf(coin.decimals as f64)
}
pub fn base_coin_balance<T>(coin: &T) -> BalanceFut<BigDecimal>
where
T: MarketCoinOps,
{
coin.my_spendable_balance()
}
pub fn address_from_str_unchecked(coin: &UtxoCoinFields, address: &str) -> MmResult<Address, AddrFromStrError> {
let mut errors = Vec::with_capacity(3);
match Address::from_str(address) {
Ok(legacy) => return Ok(legacy),
Err(e) => errors.push(e.to_string()),
};
match Address::from_segwitaddress(
address,
coin.conf.checksum_type,
coin.conf.pub_addr_prefix,
coin.conf.pub_t_addr_prefix,
) {
Ok(segwit) => return Ok(segwit),
Err(e) => errors.push(e),
}
match Address::from_cashaddress(
address,
coin.conf.checksum_type,
coin.conf.pub_addr_prefix,
coin.conf.p2sh_addr_prefix,
coin.conf.pub_t_addr_prefix,
) {
Ok(cashaddress) => return Ok(cashaddress),
Err(e) => errors.push(e),
}
MmError::err(AddrFromStrError::CannotDetermineFormat(errors))
}
pub fn my_public_key(coin: &UtxoCoinFields) -> Result<&Public, MmError<UnexpectedDerivationMethod>> {
match coin.priv_key_policy {
PrivKeyPolicy::KeyPair(ref key_pair) => Ok(key_pair.public()),
// Hardware Wallets requires BIP39/BIP44 derivation path to extract a public key.
PrivKeyPolicy::Trezor => MmError::err(UnexpectedDerivationMethod::IguanaPrivKeyUnavailable),
}
}
pub fn checked_address_from_str<T: UtxoCommonOps>(coin: &T, address: &str) -> MmResult<Address, AddrFromStrError> {
let addr = address_from_str_unchecked(coin.as_ref(), address)?;
check_withdraw_address_supported(coin, &addr)?;
Ok(addr)
}
pub async fn get_current_mtp(coin: &UtxoCoinFields, coin_variant: CoinVariant) -> UtxoRpcResult<u32> {
let current_block = coin.rpc_client.get_block_count().compat().await?;
coin.rpc_client
.get_median_time_past(current_block, coin.conf.mtp_block_count, coin_variant)
.compat()
.await
}
pub fn send_outputs_from_my_address<T>(coin: T, outputs: Vec<TransactionOutput>) -> TransactionFut
where
T: UtxoCommonOps + GetUtxoListOps,
{
let fut = send_outputs_from_my_address_impl(coin, outputs);
Box::new(fut.boxed().compat().map(|tx| tx.into()))
}
pub fn tx_size_in_v_bytes(from_addr_format: &UtxoAddressFormat, tx: &UtxoTx) -> usize {
let transaction_bytes = serialize(tx);
// 2 bytes are used to indicate the length of signature and pubkey
// total is 107
let additional_len = 2 + MAX_DER_SIGNATURE_LEN + COMPRESSED_PUBKEY_LEN;
// Virtual size of the transaction
// https://bitcoin.stackexchange.com/questions/87275/how-to-calculate-segwit-transaction-fee-in-bytes/87276#87276
match from_addr_format {
UtxoAddressFormat::Segwit => {
let base_size = transaction_bytes.len();
// 4 additional bytes (2 for the marker and 2 for the flag) and 1 additional byte for every input in the witness for the SIGHASH flag
let total_size = transaction_bytes.len() + 4 + tx.inputs().len() * (additional_len + 1);
((0.75 * base_size as f64) + (0.25 * total_size as f64)) as usize
},
_ => transaction_bytes.len() + tx.inputs().len() * additional_len,
}
}
pub struct UtxoTxBuilder<'a, T: AsRef<UtxoCoinFields> + UtxoTxGenerationOps> {
coin: &'a T,
from: Option<Address>,
/// The available inputs that *can* be included in the resulting tx
available_inputs: Vec<UnspentInfo>,
fee_policy: FeePolicy,
fee: Option<ActualTxFee>,
gas_fee: Option<u64>,
tx: TransactionInputSigner,
change: u64,
sum_inputs: u64,
sum_outputs_value: u64,
tx_fee: u64,
min_relay_fee: Option<u64>,
dust: Option<u64>,
}
impl<'a, T: AsRef<UtxoCoinFields> + UtxoTxGenerationOps> UtxoTxBuilder<'a, T> {
pub fn new(coin: &'a T) -> Self {
UtxoTxBuilder {
tx: coin.as_ref().transaction_preimage(),
coin,
from: coin.as_ref().derivation_method.iguana().cloned(),
available_inputs: vec![],
fee_policy: FeePolicy::SendExact,
fee: None,
gas_fee: None,
change: 0,
sum_inputs: 0,
sum_outputs_value: 0,
tx_fee: 0,
min_relay_fee: None,
dust: None,
}
}
pub fn with_from_address(mut self, from: Address) -> Self {
self.from = Some(from);
self
}
pub fn with_dust(mut self, dust_amount: u64) -> Self {
self.dust = Some(dust_amount);
self
}
pub fn add_required_inputs(mut self, inputs: impl IntoIterator<Item = UnspentInfo>) -> Self {
self.tx
.inputs
.extend(inputs.into_iter().map(|input| UnsignedTransactionInput {
previous_output: input.outpoint,
sequence: SEQUENCE_FINAL,
amount: input.value,
witness: Vec::new(),
}));
self
}
/// This function expects that utxos are sorted by amounts in ascending order
/// Consider sorting before calling this function
pub fn add_available_inputs(mut self, inputs: impl IntoIterator<Item = UnspentInfo>) -> Self {
self.available_inputs.extend(inputs);
self
}
pub fn add_outputs(mut self, outputs: impl IntoIterator<Item = TransactionOutput>) -> Self {
self.tx.outputs.extend(outputs);
self
}
pub fn with_fee_policy(mut self, new_policy: FeePolicy) -> Self {
self.fee_policy = new_policy;
self
}
pub fn with_fee(mut self, fee: ActualTxFee) -> Self {
self.fee = Some(fee);
self
}
/// Note `gas_fee` should be enough to execute all of the contract calls within UTXO outputs.
/// QRC20 specific: `gas_fee` should be calculated by: gas_limit * gas_price * (count of contract calls),
/// or should be sum of gas fee of all contract calls.
pub fn with_gas_fee(mut self, gas_fee: u64) -> Self {
self.gas_fee = Some(gas_fee);
self
}
/// Recalculates fee and checks whether transaction is complete (inputs collected cover the outputs)
fn update_fee_and_check_completeness(
&mut self,
from_addr_format: &UtxoAddressFormat,
actual_tx_fee: &ActualTxFee,
) -> bool {
self.tx_fee = match &actual_tx_fee {
ActualTxFee::Dynamic(f) => {
let transaction = UtxoTx::from(self.tx.clone());
let v_size = tx_size_in_v_bytes(from_addr_format, &transaction);
(f * v_size as u64) / KILO_BYTE
},
ActualTxFee::FixedPerKb(f) => {
let transaction = UtxoTx::from(self.tx.clone());
let v_size = tx_size_in_v_bytes(from_addr_format, &transaction) as u64;
let v_size_kb = if v_size % KILO_BYTE == 0 {
v_size / KILO_BYTE
} else {
v_size / KILO_BYTE + 1
};
f * v_size_kb
},
};
match self.fee_policy {
FeePolicy::SendExact => {
let mut outputs_plus_fee = self.sum_outputs_value + self.tx_fee;
if self.sum_inputs >= outputs_plus_fee {
self.change = self.sum_inputs - outputs_plus_fee;
if self.change > self.dust() {
// there will be change output
if let ActualTxFee::Dynamic(ref f) = actual_tx_fee {
self.tx_fee += (f * P2PKH_OUTPUT_LEN) / KILO_BYTE;
outputs_plus_fee += (f * P2PKH_OUTPUT_LEN) / KILO_BYTE;
}
}
if let Some(min_relay) = self.min_relay_fee {
if self.tx_fee < min_relay {
outputs_plus_fee -= self.tx_fee;
outputs_plus_fee += min_relay;
self.tx_fee = min_relay;
}
}
self.sum_inputs >= outputs_plus_fee
} else {
false
}
},
FeePolicy::DeductFromOutput(_) => {
if self.sum_inputs >= self.sum_outputs_value {
self.change = self.sum_inputs - self.sum_outputs_value;
if self.change > self.dust() {
if let ActualTxFee::Dynamic(ref f) = actual_tx_fee {
self.tx_fee += (f * P2PKH_OUTPUT_LEN) / KILO_BYTE;
}
}
if let Some(min_relay) = self.min_relay_fee {
if self.tx_fee < min_relay {
self.tx_fee = min_relay;
}
}
true
} else {
false
}
},
}
}
fn dust(&self) -> u64 {
match self.dust {
Some(dust) => dust,
None => self.coin.as_ref().dust_amount,
}
}
/// Generates unsigned transaction (TransactionInputSigner) from specified utxos and outputs.
/// Sends the change (inputs amount - outputs amount) to the [`UtxoTxBuilder::from`] address.
/// Also returns additional transaction data
pub async fn build(mut self) -> GenerateTxResult {
let coin = self.coin;
let dust: u64 = self.dust();
let from = self
.from
.clone()
.or_mm_err(|| GenerateTxError::Internal("'from' address is not specified".to_owned()))?;
let change_script_pubkey = output_script(&from, ScriptType::P2PKH).to_bytes();
let actual_tx_fee = match self.fee {
Some(fee) => fee,
None => coin.get_tx_fee().await?,
};
true_or!(!self.tx.outputs.is_empty(), GenerateTxError::EmptyOutputs);
let mut received_by_me = 0;
for output in self.tx.outputs.iter() {
let script: Script = output.script_pubkey.clone().into();
if script.opcodes().next() != Some(Ok(Opcode::OP_RETURN)) {
true_or!(output.value >= dust, GenerateTxError::OutputValueLessThanDust {
value: output.value,
dust
});
}
self.sum_outputs_value += output.value;
if output.script_pubkey == change_script_pubkey {
received_by_me += output.value;
}
}
if let Some(gas_fee) = self.gas_fee {
self.sum_outputs_value += gas_fee;
}
true_or!(
!self.available_inputs.is_empty() || !self.tx.inputs.is_empty(),
GenerateTxError::EmptyUtxoSet {
required: self.sum_outputs_value
}
);
self.min_relay_fee = if coin.as_ref().conf.force_min_relay_fee {
let fee_dec = coin.as_ref().rpc_client.get_relay_fee().compat().await?;
let min_relay_fee = sat_from_big_decimal(&fee_dec, coin.as_ref().decimals)?;
Some(min_relay_fee)
} else {
None
};
for utxo in self.available_inputs.clone() {
self.tx.inputs.push(UnsignedTransactionInput {
previous_output: utxo.outpoint,
sequence: SEQUENCE_FINAL,
amount: utxo.value,
witness: vec![],
});
self.sum_inputs += utxo.value;
if self.update_fee_and_check_completeness(&from.addr_format, &actual_tx_fee) {
break;
}
}
match self.fee_policy {
FeePolicy::SendExact => self.sum_outputs_value += self.tx_fee,
FeePolicy::DeductFromOutput(i) => {
let min_output = self.tx_fee + dust;
let val = self.tx.outputs[i].value;
true_or!(val >= min_output, GenerateTxError::DeductFeeFromOutputFailed {
output_idx: i,
output_value: val,
required: min_output,
});
self.tx.outputs[i].value -= self.tx_fee;
if self.tx.outputs[i].script_pubkey == change_script_pubkey {
received_by_me -= self.tx_fee;
}
},
};
true_or!(
self.sum_inputs >= self.sum_outputs_value,
GenerateTxError::NotEnoughUtxos {
sum_utxos: self.sum_inputs,
required: self.sum_outputs_value
}
);
let change = self.sum_inputs - self.sum_outputs_value;
let unused_change = if change > dust {
self.tx.outputs.push({
TransactionOutput {
value: change,
script_pubkey: change_script_pubkey.clone(),
}
});
received_by_me += change;
None
} else if change > 0 {
Some(change)
} else {
None
};
let data = AdditionalTxData {
fee_amount: self.tx_fee,
received_by_me,
spent_by_me: self.sum_inputs,
unused_change,
// will be changed if the ticker is KMD
kmd_rewards: None,
};
Ok(coin
.calc_interest_if_required(self.tx, data, change_script_pubkey)
.await?)
}
}
/// Calculates interest if the coin is KMD
/// Adds the value to existing output to my_script_pub or creates additional interest output
/// returns transaction and data as is if the coin is not KMD
pub async fn calc_interest_if_required<T: UtxoCommonOps>(
coin: &T,
mut unsigned: TransactionInputSigner,
mut data: AdditionalTxData,
my_script_pub: Bytes,
) -> UtxoRpcResult<(TransactionInputSigner, AdditionalTxData)> {
if coin.as_ref().conf.ticker != "KMD" {
return Ok((unsigned, data));
}
unsigned.lock_time = coin.get_current_mtp().await?;
let mut interest = 0;
for input in unsigned.inputs.iter() {
let prev_hash = input.previous_output.hash.reversed().into();
let tx = coin
.as_ref()
.rpc_client
.get_verbose_transaction(&prev_hash)