penumbra_ibc/component/rpc/
consensus_query.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
use crate::prefix::MerklePrefixExt;
use crate::IBC_COMMITMENT_PREFIX;
use async_trait::async_trait;
use ibc_proto::ibc::core::channel::v1::query_server::Query as ConsensusQuery;
use ibc_proto::ibc::core::channel::v1::{
    Channel, PacketState, QueryChannelClientStateRequest, QueryChannelClientStateResponse,
    QueryChannelConsensusStateRequest, QueryChannelConsensusStateResponse, QueryChannelRequest,
    QueryChannelResponse, QueryChannelsRequest, QueryChannelsResponse,
    QueryConnectionChannelsRequest, QueryConnectionChannelsResponse,
    QueryNextSequenceReceiveRequest, QueryNextSequenceReceiveResponse,
    QueryNextSequenceSendRequest, QueryNextSequenceSendResponse, QueryPacketAcknowledgementRequest,
    QueryPacketAcknowledgementResponse, QueryPacketAcknowledgementsRequest,
    QueryPacketAcknowledgementsResponse, QueryPacketCommitmentRequest,
    QueryPacketCommitmentResponse, QueryPacketCommitmentsRequest, QueryPacketCommitmentsResponse,
    QueryPacketReceiptRequest, QueryPacketReceiptResponse, QueryUnreceivedAcksRequest,
    QueryUnreceivedAcksResponse, QueryUnreceivedPacketsRequest, QueryUnreceivedPacketsResponse,
};
use ibc_proto::ibc::core::client::v1::{Height, IdentifiedClientState};
use ibc_types::path::{
    AckPath, ChannelEndPath, ClientConsensusStatePath, ClientStatePath, CommitmentPath,
    ReceiptPath, SeqRecvPath, SeqSendPath,
};
use ibc_types::DomainType;

use ibc_types::core::channel::{ChannelId, IdentifiedChannelEnd, PortId};

use ibc_types::core::connection::ConnectionId;
use prost::Message;

use std::str::FromStr;

use crate::component::{ChannelStateReadExt, ConnectionStateReadExt, HostInterface};

use super::utils::determine_snapshot_from_metadata;
use super::IbcQuery;

