-
Notifications
You must be signed in to change notification settings - Fork 352
/
cosmos.rs
2079 lines (1758 loc) · 70 KB
/
cosmos.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 alloc::sync::Arc;
use core::{
cmp::min,
convert::{TryFrom, TryInto},
future::Future,
str::FromStr,
time::Duration,
};
use std::{thread, time::Instant};
use bech32::{ToBase32, Variant};
use bitcoin::hashes::hex::ToHex;
use itertools::Itertools;
use prost::Message;
use prost_types::Any;
use tendermint::abci::Path as TendermintABCIPath;
use tendermint::account::Id as AccountId;
use tendermint::block::Height;
use tendermint::consensus::Params;
use tendermint_light_client::types::LightBlock as TMLightBlock;
use tendermint_proto::Protobuf;
use tendermint_rpc::endpoint::tx::Response as ResultTx;
use tendermint_rpc::query::{EventType, Query};
use tendermint_rpc::{endpoint::broadcast::tx_sync::Response, Client, HttpClient, Order};
use tokio::runtime::Runtime as TokioRuntime;
use tonic::codegen::http::Uri;
use tracing::{debug, trace, warn};
use ibc::downcast;
use ibc::events::{from_tx_response_event, IbcEvent};
use ibc::ics02_client::client_consensus::{
AnyConsensusState, AnyConsensusStateWithHeight, QueryClientEventRequest,
};
use ibc::ics02_client::client_state::{AnyClientState, IdentifiedAnyClientState};
use ibc::ics02_client::client_type::ClientType;
use ibc::ics02_client::events as ClientEvents;
use ibc::ics03_connection::connection::{ConnectionEnd, IdentifiedConnectionEnd};
use ibc::ics04_channel::channel::{ChannelEnd, IdentifiedChannelEnd, QueryPacketEventDataRequest};
use ibc::ics04_channel::events as ChannelEvents;
use ibc::ics04_channel::packet::{PacketMsgType, Sequence};
use ibc::ics07_tendermint::client_state::{AllowUpdate, ClientState};
use ibc::ics07_tendermint::consensus_state::ConsensusState as TMConsensusState;
use ibc::ics07_tendermint::header::Header as TmHeader;
use ibc::ics23_commitment::commitment::CommitmentPrefix;
use ibc::ics23_commitment::merkle::convert_tm_to_ics_merkle_proof;
use ibc::ics24_host::identifier::{ChainId, ChannelId, ClientId, ConnectionId, PortId};
use ibc::ics24_host::Path::ClientConsensusState as ClientConsensusPath;
use ibc::ics24_host::Path::ClientState as ClientStatePath;
use ibc::ics24_host::{ClientUpgradePath, Path, IBC_QUERY_PATH, SDK_UPGRADE_QUERY_PATH};
use ibc::query::{QueryTxHash, QueryTxRequest};
use ibc::signer::Signer;
use ibc::Height as ICSHeight;
use ibc_proto::cosmos::auth::v1beta1::{BaseAccount, EthAccount, QueryAccountRequest};
use ibc_proto::cosmos::base::tendermint::v1beta1::service_client::ServiceClient;
use ibc_proto::cosmos::base::tendermint::v1beta1::GetNodeInfoRequest;
use ibc_proto::cosmos::base::v1beta1::Coin;
use ibc_proto::cosmos::tx::v1beta1::mode_info::{Single, Sum};
use ibc_proto::cosmos::tx::v1beta1::{
AuthInfo, Fee, ModeInfo, SignDoc, SignerInfo, SimulateRequest, SimulateResponse, Tx, TxBody,
TxRaw,
};
use ibc_proto::ibc::core::channel::v1::{
PacketState, QueryChannelClientStateRequest, QueryChannelsRequest,
QueryConnectionChannelsRequest, QueryNextSequenceReceiveRequest,
QueryPacketAcknowledgementsRequest, QueryPacketCommitmentsRequest, QueryUnreceivedAcksRequest,
QueryUnreceivedPacketsRequest,
};
use ibc_proto::ibc::core::client::v1::{QueryClientStatesRequest, QueryConsensusStatesRequest};
use ibc_proto::ibc::core::commitment::v1::MerkleProof;
use ibc_proto::ibc::core::connection::v1::{
QueryClientConnectionsRequest, QueryConnectionsRequest,
};
use crate::config::{AddressType, ChainConfig, GasPrice};
use crate::error::Error;
use crate::event::monitor::{EventMonitor, EventReceiver};
use crate::keyring::{KeyEntry, KeyRing, Store};
use crate::light_client::tendermint::LightClient as TmLightClient;
use crate::light_client::LightClient;
use crate::light_client::Verified;
use crate::{chain::QueryResponse, event::monitor::TxMonitorCmd};
use super::{ChainEndpoint, HealthCheck};
mod compatibility;
/// Default gas limit when submitting a transaction.
const DEFAULT_MAX_GAS: u64 = 300_000;
/// Fraction of the estimated gas to add to the gas limit when submitting a transaction.
const DEFAULT_GAS_PRICE_ADJUSTMENT: f64 = 0.1;
/// Upper limit on the size of transactions submitted by Hermes, expressed as a
/// fraction of the maximum block size defined in the Tendermint core consensus parameters.
pub const GENESIS_MAX_BYTES_MAX_FRACTION: f64 = 0.9;
mod retry_strategy {
use crate::util::retry::Fixed;
use core::time::Duration;
pub fn wait_for_block_commits(max_total_wait: Duration) -> impl Iterator<Item = Duration> {
let backoff_millis = 300; // The periodic backoff
let count: usize = (max_total_wait.as_millis() / backoff_millis as u128) as usize;
Fixed::from_millis(backoff_millis).take(count)
}
}
pub struct CosmosSdkChain {
config: ChainConfig,
rpc_client: HttpClient,
grpc_addr: Uri,
rt: Arc<TokioRuntime>,
keybase: KeyRing,
/// A cached copy of the account information
account: Option<BaseAccount>,
}
impl CosmosSdkChain {
/// Performs validation of chain-specific configuration
/// parameters against the chain's genesis configuration.
///
/// Currently, validates the following:
/// - the configured `max_tx_size` is appropriate.
///
/// Emits a log warning in case any error is encountered and
/// exits early without doing subsequent validations.
pub fn validate_params(&self) -> Result<(), Error> {
// Get the latest height and convert to tendermint Height
let latest_height = Height::try_from(self.query_latest_height()?.revision_height)
.map_err(Error::invalid_height)?;
// Check on the configured max_tx_size against the consensus parameters at latest height
let result = self
.block_on(self.rpc_client.consensus_params(latest_height))
.map_err(|e| {
Error::config_validation_json_rpc(
self.id().clone(),
self.config.rpc_addr.to_string(),
"/consensus_params".to_string(),
e,
)
})?;
let max_bound = result.consensus_params.block.max_bytes;
let max_allowed = mul_ceil(max_bound, GENESIS_MAX_BYTES_MAX_FRACTION) as usize;
if self.max_tx_size() > max_allowed {
return Err(Error::config_validation_tx_size_out_of_bounds(
self.id().clone(),
self.max_tx_size(),
max_bound,
));
}
Ok(())
}
/// The unbonding period of this chain
pub fn unbonding_period(&self) -> Result<Duration, Error> {
crate::time!("unbonding_period");
let mut client = self
.block_on(
ibc_proto::cosmos::staking::v1beta1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(Error::grpc_transport)?;
let request =
tonic::Request::new(ibc_proto::cosmos::staking::v1beta1::QueryParamsRequest {});
let response = self
.block_on(client.params(request))
.map_err(Error::grpc_status)?;
let res = response
.into_inner()
.params
.ok_or_else(|| Error::grpc_response_param("none staking params".to_string()))?
.unbonding_time
.ok_or_else(|| Error::grpc_response_param("none unbonding time".to_string()))?;
Ok(Duration::new(res.seconds as u64, res.nanos as u32))
}
fn rpc_client(&self) -> &HttpClient {
&self.rpc_client
}
pub fn config(&self) -> &ChainConfig {
&self.config
}
/// Query the consensus parameters via an RPC query
/// Specific to the SDK and used only for Tendermint client create
pub fn query_consensus_params(&self) -> Result<Params, Error> {
crate::time!("query_consensus_params");
Ok(self
.block_on(self.rpc_client().genesis())
.map_err(|e| Error::rpc(self.config.rpc_addr.clone(), e))?
.consensus_params)
}
/// Run a future to completion on the Tokio runtime.
fn block_on<F: Future>(&self, f: F) -> F::Output {
crate::time!("block_on");
self.rt.block_on(f)
}
fn send_tx(&mut self, proto_msgs: Vec<Any>) -> Result<Response, Error> {
crate::time!("send_tx");
let account_seq = self.account_sequence()?;
debug!(
"[{}] send_tx: sending {} messages using nonce {}",
self.id(),
proto_msgs.len(),
account_seq,
);
let signer_info = self.signer(account_seq)?;
let fee = self.default_fee();
let (body, body_buf) = tx_body_and_bytes(proto_msgs)?;
let (auth_info, auth_buf) = auth_info_and_bytes(signer_info.clone(), fee.clone())?;
let signed_doc = self.signed_doc(body_buf.clone(), auth_buf, account_seq)?;
// Try to simulate the Tx.
// It is possible that a batch of messages are fragmented by the caller (`send_msgs`) such that
// they do not individually verify. For example for the following batch
// [`MsgUpdateClient`, `MsgRecvPacket`, ..., `MsgRecvPacket`]
// if the batch is split in two TX-es, the second one will fail the simulation in `deliverTx` check
// In this case we just leave the gas un-adjusted, i.e. use `self.max_gas()`
let estimated_gas = self
.send_tx_simulate(Tx {
body: Some(body),
auth_info: Some(auth_info),
signatures: vec![signed_doc],
})
.map_or(self.max_gas(), |sr| {
sr.gas_info.map_or(self.max_gas(), |g| g.gas_used)
});
if estimated_gas > self.max_gas() {
return Err(Error::tx_simulate_gas_estimate_exceeded(
self.id().clone(),
estimated_gas,
self.max_gas(),
));
}
let adjusted_fee = self.fee_with_gas(estimated_gas);
trace!(
"[{}] send_tx: based on the estimated gas, adjusting fee from {:?} to {:?}",
self.id(),
fee,
adjusted_fee
);
let (_auth_adjusted, auth_buf_adjusted) = auth_info_and_bytes(signer_info, adjusted_fee)?;
let account_number = self.account_number()?;
let signed_doc =
self.signed_doc(body_buf.clone(), auth_buf_adjusted.clone(), account_number)?;
let tx_raw = TxRaw {
body_bytes: body_buf,
auth_info_bytes: auth_buf_adjusted,
signatures: vec![signed_doc],
};
let mut tx_bytes = Vec::new();
prost::Message::encode(&tx_raw, &mut tx_bytes).unwrap();
let response = self.block_on(broadcast_tx_sync(self, tx_bytes))?;
debug!("[{}] send_tx: broadcast_tx_sync: {:?}", self.id(), response);
self.incr_account_sequence()?;
Ok(response)
}
/// The maximum amount of gas the relayer is willing to pay for a transaction
fn max_gas(&self) -> u64 {
self.config.max_gas.unwrap_or(DEFAULT_MAX_GAS)
}
/// The gas price
fn gas_price(&self) -> &GasPrice {
&self.config.gas_price
}
/// The gas price adjustment
fn gas_adjustment(&self) -> f64 {
self.config
.gas_adjustment
.unwrap_or(DEFAULT_GAS_PRICE_ADJUSTMENT)
}
/// Adjusts the fee based on the configured `gas_adjustment` to prevent out of gas errors.
/// The actual gas cost, when a transaction is executed, may be slightly higher than the
/// one returned by the simulation.
fn apply_adjustment_to_gas(&self, gas_amount: u64) -> u64 {
min(
gas_amount + mul_ceil(gas_amount, self.gas_adjustment()),
self.max_gas(),
)
}
/// The maximum fee the relayer pays for a transaction
fn max_fee_in_coins(&self) -> Coin {
calculate_fee(self.max_gas(), self.gas_price())
}
/// The fee in coins based on gas amount
fn fee_from_gas_in_coins(&self, gas: u64) -> Coin {
calculate_fee(gas, self.gas_price())
}
/// The maximum number of messages included in a transaction
fn max_msg_num(&self) -> usize {
self.config.max_msg_num.into()
}
/// The maximum size of any transaction sent by the relayer to this chain
fn max_tx_size(&self) -> usize {
self.config.max_tx_size.into()
}
fn query(&self, data: Path, height: ICSHeight, prove: bool) -> Result<QueryResponse, Error> {
crate::time!("query");
let path = TendermintABCIPath::from_str(IBC_QUERY_PATH).unwrap();
let height = Height::try_from(height.revision_height).map_err(Error::invalid_height)?;
if !data.is_provable() & prove {
return Err(Error::private_store());
}
let response = self.block_on(abci_query(self, path, data.to_string(), height, prove))?;
// TODO - Verify response proof, if requested.
if prove {}
Ok(response)
}
/// Perform an ABCI query against the client upgrade sub-store.
/// Fetches both the target data, as well as the proof.
///
/// The data is returned in its raw format `Vec<u8>`, and is either
/// the client state (if the target path is [`UpgradedClientState`]),
/// or the client consensus state ([`UpgradedClientConsensusState`]).
fn query_client_upgrade_state(
&self,
data: ClientUpgradePath,
height: Height,
) -> Result<(Vec<u8>, MerkleProof), Error> {
let prev_height = Height::try_from(height.value() - 1).map_err(Error::invalid_height)?;
let path = TendermintABCIPath::from_str(SDK_UPGRADE_QUERY_PATH).unwrap();
let response: QueryResponse = self.block_on(abci_query(
self,
path,
Path::Upgrade(data).to_string(),
prev_height,
true,
))?;
let proof = response.proof.ok_or_else(Error::empty_response_proof)?;
Ok((response.value, proof))
}
fn send_tx_simulate(&self, tx: Tx) -> Result<SimulateResponse, Error> {
crate::time!("tx simulate");
// The `tx` field of `SimulateRequest` was deprecated
// in favor of `tx_bytes`
let mut tx_bytes = vec![];
prost::Message::encode(&tx, &mut tx_bytes).unwrap();
#[allow(deprecated)]
let req = SimulateRequest { tx: None, tx_bytes };
let mut client = self
.block_on(
ibc_proto::cosmos::tx::v1beta1::service_client::ServiceClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(Error::grpc_transport)?;
let request = tonic::Request::new(req);
let response = self
.block_on(client.simulate(request))
.map_err(Error::grpc_status)?
.into_inner();
Ok(response)
}
fn key(&self) -> Result<KeyEntry, Error> {
self.keybase()
.get_key(&self.config.key_name)
.map_err(Error::key_base)
}
fn key_bytes(&self, key: &KeyEntry) -> Result<Vec<u8>, Error> {
let mut pk_buf = Vec::new();
prost::Message::encode(&key.public_key.public_key.to_bytes(), &mut pk_buf).unwrap();
Ok(pk_buf)
}
fn key_and_bytes(&self) -> Result<(KeyEntry, Vec<u8>), Error> {
let key = self.key()?;
let key_bytes = self.key_bytes(&key)?;
Ok((key, key_bytes))
}
fn account(&mut self) -> Result<&mut BaseAccount, Error> {
if self.account == None {
let account = self.block_on(query_account(self, self.key()?.account))?;
debug!(
sequence = %account.sequence,
number = %account.account_number,
"[{}] send_tx: retrieved account",
self.id()
);
self.account = Some(account);
}
Ok(self
.account
.as_mut()
.expect("account was supposedly just cached"))
}
fn account_number(&mut self) -> Result<u64, Error> {
Ok(self.account()?.account_number)
}
fn account_sequence(&mut self) -> Result<u64, Error> {
Ok(self.account()?.sequence)
}
fn incr_account_sequence(&mut self) -> Result<(), Error> {
self.account()?.sequence += 1;
Ok(())
}
fn signer(&self, sequence: u64) -> Result<SignerInfo, Error> {
let (_key, pk_buf) = self.key_and_bytes()?;
let pk_type = match &self.config.address_type {
AddressType::Cosmos => "/cosmos.crypto.secp256k1.PubKey".to_string(),
AddressType::Ethermint { pk_type } => pk_type.clone(),
};
// Create a MsgSend proto Any message
let pk_any = Any {
type_url: pk_type,
value: pk_buf,
};
let single = Single { mode: 1 };
let sum_single = Some(Sum::Single(single));
let mode = Some(ModeInfo { sum: sum_single });
let signer_info = SignerInfo {
public_key: Some(pk_any),
mode_info: mode,
sequence,
};
Ok(signer_info)
}
fn default_fee(&self) -> Fee {
Fee {
amount: vec![self.max_fee_in_coins()],
gas_limit: self.max_gas(),
payer: "".to_string(),
granter: "".to_string(),
}
}
fn fee_with_gas(&self, gas_limit: u64) -> Fee {
let adjusted_gas_limit = self.apply_adjustment_to_gas(gas_limit);
Fee {
amount: vec![self.fee_from_gas_in_coins(adjusted_gas_limit)],
gas_limit: adjusted_gas_limit,
..self.default_fee()
}
}
fn signed_doc(
&self,
body_bytes: Vec<u8>,
auth_info_bytes: Vec<u8>,
account_number: u64,
) -> Result<Vec<u8>, Error> {
let sign_doc = SignDoc {
body_bytes,
auth_info_bytes,
chain_id: self.config.clone().id.to_string(),
account_number,
};
// A protobuf serialization of a SignDoc
let mut signdoc_buf = Vec::new();
prost::Message::encode(&sign_doc, &mut signdoc_buf).unwrap();
// Sign doc
let signed = self
.keybase
.sign_msg(
&self.config.key_name,
signdoc_buf,
&self.config.address_type,
)
.map_err(Error::key_base)?;
Ok(signed)
}
/// Given a vector of `TxSyncResult` elements,
/// each including a transaction response hash for one or more messages, periodically queries the chain
/// with the transaction hashes to get the list of IbcEvents included in those transactions.
pub fn wait_for_block_commits(
&self,
mut tx_sync_results: Vec<TxSyncResult>,
) -> Result<Vec<TxSyncResult>, Error> {
use crate::util::retry::{retry_with_index, RetryResult};
let hashes = tx_sync_results
.iter()
.map(|res| res.response.hash.to_string())
.join(", ");
warn!(
"[{}] waiting for commit of tx hashes(s) {}",
self.id(),
hashes
);
// Wait a little bit initially
thread::sleep(Duration::from_millis(200));
let start = Instant::now();
let result = retry_with_index(
retry_strategy::wait_for_block_commits(self.config.rpc_timeout),
|index| {
if all_tx_results_found(&tx_sync_results) {
trace!(
"[{}] wait_for_block_commits: retrieved {} tx results after {} tries ({}ms)",
self.id(),
tx_sync_results.len(),
index,
start.elapsed().as_millis()
);
// All transactions confirmed
return RetryResult::Ok(());
}
for TxSyncResult { response, events } in tx_sync_results.iter_mut() {
// If this transaction was not committed, determine whether it was because it failed
// or because it hasn't been committed yet.
if empty_event_present(events) {
// If the transaction failed, replace the events with an error,
// so that we don't attempt to resolve the transaction later on.
if response.code.value() != 0 {
*events = vec![IbcEvent::ChainError(format!(
"deliver_tx on chain {} for Tx hash {} reports error: code={:?}, log={:?}",
self.id(), response.hash, response.code, response.log
))];
// Otherwise, try to resolve transaction hash to the corresponding events.
} else if let Ok(events_per_tx) =
self.query_txs(QueryTxRequest::Transaction(QueryTxHash(response.hash)))
{
// If we get events back, progress was made, so we replace the events
// with the new ones. in both cases we will check in the next iteration
// whether or not the transaction was fully committed.
if !events_per_tx.is_empty() {
*events = events_per_tx;
}
}
}
}
RetryResult::Retry(index)
},
);
match result {
// All transactions confirmed
Ok(()) => Ok(tx_sync_results),
// Did not find confirmation
Err(_) => Err(Error::tx_no_confirmation()),
}
}
fn trusting_period(&self, unbonding_period: Duration) -> Duration {
self.config
.trusting_period
.unwrap_or(2 * unbonding_period / 3)
}
}
fn empty_event_present(events: &[IbcEvent]) -> bool {
events.iter().any(|ev| matches!(ev, IbcEvent::Empty(_)))
}
fn all_tx_results_found(tx_sync_results: &[TxSyncResult]) -> bool {
tx_sync_results
.iter()
.all(|r| !empty_event_present(&r.events))
}
impl ChainEndpoint for CosmosSdkChain {
type LightBlock = TMLightBlock;
type Header = TmHeader;
type ConsensusState = TMConsensusState;
type ClientState = ClientState;
type LightClient = TmLightClient;
fn bootstrap(config: ChainConfig, rt: Arc<TokioRuntime>) -> Result<Self, Error> {
let rpc_client = HttpClient::new(config.rpc_addr.clone())
.map_err(|e| Error::rpc(config.rpc_addr.clone(), e))?;
// Initialize key store and load key
let keybase = KeyRing::new(Store::Test, &config.account_prefix, &config.id)
.map_err(Error::key_base)?;
let grpc_addr = Uri::from_str(&config.grpc_addr.to_string())
.map_err(|e| Error::invalid_uri(config.grpc_addr.to_string(), e))?;
let chain = Self {
config,
rpc_client,
grpc_addr,
rt,
keybase,
account: None,
};
Ok(chain)
}
fn init_light_client(&self) -> Result<Self::LightClient, Error> {
use tendermint_light_client::types::PeerId;
crate::time!("init_light_client");
let peer_id: PeerId = self
.rt
.block_on(self.rpc_client.status())
.map(|s| s.node_info.id)
.map_err(|e| Error::rpc(self.config.rpc_addr.clone(), e))?;
let light_client = TmLightClient::from_config(&self.config, peer_id)?;
Ok(light_client)
}
fn init_event_monitor(
&self,
rt: Arc<TokioRuntime>,
) -> Result<(EventReceiver, TxMonitorCmd), Error> {
crate::time!("init_event_monitor");
let (mut event_monitor, event_receiver, monitor_tx) = EventMonitor::new(
self.config.id.clone(),
self.config.websocket_addr.clone(),
rt,
)
.map_err(Error::event_monitor)?;
event_monitor.subscribe().map_err(Error::event_monitor)?;
thread::spawn(move || event_monitor.run());
Ok((event_receiver, monitor_tx))
}
fn shutdown(self) -> Result<(), Error> {
Ok(())
}
fn id(&self) -> &ChainId {
&self.config().id
}
fn keybase(&self) -> &KeyRing {
&self.keybase
}
fn keybase_mut(&mut self) -> &mut KeyRing {
&mut self.keybase
}
/// Does multiple RPC calls to the full node, to check for
/// reachability and some basic APIs are available.
///
/// Currently this checks that:
/// - the node responds OK to `/health` RPC call;
/// - the node has transaction indexing enabled;
/// - the SDK version is supported;
///
/// Emits a log warning in case anything is amiss.
/// Exits early if any health check fails, without doing any
/// further checks.
fn health_check(&self) -> Result<HealthCheck, Error> {
if let Err(e) = self.block_on(do_health_check(self)) {
warn!("Health checkup for chain '{}' failed", self.id());
warn!(" Reason: {}", e.detail());
warn!(" Some Hermes features may not work in this mode!");
return Ok(HealthCheck::Unhealthy(Box::new(e)));
}
if let Err(e) = self.validate_params() {
warn!("Hermes might be misconfigured for chain '{}'", self.id());
warn!(" Reason: {}", e.detail());
warn!(" Some Hermes features may not work in this mode!");
return Ok(HealthCheck::Unhealthy(Box::new(e)));
}
Ok(HealthCheck::Healthy)
}
/// Send one or more transactions that include all the specified messages.
/// The `proto_msgs` are split in transactions such they don't exceed the configured maximum
/// number of messages per transaction and the maximum transaction size.
/// Then `send_tx()` is called with each Tx. `send_tx()` determines the fee based on the
/// on-chain simulation and if this exceeds the maximum gas specified in the configuration file
/// then it returns error.
/// TODO - more work is required here for a smarter split maybe iteratively accumulating/ evaluating
/// msgs in a Tx until any of the max size, max num msgs, max fee are exceeded.
fn send_messages_and_wait_commit(
&mut self,
proto_msgs: Vec<Any>,
) -> Result<Vec<IbcEvent>, Error> {
crate::time!("send_messages_and_wait_commit");
debug!(
"send_messages_and_wait_commit with {} messages",
proto_msgs.len()
);
if proto_msgs.is_empty() {
return Ok(vec![]);
}
let mut tx_sync_results = vec![];
let mut n = 0;
let mut size = 0;
let mut msg_batch = vec![];
for msg in proto_msgs.iter() {
msg_batch.push(msg.clone());
let mut buf = Vec::new();
prost::Message::encode(msg, &mut buf).unwrap();
n += 1;
size += buf.len();
if n >= self.max_msg_num() || size >= self.max_tx_size() {
let events_per_tx = vec![IbcEvent::Empty("".to_string()); msg_batch.len()];
let tx_sync_result = self.send_tx(msg_batch)?;
tx_sync_results.push(TxSyncResult {
response: tx_sync_result,
events: events_per_tx,
});
n = 0;
size = 0;
msg_batch = vec![];
}
}
if !msg_batch.is_empty() {
let events_per_tx = vec![IbcEvent::Empty("".to_string()); msg_batch.len()];
let tx_sync_result = self.send_tx(msg_batch)?;
tx_sync_results.push(TxSyncResult {
response: tx_sync_result,
events: events_per_tx,
});
}
let tx_sync_results = self.wait_for_block_commits(tx_sync_results)?;
let events = tx_sync_results
.into_iter()
.map(|el| el.events)
.flatten()
.collect();
Ok(events)
}
fn send_messages_and_wait_check_tx(
&mut self,
proto_msgs: Vec<Any>,
) -> Result<Vec<Response>, Error> {
crate::time!("send_messages_and_wait_check_tx");
debug!(
"send_messages_and_wait_check_tx with {} messages",
proto_msgs.len()
);
if proto_msgs.is_empty() {
return Ok(vec![]);
}
let mut responses = vec![];
let mut n = 0;
let mut size = 0;
let mut msg_batch = vec![];
for msg in proto_msgs.iter() {
msg_batch.push(msg.clone());
let mut buf = Vec::new();
prost::Message::encode(msg, &mut buf).unwrap();
n += 1;
size += buf.len();
if n >= self.max_msg_num() || size >= self.max_tx_size() {
// Send the tx and enqueue the resulting response
responses.push(self.send_tx(msg_batch)?);
n = 0;
size = 0;
msg_batch = vec![];
}
}
if !msg_batch.is_empty() {
responses.push(self.send_tx(msg_batch)?);
}
Ok(responses)
}
/// Get the account for the signer
fn get_signer(&mut self) -> Result<Signer, Error> {
crate::time!("get_signer");
// Get the key from key seed file
let key = self
.keybase()
.get_key(&self.config.key_name)
.map_err(Error::key_base)?;
let bech32 = encode_to_bech32(&key.address.to_hex(), &self.config.account_prefix)?;
Ok(Signer::new(bech32))
}
/// Get the signing key
fn get_key(&mut self) -> Result<KeyEntry, Error> {
crate::time!("get_key");
// Get the key from key seed file
let key = self
.keybase()
.get_key(&self.config.key_name)
.map_err(Error::key_base)?;
Ok(key)
}
fn query_commitment_prefix(&self) -> Result<CommitmentPrefix, Error> {
crate::time!("query_commitment_prefix");
// TODO - do a real chain query
Ok(CommitmentPrefix::from(
self.config().store_prefix.as_bytes().to_vec(),
))
}
/// Query the latest height the chain is at via a RPC query
fn query_latest_height(&self) -> Result<ICSHeight, Error> {
crate::time!("query_latest_height");
let status = self
.block_on(self.rpc_client().status())
.map_err(|e| Error::rpc(self.config.rpc_addr.clone(), e))?;
if status.sync_info.catching_up {
return Err(Error::chain_not_caught_up(
self.config.rpc_addr.to_string(),
self.config().id.clone(),
));
}
Ok(ICSHeight {
revision_number: ChainId::chain_version(status.node_info.network.as_str()),
revision_height: u64::from(status.sync_info.latest_block_height),
})
}
fn query_clients(
&self,
request: QueryClientStatesRequest,
) -> Result<Vec<IdentifiedAnyClientState>, Error> {
crate::time!("query_clients");
let mut client = self
.block_on(
ibc_proto::ibc::core::client::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(Error::grpc_transport)?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.client_states(request))
.map_err(Error::grpc_status)?
.into_inner();
// Deserialize into domain type
let mut clients: Vec<IdentifiedAnyClientState> = response
.client_states
.into_iter()
.filter_map(|cs| IdentifiedAnyClientState::try_from(cs).ok())
.collect();
// Sort by client identifier counter
clients.sort_by(|a, b| {
client_id_suffix(&a.client_id)
.unwrap_or(0) // Fallback to `0` suffix (no sorting) if client id is malformed
.cmp(&client_id_suffix(&b.client_id).unwrap_or(0))
});
Ok(clients)
}
fn query_client_state(
&self,
client_id: &ClientId,
height: ICSHeight,
) -> Result<Self::ClientState, Error> {
crate::time!("query_client_state");
let client_state = self
.query(ClientStatePath(client_id.clone()), height, false)
.and_then(|v| AnyClientState::decode_vec(&v.value).map_err(Error::decode))?;
let client_state = downcast!(client_state.clone() => AnyClientState::Tendermint)
.ok_or_else(|| Error::client_state_type(format!("{:?}", client_state)))?;
Ok(client_state)
}
fn query_upgraded_client_state(
&self,
height: ICSHeight,
) -> Result<(Self::ClientState, MerkleProof), Error> {
crate::time!("query_upgraded_client_state");
// Query for the value and the proof.
let tm_height = Height::try_from(height.revision_height).map_err(Error::invalid_height)?;
let (upgraded_client_state_raw, proof) = self.query_client_upgrade_state(
ClientUpgradePath::UpgradedClientState(height.revision_height),
tm_height,
)?;
let client_state = AnyClientState::decode_vec(&upgraded_client_state_raw)
.map_err(Error::conversion_from_any)?;
let client_type = client_state.client_type();
let tm_client_state = downcast!(client_state => AnyClientState::Tendermint)
.ok_or_else(|| Error::client_type_mismatch(ClientType::Tendermint, client_type))?;
Ok((tm_client_state, proof))
}
fn query_upgraded_consensus_state(
&self,
height: ICSHeight,
) -> Result<(Self::ConsensusState, MerkleProof), Error> {
crate::time!("query_upgraded_consensus_state");
let tm_height = Height::try_from(height.revision_height).map_err(Error::invalid_height)?;
// Fetch the consensus state and its proof.
let (upgraded_consensus_state_raw, proof) = self.query_client_upgrade_state(
ClientUpgradePath::UpgradedClientConsensusState(height.revision_height),
tm_height,
)?;
let consensus_state = AnyConsensusState::decode_vec(&upgraded_consensus_state_raw)
.map_err(Error::conversion_from_any)?;
let cs_client_type = consensus_state.client_type();
let tm_consensus_state = downcast!(consensus_state => AnyConsensusState::Tendermint)
.ok_or_else(|| {
Error::consensus_state_type_mismatch(ClientType::Tendermint, cs_client_type)
})?;
Ok((tm_consensus_state, proof))
}
/// Performs a query to retrieve the identifiers of all connections.
fn query_consensus_states(
&self,
request: QueryConsensusStatesRequest,
) -> Result<Vec<AnyConsensusStateWithHeight>, Error> {
crate::time!("query_consensus_states");