ibc-relayer 0.32.2

Implementation of an IBC Relayer in Rust, as a library
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! Custom `serde` deserializer for `FilterMatch`

#![allow(clippy::mutable_key_type)]

use core::fmt;
use core::str::FromStr;
use itertools::Itertools;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;
use std::hash::Hash;

use ibc_relayer_types::applications::transfer::RawCoin;
use ibc_relayer_types::bigint::U256;
use ibc_relayer_types::core::ics24_host::identifier::{ChannelId, PortId};
use ibc_relayer_types::events::IbcEventType;

/// Represents all the filtering policies for packets.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PacketFilter {
    #[serde(flatten)]
    pub channel_policy: ChannelPolicy,
    #[serde(default)]
    pub min_fees: HashMap<ChannelFilterMatch, FeePolicy>,
}

impl Default for PacketFilter {
    /// By default, allows all channels & ports.
    fn default() -> Self {
        Self {
            channel_policy: ChannelPolicy::default(),
            min_fees: HashMap::new(),
        }
    }
}

impl PacketFilter {
    pub fn new(
        channel_policy: ChannelPolicy,
        min_fees: HashMap<ChannelFilterMatch, FeePolicy>,
    ) -> Self {
        Self {
            channel_policy,
            min_fees,
        }
    }

    pub fn allow(filters: Vec<(PortFilterMatch, ChannelFilterMatch)>) -> PacketFilter {
        PacketFilter::new(
            ChannelPolicy::Allow(ChannelFilters::new(filters)),
            HashMap::new(),
        )
    }
}

/// Represents the ways in which packets can be filtered.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
    rename_all = "lowercase",
    tag = "policy",
    content = "list",
    deny_unknown_fields
)]
pub enum ChannelPolicy {
    /// Allow packets from the specified channels.
    Allow(ChannelFilters),
    /// Deny packets from the specified channels.
    Deny(ChannelFilters),
    /// Allow any & all packets.
    AllowAll,
}

/// Represents the policy used to filter incentivized packets.
/// Currently only filtering on `recv_fee` is authorized.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FeePolicy {
    recv: Vec<MinFee>,
}

impl FeePolicy {
    pub fn new(recv: Vec<MinFee>) -> Self {
        Self { recv }
    }

    pub fn should_relay(&self, event_type: IbcEventType, fees: &[RawCoin]) -> bool {
        match event_type {
            IbcEventType::SendPacket => fees
                .iter()
                .any(|fee| self.recv.iter().any(|e| e.is_enough(fee))),
            _ => true,
        }
    }
}

/// Represents the minimum fee authorized when filtering.
/// If no denom is specified, any denom is allowed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MinFee {
    amount: u64,
    denom: Option<String>,
}

impl MinFee {
    pub fn new(amount: u64, denom: Option<String>) -> Self {
        Self { amount, denom }
    }

    pub fn is_enough(&self, fee: &RawCoin) -> bool {
        match self.denom.clone() {
            Some(denom) => fee.amount.0 >= U256::from(self.amount) && denom.eq(&fee.denom),
            None => fee.amount.0 >= U256::from(self.amount),
        }
    }
}

impl Default for ChannelPolicy {
    /// By default, allows all channels & ports.
    fn default() -> Self {
        Self::AllowAll
    }
}

impl ChannelPolicy {
    /// Returns true if the packets can be relayed on the channel with [`PortId`] and [`ChannelId`],
    /// false otherwise.
    pub fn is_allowed(&self, port_id: &PortId, channel_id: &ChannelId) -> bool {
        match self {
            ChannelPolicy::Allow(filters) => filters.matches((port_id, channel_id)),
            ChannelPolicy::Deny(filters) => !filters.matches((port_id, channel_id)),
            ChannelPolicy::AllowAll => true,
        }
    }
}

/// The internal representation of channel filter policies.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ChannelFilters(Vec<(PortFilterMatch, ChannelFilterMatch)>);

impl ChannelFilters {
    /// Create a new filter from the given list of port/channel filters.
    pub fn new(filters: Vec<(PortFilterMatch, ChannelFilterMatch)>) -> Self {
        Self(filters)
    }

