1
//! Logic for filtering and selecting channels in order to find suitable channels for a target.
2

            
3
use crate::mgr::AbstractChannel;
4
use crate::mgr::state::{ChannelState, OpenEntry, PendingEntry};
5
use tor_linkspec::{HasChanMethod, HasRelayIds, RelayIds};
6

            
7
/// Returns `true` if the open channel is allowed to be used for a new channel request to the
8
/// target.
9
19
pub(crate) fn open_channel_is_allowed<C: AbstractChannel>(
10
19
    chan: &OpenEntry<C>,
11
19
    target: &(impl HasRelayIds + HasChanMethod),
12
19
) -> bool {
13
19
    Some(chan)
14
        // only usable channels
15
19
        .filter(|entry| entry.channel.is_usable())
16
        // only channels which have *all* the relay ids of `target`
17
15
        .filter(|entry| entry.channel.has_all_relay_ids_from(target))
18
        // only channels that satisfy the torspec rules at
19
        // https://spec.torproject.org/tor-spec/creating-circuits.html#canonical-connections
20
8
        .filter(|entry| {
21
            // Any of:
22
            // - the relay knows that the IP of the connection it's using is canonical because it
23
            //   was listed in the NETINFO cell
24
            // - the IP address matches a requested address (port is ignored)
25
            // TODO: the IP matches the relay address in the consensus
26
8
            entry.channel.is_canonical()
27
                || entry
28
                    .channel
29
                    .peer_matches_chan_method(&target.chan_method())
30
8
        })
31
        .is_some()
32
19
}
33

            
34
/// Returns `true` if the pending channel could possibly be used for a new channel request to the
35
/// target. You still need to verify the final built channel with [`open_channel_is_allowed`] before
36
/// using it.
37
16
pub(crate) fn pending_channel_maybe_allowed(
38
16
    chan: &PendingEntry,
39
16
    target: &(impl HasRelayIds + HasChanMethod),
40
16
) -> bool {
41
    /// An empty [`RelayIds`].
42
    const EMPTY_IDS: RelayIds = RelayIds::empty();
43

            
44
    // TODO RELAY: The comments and behaviour below assume that it's better to create a new channel
45
    // than to wait around for a channel which may or may not end up being usable for `target`. This
46
    // has the benefit that malicious circuit extension requests won't delay legitimate circuit
47
    // extension requests, but also means that we could end up creating more channels than
48
    // necessary. This is different from C-tor, which will wait for a channel even if that channel
49
    // might not end up being usable for `target`. For example in tor's `channel_get_for_extend`,
50
    // tor will wait for an "in progress" channel if all of the following are true:
51
    //
52
    // - The requested ids are a subset of the channel's ids. (Note that in the comments below we
53
    //   require it to be a superset, not a subset.)
54
    // - The requested IPv4 or IPv6 address matches either the channel's IPv4 or IPv6 address. (Note
55
    //   that in the comments below, we require `target`s addresses to exactly match.)
56
    //
57
    // It might be good to re-evaluate what behaviour we want as we implement more channel code.
58
    //
59
    // NOTE (opara): It has been decided that C-tor's approach would be better. See the thread at:
60
    // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/2544#note_3094696
61

            
62
    // We want to avoid returning pending channels that were initially created from malicious
63
    // channel requests (for example from malicious relay-extend requests) that build channels which
64
    // will never complete successfully. Two cases where this can happen are:
65
    // 1. A malicious channel request asks us to build a channel to a target with a correct relay id
66
    //    and address, but also an additional incorrect relay id. Later when the target sends its
67
    //    CERTS cell, all of the relay ids won't match and the channel will fail to build. We don't
68
    //    want to assign non-malicious channel requests to this pending channel that will eventually
69
    //    fail to build.
70
    // 2. A malicious channel request asks us to build a channel to a target with an incorrect
71
    //    address. This pending channel may stall. We don't want to assign non-malicious channel
72
    //    requests to this pending channel that will stall for potentially a long time.
73
16
    Some(chan)
74
        // Only channels where `target`s relay ids are a superset of `entry`s relay ids.
75
        // - Hopefully the built channel will gain the additional ids that are requested by
76
        //   `target`. This should happen in most cases where none of the channels are made
77
        //   maliciously, since the `target` should return all of its relay ids in its CERTS cell.
78
        // - (Addressing 1. above) By only returning pending channels that have a subset of
79
        //   `target`s relay ids, we ensure that the returned pending channel does not have
80
        //   additional incorrect relay ids that will intentionally cause the pending channel to
81
        //   fail.
82
        // - If the built channel does not gain the remaining ids required by `target, then we won't
83
        //   be able to use this channel for the channel request to `target`. But we won't be able
84
        //   to create a new channel either, since we know that that a new channel also won't have
85
        //   all of the relay ids. So this channel request was doomed from the start.
86
        // - If the built channel gains additional ids that `target` doesn't have, that's fine and
87
        //   we can still use the channel for `target`.
88
16
        .filter(|entry| target.has_all_relay_ids_from(&entry.ids))
89
        // Only channels which have the exact same address (IP + Port) list as `target`
90
        // (the two sets of addresses must match exactly).
91
        // - While an EXTEND2 message usually only contains one IPv4 and IPv6 address, `target`
92
        //   (which is a `HasAddrs`) may have more addresses. According to tor-spec, an EXTEND2
93
        //   message can contain multiple IPv4 and IPv6 addresses:
94
        //   > Nodes MUST ignore unrecognized specifiers, and MUST accept multiple instances of
95
        //   > specifiers other than 'legacy identity' and 'Ed25519 identity'. (Nodes SHOULD reject
96
        //   > link specifier lists that include multiple instances of either one of those
97
        //   > specifiers.)
98
        // - (Addressing 2. above) By only returning pending channels that have exactly the same
99
        //   addresses, we ensure that the returned pending channel does not have any incorrect
100
        //   addresses that will cause the pending channel to stall.
101
        // - If the pending channel had additional addresses compared to `target`, the channel could
102
        //   get built using an address that is not valid for `target` and we wouldn't be able to
103
        //   use the built channel.
104
        // - If the pending channel had fewer addresses compared to `target`, the channel would have
105
        //   a lower possibility of building successfully compared to a newly created channel to
106
        //   `target`, so this would not be a good channel for us to return.
107
14
        .filter(|entry| entry.method.has_same_addrs(&target.chan_method()))
108
        // Don't allow a pending channel that has no relay ids. I don't have a good reason for
109
        // excluding this, other than "it seems weird".
110
13
        .filter(|entry| entry.ids != EMPTY_IDS)
111
        .is_some()
112
16
}
113

            
114
/// Returns the best channel among `channels`, all expected to be allowed for the target.
115
83
pub(crate) fn choose_best_allowed_channel<'a, C: AbstractChannel>(
116
83
    channels: impl IntoIterator<Item = &'a ChannelState<C>>,