#[async_trait]
impl<HI: HostInterface + Send + Sync + 'static> ConsensusQuery for IbcQuery<HI> {
    /// Channel queries an IBC Channel.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn channel(
        &self,
        request: tonic::Request<QueryChannelRequest>,
    ) -> std::result::Result<tonic::Response<QueryChannelResponse>, tonic::Status> {
        let snapshot = match determine_snapshot_from_metadata(self.storage.clone(), request.metadata()) {
            Err(err) => return Err(tonic::Status::aborted(
                format!("could not determine the correct snapshot to open given the `\"height\"` header of the request: {err:#}")
            )),
            Ok(snapshot) => snapshot,
        };
        let channel_id = ChannelId::from_str(request.get_ref().channel_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id = PortId::from_str(request.get_ref().port_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let (channel, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(ChannelEndPath::new(&port_id, &channel_id).to_string())
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map(|res| {
                let channel = res
                    .0
                    .map(|chan_bytes| Channel::decode(chan_bytes.as_ref()))
                    .transpose();

                (channel, res.1)
            })
            .map_err(|e| tonic::Status::aborted(format!("couldn't get channel: {e}")))?;

        let channel =
            channel.map_err(|e| tonic::Status::aborted(format!("couldn't decode channel: {e}")))?;

        let res = QueryChannelResponse {
            channel,
            proof: proof.encode_to_vec(),
            proof_height: Some(ibc_proto::ibc::core::client::v1::Height {
                revision_height: HI::get_block_height(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?
                    + 1,
                revision_number: HI::get_revision_number(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            }),
        };

        Ok(tonic::Response::new(res))
    }
    /// Channels queries all the IBC channels of a chain.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn channels(
        &self,
        _request: tonic::Request<QueryChannelsRequest>,
    ) -> std::result::Result<tonic::Response<QueryChannelsResponse>, tonic::Status> {
        let snapshot = self.storage.latest_snapshot();

        let height = Height {
            revision_number: HI::get_revision_number(&snapshot)
                .await
                .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            revision_height: HI::get_block_height(&snapshot)
                .await
                .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
        };

        let channel_counter = snapshot
            .get_channel_counter()
            .await
            .map_err(|e| tonic::Status::aborted(format!("couldn't get channel counter: {e}")))?;

        let mut channels = vec![];
        for chan_idx in 0..channel_counter {
            let chan_id = ChannelId(format!("channel-{}", chan_idx));
            let channel = snapshot
                .get_channel(&chan_id, &PortId::transfer())
                .await
                .map_err(|e| {
                    tonic::Status::aborted(format!("couldn't get channel {chan_id}: {e}"))
                })?
                .ok_or("unable to get channel")
                .map_err(|e| {
                    tonic::Status::aborted(format!("couldn't get channel {chan_id}: {e}"))
                })?;

            let id_chan = IdentifiedChannelEnd {
                channel_id: chan_id,
                port_id: PortId::transfer(),
                channel_end: channel,
            };
            channels.push(id_chan.into());
        }

        let res = QueryChannelsResponse {
            channels,
            pagination: None,
            height: Some(height),
        };

        Ok(tonic::Response::new(res))
    }

    /// ConnectionChannels queries all the channels associated with a connection end.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn connection_channels(
        &self,
        request: tonic::Request<QueryConnectionChannelsRequest>,
    ) -> std::result::Result<tonic::Response<QueryConnectionChannelsResponse>, tonic::Status> {
        let snapshot = self.storage.latest_snapshot();
        let height = Height {
            revision_number: HI::get_revision_number(&snapshot)
                .await
                .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            revision_height: HI::get_block_height(&snapshot)
                .await
                .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
        };

        let request = request.get_ref();
        let connection_id: ConnectionId = ConnectionId::from_str(&request.connection)
            .map_err(|e| tonic::Status::aborted(format!("invalid connection id: {e}")))?;

        // look up all of the channels for this connection
        let channel_counter = snapshot
            .get_channel_counter()
            .await
            .map_err(|e| tonic::Status::aborted(format!("couldn't get channel counter: {e}")))?;

        let mut channels = vec![];
        for chan_idx in 0..channel_counter {
            let chan_id = ChannelId(format!("channel-{}", chan_idx));
            let channel = snapshot
                .get_channel(&chan_id, &PortId::transfer())
                .await
                .map_err(|e| {
                    tonic::Status::aborted(format!("couldn't get channel {chan_id}: {e}"))
                })?
                .ok_or("unable to get channel")
                .map_err(|e| {
                    tonic::Status::aborted(format!("couldn't get channel {chan_id}: {e}"))
                })?;
            if channel.connection_hops.contains(&connection_id) {
                let id_chan = IdentifiedChannelEnd {
                    channel_id: chan_id,
                    port_id: PortId::transfer(),
                    channel_end: channel,
                };
                channels.push(id_chan.into());
            }
        }

        let res = QueryConnectionChannelsResponse {
            channels,
            pagination: None,
            height: Some(height),
        };

        Ok(tonic::Response::new(res))
    }

    /// ChannelClientState queries for the client state for the channel associated
    /// with the provided channel identifiers.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn channel_client_state(
        &self,
        request: tonic::Request<QueryChannelClientStateRequest>,
    ) -> std::result::Result<tonic::Response<QueryChannelClientStateResponse>, tonic::Status> {
        let snapshot = match determine_snapshot_from_metadata(self.storage.clone(), request.metadata()) {
            Err(err) => return Err(tonic::Status::aborted(
                format!("could not determine the correct snapshot to open given the `\"height\"` header of the request: {err:#}")
            )),
            Ok(snapshot) => snapshot,
        };

        // 1. get the channel
        let channel_id = ChannelId::from_str(request.get_ref().channel_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id = PortId::from_str(request.get_ref().port_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let channel = snapshot
            .get_channel(&channel_id, &port_id)
            .await
            .map_err(|e| {
                tonic::Status::aborted(format!(
                    "couldn't get channel {channel_id} for port {port_id}: {e}"
                ))
            })?
            .ok_or("unable to get channel")
            .map_err(|e| {
                tonic::Status::aborted(format!(
                    "couldn't get channel {channel_id} for port {port_id}: {e}"
                ))
            })?;

        // 2. get the connection for the channel
        let connection_id = channel
            .connection_hops
            .first()
            .ok_or("channel has no connection hops")
            .map_err(|e| {
                tonic::Status::aborted(format!(
                    "couldn't get connection for channel {channel_id} for port {port_id}: {e}"
                ))
            })?;

        let connection = snapshot.get_connection(&connection_id).await.map_err(|e| {
            tonic::Status::aborted(format!(
                "couldn't get connection {connection_id} for channel {channel_id} for port {port_id}: {e}"
            ))
        })?.ok_or("unable to get connection").map_err(|e| {
            tonic::Status::aborted(format!(
                "couldn't get connection {connection_id} for channel {channel_id} for port {port_id}: {e}"
            ))
        })?;

        // 3. get the client state for the connection
        let (client_state, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(ClientStatePath::new(&connection.client_id).to_string())
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map_err(|e| tonic::Status::aborted(format!("couldn't get client state: {e}")))?;

        let client_state_any = client_state
            .map(|cs_bytes| ibc_proto::google::protobuf::Any::decode(cs_bytes.as_ref()))
            .transpose()
            .map_err(|e| tonic::Status::aborted(format!("couldn't decode client state: {e}")))?;

        let identified_client_state = IdentifiedClientState {
            client_id: connection.client_id.clone().to_string(),
            client_state: client_state_any,
        };

        Ok(tonic::Response::new(QueryChannelClientStateResponse {
            identified_client_state: Some(identified_client_state),
            proof: proof.encode_to_vec(),
            proof_height: Some(ibc_proto::ibc::core::client::v1::Height {
                revision_height: HI::get_block_height(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?
                    + 1,
                revision_number: HI::get_revision_number(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            }),
        }))
    }
    /// ChannelConsensusState queries for the consensus state for the channel
    /// associated with the provided channel identifiers.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn channel_consensus_state(
        &self,
        request: tonic::Request<QueryChannelConsensusStateRequest>,
    ) -> std::result::Result<tonic::Response<QueryChannelConsensusStateResponse>, tonic::Status>
    {
        let snapshot = match determine_snapshot_from_metadata(self.storage.clone(), request.metadata()) {
            Err(err) => return Err(tonic::Status::aborted(
                format!("could not determine the correct snapshot to open given the `\"height\"` header of the request: {err:#}")
            )),
            Ok(snapshot) => snapshot,
        };
        let consensus_state_height = ibc_types::core::client::Height {
            revision_number: request.get_ref().revision_number,
            revision_height: request.get_ref().revision_height,
        };

        // 1. get the channel
        let channel_id = ChannelId::from_str(request.get_ref().channel_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id = PortId::from_str(request.get_ref().port_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let channel = snapshot
            .get_channel(&channel_id, &port_id)
            .await
            .map_err(|e| {
                tonic::Status::aborted(format!(
                    "couldn't get channel {channel_id} for port {port_id}: {e}"
                ))
            })?
            .ok_or("unable to get channel")
            .map_err(|e| {
                tonic::Status::aborted(format!(
                    "couldn't get channel {channel_id} for port {port_id}: {e}"
                ))
            })?;

        // 2. get the connection for the channel
        let connection_id = channel
            .connection_hops
            .first()
            .ok_or("channel has no connection hops")
            .map_err(|e| {
                tonic::Status::aborted(format!(
                    "couldn't get connection for channel {channel_id} for port {port_id}: {e}"
                ))
            })?;

        let connection = snapshot.get_connection(&connection_id).await.map_err(|e| {
            tonic::Status::aborted(format!(
                "couldn't get connection {connection_id} for channel {channel_id} for port {port_id}: {e}"
            ))
        })?.ok_or("unable to get connection").map_err(|e| {
            tonic::Status::aborted(format!(
                "couldn't get connection {connection_id} for channel {channel_id} for port {port_id}: {e}"
            ))
        })?;

        // 3. get the consensus state for the connection
        let (consensus_state, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(
                        ClientConsensusStatePath::new(
                            &connection.client_id,
                            &consensus_state_height,
                        )
                        .to_string(),
                    )
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map_err(|e| tonic::Status::aborted(format!("couldn't get client state: {e}")))?;

        let consensus_state_any = consensus_state
            .map(|cs_bytes| ibc_proto::google::protobuf::Any::decode(cs_bytes.as_ref()))
            .transpose()
            .map_err(|e| tonic::Status::aborted(format!("couldn't decode client state: {e}")))?;

        Ok(tonic::Response::new(QueryChannelConsensusStateResponse {
            consensus_state: consensus_state_any,
            client_id: connection.client_id.clone().to_string(),
            proof: proof.encode_to_vec(),
            proof_height: Some(ibc_proto::ibc::core::client::v1::Height {
                revision_height: HI::get_block_height(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?
                    + 1,
                revision_number: HI::get_revision_number(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            }),
        }))
    }
    /// PacketCommitment queries a stored packet commitment hash.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn packet_commitment(
        &self,
        request: tonic::Request<QueryPacketCommitmentRequest>,
    ) -> std::result::Result<tonic::Response<QueryPacketCommitmentResponse>, tonic::Status> {
        let snapshot = match determine_snapshot_from_metadata(self.storage.clone(), request.metadata()) {
            Err(err) => return Err(tonic::Status::aborted(
                format!("could not determine the correct snapshot to open given the `\"height\"` header of the request: {err:#}")
            )),
            Ok(snapshot) => snapshot,
        };

        let port_id = PortId::from_str(&request.get_ref().port_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;
        let channel_id = ChannelId::from_str(&request.get_ref().channel_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;

        let (commitment, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(
                        CommitmentPath::new(
                            &port_id,
                            &channel_id,
                            request.get_ref().sequence.into(),
                        )
                        .to_string(),
                    )
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map_err(|e| tonic::Status::aborted(format!("couldn't get packet commitment: {e}")))?;

        let commitment =
            commitment.ok_or_else(|| tonic::Status::aborted("commitment not found"))?;

        Ok(tonic::Response::new(QueryPacketCommitmentResponse {
            commitment,
            proof: proof.encode_to_vec(),
            proof_height: Some(ibc_proto::ibc::core::client::v1::Height {
                revision_height: HI::get_block_height(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?
                    + 1,
                revision_number: HI::get_revision_number(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            }),
        }))
    }
    /// PacketCommitments returns all the packet commitments hashes associated
    /// with a channel.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn packet_commitments(
        &self,
        request: tonic::Request<QueryPacketCommitmentsRequest>,
    ) -> std::result::Result<tonic::Response<QueryPacketCommitmentsResponse>, tonic::Status> {
        let snapshot = self.storage.latest_snapshot();
        let height = snapshot.version();
        let request = request.get_ref();

        let chan_id: ChannelId = ChannelId::from_str(&request.channel_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id: PortId = PortId::from_str(&request.port_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let mut commitment_states = vec![];
        let commitment_counter = snapshot
            .get_send_sequence(&chan_id, &port_id)
            .await
            .map_err(|e| {
                tonic::Status::aborted(format!(
                    "couldn't get send sequence for channel {chan_id} and port {port_id}: {e}"
                ))
            })?;

        // this starts at 1; the first commitment index is 1 (from ibc spec)
        for commitment_idx in 1..commitment_counter {
            let commitment = snapshot
                .get_packet_commitment_by_id(&chan_id, &port_id, commitment_idx)
                .await.map_err(|e| {
                    tonic::Status::aborted(format!(
                        "couldn't get packet commitment for channel {chan_id} and port {port_id} at index {commitment_idx}: {e}"
                    ))
                })?;
            if commitment.is_none() {
                continue;
            }
            let commitment = commitment.expect("commitment existence was checked earlier");

            let commitment_state = PacketState {
                port_id: request.port_id.clone(),
                channel_id: request.channel_id.clone(),
                sequence: commitment_idx,
                data: commitment.clone(),
            };

            commitment_states.push(commitment_state);
        }

        let height = Height {
            revision_number: 0,
            revision_height: height,
        };

        let res = QueryPacketCommitmentsResponse {
            commitments: commitment_states,
            pagination: None,
            height: Some(height),
        };

        Ok(tonic::Response::new(res))
    }
    /// PacketReceipt queries if a given packet sequence has been received on the
    /// queried chain
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn packet_receipt(
        &self,
        request: tonic::Request<QueryPacketReceiptRequest>,
    ) -> std::result::Result<tonic::Response<QueryPacketReceiptResponse>, tonic::Status> {
        let snapshot = match determine_snapshot_from_metadata(self.storage.clone(), request.metadata()) {
            Err(err) => return Err(tonic::Status::aborted(
                format!("could not determine the correct snapshot to open given the `\"height\"` header of the request: {err:#}")
            )),
            Ok(snapshot) => snapshot,
        };

        let port_id = PortId::from_str(&request.get_ref().port_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;
        let channel_id = ChannelId::from_str(&request.get_ref().channel_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;

        let (receipt, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(
                        ReceiptPath::new(&port_id, &channel_id, request.get_ref().sequence.into())
                            .to_string(),
                    )
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map_err(|e| tonic::Status::aborted(format!("couldn't get packet commitment: {e}")))?;

        Ok(tonic::Response::new(QueryPacketReceiptResponse {
            received: receipt.is_some(),
            proof: proof.encode_to_vec(),
            proof_height: Some(ibc_proto::ibc::core::client::v1::Height {
                revision_height: HI::get_block_height(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?
                    + 1,
                revision_number: HI::get_revision_number(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            }),
        }))
    }
    /// PacketAcknowledgement queries a stored packet acknowledgement hash.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn packet_acknowledgement(
        &self,
        request: tonic::Request<QueryPacketAcknowledgementRequest>,
    ) -> std::result::Result<tonic::Response<QueryPacketAcknowledgementResponse>, tonic::Status>
    {
        let snapshot = match determine_snapshot_from_metadata(self.storage.clone(), request.metadata()) {
            Err(err) => return Err(tonic::Status::aborted(
                format!("could not determine the correct snapshot to open given the `\"height\"` header of the request: {err:#}")
            )),
            Ok(snapshot) => snapshot,
        };

        let channel_id = ChannelId::from_str(request.get_ref().channel_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id = PortId::from_str(request.get_ref().port_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let (acknowledgement, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(
                        AckPath::new(&port_id, &channel_id, request.get_ref().sequence.into())
                            .to_string(),
                    )
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map_err(|e| {
                tonic::Status::aborted(format!("couldn't get packet acknowledgement: {e}"))
            })?;

        let acknowledgement =
            acknowledgement.ok_or_else(|| tonic::Status::aborted("acknowledgement not found"))?;

        Ok(tonic::Response::new(QueryPacketAcknowledgementResponse {
            acknowledgement,
            proof: proof.encode_to_vec(),
            proof_height: Some(ibc_proto::ibc::core::client::v1::Height {
                revision_height: HI::get_block_height(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?
                    + 1,
                revision_number: HI::get_revision_number(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            }),
        }))
    }
    /// PacketAcknowledgements returns all the packet acknowledgements associated
    /// with a channel.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn packet_acknowledgements(
        &self,
        request: tonic::Request<QueryPacketAcknowledgementsRequest>,
    ) -> std::result::Result<tonic::Response<QueryPacketAcknowledgementsResponse>, tonic::Status>
    {
        let snapshot = self.storage.latest_snapshot();
        let height = Height {
            revision_number: 0,
            revision_height: snapshot.version(),
        };
        let request = request.get_ref();

        let chan_id: ChannelId = ChannelId::from_str(&request.channel_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id: PortId = PortId::from_str(&request.port_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let ack_counter = snapshot
            .get_ack_sequence(&chan_id, &port_id)
            .await
            .map_err(|e| {
                tonic::Status::aborted(format!(
                    "couldn't get ack sequence for channel {chan_id} and port {port_id}: {e}"
                ))
            })?;

        let mut acks = vec![];
        for ack_idx in 0..ack_counter {
            let maybe_ack = snapshot
                .get_packet_acknowledgement(&port_id, &chan_id, ack_idx)
                .await.map_err(|e| {
                    tonic::Status::aborted(format!(
                        "couldn't get packet acknowledgement for channel {chan_id} and port {port_id} at index {ack_idx}: {e}"
                    ))
                })?;

            // Only include the ack if it was found; otherwise, signal lack of
            // by omitting it from the response.
            if let Some(ack) = maybe_ack {
                let ack_state = PacketState {
                    port_id: request.port_id.clone(),
                    channel_id: request.channel_id.clone(),
                    sequence: ack_idx,
                    data: ack.clone(),
                };

                acks.push(ack_state);
            }
        }

        let res = QueryPacketAcknowledgementsResponse {
            acknowledgements: acks,
            pagination: None,
            height: Some(height),
        };

        Ok(tonic::Response::new(res))
    }
    /// UnreceivedPackets returns all the unreceived IBC packets associated with a
    /// channel and sequences.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn unreceived_packets(
        &self,
        request: tonic::Request<QueryUnreceivedPacketsRequest>,
    ) -> std::result::Result<tonic::Response<QueryUnreceivedPacketsResponse>, tonic::Status> {
        let snapshot = self.storage.latest_snapshot();
        let height = snapshot.version();
        let request = request.get_ref();

        let chan_id: ChannelId = ChannelId::from_str(&request.channel_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id: PortId = PortId::from_str(&request.port_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let mut unreceived_seqs = vec![];

        for seq in request.packet_commitment_sequences.clone() {
            if seq == 0 {
                return Err(tonic::Status::aborted(format!(
                    "packet sequence {} cannot be 0",
                    seq
                )));
            }

            if !snapshot
                .seen_packet_by_channel(&chan_id, &port_id, seq)
                .await.map_err(|e| {
                    tonic::Status::aborted(format!(
                        "couldn't get packet commitment for channel {chan_id} and port {port_id} at index {seq}: {e}"
                    ))
                })?
            {
                unreceived_seqs.push(seq);
            }
        }

        let height = Height {
            revision_number: 0,
            revision_height: height,
        };

        let res = QueryUnreceivedPacketsResponse {
            sequences: unreceived_seqs,
            height: Some(height),
        };

        Ok(tonic::Response::new(res))
    }
    /// UnreceivedAcks returns all the unreceived IBC acknowledgements associated
    /// with a channel and sequences.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn unreceived_acks(
        &self,
        request: tonic::Request<QueryUnreceivedAcksRequest>,
    ) -> std::result::Result<tonic::Response<QueryUnreceivedAcksResponse>, tonic::Status> {
        let snapshot = self.storage.latest_snapshot();
        let height = Height {
            revision_number: 0,
            revision_height: snapshot.version(),
        };
        let request = request.get_ref();

        let chan_id: ChannelId = ChannelId::from_str(&request.channel_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id: PortId = PortId::from_str(&request.port_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let mut unreceived_seqs = vec![];

        for seq in request.packet_ack_sequences.clone() {
            if seq == 0 {
                return Err(tonic::Status::aborted(format!(
                    "packet sequence {} cannot be 0",
                    seq
                )));
            }

            if snapshot
                .get_packet_commitment_by_id(&chan_id, &port_id, seq)
                .await.map_err(|e| {
                    tonic::Status::aborted(format!(
                        "couldn't get packet commitment for channel {chan_id} and port {port_id} at index {seq}: {e}"
                    ))
                })?
                .is_some()
            {
                unreceived_seqs.push(seq);
            }
        }

        let res = QueryUnreceivedAcksResponse {
            sequences: unreceived_seqs,
            height: Some(height),
        };

        Ok(tonic::Response::new(res))
    }

    /// NextSequenceReceive returns the next receive sequence for a given channel.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn next_sequence_receive(
        &self,
        request: tonic::Request<QueryNextSequenceReceiveRequest>,
    ) -> std::result::Result<tonic::Response<QueryNextSequenceReceiveResponse>, tonic::Status> {
        let snapshot = match determine_snapshot_from_metadata(self.storage.clone(), request.metadata()) {
            Err(err) => return Err(tonic::Status::aborted(
                format!("could not determine the correct snapshot to open given the `\"height\"` header of the request: {err:#}")
            )),
            Ok(snapshot) => snapshot,
        };

        let channel_id = ChannelId::from_str(request.get_ref().channel_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id = PortId::from_str(request.get_ref().port_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let (next_recv_sequence, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(SeqRecvPath::new(&port_id, &channel_id).to_string())
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map_err(|e| tonic::Status::aborted(format!("couldn't get channel: {e}")))?;

        let next_recv_sequence = next_recv_sequence
            .map(|seq_bytes| u64::from_be_bytes(seq_bytes.try_into().expect("invalid sequence")))
            .ok_or_else(|| tonic::Status::aborted("next receive sequence not found"))?;

        Ok(tonic::Response::new(QueryNextSequenceReceiveResponse {
            next_sequence_receive: next_recv_sequence,
            proof: proof.encode_to_vec(),
            proof_height: Some(ibc_proto::ibc::core::client::v1::Height {
                revision_height: HI::get_block_height(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?
                    + 1,
                revision_number: HI::get_revision_number(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            }),
        }))
    }

    /// Returns the next send sequence for a given channel.
    #[tracing::instrument(skip(self), err, level = "debug")]
    async fn next_sequence_send(
        &self,
        request: tonic::Request<QueryNextSequenceSendRequest>,
    ) -> std::result::Result<tonic::Response<QueryNextSequenceSendResponse>, tonic::Status> {
        let snapshot = match determine_snapshot_from_metadata(self.storage.clone(), request.metadata()) {
            Err(err) => return Err(tonic::Status::aborted(
                format!("could not determine the correct snapshot to open given the `\"height\"` header of the request: {err:#}")
            )),
            Ok(snapshot) => snapshot,
        };

        let channel_id = ChannelId::from_str(request.get_ref().channel_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid channel id: {e}")))?;
        let port_id = PortId::from_str(request.get_ref().port_id.as_str())
            .map_err(|e| tonic::Status::aborted(format!("invalid port id: {e}")))?;

        let (next_send_sequence, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(SeqSendPath::new(&port_id, &channel_id).to_string())
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map_err(|e| tonic::Status::aborted(format!("couldn't get channel: {e}")))?;

        let next_send_sequence = next_send_sequence
            .map(|seq_bytes| u64::from_be_bytes(seq_bytes.try_into().expect("invalid sequence")))
            .ok_or_else(|| tonic::Status::aborted("next receive sequence not found"))?;

        Ok(tonic::Response::new(QueryNextSequenceSendResponse {
            next_sequence_send: next_send_sequence,
            proof: proof.encode_to_vec(),
            proof_height: Some(ibc_proto::ibc::core::client::v1::Height {
                revision_height: HI::get_block_height(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?
                    + 1,
                revision_number: HI::get_revision_number(&snapshot)
                    .await
                    .map_err(|e| tonic::Status::aborted(format!("couldn't decode height: {e}")))?,
            }),
        }))
    }
}