penumbra_ibc/component/rpc/
connection_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
use async_trait::async_trait;

use ibc_proto::ibc::core::client::v1::{Height, IdentifiedClientState};
use ibc_proto::ibc::core::connection::v1::query_server::Query as ConnectionQuery;
use ibc_proto::ibc::core::connection::v1::{
    ConnectionEnd, QueryClientConnectionsRequest, QueryClientConnectionsResponse,
    QueryConnectionClientStateRequest, QueryConnectionClientStateResponse,
    QueryConnectionConsensusStateRequest, QueryConnectionConsensusStateResponse,
    QueryConnectionRequest, QueryConnectionResponse, QueryConnectionsRequest,
    QueryConnectionsResponse,
};

use ibc_types::core::client::ClientId;
use ibc_types::core::connection::{ClientPaths, ConnectionId, IdentifiedConnectionEnd};
use ibc_types::path::{
    ClientConnectionPath, ClientConsensusStatePath, ClientStatePath, ConnectionPath,
};
use ibc_types::DomainType;
use prost::Message;
use std::str::FromStr;

use crate::component::{ConnectionStateReadExt, HostInterface};
use crate::prefix::MerklePrefixExt;
use crate::IBC_COMMITMENT_PREFIX;

use super::IbcQuery;

#[async_trait]
impl<HI: HostInterface + Send + Sync + 'static> ConnectionQuery for IbcQuery<HI> {
    /// Connection queries an IBC connection end.
    async fn connection(
        &self,
        request: tonic::Request<QueryConnectionRequest>,
    ) -> std::result::Result<tonic::Response<QueryConnectionResponse>, tonic::Status> {
        tracing::debug!("querying connection {:?}", request);
        let snapshot = self.storage.latest_snapshot();
        let connection_id = &ConnectionId::from_str(&request.get_ref().connection_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid connection id: {e}")))?;

        let (conn, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(ConnectionPath::new(connection_id).to_string())
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map(|res| {
                let conn = res
                    .0
                    .map(|conn_bytes| ConnectionEnd::decode(conn_bytes.as_ref()))
                    .transpose();

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

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

        let res = QueryConnectionResponse {
            connection: conn,
            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))
    }

    async fn connection_params(
        &self,
        _request: tonic::Request<
            ibc_proto::ibc::core::connection::v1::QueryConnectionParamsRequest,
        >,
    ) -> std::result::Result<
        tonic::Response<ibc_proto::ibc::core::connection::v1::QueryConnectionParamsResponse>,
        tonic::Status,
    > {
        Err(tonic::Status::unimplemented("not implemented"))
    }

    /// Connections queries all the IBC connections of a chain.
    async fn connections(
        &self,
        _request: tonic::Request<QueryConnectionsRequest>,
    ) -> std::result::Result<tonic::Response<QueryConnectionsResponse>, tonic::Status> {
        let snapshot = self.storage.latest_snapshot();
        let height = snapshot.version() + 1;

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

        let mut connections = vec![];
        for conn_idx in 0..connection_counter.0 {
            let conn_id = ConnectionId(format!("connection-{}", conn_idx));
            let connection = snapshot
                .get_connection(&conn_id)
                .await
                .map_err(|e| {
                    tonic::Status::aborted(format!("couldn't get connection {conn_id}: {e}"))
                })?
                .ok_or("unable to get connection")
                .map_err(|e| {
                    tonic::Status::aborted(format!("couldn't get connection {conn_id}: {e}"))
                })?;
            let id_conn = IdentifiedConnectionEnd {
                connection_id: conn_id,
                connection_end: connection,
            };
            connections.push(id_conn.into());
        }

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

        let res = QueryConnectionsResponse {
            connections,
            pagination: None,
            height: Some(height),
        };

        Ok(tonic::Response::new(res))
    }
    /// ClientConnections queries the connection paths associated with a client
    /// state.
    async fn client_connections(
        &self,
        request: tonic::Request<QueryClientConnectionsRequest>,
    ) -> std::result::Result<tonic::Response<QueryClientConnectionsResponse>, tonic::Status> {
        let snapshot = self.storage.latest_snapshot();
        let client_id = &ClientId::from_str(&request.get_ref().client_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid client id: {e}")))?;

        let (client_connections, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(ClientConnectionPath::new(client_id).to_string())
                    .as_bytes()
                    .to_vec(),
            )
            .await
            .map_err(|e| tonic::Status::aborted(format!("couldn't get client connections: {e}")))?;

        let connection_paths: Vec<String> = client_connections
            .map(|client_connections| ClientPaths::decode(client_connections.as_ref()))
            .transpose()
            .map_err(|e| {
                tonic::Status::aborted(format!("couldn't decode client connections: {e}"))
            })?
            .map(|client_paths| client_paths.paths)
            .map(|paths| paths.into_iter().map(|path| path.to_string()).collect())
            .unwrap_or_default();

        Ok(tonic::Response::new(QueryClientConnectionsResponse {
            connection_paths,
            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}")))?,
            }),
        }))
    }
    /// ConnectionClientState queries the client state associated with the
    /// connection.
    async fn connection_client_state(
        &self,
        request: tonic::Request<QueryConnectionClientStateRequest>,
    ) -> std::result::Result<tonic::Response<QueryConnectionClientStateResponse>, tonic::Status>
    {
        let snapshot = self.storage.latest_snapshot();
        let connection_id = &ConnectionId::from_str(&request.get_ref().connection_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid connection id: {e}")))?;

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

        let (client_state, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(ClientStatePath::new(&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: client_id.clone().to_string(),
            client_state: client_state_any,
        };

        Ok(tonic::Response::new(QueryConnectionClientStateResponse {
            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}")))?,
            }),
        }))
    }
    /// ConnectionConsensusState queries the consensus state associated with the
    /// connection.
    async fn connection_consensus_state(
        &self,
        request: tonic::Request<QueryConnectionConsensusStateRequest>,
    ) -> std::result::Result<tonic::Response<QueryConnectionConsensusStateResponse>, tonic::Status>
    {
        let snapshot = self.storage.latest_snapshot();
        let consensus_state_height = ibc_types::core::client::Height {
            revision_number: request.get_ref().revision_number,
            revision_height: request.get_ref().revision_height,
        };
        let connection_id = &ConnectionId::from_str(&request.get_ref().connection_id)
            .map_err(|e| tonic::Status::aborted(format!("invalid connection id: {e}")))?;

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

        let (consensus_state, proof) = snapshot
            .get_with_proof(
                IBC_COMMITMENT_PREFIX
                    .apply_string(
                        ClientConsensusStatePath::new(&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(
            QueryConnectionConsensusStateResponse {
                consensus_state: consensus_state_any,
                client_id: client_id.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}"))
                    })?,
                }),
            },
        ))
    }
}