117
83
) -> Option<&'a ChannelState<C>> {
118
    use ChannelState::*;
119
    use std::cmp::Ordering;
120

            
121
83
    let channels = channels.into_iter();
122

            
123
    /// Compare two channels to determine the better channel.
124
102
    fn choose_channel<C: AbstractChannel>(a: &&ChannelState<C>, b: &&ChannelState<C>) -> Choice {
125
        // TODO: follow `channel_is_better` in C tor
126
102
        match (a, b) {
127
            // if the open channel is not usable, prefer the pending channel
128
54
            (Open(a), Building(_b)) if !a.channel.is_usable() => Choice::Second,
129
            // otherwise prefer the open channel
130
42
            (Open(_a), Building(_b)) => Choice::First,
131

            
132
            // the logic above, but reversed
133
24
            (Building(_), Open(_)) => choose_channel(b, a).reverse(),
134

            
135
            // not much info to help choose when both channels are pending, but this should be rare
136
8
            (Building(_a), Building(_b)) => Choice::Either,
137

            
138
            // both channels are open
139
            (Open(a), Open(b)) => {
140
16
                let a_is_usable = a.channel.is_usable();
141
16
                let b_is_usable = b.channel.is_usable();
142

            
143
                // if neither open channel is usable, don't take preference
144
16
                if !a_is_usable && !b_is_usable {
145
                    return Choice::Either;
146
16
                }
147

            
148
                // prefer a channel that is usable
149
16
                if !a_is_usable {
150
3
                    return Choice::Second;
151
13
                }
152
13
                if !b_is_usable {
153
13
                    return Choice::First;
154
                }
155

            
156
                // Prefer a channel that we see as canonical.
157
                let a_is_canonical = a.channel.is_canonical();
158
                let b_is_canonical = b.channel.is_canonical();
159

            
160
                if a_is_canonical && !b_is_canonical {
161
                    return Choice::First;
162
                }
163
                if !a_is_canonical && b_is_canonical {
164
                    return Choice::Second;
165
                }
166

            
167
                // Prefer a channel that the peer sees as canonical.
168
                let a_is_canonical_to_peer = a.channel.is_canonical_to_peer();
169
                let b_is_canonical_to_peer = b.channel.is_canonical_to_peer();
170

            
171
                if a_is_canonical_to_peer && !b_is_canonical_to_peer {
172
                    return Choice::First;
173
                }
174
                if !a_is_canonical_to_peer && b_is_canonical_to_peer {
175
                    return Choice::Second;
176
                }
177

            
178
                // Prefer the older channel.
179
                match a.channel.age().cmp(&b.channel.age()) {
180
                    Ordering::Greater => return Choice::First,
181
                    Ordering::Less => return Choice::Second,
182
                    Ordering::Equal => {}
183
                }
184

            
185
                // TODO: use number of circuits as tie-breaker?
186

            
187
                Choice::Either
188
            }
189
        }
190
102
    }
