-
Notifications
You must be signed in to change notification settings - Fork 82
/
packet.rs
511 lines (466 loc) · 17.2 KB
/
packet.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
use crate::prelude::*;
use core::str::FromStr;
use ibc_proto::ibc::core::channel::v1::Packet as RawPacket;
use super::handler::{
acknowledgement::AckPacketResult, recv_packet::RecvPacketResult, send_packet::SendPacketResult,
timeout::TimeoutPacketResult, write_acknowledgement::WriteAckPacketResult,
};
use super::timeout::TimeoutHeight;
use crate::core::ics04_channel::error::{ChannelError, PacketError};
use crate::core::ics24_host::identifier::{ChannelId, PortId};
use crate::timestamp::{Expiry::Expired, Timestamp};
use crate::Height;
/// Enumeration of proof carrying ICS4 message, helper for relayer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PacketMsgType {
Recv,
Ack,
TimeoutUnordered,
TimeoutOrdered,
TimeoutOnClose,
}
#[derive(Clone, Debug)]
pub enum PacketResult {
Send(SendPacketResult),
Recv(RecvPacketResult),
WriteAck(WriteAckPacketResult),
Ack(AckPacketResult),
Timeout(TimeoutPacketResult),
}
#[cfg_attr(
feature = "parity-scale-codec",
derive(
parity_scale_codec::Encode,
parity_scale_codec::Decode,
scale_info::TypeInfo
)
)]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[derive(Clone, Debug)]
pub enum Receipt {
Ok,
}
impl core::fmt::Display for PacketMsgType {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
PacketMsgType::Recv => write!(f, "(PacketMsgType::Recv)"),
PacketMsgType::Ack => write!(f, "(PacketMsgType::Ack)"),
PacketMsgType::TimeoutUnordered => write!(f, "(PacketMsgType::TimeoutUnordered)"),
PacketMsgType::TimeoutOrdered => write!(f, "(PacketMsgType::TimeoutOrdered)"),
PacketMsgType::TimeoutOnClose => write!(f, "(PacketMsgType::TimeoutOnClose)"),
}
}
}
#[cfg_attr(
feature = "parity-scale-codec",
derive(
parity_scale_codec::Encode,
parity_scale_codec::Decode,
scale_info::TypeInfo
)
)]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// The sequence number of a packet enforces ordering among packets from the same source.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Sequence(u64);
impl FromStr for Sequence {
type Err = ChannelError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::from(s.parse::<u64>().map_err(|e| {
ChannelError::InvalidStringAsSequence {
value: s.to_string(),
error: e,
}
})?))
}
}
impl Sequence {
pub fn is_zero(&self) -> bool {
self.0 == 0
}
pub fn increment(&self) -> Sequence {
Sequence(self.0 + 1)
}
}
impl From<u64> for Sequence {
fn from(seq: u64) -> Self {
Sequence(seq)
}
}
impl From<Sequence> for u64 {
fn from(s: Sequence) -> u64 {
s.0
}
}
impl core::fmt::Display for Sequence {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
write!(f, "{}", self.0)
}
}
#[cfg_attr(
feature = "parity-scale-codec",
derive(
parity_scale_codec::Encode,
parity_scale_codec::Decode,
scale_info::TypeInfo
)
)]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Default, Hash, PartialEq, Eq)]
pub struct Packet {
pub sequence: Sequence,
pub port_on_a: PortId,
pub chan_on_a: ChannelId,
pub port_on_b: PortId,
pub chan_on_b: ChannelId,
#[cfg_attr(
feature = "serde",
serde(serialize_with = "crate::serializers::ser_hex_upper")
)]
pub data: Vec<u8>,
pub timeout_height_on_b: TimeoutHeight,
pub timeout_timestamp_on_b: Timestamp,
}
struct PacketData<'a>(&'a [u8]);
impl<'a> core::fmt::Debug for PacketData<'a> {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
write!(formatter, "{:?}", self.0)
}
}
impl core::fmt::Debug for Packet {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
// Remember: if you alter the definition of `Packet`,
// 1. update the formatter debug struct builder calls (return object of
// this function)
// 2. update this destructuring assignment accordingly
let Packet {
sequence: _,
port_on_a: _,
chan_on_a: _,
port_on_b: _,
chan_on_b: _,
data,
timeout_height_on_b: _,
timeout_timestamp_on_b: _,
} = self;
let data_wrapper = PacketData(data);
formatter
.debug_struct("Packet")
.field("sequence", &self.sequence)
.field("source_port", &self.port_on_a)
.field("source_channel", &self.chan_on_a)
.field("destination_port", &self.port_on_b)
.field("destination_channel", &self.chan_on_b)
.field("data", &data_wrapper)
.field("timeout_height", &self.timeout_height_on_b)
.field("timeout_timestamp", &self.timeout_timestamp_on_b)
.finish()
}
}
impl Packet {
/// Checks whether a packet from a
/// [`SendPacket`](crate::core::ics04_channel::events::SendPacket)
/// event is timed-out relative to the current state of the
/// destination chain.
///
/// Checks both for time-out relative to the destination chain's
/// current timestamp `dst_chain_ts` as well as relative to
/// the height `dst_chain_height`.
///
/// Note: a timed-out packet should result in a
/// [`MsgTimeout`](crate::core::ics04_channel::msgs::timeout::MsgTimeout),
/// instead of the common-case where it results in
/// [`MsgRecvPacket`](crate::core::ics04_channel::msgs::recv_packet::MsgRecvPacket).
pub fn timed_out(&self, dst_chain_ts: &Timestamp, dst_chain_height: Height) -> bool {
let height_timed_out = self.timeout_height_on_b.has_expired(dst_chain_height);
let timestamp_timed_out = self.timeout_timestamp_on_b != Timestamp::none()
&& dst_chain_ts.check_expiry(&self.timeout_timestamp_on_b) == Expired;
height_timed_out || timestamp_timed_out
}
}
/// Custom debug output to omit the packet data
impl core::fmt::Display for Packet {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
write!(
f,
"seq:{}, path:{}/{}->{}/{}, toh:{}, tos:{})",
self.sequence,
self.chan_on_a,
self.port_on_a,
self.chan_on_b,
self.port_on_b,
self.timeout_height_on_b,
self.timeout_timestamp_on_b
)
}
}
impl TryFrom<RawPacket> for Packet {
type Error = PacketError;
fn try_from(raw_pkt: RawPacket) -> Result<Self, Self::Error> {
if Sequence::from(raw_pkt.sequence).is_zero() {
return Err(PacketError::ZeroPacketSequence);
}
// Note: ibc-go currently (July 2022) incorrectly treats the timeout
// heights `{revision_number : >0, revision_height: 0}` as valid
// timeouts. However, heights with `revision_height == 0` are invalid in
// Tendermint. We explicitly reject these values because they go against
// the Tendermint spec, and shouldn't be used. To timeout on the next
// revision_number as soon as the chain starts,
// `{revision_number: old_rev + 1, revision_height: 1}`
// should be used.
let packet_timeout_height: TimeoutHeight = raw_pkt
.timeout_height
.try_into()
.map_err(|_| PacketError::InvalidTimeoutHeight)?;
if raw_pkt.data.is_empty() {
return Err(PacketError::ZeroPacketData);
}
let timeout_timestamp_on_b = Timestamp::from_nanoseconds(raw_pkt.timeout_timestamp)
.map_err(PacketError::InvalidPacketTimestamp)?;
Ok(Packet {
sequence: Sequence::from(raw_pkt.sequence),
port_on_a: raw_pkt
.source_port
.parse()
.map_err(PacketError::Identifier)?,
chan_on_a: raw_pkt
.source_channel
.parse()
.map_err(PacketError::Identifier)?,
port_on_b: raw_pkt
.destination_port
.parse()
.map_err(PacketError::Identifier)?,
chan_on_b: raw_pkt
.destination_channel
.parse()
.map_err(PacketError::Identifier)?,
data: raw_pkt.data,
timeout_height_on_b: packet_timeout_height,
timeout_timestamp_on_b,
})
}
}
impl From<Packet> for RawPacket {
fn from(packet: Packet) -> Self {
RawPacket {
sequence: packet.sequence.0,
source_port: packet.port_on_a.to_string(),
source_channel: packet.chan_on_a.to_string(),
destination_port: packet.port_on_b.to_string(),
destination_channel: packet.chan_on_b.to_string(),
data: packet.data,
timeout_height: packet.timeout_height_on_b.into(),
timeout_timestamp: packet.timeout_timestamp_on_b.nanoseconds(),
}
}
}
#[cfg(test)]
pub mod test_utils {
use crate::prelude::*;
use ibc_proto::ibc::core::channel::v1::Packet as RawPacket;
use ibc_proto::ibc::core::client::v1::Height as RawHeight;
use crate::core::ics24_host::identifier::{ChannelId, PortId};
/// Returns a dummy `RawPacket`, for testing only!
pub fn get_dummy_raw_packet(timeout_height: u64, timeout_timestamp: u64) -> RawPacket {
RawPacket {
sequence: 1,
source_port: PortId::default().to_string(),
source_channel: ChannelId::default().to_string(),
destination_port: PortId::default().to_string(),
destination_channel: ChannelId::default().to_string(),
data: vec![0],
timeout_height: Some(RawHeight {
revision_number: 0,
revision_height: timeout_height,
}),
timeout_timestamp,
}
}
}
#[cfg(test)]
mod tests {
use crate::prelude::*;
use test_log::test;
use ibc_proto::ibc::core::channel::v1::Packet as RawPacket;
use ibc_proto::ibc::core::client::v1::Height as RawHeight;
use crate::core::ics04_channel::packet::test_utils::get_dummy_raw_packet;
use crate::core::ics04_channel::packet::Packet;
#[test]
fn packet_try_from_raw() {
struct Test {
name: String,
raw: RawPacket,
want_pass: bool,
}
let proof_height = 10;
let default_raw_packet = get_dummy_raw_packet(proof_height, 0);
let raw_packet_no_timeout_or_timestamp = get_dummy_raw_packet(0, 0);
let mut raw_packet_invalid_timeout_height = get_dummy_raw_packet(0, 0);
raw_packet_invalid_timeout_height.timeout_height = Some(RawHeight {
revision_number: 1,
revision_height: 0,
});
let tests: Vec<Test> = vec![
Test {
name: "Good parameters".to_string(),
raw: default_raw_packet.clone(),
want_pass: true,
},
Test {
// Note: ibc-go currently (July 2022) incorrectly rejects this
// case, even though it is allowed in ICS-4.
name: "Packet with no timeout of timestamp".to_string(),
raw: raw_packet_no_timeout_or_timestamp,
want_pass: true,
},
Test {
name: "Packet with invalid timeout height".to_string(),
raw: raw_packet_invalid_timeout_height,
want_pass: false,
},
Test {
name: "Src port validation: correct".to_string(),
raw: RawPacket {
source_port: "srcportp34".to_string(),
..default_raw_packet.clone()
},
want_pass: true,
},
Test {
name: "Bad src port, name too short".to_string(),
raw: RawPacket {
source_port: "p".to_string(),
..default_raw_packet.clone()
},
want_pass: false,
},
Test {
name: "Bad src port, name too long".to_string(),
raw: RawPacket {
source_port: "abcdefghijasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfadgasgasdfasdfasdfasdfaklmnopqrstuabcdefghijasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfadgasgasdfasdfasdfasdfaklmnopqrstu".to_string(),
..default_raw_packet.clone()
},
want_pass: false,
},
Test {
name: "Dst port validation: correct".to_string(),
raw: RawPacket {
destination_port: "destportsrcp34".to_string(),
..default_raw_packet.clone()
},
want_pass: true,
},
Test {
name: "Bad dst port, name too short".to_string(),
raw: RawPacket {
destination_port: "p".to_string(),
..default_raw_packet.clone()
},
want_pass: false,
},
Test {
name: "Bad dst port, name too long".to_string(),
raw: RawPacket {
destination_port: "abcdefghijasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfadgasgasdfasdfasdfasdfaklmnopqrstuabcdefghijasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfadgasgasdfas".to_string(),
..default_raw_packet.clone()
},
want_pass: false,
},
Test {
name: "Src channel validation: correct".to_string(),
raw: RawPacket {
source_channel: "channel-1".to_string(),
..default_raw_packet.clone()
},
want_pass: true,
},
Test {
name: "Bad src channel, name too short".to_string(),
raw: RawPacket {
source_channel: "p".to_string(),
..default_raw_packet.clone()
},
want_pass: false,
},
Test {
name: "Bad src channel, name too long".to_string(),
raw: RawPacket {
source_channel: "channel-128391283791827398127398791283912837918273981273987912839".to_string(),
..default_raw_packet.clone()
},
want_pass: false,
},
Test {
name: "Dst channel validation: correct".to_string(),
raw: RawPacket {
destination_channel: "channel-34".to_string(),
..default_raw_packet.clone()
},
want_pass: true,
},
Test {
name: "Bad dst channel, name too short".to_string(),
raw: RawPacket {
destination_channel: "p".to_string(),
..default_raw_packet.clone()
},
want_pass: false,
},
Test {
name: "Bad dst channel, name too long".to_string(),
raw: RawPacket {
destination_channel: "channel-128391283791827398127398791283912837918273981273987912839".to_string(),
..default_raw_packet.clone()
},
want_pass: false,
},
// Note: `timeout_height == None` is a quirk of protobuf. In
// `proto3` syntax, all structs are "nullable" by default and are
// represented as `Option<T>`. `ibc-go` defines the protobuf file
// with the extension option `gogoproto.nullable = false`, which
// means that they will always generate a field. It is left
// unspecified what a `None` value means. In this case, I believe it
// is best to assume the obvious semantic of "no timeout".
Test {
name: "Missing timeout height".to_string(),
raw: RawPacket {
timeout_height: None,
..default_raw_packet
},
want_pass: true,
},
];
for test in tests {
let res_msg = Packet::try_from(test.raw.clone());
assert_eq!(
test.want_pass,
res_msg.is_ok(),
"Packet::try_from failed for test {}, \nraw packet {:?} with error {:?}",
test.name,
test.raw,
res_msg.err(),
);
}
}
#[test]
fn to_and_from() {
let raw = get_dummy_raw_packet(15, 0);
let msg = Packet::try_from(raw.clone()).unwrap();
let raw_back = RawPacket::from(msg.clone());
let msg_back = Packet::try_from(raw_back.clone()).unwrap();
assert_eq!(raw, raw_back);
assert_eq!(msg, msg_back);
}
}