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
//! Protocol logic specific to processing ICS3 messages of type `MsgConnectionOpenTry`.

use crate::core::ics03_connection::connection::{ConnectionEnd, Counterparty, State};
use crate::core::ics03_connection::context::ConnectionReader;
use crate::core::ics03_connection::error::Error;
use crate::core::ics03_connection::events::Attributes;
use crate::core::ics03_connection::handler::verify::{
    check_client_consensus_height, verify_proofs,
};
use crate::core::ics03_connection::handler::{ConnectionIdState, ConnectionResult};
use crate::core::ics03_connection::msgs::conn_open_try::MsgConnectionOpenTry;
use crate::core::ics24_host::identifier::ConnectionId;
use crate::events::IbcEvent;
use crate::handler::{HandlerOutput, HandlerResult};
use crate::prelude::*;

pub(crate) fn process(
    ctx: &dyn ConnectionReader,
    msg: MsgConnectionOpenTry,
) -> HandlerResult<ConnectionResult, Error> {
    let mut output = HandlerOutput::builder();

    // Check that consensus height (for client proof) in message is not too advanced nor too old.
    check_client_consensus_height(ctx, msg.consensus_height())?;

    // Unwrap the old connection end (if any) and its identifier.
    let (mut new_connection_end, conn_id) = match &msg.previous_connection_id {
        // A connection with this id should already exist. Search & validate.
        Some(prev_id) => {
            let old_connection_end = ctx.connection_end(prev_id)?;

            // Validate that existing connection end matches with the one we're trying to establish.
            if old_connection_end.state_matches(&State::Init)
                && old_connection_end.counterparty_matches(&msg.counterparty)
                && old_connection_end.client_id_matches(&msg.client_id)
                && old_connection_end.delay_period() == msg.delay_period
            {
                // A ConnectionEnd already exists and all validation passed.
                output.log(format!(
                    "success: `previous_connection_id` {} validation passed",
                    prev_id
                ));
                Ok((old_connection_end, prev_id.clone()))
            } else {
                // A ConnectionEnd already exists and validation failed.
                Err(Error::connection_mismatch(prev_id.clone()))
            }
        }
        // No prev. connection id was supplied, create a new connection end and conn id.
        None => {
            // Build a new connection end as well as an identifier.
            let conn_end = ConnectionEnd::new(
                State::Init,
                msg.client_id.clone(),
                msg.counterparty.clone(),
                msg.counterparty_versions.clone(),
                msg.delay_period,
            );
            let id_counter = ctx.connection_counter()?;
            let conn_id = ConnectionId::new(id_counter);

            output.log(format!(
                "success: new connection end and identifier {} generated",
                conn_id
            ));
            Ok((conn_end, conn_id))
        }
    }?;

    // Proof verification in two steps:
    // 1. Setup: build the ConnectionEnd as we expect to find it on the other party.
    let expected_conn = ConnectionEnd::new(
        State::Init,
        msg.counterparty.client_id().clone(),
        Counterparty::new(msg.client_id.clone(), None, ctx.commitment_prefix()),
        msg.counterparty_versions.clone(),
        msg.delay_period,
    );

    // 2. Pass the details to the verification function.
    verify_proofs(
        ctx,
        msg.client_state.clone(),
        msg.proofs.height(),
        &new_connection_end,
        &expected_conn,
        &msg.proofs,
    )?;

    // Transition the connection end to the new state & pick a version.
    new_connection_end.set_state(State::TryOpen);

    // Pick the version.
    new_connection_end.set_version(ctx.pick_version(
        ctx.get_compatible_versions(),
        msg.counterparty_versions.clone(),
    )?);

    assert_eq!(new_connection_end.versions().len(), 1);

    output.log("success: connection verification passed");

    let result = ConnectionResult {
        connection_id: conn_id.clone(),
        connection_id_state: if matches!(msg.previous_connection_id, None) {
            ConnectionIdState::Generated
        } else {
            ConnectionIdState::Reused
        },
        connection_end: new_connection_end,
    };

    let event_attributes = Attributes {
        connection_id: Some(conn_id),
        height: ctx.host_current_height(),
        ..Default::default()
    };
    output.emit(IbcEvent::OpenTryConnection(event_attributes.into()));

    Ok(output.with_result(result))
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;

    use test_log::test;

    use crate::core::ics03_connection::connection::State;
    use crate::core::ics03_connection::context::ConnectionReader;
    use crate::core::ics03_connection::handler::{dispatch, ConnectionResult};
    use crate::core::ics03_connection::msgs::conn_open_try::test_util::get_dummy_raw_msg_conn_open_try;
    use crate::core::ics03_connection::msgs::conn_open_try::MsgConnectionOpenTry;
    use crate::core::ics03_connection::msgs::ConnectionMsg;
    use crate::core::ics24_host::identifier::ChainId;
    use crate::events::IbcEvent;
    use crate::mock::context::MockContext;
    use crate::mock::host::HostType;
    use crate::Height;

    #[test]
    fn conn_open_try_msg_processing() {
        struct Test {
            name: String,
            ctx: MockContext,
            msg: ConnectionMsg,
            want_pass: bool,
        }

        let host_chain_height = Height::new(0, 35);
        let max_history_size = 5;
        let context = MockContext::new(
            ChainId::new("mockgaia".to_string(), 0),
            HostType::Mock,
            max_history_size,
            host_chain_height,
        );
        let client_consensus_state_height = 10;

        let msg_conn_try = MsgConnectionOpenTry::try_from(get_dummy_raw_msg_conn_open_try(
            client_consensus_state_height,
            host_chain_height.revision_height,
        ))
        .unwrap();

        // The proof targets a height that does not exist (i.e., too advanced) on destination chain.
        let msg_height_advanced = MsgConnectionOpenTry::try_from(get_dummy_raw_msg_conn_open_try(
            client_consensus_state_height,
            host_chain_height.increment().revision_height,
        ))
        .unwrap();
        let pruned_height = host_chain_height
            .sub(max_history_size as u64 + 1)
            .unwrap()
            .revision_height;
        // The consensus proof targets a missing height (pruned) on destination chain.
        let msg_height_old = MsgConnectionOpenTry::try_from(get_dummy_raw_msg_conn_open_try(
            client_consensus_state_height,
            pruned_height,
        ))
        .unwrap();

        // The proofs in this message are created at a height which the client on destination chain does not have.
        let msg_proof_height_missing =
            MsgConnectionOpenTry::try_from(get_dummy_raw_msg_conn_open_try(
                client_consensus_state_height - 1,
                host_chain_height.revision_height,
            ))
            .unwrap();

        let tests: Vec<Test> = vec![
            Test {
                name: "Processing fails because the height is too advanced".to_string(),
                ctx: context.clone(),
                msg: ConnectionMsg::ConnectionOpenTry(Box::new(msg_height_advanced)),
                want_pass: false,
            },
            Test {
                name: "Processing fails because the height is too old".to_string(),
                ctx: context.clone(),
                msg: ConnectionMsg::ConnectionOpenTry(Box::new(msg_height_old)),
                want_pass: false,
            },
            Test {
                name: "Processing fails because no client exists".to_string(),
                ctx: context.clone(),
                msg: ConnectionMsg::ConnectionOpenTry(Box::new(msg_conn_try.clone())),
                want_pass: false,
            },
            Test {
                name: "Processing fails because the client misses the consensus state targeted by the proof".to_string(),
                ctx: context.clone().with_client(&msg_proof_height_missing.client_id, Height::new(0, client_consensus_state_height)),
                msg: ConnectionMsg::ConnectionOpenTry(Box::new(msg_proof_height_missing)),
                want_pass: false,
            },
            Test {
                name: "Good parameters but has previous_connection_id".to_string(),
                ctx: context.clone().with_client(&msg_conn_try.client_id, Height::new(0, client_consensus_state_height)),
                msg: ConnectionMsg::ConnectionOpenTry(Box::new(msg_conn_try.clone())),
                want_pass: false,
            },
            Test {
                name: "Good parameters".to_string(),
                ctx: context.with_client(&msg_conn_try.client_id, Height::new(0, client_consensus_state_height)),
                msg: ConnectionMsg::ConnectionOpenTry(Box::new(msg_conn_try.with_previous_connection_id(None))),
                want_pass: true,
            },
        ]
        .into_iter()
        .collect();

        for test in tests {
            let res = dispatch(&test.ctx, test.msg.clone());
            // Additionally check the events and the output objects in the result.
            match res {
                Ok(proto_output) => {
                    assert!(
                        test.want_pass,
                        "conn_open_try: test passed but was supposed to fail for test: {}, \nparams {:?} {:?}",
                        test.name,
                        test.msg.clone(),
                        test.ctx.clone()
                    );

                    assert!(!proto_output.events.is_empty()); // Some events must exist.

                    // The object in the output is a ConnectionEnd, should have TryOpen state.
                    let res: ConnectionResult = proto_output.result;
                    assert_eq!(res.connection_end.state().clone(), State::TryOpen);

                    for e in proto_output.events.iter() {
                        assert!(matches!(e, &IbcEvent::OpenTryConnection(_)));
                        assert_eq!(e.height(), test.ctx.host_current_height());
                    }
                }
                Err(e) => {
                    assert!(
                        !test.want_pass,
                        "conn_open_try: failed for test: {}, \nparams {:?} {:?} error: {:?}",
                        test.name,
                        test.msg,
                        test.ctx.clone(),
                        e,
                    );
                }
            }
        }
    }
}