191

            
192
    // preferred channels will be ordered higher, and we choose the max
193
83
    channels.max_by(|a, b| match choose_channel(a, b) {
194
45
        Choice::First => Ordering::Greater,
195
25
        Choice::Second => Ordering::Less,
196
8
        Choice::Either => Ordering::Equal,
197
78
    })
198
83
}
199

            
200
/// Similar to [`Ordering`](std::cmp::Ordering), but is easier to reason about when comparing two
201
/// objects that don't have a numeric sense of ordering (ex: returning `Greater` is confusing if the
202
/// ordering isn't numeric).
203
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
204
enum Choice {
205
    /// Choose the first.
206
    First,
207
    /// Choose the second.
208
    Second,
209
    /// Choose either.
210
    Either,
211
}
212

            
213
impl Choice {
214
    /// Reverses the `Choice`.
215
    ///
216
    /// - `First` becomes `Second`.
217
    /// - `Second` becomes `First`.
218
    /// - `Either` becomes `Either`.
219
24
    fn reverse(self) -> Self {
220
24
        match self {
221
17
            Self::First => Self::Second,
222
7
            Self::Second => Self::First,
223
            Self::Either => Self::Either,
224
        }
225
24
    }
226
}
227

            
228
#[cfg(test)]
229
mod test {
230
    // @@ begin test lint list maintained by maint/add_warning @@
231
    #![allow(clippy::bool_assert_comparison)]
232
    #![allow(clippy::clone_on_copy)]
233
    #![allow(clippy::dbg_macro)]
234
    #![allow(clippy::mixed_attributes_style)]
235
    #![allow(clippy::print_stderr)]
236
    #![allow(clippy::print_stdout)]
237
    #![allow(clippy::single_char_pattern)]
238
    #![allow(clippy::unwrap_used)]
239
    #![allow(clippy::unchecked_time_subtraction)]
240
    #![allow(clippy::useless_vec)]
241
    #![allow(clippy::needless_pass_by_value)]
242
    #![allow(clippy::string_slice)] // See arti#2571
243
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
244

            
245
    use super::*;
246

            
247
    use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
248
    use std::sync::Arc;
249
    use std::time::Duration;
250

            
251
    use tor_linkspec::ChannelMethod;
252
    use tor_llcrypto::pk::ed25519::Ed25519Identity;
253
    use tor_llcrypto::pk::rsa::RsaIdentity;
254
    use tor_proto::channel::ChannelPaddingInstructionsUpdates;
255
    use tor_proto::channel::kist::KistParams;
256

            
257
    // Address we can use in tests.
258
    const ADDR_A: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(1, 1, 1, 1), 443));
259

            
260
    #[derive(Debug)]
261
    struct FakeChannel {
262
        usable: bool,
263
        ids: RelayIds,
264
    }
265

            
266
    impl AbstractChannel for FakeChannel {
267
        fn is_canonical(&self) -> bool {
268
            true
269
        }
270
        fn is_canonical_to_peer(&self) -> bool {
271
            unimplemented!()
272
        }
273
        fn peer_matches_chan_method(&self, _method: &tor_linkspec::ChannelMethod) -> bool {
274
            unimplemented!()
275
        }
276
        fn age(&self) -> Duration {
277
            unimplemented!()
278
        }
279
        fn is_usable(&self) -> bool {
280
            self.usable
281
        }
282
        fn duration_unused(&self) -> Option<Duration> {
283
            None
284
        }
285
        fn reparameterize(
286
            &self,
287
            _updates: Arc<ChannelPaddingInstructionsUpdates>,
288
        ) -> tor_proto::Result<()> {
289
            Ok(())
290
        }
291
        fn reparameterize_kist(&self, _kist_params: KistParams) -> tor_proto::Result<()> {
292
            Ok(())
293
        }
294
        fn engage_padding_activities(&self) {}
295
    }
