forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathlp_coins.rs
More file actions
4376 lines (3854 loc) · 154 KB
/
Copy pathlp_coins.rs
File metadata and controls
4376 lines (3854 loc) · 154 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* Copyright © 2022 Atomic Private Limited and its contributors *
* *
* See the CONTRIBUTOR-LICENSE-AGREEMENT, COPYING, LICENSE-COPYRIGHT-NOTICE *
* and DEVELOPER-CERTIFICATE-OF-ORIGIN files in the LEGAL directory in *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* AtomicDEX software, including this file may be copied, modified, propagated*
* or distributed except according to the terms contained in the *
* LICENSE-COPYRIGHT-NOTICE file. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
//
// coins.rs
// marketmaker
//
// `mockable` implementation uses these
#![allow(
clippy::forget_ref,
clippy::forget_copy,
clippy::swap_ptr_to_ref,
clippy::forget_non_drop
)]
#![allow(uncommon_codepoints)]
#![feature(integer_atomics)]
#![feature(async_closure)]
#![feature(hash_raw_entry)]
#![feature(stmt_expr_attributes)]
#![feature(result_flattening)]
#![feature(let_chains)]
#[macro_use] extern crate common;
#[macro_use] extern crate gstuff;
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate mm2_metrics;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate ser_error_derive;
use async_trait::async_trait;
use base58::FromBase58Error;
use bip32::ExtendedPrivateKey;
use common::custom_futures::timeout::TimeoutError;
use common::executor::{abortable_queue::{AbortableQueue, WeakSpawner},
AbortSettings, AbortedError, SpawnAbortable, SpawnFuture};
use common::log::{warn, LogOnError};
use common::{calc_total_pages, now_sec, ten, HttpStatusCode};
use crypto::{derive_secp256k1_secret, Bip32Error, CryptoCtx, CryptoCtxError, DerivationPath, GlobalHDAccountArc,
HwRpcError, KeyPairPolicy, Secp256k1Secret, StandardHDCoinAddress, StandardHDPathToCoin, WithHwRpcError};
use derive_more::Display;
use enum_from::{EnumFromStringify, EnumFromTrait};
use ethereum_types::H256;
use futures::compat::Future01CompatExt;
use futures::lock::Mutex as AsyncMutex;
use futures::{FutureExt, TryFutureExt};
use futures01::Future;
use http::{Response, StatusCode};
use keys::{AddressFormat as UtxoAddressFormat, KeyPair, NetworkPrefix as CashAddrPrefix};
use mm2_core::mm_ctx::{from_ctx, MmArc};
use mm2_err_handle::prelude::*;
use mm2_metrics::MetricsWeak;
use mm2_number::{bigdecimal::{BigDecimal, ParseBigDecimalError, Zero},
MmNumber};
use mm2_rpc::data::legacy::{EnabledCoin, GetEnabledResponse, Mm2RpcResult};
use parking_lot::Mutex as PaMutex;
use rpc::v1::types::{Bytes as BytesJson, H256 as H256Json};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::{self as json, Value as Json};
use std::cmp::Ordering;
use std::collections::hash_map::{HashMap, RawEntryMut};
use std::collections::HashSet;
use std::fmt;
use std::future::Future as Future03;
use std::num::NonZeroUsize;
use std::ops::{Add, Deref};
use std::str::FromStr;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering as AtomicOrdering;
use std::sync::Arc;
use std::time::Duration;
use utxo_signer::with_key_pair::UtxoSignWithKeyPairError;
use zcash_primitives::transaction::Transaction as ZTransaction;
cfg_native! {
use crate::lightning::LightningCoin;
use crate::lightning::ln_conf::PlatformCoinConfirmationTargets;
use ::lightning::ln::PaymentHash as LightningPayment;
use async_std::fs;
use futures::AsyncWriteExt;
use lightning_invoice::{Invoice, ParseOrSemanticError};
use std::io;
use std::path::PathBuf;
}
cfg_wasm32! {
use ethereum_types::{H264 as EthH264, H520 as EthH520};
use hd_wallet_storage::HDWalletDb;
use mm2_db::indexed_db::{ConstructibleDb, DbLocked, SharedDb};
use tx_history_storage::wasm::{clear_tx_history, load_tx_history, save_tx_history, TxHistoryDb};
pub type TxHistoryDbLocked<'a> = DbLocked<'a, TxHistoryDb>;
}
// using custom copy of try_fus as futures crate was renamed to futures01
macro_rules! try_fus {
($e: expr) => {
match $e {
Ok(ok) => ok,
Err(err) => return Box::new(futures01::future::err(ERRL!("{}", err))),
}
};
}
macro_rules! try_f {
($e: expr) => {
match $e {
Ok(ok) => ok,
Err(e) => return Box::new(futures01::future::err(e.into())),
}
};
}
/// `TransactionErr` compatible `try_fus` macro.
macro_rules! try_tx_fus {
($e: expr) => {
match $e {
Ok(ok) => ok,
Err(err) => return Box::new(futures01::future::err(crate::TransactionErr::Plain(ERRL!("{:?}", err)))),
}
};
($e: expr, $tx: expr) => {
match $e {
Ok(ok) => ok,
Err(err) => {
return Box::new(futures01::future::err(crate::TransactionErr::TxRecoverable(
TransactionEnum::from($tx),
ERRL!("{:?}", err),
)))
},
}
};
}
/// `TransactionErr` compatible `try_s` macro.
macro_rules! try_tx_s {
($e: expr) => {
match $e {
Ok(ok) => ok,
Err(err) => {
return Err(crate::TransactionErr::Plain(format!(
"{}:{}] {:?}",
file!(),
line!(),
err
)))
},
}
};
($e: expr, $tx: expr) => {
match $e {
Ok(ok) => ok,
Err(err) => {
return Err(crate::TransactionErr::TxRecoverable(
TransactionEnum::from($tx),
format!("{}:{}] {:?}", file!(), line!(), err),
))
},
}
};
}
/// `TransactionErr:Plain` compatible `ERR` macro.
macro_rules! TX_PLAIN_ERR {
($format: expr, $($args: tt)+) => { Err(crate::TransactionErr::Plain((ERRL!($format, $($args)+)))) };
($format: expr) => { Err(crate::TransactionErr::Plain(ERRL!($format))) }
}
/// `TransactionErr:TxRecoverable` compatible `ERR` macro.
#[allow(unused_macros)]
macro_rules! TX_RECOVERABLE_ERR {
($tx: expr, $format: expr, $($args: tt)+) => {
Err(crate::TransactionErr::TxRecoverable(TransactionEnum::from($tx), ERRL!($format, $($args)+)))
};
($tx: expr, $format: expr) => {
Err(crate::TransactionErr::TxRecoverable(TransactionEnum::from($tx), ERRL!($format)))
};
}
macro_rules! ok_or_continue_after_sleep {
($e:expr, $delay: ident) => {
match $e {
Ok(res) => res,
Err(e) => {
error!("error {:?}", e);
Timer::sleep($delay).await;
continue;
},
}
};
}
pub mod coin_balance;
pub mod lp_price;
pub mod watcher_common;
pub mod coin_errors;
use coin_errors::{MyAddressError, ValidatePaymentError, ValidatePaymentFut};
#[doc(hidden)]
#[cfg(test)]
pub mod coins_tests;
pub mod eth;
use eth::GetValidEthWithdrawAddError;
use eth::{eth_coin_from_conf_and_request, get_eth_address, EthCoin, EthGasDetailsErr, EthTxFeeDetails,
GetEthAddressError, SignedEthTx};
pub mod hd_confirm_address;
pub mod hd_pubkey;
pub mod hd_wallet;
use hd_wallet::{HDAccountAddressId, HDAddress};
pub mod hd_wallet_storage;
#[cfg(not(target_arch = "wasm32"))] pub mod lightning;
#[cfg_attr(target_arch = "wasm32", allow(dead_code, unused_imports))]
pub mod my_tx_history_v2;
pub mod qrc20;
use qrc20::{qrc20_coin_with_policy, Qrc20ActivationParams, Qrc20Coin, Qrc20FeeDetails};
pub mod rpc_command;
use rpc_command::{get_new_address::{GetNewAddressTaskManager, GetNewAddressTaskManagerShared},
init_account_balance::{AccountBalanceTaskManager, AccountBalanceTaskManagerShared},
init_create_account::{CreateAccountTaskManager, CreateAccountTaskManagerShared},
init_scan_for_new_addresses::{ScanAddressesTaskManager, ScanAddressesTaskManagerShared},
init_withdraw::{WithdrawTaskManager, WithdrawTaskManagerShared}};
pub mod tendermint;
use tendermint::{CosmosTransaction, CustomTendermintMsgType, TendermintCoin, TendermintFeeDetails,
TendermintProtocolInfo, TendermintToken, TendermintTokenProtocolInfo};
#[doc(hidden)]
#[allow(unused_variables)]
pub mod test_coin;
pub use test_coin::TestCoin;
pub mod tx_history_storage;
#[doc(hidden)]
#[allow(unused_variables)]
#[cfg(all(
feature = "enable-solana",
not(target_os = "ios"),
not(target_os = "android"),
not(target_arch = "wasm32")
))]
pub mod solana;
#[cfg(all(
feature = "enable-solana",
not(target_os = "ios"),
not(target_os = "android"),
not(target_arch = "wasm32")
))]
pub use solana::spl::SplToken;
#[cfg(all(
feature = "enable-solana",
not(target_os = "ios"),
not(target_os = "android"),
not(target_arch = "wasm32")
))]
pub use solana::{SolanaActivationParams, SolanaCoin, SolanaFeeDetails};
pub mod utxo;
use utxo::bch::{bch_coin_with_policy, BchActivationRequest, BchCoin};
use utxo::qtum::{self, qtum_coin_with_policy, Qrc20AddressError, QtumCoin, QtumDelegationOps, QtumDelegationRequest,
QtumStakingInfosDetails, ScriptHashTypeNotSupported};
use utxo::rpc_clients::UtxoRpcError;
use utxo::slp::SlpToken;
use utxo::slp::{slp_addr_from_pubkey_str, SlpFeeDetails};
use utxo::utxo_common::big_decimal_from_sat_unsigned;
use utxo::utxo_standard::{utxo_standard_coin_with_policy, UtxoStandardCoin};
use utxo::UtxoActivationParams;
use utxo::{BlockchainNetwork, GenerateTxError, UtxoFeeDetails, UtxoTx};
pub mod nft;
use nft::nft_errors::GetNftInfoError;
pub mod z_coin;
use z_coin::{ZCoin, ZcoinProtocolInfo};
pub type TransactionFut = Box<dyn Future<Item = TransactionEnum, Error = TransactionErr> + Send>;
pub type TransactionResult = Result<TransactionEnum, TransactionErr>;
pub type BalanceResult<T> = Result<T, MmError<BalanceError>>;
pub type BalanceFut<T> = Box<dyn Future<Item = T, Error = MmError<BalanceError>> + Send>;
pub type NonZeroBalanceFut<T> = Box<dyn Future<Item = T, Error = MmError<GetNonZeroBalance>> + Send>;
pub type NumConversResult<T> = Result<T, MmError<NumConversError>>;
pub type StakingInfosResult = Result<StakingInfos, MmError<StakingInfosError>>;
pub type StakingInfosFut = Box<dyn Future<Item = StakingInfos, Error = MmError<StakingInfosError>> + Send>;
pub type DelegationResult = Result<TransactionDetails, MmError<DelegationError>>;
pub type DelegationFut = Box<dyn Future<Item = TransactionDetails, Error = MmError<DelegationError>> + Send>;
pub type WithdrawResult = Result<TransactionDetails, MmError<WithdrawError>>;
pub type WithdrawFut = Box<dyn Future<Item = TransactionDetails, Error = MmError<WithdrawError>> + Send>;
pub type TradePreimageResult<T> = Result<T, MmError<TradePreimageError>>;
pub type TradePreimageFut<T> = Box<dyn Future<Item = T, Error = MmError<TradePreimageError>> + Send>;
pub type CoinFindResult<T> = Result<T, MmError<CoinFindError>>;
pub type TxHistoryFut<T> = Box<dyn Future<Item = T, Error = MmError<TxHistoryError>> + Send>;
pub type TxHistoryResult<T> = Result<T, MmError<TxHistoryError>>;
pub type RawTransactionResult = Result<RawTransactionRes, MmError<RawTransactionError>>;
pub type RawTransactionFut<'a> =
Box<dyn Future<Item = RawTransactionRes, Error = MmError<RawTransactionError>> + Send + 'a>;
pub type RefundResult<T> = Result<T, MmError<RefundError>>;
/// Helper type used for taker payment's spend preimage generation result
pub type GenTakerPaymentSpendResult = MmResult<TxPreimageWithSig, TxGenError>;
/// Helper type used for taker payment's validation result
pub type ValidateTakerPaymentResult = MmResult<(), ValidateTakerPaymentError>;
/// Helper type used for taker payment's spend preimage validation result
pub type ValidateTakerPaymentSpendPreimageResult = MmResult<(), ValidateTakerPaymentSpendPreimageError>;
pub type IguanaPrivKey = Secp256k1Secret;
// Constants for logs used in tests
pub const INVALID_SENDER_ERR_LOG: &str = "Invalid sender";
pub const EARLY_CONFIRMATION_ERR_LOG: &str = "Early confirmation";
pub const OLD_TRANSACTION_ERR_LOG: &str = "Old transaction";
pub const INVALID_RECEIVER_ERR_LOG: &str = "Invalid receiver";
pub const INVALID_CONTRACT_ADDRESS_ERR_LOG: &str = "Invalid contract address";
pub const INVALID_PAYMENT_STATE_ERR_LOG: &str = "Invalid payment state";
pub const INVALID_SWAP_ID_ERR_LOG: &str = "Invalid swap id";
pub const INVALID_SCRIPT_ERR_LOG: &str = "Invalid script";
pub const INVALID_REFUND_TX_ERR_LOG: &str = "Invalid refund transaction";
#[derive(Debug, Deserialize, Display, Serialize, SerializeErrorType)]
#[serde(tag = "error_type", content = "error_data")]
pub enum RawTransactionError {
#[display(fmt = "No such coin {}", coin)]
NoSuchCoin { coin: String },
#[display(fmt = "Invalid hash: {}", _0)]
InvalidHashError(String),
#[display(fmt = "Transport error: {}", _0)]
Transport(String),
#[display(fmt = "Hash does not exist: {}", _0)]
HashNotExist(String),
#[display(fmt = "Internal error: {}", _0)]
InternalError(String),
}
impl HttpStatusCode for RawTransactionError {
fn status_code(&self) -> StatusCode {
match self {
RawTransactionError::NoSuchCoin { .. }
| RawTransactionError::InvalidHashError(_)
| RawTransactionError::HashNotExist(_) => StatusCode::BAD_REQUEST,
RawTransactionError::Transport(_) | RawTransactionError::InternalError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
},
}
}
}
impl From<CoinFindError> for RawTransactionError {
fn from(e: CoinFindError) -> Self {
match e {
CoinFindError::NoSuchCoin { coin } => RawTransactionError::NoSuchCoin { coin },
}
}
}
#[derive(Clone, Debug, Deserialize, Display, EnumFromStringify, PartialEq, Serialize, SerializeErrorType)]
#[serde(tag = "error_type", content = "error_data")]
pub enum GetMyAddressError {
CoinsConfCheckError(String),
CoinIsNotSupported(String),
#[from_stringify("CryptoCtxError")]
#[display(fmt = "Internal error: {}", _0)]
Internal(String),
#[from_stringify("serde_json::Error")]
#[display(fmt = "Invalid request error error: {}", _0)]
InvalidRequest(String),
#[display(fmt = "Get Eth address error: {}", _0)]
GetEthAddressError(GetEthAddressError),
}
impl From<GetEthAddressError> for GetMyAddressError {
fn from(e: GetEthAddressError) -> Self { GetMyAddressError::GetEthAddressError(e) }
}
impl HttpStatusCode for GetMyAddressError {
fn status_code(&self) -> StatusCode {
match self {
GetMyAddressError::CoinsConfCheckError(_)
| GetMyAddressError::CoinIsNotSupported(_)
| GetMyAddressError::InvalidRequest(_) => StatusCode::BAD_REQUEST,
GetMyAddressError::Internal(_) | GetMyAddressError::GetEthAddressError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
},
}
}
}
#[derive(Deserialize)]
pub struct RawTransactionRequest {
pub coin: String,
pub tx_hash: String,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct RawTransactionRes {
/// Raw bytes of signed transaction in hexadecimal string, this should be return hexadecimal encoded signed transaction for get_raw_transaction
pub tx_hex: BytesJson,
}
#[derive(Debug, Deserialize)]
pub struct MyAddressReq {
coin: String,
#[serde(default)]
path_to_address: StandardHDCoinAddress,
}
#[derive(Debug, Serialize)]
pub struct MyWalletAddress {
coin: String,
wallet_address: String,
}
pub type SignatureResult<T> = Result<T, MmError<SignatureError>>;
pub type VerificationResult<T> = Result<T, MmError<VerificationError>>;
#[derive(Debug, Display)]
pub enum TxHistoryError {
ErrorSerializing(String),
ErrorDeserializing(String),
ErrorSaving(String),
ErrorLoading(String),
ErrorClearing(String),
#[display(fmt = "'internal_id' not found: {:?}", internal_id)]
FromIdNotFound {
internal_id: BytesJson,
},
NotSupported(String),
InternalError(String),
}
#[derive(Clone, Debug, Deserialize, Display, PartialEq)]
pub enum PrivKeyPolicyNotAllowed {
#[display(fmt = "Hardware Wallet is not supported")]
HardwareWalletNotSupported,
#[display(fmt = "Unsupported method: {}", _0)]
UnsupportedMethod(String),
#[display(fmt = "Internal error: {}", _0)]
InternalError(String),
}
impl Serialize for PrivKeyPolicyNotAllowed {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_string())
}
}
#[derive(Clone, Debug, Display, PartialEq, Serialize)]
pub enum UnexpectedDerivationMethod {
#[display(fmt = "Expected 'SingleAddress' derivation method")]
ExpectedSingleAddress,
#[display(fmt = "Expected 'HDWallet' derivationMethod")]
ExpectedHDWallet,
#[display(fmt = "Trezor derivation method is not supported yet!")]
Trezor,
#[display(fmt = "Unsupported error: {}", _0)]
UnsupportedError(String),
#[display(fmt = "Internal error: {}", _0)]
InternalError(String),
}
impl From<PrivKeyPolicyNotAllowed> for UnexpectedDerivationMethod {
fn from(e: PrivKeyPolicyNotAllowed) -> Self {
match e {
PrivKeyPolicyNotAllowed::HardwareWalletNotSupported => UnexpectedDerivationMethod::Trezor,
PrivKeyPolicyNotAllowed::UnsupportedMethod(method) => UnexpectedDerivationMethod::UnsupportedError(method),
PrivKeyPolicyNotAllowed::InternalError(e) => UnexpectedDerivationMethod::InternalError(e),
}
}
}
pub trait Transaction: fmt::Debug + 'static {
/// Raw transaction bytes of the transaction
fn tx_hex(&self) -> Vec<u8>;
/// Serializable representation of tx hash for displaying purpose
fn tx_hash(&self) -> BytesJson;
}
#[derive(Clone, Debug, PartialEq)]
pub enum TransactionEnum {
UtxoTx(UtxoTx),
SignedEthTx(SignedEthTx),
ZTransaction(ZTransaction),
CosmosTransaction(CosmosTransaction),
#[cfg(not(target_arch = "wasm32"))]
LightningPayment(LightningPayment),
}
ifrom!(TransactionEnum, UtxoTx);
ifrom!(TransactionEnum, SignedEthTx);
ifrom!(TransactionEnum, ZTransaction);
#[cfg(not(target_arch = "wasm32"))]
ifrom!(TransactionEnum, LightningPayment);
impl TransactionEnum {
#[cfg(not(target_arch = "wasm32"))]
pub fn supports_tx_helper(&self) -> bool { !matches!(self, TransactionEnum::LightningPayment(_)) }
#[cfg(target_arch = "wasm32")]
pub fn supports_tx_helper(&self) -> bool { true }
}
// NB: When stable and groked by IDEs, `enum_dispatch` can be used instead of `Deref` to speed things up.
impl Deref for TransactionEnum {
type Target = dyn Transaction;
fn deref(&self) -> &dyn Transaction {
match self {
TransactionEnum::UtxoTx(ref t) => t,
TransactionEnum::SignedEthTx(ref t) => t,
TransactionEnum::ZTransaction(ref t) => t,
TransactionEnum::CosmosTransaction(ref t) => t,
#[cfg(not(target_arch = "wasm32"))]
TransactionEnum::LightningPayment(ref p) => p,
}
}
}
/// Error type for handling tx serialization/deserialization operations.
#[derive(Debug, Clone)]
pub enum TxMarshalingErr {
InvalidInput(String),
/// For cases where serialized and deserialized values doesn't verify each other.
CrossCheckFailed(String),
NotSupported(String),
Internal(String),
}
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum TransactionErr {
/// Keeps transactions while throwing errors.
TxRecoverable(TransactionEnum, String),
/// Simply for plain error messages.
Plain(String),
}
impl TransactionErr {
/// Returns transaction if the error includes it.
#[inline]
pub fn get_tx(&self) -> Option<TransactionEnum> {
match self {
TransactionErr::TxRecoverable(tx, _) => Some(tx.clone()),
_ => None,
}
}
#[inline]
/// Returns plain text part of error.
pub fn get_plain_text_format(&self) -> String {
match self {
TransactionErr::TxRecoverable(_, err) => err.to_string(),
TransactionErr::Plain(err) => err.to_string(),
}
}
}
#[derive(Debug, PartialEq)]
pub enum FoundSwapTxSpend {
Spent(TransactionEnum),
Refunded(TransactionEnum),
}
pub enum CanRefundHtlc {
CanRefundNow,
// returns the number of seconds to sleep before HTLC becomes refundable
HaveToWait(u64),
}
#[derive(Debug, Display, Eq, PartialEq)]
pub enum NegotiateSwapContractAddrErr {
#[display(fmt = "InvalidOtherAddrLen, addr supplied {:?}", _0)]
InvalidOtherAddrLen(BytesJson),
#[display(fmt = "UnexpectedOtherAddr, addr supplied {:?}", _0)]
UnexpectedOtherAddr(BytesJson),
NoOtherAddrAndNoFallback,
}
#[derive(Debug, Display, Eq, PartialEq)]
pub enum ValidateOtherPubKeyErr {
#[display(fmt = "InvalidPubKey: {:?}", _0)]
InvalidPubKey(String),
}
#[derive(Clone, Debug)]
pub struct ConfirmPaymentInput {
pub payment_tx: Vec<u8>,
pub confirmations: u64,
pub requires_nota: bool,
pub wait_until: u64,
pub check_every: u64,
}
#[derive(Clone, Debug)]
pub struct WatcherValidateTakerFeeInput {
pub taker_fee_hash: Vec<u8>,
pub sender_pubkey: Vec<u8>,
pub min_block_number: u64,
pub fee_addr: Vec<u8>,
pub lock_duration: u64,
}
/// Helper struct wrapping arguments for [WatcherOps::watcher_validate_taker_payment].
#[derive(Clone)]
pub struct WatcherValidatePaymentInput {
/// Taker payment serialized to raw bytes.
pub payment_tx: Vec<u8>,
/// Payment refund preimage generated by taker.
pub taker_payment_refund_preimage: Vec<u8>,
/// Taker payment can be refunded after this timestamp.
pub time_lock: u64,
/// Taker's pubkey.
pub taker_pub: Vec<u8>,
/// Maker's pubkey.
pub maker_pub: Vec<u8>,
/// Hash of the secret generated by maker.
pub secret_hash: Vec<u8>,
/// Validation timeout.
pub wait_until: u64,
/// Required number of taker payment's on-chain confirmations.
pub confirmations: u64,
/// Maker coin.
pub maker_coin: MmCoinEnum,
}
/// Helper struct wrapping arguments for [SwapOps::validate_taker_payment] and [SwapOps::validate_maker_payment].
#[derive(Clone, Debug)]
pub struct ValidatePaymentInput {
/// Payment transaction serialized to raw bytes.
pub payment_tx: Vec<u8>,
/// Time lock duration in seconds.
pub time_lock_duration: u64,
/// Payment can be refunded after this timestamp.
pub time_lock: u64,
/// Pubkey of other side of the swap.
pub other_pub: Vec<u8>,
/// Hash of the secret generated by maker.
pub secret_hash: Vec<u8>,
/// Expected payment amount.
pub amount: BigDecimal,
/// Swap contract address if applicable.
pub swap_contract_address: Option<BytesJson>,
/// SPV proof check timeout.
pub try_spv_proof_until: u64,
/// Required number of payment's on-chain confirmations.
pub confirmations: u64,
/// Unique data of specific swap.
pub unique_swap_data: Vec<u8>,
/// The reward assigned to watcher for providing help to complete the swap.
pub watcher_reward: Option<WatcherReward>,
}
#[derive(Clone, Debug)]
pub struct WatcherSearchForSwapTxSpendInput<'a> {
pub time_lock: u32,
pub taker_pub: &'a [u8],
pub maker_pub: &'a [u8],
pub secret_hash: &'a [u8],
pub tx: &'a [u8],
pub search_from_block: u64,
pub watcher_reward: bool,
}
#[derive(Clone, Debug)]
pub struct SendMakerPaymentSpendPreimageInput<'a> {
pub preimage: &'a [u8],
pub secret_hash: &'a [u8],
pub secret: &'a [u8],
pub taker_pub: &'a [u8],
pub watcher_reward: bool,
}
pub struct SearchForSwapTxSpendInput<'a> {
pub time_lock: u64,
pub other_pub: &'a [u8],
pub secret_hash: &'a [u8],
pub tx: &'a [u8],
pub search_from_block: u64,
pub swap_contract_address: &'a Option<BytesJson>,
pub swap_unique_data: &'a [u8],
pub watcher_reward: bool,
}
#[derive(Copy, Clone, Debug)]
pub enum RewardTarget {
None,
Contract,
PaymentSender,
PaymentSpender,
PaymentReceiver,
}
#[derive(Clone, Debug)]
pub struct WatcherReward {
pub amount: BigDecimal,
pub is_exact_amount: bool,
pub reward_target: RewardTarget,
pub send_contract_reward_on_spend: bool,
}
/// Helper struct wrapping arguments for [SwapOps::send_taker_payment] and [SwapOps::send_maker_payment].
#[derive(Clone, Debug)]
pub struct SendPaymentArgs<'a> {
/// Time lock duration in seconds.
pub time_lock_duration: u64,
/// Payment can be refunded after this timestamp.
pub time_lock: u64,
/// This is either:
/// * Taker's pubkey if this structure is used in [`SwapOps::send_maker_payment`].
/// * Maker's pubkey if this structure is used in [`SwapOps::send_taker_payment`].
pub other_pubkey: &'a [u8],
/// Hash of the secret generated by maker.
pub secret_hash: &'a [u8],
/// Payment amount
pub amount: BigDecimal,
/// Swap contract address if applicable.
pub swap_contract_address: &'a Option<BytesJson>,
/// Unique data of specific swap.
pub swap_unique_data: &'a [u8],
/// Instructions for the next step of the swap (e.g., Lightning invoice).
pub payment_instructions: &'a Option<PaymentInstructions>,
/// The reward assigned to watcher for providing help to complete the swap.
pub watcher_reward: Option<WatcherReward>,
/// As of now, this field is specifically used to wait for confirmations of ERC20 approval transaction.
pub wait_for_confirmation_until: u64,
}
#[derive(Clone, Debug)]
pub struct SpendPaymentArgs<'a> {
/// This is either:
/// * Taker's payment tx if this structure is used in [`SwapOps::send_maker_spends_taker_payment`].
/// * Maker's payment tx if this structure is used in [`SwapOps::send_taker_spends_maker_payment`].
pub other_payment_tx: &'a [u8],
pub time_lock: u64,
/// This is either:
/// * Taker's pubkey if this structure is used in [`SwapOps::send_maker_spends_taker_payment`].
/// * Maker's pubkey if this structure is used in [`SwapOps::send_taker_spends_maker_payment`].
pub other_pubkey: &'a [u8],
pub secret: &'a [u8],
pub secret_hash: &'a [u8],
pub swap_contract_address: &'a Option<BytesJson>,
pub swap_unique_data: &'a [u8],
pub watcher_reward: bool,
}
#[derive(Clone, Debug)]
pub struct RefundPaymentArgs<'a> {
pub payment_tx: &'a [u8],
pub time_lock: u64,
/// This is either:
/// * Taker's pubkey if this structure is used in [`SwapOps::send_maker_refunds_payment`].
/// * Maker's pubkey if this structure is used in [`SwapOps::send_taker_refunds_payment`].
pub other_pubkey: &'a [u8],
pub secret_hash: &'a [u8],
pub swap_contract_address: &'a Option<BytesJson>,
pub swap_unique_data: &'a [u8],
pub watcher_reward: bool,
}
/// Helper struct wrapping arguments for [SwapOps::check_if_my_payment_sent].
#[derive(Clone, Debug)]
pub struct CheckIfMyPaymentSentArgs<'a> {
/// Payment can be refunded after this timestamp.
pub time_lock: u64,
/// Pubkey of other side of the swap.
pub other_pub: &'a [u8],
/// Hash of the secret generated by maker.
pub secret_hash: &'a [u8],
/// Search after specific block to avoid scanning entire blockchain.
pub search_from_block: u64,
/// Swap contract address if applicable.
pub swap_contract_address: &'a Option<BytesJson>,
/// Unique data of specific swap.
pub swap_unique_data: &'a [u8],
/// Payment amount.
pub amount: &'a BigDecimal,
/// Instructions for the next step of the swap (e.g., Lightning invoice).
pub payment_instructions: &'a Option<PaymentInstructions>,
}
#[derive(Clone, Debug)]
pub struct ValidateFeeArgs<'a> {
pub fee_tx: &'a TransactionEnum,
pub expected_sender: &'a [u8],
pub fee_addr: &'a [u8],
pub amount: &'a BigDecimal,
pub min_block_number: u64,
pub uuid: &'a [u8],
}
pub struct EthValidateFeeArgs<'a> {
pub fee_tx_hash: &'a H256,
pub expected_sender: &'a [u8],
pub fee_addr: &'a [u8],
pub amount: &'a BigDecimal,
pub min_block_number: u64,
pub uuid: &'a [u8],
}
#[derive(Clone, Debug)]
pub struct WaitForHTLCTxSpendArgs<'a> {
pub tx_bytes: &'a [u8],
pub secret_hash: &'a [u8],
pub wait_until: u64,
pub from_block: u64,
pub swap_contract_address: &'a Option<BytesJson>,
pub check_every: f64,
pub watcher_reward: bool,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum PaymentInstructions {
#[cfg(not(target_arch = "wasm32"))]
Lightning(Invoice),
WatcherReward(BigDecimal),
}
#[derive(Clone, Debug, Default)]
pub struct PaymentInstructionArgs<'a> {
pub secret_hash: &'a [u8],
pub amount: BigDecimal,
pub maker_lock_duration: u64,
pub expires_in: u64,
pub watcher_reward: bool,
pub wait_until: u64,
}
#[derive(Display)]
pub enum PaymentInstructionsErr {
LightningInvoiceErr(String),
WatcherRewardErr(String),
InternalError(String),
}
impl From<NumConversError> for PaymentInstructionsErr {
fn from(e: NumConversError) -> Self { PaymentInstructionsErr::InternalError(e.to_string()) }
}
#[derive(Display)]
pub enum ValidateInstructionsErr {
ValidateLightningInvoiceErr(String),
UnsupportedCoin(String),
DeserializationErr(String),
}
#[cfg(not(target_arch = "wasm32"))]
impl From<ParseOrSemanticError> for ValidateInstructionsErr {
fn from(e: ParseOrSemanticError) -> Self { ValidateInstructionsErr::ValidateLightningInvoiceErr(e.to_string()) }
}
#[derive(Display)]
pub enum RefundError {
DecodeErr(String),
DbError(String),
Timeout(String),
Internal(String),
}
#[derive(Debug, Display)]
pub enum WatcherRewardError {
RPCError(String),
InvalidCoinType(String),
InternalError(String),
}
/// Swap operations (mostly based on the Hash/Time locked transactions implemented by coin wallets).
#[async_trait]
pub trait SwapOps {
fn send_taker_fee(&self, fee_addr: &[u8], amount: BigDecimal, uuid: &[u8]) -> TransactionFut;
fn send_maker_payment(&self, maker_payment_args: SendPaymentArgs<'_>) -> TransactionFut;
fn send_taker_payment(&self, taker_payment_args: SendPaymentArgs<'_>) -> TransactionFut;
fn send_maker_spends_taker_payment(&self, maker_spends_payment_args: SpendPaymentArgs<'_>) -> TransactionFut;
fn send_taker_spends_maker_payment(&self, taker_spends_payment_args: SpendPaymentArgs<'_>) -> TransactionFut;
async fn send_taker_refunds_payment(&self, taker_refunds_payment_args: RefundPaymentArgs<'_>) -> TransactionResult;
async fn send_maker_refunds_payment(&self, maker_refunds_payment_args: RefundPaymentArgs<'_>) -> TransactionResult;
fn validate_fee(&self, validate_fee_args: ValidateFeeArgs<'_>) -> ValidatePaymentFut<()>;
fn validate_maker_payment(&self, input: ValidatePaymentInput) -> ValidatePaymentFut<()>;
fn validate_taker_payment(&self, input: ValidatePaymentInput) -> ValidatePaymentFut<()>;
fn check_if_my_payment_sent(
&self,
if_my_payment_sent_args: CheckIfMyPaymentSentArgs<'_>,
) -> Box<dyn Future<Item = Option<TransactionEnum>, Error = String> + Send>;
async fn search_for_swap_tx_spend_my(
&self,
input: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String>;
async fn search_for_swap_tx_spend_other(
&self,
input: SearchForSwapTxSpendInput<'_>,
) -> Result<Option<FoundSwapTxSpend>, String>;
async fn extract_secret(
&self,
secret_hash: &[u8],
spend_tx: &[u8],
watcher_reward: bool,
) -> Result<Vec<u8>, String>;
fn check_tx_signed_by_pub(&self, tx: &[u8], expected_pub: &[u8]) -> Result<bool, MmError<ValidatePaymentError>>;
/// Whether the refund transaction can be sent now
/// For example: there are no additional conditions for ETH, but for some UTXO coins we should wait for
/// locktime < MTP
fn can_refund_htlc(&self, locktime: u64) -> Box<dyn Future<Item = CanRefundHtlc, Error = String> + Send + '_> {
let now = now_sec();
let result = if now > locktime {
CanRefundHtlc::CanRefundNow
} else {
CanRefundHtlc::HaveToWait(locktime - now + 1)
};
Box::new(futures01::future::ok(result))
}
/// Whether the swap payment is refunded automatically or not when the locktime expires, or the other side fails the HTLC.
fn is_auto_refundable(&self) -> bool;
/// Waits for an htlc to be refunded automatically.
async fn wait_for_htlc_refund(&self, _tx: &[u8], _locktime: u64) -> RefundResult<()>;
fn negotiate_swap_contract_addr(
&self,
other_side_address: Option<&[u8]>,
) -> Result<Option<BytesJson>, MmError<NegotiateSwapContractAddrErr>>;
/// Consider using [`SwapOps::derive_htlc_pubkey`] if you need the public key only.
/// Some coins may not have a private key.
fn derive_htlc_key_pair(&self, swap_unique_data: &[u8]) -> KeyPair;
/// Derives an HTLC key-pair and returns a public key corresponding to that key.
fn derive_htlc_pubkey(&self, swap_unique_data: &[u8]) -> Vec<u8>;
fn validate_other_pubkey(&self, raw_pubkey: &[u8]) -> MmResult<(), ValidateOtherPubKeyErr>;
/// Instructions from the taker on how the maker should send his payment.
async fn maker_payment_instructions(
&self,
args: PaymentInstructionArgs<'_>,
) -> Result<Option<Vec<u8>>, MmError<PaymentInstructionsErr>>;
/// Instructions from the maker on how the taker should send his payment.
async fn taker_payment_instructions(
&self,
args: PaymentInstructionArgs<'_>,
) -> Result<Option<Vec<u8>>, MmError<PaymentInstructionsErr>>;
fn validate_maker_payment_instructions(
&self,
instructions: &[u8],
args: PaymentInstructionArgs<'_>,
) -> Result<PaymentInstructions, MmError<ValidateInstructionsErr>>;
fn validate_taker_payment_instructions(
&self,
instructions: &[u8],
args: PaymentInstructionArgs<'_>,
) -> Result<PaymentInstructions, MmError<ValidateInstructionsErr>>;
fn is_supported_by_watchers(&self) -> bool { false }
// Do we also need a method for the fallback contract?
fn contract_supports_watchers(&self) -> bool { true }
fn maker_locktime_multiplier(&self) -> f64 { 2.0 }
}
/// Operations on maker coin from taker swap side
#[async_trait]
pub trait TakerSwapMakerCoin {
/// Performs an action on Maker coin payment just before the Taker Swap payment refund begins
async fn on_taker_payment_refund_start(&self, maker_payment: &[u8]) -> RefundResult<()>;