forked from jl777/SuperNET
-
Notifications
You must be signed in to change notification settings - Fork 94
/
tendermint_coin.rs
2533 lines (2155 loc) · 94.5 KB
/
tendermint_coin.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::htlc::{IrisHtlc, MsgCreateHtlc, HTLC_STATE_COMPLETED, HTLC_STATE_OPEN, HTLC_STATE_REFUNDED};
#[cfg(not(target_arch = "wasm32"))]
use super::tendermint_native_rpc::*;
#[cfg(target_arch = "wasm32")] use super::tendermint_wasm_rpc::*;
use crate::coin_errors::{MyAddressError, ValidatePaymentError};
use crate::tendermint::htlc::MsgClaimHtlc;
use crate::tendermint::htlc_proto::{CreateHtlcProtoRep, QueryHtlcRequestProto, QueryHtlcResponseProto};
use crate::utxo::sat_from_big_decimal;
use crate::utxo::utxo_common::big_decimal_from_sat;
use crate::{big_decimal_from_sat_unsigned, BalanceError, BalanceFut, BigDecimal, CheckIfMyPaymentSentArgs,
CoinBalance, CoinFutSpawner, FeeApproxStage, FoundSwapTxSpend, HistorySyncState, MarketCoinOps, MmCoin,
NegotiateSwapContractAddrErr, PaymentInstructions, PaymentInstructionsErr, RawTransactionError,
RawTransactionFut, RawTransactionRequest, RawTransactionRes, SearchForSwapTxSpendInput,
SendMakerPaymentArgs, SendMakerRefundsPaymentArgs, SendMakerSpendsTakerPaymentArgs, SendTakerPaymentArgs,
SendTakerRefundsPaymentArgs, SendTakerSpendsMakerPaymentArgs, SignatureError, SignatureResult, SwapOps,
TradeFee, TradePreimageFut, TradePreimageResult, TradePreimageValue, TransactionDetails, TransactionEnum,
TransactionErr, TransactionFut, TransactionType, TxFeeDetails, TxMarshalingErr,
UnexpectedDerivationMethod, ValidateAddressResult, ValidateFeeArgs, ValidateInstructionsErr,
ValidateOtherPubKeyErr, ValidatePaymentFut, ValidatePaymentInput, VerificationError, VerificationResult,
WatcherOps, WatcherValidatePaymentInput, WithdrawError, WithdrawFut, WithdrawRequest};
use async_std::prelude::FutureExt as AsyncStdFutureExt;
use async_trait::async_trait;
use bitcrypto::{dhash160, sha256};
use common::executor::Timer;
use common::executor::{abortable_queue::AbortableQueue, AbortableSystem};
use common::log::warn;
use common::{get_utc_timestamp, log, Future01CompatExt};
use cosmrs::bank::MsgSend;
use cosmrs::crypto::secp256k1::SigningKey;
use cosmrs::proto::cosmos::auth::v1beta1::{BaseAccount, QueryAccountRequest, QueryAccountResponse};
use cosmrs::proto::cosmos::bank::v1beta1::{MsgSend as MsgSendProto, QueryBalanceRequest, QueryBalanceResponse};
use cosmrs::proto::cosmos::base::tendermint::v1beta1::{GetBlockByHeightRequest, GetBlockByHeightResponse,
GetLatestBlockRequest, GetLatestBlockResponse};
use cosmrs::proto::cosmos::base::v1beta1::Coin as CoinProto;
use cosmrs::proto::cosmos::tx::v1beta1::{GetTxRequest, GetTxResponse, GetTxsEventRequest, GetTxsEventResponse,
SimulateRequest, SimulateResponse, Tx, TxBody, TxRaw};
use cosmrs::tendermint::block::Height;
use cosmrs::tendermint::chain::Id as ChainId;
use cosmrs::tendermint::PublicKey;
use cosmrs::tx::{self, Fee, Msg, Raw, SignDoc, SignerInfo};
use cosmrs::{AccountId, Any, Coin, Denom, ErrorReport};
use crypto::privkey::key_pair_from_secret;
use derive_more::Display;
use futures::lock::Mutex as AsyncMutex;
use futures::{FutureExt, TryFutureExt};
use futures01::Future;
use hex::FromHexError;
use keys::KeyPair;
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::*;
use mm2_number::MmNumber;
use parking_lot::Mutex as PaMutex;
use prost::{DecodeError, Message};
use rpc::v1::types::Bytes as BytesJson;
use serde_json::Value as Json;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use uuid::Uuid;
// ABCI Request Paths
const ABCI_GET_LATEST_BLOCK_PATH: &str = "/cosmos.base.tendermint.v1beta1.Service/GetLatestBlock";
const ABCI_GET_BLOCK_BY_HEIGHT_PATH: &str = "/cosmos.base.tendermint.v1beta1.Service/GetBlockByHeight";
const ABCI_SIMULATE_TX_PATH: &str = "/cosmos.tx.v1beta1.Service/Simulate";
const ABCI_QUERY_ACCOUNT_PATH: &str = "/cosmos.auth.v1beta1.Query/Account";
const ABCI_QUERY_BALANCE_PATH: &str = "/cosmos.bank.v1beta1.Query/Balance";
const ABCI_GET_TX_PATH: &str = "/cosmos.tx.v1beta1.Service/GetTx";
const ABCI_QUERY_HTLC_PATH: &str = "/irismod.htlc.Query/HTLC";
const ABCI_GET_TXS_EVENT_PATH: &str = "/cosmos.tx.v1beta1.Service/GetTxsEvent";
pub(crate) const MIN_TX_SATOSHIS: i64 = 1;
// ABCI Request Defaults
const ABCI_REQUEST_HEIGHT: Option<Height> = None;
const ABCI_REQUEST_PROVE: bool = false;
/// 0.25 is good average gas price on atom and iris
const DEFAULT_GAS_PRICE: f64 = 0.25;
pub(super) const TIMEOUT_HEIGHT_DELTA: u64 = 100;
pub const GAS_LIMIT_DEFAULT: u64 = 100_000;
pub(crate) const TX_DEFAULT_MEMO: &str = "";
// https://github.com/irisnet/irismod/blob/5016c1be6fdbcffc319943f33713f4a057622f0a/modules/htlc/types/validation.go#L19-L22
const MAX_TIME_LOCK: i64 = 34560;
const MIN_TIME_LOCK: i64 = 50;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TendermintFeeDetails {
pub coin: String,
pub amount: BigDecimal,
pub gas_limit: u64,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TendermintProtocolInfo {
decimals: u8,
denom: String,
pub account_prefix: String,
chain_id: String,
gas_price: Option<f64>,
}
#[derive(Clone)]
pub struct ActivatedTokenInfo {
decimals: u8,
denom: Denom,
}
pub struct TendermintCoinImpl {
ticker: String,
/// TODO
/// Test Vec<String(rpc_urls)> instead of HttpClient and pick
/// better one in terms of performance & resource consumption on runtime.
rpc_clients: Vec<HttpClient>,
/// My address
avg_block_time: u8,
pub account_id: AccountId,
pub(super) account_prefix: String,
priv_key: Vec<u8>,
decimals: u8,
pub(super) denom: Denom,
chain_id: ChainId,
gas_price: Option<f64>,
pub(super) sequence_lock: AsyncMutex<()>,
tokens_info: PaMutex<HashMap<String, ActivatedTokenInfo>>,
/// This spawner is used to spawn coin's related futures that should be aborted on coin deactivation
/// or on [`MmArc::stop`].
pub(super) abortable_system: AbortableQueue,
}
#[derive(Clone)]
pub struct TendermintCoin(Arc<TendermintCoinImpl>);
impl Deref for TendermintCoin {
type Target = TendermintCoinImpl;
fn deref(&self) -> &Self::Target { &self.0 }
}
#[derive(Debug)]
pub struct TendermintInitError {
pub ticker: String,
pub kind: TendermintInitErrorKind,
}
#[derive(Display, Debug)]
pub enum TendermintInitErrorKind {
Internal(String),
InvalidPrivKey(String),
CouldNotGenerateAccountId(String),
EmptyRpcUrls,
RpcClientInitError(String),
InvalidChainId(String),
InvalidDenom(String),
RpcError(String),
#[display(fmt = "avg_block_time missing or invalid. Please provide it with min 1 or max 255 value.")]
AvgBlockTimeMissingOrInvalid,
}
#[derive(Display, Debug)]
pub enum TendermintCoinRpcError {
Prost(DecodeError),
InvalidResponse(String),
PerformError(String),
}
impl From<DecodeError> for TendermintCoinRpcError {
fn from(err: DecodeError) -> Self { TendermintCoinRpcError::Prost(err) }
}
impl From<TendermintCoinRpcError> for WithdrawError {
fn from(err: TendermintCoinRpcError) -> Self { WithdrawError::Transport(err.to_string()) }
}
impl From<TendermintCoinRpcError> for BalanceError {
fn from(err: TendermintCoinRpcError) -> Self {
match err {
TendermintCoinRpcError::InvalidResponse(e) => BalanceError::InvalidResponse(e),
TendermintCoinRpcError::Prost(e) => BalanceError::InvalidResponse(e.to_string()),
TendermintCoinRpcError::PerformError(e) => BalanceError::Transport(e),
}
}
}
impl From<TendermintCoinRpcError> for ValidatePaymentError {
fn from(err: TendermintCoinRpcError) -> Self {
match err {
TendermintCoinRpcError::InvalidResponse(e) => ValidatePaymentError::InvalidRpcResponse(e),
TendermintCoinRpcError::Prost(e) => ValidatePaymentError::InvalidRpcResponse(e.to_string()),
TendermintCoinRpcError::PerformError(e) => ValidatePaymentError::Transport(e),
}
}
}
#[cfg(not(target_arch = "wasm32"))]
impl From<cosmrs::rpc::Error> for TendermintCoinRpcError {
fn from(err: cosmrs::rpc::Error) -> Self { TendermintCoinRpcError::PerformError(err.to_string()) }
}
#[cfg(target_arch = "wasm32")]
impl From<PerformError> for TendermintCoinRpcError {
fn from(err: PerformError) -> Self { TendermintCoinRpcError::PerformError(err.to_string()) }
}
impl From<TendermintCoinRpcError> for RawTransactionError {
fn from(err: TendermintCoinRpcError) -> Self { RawTransactionError::Transport(err.to_string()) }
}
#[derive(Clone, Debug, PartialEq)]
pub struct CosmosTransaction {
pub data: cosmrs::proto::cosmos::tx::v1beta1::TxRaw,
}
impl crate::Transaction for CosmosTransaction {
fn tx_hex(&self) -> Vec<u8> { self.data.encode_to_vec() }
fn tx_hash(&self) -> BytesJson {
let bytes = self.data.encode_to_vec();
let hash = sha256(&bytes);
hash.to_vec().into()
}
}
fn account_id_from_privkey(priv_key: &[u8], prefix: &str) -> MmResult<AccountId, TendermintInitErrorKind> {
let signing_key =
SigningKey::from_bytes(priv_key).map_to_mm(|e| TendermintInitErrorKind::InvalidPrivKey(e.to_string()))?;
signing_key
.public_key()
.account_id(prefix)
.map_to_mm(|e| TendermintInitErrorKind::CouldNotGenerateAccountId(e.to_string()))
}
#[derive(Display, Debug)]
pub enum AccountIdFromPubkeyHexErr {
InvalidHexString(FromHexError),
CouldNotCreateAccountId(ErrorReport),
}
impl From<FromHexError> for AccountIdFromPubkeyHexErr {
fn from(err: FromHexError) -> Self { AccountIdFromPubkeyHexErr::InvalidHexString(err) }
}
impl From<ErrorReport> for AccountIdFromPubkeyHexErr {
fn from(err: ErrorReport) -> Self { AccountIdFromPubkeyHexErr::CouldNotCreateAccountId(err) }
}
pub fn account_id_from_pubkey_hex(prefix: &str, pubkey: &str) -> MmResult<AccountId, AccountIdFromPubkeyHexErr> {
let pubkey_bytes = hex::decode(pubkey)?;
let pubkey_hash = dhash160(&pubkey_bytes);
Ok(AccountId::new(prefix, pubkey_hash.as_slice())?)
}
pub struct AllBalancesResult {
pub platform_balance: BigDecimal,
pub tokens_balances: HashMap<String, BigDecimal>,
}
#[derive(Debug, Display)]
enum SearchForSwapTxSpendErr {
Cosmrs(ErrorReport),
Rpc(TendermintCoinRpcError),
TxMessagesEmpty,
ClaimHtlcTxNotFound,
UnexpectedHtlcState(i32),
Proto(DecodeError),
}
impl From<ErrorReport> for SearchForSwapTxSpendErr {
fn from(e: ErrorReport) -> Self { SearchForSwapTxSpendErr::Cosmrs(e) }
}
impl From<TendermintCoinRpcError> for SearchForSwapTxSpendErr {
fn from(e: TendermintCoinRpcError) -> Self { SearchForSwapTxSpendErr::Rpc(e) }
}
impl From<DecodeError> for SearchForSwapTxSpendErr {
fn from(e: DecodeError) -> Self { SearchForSwapTxSpendErr::Proto(e) }
}
impl TendermintCoin {
pub async fn init(
ctx: &MmArc,
ticker: String,
avg_block_time: u8,
protocol_info: TendermintProtocolInfo,
rpc_urls: Vec<String>,
priv_key: &[u8],
) -> MmResult<Self, TendermintInitError> {
if rpc_urls.is_empty() {
return MmError::err(TendermintInitError {
ticker,
kind: TendermintInitErrorKind::EmptyRpcUrls,
});
}
let account_id =
account_id_from_privkey(priv_key, &protocol_info.account_prefix).mm_err(|kind| TendermintInitError {
ticker: ticker.clone(),
kind,
})?;
let rpc_clients: Result<Vec<HttpClient>, _> = rpc_urls
.iter()
.map(|url| {
HttpClient::new(url.as_str()).map_to_mm(|e| TendermintInitError {
ticker: ticker.clone(),
kind: TendermintInitErrorKind::RpcClientInitError(e.to_string()),
})
})
.collect();
let rpc_clients = rpc_clients?;
let chain_id = ChainId::try_from(protocol_info.chain_id).map_to_mm(|e| TendermintInitError {
ticker: ticker.clone(),
kind: TendermintInitErrorKind::InvalidChainId(e.to_string()),
})?;
let denom = Denom::from_str(&protocol_info.denom).map_to_mm(|e| TendermintInitError {
ticker: ticker.clone(),
kind: TendermintInitErrorKind::InvalidDenom(e.to_string()),
})?;
// Create an abortable system linked to the `MmCtx` so if the context is stopped via `MmArc::stop`,
// all spawned futures related to `TendermintCoin` will be aborted as well.
let abortable_system = ctx
.abortable_system
.create_subsystem()
.map_to_mm(|e| TendermintInitError {
ticker: ticker.clone(),
kind: TendermintInitErrorKind::Internal(e.to_string()),
})?;
Ok(TendermintCoin(Arc::new(TendermintCoinImpl {
ticker,
rpc_clients,
account_id,
account_prefix: protocol_info.account_prefix,
priv_key: priv_key.to_vec(),
decimals: protocol_info.decimals,
denom,
chain_id,
gas_price: protocol_info.gas_price,
avg_block_time,
sequence_lock: AsyncMutex::new(()),
tokens_info: PaMutex::new(HashMap::new()),
abortable_system,
})))
}
// TODO
// Save one working client to the coin context, only try others once it doesn't
// work anymore.
// Also, try couple times more on health check errors.
async fn rpc_client(&self) -> MmResult<HttpClient, TendermintCoinRpcError> {
for rpc_client in self.rpc_clients.iter() {
match rpc_client.perform(HealthRequest).timeout(Duration::from_secs(3)).await {
Ok(Ok(_)) => return Ok(rpc_client.clone()),
Ok(Err(e)) => log::warn!(
"Recieved error from Tendermint rpc node during health check. Error: {:?}",
e
),
Err(_) => log::warn!("Tendermint rpc node: {:?} got timeout during health check", rpc_client),
};
}
MmError::err(TendermintCoinRpcError::PerformError(
"All the current rpc nodes are unavailable.".to_string(),
))
}
#[inline(always)]
fn gas_price(&self) -> f64 { self.gas_price.unwrap_or(DEFAULT_GAS_PRICE) }
#[allow(unused)]
async fn get_latest_block(&self) -> MmResult<GetLatestBlockResponse, TendermintCoinRpcError> {
let path = AbciPath::from_str(ABCI_GET_LATEST_BLOCK_PATH).expect("valid path");
let request = GetLatestBlockRequest {};
let request = AbciRequest::new(
Some(path),
request.encode_to_vec(),
ABCI_REQUEST_HEIGHT,
ABCI_REQUEST_PROVE,
);
let response = self.rpc_client().await?.perform(request).await?;
Ok(GetLatestBlockResponse::decode(response.response.value.as_slice())?)
}
#[allow(unused)]
async fn get_block_by_height(&self, height: i64) -> MmResult<GetBlockByHeightResponse, TendermintCoinRpcError> {
let path = AbciPath::from_str(ABCI_GET_BLOCK_BY_HEIGHT_PATH).expect("valid path");
let request = GetBlockByHeightRequest { height };
let request = AbciRequest::new(
Some(path),
request.encode_to_vec(),
ABCI_REQUEST_HEIGHT,
ABCI_REQUEST_PROVE,
);
let response = self.rpc_client().await?.perform(request).await?;
Ok(GetBlockByHeightResponse::decode(response.response.value.as_slice())?)
}
// We must simulate the tx on rpc nodes in order to calculate network fee.
// Right now cosmos doesn't expose any of gas price and fee informations directly.
// Therefore, we can call SimulateRequest or CheckTx(doesn't work with using Abci interface) to get used gas or fee itself.
pub(super) fn gen_simulated_tx(
&self,
account_info: BaseAccount,
tx_payload: Any,
timeout_height: u64,
memo: String,
) -> cosmrs::Result<Vec<u8>> {
let fee_amount = Coin {
denom: self.denom.clone(),
amount: 0_u64.into(),
};
let fee = Fee::from_amount_and_gas(fee_amount, GAS_LIMIT_DEFAULT);
let signkey = SigningKey::from_bytes(&self.priv_key)?;
let tx_body = tx::Body::new(vec![tx_payload], memo, timeout_height as u32);
let auth_info = SignerInfo::single_direct(Some(signkey.public_key()), account_info.sequence).auth_info(fee);
let sign_doc = SignDoc::new(&tx_body, &auth_info, &self.chain_id, account_info.account_number)?;
sign_doc.sign(&signkey)?.to_bytes()
}
/// This is converted from irismod and cosmos-sdk source codes written in golang.
/// Refs:
/// - Main algorithm: https://github.com/irisnet/irismod/blob/main/modules/htlc/types/htlc.go#L157
/// - Coins string building https://github.com/cosmos/cosmos-sdk/blob/main/types/coin.go#L210-L225
fn calculate_htlc_id(
&self,
from_address: &AccountId,
to_address: &AccountId,
amount: Vec<Coin>,
secret_hash: &[u8],
) -> String {
// Needs to be sorted if cointains multiple coins
// let mut amount = amount;
// amount.sort();
let coins_string = amount
.iter()
.map(|t| format!("{}{}", t.amount, t.denom))
.collect::<Vec<String>>()
.join(",");
let mut htlc_id = vec![];
htlc_id.extend_from_slice(secret_hash);
htlc_id.extend_from_slice(&from_address.to_bytes());
htlc_id.extend_from_slice(&to_address.to_bytes());
htlc_id.extend_from_slice(coins_string.as_bytes());
sha256(&htlc_id).to_string().to_uppercase()
}
#[allow(deprecated)]
pub(super) async fn calculate_fee(
&self,
base_denom: Denom,
tx_bytes: Vec<u8>,
) -> MmResult<Fee, TendermintCoinRpcError> {
let path = AbciPath::from_str(ABCI_SIMULATE_TX_PATH).expect("valid path");
let request = SimulateRequest { tx_bytes, tx: None };
let request = AbciRequest::new(
Some(path),
request.encode_to_vec(),
ABCI_REQUEST_HEIGHT,
ABCI_REQUEST_PROVE,
);
let response = self.rpc_client().await?.perform(request).await?;
let response = SimulateResponse::decode(response.response.value.as_slice())?;
let gas = response.gas_info.as_ref().ok_or_else(|| {
TendermintCoinRpcError::InvalidResponse(format!(
"Could not read gas_info. Invalid Response: {:?}",
response
))
})?;
let amount = ((gas.gas_used as f64 * 1.5) * self.gas_price()).ceil();
let fee_amount = Coin {
denom: base_denom,
amount: (amount as u64).into(),
};
Ok(Fee::from_amount_and_gas(fee_amount, GAS_LIMIT_DEFAULT))
}
#[allow(deprecated)]
pub(super) async fn calculate_fee_amount_as_u64(&self, tx_bytes: Vec<u8>) -> MmResult<u64, TendermintCoinRpcError> {
let path = AbciPath::from_str(ABCI_SIMULATE_TX_PATH).expect("valid path");
let request = SimulateRequest { tx_bytes, tx: None };
let request = AbciRequest::new(
Some(path),
request.encode_to_vec(),
ABCI_REQUEST_HEIGHT,
ABCI_REQUEST_PROVE,
);
let response = self.rpc_client().await?.perform(request).await?;
let response = SimulateResponse::decode(response.response.value.as_slice())?;
let gas = response.gas_info.as_ref().ok_or_else(|| {
TendermintCoinRpcError::InvalidResponse(format!(
"Could not read gas_info. Invalid Response: {:?}",
response
))
})?;
Ok(((gas.gas_used as f64 * 1.5) * self.gas_price()).ceil() as u64)
}
pub(super) async fn my_account_info(&self) -> MmResult<BaseAccount, TendermintCoinRpcError> {
let path = AbciPath::from_str(ABCI_QUERY_ACCOUNT_PATH).expect("valid path");
let request = QueryAccountRequest {
address: self.account_id.to_string(),
};
let request = AbciRequest::new(
Some(path),
request.encode_to_vec(),
ABCI_REQUEST_HEIGHT,
ABCI_REQUEST_PROVE,
);
let response = self.rpc_client().await?.perform(request).await?;
let account_response = QueryAccountResponse::decode(response.response.value.as_slice())?;
let account = account_response
.account
.or_mm_err(|| TendermintCoinRpcError::InvalidResponse("Account is None".into()))?;
Ok(BaseAccount::decode(account.value.as_slice())?)
}
pub(super) async fn balance_for_denom(&self, denom: String) -> MmResult<u64, TendermintCoinRpcError> {
let path = AbciPath::from_str(ABCI_QUERY_BALANCE_PATH).expect("valid path");
let request = QueryBalanceRequest {
address: self.account_id.to_string(),
denom,
};
let request = AbciRequest::new(
Some(path),
request.encode_to_vec(),
ABCI_REQUEST_HEIGHT,
ABCI_REQUEST_PROVE,
);
let response = self.rpc_client().await?.perform(request).await?;
let response = QueryBalanceResponse::decode(response.response.value.as_slice())?;
response
.balance
.or_mm_err(|| TendermintCoinRpcError::InvalidResponse("balance is None".into()))?
.amount
.parse()
.map_to_mm(|e| TendermintCoinRpcError::InvalidResponse(format!("balance is not u64, err {}", e)))
}
pub async fn all_balances(&self) -> MmResult<AllBalancesResult, TendermintCoinRpcError> {
let platform_balance_denom = self.balance_for_denom(self.denom.to_string()).await?;
let platform_balance = big_decimal_from_sat_unsigned(platform_balance_denom, self.decimals);
let ibc_assets_info = self.tokens_info.lock().clone();
let mut result = AllBalancesResult {
platform_balance,
tokens_balances: HashMap::new(),
};
for (ticker, info) in ibc_assets_info {
let balance_denom = self.balance_for_denom(info.denom.to_string()).await?;
let balance_decimal = big_decimal_from_sat_unsigned(balance_denom, info.decimals);
result.tokens_balances.insert(ticker, balance_decimal);
}
Ok(result)
}
fn gen_create_htlc_tx(
&self,
denom: Denom,
to: &AccountId,
amount: cosmrs::Decimal,
secret_hash: &[u8],
time_lock: u64,
) -> MmResult<IrisHtlc, TxMarshalingErr> {
let amount = vec![Coin { denom, amount }];
let timestamp = 0_u64;
let msg_payload = MsgCreateHtlc {
sender: self.account_id.clone(),
to: to.clone(),
receiver_on_other_chain: "".to_string(),
sender_on_other_chain: "".to_string(),
amount: amount.clone(),
hash_lock: hex::encode(secret_hash),
timestamp,
time_lock,
transfer: false,
};
let htlc_id = self.calculate_htlc_id(&self.account_id, to, amount, secret_hash);
Ok(IrisHtlc {
id: htlc_id,
msg_payload: msg_payload
.to_any()
.map_err(|e| MmError::new(TxMarshalingErr::InvalidInput(e.to_string())))?,
})
}
fn gen_claim_htlc_tx(&self, htlc_id: String, secret: &[u8]) -> MmResult<IrisHtlc, TxMarshalingErr> {
let msg_payload = MsgClaimHtlc {
id: htlc_id.clone(),
sender: self.account_id.clone(),
secret: hex::encode(secret),
};
Ok(IrisHtlc {
id: htlc_id,
msg_payload: msg_payload
.to_any()
.map_err(|e| MmError::new(TxMarshalingErr::InvalidInput(e.to_string())))?,
})
}
pub(super) fn any_to_signed_raw_tx(
&self,
account_info: BaseAccount,
tx_payload: Any,
fee: Fee,
timeout_height: u64,
memo: String,
) -> cosmrs::Result<Raw> {
let signkey = SigningKey::from_bytes(&self.priv_key)?;
let tx_body = tx::Body::new(vec![tx_payload], memo, timeout_height as u32);
let auth_info = SignerInfo::single_direct(Some(signkey.public_key()), account_info.sequence).auth_info(fee);
let sign_doc = SignDoc::new(&tx_body, &auth_info, &self.chain_id, account_info.account_number)?;
sign_doc.sign(&signkey)
}
pub fn add_activated_token_info(&self, ticker: String, decimals: u8, denom: Denom) {
self.tokens_info
.lock()
.insert(ticker, ActivatedTokenInfo { decimals, denom });
}
fn estimate_blocks_from_duration(&self, duration: u64) -> i64 {
let estimated_time_lock = (duration / self.avg_block_time as u64) as i64;
estimated_time_lock.clamp(MIN_TIME_LOCK, MAX_TIME_LOCK)
}
pub(crate) fn check_if_my_payment_sent_for_denom(
&self,
decimals: u8,
denom: Denom,
other_pub: &[u8],
secret_hash: &[u8],
amount: &BigDecimal,
) -> Box<dyn Future<Item = Option<TransactionEnum>, Error = String> + Send> {
let amount = try_fus!(sat_from_big_decimal(amount, decimals));
let amount = vec![Coin {
denom,
amount: amount.into(),
}];
let pubkey_hash = dhash160(other_pub);
let to_address = try_fus!(AccountId::new(&self.account_prefix, pubkey_hash.as_slice()));
let htlc_id = self.calculate_htlc_id(&self.account_id, &to_address, amount, secret_hash);
let coin = self.clone();
let fut = async move {
let htlc_response = try_s!(coin.query_htlc(htlc_id.clone()).await);
let htlc_data = match htlc_response.htlc {
Some(htlc) => htlc,
None => return Ok(None),
};
match htlc_data.state {
HTLC_STATE_OPEN | HTLC_STATE_COMPLETED | HTLC_STATE_REFUNDED => {},
unexpected_state => return Err(format!("Unexpected state for HTLC {}", unexpected_state)),
};
let rpc_client = try_s!(coin.rpc_client().await);
let q = format!("create_htlc.id = '{}'", htlc_id);
let response = try_s!(
// Search single tx
rpc_client
.perform(TxSearchRequest::new(q, false, 1, 1, TendermintResultOrder::Descending))
.await
);
if let Some(tx) = response.txs.first() {
if let cosmrs::tendermint::abci::Code::Err(err_code) = tx.tx_result.code {
return Err(format!(
"Got {} error code. Broadcasted HTLC likely isn't valid.",
err_code
));
}
let deserialized_tx = try_s!(cosmrs::Tx::from_bytes(tx.tx.as_bytes()));
let msg = try_s!(deserialized_tx.body.messages.first().ok_or("Tx body couldn't be read."));
let htlc = try_s!(CreateHtlcProtoRep::decode(msg.value.as_slice()));
if htlc.hash_lock.to_uppercase() == htlc_data.hash_lock.to_uppercase() {
let htlc = TransactionEnum::CosmosTransaction(CosmosTransaction {
data: try_s!(TxRaw::decode(tx.tx.as_bytes())),
});
return Ok(Some(htlc));
}
}
Ok(None)
};
Box::new(fut.boxed().compat())
}
pub(super) fn send_htlc_for_denom(
&self,
time_lock_duration: u64,
other_pub: &[u8],
secret_hash: &[u8],
amount: BigDecimal,
denom: Denom,
decimals: u8,
) -> TransactionFut {
let pubkey_hash = dhash160(other_pub);
let to = try_tx_fus!(AccountId::new(&self.account_prefix, pubkey_hash.as_slice()));
let amount_as_u64 = try_tx_fus!(sat_from_big_decimal(&amount, decimals));
let amount = cosmrs::Decimal::from(amount_as_u64);
let secret_hash = secret_hash.to_vec();
let coin = self.clone();
let fut = async move {
let time_lock = coin.estimate_blocks_from_duration(time_lock_duration);
let create_htlc_tx = try_tx_s!(coin.gen_create_htlc_tx(denom, &to, amount, &secret_hash, time_lock as u64));
let _sequence_lock = coin.sequence_lock.lock().await;
let current_block = try_tx_s!(coin.current_block().compat().await);
let timeout_height = current_block + TIMEOUT_HEIGHT_DELTA;
let account_info = try_tx_s!(coin.my_account_info().await);
let simulated_tx = try_tx_s!(coin.gen_simulated_tx(
account_info.clone(),
create_htlc_tx.msg_payload.clone(),
timeout_height,
TX_DEFAULT_MEMO.into(),
));
let fee = try_tx_s!(coin.calculate_fee(coin.denom.clone(), simulated_tx).await);
let tx_raw = try_tx_s!(coin.any_to_signed_raw_tx(
account_info.clone(),
create_htlc_tx.msg_payload.clone(),
fee,
timeout_height,
TX_DEFAULT_MEMO.into(),
));
let _tx_id = try_tx_s!(coin.send_raw_tx_bytes(&try_tx_s!(tx_raw.to_bytes())).compat().await);
Ok(TransactionEnum::CosmosTransaction(CosmosTransaction {
data: tx_raw.into(),
}))
};
Box::new(fut.boxed().compat())
}
pub(super) fn send_taker_fee_for_denom(
&self,
fee_addr: &[u8],
amount: BigDecimal,
denom: Denom,
decimals: u8,
uuid: &[u8],
) -> TransactionFut {
let memo = try_tx_fus!(Uuid::from_slice(uuid)).to_string();
let from_address = self.account_id.clone();
let pubkey_hash = dhash160(fee_addr);
let to_address = try_tx_fus!(AccountId::new(&self.account_prefix, pubkey_hash.as_slice()));
let amount_as_u64 = try_tx_fus!(sat_from_big_decimal(&amount, decimals));
let amount = cosmrs::Decimal::from(amount_as_u64);
let amount = vec![Coin { denom, amount }];
let tx_payload = try_tx_fus!(MsgSend {
from_address,
to_address,
amount,
}
.to_any());
let coin = self.clone();
let fut = async move {
let _sequence_lock = coin.sequence_lock.lock().await;
let account_info = try_tx_s!(coin.my_account_info().await);
let current_block = try_tx_s!(coin.current_block().compat().await.map_to_mm(WithdrawError::Transport));
let timeout_height = current_block + TIMEOUT_HEIGHT_DELTA;
let simulated_tx = try_tx_s!(coin.gen_simulated_tx(
account_info.clone(),
tx_payload.clone(),
timeout_height,
TX_DEFAULT_MEMO.into(),
));
let fee = try_tx_s!(coin.calculate_fee(coin.denom.clone(), simulated_tx).await);
let tx_raw = try_tx_s!(coin
.any_to_signed_raw_tx(account_info, tx_payload, fee, timeout_height, memo)
.map_to_mm(|e| WithdrawError::InternalError(e.to_string())));
let tx_bytes = try_tx_s!(tx_raw
.to_bytes()
.map_to_mm(|e| WithdrawError::InternalError(e.to_string())));
let _tx_id = try_tx_s!(coin.send_raw_tx_bytes(&tx_bytes).compat().await);
Ok(TransactionEnum::CosmosTransaction(CosmosTransaction {
data: tx_raw.into(),
}))
};
Box::new(fut.boxed().compat())
}
#[allow(clippy::too_many_arguments)]
pub(super) fn validate_fee_for_denom(
&self,
fee_tx: &TransactionEnum,
expected_sender: &[u8],
fee_addr: &[u8],
amount: &BigDecimal,
decimals: u8,
uuid: &[u8],
denom: String,
) -> Box<dyn Future<Item = (), Error = String> + Send> {
let tx = match fee_tx {
TransactionEnum::CosmosTransaction(tx) => tx.clone(),
invalid_variant => {
return Box::new(futures01::future::err(ERRL!(
"Unexpected tx variant {:?}",
invalid_variant
)))
},
};
let uuid = try_fus!(Uuid::from_slice(uuid)).to_string();
let sender_pubkey_hash = dhash160(expected_sender);
let expected_sender_address =
try_fus!(AccountId::new(&self.account_prefix, sender_pubkey_hash.as_slice())).to_string();
let dex_fee_addr_pubkey_hash = dhash160(fee_addr);
let expected_dex_fee_address = try_fus!(AccountId::new(
&self.account_prefix,
dex_fee_addr_pubkey_hash.as_slice()
))
.to_string();
let expected_amount = try_fus!(sat_from_big_decimal(amount, decimals));
let expected_amount = CoinProto {
denom,
amount: expected_amount.to_string(),
};
let coin = self.clone();
let fut = async move {
let tx_body = try_s!(TxBody::decode(tx.data.body_bytes.as_slice()));
if tx_body.messages.len() != 1 {
return ERR!("Tx body must have exactly one message");
}
let msg = try_s!(MsgSendProto::decode(tx_body.messages[0].value.as_slice()));
if msg.to_address != expected_dex_fee_address {
return ERR!(
"Dex fee is sent to wrong address: {}, expected {}",
msg.to_address,
expected_dex_fee_address
);
}
if msg.amount.len() != 1 {
return ERR!("Msg must have exactly one Coin");
}
if msg.amount[0] != expected_amount {
return ERR!("Invalid amount {:?}, expected {:?}", msg.amount[0], expected_amount);
}
if msg.from_address != expected_sender_address {
return ERR!(
"Invalid sender: {}, expected {}",
msg.from_address,
expected_sender_address
);
}
if tx_body.memo != uuid {
return ERR!("Invalid memo: {}, expected {}", msg.from_address, uuid);
}
let encoded_tx = tx.data.encode_to_vec();
let hash = hex::encode_upper(sha256(&encoded_tx).as_slice());
let encoded_from_rpc = try_s!(coin.request_tx(hash).await).encode_to_vec();
if encoded_tx != encoded_from_rpc {
return ERR!("Transaction from RPC doesn't match the input");
}
Ok(())
};
Box::new(fut.boxed().compat())
}
pub(super) fn validate_payment_for_denom(
&self,
input: ValidatePaymentInput,
denom: Denom,
decimals: u8,
) -> ValidatePaymentFut<()> {
let coin = self.clone();
let fut = async move {
let tx = cosmrs::Tx::from_bytes(&input.payment_tx)
.map_to_mm(|e| ValidatePaymentError::TxDeserializationError(e.to_string()))?;
if tx.body.messages.len() != 1 {
return MmError::err(ValidatePaymentError::WrongPaymentTx(
"Payment tx must have exactly one message".into(),
));
}
let create_htlc_msg_proto = CreateHtlcProtoRep::decode(tx.body.messages[0].value.as_slice())
.map_to_mm(|e| ValidatePaymentError::WrongPaymentTx(e.to_string()))?;
let create_htlc_msg = MsgCreateHtlc::try_from(create_htlc_msg_proto)
.map_to_mm(|e| ValidatePaymentError::WrongPaymentTx(e.to_string()))?;
let sender_pubkey_hash = dhash160(&input.other_pub);
let sender = AccountId::new(&coin.account_prefix, sender_pubkey_hash.as_slice())
.map_to_mm(|e| ValidatePaymentError::InvalidParameter(e.to_string()))?;
let amount = sat_from_big_decimal(&input.amount, decimals)?;
let amount = vec![Coin {
denom,
amount: amount.into(),
}];
let time_lock = coin.estimate_blocks_from_duration(input.time_lock_duration);
let expected_msg = MsgCreateHtlc {
sender: sender.clone(),
to: coin.account_id.clone(),
receiver_on_other_chain: "".into(),
sender_on_other_chain: "".into(),
amount: amount.clone(),
hash_lock: hex::encode(&input.secret_hash),
timestamp: 0,
time_lock: time_lock as u64,
transfer: false,
};
if create_htlc_msg != expected_msg {
return MmError::err(ValidatePaymentError::WrongPaymentTx(format!(
"Incorrect CreateHtlc message {:?}, expected {:?}",
create_htlc_msg, expected_msg
)));
}
let hash = hex::encode_upper(sha256(&input.payment_tx).as_slice());
let tx_from_rpc = coin.request_tx(hash).await?;
if input.payment_tx != tx_from_rpc.encode_to_vec() {
return MmError::err(ValidatePaymentError::InvalidRpcResponse(
"Tx from RPC doesn't match the input".into(),
));
}
let htlc_id = coin.calculate_htlc_id(&sender, &coin.account_id, amount, &input.secret_hash);
let htlc_response = coin.query_htlc(htlc_id.clone()).await?;
let htlc_data = htlc_response
.htlc
.or_mm_err(|| ValidatePaymentError::InvalidRpcResponse(format!("No HTLC data for {}", htlc_id)))?;
match htlc_data.state {
0 => Ok(()),
unexpected_state => MmError::err(ValidatePaymentError::UnexpectedPaymentState(format!(
"{}",
unexpected_state