-
Notifications
You must be signed in to change notification settings - Fork 370
/
Copy pathcosmos.rs
1674 lines (1400 loc) · 57.3 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::{
convert::{TryFrom, TryInto},
future::Future,
str::FromStr,
time::Duration,
};
use num_bigint::BigInt;
use std::thread;
use bitcoin::hashes::hex::ToHex;
use tendermint::block::Height;
use tendermint::{
abci::{Event, Path as TendermintABCIPath},
node::info::TxIndexStatus,
};
use tendermint_light_client_verifier::types::LightBlock as TMLightBlock;
use tendermint_proto::Protobuf;
use tendermint_rpc::{
endpoint::broadcast::tx_sync::Response, endpoint::status, Client, HttpClient, Order,
};
use tokio::runtime::Runtime as TokioRuntime;
use tonic::codegen::http::Uri;
use tracing::{error, span, warn, Level};
use ibc::clients::ics07_tendermint::client_state::{AllowUpdate, ClientState};
use ibc::clients::ics07_tendermint::consensus_state::ConsensusState as TMConsensusState;
use ibc::clients::ics07_tendermint::header::Header as TmHeader;
use ibc::core::ics02_client::client_consensus::{AnyConsensusState, AnyConsensusStateWithHeight};
use ibc::core::ics02_client::client_state::{AnyClientState, IdentifiedAnyClientState};
use ibc::core::ics02_client::client_type::ClientType;
use ibc::core::ics02_client::error::Error as ClientError;
use ibc::core::ics03_connection::connection::{ConnectionEnd, IdentifiedConnectionEnd};
use ibc::core::ics04_channel::channel::{
ChannelEnd, IdentifiedChannelEnd, QueryPacketEventDataRequest,
};
use ibc::core::ics04_channel::events as ChannelEvents;
use ibc::core::ics04_channel::packet::{Packet, PacketMsgType, Sequence};
use ibc::core::ics23_commitment::commitment::CommitmentPrefix;
use ibc::core::ics24_host::identifier::{ChainId, ChannelId, ClientId, ConnectionId, PortId};
use ibc::core::ics24_host::path::{
AcksPath, ChannelEndsPath, ClientConsensusStatePath, ClientStatePath, CommitmentsPath,
ConnectionsPath, ReceiptsPath, SeqRecvsPath,
};
use ibc::core::ics24_host::{ClientUpgradePath, Path, IBC_QUERY_PATH, SDK_UPGRADE_QUERY_PATH};
use ibc::events::IbcEvent;
use ibc::query::QueryBlockRequest;
use ibc::query::QueryTxRequest;
use ibc::signer::Signer;
use ibc::Height as ICSHeight;
use ibc_proto::cosmos::staking::v1beta1::Params as StakingParams;
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::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,
};
use crate::chain::cosmos::encode::encode_to_bech32;
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_balance;
use crate::chain::cosmos::query::status::query_status;
use crate::chain::cosmos::query::tx::query_txs;
use crate::chain::cosmos::query::{abci_query, fetch_version_specs, packet_query};
use crate::chain::cosmos::types::account::Account;
use crate::chain::cosmos::types::config::TxConfig;
use crate::chain::cosmos::types::gas::{default_gas_from_config, max_gas_from_config};
use crate::chain::tx::TrackedMsgs;
use crate::chain::{ChainEndpoint, HealthCheck};
use crate::chain::{ChainStatus, QueryResponse};
use crate::config::ChainConfig;
use crate::error::Error;
use crate::event::monitor::{EventMonitor, EventReceiver, TxMonitorCmd};
use crate::keyring::{KeyEntry, KeyRing};
use crate::light_client::tendermint::LightClient as TmLightClient;
use crate::light_client::{LightClient, Verified};
pub mod batch;
pub mod client;
pub mod compatibility;
pub mod encode;
pub mod estimate;
pub mod gas;
pub mod query;
pub mod retry;
pub mod simulate;
pub mod tx;
pub mod types;
pub mod version;
pub mod wait;
/// fraction of the maximum block size defined in the Tendermint core consensus parameters.
pub const GENESIS_MAX_BYTES_MAX_FRACTION: f64 = 0.9;
// https://github.com/cosmos/cosmos-sdk/blob/v0.44.0/types/errors/errors.go#L115-L117
pub struct CosmosSdkChain {
config: ChainConfig,
tx_config: TxConfig,
rpc_client: HttpClient,
grpc_addr: Uri,
rt: Arc<TokioRuntime>,
keybase: KeyRing,
/// A cached copy of the account information
account: Option<Account>,
}
impl CosmosSdkChain {
/// Get a reference to the configuration for this chain.
pub fn config(&self) -> &ChainConfig {
&self.config
}
/// Performs validation of chain-specific configuration
/// parameters against the chain's genesis configuration.
///
/// 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(&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 and convert to tendermint Height
let latest_height = Height::try_from(self.query_chain_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);
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,
));
}
}
Ok(())
}
/// Query the chain staking parameters
pub fn query_staking_params(&self) -> Result<StakingParams, Error> {
crate::time!("query_staking_params");
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)?;
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 params = response
.into_inner()
.params
.ok_or_else(|| Error::grpc_response_param("no staking params".to_string()))?;
Ok(params)
}
/// The unbonding period of this chain
pub fn unbonding_period(&self) -> Result<Duration, Error> {
crate::time!("unbonding_period");
let unbonding_time = 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");
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 {
crate::time!("block_on");
self.rt.block_on(f)
}
/// 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: impl Into<Path>,
height: ICSHeight,
prove: bool,
) -> Result<QueryResponse, Error> {
crate::time!("query");
// SAFETY: Creating a Path from a constant; this should never fail
let path = TendermintABCIPath::from_str(IBC_QUERY_PATH)
.expect("Turning IBC query path constant into a Tendermint ABCI path");
let height = Height::try_from(height.revision_height).map_err(Error::invalid_height)?;
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,
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)?;
// SAFETY: Creating a Path from a constant; this should never fail
let path = TendermintABCIPath::from_str(SDK_UPGRADE_QUERY_PATH)
.expect("Turning SDK upgrade query path constant into a Tendermint ABCI path");
let response: QueryResponse = self.block_on(abci_query(
&self.rpc_client,
&self.config.rpc_addr,
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 key(&self) -> Result<KeyEntry, Error> {
self.keybase()
.get_key(&self.config.key_name)
.map_err(Error::key_base)
}
fn trusting_period(&self, unbonding_period: Duration) -> Duration {
self.config
.trusting_period
.unwrap_or(2 * unbonding_period / 3)
}
/// 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_status(&self) -> Result<status::Response, Error> {
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(status)
}
/// Query the chain's latest height
pub fn query_chain_latest_height(&self) -> Result<ICSHeight, Error> {
crate::time!("query_latest_height");
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)
}
async fn do_send_messages_and_wait_commit(
&mut self,
tracked_msgs: TrackedMsgs,
) -> Result<Vec<IbcEvent>, Error> {
crate::time!("send_messages_and_wait_commit");
let _span =
span!(Level::DEBUG, "send_tx_commit", id = %tracked_msgs.tracking_id()).entered();
let proto_msgs = tracked_msgs.msgs;
let key_entry = self.key()?;
let account =
get_or_fetch_account(&self.grpc_addr, &key_entry.account, &mut self.account).await?;
send_batched_messages_and_wait_commit(
&self.tx_config,
self.config.max_msg_num,
self.config.max_tx_size,
&key_entry,
account,
&self.config.memo_prefix,
proto_msgs,
)
.await
}
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");
let span = span!(Level::DEBUG, "send_tx_check", id = %tracked_msgs.tracking_id());
let _enter = span.enter();
let proto_msgs = tracked_msgs.msgs;
let key_entry = self.key()?;
let account =
get_or_fetch_account(&self.grpc_addr, &key_entry.account, &mut self.account).await?;
send_batched_messages_and_wait_check_tx(
&self.tx_config,
self.config.max_msg_num,
self.config.max_tx_size,
&key_entry,
account,
&self.config.memo_prefix,
proto_msgs,
)
.await
}
}
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(config.key_store_type, &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 tx_config = TxConfig::try_from(&config)?;
// Retrieve the version specification of this chain
let chain = Self {
config,
rpc_client,
grpc_addr,
rt,
keybase,
account: None,
tx_config,
};
Ok(chain)
}
fn init_light_client(&self) -> Result<Self::LightClient, Error> {
use tendermint_light_client_verifier::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) = 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,
tracked_msgs: TrackedMsgs,
) -> Result<Vec<IbcEvent>, Error> {
let runtime = self.rt.clone();
runtime.block_on(self.do_send_messages_and_wait_commit(tracked_msgs))
}
fn send_messages_and_wait_check_tx(
&mut self,
tracked_msgs: TrackedMsgs,
) -> Result<Vec<Response>, Error> {
let runtime = self.rt.clone();
runtime.block_on(self.do_send_messages_and_wait_check_tx(tracked_msgs))
}
/// 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(|e| Error::key_not_found(self.config.key_name.clone(), e))?;
let bech32 = encode_to_bech32(&key.address.to_hex(), &self.config.account_prefix)?;
Ok(Signer::new(bech32))
}
/// Get the chain configuration
fn config(&self) -> ChainConfig {
self.config.clone()
}
/// 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(|e| Error::key_not_found(self.config.key_name.clone(), e))?;
Ok(key)
}
fn add_key(&mut self, key_name: &str, key: KeyEntry) -> Result<(), Error> {
self.keybase_mut()
.add_key(key_name, key)
.map_err(Error::key_base)?;
Ok(())
}
fn ibc_version(&self) -> Result<Option<semver::Version>, Error> {
let version_specs = self.block_on(fetch_version_specs(self.id(), &self.grpc_addr))?;
Ok(version_specs.ibc_go_version)
}
fn query_balance(&self) -> Result<Balance, Error> {
let key = self.key()?;
let balance = self.block_on(query_balance(
&self.grpc_addr,
&key.account,
&self.config.gas_price.denom,
))?;
Ok(balance)
}
fn query_commitment_prefix(&self) -> Result<CommitmentPrefix, Error> {
crate::time!("query_commitment_prefix");
crate::telemetry!(query, self.id(), "query_commitment_prefix");
// TODO - do a real chain query
CommitmentPrefix::try_from(self.config().store_prefix.as_bytes().to_vec())
.map_err(|_| Error::ics02(ClientError::empty_prefix()))
}
/// Query the application status
fn query_application_status(&self) -> Result<ChainStatus, Error> {
crate::time!("query_application_status");
crate::telemetry!(query, self.id(), "query_application_status");
// We cannot rely on `/status` endpoint to provide details about the latest block.
// Instead, we need to pull block height via `/abci_info` and then fetch block
// metadata at the given height via `/blockchain` endpoint.
let abci_info = self
.block_on(self.rpc_client.abci_info())
.map_err(|e| Error::rpc(self.config.rpc_addr.clone(), e))?;
// Query `/blockchain` endpoint to pull the block metadata corresponding to
// the latest block that the application committed.
// TODO: Replace this query with `/header`, once it's available.
// https://github.com/informalsystems/tendermint-rs/pull/1101
let blocks = self
.block_on(
self.rpc_client
.blockchain(abci_info.last_block_height, abci_info.last_block_height),
)
.map_err(|e| Error::rpc(self.config.rpc_addr.clone(), e))?
.block_metas;
return if let Some(latest_app_block) = blocks.first() {
let height = ICSHeight {
revision_number: ChainId::chain_version(latest_app_block.header.chain_id.as_str()),
revision_height: u64::from(abci_info.last_block_height),
};
let timestamp = latest_app_block.header.time.into();
Ok(ChainStatus { height, timestamp })
} else {
// The `/blockchain` query failed to return the header we wanted
Err(Error::query(
"/blockchain endpoint for latest app. block".to_owned(),
))
};
}
fn query_clients(
&self,
request: QueryClientStatesRequest,
) -> Result<Vec<IdentifiedAnyClientState>, Error> {
crate::time!("query_clients");
crate::telemetry!(query, self.id(), "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_cached_key(|c| client_id_suffix(&c.client_id).unwrap_or(0));
Ok(clients)
}
fn query_client_state(
&self,
client_id: &ClientId,
height: ICSHeight,
) -> Result<AnyClientState, Error> {
crate::time!("query_client_state");
crate::telemetry!(query, self.id(), "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))?;
Ok(client_state)
}
fn query_upgraded_client_state(
&self,
height: ICSHeight,
) -> Result<(AnyClientState, MerkleProof), Error> {
crate::time!("query_upgraded_client_state");
crate::telemetry!(query, self.id(), "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)?;
Ok((client_state, proof))
}
fn query_upgraded_consensus_state(
&self,
height: ICSHeight,
) -> Result<(AnyConsensusState, MerkleProof), Error> {
crate::time!("query_upgraded_consensus_state");
crate::telemetry!(query, self.id(), "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)?;
Ok((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");
crate::telemetry!(query, self.id(), "query_consensus_states");
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.consensus_states(request))
.map_err(Error::grpc_status)?
.into_inner();
let mut consensus_states: Vec<AnyConsensusStateWithHeight> = response
.consensus_states
.into_iter()
.filter_map(|cs| TryFrom::try_from(cs).ok())
.collect();
consensus_states.sort_by(|a, b| a.height.cmp(&b.height));
consensus_states.reverse();
Ok(consensus_states)
}
fn query_consensus_state(
&self,
client_id: ClientId,
consensus_height: ICSHeight,
query_height: ICSHeight,
) -> Result<AnyConsensusState, Error> {
crate::time!("query_consensus_state");
crate::telemetry!(query, self.id(), "query_consensus_state");
let (consensus_state, _proof) =
self.proven_client_consensus(&client_id, consensus_height, query_height)?;
Ok(consensus_state)
}
fn query_client_connections(
&self,
request: QueryClientConnectionsRequest,
) -> Result<Vec<ConnectionId>, Error> {
crate::time!("query_client_connections");
crate::telemetry!(query, self.id(), "query_client_connections");
let mut client = self
.block_on(
ibc_proto::ibc::core::connection::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(Error::grpc_transport)?;
let request = tonic::Request::new(request);
let response = match self.block_on(client.client_connections(request)) {
Ok(res) => res.into_inner(),
Err(e) if e.code() == tonic::Code::NotFound => return Ok(vec![]),
Err(e) => return Err(Error::grpc_status(e)),
};
// TODO: add warnings for any identifiers that fail to parse (below).
// similar to the parsing in `query_connection_channels`.
let ids = response
.connection_paths
.iter()
.filter_map(|id| ConnectionId::from_str(id).ok())
.collect();
Ok(ids)
}
fn query_connections(
&self,
request: QueryConnectionsRequest,
) -> Result<Vec<IdentifiedConnectionEnd>, Error> {
crate::time!("query_connections");
crate::telemetry!(query, self.id(), "query_connections");
let mut client = self
.block_on(
ibc_proto::ibc::core::connection::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.connections(request))
.map_err(Error::grpc_status)?
.into_inner();
// TODO: add warnings for any identifiers that fail to parse (below).
// similar to the parsing in `query_connection_channels`.
let connections = response
.connections
.into_iter()
.filter_map(|co| IdentifiedConnectionEnd::try_from(co).ok())
.collect();
Ok(connections)
}
fn query_connection(
&self,
connection_id: &ConnectionId,
height: ICSHeight,
) -> Result<ConnectionEnd, Error> {
crate::time!("query_connection");
crate::telemetry!(query, self.id(), "query_connection");
async fn do_query_connection(
chain: &CosmosSdkChain,
connection_id: &ConnectionId,
height: ICSHeight,
) -> Result<ConnectionEnd, Error> {
use ibc_proto::ibc::core::connection::v1 as connection;
use tonic::IntoRequest;
let mut client =
connection::query_client::QueryClient::connect(chain.grpc_addr.clone())
.await
.map_err(Error::grpc_transport)?;
let mut request = connection::QueryConnectionRequest {
connection_id: connection_id.to_string(),
}
.into_request();
let height_param =
str::parse(&height.revision_height.to_string()).map_err(Error::invalid_metadata)?;
request
.metadata_mut()
.insert("x-cosmos-block-height", height_param);
let response = client.connection(request).await.map_err(|e| {
if e.code() == tonic::Code::NotFound {
Error::connection_not_found(connection_id.clone())
} else {
Error::grpc_status(e)
}
})?;
match response.into_inner().connection {
Some(raw_connection) => {
let connection_end = raw_connection.try_into().map_err(Error::ics03)?;
Ok(connection_end)
}
None => {
// When no connection is found, the GRPC call itself should return
// the NotFound error code. Nevertheless even if the call is successful,
// the connection field may not be present, because in protobuf3
// everything is optional.
Err(Error::connection_not_found(connection_id.clone()))
}
}
}
self.block_on(async { do_query_connection(self, connection_id, height).await })
}
fn query_connection_channels(
&self,
request: QueryConnectionChannelsRequest,
) -> Result<Vec<IdentifiedChannelEnd>, Error> {
crate::time!("query_connection_channels");
crate::telemetry!(query, self.id(), "query_connection_channels");
let mut client = self
.block_on(
ibc_proto::ibc::core::channel::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.connection_channels(request))
.map_err(Error::grpc_status)?
.into_inner();
// TODO: add warnings for any identifiers that fail to parse (below).
// https://github.com/informalsystems/ibc-rs/pull/506#discussion_r555945560
let channels = response
.channels
.into_iter()
.filter_map(|ch| IdentifiedChannelEnd::try_from(ch).ok())
.collect();
Ok(channels)
}
fn query_channels(
&self,
request: QueryChannelsRequest,