-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathhandler.rs
317 lines (280 loc) · 13 KB
/
handler.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
use prost_types::Any;
use tendermint_proto::Protobuf;
// use crate::handler;
use crate::events::IBCEvent;
use crate::handler::HandlerOutput;
use crate::ics02_client::handler::dispatch as ics2_msg_dispatcher;
use crate::ics02_client::msgs::create_client;
use crate::ics02_client::msgs::update_client;
use crate::ics02_client::msgs::ClientMsg;
use crate::ics03_connection::handler::dispatch as ics3_msg_dispatcher;
use crate::ics04_channel::handler::dispatch as ics4_msg_dispatcher;
//use crate::ics04_channel::msgs::chan_open_try::test_util::get_dummy_raw_msg_chan_open_try;
use crate::ics26_routing::context::ICS26Context;
use crate::ics26_routing::error::{Error, Kind};
use crate::ics26_routing::msgs::ICS26Envelope;
use crate::ics26_routing::msgs::ICS26Envelope::{ICS2Msg, ICS3Msg, ICS4Msg};
// use crate::ics04_channel::msgs::chan_open_try::test_util::get_dummy_raw_msg_chan_open_try;
/// Mimics the DeliverTx ABCI interface, but a slightly lower level. No need for authentication
/// info or signature checks here.
/// https://github.com/cosmos/cosmos-sdk/tree/master/docs/basics
/// Returns a vector of all events that got generated as a byproduct of processing `messages`.
pub fn deliver<Ctx>(ctx: &mut Ctx, messages: Vec<Any>) -> Result<Vec<IBCEvent>, Error>
where
Ctx: ICS26Context,
{
// Create a clone, which will store each intermediary stage of applying txs.
let mut ctx_interim = ctx.clone();
// A buffer for all the events, to be used as return value.
let mut res: Vec<IBCEvent> = vec![];
for any_msg in messages {
// Decode the proto message into a domain message, creating an ICS26 envelope.
let envelope = match any_msg.type_url.as_str() {
// ICS2 messages
create_client::TYPE_URL => {
// Pop out the message and then wrap it in the corresponding type.
let domain_msg = create_client::MsgCreateAnyClient::decode_vec(&any_msg.value)
.map_err(|e| Kind::MalformedMessageBytes.context(e))?;
Ok(ICS2Msg(ClientMsg::CreateClient(domain_msg)))
}
update_client::TYPE_URL => {
let domain_msg = update_client::MsgUpdateAnyClient::decode_vec(&any_msg.value)
.map_err(|e| Kind::MalformedMessageBytes.context(e))?;
Ok(ICS2Msg(ClientMsg::UpdateClient(domain_msg)))
}
// TODO: ICS3 messages
_ => Err(Kind::UnknownMessageTypeURL(any_msg.type_url)),
}?;
// Process the envelope, and accumulate any events that were generated.
let mut output = dispatch(&mut ctx_interim, envelope)?;
// TODO: output.log and output.result are discarded
res.append(&mut output.events);
}
// No error has surfaced, so we now apply the changes permanently to the original context.
*ctx = ctx_interim;
Ok(res)
}
/// Top-level ICS dispatch function. Routes incoming IBC messages to their corresponding module.
/// Returns a handler output with empty result of type `HandlerOutput<()>` which contains the log
/// and events produced after processing the input `msg`.
pub fn dispatch<Ctx>(ctx: &mut Ctx, msg: ICS26Envelope) -> Result<HandlerOutput<()>, Error>
where
Ctx: ICS26Context,
{
let output = match msg {
ICS2Msg(msg) => {
let handler_output =
ics2_msg_dispatcher(ctx, msg).map_err(|e| Kind::HandlerRaisedError.context(e))?;
// Apply the result to the context (host chain store).
ctx.store_client_result(handler_output.result)
.map_err(|e| Kind::KeeperRaisedError.context(e))?;
HandlerOutput::builder()
.with_log(handler_output.log)
.with_events(handler_output.events)
.with_result(())
}
ICS3Msg(msg) => {
let handler_output =
ics3_msg_dispatcher(ctx, msg).map_err(|e| Kind::HandlerRaisedError.context(e))?;
// Apply any results to the host chain store.
ctx.store_connection_result(handler_output.result)
.map_err(|e| Kind::KeeperRaisedError.context(e))?;
HandlerOutput::builder()
.with_log(handler_output.log)
.with_events(handler_output.events)
.with_result(())
}
ICS4Msg(msg) => {
let handler_output =
ics4_msg_dispatcher(ctx, msg).map_err(|e| Kind::HandlerRaisedError.context(e))?;
// Apply any results to the host chain store.
ctx.store_channel_result(handler_output.result)
.map_err(|e| Kind::KeeperRaisedError.context(e))?;
HandlerOutput::builder()
.with_log(handler_output.log)
.with_events(handler_output.events)
.with_result(())
} // TODO: add dispatchers for others.
};
Ok(output)
}
#[cfg(test)]
mod tests {
use std::convert::TryFrom;
use std::str::FromStr;
use crate::ics02_client::client_def::{AnyClientState, AnyConsensusState};
use crate::ics02_client::msgs::create_client::MsgCreateAnyClient;
use crate::ics02_client::msgs::update_client::MsgUpdateAnyClient;
use crate::ics02_client::msgs::ClientMsg;
use crate::ics03_connection::msgs::conn_open_init::test_util::get_dummy_msg_conn_open_init;
use crate::ics03_connection::msgs::conn_open_init::MsgConnectionOpenInit;
use crate::ics03_connection::msgs::conn_open_try::test_util::get_dummy_msg_conn_open_try;
use crate::ics03_connection::msgs::conn_open_try::MsgConnectionOpenTry;
use crate::ics03_connection::msgs::ConnectionMsg;
use crate::ics04_channel::msgs::chan_open_init::test_util::get_dummy_raw_msg_chan_open_init;
use crate::ics04_channel::msgs::chan_open_init::test_util::get_dummy_raw_msg_chan_open_init_with_missing_connection;
use crate::ics04_channel::msgs::chan_open_init::MsgChannelOpenInit;
use crate::ics04_channel::msgs::chan_open_try::test_util::get_dummy_raw_msg_chan_open_try;
use crate::ics04_channel::msgs::chan_open_try::MsgChannelOpenTry;
use crate::ics04_channel::msgs::ChannelMsg;
use crate::ics24_host::identifier::ChannelId;
use crate::events::IBCEvent;
use crate::ics26_routing::handler::dispatch;
use crate::ics26_routing::msgs::ICS26Envelope;
use crate::mock::client_state::{MockClientState, MockConsensusState};
use crate::mock::context::MockContext;
use crate::mock::header::MockHeader;
use crate::test_utils::get_dummy_account_id;
use crate::Height;
#[test]
// These tests exercise two main paths: (1) the ability of the ICS26 routing module to dispatch
// messages to the correct module handler, and more importantly: (2) the ability of ICS handlers
// to work with the context and correctly store results (i.e., the ClientKeeper and
// ConnectionKeeper traits).
fn routing_module_and_keepers() {
// Test parameters
struct Test {
name: String,
msg: ICS26Envelope,
want_pass: bool,
}
let default_signer = get_dummy_account_id();
let start_client_height = Height::new(0, 42);
let update_client_height = Height::new(0, 50);
let create_client_msg = MsgCreateAnyClient::new(
AnyClientState::from(MockClientState(MockHeader(start_client_height))),
AnyConsensusState::from(MockConsensusState(MockHeader(start_client_height))),
get_dummy_account_id(),
)
.unwrap();
let msg_conn_init =
MsgConnectionOpenInit::try_from(get_dummy_msg_conn_open_init()).unwrap();
let incorrect_msg_conn_try =
MsgConnectionOpenTry::try_from(get_dummy_msg_conn_open_try(10, 34)).unwrap();
let msg_conn_try_good_height =
MsgConnectionOpenTry::try_from(get_dummy_msg_conn_open_try(10, 29)).unwrap();
let msg_chan_init =
MsgChannelOpenInit::try_from(get_dummy_raw_msg_chan_open_init()).unwrap();
let msg_chan_init2 = MsgChannelOpenInit::try_from(
get_dummy_raw_msg_chan_open_init_with_missing_connection(),
)
.unwrap();
let proof_height = 10;
//let msg_chan_try =
// MsgChannelOpenTry::try_from(get_dummy_raw_msg_chan_open_try(proof_height)).unwrap();
let mut msg_chan_try2 =
MsgChannelOpenTry::try_from(get_dummy_raw_msg_chan_open_try(proof_height)).unwrap();
// We reuse this same context across all tests. Nothing in particular needs parametrizing.
let mut ctx = MockContext::default();
let prefix = ChannelId::default().to_string();
let suffix = 0;
msg_chan_try2.previous_channel_id = Some(
<ChannelId as FromStr>::from_str(format!("{}-{}", prefix, suffix).as_str()).unwrap(),
);
// msg_chan_try2.counterparty_version = get_compatible_versions().clone()[0].clone();
// First, create a client..
let res = dispatch(
&mut ctx,
ICS26Envelope::ICS2Msg(ClientMsg::CreateClient(create_client_msg.clone())),
);
assert_eq!(
true,
res.is_ok(),
"ICS26 routing dispatch test 'client creation' failed for message {:?} with result: {:?}",
create_client_msg,
res
);
ctx.add_port(msg_chan_init.port_id().clone());
// Figure out the ID of the client that was just created.
let mut events = res.unwrap().events;
let client_id_event = events.pop();
assert!(
client_id_event.is_some(),
"There was no event generated for client creation!"
);
let client_id = match client_id_event.unwrap() {
IBCEvent::CreateClient(create_client) => create_client.client_id().clone(),
event => panic!("unexpected IBC event: {:?}", event),
};
let tests: Vec<Test> = vec![
// Test some ICS2 client functionality.
Test {
name: "Client update successful".to_string(),
msg: ICS26Envelope::ICS2Msg(ClientMsg::UpdateClient(MsgUpdateAnyClient {
client_id: client_id.clone(),
header: MockHeader(update_client_height).into(),
signer: default_signer,
})),
want_pass: true,
},
Test {
name: "Client update fails due to stale header".to_string(),
msg: ICS26Envelope::ICS2Msg(ClientMsg::UpdateClient(MsgUpdateAnyClient {
client_id: client_id.clone(),
header: MockHeader(update_client_height).into(),
signer: default_signer,
})),
want_pass: false,
},
// Test the ICS3 connection functionality.
Test {
name: "Connection open init fail due to missing client".to_string(),
msg: ICS26Envelope::ICS3Msg(ConnectionMsg::ConnectionOpenInit(
msg_conn_init.clone(),
)),
want_pass: false,
},
Test {
name: "Connection open init success".to_string(),
msg: ICS26Envelope::ICS3Msg(ConnectionMsg::ConnectionOpenInit(
msg_conn_init.with_client_id(client_id),
)),
want_pass: true,
},
Test {
name: "Connection open try fails due to InvalidConsensusHeight (too high)"
.to_string(),
msg: ICS26Envelope::ICS3Msg(ConnectionMsg::ConnectionOpenTry(Box::new(
incorrect_msg_conn_try,
))),
want_pass: false,
},
Test {
name: "Connection open try fails due to mismatching connection ends".to_string(),
msg: ICS26Envelope::ICS3Msg(ConnectionMsg::ConnectionOpenTry(Box::new(
msg_conn_try_good_height,
))),
want_pass: false,
},
// ICS04
Test {
name: "Channel open init success".to_string(),
msg: ICS26Envelope::ICS4Msg(ChannelMsg::ChannelOpenInit(msg_chan_init)),
want_pass: true,
},
Test {
name: "Channel open init fail due to missing connection".to_string(),
msg: ICS26Envelope::ICS4Msg(ChannelMsg::ChannelOpenInit(msg_chan_init2)),
want_pass: false,
},
Test {
name: "Channel open try fails due to connection not open".to_string(),
msg: ICS26Envelope::ICS4Msg(ChannelMsg::ChannelOpenTry(msg_chan_try2)),
want_pass: false,
},
]
.into_iter()
.collect();
for test in tests {
let res = dispatch(&mut ctx, test.msg.clone());
assert_eq!(
test.want_pass,
res.is_ok(),
"ICS26 routing dispatch test '{}' failed for message {:?} with result: {:?}",
test.name,
test.msg,
res
);
}
}
}