    /// Returns the number of filters.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns true if there are no filters, false otherwise.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Indicates whether a match for the given [`PortId`]-[`ChannelId`] pair
    /// exists in the filter policy.
    pub fn matches(&self, channel_port: (&PortId, &ChannelId)) -> bool {
        let (port_id, channel_id) = channel_port;
        self.0.iter().any(|(port_filter, chan_filter)| {
            port_filter.matches(port_id) && chan_filter.matches(channel_id)
        })
    }

    /// Indicates whether this filter policy contains only exact patterns.
    #[inline]
    pub fn is_exact(&self) -> bool {
        self.0.iter().all(|(port_filter, channel_filter)| {
            port_filter.is_exact() && channel_filter.is_exact()
        })
    }

    /// An iterator over the [`PortId`]-[`ChannelId`] pairs that don't contain wildcards.
    pub fn iter_exact(&self) -> impl Iterator<Item = (&PortId, &ChannelId)> {
        self.0.iter().filter_map(|port_chan_filter| {
            if let &(FilterPattern::Exact(ref port_id), FilterPattern::Exact(ref chan_id)) =
                port_chan_filter
            {
                Some((port_id, chan_id))
            } else {
                None
            }
        })
    }
}

impl fmt::Display for ChannelFilters {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            self.0
                .iter()
                .map(|(pid, cid)| format!("{pid}/{cid}"))
                .join(", ")
        )
    }
}

impl Serialize for ChannelFilters {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::SerializeSeq;

        struct Pair<'a> {
            a: &'a FilterPattern<PortId>,
            b: &'a FilterPattern<ChannelId>,
        }

        impl Serialize for Pair<'_> {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                let mut seq = serializer.serialize_seq(Some(2))?;
                seq.serialize_element(self.a)?;
                seq.serialize_element(self.b)?;
                seq.end()
            }
        }

        let mut outer_seq = serializer.serialize_seq(Some(self.0.len()))?;

        for (port, channel) in &self.0 {
            outer_seq.serialize_element(&Pair {
                a: port,
                b: channel,
            })?;
        }

        outer_seq.end()
    }
}

/// Newtype wrapper for expressing wildcard patterns compiled to a [`regex::Regex`].
#[derive(Clone, Debug)]
pub struct Wildcard {
    pattern: String,
    regex: regex::Regex,
}

impl Wildcard {
    pub fn new(pattern: String) -> Result<Self, regex::Error> {
        let escaped = regex::escape(&pattern).replace("\\*", "(?:.*)");
        let regex = format!("^{escaped}$").parse()?;
        Ok(Self { pattern, regex })
    }

    #[inline]
    pub fn is_match(&self, text: &str) -> bool {
        self.regex.is_match(text)
    }
}

impl FromStr for Wildcard {
    type Err = regex::Error;

    fn from_str(pattern: &str) -> Result<Self, Self::Err> {
        Self::new(pattern.to_string())
    }
}

impl fmt::Display for Wildcard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.pattern)
    }
}

impl Serialize for Wildcard {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.pattern)
    }
}

impl PartialEq for Wildcard {
    fn eq(&self, other: &Self) -> bool {
        self.pattern == other.pattern
    }
}

impl Eq for Wildcard {}

impl Hash for Wildcard {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.pattern.hash(state);
    }
}

/// Represents a single channel to be filtered in a [`ChannelFilters`] list.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum FilterPattern<T> {
    /// A channel specified exactly with its [`PortId`] & [`ChannelId`].
    Exact(T),
    /// A glob of channel(s) specified with a wildcard in either or both [`PortId`] & [`ChannelId`].
    Wildcard(Wildcard),
}

impl<T> FilterPattern<T> {
    /// Indicates whether this filter is specified in part with a wildcard.
    pub fn is_wildcard(&self) -> bool {
        matches!(self, Self::Wildcard(_))
    }

    /// Indicates whether this filter is specified as an exact match.
    pub fn is_exact(&self) -> bool {
        matches!(self, Self::Exact(_))
    }

