-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathcosmos.rs
1516 lines (1275 loc) · 50 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 std::{
convert::TryFrom, convert::TryInto, future::Future, str::FromStr, sync::Arc, thread,
time::Duration,
};
use anomaly::fail;
use bech32::{ToBase32, Variant};
use bitcoin::hashes::hex::ToHex;
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::query::Query;
use tendermint_rpc::{endpoint::broadcast::tx_commit::Response, Client, HttpClient, Order};
use tokio::runtime::Runtime as TokioRuntime;
use tonic::codegen::http::Uri;
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::events as ClientEvents;
use ibc::ics03_connection::connection::{ConnectionEnd, State as ConnectionState};
use ibc::ics04_channel::channel::{
ChannelEnd, IdentifiedChannelEnd, QueryPacketEventDataRequest, State as ChannelState,
};
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::QueryTxRequest;
use ibc::signer::Signer;
use ibc::Height as ICSHeight;
// Support for GRPC
use ibc_proto::cosmos::auth::v1beta1::{BaseAccount, QueryAccountRequest};
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, TxBody, TxRaw};
use ibc_proto::cosmos::upgrade::v1beta1::{
QueryCurrentPlanRequest, QueryUpgradedConsensusStateRequest,
};
use ibc_proto::ibc::core::channel::v1::{
PacketState, 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::chain::QueryResponse;
use crate::config::ChainConfig;
use crate::error::{Error, Kind};
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 super::Chain;
use tendermint_rpc::endpoint::tx_search::ResultTx;
// TODO size this properly
const DEFAULT_MAX_GAS: u64 = 300000;
const DEFAULT_MAX_MSG_NUM: usize = 30;
const DEFAULT_MAX_TX_SIZE: usize = 2 * 1048576; // 2 MBytes
const DEFAULT_GAS_FEE_AMOUNT: u64 = 1000;
pub struct CosmosSdkChain {
config: ChainConfig,
rpc_client: HttpClient,
grpc_addr: Uri,
rt: Arc<TokioRuntime>,
keybase: KeyRing,
}
impl CosmosSdkChain {
/// 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(|e| Kind::Grpc.context(e))?;
let request =
tonic::Request::new(ibc_proto::cosmos::staking::v1beta1::QueryParamsRequest {});
let response = self
.block_on(client.params(request))
.map_err(|e| Kind::Grpc.context(e))?;
let res = response
.into_inner()
.params
.ok_or_else(|| Kind::Grpc.context("none staking params".to_string()))?
.unbonding_time
.ok_or_else(|| Kind::Grpc.context("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| Kind::Rpc(self.config.rpc_addr.clone()).context(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(&self, proto_msgs: Vec<Any>) -> Result<Vec<IbcEvent>, Error> {
crate::time!("send_tx");
let key = self
.keybase()
.get_key()
.map_err(|e| Kind::KeyBase.context(e))?;
// Create TxBody
let body = TxBody {
messages: proto_msgs.to_vec(),
memo: "".to_string(),
timeout_height: 0_u64,
extension_options: Vec::<Any>::new(),
non_critical_extension_options: Vec::<Any>::new(),
};
// A protobuf serialization of a TxBody
let mut body_buf = Vec::new();
prost::Message::encode(&body, &mut body_buf).unwrap();
let mut pk_buf = Vec::new();
prost::Message::encode(&key.public_key.public_key.to_bytes(), &mut pk_buf).unwrap();
crate::time!("PK {:?}", hex::encode(key.public_key.public_key.to_bytes()));
// Create a MsgSend proto Any message
let pk_any = Any {
type_url: "/cosmos.crypto.secp256k1.PubKey".to_string(),
value: pk_buf,
};
let acct_response = self
.block_on(query_account(self, key.account))
.map_err(|e| Kind::Grpc.context(e))?;
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: acct_response.sequence,
};
let fee = Some(Fee {
amount: vec![self.fee()],
gas_limit: self.gas(),
payer: "".to_string(),
granter: "".to_string(),
});
let auth_info = AuthInfo {
signer_infos: vec![signer_info],
fee,
};
// A protobuf serialization of a AuthInfo
let mut auth_buf = Vec::new();
prost::Message::encode(&auth_info, &mut auth_buf).unwrap();
let sign_doc = SignDoc {
body_bytes: body_buf.clone(),
auth_info_bytes: auth_buf.clone(),
chain_id: self.config.clone().id.to_string(),
account_number: acct_response.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 and broadcast
let signed = self
.keybase
.sign_msg(signdoc_buf)
.map_err(|e| Kind::KeyBase.context(e))?;
let tx_raw = TxRaw {
body_bytes: body_buf,
auth_info_bytes: auth_buf,
signatures: vec![signed],
};
let mut txraw_buf = Vec::new();
prost::Message::encode(&tx_raw, &mut txraw_buf).unwrap();
crate::time!("TxRAW {:?}", hex::encode(txraw_buf.clone()));
let response = self
.block_on(broadcast_tx_commit(self, txraw_buf))
.map_err(|e| Kind::Rpc(self.config.rpc_addr.clone()).context(e))?;
let res = tx_result_to_event(&self.config.id, response)?;
Ok(res)
}
fn gas(&self) -> u64 {
self.config.gas.unwrap_or(DEFAULT_MAX_GAS)
}
fn fee(&self) -> Coin {
let amount = self
.config
.clone()
.fee_amount
.unwrap_or(DEFAULT_GAS_FEE_AMOUNT);
Coin {
denom: self.config.fee_denom.clone(),
amount: amount.to_string(),
}
}
fn max_msg_num(&self) -> usize {
self.config.max_msg_num.unwrap_or(DEFAULT_MAX_MSG_NUM)
}
fn max_tx_size(&self) -> usize {
self.config.max_tx_size.unwrap_or(DEFAULT_MAX_TX_SIZE)
}
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(|e| Kind::InvalidHeight.context(e))?;
if !data.is_provable() & prove {
return Err(Kind::Store
.context("requested proof for a path in the privateStore")
.into());
}
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 to fetch a proof.
fn query_client_upgrade_proof(
&self,
data: ClientUpgradePath,
height: Height,
) -> Result<(MerkleProof, ICSHeight), Error> {
let prev_height =
Height::try_from(height.value() - 1).map_err(|e| Kind::InvalidHeight.context(e))?;
let path = TendermintABCIPath::from_str(SDK_UPGRADE_QUERY_PATH).unwrap();
let response = self.block_on(abci_query(
&self,
path,
Path::Upgrade(data).to_string(),
prev_height,
true,
))?;
let proof = response.proof.ok_or(Kind::EmptyResponseProof)?;
let height = ICSHeight::new(
self.config.id.version(),
response.height.increment().value(),
);
Ok((proof, height))
}
}
impl Chain for CosmosSdkChain {
type LightBlock = TMLightBlock;
type Header = TmHeader;
type ConsensusState = TMConsensusState;
type ClientState = ClientState;
fn bootstrap(config: ChainConfig, rt: Arc<TokioRuntime>) -> Result<Self, Error> {
let rpc_client = HttpClient::new(config.rpc_addr.clone())
.map_err(|e| Kind::Rpc(config.rpc_addr.clone()).context(e))?;
// Initialize key store and load key
let keybase =
KeyRing::new(Store::Test, config.clone()).map_err(|e| Kind::KeyBase.context(e))?;
let grpc_addr =
Uri::from_str(&config.grpc_addr.to_string()).map_err(|e| Kind::Grpc.context(e))?;
Ok(Self {
config,
rpc_client,
grpc_addr,
rt,
keybase,
})
}
fn init_light_client(&self) -> Result<Box<dyn LightClient<Self>>, 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| Kind::Rpc(self.config.rpc_addr.clone()).context(e))?;
let light_client = TmLightClient::from_config(&self.config, peer_id)?;
Ok(Box::new(light_client))
}
fn init_event_monitor(
&self,
rt: Arc<TokioRuntime>,
) -> Result<(EventReceiver, Option<thread::JoinHandle<()>>), Error> {
crate::time!("init_event_monitor");
let (mut event_monitor, event_receiver) = EventMonitor::new(
self.config.id.clone(),
self.config.websocket_addr.clone(),
rt,
)
.map_err(Kind::EventMonitor)?;
event_monitor.subscribe().map_err(Kind::EventMonitor)?;
let monitor_thread = thread::spawn(move || event_monitor.run());
Ok((event_receiver, Some(monitor_thread)))
}
fn id(&self) -> &ChainId {
&self.config().id
}
fn keybase(&self) -> &KeyRing {
&self.keybase
}
fn keybase_mut(&mut self) -> &mut KeyRing {
&mut self.keybase
}
/// Send one or more transactions that include all the specified messages
fn send_msgs(&mut self, proto_msgs: Vec<Any>) -> Result<Vec<IbcEvent>, Error> {
crate::time!("send_msgs");
if proto_msgs.is_empty() {
return Ok(vec![IbcEvent::Empty("No messages to send".to_string())]);
}
let mut res = vec![];
let mut n = 0;
let mut size = 0;
let mut msg_batch = vec![];
for msg in proto_msgs.iter() {
msg_batch.append(&mut vec![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 mut result = self.send_tx(msg_batch)?;
res.append(&mut result);
n = 0;
size = 0;
msg_batch = vec![];
}
}
if !msg_batch.is_empty() {
let mut result = self.send_tx(msg_batch)?;
res.append(&mut result);
}
Ok(res)
}
/// 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()
.map_err(|e| Kind::KeyBase.context(e))?;
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()
.map_err(|e| Kind::KeyBase.context(e))?;
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| Kind::Rpc(self.config.rpc_addr.clone()).context(e))?;
if status.sync_info.catching_up {
fail!(
Kind::LightClient(self.config.rpc_addr.to_string()),
"node at {} running chain {} not caught up",
self.config().rpc_addr,
self.config().id,
);
}
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_chain_clients");
let mut client = self
.block_on(
ibc_proto::ibc::core::client::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.client_states(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
let clients = response
.client_states
.into_iter()
.filter_map(|cs| IdentifiedAnyClientState::try_from(cs).ok())
.collect();
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)
.map_err(|e| Kind::Query("client state".into()).context(e))
.and_then(|v| {
AnyClientState::decode_vec(&v.value)
.map_err(|e| Kind::Query("client state".into()).context(e))
})?;
let client_state =
downcast!(client_state => AnyClientState::Tendermint).ok_or_else(|| {
Kind::Query("client state".into()).context("unexpected client state type")
})?;
Ok(client_state)
}
fn query_upgraded_client_state(
&self,
height: ICSHeight,
) -> Result<(Self::ClientState, MerkleProof), Error> {
crate::time!("query_upgraded_client_state");
let mut client = self
.block_on(
ibc_proto::cosmos::upgrade::v1beta1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let req = tonic::Request::new(QueryCurrentPlanRequest {});
let response = self
.block_on(client.current_plan(req))
.map_err(|e| Kind::Grpc.context(e))?;
let upgraded_client_state_raw = response
.into_inner()
.plan
.ok_or(Kind::EmptyResponseValue)?
.upgraded_client_state
.ok_or(Kind::EmptyUpgradedClientState)?;
let client_state = AnyClientState::try_from(upgraded_client_state_raw)
.map_err(|e| Kind::Grpc.context(e))?;
// TODO: Better error kinds here.
let tm_client_state =
downcast!(client_state => AnyClientState::Tendermint).ok_or_else(|| {
Kind::Query("upgraded client state".into()).context("unexpected client state type")
})?;
// Query for the proof.
let tm_height =
Height::try_from(height.revision_height).map_err(|e| Kind::InvalidHeight.context(e))?;
let (proof, _proof_height) = self.query_client_upgrade_proof(
ClientUpgradePath::UpgradedClientState(height.revision_height),
tm_height,
)?;
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(|e| Kind::InvalidHeight.context(e))?;
let mut client = self
.block_on(
ibc_proto::cosmos::upgrade::v1beta1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let req = tonic::Request::new(QueryUpgradedConsensusStateRequest {
last_height: tm_height.into(),
});
let response = self
.block_on(client.upgraded_consensus_state(req))
.map_err(|e| Kind::Grpc.context(e))?;
let upgraded_consensus_state_raw = response
.into_inner()
.upgraded_consensus_state
.ok_or(Kind::EmptyResponseValue)?;
// TODO: More explicit error kinds (should not reuse Grpc all over the place)
let consensus_state = AnyConsensusState::try_from(upgraded_consensus_state_raw)
.map_err(|e| Kind::Grpc.context(e))?;
let tm_consensus_state = downcast!(consensus_state => AnyConsensusState::Tendermint)
.ok_or_else(|| {
Kind::Query("upgraded consensus state".into())
.context("unexpected consensus state type")
})?;
// Fetch the proof.
let (proof, _proof_height) = self.query_client_upgrade_proof(
ClientUpgradePath::UpgradedClientConsensusState(height.revision_height),
tm_height,
)?;
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_chain_clients");
let mut client = self
.block_on(
ibc_proto::ibc::core::client::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.consensus_states(request))
.map_err(|e| Kind::Grpc.context(e))?
.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_chain_clients");
let consensus_state = self
.proven_client_consensus(&client_id, consensus_height, query_height)?
.0;
Ok(AnyConsensusState::Tendermint(consensus_state))
}
fn query_client_connections(
&self,
request: QueryClientConnectionsRequest,
) -> Result<Vec<ConnectionId>, Error> {
crate::time!("query_connections");
let mut client = self
.block_on(
ibc_proto::ibc::core::connection::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.client_connections(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
// 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<ConnectionId>, Error> {
crate::time!("query_connections");
let mut client = self
.block_on(
ibc_proto::ibc::core::connection::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.connections(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
// TODO: add warnings for any identifiers that fail to parse (below).
// similar to the parsing in `query_connection_channels`.
let ids = response
.connections
.iter()
.filter_map(|ic| ConnectionId::from_str(ic.id.as_str()).ok())
.collect();
Ok(ids)
}
fn query_connection(
&self,
connection_id: &ConnectionId,
height: ICSHeight,
) -> Result<ConnectionEnd, Error> {
let res = self.query(Path::Connections(connection_id.clone()), height, false)?;
let connection_end = ConnectionEnd::decode_vec(&res.value)
.map_err(|e| Kind::Query(format!("connection '{}'", connection_id)).context(e))?;
match connection_end.state() {
ConnectionState::Uninitialized => {
Err(Kind::Query(format!("connection '{}'", connection_id))
.context("connection does not exist")
.into())
}
_ => Ok(connection_end),
}
}
fn query_connection_channels(
&self,
request: QueryConnectionChannelsRequest,
) -> Result<Vec<ChannelId>, Error> {
crate::time!("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(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.connection_channels(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
// TODO: add warnings for any identifiers that fail to parse (below).
// https://github.com/informalsystems/ibc-rs/pull/506#discussion_r555945560
let vec_ids = response
.channels
.iter()
.filter_map(|ic| ChannelId::from_str(ic.channel_id.as_str()).ok())
.collect();
Ok(vec_ids)
}
fn query_channels(
&self,
request: QueryChannelsRequest,
) -> Result<Vec<IdentifiedChannelEnd>, Error> {
crate::time!("query_connections");
let mut client = self
.block_on(
ibc_proto::ibc::core::channel::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.channels(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
let channels = response
.channels
.into_iter()
.filter_map(|ch| IdentifiedChannelEnd::try_from(ch).ok())
.collect();
Ok(channels)
}
fn query_channel(
&self,
port_id: &PortId,
channel_id: &ChannelId,
height: ICSHeight,
) -> Result<ChannelEnd, Error> {
let res = self.query(
Path::ChannelEnds(port_id.clone(), channel_id.clone()),
height,
false,
)?;
let channel_end = ChannelEnd::decode_vec(&res.value).map_err(|e| {
Kind::Query(format!("port '{}' & channel '{}'", port_id, channel_id)).context(e)
})?;
match channel_end.state() {
ChannelState::Uninitialized => Err(Kind::Query(format!(
"port '{}' & channel '{}'",
port_id, channel_id
))
.context("channel does not exist")
.into()),
_ => Ok(channel_end),
}
}
/// Queries the packet commitment hashes associated with a channel.
fn query_packet_commitments(
&self,
request: QueryPacketCommitmentsRequest,
) -> Result<(Vec<PacketState>, ICSHeight), Error> {
crate::time!("query_packet_commitments");
let mut client = self
.block_on(
ibc_proto::ibc::core::channel::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.packet_commitments(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
let pc = response.commitments;
let height = response
.height
.ok_or_else(|| Kind::Grpc.context("missing height in response"))?
.try_into()
.map_err(|_| Kind::Grpc.context("invalid height in response"))?;
Ok((pc, height))
}
/// Queries the unreceived packet sequences associated with a channel.
fn query_unreceived_packets(
&self,
request: QueryUnreceivedPacketsRequest,
) -> Result<Vec<u64>, Error> {
crate::time!("query_unreceived_packets");
let mut client = self
.block_on(
ibc_proto::ibc::core::channel::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let mut response = self
.block_on(client.unreceived_packets(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
response.sequences.sort_unstable();
Ok(response.sequences)
}
/// Queries the packet acknowledgment hashes associated with a channel.
fn query_packet_acknowledgements(
&self,
request: QueryPacketAcknowledgementsRequest,
) -> Result<(Vec<PacketState>, ICSHeight), Error> {
crate::time!("query_packet_acknowledgements");
let mut client = self
.block_on(
ibc_proto::ibc::core::channel::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.packet_acknowledgements(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
let pc = response.acknowledgements;
let height = response
.height
.ok_or_else(|| Kind::Grpc.context("missing height in response"))?
.try_into()
.map_err(|_| Kind::Grpc.context("invalid height in response"))?;
Ok((pc, height))
}
/// Queries the unreceived acknowledgements sequences associated with a channel.
fn query_unreceived_acknowledgements(
&self,
request: QueryUnreceivedAcksRequest,
) -> Result<Vec<u64>, Error> {
crate::time!("query_unreceived_acknowledgements");
let mut client = self
.block_on(
ibc_proto::ibc::core::channel::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let mut response = self
.block_on(client.unreceived_acks(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
response.sequences.sort_unstable();
Ok(response.sequences)
}
fn query_next_sequence_receive(
&self,
request: QueryNextSequenceReceiveRequest,
) -> Result<Sequence, Error> {
crate::time!("query_next_sequence_receive");
let mut client = self
.block_on(
ibc_proto::ibc::core::channel::v1::query_client::QueryClient::connect(
self.grpc_addr.clone(),
),
)
.map_err(|e| Kind::Grpc.context(e))?;
let request = tonic::Request::new(request);
let response = self
.block_on(client.next_sequence_receive(request))
.map_err(|e| Kind::Grpc.context(e))?
.into_inner();
Ok(Sequence::from(response.next_sequence_receive))
}
/// This function queries transactions for events matching certain criteria.
/// 1. Client Update request - returns a vector with at most one update client event
/// 2. Packet event request - returns at most one packet event for each sequence specified
/// in the request.
/// Note - there is no way to format the packet query such that it asks for Tx-es with either
/// sequence (the query conditions can only be AND-ed).
/// There is a possibility to include "<=" and ">=" conditions but it doesn't work with
/// string attributes (sequence is emmitted as a string).
/// Therefore, for packets we perform one tx_search for each sequence.
/// Alternatively, a single query for all packets could be performed but it would return all
/// packets ever sent.