forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
bch.rs
1580 lines (1358 loc) · 58.7 KB
/
bch.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_errors::MyAddressError;
use crate::my_tx_history_v2::{CoinWithTxHistoryV2, MyTxHistoryErrorV2, MyTxHistoryTarget, TxDetailsBuilder,
TxHistoryStorage};
use crate::tx_history_storage::{GetTxHistoryFilters, WalletId};
use crate::utxo::rpc_clients::UtxoRpcFut;
use crate::utxo::slp::{parse_slp_script, SlpGenesisParams, SlpTokenInfo, SlpTransaction, SlpUnspent};
use crate::utxo::utxo_builder::{UtxoArcBuilder, UtxoCoinBuilder};
use crate::utxo::utxo_common::big_decimal_from_sat_unsigned;
use crate::utxo::utxo_tx_history_v2::{UtxoMyAddressesHistoryError, UtxoTxDetailsError, UtxoTxDetailsParams,
UtxoTxHistoryOps};
use crate::{BlockHeightAndTime, CanRefundHtlc, CheckIfMyPaymentSentArgs, CoinBalance, CoinProtocol,
CoinWithDerivationMethod, ConfirmPaymentInput, IguanaPrivKey, MakerSwapTakerCoin, MmCoinEnum,
NegotiateSwapContractAddrErr, PaymentInstructionArgs, PaymentInstructions, PaymentInstructionsErr,
PrivKeyBuildPolicy, RawTransactionFut, RawTransactionRequest, RefundError, RefundPaymentArgs,
RefundResult, SearchForSwapTxSpendInput, SendMakerPaymentSpendPreimageInput, SendPaymentArgs,
SignatureResult, SpendPaymentArgs, SwapOps, TakerSwapMakerCoin, TradePreimageValue, TransactionFut,
TransactionType, TxFeeDetails, TxMarshalingErr, UnexpectedDerivationMethod, ValidateAddressResult,
ValidateFeeArgs, ValidateInstructionsErr, ValidateOtherPubKeyErr, ValidatePaymentError,
ValidatePaymentFut, ValidatePaymentInput, VerificationResult, WaitForHTLCTxSpendArgs, WatcherOps,
WatcherReward, WatcherRewardError, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput,
WatcherValidateTakerFeeInput, WithdrawFut};
use common::executor::{AbortableSystem, AbortedError};
use common::log::warn;
use derive_more::Display;
use futures::{FutureExt, TryFutureExt};
use itertools::Either as EitherIter;
use keys::hash::H256;
use keys::CashAddress;
pub use keys::NetworkPrefix as CashAddrPrefix;
use mm2_metrics::MetricsArc;
use mm2_number::MmNumber;
use serde_json::{self as json, Value as Json};
use serialization::{deserialize, CoinVariant};
use std::sync::MutexGuard;
pub type BchUnspentMap = HashMap<Address, BchUnspents>;
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct BchActivationRequest {
#[serde(default)]
allow_slp_unsafe_conf: bool,
bchd_urls: Vec<String>,
#[serde(flatten)]
pub utxo_params: UtxoActivationParams,
}
#[derive(Debug, Display)]
pub enum BchFromLegacyReqErr {
InvalidUtxoParams(UtxoFromLegacyReqErr),
InvalidBchdUrls(json::Error),
}
impl From<UtxoFromLegacyReqErr> for BchFromLegacyReqErr {
fn from(err: UtxoFromLegacyReqErr) -> Self { BchFromLegacyReqErr::InvalidUtxoParams(err) }
}
impl BchActivationRequest {
pub fn from_legacy_req(req: &Json) -> Result<Self, MmError<BchFromLegacyReqErr>> {
let bchd_urls = json::from_value(req["bchd_urls"].clone()).map_to_mm(BchFromLegacyReqErr::InvalidBchdUrls)?;
let allow_slp_unsafe_conf = req["allow_slp_unsafe_conf"].as_bool().unwrap_or_default();
let utxo_params = UtxoActivationParams::from_legacy_req(req)?;
Ok(BchActivationRequest {
allow_slp_unsafe_conf,
bchd_urls,
utxo_params,
})
}
}
#[derive(Clone)]
pub struct BchCoin {
utxo_arc: UtxoArc,
slp_addr_prefix: CashAddrPrefix,
bchd_urls: Vec<String>,
slp_tokens_infos: Arc<Mutex<HashMap<String, SlpTokenInfo>>>,
}
#[allow(clippy::large_enum_variant)]
pub enum IsSlpUtxoError {
Rpc(UtxoRpcError),
TxDeserialization(serialization::Error),
}
#[derive(Debug, Default)]
pub struct BchUnspents {
/// Standard BCH UTXOs
standard: Vec<UnspentInfo>,
/// SLP related UTXOs
slp: HashMap<H256, Vec<SlpUnspent>>,
/// SLP minting batons outputs, DO NOT use them as MM2 doesn't support SLP minting by default
slp_batons: Vec<UnspentInfo>,
/// The unspents of transaction with an undetermined protocol (OP_RETURN in 0 output but not SLP)
/// DO NOT ever use them to avoid burning users funds
undetermined: Vec<UnspentInfo>,
}
impl BchUnspents {
fn add_standard(&mut self, utxo: UnspentInfo) { self.standard.push(utxo) }
fn add_slp(&mut self, token_id: H256, bch_unspent: UnspentInfo, slp_amount: u64) {
let slp_unspent = SlpUnspent {
bch_unspent,
slp_amount,
};
self.slp.entry(token_id).or_insert_with(Vec::new).push(slp_unspent);
}
fn add_slp_baton(&mut self, utxo: UnspentInfo) { self.slp_batons.push(utxo) }
fn add_undetermined(&mut self, utxo: UnspentInfo) { self.undetermined.push(utxo) }
pub fn platform_balance(&self, decimals: u8) -> CoinBalance {
let spendable_sat = total_unspent_value(&self.standard);
let unspendable_slp = self.slp.iter().fold(0, |cur, (_, slp_unspents)| {
let bch_value = total_unspent_value(slp_unspents.iter().map(|slp| &slp.bch_unspent));
cur + bch_value
});
let unspendable_slp_batons = total_unspent_value(&self.slp_batons);
let unspendable_undetermined = total_unspent_value(&self.undetermined);
let total_unspendable = unspendable_slp + unspendable_slp_batons + unspendable_undetermined;
CoinBalance {
spendable: big_decimal_from_sat_unsigned(spendable_sat, decimals),
unspendable: big_decimal_from_sat_unsigned(total_unspendable, decimals),
}
}
pub fn slp_token_balance(&self, token_id: &H256, decimals: u8) -> CoinBalance {
self.slp
.get(token_id)
.map(|unspents| {
let total_sat = unspents.iter().fold(0, |cur, unspent| cur + unspent.slp_amount);
CoinBalance {
spendable: big_decimal_from_sat_unsigned(total_sat, decimals),
unspendable: 0.into(),
}
})
.unwrap_or_default()
}
}
impl From<UtxoRpcError> for IsSlpUtxoError {
fn from(err: UtxoRpcError) -> IsSlpUtxoError { IsSlpUtxoError::Rpc(err) }
}
impl From<serialization::Error> for IsSlpUtxoError {
fn from(err: serialization::Error) -> IsSlpUtxoError { IsSlpUtxoError::TxDeserialization(err) }
}
impl BchCoin {
pub fn slp_prefix(&self) -> &CashAddrPrefix { &self.slp_addr_prefix }
pub fn slp_address(&self, address: &Address) -> Result<CashAddress, String> {
let conf = &self.as_ref().conf;
address.to_cashaddress(
&self.slp_prefix().to_string(),
conf.pub_addr_prefix,
conf.p2sh_addr_prefix,
)
}
pub fn bchd_urls(&self) -> &[String] { &self.bchd_urls }
async fn utxos_into_bch_unspents(&self, utxos: Vec<UnspentInfo>) -> UtxoRpcResult<BchUnspents> {
let mut result = BchUnspents::default();
let mut temporary_undetermined = Vec::new();
let to_verbose: HashSet<H256Json> = utxos
.into_iter()
.filter_map(|unspent| {
if unspent.outpoint.index == 0 {
// Zero output is reserved for OP_RETURN of specific protocols
// so if we get it we can safely consider this as standard BCH UTXO.
// There is no need to request verbose transaction for such UTXO.
result.add_standard(unspent);
None
} else {
let hash = unspent.outpoint.hash.reversed().into();
temporary_undetermined.push(unspent);
Some(hash)
}
})
.collect();
let verbose_txs = self
.get_verbose_transactions_from_cache_or_rpc(to_verbose)
.compat()
.await?;
for unspent in temporary_undetermined {
let prev_tx_hash = unspent.outpoint.hash.reversed().into();
let prev_tx_bytes = verbose_txs
.get(&prev_tx_hash)
.or_mm_err(|| {
UtxoRpcError::Internal(format!(
"'get_verbose_transactions_from_cache_or_rpc' should have returned '{:?}'",
prev_tx_hash
))
})?
.to_inner();
let prev_tx: UtxoTx = match deserialize(prev_tx_bytes.hex.as_slice()) {
Ok(b) => b,
Err(e) => {
warn!(
"Failed to deserialize prev_tx {:?} with error {:?}, considering {:?} as undetermined",
prev_tx_bytes, e, unspent
);
result.add_undetermined(unspent);
continue;
},
};
if prev_tx.outputs.is_empty() {
warn!(
"Prev_tx {:?} outputs are empty, considering {:?} as undetermined",
prev_tx_bytes, unspent
);
result.add_undetermined(unspent);
continue;
}
let zero_out_script: Script = prev_tx.outputs[0].script_pubkey.clone().into();
if zero_out_script.is_pay_to_public_key()
|| zero_out_script.is_pay_to_public_key_hash()
|| zero_out_script.is_pay_to_script_hash()
{
result.add_standard(unspent);
} else {
match parse_slp_script(&prev_tx.outputs[0].script_pubkey) {
Ok(slp_data) => match slp_data.transaction {
SlpTransaction::Send { token_id, amounts } => {
match amounts.get(unspent.outpoint.index as usize - 1) {
Some(slp_amount) => result.add_slp(token_id, unspent, *slp_amount),
None => result.add_standard(unspent),
}
},
SlpTransaction::Genesis(genesis) => {
if unspent.outpoint.index == 1 {
let token_id = prev_tx.hash().reversed();
result.add_slp(token_id, unspent, genesis.initial_token_mint_quantity);
} else if Some(unspent.outpoint.index) == genesis.mint_baton_vout.map(|u| u as u32) {
result.add_slp_baton(unspent);
} else {
result.add_standard(unspent);
}
},
SlpTransaction::Mint {
token_id,
additional_token_quantity,
mint_baton_vout,
} => {
if unspent.outpoint.index == 1 {
result.add_slp(token_id, unspent, additional_token_quantity);
} else if Some(unspent.outpoint.index) == mint_baton_vout.map(|u| u as u32) {
result.add_slp_baton(unspent);
} else {
result.add_standard(unspent);
}
},
},
Err(e) => {
warn!(
"Error {} parsing script {:?} as SLP, considering {:?} as undetermined",
e, prev_tx.outputs[0].script_pubkey, unspent
);
result.undetermined.push(unspent);
},
};
}
}
Ok(result)
}
/// Returns unspents to calculate balance, use for displaying purposes only!
/// DO NOT USE to build transactions, it can lead to double spending attempt and also have other unpleasant consequences
pub async fn bch_unspents_for_display(&self, address: &Address) -> UtxoRpcResult<BchUnspents> {
// ordering is not required to display balance to we can simply call "normal" list_unspent
let all_unspents = self
.utxo_arc
.rpc_client
.list_unspent(address, self.utxo_arc.decimals)
.compat()
.await?;
self.utxos_into_bch_unspents(all_unspents).await
}
/// Locks recently spent cache to safely return UTXOs for spending
pub async fn bch_unspents_for_spend(
&self,
address: &Address,
) -> UtxoRpcResult<(BchUnspents, RecentlySpentOutPointsGuard<'_>)> {
let (all_unspents, recently_spent) = utxo_common::get_unspent_ordered_list(self, address).await?;
let result = self.utxos_into_bch_unspents(all_unspents).await?;
Ok((result, recently_spent))
}
pub async fn get_token_utxos_for_spend(
&self,
token_id: &H256,
) -> UtxoRpcResult<(Vec<SlpUnspent>, Vec<UnspentInfo>, RecentlySpentOutPointsGuard<'_>)> {
let my_address = self
.as_ref()
.derivation_method
.single_addr_or_err()
.mm_err(|e| UtxoRpcError::Internal(e.to_string()))?;
let (mut bch_unspents, recently_spent) = self.bch_unspents_for_spend(my_address).await?;
let (mut slp_unspents, standard_utxos) = (
bch_unspents.slp.remove(token_id).unwrap_or_default(),
bch_unspents.standard,
);
slp_unspents.sort_by(|a, b| a.slp_amount.cmp(&b.slp_amount));
Ok((slp_unspents, standard_utxos, recently_spent))
}
pub async fn get_token_utxos_for_display(
&self,
token_id: &H256,
) -> UtxoRpcResult<(Vec<SlpUnspent>, Vec<UnspentInfo>)> {
let my_address = self
.as_ref()
.derivation_method
.single_addr_or_err()
.mm_err(|e| UtxoRpcError::Internal(e.to_string()))?;
let mut bch_unspents = self.bch_unspents_for_display(my_address).await?;
let (mut slp_unspents, standard_utxos) = (
bch_unspents.slp.remove(token_id).unwrap_or_default(),
bch_unspents.standard,
);
slp_unspents.sort_by(|a, b| a.slp_amount.cmp(&b.slp_amount));
Ok((slp_unspents, standard_utxos))
}
pub fn add_slp_token_info(&self, ticker: String, info: SlpTokenInfo) {
self.slp_tokens_infos.lock().unwrap().insert(ticker, info);
}
pub fn get_slp_tokens_infos(&self) -> MutexGuard<'_, HashMap<String, SlpTokenInfo>> {
self.slp_tokens_infos.lock().unwrap()
}
pub fn get_my_slp_address(&self) -> Result<CashAddress, String> {
let my_address = try_s!(self.as_ref().derivation_method.single_addr_or_err());
let slp_address = my_address.to_cashaddress(
&self.slp_prefix().to_string(),
self.as_ref().conf.pub_addr_prefix,
self.as_ref().conf.p2sh_addr_prefix,
)?;
Ok(slp_address)
}
/// Returns multiple details by tx hash if token transfers also occurred in the transaction
pub async fn transaction_details_with_token_transfers<T: TxHistoryStorage>(
&self,
params: UtxoTxDetailsParams<'_, T>,
) -> MmResult<Vec<TransactionDetails>, UtxoTxDetailsError> {
let tx = self.tx_from_storage_or_rpc(params.hash, params.storage).await?;
let bch_tx_details = self
.bch_tx_details(
params.hash,
&tx,
params.block_height_and_time,
params.storage,
params.my_addresses,
)
.await?;
let maybe_op_return: Script = tx.outputs[0].script_pubkey.clone().into();
if !(maybe_op_return.is_pay_to_public_key_hash()
|| maybe_op_return.is_pay_to_public_key()
|| maybe_op_return.is_pay_to_script_hash())
{
if let Ok(slp_details) = parse_slp_script(&maybe_op_return) {
let slp_tx_details = self
.slp_tx_details(
&tx,
slp_details.transaction,
params.block_height_and_time,
bch_tx_details.fee_details.clone(),
params.storage,
params.my_addresses,
)
.await?;
return Ok(vec![bch_tx_details, slp_tx_details]);
}
}
Ok(vec![bch_tx_details])
}
async fn bch_tx_details<T: TxHistoryStorage>(
&self,
tx_hash: &H256Json,
tx: &UtxoTx,
height_and_time: Option<BlockHeightAndTime>,
storage: &T,
my_addresses: &HashSet<Address>,
) -> MmResult<TransactionDetails, UtxoTxDetailsError> {
let mut tx_builder = TxDetailsBuilder::new(self.ticker().to_owned(), tx, height_and_time, my_addresses.clone());
for output in &tx.outputs {
let addresses = match self.addresses_from_script(&output.script_pubkey.clone().into()) {
Ok(a) => a,
Err(_) => continue,
};
if addresses.is_empty() {
continue;
}
if addresses.len() != 1 {
let msg = format!(
"{} tx {:02x} output script resulted into unexpected number of addresses",
self.ticker(),
tx_hash,
);
return MmError::err(UtxoTxDetailsError::TxAddressDeserializationError(msg));
}
let amount = big_decimal_from_sat_unsigned(output.value, self.decimals());
for address in addresses {
tx_builder.transferred_to(address, &amount);
}
}
let mut total_input = 0;
for input in &tx.inputs {
let index = input.previous_output.index;
let prev_tx = self
.tx_from_storage_or_rpc(&input.previous_output.hash.reversed().into(), storage)
.await?;
let prev_script = prev_tx.outputs[index as usize].script_pubkey.clone().into();
let addresses = self
.addresses_from_script(&prev_script)
.map_to_mm(UtxoTxDetailsError::TxAddressDeserializationError)?;
if addresses.len() != 1 {
let msg = format!(
"{} tx {:02x} output script resulted into unexpected number of addresses",
self.ticker(),
tx_hash,
);
return MmError::err(UtxoTxDetailsError::TxAddressDeserializationError(msg));
}
let prev_value = prev_tx.outputs[index as usize].value;
total_input += prev_value;
let amount = big_decimal_from_sat_unsigned(prev_value, self.decimals());
for address in addresses {
tx_builder.transferred_from(address, &amount);
}
}
let total_output = tx.outputs.iter().fold(0, |total, output| total + output.value);
let fee = Some(TxFeeDetails::Utxo(UtxoFeeDetails {
coin: Some(self.ticker().into()),
amount: big_decimal_from_sat_unsigned(total_input - total_output, self.decimals()),
}));
tx_builder.set_tx_fee(fee);
Ok(tx_builder.build())
}
async fn get_slp_genesis_params<T: TxHistoryStorage>(
&self,
token_id: H256,
storage: &T,
) -> MmResult<SlpGenesisParams, UtxoTxDetailsError> {
let token_genesis_tx = self.tx_from_storage_or_rpc(&token_id.into(), storage).await?;
let maybe_genesis_script: Script = token_genesis_tx.outputs[0].script_pubkey.clone().into();
let slp_details = parse_slp_script(&maybe_genesis_script)?;
match slp_details.transaction {
SlpTransaction::Genesis(params) => Ok(params),
_ => {
let error = format!("SLP token ID '{}' is not a genesis TX", token_id);
MmError::err(UtxoTxDetailsError::InvalidTransaction(error))
},
}
}
async fn slp_transferred_amounts<T: TxHistoryStorage>(
&self,
utxo_tx: &UtxoTx,
slp_tx: SlpTransaction,
storage: &T,
) -> MmResult<HashMap<usize, (CashAddress, BigDecimal)>, UtxoTxDetailsError> {
let slp_amounts = match slp_tx {
SlpTransaction::Send { token_id, amounts } => {
let genesis_params = self.get_slp_genesis_params(token_id, storage).await?;
EitherIter::Left(
amounts
.into_iter()
.map(move |amount| big_decimal_from_sat_unsigned(amount, genesis_params.decimals[0])),
)
},
SlpTransaction::Mint {
token_id,
additional_token_quantity,
..
} => {
let slp_genesis_params = self.get_slp_genesis_params(token_id, storage).await?;
EitherIter::Right(std::iter::once(big_decimal_from_sat_unsigned(
additional_token_quantity,
slp_genesis_params.decimals[0],
)))
},
SlpTransaction::Genesis(genesis_params) => EitherIter::Right(std::iter::once(
big_decimal_from_sat_unsigned(genesis_params.initial_token_mint_quantity, genesis_params.decimals[0]),
)),
};
let mut result = HashMap::new();
for (i, amount) in slp_amounts.into_iter().enumerate() {
let output_index = i + 1;
match utxo_tx.outputs.get(output_index) {
Some(output) => {
let addresses = self
.addresses_from_script(&output.script_pubkey.clone().into())
.map_to_mm(UtxoTxDetailsError::TxAddressDeserializationError)?;
if addresses.len() != 1 {
let msg = format!(
"{} tx {:?} output script resulted into unexpected number of addresses",
self.ticker(),
utxo_tx.hash().reversed(),
);
return MmError::err(UtxoTxDetailsError::TxAddressDeserializationError(msg));
}
let slp_address = self
.slp_address(&addresses[0])
.map_to_mm(UtxoTxDetailsError::InvalidTransaction)?;
result.insert(output_index, (slp_address, amount));
},
None => {
let error = format!(
"Unexpected '{}' output index at {} TX",
output_index,
utxo_tx.hash().reversed()
);
return MmError::err(UtxoTxDetailsError::InvalidTransaction(error));
},
}
}
Ok(result)
}
async fn slp_tx_details<Storage: TxHistoryStorage>(
&self,
tx: &UtxoTx,
slp_tx: SlpTransaction,
height_and_time: Option<BlockHeightAndTime>,
tx_fee: Option<TxFeeDetails>,
storage: &Storage,
my_addresses: &HashSet<Address>,
) -> MmResult<TransactionDetails, UtxoTxDetailsError> {
let token_id = match slp_tx.token_id() {
Some(id) => id,
None => tx.hash().reversed(),
};
let slp_addresses: Vec<_> = my_addresses
.iter()
.map(|addr| self.slp_address(addr))
.collect::<Result<_, _>>()
.map_to_mm(UtxoTxDetailsError::Internal)?;
let mut slp_tx_details_builder =
TxDetailsBuilder::new(self.ticker().to_owned(), tx, height_and_time, slp_addresses);
let slp_transferred_amounts = self.slp_transferred_amounts(tx, slp_tx, storage).await?;
for (_, (address, amount)) in slp_transferred_amounts {
slp_tx_details_builder.transferred_to(address, &amount);
}
for input in &tx.inputs {
let prev_tx = self
.tx_from_storage_or_rpc(&input.previous_output.hash.reversed().into(), storage)
.await?;
if let Ok(slp_tx_details) = parse_slp_script(&prev_tx.outputs[0].script_pubkey) {
let mut prev_slp_transferred = self
.slp_transferred_amounts(&prev_tx, slp_tx_details.transaction, storage)
.await?;
let i = input.previous_output.index as usize;
if let Some((address, amount)) = prev_slp_transferred.remove(&i) {
slp_tx_details_builder.transferred_from(address, &amount);
}
}
}
slp_tx_details_builder.set_transaction_type(TransactionType::TokenTransfer(token_id.take().to_vec().into()));
slp_tx_details_builder.set_tx_fee(tx_fee);
Ok(slp_tx_details_builder.build())
}
pub async fn get_block_timestamp(&self, height: u64) -> Result<u64, MmError<GetBlockHeaderError>> {
self.as_ref().rpc_client.get_block_timestamp(height).await
}
}
impl AsRef<UtxoCoinFields> for BchCoin {
fn as_ref(&self) -> &UtxoCoinFields { &self.utxo_arc }
}
pub async fn bch_coin_with_policy(
ctx: &MmArc,
ticker: &str,
conf: &Json,
params: BchActivationRequest,
slp_addr_prefix: CashAddrPrefix,
priv_key_policy: PrivKeyBuildPolicy,
) -> Result<BchCoin, String> {
if params.bchd_urls.is_empty() && !params.allow_slp_unsafe_conf {
return Err("Using empty bchd_urls is unsafe for SLP users!".into());
}
let bchd_urls = params.bchd_urls;
let slp_tokens_infos = Arc::new(Mutex::new(HashMap::new()));
let constructor = {
move |utxo_arc| BchCoin {
utxo_arc,
slp_addr_prefix: slp_addr_prefix.clone(),
bchd_urls: bchd_urls.clone(),
slp_tokens_infos: slp_tokens_infos.clone(),
}
};
let coin = try_s!(
UtxoArcBuilder::new(ctx, ticker, conf, ¶ms.utxo_params, priv_key_policy, constructor)
.build()
.await
);
Ok(coin)
}
pub async fn bch_coin_with_priv_key(
ctx: &MmArc,
ticker: &str,
conf: &Json,
params: BchActivationRequest,
slp_addr_prefix: CashAddrPrefix,
priv_key: IguanaPrivKey,
) -> Result<BchCoin, String> {
let priv_key_policy = PrivKeyBuildPolicy::IguanaPrivKey(priv_key);
bch_coin_with_policy(ctx, ticker, conf, params, slp_addr_prefix, priv_key_policy).await
}
#[derive(Debug)]
pub enum BchActivationError {
CoinInitError(String),
TokenConfIsNotFound {
token: String,
},
TokenCoinProtocolParseError {
token: String,
error: json::Error,
},
TokenCoinProtocolIsNotSlp {
token: String,
protocol: CoinProtocol,
},
TokenPlatformCoinIsInvalidInConf {
token: String,
expected_platform: String,
actual_platform: String,
},
RpcError(UtxoRpcError),
SlpPrefixParseError(String),
}
impl From<UtxoRpcError> for BchActivationError {
fn from(e: UtxoRpcError) -> Self { BchActivationError::RpcError(e) }
}
// if mockable is placed before async_trait there is `munmap_chunk(): invalid pointer` error on async fn mocking attempt
#[async_trait]
#[cfg_attr(test, mockable)]
impl UtxoTxBroadcastOps for BchCoin {
async fn broadcast_tx(&self, tx: &UtxoTx) -> Result<H256Json, MmError<BroadcastTxErr>> {
utxo_common::broadcast_tx(self, tx).await
}
}
// if mockable is placed before async_trait there is `munmap_chunk(): invalid pointer` error on async fn mocking attempt
#[async_trait]
#[cfg_attr(test, mockable)]
impl UtxoTxGenerationOps for BchCoin {
async fn get_tx_fee(&self) -> UtxoRpcResult<ActualTxFee> { utxo_common::get_tx_fee(&self.utxo_arc).await }
async fn calc_interest_if_required(
&self,
unsigned: TransactionInputSigner,
data: AdditionalTxData,
my_script_pub: Bytes,
) -> UtxoRpcResult<(TransactionInputSigner, AdditionalTxData)> {
utxo_common::calc_interest_if_required(self, unsigned, data, my_script_pub).await
}
}
#[async_trait]
#[cfg_attr(test, mockable)]
impl GetUtxoListOps for BchCoin {
async fn get_unspent_ordered_list(
&self,
address: &Address,
) -> UtxoRpcResult<(Vec<UnspentInfo>, RecentlySpentOutPointsGuard<'_>)> {
let (bch_unspents, recently_spent) = self.bch_unspents_for_spend(address).await?;
Ok((bch_unspents.standard, recently_spent))
}
async fn get_all_unspent_ordered_list(
&self,
address: &Address,
) -> UtxoRpcResult<(Vec<UnspentInfo>, RecentlySpentOutPointsGuard<'_>)> {
utxo_common::get_all_unspent_ordered_list(self, address).await
}
async fn get_mature_unspent_ordered_list(
&self,
address: &Address,
) -> UtxoRpcResult<(MatureUnspentList, RecentlySpentOutPointsGuard<'_>)> {
let (unspents, recently_spent) = utxo_common::get_all_unspent_ordered_list(self, address).await?;
Ok((MatureUnspentList::new_mature(unspents), recently_spent))
}
}
// if mockable is placed before async_trait there is `munmap_chunk(): invalid pointer` error on async fn mocking attempt
#[async_trait]
#[cfg_attr(test, mockable)]
impl UtxoCommonOps for BchCoin {
async fn get_htlc_spend_fee(&self, tx_size: u64, stage: &FeeApproxStage) -> UtxoRpcResult<u64> {
utxo_common::get_htlc_spend_fee(self, tx_size, stage).await
}
fn addresses_from_script(&self, script: &Script) -> Result<Vec<Address>, String> {
utxo_common::addresses_from_script(self, script)
}
fn denominate_satoshis(&self, satoshi: i64) -> f64 { utxo_common::denominate_satoshis(&self.utxo_arc, satoshi) }
fn my_public_key(&self) -> Result<&Public, MmError<UnexpectedDerivationMethod>> {
utxo_common::my_public_key(self.as_ref())
}
fn address_from_str(&self, address: &str) -> MmResult<Address, AddrFromStrError> {
utxo_common::checked_address_from_str(self, address)
}
async fn get_current_mtp(&self) -> UtxoRpcResult<u32> {
utxo_common::get_current_mtp(&self.utxo_arc, CoinVariant::Standard).await
}
fn is_unspent_mature(&self, output: &RpcTransaction) -> bool {
utxo_common::is_unspent_mature(self.utxo_arc.conf.mature_confirmations, output)
}
async fn calc_interest_of_tx(&self, tx: &UtxoTx, input_transactions: &mut HistoryUtxoTxMap) -> UtxoRpcResult<u64> {
utxo_common::calc_interest_of_tx(self, tx, input_transactions).await
}
async fn get_mut_verbose_transaction_from_map_or_rpc<'a, 'b>(
&'a self,
tx_hash: H256Json,
utxo_tx_map: &'b mut HistoryUtxoTxMap,
) -> UtxoRpcResult<&'b mut HistoryUtxoTx> {
utxo_common::get_mut_verbose_transaction_from_map_or_rpc(self, tx_hash, utxo_tx_map).await
}
async fn p2sh_spending_tx(&self, input: utxo_common::P2SHSpendingTxInput<'_>) -> Result<UtxoTx, String> {
utxo_common::p2sh_spending_tx(self, input).await
}
fn get_verbose_transactions_from_cache_or_rpc(
&self,
tx_ids: HashSet<H256Json>,
) -> UtxoRpcFut<HashMap<H256Json, VerboseTransactionFrom>> {
let selfi = self.clone();
let fut = async move { utxo_common::get_verbose_transactions_from_cache_or_rpc(&selfi.utxo_arc, tx_ids).await };
Box::new(fut.boxed().compat())
}
async fn preimage_trade_fee_required_to_send_outputs(
&self,
outputs: Vec<TransactionOutput>,
fee_policy: FeePolicy,
gas_fee: Option<u64>,
stage: &FeeApproxStage,
) -> TradePreimageResult<BigDecimal> {
utxo_common::preimage_trade_fee_required_to_send_outputs(
self,
self.ticker(),
outputs,
fee_policy,
gas_fee,
stage,
)
.await
}
fn increase_dynamic_fee_by_stage(&self, dynamic_fee: u64, stage: &FeeApproxStage) -> u64 {
utxo_common::increase_dynamic_fee_by_stage(self, dynamic_fee, stage)
}
async fn p2sh_tx_locktime(&self, htlc_locktime: u32) -> Result<u32, MmError<UtxoRpcError>> {
utxo_common::p2sh_tx_locktime(self, &self.utxo_arc.conf.ticker, htlc_locktime).await
}
fn addr_format(&self) -> &UtxoAddressFormat { utxo_common::addr_format(self) }
fn addr_format_for_standard_scripts(&self) -> UtxoAddressFormat {
utxo_common::addr_format_for_standard_scripts(self)
}
fn address_from_pubkey(&self, pubkey: &Public) -> Address {
let conf = &self.utxo_arc.conf;
let addr_format = self.addr_format().clone();
utxo_common::address_from_pubkey(
pubkey,
conf.pub_addr_prefix,
conf.pub_t_addr_prefix,
conf.checksum_type,
conf.bech32_hrp.clone(),
addr_format,
)
}
}
#[async_trait]
impl SwapOps for BchCoin {
#[inline]
fn send_taker_fee(&self, fee_addr: &[u8], amount: BigDecimal, _uuid: &[u8]) -> TransactionFut {
utxo_common::send_taker_fee(self.clone(), fee_addr, amount)
}
#[inline]
fn send_maker_payment(&self, maker_payment_args: SendPaymentArgs) -> TransactionFut {
utxo_common::send_maker_payment(self.clone(), maker_payment_args)
}
#[inline]
fn send_taker_payment(&self, taker_payment_args: SendPaymentArgs) -> TransactionFut {
utxo_common::send_taker_payment(self.clone(), taker_payment_args)
}
#[inline]
fn send_maker_spends_taker_payment(&self, maker_spends_payment_args: SpendPaymentArgs) -> TransactionFut {
utxo_common::send_maker_spends_taker_payment(self.clone(), maker_spends_payment_args)
}
#[inline]
fn send_taker_spends_maker_payment(&self, taker_spends_payment_args: SpendPaymentArgs) -> TransactionFut {
utxo_common::send_taker_spends_maker_payment(self.clone(), taker_spends_payment_args)
}
#[inline]
fn send_taker_refunds_payment(&self, taker_refunds_payment_args: RefundPaymentArgs) -> TransactionFut {
utxo_common::send_taker_refunds_payment(self.clone(), taker_refunds_payment_args)
}
#[inline]
fn send_maker_refunds_payment(&self, maker_refunds_payment_args: RefundPaymentArgs) -> TransactionFut {
utxo_common::send_maker_refunds_payment(self.clone(), maker_refunds_payment_args)
}
fn validate_fee(&self, validate_fee_args: ValidateFeeArgs) -> ValidatePaymentFut<()> {
let tx = match validate_fee_args.fee_tx {
TransactionEnum::UtxoTx(tx) => tx.clone(),
_ => panic!(),
};
utxo_common::validate_fee(
self.clone(),
tx,
utxo_common::DEFAULT_FEE_VOUT,
validate_fee_args.expected_sender,
validate_fee_args.amount,
validate_fee_args.min_block_number,
validate_fee_args.fee_addr,
)
}
#[inline]
fn validate_maker_payment(&self, input: ValidatePaymentInput) -> ValidatePaymentFut<()> {
utxo_common::validate_maker_payment(self, input)
}
#[inline]
fn validate_taker_payment(&self, input: ValidatePaymentInput) -> ValidatePaymentFut<()> {
utxo_common::validate_taker_payment(self, input)
}
#[inline]
fn check_if_my_payment_sent(
&self,
if_my_payment_sent_args: CheckIfMyPaymentSentArgs,
) -> Box<dyn Future<Item = Option<TransactionEnum>, Error = String> + Send> {
utxo_common::check_if_my_payment_sent(
self.clone(),
if_my_payment_sent_args.time_lock,
if_my_payment_sent_args.other_pub,
if_my_payment_sent_args.secret_hash,
if_my_payment_sent_args.swap_unique_data,
)
}
#[inline]
async fn search_for_swap_tx_spend_my(
&self,
input: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String> {
utxo_common::search_for_swap_tx_spend_my(self, input, utxo_common::DEFAULT_SWAP_VOUT).await
}
#[inline]
async fn search_for_swap_tx_spend_other(
&self,
input: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String> {
utxo_common::search_for_swap_tx_spend_other(self, input, utxo_common::DEFAULT_SWAP_VOUT).await
}
#[inline]
fn check_tx_signed_by_pub(&self, tx: &[u8], expected_pub: &[u8]) -> Result<bool, MmError<ValidatePaymentError>> {
utxo_common::check_all_inputs_signed_by_pub(tx, expected_pub)
}
#[inline]
async fn extract_secret(
&self,
secret_hash: &[u8],
spend_tx: &[u8],
_watcher_reward: bool,
) -> Result<Vec<u8>, String> {
utxo_common::extract_secret(secret_hash, spend_tx)
}
fn is_auto_refundable(&self) -> bool { false }
async fn wait_for_htlc_refund(&self, _tx: &[u8], _locktime: u64) -> RefundResult<()> {
MmError::err(RefundError::Internal(
"wait_for_htlc_refund is not supported for this coin!".into(),
))
}
#[inline]
fn can_refund_htlc(&self, locktime: u64) -> Box<dyn Future<Item = CanRefundHtlc, Error = String> + Send + '_> {
Box::new(
utxo_common::can_refund_htlc(self, locktime)
.boxed()
.map_err(|e| ERRL!("{}", e))
.compat(),
)
}
#[inline]
fn negotiate_swap_contract_addr(
&self,
_other_side_address: Option<&[u8]>,
) -> Result<Option<BytesJson>, MmError<NegotiateSwapContractAddrErr>> {
Ok(None)
}
fn derive_htlc_key_pair(&self, swap_unique_data: &[u8]) -> KeyPair {
utxo_common::derive_htlc_key_pair(self.as_ref(), swap_unique_data)
}
fn derive_htlc_pubkey(&self, swap_unique_data: &[u8]) -> Vec<u8> {
utxo_common::derive_htlc_pubkey(self, swap_unique_data)
}
#[inline]
fn validate_other_pubkey(&self, raw_pubkey: &[u8]) -> MmResult<(), ValidateOtherPubKeyErr> {
utxo_common::validate_other_pubkey(raw_pubkey)
}
async fn maker_payment_instructions(
&self,
_args: PaymentInstructionArgs<'_>,
) -> Result<Option<Vec<u8>>, MmError<PaymentInstructionsErr>> {
Ok(None)
}
async fn taker_payment_instructions(
&self,
_args: PaymentInstructionArgs<'_>,
) -> Result<Option<Vec<u8>>, MmError<PaymentInstructionsErr>> {
Ok(None)
}
fn validate_maker_payment_instructions(
&self,
_instructions: &[u8],
_args: PaymentInstructionArgs,
) -> Result<PaymentInstructions, MmError<ValidateInstructionsErr>> {
MmError::err(ValidateInstructionsErr::UnsupportedCoin(self.ticker().to_string()))
}
fn validate_taker_payment_instructions(
&self,