-
Notifications
You must be signed in to change notification settings - Fork 332
/
cosmos.rs
2704 lines (2336 loc) · 93.9 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::{future::Future, str::FromStr, time::Duration};
use std::{cmp::Ordering, thread};
use bytes::{Buf, Bytes};
use futures::future::join_all;
use num_bigint::BigInt;
use tokio::runtime::Runtime as TokioRuntime;
use tonic::codegen::http::Uri;
use tonic::metadata::AsciiMetadataValue;
use tracing::{debug, error, info, instrument, trace, warn};
use ibc_proto::cosmos::base::node::v1beta1::ConfigResponse;
use ibc_proto::cosmos::base::tendermint::v1beta1::service_client::ServiceClient;
use ibc_proto::cosmos::base::tendermint::v1beta1::{GetSyncingRequest, GetSyncingResponse};
use ibc_proto::cosmos::staking::v1beta1::Params as StakingParams;
use ibc_proto::ibc::apps::fee::v1::{
QueryIncentivizedPacketRequest, QueryIncentivizedPacketResponse,
};
use ibc_proto::ibc::core::channel::v1::{QueryUpgradeErrorRequest, QueryUpgradeRequest};
use ibc_proto::interchain_security::ccv::v1::ConsumerParams as CcvConsumerParams;
use ibc_proto::Protobuf;
use ibc_relayer_types::applications::ics31_icq::response::CrossChainQueryResponse;
use ibc_relayer_types::clients::ics07_tendermint::client_state::{
AllowUpdate, ClientState as TmClientState,
};
use ibc_relayer_types::clients::ics07_tendermint::consensus_state::ConsensusState as TmConsensusState;
use ibc_relayer_types::clients::ics07_tendermint::header::Header as TmHeader;
use ibc_relayer_types::core::ics02_client::client_type::ClientType;
use ibc_relayer_types::core::ics02_client::error::Error as ClientError;
use ibc_relayer_types::core::ics02_client::events::UpdateClient;
use ibc_relayer_types::core::ics03_connection::connection::{
ConnectionEnd, IdentifiedConnectionEnd,
};
use ibc_relayer_types::core::ics04_channel::channel::{ChannelEnd, IdentifiedChannelEnd};
use ibc_relayer_types::core::ics04_channel::channel::{State, UpgradeState};
use ibc_relayer_types::core::ics04_channel::packet::Sequence;
use ibc_relayer_types::core::ics23_commitment::commitment::CommitmentPrefix;
use ibc_relayer_types::core::ics23_commitment::merkle::MerkleProof;
use ibc_relayer_types::core::ics24_host::identifier::{
ChainId, ChannelId, ClientId, ConnectionId, PortId,
};
use ibc_relayer_types::core::ics24_host::path::{
AcksPath, ChannelEndsPath, ChannelUpgradeErrorPath, ChannelUpgradePath,
ClientConsensusStatePath, ClientStatePath, CommitmentsPath, ConnectionsPath, ReceiptsPath,
SeqRecvsPath,
};
use ibc_relayer_types::core::ics24_host::{
ClientUpgradePath, Path, IBC_QUERY_PATH, SDK_UPGRADE_QUERY_PATH,
};
use ibc_relayer_types::core::{
ics02_client::height::Height, ics04_channel::upgrade::ErrorReceipt,
ics04_channel::upgrade::Upgrade,
};
use ibc_relayer_types::signer::Signer;
use ibc_relayer_types::Height as ICSHeight;
use tendermint::block::Height as TmHeight;
use tendermint::node::{self, info::TxIndexStatus};
use tendermint::time::Time as TmTime;
use tendermint_light_client::verifier::types::LightBlock as TmLightBlock;
use tendermint_rpc::client::CompatMode;
use tendermint_rpc::endpoint::broadcast::tx_sync::Response;
use tendermint_rpc::endpoint::status;
use tendermint_rpc::{Client, HttpClient, Order};
use crate::account::Balance;
use crate::chain::client::ClientSettings;
use crate::chain::cosmos::batch::{
send_batched_messages_and_wait_check_tx, send_batched_messages_and_wait_commit,
sequential_send_batched_messages_and_wait_commit,
};
use crate::chain::cosmos::encode::key_pair_to_signer;
use crate::chain::cosmos::fee::maybe_register_counterparty_payee;
use crate::chain::cosmos::gas::{calculate_fee, mul_ceil};
use crate::chain::cosmos::query::account::get_or_fetch_account;
use crate::chain::cosmos::query::balance::{query_all_balances, query_balance};
use crate::chain::cosmos::query::consensus_state::query_consensus_state_heights;
use crate::chain::cosmos::query::custom::cross_chain_query_via_rpc;
use crate::chain::cosmos::query::denom_trace::query_denom_trace;
use crate::chain::cosmos::query::fee::query_incentivized_packet;
use crate::chain::cosmos::query::status::query_status;
use crate::chain::cosmos::query::tx::{
filter_matching_event, query_packets_from_block, query_packets_from_txs, query_txs,
};
use crate::chain::cosmos::query::{abci_query, fetch_version_specs, packet_query, QueryResponse};
use crate::chain::cosmos::types::account::Account;
use crate::chain::cosmos::types::config::TxConfig;
use crate::chain::cosmos::types::gas::{
default_gas_from_config, gas_multiplier_from_config, max_gas_from_config,
};
use crate::chain::endpoint::{ChainEndpoint, ChainStatus, HealthCheck};
use crate::chain::handle::Subscription;
use crate::chain::requests::*;
use crate::chain::tracking::TrackedMsgs;
use crate::client_state::{AnyClientState, IdentifiedAnyClientState};
use crate::config::Error as ConfigError;
use crate::config::{parse_gas_prices, ChainConfig, GasPrice};
use crate::consensus_state::AnyConsensusState;
use crate::denom::DenomTrace;
use crate::error::Error;
use crate::event::source::{EventSource, TxEventSourceCmd};
use crate::event::IbcEventWithHeight;
use crate::keyring::{KeyRing, Secp256k1KeyPair, SigningKeyPair};
use crate::light_client::tendermint::LightClient as TmLightClient;
use crate::light_client::{LightClient, Verified};
use crate::misbehaviour::MisbehaviourEvidence;
use crate::util::compat_mode::compat_mode_from_version;
use crate::util::pretty::PrettySlice;
use crate::util::pretty::{
PrettyIdentifiedChannel, PrettyIdentifiedClientState, PrettyIdentifiedConnection,
};
use crate::HERMES_VERSION;
use self::gas::dynamic_gas_price;
use self::types::app_state::GenesisAppState;
use self::types::gas::GasConfig;
use self::version::Specs;
pub mod batch;
pub mod client;
pub mod compatibility;
pub mod config;
pub mod eip_base_fee;
pub mod encode;
pub mod estimate;
pub mod fee;
pub mod gas;
pub mod query;
pub mod retry;
pub mod simulate;
pub mod tx;
pub mod types;
pub mod version;
pub mod wait;
/// Defines an upper limit on how large any transaction can be.
/// This upper limit is defined as a fraction relative to the block's
/// maximum bytes. For example, if the fraction is `0.9`, then
/// `max_tx_size` will not be allowed to exceed 0.9 of the
/// maximum block size of any Cosmos SDK network.
///
/// The default fraction we use is `0.9`; anything larger than that
/// would be risky, as transactions might be rejected; a smaller value
/// might be un-necessarily restrictive on the relayer side.
/// The [default max. block size in Tendermint 0.37 is 21MB](tm-37-max).
/// With a fraction of `0.9`, then Hermes will never permit the configuration
/// of `max_tx_size` to exceed ~18.9MB.
///
/// [tm-37-max]: https://github.com/tendermint/tendermint/blob/v0.37.0-rc1/types/params.go#L79
pub const BLOCK_MAX_BYTES_MAX_FRACTION: f64 = 0.9;
pub struct CosmosSdkChain {
config: config::CosmosSdkConfig,
tx_config: TxConfig,
pub rpc_client: HttpClient,
compat_mode: CompatMode,
grpc_addr: Uri,
light_client: TmLightClient,
rt: Arc<TokioRuntime>,
keybase: KeyRing<Secp256k1KeyPair>,
/// A cached copy of the account information
account: Option<Account>,
tx_monitor_cmd: Option<TxEventSourceCmd>,
}
impl CosmosSdkChain {
/// Get a reference to the configuration for this chain.
pub fn config(&self) -> &config::CosmosSdkConfig {
&self.config
}
/// 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 key(&self) -> Result<Secp256k1KeyPair, Error> {
self.keybase()
.get_key(&self.config.key_name)
.map_err(Error::key_base)
}
/// Fetches the trusting period as a `Duration` from the chain config.
/// If no trusting period exists in the config, the trusting period is calculated
/// as two-thirds of the `unbonding_period`.
fn trusting_period(&self, unbonding_period: Duration) -> Duration {
self.config
.trusting_period
.unwrap_or(2 * unbonding_period / 3)
}
/// Performs validation of the relayer's configuration
/// for a specific chain against the parameters of that chain.
///
/// Currently, validates the following:
/// - the configured `max_tx_size` is appropriate
/// - the trusting period is greater than zero
/// - the trusting period is smaller than the unbonding period
/// - the default gas is smaller than the max gas
///
/// Emits a log warning in case any error is encountered and
/// exits early without doing subsequent validations.
pub fn validate_params(&mut self) -> Result<(), Error> {
let unbonding_period = self.unbonding_period()?;
let trusting_period = self.trusting_period(unbonding_period);
// Check that the trusting period is greater than zero
if trusting_period <= Duration::ZERO {
return Err(Error::config_validation_trusting_period_smaller_than_zero(
self.id().clone(),
trusting_period,
));
}
// Check that the trusting period is smaller than the unbounding period
if trusting_period >= unbonding_period {
return Err(
Error::config_validation_trusting_period_greater_than_unbonding_period(
self.id().clone(),
trusting_period,
unbonding_period,
),
);
}
let max_gas = max_gas_from_config(&self.config);
let default_gas = default_gas_from_config(&self.config);
// If the default gas is strictly greater than the max gas and the tx simulation fails,
// Hermes won't be able to ever submit that tx because the gas amount wanted will be
// greater than the max gas.
if default_gas > max_gas {
return Err(Error::config_validation_default_gas_too_high(
self.id().clone(),
default_gas,
max_gas,
));
}
// Get the latest height
let latest_height = self.query_chain_latest_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, BLOCK_MAX_BYTES_MAX_FRACTION);
let max_tx_size = BigInt::from(self.max_tx_size());
if max_tx_size > max_allowed {
return Err(Error::config_validation_tx_size_out_of_bounds(
self.id().clone(),
self.max_tx_size(),
max_bound,
));
}
// Check that the configured max gas is lower or equal to the consensus params max gas.
let consensus_max_gas = result.consensus_params.block.max_gas;
// If the consensus max gas is < 0, we don't need to perform the check.
if consensus_max_gas >= 0 {
let consensus_max_gas: u64 = consensus_max_gas
.try_into()
.expect("cannot over or underflow because it is positive");
let max_gas = max_gas_from_config(&self.config);
if max_gas > consensus_max_gas {
return Err(Error::config_validation_max_gas_too_high(
self.id().clone(),
max_gas,
result.consensus_params.block.max_gas,
));
}
}
let gas_multiplier = gas_multiplier_from_config(&self.config);
if gas_multiplier < 1.1 {
return Err(Error::config_validation_gas_multiplier_low(
self.id().clone(),
gas_multiplier,
));
}
// Query /genesis RPC endpoint to retrieve the `max_expected_time_per_block` value to use as `max_block_time`.
// If it is not found, keep the configured `max_block_time`.
match self.block_on(self.rpc_client.genesis::<GenesisAppState>()) {
Ok(genesis_reponse) => {
let old_max_block_time = self.config.max_block_time;
let new_max_block_time =
Duration::from_nanos(genesis_reponse.app_state.max_expected_time_per_block());
if old_max_block_time.as_secs() != new_max_block_time.as_secs() {
self.config.max_block_time = new_max_block_time;
info!(
"Updated `max_block_time` using /genesis endpoint. Old value: `{}s`, new value: `{}s`",
old_max_block_time.as_secs(),
self.config.max_block_time.as_secs()
);
}
}
Err(e) => {
warn!(
"Will use fallback value for max_block_time: `{}s`. Error: {e}",
self.config.max_block_time.as_secs()
);
}
}
Ok(())
}
fn init_event_source(&mut self) -> Result<TxEventSourceCmd, Error> {
crate::time!(
"init_event_source",
{
"src_chain": self.config().id.to_string(),
}
);
use crate::config::EventSourceMode as Mode;
let (event_source, monitor_tx) = match &self.config.event_source {
Mode::Push { url, batch_delay } => EventSource::websocket(
self.config.id.clone(),
url.clone(),
self.compat_mode,
*batch_delay,
self.rt.clone(),
),
Mode::Pull {
interval,
max_retries,
} => EventSource::rpc(
self.config.id.clone(),
self.rpc_client.clone(),
*interval,
*max_retries,
self.rt.clone(),
),
}
.map_err(Error::event_source)?;
thread::spawn(move || event_source.run());
Ok(monitor_tx)
}
/// Performs a gRPC query to fetch CCV Consumer chain staking parameters.
pub fn query_ccv_consumer_chain_params(&self) -> Result<CcvConsumerParams, Error> {
crate::time!(
"query_ccv_consumer_chain_params",
{
"src_chain": self.config().id.to_string(),
}
);
crate::telemetry!(query, self.id(), "query_ccv_consumer_chain_params");
let mut client = self
.block_on(
ibc_proto::interchain_security::ccv::consumer::v1::query_client::QueryClient::connect(
self.grpc_addr.clone()
),
)
.map_err(Error::grpc_transport)?;
client = client
.max_decoding_message_size(self.config().max_grpc_decoding_size.get_bytes() as usize);
let request = tonic::Request::new(
ibc_proto::interchain_security::ccv::consumer::v1::QueryParamsRequest {},
);
let response = self
.block_on(client.query_params(request))
.map_err(|e| Error::grpc_status(e, "query_ccv_consumer_chain_params".to_owned()))?;
let params = response
.into_inner()
.params
.ok_or_else(|| Error::grpc_response_param("no staking params".to_string()))?;
Ok(params)
}
/// Performs a gRPC query for Cosmos chain staking parameters.
pub fn query_staking_params(&self) -> Result<StakingParams, Error> {
crate::time!(
"query_staking_params",
{
"src_chain": self.config().id.to_string(),
}
);
crate::telemetry!(query, self.id(), "query_staking_params");
let mut client = self
.block_on(
ibc_proto::cosmos::staking::v1beta1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(Error::grpc_transport)?;
client = client
.max_decoding_message_size(self.config().max_grpc_decoding_size.get_bytes() as usize);
let request =
tonic::Request::new(ibc_proto::cosmos::staking::v1beta1::QueryParamsRequest {});
let response = self
.block_on(client.params(request))
.map_err(|e| Error::grpc_status(e, "query_staking_params".to_owned()))?;
let params = response
.into_inner()
.params
.ok_or_else(|| Error::grpc_response_param("no staking params".to_string()))?;
Ok(params)
}
/// Performs a gRPC query to fetch the configuration parameters of the node.
///
/// ### Note: This query endpoint was introduced in SDK v0.46.3/v0.45.10. Not available before that.
///
/// Returns:
/// - `Ok(Some(..))` if the query was successful.
/// - `Ok(None) in case the query endpoint is not available.
/// - `Err` for any other error.
pub fn query_config_params(&self) -> Result<Option<ConfigResponse>, Error> {
crate::time!(
"query_config_params",
{
"src_chain": self.config().id.to_string(),
}
);
crate::telemetry!(query, self.id(), "query_config_params");
// Helper function to diagnose if the node config query is unimplemented
// by matching on the error details.
fn is_unimplemented_node_query(err_status: &tonic::Status) -> bool {
if err_status.code() != tonic::Code::Unimplemented {
return false;
}
err_status
.message()
.contains("unknown service cosmos.base.node.v1beta1.Service")
}
let mut client = self
.block_on(
ibc_proto::cosmos::base::node::v1beta1::service_client::ServiceClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(Error::grpc_transport)?;
client = client
.max_decoding_message_size(self.config().max_grpc_decoding_size.get_bytes() as usize);
let request = tonic::Request::new(ibc_proto::cosmos::base::node::v1beta1::ConfigRequest {});
match self.block_on(client.config(request)) {
Ok(response) => {
let params = response.into_inner();
Ok(Some(params))
}
Err(e) => {
if is_unimplemented_node_query(&e) {
Ok(None)
} else {
Err(Error::grpc_status(e, "query_config_params".to_owned()))
}
}
}
}
/// The minimum gas price that this node accepts
pub fn min_gas_price(&self) -> Result<Option<Vec<GasPrice>>, Error> {
crate::time!(
"min_gas_price",
{
"src_chain": self.config().id.to_string(),
}
);
let min_gas_price: Option<Vec<GasPrice>> = self
.query_config_params()?
.map(|cfg_response| parse_gas_prices(cfg_response.minimum_gas_price));
Ok(min_gas_price)
}
pub fn dynamic_gas_price(&self) -> GasPrice {
let gas_config = GasConfig::from(self.config());
self.rt.block_on(dynamic_gas_price(
&gas_config,
&self.config.id,
&self.config.rpc_addr,
))
}
/// The unbonding period of this chain
pub fn unbonding_period(&self) -> Result<Duration, Error> {
crate::time!(
"unbonding_period",
{
"src_chain": self.config().id.to_string(),
}
);
let unbonding_time = if self.config.ccv_consumer_chain {
self.query_ccv_consumer_chain_params()?
.unbonding_period
.ok_or_else(|| {
Error::grpc_response_param("no unbonding time in staking params".to_string())
})?
} else {
self.query_staking_params()?.unbonding_time.ok_or_else(|| {
Error::grpc_response_param("no unbonding time in staking params".to_string())
})?
};
Ok(Duration::new(
unbonding_time.seconds as u64,
unbonding_time.nanos as u32,
))
}
/// The number of historical entries kept by this chain
pub fn historical_entries(&self) -> Result<u32, Error> {
crate::time!(
"historical_entries",
{
"src_chain": self.config().id.to_string(),
}
);
if self.config.ccv_consumer_chain {
let ccv_parameters = self.query_ccv_consumer_chain_params()?;
ccv_parameters.historical_entries.try_into().map_err(|_| {
Error::invalid_historical_entries(
self.id().clone(),
ccv_parameters.historical_entries,
)
})
} else {
self.query_staking_params().map(|p| p.historical_entries)
}
}
/// Run a future to completion on the Tokio runtime.
fn block_on<F: Future>(&self, f: F) -> F::Output {
self.rt.block_on(f)
}
fn query(
&self,
data: impl Into<Path>,
height_query: QueryHeight,
prove: bool,
) -> Result<QueryResponse, Error> {
crate::time!("query",
{
"src_chain": self.config().id.to_string(),
});
let data = data.into();
if !data.is_provable() & prove {
return Err(Error::private_store());
}
let response = self.block_on(abci_query(
&self.rpc_client,
&self.config.rpc_addr,
IBC_QUERY_PATH.to_string(),
data.to_string(),
height_query.into(),
prove,
))?;
// TODO: Verify response proof, if requested.
Ok(response)
}
/// Perform an ABCI query against the client upgrade sub-store.
///
/// 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`]).
///
/// Note: This is a special query in that it will only succeed if the chain
/// is halted after reaching the height proposed in a successful governance
/// proposal to upgrade the chain. In this scenario, let P be the height at
/// which the chain is planned to upgrade. We assume that the chain is
/// halted at height P. Tendermint will be at height P (as reported by the
/// /status RPC query), but the application will be at height P-1 (as
/// reported by the /abci_info RPC query).
///
/// Therefore, `query_height` needs to be P-1. However, the path specified
/// in `query_data` needs to be constructed with height `P`, as this is how
/// the chain will have stored it in its upgrade sub-store.
fn query_client_upgrade_state(
&self,
query_data: ClientUpgradePath,
query_height: ICSHeight,
) -> Result<(Vec<u8>, MerkleProof), Error> {
let path = SDK_UPGRADE_QUERY_PATH.into();
let response: QueryResponse = self.block_on(abci_query(
&self.rpc_client,
&self.config.rpc_addr,
path,
Path::Upgrade(query_data).to_string(),
query_height.into(),
true,
))?;
let proof = response.proof.ok_or_else(Error::empty_response_proof)?;
Ok((response.value, proof))
}
/// Query the chain status via an RPC query.
///
/// Returns an error if the node is still syncing and has not caught up,
/// ie. if `sync_info.catching_up` is `true`.
fn chain_rpc_status(&self) -> Result<status::Response, Error> {
crate::time!(
"chain_rpc_status",
{
"src_chain": self.config().id.to_string(),
}
);
crate::telemetry!(query, self.id(), "rpc_status");
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 {
Err(Error::chain_not_caught_up(
self.config.rpc_addr.to_string(),
self.config().id.clone(),
))
} else {
Ok(status)
}
}
/// Query the chain syncing status via a gRPC query.
///
/// Returns an error if the node is still syncing and has not caught up,
/// ie. if `sync_info.syncing` is `true`.
fn chain_grpc_status(&self) -> Result<GetSyncingResponse, Error> {
crate::time!(
"chain_grpc_status",
{
"src_chain": self.config().id.to_string(),
}
);
crate::telemetry!(query, self.id(), "grpc_status");
let grpc_addr = self.grpc_addr.clone();
let grpc_addr_string = grpc_addr.to_string();
let mut client = self
.block_on(ServiceClient::connect(grpc_addr.clone()))
.map_err(Error::grpc_transport)?;
let request = tonic::Request::new(GetSyncingRequest {});
let sync_info = self
.block_on(client.get_syncing(request))
.map_err(|e| Error::grpc_status(e, "get_syncing".to_string()))?
.into_inner();
if sync_info.syncing {
Err(Error::chain_not_caught_up(
grpc_addr_string,
self.config().id.clone(),
))
} else {
Ok(sync_info)
}
}
/// Query the chain status of the RPC and gRPC nodes.
///
/// Returns an error if any of the node is still syncing and has not caught up.
fn chain_status(&self) -> Result<status::Response, Error> {
crate::time!(
"chain_status",
{
"src_chain": self.config().id.to_string(),
}
);
crate::telemetry!(query, self.id(), "status");
let rpc_status = self.chain_rpc_status()?;
if rpc_status.sync_info.catching_up {
return Err(Error::chain_not_caught_up(
self.config.rpc_addr.to_string(),
self.config().id.clone(),
));
}
let grpc_status = self.chain_grpc_status()?;
if grpc_status.syncing {
return Err(Error::chain_not_caught_up(
self.config.grpc_addr.to_string(),
self.config().id.clone(),
));
}
Ok(rpc_status)
}
/// Query the chain's latest height
pub fn query_chain_latest_height(&self) -> Result<ICSHeight, Error> {
crate::time!(
"query_latest_height",
{
"src_chain": self.config().id.to_string(),
}
);
crate::telemetry!(query, self.id(), "query_latest_height");
let status = self.rt.block_on(query_status(
self.id(),
&self.rpc_client,
&self.config.rpc_addr,
))?;
Ok(status.height)
}
#[instrument(
name = "send_messages_and_wait_commit",
level = "error",
skip_all,
fields(
chain = %self.id(),
tracking_id = %tracked_msgs.tracking_id()
),
)]
async fn do_send_messages_and_wait_commit(
&mut self,
tracked_msgs: TrackedMsgs,
) -> Result<Vec<IbcEventWithHeight>, Error> {
crate::time!(
"send_messages_and_wait_commit",
{
"src_chain": self.config().id.to_string(),
}
);
let proto_msgs = tracked_msgs.msgs;
let key_pair = self.key()?;
let key_account = key_pair.account();
let account =
get_or_fetch_account(&self.grpc_addr, &key_account, &mut self.account).await?;
if self.config.sequential_batch_tx {
sequential_send_batched_messages_and_wait_commit(
&self.rpc_client,
&self.tx_config,
&key_pair,
account,
&self.config.memo_prefix,
proto_msgs,
)
.await
} else {
send_batched_messages_and_wait_commit(
&self.rpc_client,
&self.tx_config,
&key_pair,
account,
&self.config.memo_prefix,
proto_msgs,
)
.await
}
}
#[instrument(
name = "send_messages_and_wait_check_tx",
level = "error",
skip_all,
fields(
chain = %self.id(),
tracking_id = %tracked_msgs.tracking_id()
),
)]
async fn do_send_messages_and_wait_check_tx(
&mut self,
tracked_msgs: TrackedMsgs,
) -> Result<Vec<Response>, Error> {
crate::time!(
"send_messages_and_wait_check_tx",
{
"src_chain": self.config().id.to_string(),
}
);
let proto_msgs = tracked_msgs.msgs;
let key_pair = self.key()?;
let key_account = key_pair.account();
let account =
get_or_fetch_account(&self.grpc_addr, &key_account, &mut self.account).await?;
send_batched_messages_and_wait_check_tx(
&self.rpc_client,
&self.tx_config,
&key_pair,
account,
&self.config.memo_prefix,
proto_msgs,
)
.await
}
fn query_packet_from_block(
&self,
request: &QueryPacketEventDataRequest,
seqs: &[Sequence],
block_height: &ICSHeight,
) -> Result<(Vec<IbcEventWithHeight>, Vec<IbcEventWithHeight>), Error> {
crate::time!(
"query_block: query block packet events",
{
"src_chain": self.config().id.to_string(),
}
);
crate::telemetry!(query, self.id(), "query_block");
let tm_height =
tendermint::block::Height::try_from(block_height.revision_height()).unwrap();
let response = self
.block_on(self.rpc_client.block_results(tm_height))
.map_err(|e| Error::rpc(self.config.rpc_addr.clone(), e))?;
let response_height = ICSHeight::new(self.id().version(), u64::from(response.height))
.map_err(|_| Error::invalid_height_no_source())?;
let begin_block_events = response
.begin_block_events
.unwrap_or_default()
.iter()
.filter_map(|ev| filter_matching_event(ev, request, seqs))
.map(|ev| IbcEventWithHeight::new(ev, response_height))
.collect();
let mut end_block_events: Vec<_> = response
.end_block_events
.unwrap_or_default()
.iter()
.filter_map(|ev| filter_matching_event(ev, request, seqs))
.map(|ev| IbcEventWithHeight::new(ev, response_height))
.collect();
// Since CometBFT 0.38, block events are returned in the
// finalize_block_events field and the other *_block_events fields
// are no longer present. We put these in place of the end_block_events
// in older protocol.
end_block_events.extend(
response
.finalize_block_events
.iter()
.filter_map(|ev| filter_matching_event(ev, request, seqs))
.map(|ev| IbcEventWithHeight::new(ev, response_height)),
);
Ok((begin_block_events, end_block_events))
}
fn query_packets_from_blocks(
&self,
request: &QueryPacketEventDataRequest,
) -> Result<(Vec<IbcEventWithHeight>, Vec<IbcEventWithHeight>), Error> {
crate::time!(
"query_blocks: query block packet events",
{
"src_chain": self.config().id.to_string(),
}
);
crate::telemetry!(query, self.id(), "query_blocks");
let mut begin_block_events = vec![];
let mut end_block_events = vec![];
for seq in request.sequences.iter().copied() {
let response = self
.block_on(self.rpc_client.block_search(
packet_query(request, seq),
// We only need the first page
1,
// There should only be a single match for this query, but due to
// the fact that the indexer treat the query as a disjunction over
// all events in a block rather than a conjunction over a single event,
// we may end up with partial matches and therefore have to account for
// that by fetching multiple results and filter it down after the fact.
// In the worst case we get N blocks where N is the number of channels,
// but 10 seems to work well enough in practice while keeping the response
// size, and therefore pressure on the node, fairly low.
10,
// We could pick either ordering here, since matching blocks may be at pretty
// much any height relative to the target blocks, so we went with most recent
// blocks first.
Order::Descending,
))
.map_err(|e| Error::rpc(self.config.rpc_addr.clone(), e))?;
for block in response.blocks.into_iter().map(|response| response.block) {
let response_height =
ICSHeight::new(self.id().version(), u64::from(block.header.height))
.map_err(|_| Error::invalid_height_no_source())?;
if let QueryHeight::Specific(query_height) = request.height.get() {
if response_height > query_height {
continue;
}
}
// `query_packet_from_block` retrieves the begin and end block events
// and filter them to retain only those matching the query
let (new_begin_block_events, new_end_block_events) =
self.query_packet_from_block(request, &[seq], &response_height)?;
begin_block_events.extend(new_begin_block_events);
end_block_events.extend(new_end_block_events);
}
}
Ok((begin_block_events, end_block_events))
}
}
impl ChainEndpoint for CosmosSdkChain {
type LightBlock = TmLightBlock;
type Header = TmHeader;
type ConsensusState = TmConsensusState;
type ClientState = TmClientState;
type Time = TmTime;
type SigningKeyPair = Secp256k1KeyPair;
fn id(&self) -> &ChainId {
&self.config.id
}
fn bootstrap(config: ChainConfig, rt: Arc<TokioRuntime>) -> Result<Self, Error> {
#[allow(irrefutable_let_patterns)]
let ChainConfig::CosmosSdk(config) = config
else {
return Err(Error::config(ConfigError::wrong_type()));
};
let mut rpc_client = HttpClient::builder(config.rpc_addr.clone().try_into().unwrap())
.user_agent(format!("hermes/{}", HERMES_VERSION))
.build()
.map_err(|e| Error::rpc(config.rpc_addr.clone(), e))?;
let node_info = rt.block_on(fetch_node_info(&rpc_client, &config))?;
let compat_mode = compat_mode_from_version(&config.compat_mode, node_info.version)?.into();
rpc_client.set_compat_mode(compat_mode);
let light_client = TmLightClient::from_cosmos_sdk_config(&config, node_info.id)?;
// Initialize key store and load key
let keybase = KeyRing::new_secp256k1(
config.key_store_type,
&config.account_prefix,
&config.id,