296

            
297
    impl HasRelayIds for FakeChannel {
298
        fn identity(
299
            &self,
300
            key_type: tor_linkspec::RelayIdType,
301
        ) -> Option<tor_linkspec::RelayIdRef<'_>> {
302
            self.ids.identity(key_type)
303
        }
304
    }
305

            
306
    #[derive(Clone, Debug)]
307
    struct FakeBuildSpec {
308
        ids: RelayIds,
309
        addrs: Vec<SocketAddr>,
310
    }
311

            
312
    impl FakeBuildSpec {
313
        fn new(ids: RelayIds, addrs: Vec<SocketAddr>) -> Self {
314
            Self { ids, addrs }
315
        }
316
    }
317

            
318
    impl HasRelayIds for FakeBuildSpec {
319
        fn identity(
320
            &self,
321
            key_type: tor_linkspec::RelayIdType,
322
        ) -> Option<tor_linkspec::RelayIdRef<'_>> {
323
            self.ids.identity(key_type)
324
        }
325
    }
326

            
327
    impl HasChanMethod for FakeBuildSpec {
328
        fn chan_method(&self) -> ChannelMethod {
329
            ChannelMethod::Direct(self.addrs.clone())
330
        }
331
    }
332

            
333
    /// Assert that two `Option<&T>` point to the same data.
334
    macro_rules! assert_opt_ptr_eq {
335
        ($a:expr, $b:expr) => {
336
            assert_opt_ptr_eq!($a, $b,);
337
        };
338
        ($a:expr, $b:expr, $($x:tt)*) => {
339
            assert_eq!($a.map(std::ptr::from_ref), $b.map(std::ptr::from_ref), $($x)*);
340
        };
341
    }
342

            
343
    /// Calls `f` with every permutation of `list`. Don't use with large lists :)
344
    fn with_permutations<T>(list: &[T], mut f: impl FnMut(Vec<&T>)) {
345
        use itertools::Itertools;
346
        for new_list in list.iter().permutations(list.len()) {
347
            f(new_list);
348
        }
349
    }
350

            
351
    /// Helper to make a fake Ed identity from some bytes.
352
    fn ed(a: &[u8]) -> Ed25519Identity {
353
        let mut bytes = [0; 32];
354
        bytes[0..a.len()].copy_from_slice(a);
355
        bytes.into()
356
    }
357

            
358
    /// Helper to make a fake rsa identity from some bytes.
359
    fn rsa(a: &[u8]) -> RsaIdentity {
360
        let mut bytes = [0; 20];
361
        bytes[0..a.len()].copy_from_slice(a);
362
        bytes.into()
363
    }
364

            
365
    /// Helper to build a `RelayIds` to make tests shorter.
366
    fn ids(
367
        rsa: impl Into<Option<RsaIdentity>>,
368
        ed: impl Into<Option<Ed25519Identity>>,
369
    ) -> RelayIds {
370
        let mut ids = tor_linkspec::RelayIdsBuilder::default();
371
        if let Some(rsa) = rsa.into() {
372
            ids.rsa_identity(rsa);
373
        }
374
        if let Some(ed) = ed.into() {
375
            ids.ed_identity(ed);
376
        }
377
        ids.build().unwrap()
378
    }
379

            
380
    /// Create an open channel entry.
381
    fn open_channel<C>(chan: C) -> OpenEntry<C> {
382
        OpenEntry {
383
            channel: Arc::new(chan),
384
            max_unused_duration: Duration::from_secs(0),
385
        }
386
    }
387

            
388
    /// Create a pending channel entry with the given IDs and a channel method that
389
    /// always use `ADDR_A`.
390
    fn pending_channel(ids: RelayIds) -> PendingEntry {
391
        use crate::mgr::state::UniqPendingChanId;
392
        use futures::FutureExt;
393
        use oneshot_fused_workaround as oneshot;
394

            
395
        PendingEntry {
396
            ids,
397
            method: ChannelMethod::Direct(vec![ADDR_A]),
398
            pending: oneshot::channel().1.shared(),
399
            unique_id: UniqPendingChanId::new(),
400
        }
401
    }
402

            
403
    #[test]
