-
Notifications
You must be signed in to change notification settings - Fork 336
/
ibc.rs
469 lines (420 loc) · 16.1 KB
/
ibc.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
use cosmwasm_std::{
attr, entry_point, from_slice, to_binary, DepsMut, Env, IbcBasicResponse, IbcChannelCloseMsg,
IbcChannelConnectMsg, IbcChannelOpenMsg, IbcMsg, IbcOrder, IbcPacketAckMsg,
IbcPacketReceiveMsg, IbcPacketTimeoutMsg, IbcReceiveResponse, StdError, StdResult, SubMsg,
};
use crate::ibc_msg::{
AcknowledgementMsg, BalancesResponse, DispatchResponse, PacketMsg, WhoAmIResponse,
};
use crate::state::{accounts, AccountData};
pub const IBC_VERSION: &str = "ibc-reflect-v1";
// TODO: make configurable?
/// packets live one hour
pub const PACKET_LIFETIME: u64 = 60 * 60;
#[entry_point]
/// enforces ordering and versioing constraints
pub fn ibc_channel_open(_deps: DepsMut, _env: Env, msg: IbcChannelOpenMsg) -> StdResult<()> {
let channel = msg.channel;
if channel.order != IbcOrder::Ordered {
return Err(StdError::generic_err("Only supports ordered channels"));
}
if channel.version.as_str() != IBC_VERSION {
return Err(StdError::generic_err(format!(
"Must set version to `{}`",
IBC_VERSION
)));
}
// TODO: do we need to check counterparty version as well?
// This flow needs to be well documented
if let Some(counter_version) = channel.counterparty_version {
if counter_version.as_str() != IBC_VERSION {
return Err(StdError::generic_err(format!(
"Counterparty version must be `{}`",
IBC_VERSION
)));
}
}
Ok(())
}
#[entry_point]
/// once it's established, we send a WhoAmI message
pub fn ibc_channel_connect(
deps: DepsMut,
env: Env,
msg: IbcChannelConnectMsg,
) -> StdResult<IbcBasicResponse> {
let channel = msg.channel;
let channel_id = channel.endpoint.channel_id;
// create an account holder the channel exists (not found if not registered)
let data = AccountData::default();
accounts(deps.storage).save(channel_id.as_bytes(), &data)?;
// construct a packet to send
let packet = PacketMsg::WhoAmI {};
let msg = IbcMsg::SendPacket {
channel_id: channel_id.clone(),
data: to_binary(&packet)?,
timeout: env.block.time.plus_seconds(PACKET_LIFETIME).into(),
};
Ok(IbcBasicResponse {
messages: vec![SubMsg::new(msg)],
attributes: vec![
attr("action", "ibc_connect"),
attr("channel_id", channel_id),
],
})
}
#[entry_point]
/// On closed channel, simply delete the account from our local store
pub fn ibc_channel_close(
deps: DepsMut,
_env: Env,
msg: IbcChannelCloseMsg,
) -> StdResult<IbcBasicResponse> {
let channel = msg.channel;
// remove the channel
let channel_id = channel.endpoint.channel_id;
accounts(deps.storage).remove(channel_id.as_bytes());
Ok(IbcBasicResponse {
attributes: vec![attr("action", "ibc_close"), attr("channel_id", channel_id)],
messages: vec![],
})
}
#[entry_point]
/// never should be called as the other side never sends packets
pub fn ibc_packet_receive(
_deps: DepsMut,
_env: Env,
_packet: IbcPacketReceiveMsg,
) -> StdResult<IbcReceiveResponse> {
Ok(IbcReceiveResponse {
acknowledgement: b"{}".into(),
messages: vec![],
attributes: vec![attr("action", "ibc_packet_ack")],
})
}
#[entry_point]
pub fn ibc_packet_ack(
deps: DepsMut,
env: Env,
msg: IbcPacketAckMsg,
) -> StdResult<IbcBasicResponse> {
let ack = msg.ack;
// which local channel was this packet send from
let caller = ack.original_packet.src.channel_id;
// we need to parse the ack based on our request
let msg: PacketMsg = from_slice(&ack.original_packet.data)?;
match msg {
PacketMsg::Dispatch { .. } => {
let res: AcknowledgementMsg<DispatchResponse> = from_slice(&ack.acknowledgement.data)?;
acknowledge_dispatch(deps, caller, res)
}
PacketMsg::WhoAmI {} => {
let res: AcknowledgementMsg<WhoAmIResponse> = from_slice(&ack.acknowledgement.data)?;
acknowledge_who_am_i(deps, caller, res)
}
PacketMsg::Balances {} => {
let res: AcknowledgementMsg<BalancesResponse> = from_slice(&ack.acknowledgement.data)?;
acknowledge_balances(deps, env, caller, res)
}
}
}
// receive PacketMsg::Dispatch response
#[allow(clippy::unnecessary_wraps)]
fn acknowledge_dispatch(
_deps: DepsMut,
_caller: String,
_ack: AcknowledgementMsg<DispatchResponse>,
) -> StdResult<IbcBasicResponse> {
// TODO: actually handle success/error?
Ok(IbcBasicResponse {
messages: vec![],
attributes: vec![attr("action", "acknowledge_dispatch")],
})
}
// receive PacketMsg::WhoAmI response
// store address info in accounts info
fn acknowledge_who_am_i(
deps: DepsMut,
caller: String,
ack: AcknowledgementMsg<WhoAmIResponse>,
) -> StdResult<IbcBasicResponse> {
// ignore errors (but mention in log)
let WhoAmIResponse { account } = match ack {
AcknowledgementMsg::Ok(res) => res,
AcknowledgementMsg::Err(e) => {
return Ok(IbcBasicResponse {
messages: vec![],
attributes: vec![attr("action", "acknowledge_who_am_i"), attr("error", e)],
})
}
};
accounts(deps.storage).update(caller.as_bytes(), |acct| -> StdResult<_> {
match acct {
Some(mut acct) => {
// set the account the first time
if acct.remote_addr.is_none() {
acct.remote_addr = Some(account);
}
Ok(acct)
}
None => Err(StdError::generic_err("no account to update")),
}
})?;
Ok(IbcBasicResponse {
messages: vec![],
attributes: vec![attr("action", "acknowledge_who_am_i")],
})
}
// receive PacketMsg::Balances response
fn acknowledge_balances(
deps: DepsMut,
env: Env,
caller: String,
ack: AcknowledgementMsg<BalancesResponse>,
) -> StdResult<IbcBasicResponse> {
// ignore errors (but mention in log)
let BalancesResponse { account, balances } = match ack {
AcknowledgementMsg::Ok(res) => res,
AcknowledgementMsg::Err(e) => {
return Ok(IbcBasicResponse {
messages: vec![],
attributes: vec![attr("action", "acknowledge_balances"), attr("error", e)],
})
}
};
accounts(deps.storage).update(caller.as_bytes(), |acct| -> StdResult<_> {
match acct {
Some(acct) => {
if let Some(old_addr) = acct.remote_addr {
if old_addr != account {
return Err(StdError::generic_err(format!(
"remote account changed from {} to {}",
old_addr, account
)));
}
}
Ok(AccountData {
last_update_time: env.block.time,
remote_addr: Some(account),
remote_balance: balances,
})
}
None => Err(StdError::generic_err("no account to update")),
}
})?;
Ok(IbcBasicResponse {
messages: vec![],
attributes: vec![attr("action", "acknowledge_balances")],
})
}
#[entry_point]
/// we just ignore these now. shall we store some info?
pub fn ibc_packet_timeout(
_deps: DepsMut,
_env: Env,
_msg: IbcPacketTimeoutMsg,
) -> StdResult<IbcBasicResponse> {
Ok(IbcBasicResponse {
messages: vec![],
attributes: vec![attr("action", "ibc_packet_timeout")],
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::contract::{execute, instantiate, query};
use crate::msg::{AccountResponse, ExecuteMsg, InstantiateMsg, QueryMsg};
use cosmwasm_std::testing::{
mock_dependencies, mock_env, mock_ibc_channel, mock_ibc_packet_ack, mock_info, MockApi,
MockQuerier, MockStorage,
};
use cosmwasm_std::{
coin, coins, BankMsg, CosmosMsg, IbcAcknowledgement, IbcAcknowledgementWithPacket,
OwnedDeps,
};
const CREATOR: &str = "creator";
fn setup() -> OwnedDeps<MockStorage, MockApi, MockQuerier> {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg {};
let info = mock_info(CREATOR, &[]);
let res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
assert_eq!(0, res.messages.len());
deps
}
// connect will run through the entire handshake to set up a proper connect and
// save the account (tested in detail in `proper_handshake_flow`)
fn connect(mut deps: DepsMut, channel_id: &str) {
// open packet has no counterparty version, connect does
let mut handshake_open =
IbcChannelOpenMsg::new(mock_ibc_channel(channel_id, IbcOrder::Ordered, IBC_VERSION));
handshake_open.channel.counterparty_version = None;
// first we try to open with a valid handshake
ibc_channel_open(deps.branch(), mock_env(), handshake_open).unwrap();
// then we connect (with counter-party version set)
let handshake_connect =
IbcChannelConnectMsg::new(mock_ibc_channel(channel_id, IbcOrder::Ordered, IBC_VERSION));
let res = ibc_channel_connect(deps.branch(), mock_env(), handshake_connect).unwrap();
// this should send a WhoAmI request, which is received some blocks later
assert_eq!(1, res.messages.len());
match &res.messages[0].msg {
CosmosMsg::Ibc(IbcMsg::SendPacket {
channel_id: packet_channel,
..
}) => assert_eq!(packet_channel.as_str(), channel_id),
o => panic!("Unexpected message: {:?}", o),
};
}
fn who_am_i_response<T: Into<String>>(deps: DepsMut, channel_id: &str, account: T) {
let packet = PacketMsg::WhoAmI {};
let response = AcknowledgementMsg::Ok(WhoAmIResponse {
account: account.into(),
});
let ack = IbcAcknowledgementWithPacket {
acknowledgement: IbcAcknowledgement::encode_json(&response).unwrap(),
original_packet: mock_ibc_packet_ack(channel_id, &packet).unwrap(),
};
let msg = IbcPacketAckMsg::new(ack);
let res = ibc_packet_ack(deps, mock_env(), msg).unwrap();
assert_eq!(0, res.messages.len());
}
#[test]
fn enforce_version_in_handshake() {
let mut deps = setup();
let wrong_order = IbcChannelOpenMsg::new(mock_ibc_channel(
"channel-12",
IbcOrder::Unordered,
IBC_VERSION,
));
ibc_channel_open(deps.as_mut(), mock_env(), wrong_order).unwrap_err();
let wrong_version =
IbcChannelOpenMsg::new(mock_ibc_channel("channel-12", IbcOrder::Ordered, "reflect"));
ibc_channel_open(deps.as_mut(), mock_env(), wrong_version).unwrap_err();
let valid_handshake = IbcChannelOpenMsg::new(mock_ibc_channel(
"channel-12",
IbcOrder::Ordered,
IBC_VERSION,
));
ibc_channel_open(deps.as_mut(), mock_env(), valid_handshake).unwrap();
}
#[test]
fn proper_handshake_flow() {
// setup and connect handshake
let mut deps = setup();
let channel_id = "channel-1234";
connect(deps.as_mut(), channel_id);
// check for empty account
let q = QueryMsg::Account {
channel_id: channel_id.into(),
};
let r = query(deps.as_ref(), mock_env(), q).unwrap();
let acct: AccountResponse = from_slice(&r).unwrap();
assert!(acct.remote_addr.is_none());
assert!(acct.remote_balance.is_empty());
assert_eq!(0, acct.last_update_time.nanos());
// now get feedback from WhoAmI packet
let remote_addr = "account-789";
who_am_i_response(deps.as_mut(), channel_id, remote_addr);
// account should be set up
let q = QueryMsg::Account {
channel_id: channel_id.into(),
};
let r = query(deps.as_ref(), mock_env(), q).unwrap();
let acct: AccountResponse = from_slice(&r).unwrap();
assert_eq!(acct.remote_addr.unwrap(), remote_addr);
assert!(acct.remote_balance.is_empty());
assert_eq!(0, acct.last_update_time.nanos());
}
#[test]
fn dispatch_message_send_and_ack() {
let channel_id = "channel-1234";
let remote_addr = "account-789";
// init contract
let mut deps = setup();
// channel handshake
connect(deps.as_mut(), channel_id);
// get feedback from WhoAmI packet
who_am_i_response(deps.as_mut(), channel_id, remote_addr);
// try to dispatch a message
let msgs_to_dispatch = vec![BankMsg::Send {
to_address: "my-friend".into(),
amount: coins(123456789, "uatom"),
}
.into()];
let handle_msg = ExecuteMsg::SendMsgs {
channel_id: channel_id.into(),
msgs: msgs_to_dispatch,
};
let info = mock_info(CREATOR, &[]);
let mut res = execute(deps.as_mut(), mock_env(), info, handle_msg).unwrap();
assert_eq!(1, res.messages.len());
let packet = match res.messages.swap_remove(0).msg {
CosmosMsg::Ibc(IbcMsg::SendPacket {
channel_id, data, ..
}) => {
let mut packet = mock_ibc_packet_ack(&channel_id, &1).unwrap();
packet.data = data;
packet
}
o => panic!("Unexpected message: {:?}", o),
};
// and handle the ack
let ack = IbcAcknowledgementWithPacket {
acknowledgement: IbcAcknowledgement::encode_json(&AcknowledgementMsg::Ok(())).unwrap(),
original_packet: packet,
};
let msg = IbcPacketAckMsg::new(ack);
let res = ibc_packet_ack(deps.as_mut(), mock_env(), msg).unwrap();
// no actions expected, but let's check the events to see it was dispatched properly
assert_eq!(0, res.messages.len());
assert_eq!(vec![attr("action", "acknowledge_dispatch")], res.attributes)
}
#[test]
fn send_remote_funds() {
let reflect_channel_id = "channel-1234";
let remote_addr = "account-789";
let transfer_channel_id = "transfer-2";
// init contract
let mut deps = setup();
// channel handshake
connect(deps.as_mut(), reflect_channel_id);
// get feedback from WhoAmI packet
who_am_i_response(deps.as_mut(), reflect_channel_id, remote_addr);
// let's try to send funds to a channel that doesn't exist
let msg = ExecuteMsg::SendFunds {
reflect_channel_id: "random-channel".into(),
transfer_channel_id: transfer_channel_id.into(),
};
let info = mock_info(CREATOR, &coins(12344, "utrgd"));
execute(deps.as_mut(), mock_env(), info, msg).unwrap_err();
// let's try with no sent funds in the message
let msg = ExecuteMsg::SendFunds {
reflect_channel_id: reflect_channel_id.into(),
transfer_channel_id: transfer_channel_id.into(),
};
let info = mock_info(CREATOR, &[]);
execute(deps.as_mut(), mock_env(), info, msg).unwrap_err();
// 3rd times the charm
let msg = ExecuteMsg::SendFunds {
reflect_channel_id: reflect_channel_id.into(),
transfer_channel_id: transfer_channel_id.into(),
};
let info = mock_info(CREATOR, &coins(12344, "utrgd"));
let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap();
assert_eq!(1, res.messages.len());
match &res.messages[0].msg {
CosmosMsg::Ibc(IbcMsg::Transfer {
channel_id,
to_address,
amount,
timeout,
}) => {
assert_eq!(transfer_channel_id, channel_id.as_str());
assert_eq!(remote_addr, to_address.as_str());
assert_eq!(&coin(12344, "utrgd"), amount);
assert!(timeout.block().is_none());
assert!(timeout.timestamp().is_some());
}
o => panic!("unexpected message: {:?}", o),
}
}
}