    /// Matches the given value via strict equality if the filter is an `Exact`, or via
    /// wildcard matching if the filter is a `Pattern`.
    pub fn matches(&self, value: &T) -> bool
    where
        T: PartialEq + ToString,
    {
        match self {
            FilterPattern::Exact(v) => value == v,
            FilterPattern::Wildcard(regex) => regex.is_match(&value.to_string()),
        }
    }

    /// Returns the contained value if this filter contains an `Exact` variant, or
    /// `None` if it contains a `Pattern`.
    pub fn exact_value(&self) -> Option<&T> {
        match self {
            FilterPattern::Exact(value) => Some(value),
            FilterPattern::Wildcard(_) => None,
        }
    }
}

impl<T: fmt::Display> fmt::Display for FilterPattern<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FilterPattern::Exact(value) => write!(f, "{value}"),
            FilterPattern::Wildcard(regex) => write!(f, "{regex}"),
        }
    }
}

impl<T> Serialize for FilterPattern<T>
where
    T: ToString,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            FilterPattern::Exact(e) => serializer.serialize_str(&e.to_string()),
            FilterPattern::Wildcard(t) => serializer.serialize_str(&t.to_string()),
        }
    }
}

/// Type alias for a [`FilterPattern`] containing a [`PortId`].
pub type PortFilterMatch = FilterPattern<PortId>;
/// Type alias for a [`FilterPattern`] containing a [`ChannelId`].
pub type ChannelFilterMatch = FilterPattern<ChannelId>;

impl<'de> Deserialize<'de> for PortFilterMatch {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<PortFilterMatch, D::Error> {
        deserializer.deserialize_string(port::PortFilterMatchVisitor)
    }
}

impl<'de> Deserialize<'de> for ChannelFilterMatch {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<ChannelFilterMatch, D::Error> {
        deserializer.deserialize_string(channel::ChannelFilterMatchVisitor)
    }
}

pub(crate) mod port {
    use super::*;

    pub struct PortFilterMatchVisitor;

    impl de::Visitor<'_> for PortFilterMatchVisitor {
        type Value = PortFilterMatch;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("valid PortId or wildcard")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
            let trimmed_v = v.trim();
            if trimmed_v.contains('*') {
                let wildcard = trimmed_v.parse().map_err(E::custom)?;
                Ok(PortFilterMatch::Wildcard(wildcard))
            } else {
                let port_id = PortId::from_str(trimmed_v).map_err(E::custom)?;
                Ok(PortFilterMatch::Exact(port_id))
            }
        }

        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
            self.visit_str(&v)
        }
    }
}

pub(crate) mod channel {
    use super::*;

    pub struct ChannelFilterMatchVisitor;

    impl de::Visitor<'_> for ChannelFilterMatchVisitor {
        type Value = ChannelFilterMatch;

        fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("valid ChannelId or wildcard")
        }

        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
            let trimmed_v = v.trim();
            if trimmed_v.contains('*') {
                let wildcard = trimmed_v.parse().map_err(E::custom)?;
                Ok(ChannelFilterMatch::Wildcard(wildcard))
            } else {
                let channel_id = ChannelId::from_str(trimmed_v.trim()).map_err(E::custom)?;
                Ok(ChannelFilterMatch::Exact(channel_id))
            }
        }

        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
            self.visit_str(&v)
        }
    }
}

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

    #[test]
    fn deserialize_packet_filter_policy() {
        let toml_content = r#"
            policy = 'allow'
            list = [
              ['ica*', '*'],
              ['transfer', 'channel-0'],
            ]
            "#;

        let filter_policy: ChannelPolicy =
            toml::from_str(toml_content).expect("could not parse filter policy");

        dbg!(filter_policy);
    }

    #[test]
    fn serialize_packet_filter_policy() {
        use std::str::FromStr;

        use ibc_relayer_types::core::ics24_host::identifier::{ChannelId, PortId};

        let filter_policy = ChannelFilters(vec![
            (
                FilterPattern::Exact(PortId::from_str("transfer").unwrap()),
                FilterPattern::Exact(ChannelId::from_str("channel-0").unwrap()),
            ),
            (
                FilterPattern::Wildcard("ica*".parse().unwrap()),
                FilterPattern::Wildcard("*".parse().unwrap()),
            ),
        ]);

        let fp = ChannelPolicy::Allow(filter_policy);
        let toml_str = toml::to_string_pretty(&fp).expect("could not serialize packet filter");

        println!("{toml_str}");
    }

    #[test]
    fn channel_filter_iter_exact() {
        let toml_content = r#"
            policy = 'deny'
            list = [
              ['ica', 'channel-*'],
              ['ica*', '*'],
              ['transfer', 'channel-0'],
              ['transfer*', 'channel-1'],
              ['ft-transfer', 'channel-2'],
            ]
            "#;

        let pf: ChannelPolicy =
            toml::from_str(toml_content).expect("could not parse filter policy");

        if let ChannelPolicy::Deny(channel_filters) = pf {
            let exact_matches = channel_filters.iter_exact().collect::<Vec<_>>();
            assert_eq!(
                exact_matches,
                vec![
                    (
                        &PortId::from_str("transfer").unwrap(),
                        &ChannelId::from_str("channel-0").unwrap()
                    ),
                    (
                        &PortId::from_str("ft-transfer").unwrap(),
                        &ChannelId::from_str("channel-2").unwrap()
                    )
                ]
            );
        } else {
            panic!("expected `ChannelPolicy::Deny` variant");
        }
    }

    #[test]
    fn packet_filter_deny_policy() {
        let deny_policy = r#"
            policy = 'deny'
            list = [
              ['ica', 'channel-*'],
              ['ica*', '*'],
              ['transfer', 'channel-0'],
              ['transfer*', 'channel-1'],
              ['ft-transfer', 'channel-2'],
            ]
            "#;

        let pf: ChannelPolicy = toml::from_str(deny_policy).expect("could not parse filter policy");

        assert!(!pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
        assert!(pf.is_allowed(
            &PortId::from_str("transfer").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(!pf.is_allowed(
            &PortId::from_str("ica-1").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
    }

    #[test]
    fn packet_filter_allow_policy() {
        let allow_policy = r#"
            policy = 'allow'
            list = [
              ['ica', 'channel-*'],
              ['ica*', '*'],
              ['transfer', 'channel-0'],
              ['transfer*', 'channel-1'],
              ['ft-transfer', 'channel-2'],
            ]
            "#;

        let pf: ChannelPolicy =
            toml::from_str(allow_policy).expect("could not parse filter policy");

        assert!(pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(!pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
        assert!(!pf.is_allowed(
            &PortId::from_str("transfer-1").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(pf.is_allowed(
            &PortId::from_str("ica-1").unwrap(),
            &ChannelId::from_str("channel-2").unwrap()
        ));
        assert!(pf.is_allowed(
            &PortId::from_str("ica").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
    }

    #[test]
    fn packet_filter_regex() {
        let allow_policy = r#"
            policy = 'allow'
            list = [
              ['transfer*', 'channel-1'],
            ]
            "#;

        let pf: ChannelPolicy =
            toml::from_str(allow_policy).expect("could not parse filter policy");

        assert!(!pf.is_allowed(
            &PortId::from_str("ft-transfer").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
        assert!(!pf.is_allowed(
            &PortId::from_str("ft-transfer-port").unwrap(),
            &ChannelId::from_str("channel-1").unwrap()
        ));
    }

    #[test]
    fn to_string_wildcards() {
        let wildcard = "ica*".parse::<Wildcard>().unwrap();
        assert_eq!(wildcard.to_string(), "ica*".to_string());
    }

    #[test]
    fn test_exact_matches() {
        let allow_policy = r#"
            policy = "allow"
            list = [
                [ "transfer", "channel-88", ], # Standard exact match
                [ "transfer", "channel-476 ", ], # Whitespace abstraction
            ]
            "#;

        let pf: ChannelPolicy =
            toml::from_str(allow_policy).expect("could not parse filter policy");

        let assert_allow = matches!(pf, ChannelPolicy::Allow(filters) if filters.is_exact());
        assert!(assert_allow);
    }
}