404
    fn best_channel_usable_unusable() {
405
        // two channels where only the first is usable
406
        let channels = [
407
            ChannelState::Open(open_channel(FakeChannel {
408
                usable: true,
409
                ids: ids(None, ed(b"A")),
410
            })),
411
            ChannelState::Open(open_channel(FakeChannel {
412
                usable: false,
413
                ids: ids(None, ed(b"A")),
414
            })),
415
        ];
416

            
417
        // should return the usable channel
418
        with_permutations(&channels, |x| {
419
            assert_opt_ptr_eq!(choose_best_allowed_channel(x), Some(&channels[0]));
420
        });
421
    }
422

            
423
    #[test]
424
    fn best_channel_open_pending() {
425
        // a usable open channel and a pending channel
426
        let channels = [
427
            ChannelState::Open(open_channel(FakeChannel {
428
                usable: true,
429
                ids: ids(None, ed(b"A")),
430
            })),
431
            ChannelState::Building(pending_channel(ids(None, ed(b"A")))),
432
        ];
433

            
434
        // should return the open channel
435
        with_permutations(&channels, |x| {
436
            assert_opt_ptr_eq!(choose_best_allowed_channel(x), Some(&channels[0]));
437
        });
438

            
439
        // an unusable open channel and a pending channel
440
        let channels = [
441
            ChannelState::Open(open_channel(FakeChannel {
442
                usable: false,
443
                ids: ids(None, ed(b"A")),
444
            })),
445
            ChannelState::Building(pending_channel(ids(None, ed(b"A")))),
446
        ];
447

            
448
        // should return the pending channel
449
        with_permutations(&channels, |x| {
450
            assert_opt_ptr_eq!(choose_best_allowed_channel(x), Some(&channels[1]));
451
        });
452
    }
453

            
454
    #[test]
455
    fn best_channel_many() {
456
        // some misc channels (as we make `choose_best_allowed_channel` more complex, hopeful we
457
        // can add more channels here)
458
        let channels = [
459
            ChannelState::Open(open_channel(FakeChannel {
460
                usable: false,
461
                ids: ids(None, ed(b"A")),
462
            })),
463
            ChannelState::Open(open_channel(FakeChannel {
464
                usable: true,
465
                ids: ids(None, ed(b"A")),
466
            })),
467
            ChannelState::Building(pending_channel(ids(None, ed(b"A")))),
468
            ChannelState::Building(pending_channel(ids(None, None))),
469
        ];
470

            
471
        // should return the open+usable channel
472
        with_permutations(&channels, |x| {
473
            assert_opt_ptr_eq!(choose_best_allowed_channel(x), Some(&channels[1]));
474
        });
475
    }
476

            
477
    #[test]
478
    fn test_open_channel_is_allowed() {
479
        // target with an ed relay id
480
        let target = FakeBuildSpec::new(ids(None, ed(b"A")), vec![ADDR_A]);
481

            
482
        // not allowed: unusable channel
483
        assert!(!open_channel_is_allowed(
484
            &open_channel(FakeChannel {
485
                usable: false,
486
                ids: ids(None, ed(b"A")),
487
            }),
488
            &target,
489
        ));
490

            
491
        // allowed: usable channel with correct relay id
492
        assert!(open_channel_is_allowed(
493
            &open_channel(FakeChannel {
494
                usable: true,
495
                ids: ids(None, ed(b"A")),
496
            }),
497
            &target,
498
        ));
499

            
500
        // not allowed: usable channel with incorrect relay id
501
        assert!(!open_channel_is_allowed(
502
            &open_channel(FakeChannel {
503
                usable: true,
504
                ids: ids(None, ed(b"B")),
505
            }),
506
            &target,
507
        ));
508

            
509
        // not allowed: usable channel with no relay ids
510
        assert!(!open_channel_is_allowed(
511
            &open_channel(FakeChannel {
512
                usable: true,
513
                ids: ids(None, None),
514
            }),
515
            &target,
516
        ));
517

            
518
        // allowed: usable channel with additional relay id
519
        assert!(open_channel_is_allowed(
520
            &open_channel(FakeChannel {
521
                usable: true,
522
                ids: ids(rsa(b"X"), ed(b"A")),
523
            }),
524
            &target,
525
        ));
526

            
527
        // not allowed: usable channel with missing ed relay id
528
        assert!(!open_channel_is_allowed(
529
            &open_channel(FakeChannel {
530
                usable: true,
531
                ids: ids(rsa(b"X"), None),
532
            }),
533
            &target,
534
        ));
535

            
536
        // target with no relay id
537
        let target = FakeBuildSpec::new(ids(None, None), vec![ADDR_A]);
538

            
539
        // not allowed: unusable channel
540
        assert!(!open_channel_is_allowed(
541
            &open_channel(FakeChannel {
542
                usable: false,
543
                ids: ids(None, None),
544
            }),
545
            &target,
546
        ));
547

            
548
        // allowed: usable channel with no relay ids
549
        assert!(open_channel_is_allowed(
550
            &open_channel(FakeChannel {
551
                usable: true,
552
                ids: ids(None, None),
553
            }),
554
            &target,
555
        ));
556

            
557
        // target with multiple relay ids
558
        let target = FakeBuildSpec::new(ids(rsa(b"X"), ed(b"A")), vec![ADDR_A]);
559

            
560
        // not allowed: unusable channel
561
        assert!(!open_channel_is_allowed(
562
            &open_channel(FakeChannel {
563
                usable: false,
564
                ids: ids(rsa(b"X"), ed(b"A")),
565
            }),
566
            &target,
567
        ));
568

            
569
        // allowed: usable channel with correct relay ids
570
        assert!(open_channel_is_allowed(
571
            &open_channel(FakeChannel {
572
                usable: true,
573
                ids: ids(rsa(b"X"), ed(b"A")),
574
            }),
575
            &target,
576
        ));
577

            
578
        // not allowed: usable channel with partial relay ids
579
        assert!(!open_channel_is_allowed(
580
            &open_channel(FakeChannel {
581
                usable: true,
582
                ids: ids(None, ed(b"A")),
583
            }),
584
            &target,
585
        ));
586
        assert!(!open_channel_is_allowed(
587
            &open_channel(FakeChannel {
588
                usable: true,
589
                ids: ids(rsa(b"X"), None),
590
            }),
591
            &target,
592
        ));
593

            
594
        // not allowed: usable channel with one incorrect relay id
595
        assert!(!open_channel_is_allowed(
596
            &open_channel(FakeChannel {
597
                usable: true,
598
                ids: ids(rsa(b"X"), ed(b"B")),
599
            }),
600
            &target,
601
        ));
602
        assert!(!open_channel_is_allowed(
603
            &open_channel(FakeChannel {
604
                usable: true,
605
                ids: ids(rsa(b"Y"), ed(b"A")),
606
            }),
607
            &target,
608
        ));
609
    }
610

            
611
    #[test]
612
    fn test_pending_channel_maybe_allowed() {
613
        // target with an ed relay id
614
        let target = FakeBuildSpec::new(ids(None, ed(b"A")), vec![ADDR_A]);
615

            
616
        // allowed: channel with same relay id
617
        assert!(pending_channel_maybe_allowed(
618
            &pending_channel(ids(None, ed(b"A"))),
619
            &target,
620
        ));
621

            
622
        // not allowed: channel with additional relay id
623
        assert!(!pending_channel_maybe_allowed(
624
            &pending_channel(ids(rsa(b"X"), ed(b"A"))),
625
            &target,
626
        ));
627

            
628
        // target with multiple relay ids
629
        let target = FakeBuildSpec::new(ids(rsa(b"X"), ed(b"A")), vec![ADDR_A]);
630

            
631
        // allowed: channel with same relay ids
632
        assert!(pending_channel_maybe_allowed(
633
            &pending_channel(ids(rsa(b"X"), ed(b"A"))),
634
            &target,
635
        ));
636

            
637
        // allowed: channel with fewer relay ids
638
        assert!(pending_channel_maybe_allowed(
639
            &pending_channel(ids(None, ed(b"A"))),
640
            &target,
641
        ));
642
        assert!(pending_channel_maybe_allowed(
643
            &pending_channel(ids(rsa(b"X"), None)),
644
            &target,
645
        ));
646

            
647
        // not allowed: channel with no relay ids
648
        assert!(!pending_channel_maybe_allowed(
649
            &pending_channel(ids(None, None)),
650
            &target,
651
        ));
652

            
653
        // target with no relay ids
654
        let target = FakeBuildSpec::new(ids(None, None), vec![ADDR_A]);
655

            
656
        // not allowed: channel with a relay id
657
        assert!(!pending_channel_maybe_allowed(
658
            &pending_channel(ids(None, ed(b"A"))),
659
            &target,
660
        ));
661

            
662
        // not allowed: channel with no relay ids
663
        assert!(!pending_channel_maybe_allowed(
664
            &pending_channel(ids(None, None)),
665
            &target,
666
        ));
667
    }
668
}