1
//! Logic for manipulating a sampled set of guards, along with various
2
//! orderings on that sample.
3

            
4
mod candidate;
5

            
6
use crate::filter::GuardFilter;
7
use crate::guard::{Guard, NewlyConfirmed, Reachable};
8
use crate::skew::SkewObservation;
9
use crate::{
10
    ExternalActivity, GuardParams, GuardUsage, GuardUsageKind, PickGuardError, ids::GuardId,
11
};
12
use crate::{FirstHop, GuardSetSelector};
13
use saturating_time::SaturatingTime as _;
14
use tor_basic_utils::iter::{FilterCount, IteratorExt as _};
15
use tor_basic_utils::onionperf_types::{OnionperfEvent, OnionperfGuardStatus};
16
use tor_error::{internal, warn_report};
17
use tor_linkspec::{ByRelayIds, HasRelayIds};
18

            
19
use itertools::Itertools;
20
use rand::seq::IndexedRandom;
21
use serde::{Deserialize, Serialize};
22
use std::borrow::Cow;
23
use std::collections::{HashMap, HashSet};
24
use tracing::{debug, info, trace};
25
use web_time_compat::{Instant, SystemTime};
26

            
27
#[allow(unused_imports)]
28
pub(crate) use candidate::{Candidate, CandidateStatus, Universe, UniverseRef, WeightThreshold};
29

            
30
/// A set of sampled guards, along with various orderings on subsets
31
/// of the sample.
32
///
33
/// Every guard in a `GuardSet` is considered to be "sampled": that
34
/// is, selected from a network directory at some point in the past.
35
/// The guards in the sample are ordered (roughly) by the time at
36
/// which they were added.  This list is persistent.
37
///
38
/// Any guard which we've successfully used at least once is
39
/// considered "confirmed".  Confirmed guards are ordered (roughly) by
40
/// the time at which we first used them.  This list is persistent.
41
///
42
/// The guards which we would prefer to use are called "primary".
43
/// Primary guards are ordered from most- to least-preferred.
44
/// This list is not persistent, and is re-derived as needed.
45
///
46
/// These lists together define a "preference order".  All primary
47
/// guards come first in preference order.  Then come the non-primary
48
/// confirmed guards, in their confirmed order.  Finally come the
49
/// non-primary, non-confirmed guards, in their sampled order.
50
#[derive(Debug, Default, Clone, Deserialize)]
51
#[serde(from = "GuardSample")]
52
pub(crate) struct GuardSet {
53
    /// Map from identities to guards, for every guard in this sample.
54
    ///
55
    /// The key for each entry is a set of identities which we have
56
    /// good (trustworthy-enough) reason to link together.
57
    ///
58
    /// When we connect to a guard we require it to demonstrate
59
    /// that it has *all* of these identities;
60
    /// and we do pinning, so that we note down the other identities we discover it has,
61
    /// with the intent that we will require them in future.
62
    ///
63
    /// ### Sources of linkage:
64
    ///
65
    ///  * If we connect to a relay and it proves a set of identities,
66
    ///    that necessarily will include at least the ones we have already.
67
    ///    We can add any other identities we have discovered.
68
    ///    Justification: the owners of the old ids have made a statement
69
    ///    (via the connection protocols) that these other ids are also theirs,
70
    ///    and should be required in future.
71
    ///
72
    ///  * If we obtain a (full) descriptor for a relay, and check the
73
    ///    self-signatures by all the identities we have already,
74
    ///    we can add any other identities listed in the descriptor.
75
    ///    Justification: the owners of the old ids have made an explicit statement
76
    ///    that these other ids are also theirs,
77
    ///    and should be required in future.
78
    ///
79
    ///  * For a relay in the netdir, if the netdir links some ids together,
80
    ///    we can combine the entries.
81
    ///    Justification: the netdir is authoritative for netdir-based relays.
82
    ///
83
    ///  * For a configured bridge, if our configuration links some identities,
84
    ///    we must insist on all those identities.
85
    ///    So we combine them.
86
    ///
87
    /// ### Handling of conflicting entries:
88
    ///
89
    /// `ByRelayIds` will implicitly delete conflicting entries,
90
    /// simply forgetting about them.
91
    /// This is OK for netdir relays, since we do not expect this to occur in practice.
92
    ///
93
    /// For bridges, conflicts may in fact occur,
94
    /// since bridge lines are not issued by a single authority,
95
    /// and should be afforded limited trust.
96
    ///
97
    ///  * If the configuration contains bridge lines that mutually conflict,
98
    ///    affected bridge lines should be disregarded,
99
    ///    or the configuration rejected.
100
    ///
101
    ///  * If the configuration contains information which is inconsistent with
102
    ///    our past experience, we should discard the past experiences which
103
    ///    aren't reconcilable with the configuration.
104
    ///
105
    ///  * We may discover a linkage which demonstrates that the configuration
106
    ///    is wrong: for example, two bridge lines for identities X and Y,
107
    ///    but in fact there is only one bridge with both identities.
108
    ///    In this situation it is OK to effectively disregard some the configuration
109
    ///    entries which are at variance with reality, maybe with a warning,
110
    ///    but keeping at least one of every usable id set (actually existing bridge)
111
    ///    would be good.
112
    guards: ByRelayIds<Guard>,
113
    /// Identities of all the guards in the sample, in sample order.
114
    ///
115
    /// This contains the same elements as the keys of `guards`
116
    sample: Vec<GuardId>,
117
    /// Identities of all the confirmed guards in the sample, in
118
    /// confirmed order.
119
    ///
120
    /// This contains a subset of the values in `sample`.
121
    confirmed: Vec<GuardId>,
122
    /// Identities of all the primary guards, in preference order
123
    /// (from best to worst).
124
    ///
125
    /// This contains a subset of the values in `sample`.
126
    primary: Vec<GuardId>,
127
    /// Currently active filter that restricts which guards we can use.
128
    ///
129
    /// Note that all of the lists above (with the exception of `primary`)
130
    /// can hold guards that the filter doesn't permit.  This behavior
131
    /// is meant to give good security behavior in the presence of filters
132
    /// that change over time.
133
    active_filter: GuardFilter,
134

            
135
    /// If true, the active filter is "very restrictive".
136
    filter_is_restrictive: bool,
137

            
138
    /// Set to 'true' whenever something changes that would force us
139
    /// to call 'select_primary_guards()', and cleared whenever we call it.
140
    primary_guards_invalidated: bool,
141

            
142
    /// Fields from the state file that was used to make this `GuardSet` that
143
    /// this version of Arti doesn't understand.
144
    unknown_fields: HashMap<String, JsonValue>,
145
}
146

            
147
/// Which of our lists did a given guard come from?
148
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
149
pub(crate) enum ListKind {
150
    /// A guard that came from the primary guard list.
151
    Primary,
152
    /// A non-primary guard that came from the confirmed guard list.
153
    Confirmed,
154
    /// A non-primary, non-confirmed guard.
155
    Sample,
156
    /// Not a guard at all, but a fallback directory.
157
    Fallback,
158
}
159

            
160
impl ListKind {
161
    /// Return true if this is a primary guard.
162
1133665
    pub(crate) fn is_primary(&self) -> bool {
163
1133665
        self == &ListKind::Primary
164
1133665
    }
165

            
166
    /// Return true if this guard's origin indicates that you can use successful
167
    /// circuits built through it immediately without waiting for any other
168
    /// circuits to succeed or fail.
169
555874
    pub(crate) fn usable_immediately(&self) -> bool {
170
555874
        match self {
171
555862
            ListKind::Primary | ListKind::Fallback => true,
172
12
            ListKind::Confirmed | ListKind::Sample => false,
173
        }
174
555874
    }
175
}
176

            
177
impl GuardSet {
178
    /// Return the lengths of the different elements of the guard set.
179
    ///
180
    /// Used to report bugs or corruption in consistency.
181
980162
    fn inner_lengths(&self) -> (usize, usize, usize, usize) {
182
980162
        (
183
980162
            self.guards.len(),
184
980162
            self.sample.len(),
185
980162
            self.confirmed.len(),
186
980162
            self.primary.len(),
187
980162
        )
188
980162
    }
189

            
190
    /// Remove all elements from this `GuardSet` that ought to be referenced by
191
    /// another element, but which are not.
192
    ///
193
    /// This method only removes corrupted elements and updates IDs in the ID
194
    /// list (possibly adding new IDs); it doesn't add guards or other data.
195
    /// It won't do anything if the `GuardSet` is well-formed.
196
502080
    fn fix_consistency(&mut self) {
197
        /// Remove every element of `id_list` that does not belong to some guard
198
        /// in `guards`, and update the others to have any extra identities
199
        /// listed in `guards`.
200
1506240
        fn fix_id_list(guards: &ByRelayIds<Guard>, id_list: &mut Vec<GuardId>) {
201
5611361
            id_list.retain_mut(|id| match guards.by_all_ids(id) {
202
                Some(guard) => {
203
5611361
                    *id = guard.guard_id().clone();
204
5611361
                    true
205
                }
206
                None => false,
207
5611361
            });
208
1506240
        }
209

            
210
502080
        let sample_set: HashSet<_> = self.sample.iter().collect();
211
4342711
        self.guards.retain(|g| sample_set.contains(g.guard_id()));
212
502080
        fix_id_list(&self.guards, &mut self.sample);
213
502080
        fix_id_list(&self.guards, &mut self.confirmed);
214
502080
        fix_id_list(&self.guards, &mut self.primary);
215
502080
    }
216

            
217
    /// Log an internal error if this `GuardSet` is not internally consistent.
218
    ///
219
    /// If debug assertions are enabled, panic on failure.
220
    ///
221
    /// Incidentally fixes the consistency of this `GuardSet` if needed.
222
490062
    fn assert_consistency(&mut self) {
223
490062
        let len_pre = self.inner_lengths();
224
490062
        self.fix_consistency();
225
490062
        let len_post = self.inner_lengths();
226
490062
        if len_pre != len_post {
227
            // This is the most convenient way to get a backtrace.  We want a backtrace so that
228
            // we can blame the function where the error actually occurred.
229
            let e = internal!("Inner length changed from {len_pre:?} to {len_post:?}");
230
            warn_report!(
231
                e,
232
                "Found guard sample in an inconsistent state, and restored it"
233
            );
234
            debug_assert_eq!(len_pre, len_post);
235
490062
        }
236
490062
    }
237

            
238
    /// Return the guard that has every identity in `id`, if any.
239
555876
    pub(crate) fn get(&self, id: &GuardId) -> Option<&Guard> {
240
555876
        self.guards.by_all_ids(id)
241
555876
    }
242

            
243
    /// Replace the filter used by this `GuardSet` with `filter`.
244
    ///
245
    /// Removes all primary guards that the filter doesn't permit.
246
    ///
247
    /// If `restrictive` is true, this filter is treated as "extremely restrictive".
248
540
    pub(crate) fn set_filter(&mut self, filter: GuardFilter, restrictive: bool) {
249
540
        self.active_filter = filter;
250
540
        self.filter_is_restrictive = restrictive;
251

            
252
540
        self.assert_consistency();
253

            
254
540
        let guards = &self.guards; // avoid borrow issues
255
540
        let filt = &self.active_filter;
256
540
        self.primary.retain(|id| {
257
            guards
258
                .by_all_ids(id)
259
                .map(|g| g.usable() && filt.permits(g))
260
                .unwrap_or(false)
261
        });
262

            
263
540
        self.primary_guards_invalidated = true;
264
540
    }
265

            
266
    /// Return the current filter for this `GuardSet`.
267
9300
    pub(crate) fn filter(&self) -> &GuardFilter {
268
9300
        &self.active_filter
269
9300
    }
270

            
271
    /// Copy non-persistent status from every guard shared with `other`.
272
    ///
273
    /// This is used as part of our reload process when we don't own our state
274
    /// files, and we're reloading in order to find out what the other Arti
275
    /// instance thinks the guards are. At that point, `self` is the set of
276
    /// guards that we just loaded from state, and `other` is our old guards,
277
    /// which we are using only for their status information.
278
2
    pub(crate) fn copy_ephemeral_status_into_newly_loaded_state(&mut self, mut other: GuardSet) {
279
2
        let old_guards = std::mem::take(&mut self.guards);
280
2
        self.guards = old_guards
281
2
            .into_values()
282
10
            .map(|guard| {
283
10
                let id = guard.guard_id();
284

            
285
10
                if let Some(other_guard) = other.guards.remove_exact(id) {
286
7
                    guard.copy_ephemeral_status_into_newly_loaded_state(other_guard)
287
                } else {
288
3
                    guard
289
                }
290
10
            })
291
            .collect();
292
2
    }
293

            
294
    /// Return a serializable state object that can be stored to disk
295
    /// to capture the current state of this GuardSet.
296
19
    fn get_state(&self) -> GuardSample<'_> {
297
19
        let guards = self
298
19
            .sample
299
19
            .iter()
300
35
            .map(|id| Cow::Borrowed(self.guards.by_all_ids(id).expect("Inconsistent state")))
301
            .collect();
302

            
303
19
        GuardSample {
304
19
            guards,
305
19
            confirmed: Cow::Borrowed(&self.confirmed),
306
19
            remaining: self.unknown_fields.clone(),
307
19
        }
308
19
    }
309

            
310
    /// Reconstruct a guard state from its serialized representation.
311
19
    fn from_state(state: GuardSample<'_>) -> Self {
312
19
        let mut guards = ByRelayIds::new();
313
19
        let mut sample = Vec::new();
314
19
        for guard in state.guards {
315
35
            sample.push(guard.guard_id().clone());
316
35
            guards.insert(guard.into_owned());
317
        }
318
19
        let confirmed = state.confirmed.into_owned();
319
19
        let primary = Vec::new();
320
19
        let mut guard_set = GuardSet {
321
19
            guards,
322
19
            sample,
323
19
            confirmed,
324
19
            primary,
325
19
            active_filter: GuardFilter::default(),
326
19
            filter_is_restrictive: false,
327
19
            primary_guards_invalidated: true,
328
19
            unknown_fields: state.remaining,
329
19
        };
330

            
331
        // Fix any inconsistencies in the stored representation.
332
19
        let len_pre = guard_set.inner_lengths();
333
19
        guard_set.fix_consistency();
334
19
        let len_post = guard_set.inner_lengths();
335
19
        if len_pre != len_post {
336
            info!(
337
                "Resolved a consistency issue in stored guard state. Diagnostic codes: {:?}, {:?}",
338
                len_pre, len_post
339
            );
340
19
        }
341
19
        debug!(
342
            n_guards = len_post.0,
343
            n_confirmed = len_post.2,
344
            "Guard set loaded."
345
        );
346

            
347
19
        guard_set
348
19
    }
349

            
350
    /// Return `Ok(true)` if `id` is definitely a member of this set, and
351
    /// `Ok(false)` if it is definitely not a member.
352
    ///
353
    /// If we cannot tell, it's because there is a guard in this sample that has
354
    /// a _subset_ of the IDs in `id`. In that case, we return
355
    /// `Err(guard_ident)`, where `guard_ident`  is the identity of that guard.
356
36
    pub(crate) fn contains(&self, id: &GuardId) -> Result<bool, &GuardId> {
357
36
        let overlapping = self.guards.all_overlapping(id);
358
36
        match &overlapping[..] {
359
            [singleton] => {
360
12
                if singleton.has_all_relay_ids_from(id) {
361
12
                    Ok(true)
362
                } else {
363
                    Err(singleton.guard_id())
364
                }
365
            }
366
24
            _ => Ok(false),
367
        }
368
36
    }
369

            
370
    /// If there are not enough filter-permitted usable guards in this
371
    /// sample (according to the current active filter), then add
372
    /// more, up to the limits allowed by the parameters.
373
    ///
374
    /// This is the only function that adds new guards to the sample.
375
    ///
376
    /// Guards always start out un-confirmed.
377
    ///
378
    /// Return true if any guards were added.
379
12016
    pub(crate) fn extend_sample_as_needed<U: Universe>(
380
12016
        &mut self,
381
12016
        now: SystemTime,
382
12016
        params: &GuardParams,
383
12016
        dir: &U,
384
12016
    ) -> crate::ExtendedStatus {
385
12016
        let mut any_added = crate::ExtendedStatus::No;
386
24022
        while self.extend_sample_inner(now, params, dir) {
387
12006
            any_added = crate::ExtendedStatus::Yes;
388
        }
389
12016
        any_added
390
12016
    }
391

            
392
    /// Implementation helper for extend_sample_as_needed.
393
    ///
394
    /// # Complications
395
    ///
396
    /// For spec conformance, we only consider our filter when selecting new
397
    /// guards if the filter is "very restrictive". That makes it possible that
398
    /// this function will add fewer filter-permitted guards than we had wanted.
399
    /// Because of that, this is a separate function, and
400
    /// extend_sample_as_needed runs it in a loop until it returns false.
401
24022
    fn extend_sample_inner<U: Universe>(
402
24022
        &mut self,
403
24022
        now: SystemTime,
404
24022
        params: &GuardParams,
405
24022
        dir: &U,
406
24022
    ) -> bool {
407
24022
        self.assert_consistency();
408
24022
        let n_filtered_usable = self
409
24022
            .guards
410
24022
            .values()
411
117185
            .filter(|g| {
412
117185
                g.usable()
413
117185
                    && self.active_filter.permits(*g)
414
117185
                    && g.reachable() != Reachable::Unreachable
415
117185
            })
416
            .count();
417
24022
        if n_filtered_usable >= params.min_filtered_sample_size {
418
436
            return false; // We have enough usage guards in our sample.
419
23586
        }
420
23586
        if self.guards.len() >= params.max_sample_size {
421
            return false; // We can't add any more guards to our sample.
422
23586
        }
423

            
424
        // What are the most guards we're willing to have in the sample?
425
23586
        let max_to_add = params.max_sample_size - self.sample.len();
426
23586
        let want_to_add = params.min_filtered_sample_size - n_filtered_usable;
427
23586
        let n_to_add = std::cmp::min(max_to_add, want_to_add);
428

            
429
        let WeightThreshold {
430
            mut current_weight,
431
            maximum_weight,
432
23586
        } = dir.weight_threshold(&self.guards, params);
433

            
434
        // Ask the netdir for a set of guards we could use.
435
23586
        let no_filter = GuardFilter::unfiltered();
436
        let (n_candidates, pre_filter) =
437
23586
            if self.filter_is_restrictive || self.active_filter.is_unfiltered() {
438
23586
                (n_to_add, &self.active_filter)
439
            } else {
440
                // The filter will probably reject a bunch of guards, but we sample
441
                // before filtering, so we make this larger on an ad-hoc basis.
442
                (n_to_add * 3, &no_filter)
443
            };
444

            
445
23586
        let candidates = dir.sample(&self.guards, pre_filter, n_candidates);
446

            
447
        // Add those candidates to the sample.
448
23586
        let mut any_added = false;
449
23586
        let mut n_filtered_usable = n_filtered_usable;
450
23586
        for (candidate, weight) in candidates {
451
            // Don't add any more if we have met the minimal sample size, and we
452
            // have added too much weight.
453
117126
            if current_weight >= maximum_weight
454
92425
                && self.guards.len() >= params.min_filtered_sample_size
455
            {
456
                break;
457
117126
            }
458
117126
            if self.guards.len() >= params.max_sample_size {
459
                // Can't add any more.
460
                break;
461
117126
            }
462
117126
            if n_filtered_usable >= params.min_filtered_sample_size {
463
                // We've reached our target; no need to add more.
464
                break;
465
117126
            }
466
117126
            if self.active_filter.permits(&candidate.owned_target) {
467
117126
                n_filtered_usable += 1;
468
            }
469
117126
            current_weight += weight;
470
117126
            self.add_guard(candidate, now, params);
471
117126
            any_added = true;
472
        }
473
23586
        self.assert_consistency();
474
23586
        any_added
475
24022
    }
476

            
477
    /// Add `relay` as a new guard.
478
    ///
479
    /// Does nothing if it is already a guard, or if there is an existing guard
480
    /// with any of the same ID keys.
481
117126
    fn add_guard(&mut self, relay: Candidate, now: SystemTime, params: &GuardParams) {
482
117126
        let id = GuardId::from_relay_ids(&relay.owned_target);
483
117126
        if self.guards.contains_any_overlapping(&id) {
484
1
            return;
485
117125
        }
486
117125
        debug!(guard_id=?id, "Adding guard to sample.");
487
        // TODO: I don't think onionperf actually needs the guard fingerpint,
488
        // but if it does, add it here.
489
117125
        trace!(
490
            onionperf = true,
491
            event = ?OnionperfEvent::Guard(OnionperfGuardStatus::New),
492
            guard_id = ?id,
493
        );
494
117125
        let guard = Guard::from_candidate(relay, now, params);
495
117125
        self.guards.insert(guard);
496
117125
        self.sample.push(id);
497
117125
        self.primary_guards_invalidated = true;
498
117126
    }
499

            
500
    /// Return the number of our primary guards that are missing directory
501
    /// information in `universe`.
502
    ///
503
    /// Note that "missing directory information" is not the same as "absent":
504
    /// in this case, we  are counting the primary guards where we cannot tell
505
    /// whether they appear in the universe or not because we have not yet
506
    /// downloaded their descriptors.
507
12001
    pub(crate) fn n_primary_without_id_info_in<U: Universe>(&mut self, universe: &U) -> usize {
508
12001
        self.primary
509
12001
            .iter()
510
15
            .filter(|id| {
511
15
                let g = self
512
15
                    .guards
513
15
                    .by_all_ids(*id)
514
15
                    .expect("Inconsistent guard state");
515
15
                g.listed_in(universe).is_none()
516
15
            })
517
            .count()
518
12001
    }
519

            
520
    /// Update the status of every guard  in this sample from a given source.
521
11999
    pub(crate) fn update_status_from_dir<U: Universe>(&mut self, dir: &U) {
522
11999
        let old_guards = std::mem::take(&mut self.guards);
523
11999
        self.guards = old_guards
524
11999
            .into_values()
525
35
            .map(|mut guard| {
526
35
                guard.update_from_universe(dir);
527
35
                guard
528
35
            })
529
            .collect();
530
        // Call "fix consistency", in case any guards got a new ID.
531
11999
        self.fix_consistency();
532
11999
    }
533

            
534
    /// Re-build the list of primary guards.
535
    ///
536
    /// Primary guards are chosen according to preference order over all
537
    /// the guards in the set, restricted by the current filter.
538
    ///
539
    /// TODO: Enumerate all the times when this function needs to be called.
540
    ///
541
    /// TODO: Make sure this is called enough.
542
382565
    pub(crate) fn select_primary_guards(&mut self, params: &GuardParams) {
543
        // TODO-SPEC: This is not 100% what the spec says, but it does match what
544
        // Tor does.  We pick first from the confirmed guards,
545
        // then from any previous primary guards, and then from maybe-reachable
546
        // guards in the sample.
547

            
548
        // Only for logging.
549
382565
        let old_primary = self.primary.clone();
550

            
551
382565
        self.primary = self
552
382565
            // First, we look at the confirmed guards.
553
382565
            .confirmed
554
382565
            .iter()
555
382565
            // Then we consider existing primary guards.
556
382565
            .chain(self.primary.iter())
557
382565
            // Finally, we look at the rest of the sample for guards not marked
558
382565
            // as "unreachable".
559
382565
            .chain(self.reachable_sample_ids())
560
382565
            // We only consider each guard the first time it appears.
561
382565
            .unique()
562
            // We only consider usable guards that the filter allows.
563
1129061
            .filter_map(|id| {
564
1129061
                let g = self
565
1129061
                    .guards
566
1129061
                    .by_all_ids(id)
567
1129061
                    .expect("Inconsistent guard state");
568
1129061
                if g.usable() && self.active_filter.permits(g) {
569
1129061
                    Some(id.clone())
570
                } else {
571
                    None
572
                }
573
1129061
            })
574
            // The first n_primary guards on that list are primary!
575
382565
            .take(params.n_primary)
576
            .collect();
577

            
578
382565
        if self.primary != old_primary {
579
12280
            debug!(old=?old_primary, new=?self.primary, "Updated primary guards.");
580
370285
        }
581

            
582
        // Clear exploratory_circ_pending for all primary guards.
583
382565
        for id in &self.primary {
584
1129061
            self.guards.modify_by_all_ids(id, |guard| {
585
1129061
                guard.note_exploratory_circ(false);
586
1129061
            });
587
        }
588

            
589
        // TODO: Recalculate retry times, perhaps, since we may have changed
590
        // the timeouts?
591

            
592
382565
        self.assert_consistency();
593
382565
        self.primary_guards_invalidated = false;
594
382565
    }
595

            
596
    /// Remove all guards which should expire `now`, according to the settings
597
    /// in `params`.
598
19423
    pub(crate) fn expire_old_guards(&mut self, params: &GuardParams, now: SystemTime) {
599
19423
        self.assert_consistency();
600
19423
        let n_pre = self.guards.len();
601
        // TODO: Might be more ideal to do this after the assert_consistency.
602
19423
        for guard in self.guards.values() {
603
15499
            if guard.is_expired(params, now) {
604
10
                tracing::trace!(
605
                    onionperf = true,
606
                    event = ?OnionperfEvent::Guard(OnionperfGuardStatus::Dropped),
607
                    guard_id = ?guard.guard_id(),
608
                );
609
15489
            }
610
        }
611
19459
        self.guards.retain(|g| !g.is_expired(params, now));
612
19423
        let guards = &self.guards;
613
19459
        self.sample.retain(|id| guards.by_all_ids(id).is_some());
614
19423
        self.confirmed.retain(|id| guards.by_all_ids(id).is_some());
615
19423
        self.primary.retain(|id| guards.by_all_ids(id).is_some());
616
19423
        self.assert_consistency();
617

            
618
19423
        if self.guards.len() < n_pre {
619
2
            let n_expired = n_pre - self.guards.len();
620
2
            debug!(n_expired, "Expired guards as too old.");
621
2
            self.primary_guards_invalidated = true;
622
19421
        }
623
19423
    }
624

            
625
    /// Return an iterator over the Id for every Guard in the sample that
626
    /// is not known to be Unreachable.
627
382565
    fn reachable_sample_ids(&self) -> impl Iterator<Item = &GuardId> {
628
382565
        self.sample.iter().filter(move |id| {
629
35058
            let g = self
630
35058
                .guards
631
35058
                .by_all_ids(*id)
632
35058
                .expect("Inconsistent guard state");
633
35058
            g.reachable() != Reachable::Unreachable
634
35058
        })
635
382565
    }
636

            
637
    /// Return an iterator that yields an element for every guard in
638
    /// this set, in preference order.
639
    ///
640
    /// Each element contains a `ListKind` that describes which list the
641
    /// guard was in, and a `&GuardId` that identifies the guard.
642
    ///
643
    /// Note that this function will return guards that are not
644
    /// accepted by the current active filter: the caller must apply
645
    /// that filter if appropriate.
646
566084
    fn preference_order_ids(&self) -> impl Iterator<Item = (ListKind, &GuardId)> {
647
566084
        self.primary
648
566084
            .iter()
649
578114
            .map(|id| (ListKind::Primary, id))
650
566084
            .chain(self.confirmed.iter().map(|id| (ListKind::Confirmed, id)))
651
566320
            .chain(self.sample.iter().map(|id| (ListKind::Sample, id)))
652
578640
            .unique_by(|(_, id)| *id)
653
566084
    }
654

            
655
    /// Like `preference_order_ids`, but yields `&Guard` instead of `&GuardId`.
656
566084
    fn preference_order(&self) -> impl Iterator<Item = (ListKind, &Guard)> + '_ {
657
566084
        self.preference_order_ids()
658
578344
            .filter_map(move |(p, id)| self.guards.by_all_ids(id).map(|g| (p, g)))
659
566084
    }
660

            
661
    /// Return true if `guard_id` is an identity subset for any primary guard in this set.
662
566221
    fn guard_is_primary(&self, guard_id: &GuardId) -> bool {
663
        // (This could be yes/no/maybe.)
664

            
665
        // This is O(n), but the list is short.
666
566221
        self.primary
667
566221
            .iter()
668
584006
            .any(|p| p.has_all_relay_ids_from(guard_id))
669
566221
    }
670

            
671
    /// For every guard that has been marked as `Unreachable` for too long,
672
    /// mark it as `Unknown`.
673
555874
    pub(crate) fn consider_all_retries(&mut self, now: Instant) {
674
555874
        let old_guards = std::mem::take(&mut self.guards);
675
555874
        self.guards = old_guards
676
555874
            .into_values()
677
5457192
            .map(|mut guard| {
678
5457192
                guard.consider_retry(now);
679
5457192
                guard
680
5457192
            })
681
            .collect();
682
555874
    }
683

            
684
    /// Return the earliest time at which any guard will be retriable.
685
10121
    pub(crate) fn next_retry(&self, usage: &GuardUsage) -> Option<Instant> {
686
10121
        self.guards
687
10121
            .values()
688
5
            .filter_map(|g| g.next_retry(usage))
689
            .min()
690
10121
    }
691

            
692
    /// Mark every `Unreachable` primary guard as `Unknown`.
693
1
    pub(crate) fn mark_primary_guards_retriable(&mut self) {
694
1
        for id in &self.primary {
695
2
            self.guards
696
2
                .modify_by_all_ids(id, |guard| guard.mark_retriable());
697
        }
698
1
    }
699

            
700
    /// Return true if all of our primary guards are currently marked
701
    /// unreachable.
702
4
    pub(crate) fn all_primary_guards_are_unreachable(&mut self) -> bool {
703
4
        self.primary
704
4
            .iter()
705
6
            .flat_map(|id| self.guards.by_all_ids(id))
706
6
            .all(|g| g.reachable() == Reachable::Unreachable)
707
4
    }
708

            
709
    /// Mark every `Unreachable` guard as `Unknown`.
710
    pub(crate) fn mark_all_guards_retriable(&mut self) {
711
        let old_guards = std::mem::take(&mut self.guards);
712
        self.guards = old_guards
713
            .into_values()
714
            .map(|mut guard| {
715
                guard.mark_retriable();
716
                guard
717
            })
718
            .collect();
719
    }
720

            
721
    /// Record that an attempt has begun to use the guard with
722
    /// `guard_id`.
723
555884
    pub(crate) fn record_attempt(&mut self, guard_id: &GuardId, now: Instant) {
724
555884
        let is_primary = self.guard_is_primary(guard_id);
725
555884
        self.guards.modify_by_all_ids(guard_id, |guard| {
726
555884
            guard.record_attempt(now);
727

            
728
555884
            if !is_primary {
729
17
                guard.note_exploratory_circ(true);
730
555867
            }
731
555884
        });
732
555884
    }
733

            
734
    /// Record that an attempt to use the guard with `guard_id` has just
735
    /// succeeded.
736
    ///
737
    /// If `how` is provided, it's an operation from outside the crate that the
738
    /// guard succeeded at doing.
739
10248
    pub(crate) fn record_success(
740
10248
        &mut self,
741
10248
        guard_id: &GuardId,
742
10248
        params: &GuardParams,
743
10248
        how: Option<ExternalActivity>,
744
10248
        now: SystemTime,
745
10248
    ) {
746
10248
        self.assert_consistency();
747
10248
        self.guards.modify_by_all_ids(guard_id, |guard| match how {
748
6
            Some(external) => guard.record_external_success(external),
749
            None => {
750
10242
                let newly_confirmed = guard.record_success(now, params);
751

            
752
10242
                if newly_confirmed == NewlyConfirmed::Yes {
753
734
                    self.confirmed.push(guard_id.clone());
754
734
                    self.primary_guards_invalidated = true;
755
9508
                }
756
            }
757
10248
        });
758
10248
        self.assert_consistency();
759
10248
    }
760

            
761
    /// Record that an attempt to use the guard with `guard_id` has just failed.
762
    ///
763
35
    pub(crate) fn record_failure(
764
35
        &mut self,
765
35
        guard_id: &GuardId,
766
35
        how: Option<ExternalActivity>,
767
35
        now: Instant,
768
35
    ) {
769
35
        trace!(
770
            onionperf = true,
771
            event = ?OnionperfEvent::Guard(OnionperfGuardStatus::Down),
772
            ?guard_id,
773
        );
774
        // TODO use instant uniformly for in-process, and systemtime for storage?
775
35
        let is_primary = self.guard_is_primary(guard_id);
776
35
        self.guards.modify_by_all_ids(guard_id, |guard| match how {
777
6
            Some(external) => guard.record_external_failure(external, now),
778
29
            None => guard.record_failure(now, is_primary),
779
35
        });
780
35
    }
781

            
782
    /// Record that an attempt to use the guard with `guard_id` has
783
    /// just been abandoned, without learning whether it succeeded or failed.
784
352949
    pub(crate) fn record_attempt_abandoned(&mut self, guard_id: &GuardId) {
785
352949
        self.guards
786
352949
            .modify_by_all_ids(guard_id, |guard| guard.note_exploratory_circ(false));
787
352949
    }
788

            
789
    /// Record that an attempt to use the guard with `guard_id` has
790
    /// just failed in a way that we could not definitively attribute to
791
    /// the guard.
792
    pub(crate) fn record_indeterminate_result(&mut self, guard_id: &GuardId) {
793
        self.guards.modify_by_all_ids(guard_id, |guard| {
794
            guard.note_exploratory_circ(false);
795
            guard.record_indeterminate_result();
796
        });
797
    }
798

            
799
    /// Record that a given guard has told us about clock skew.
800
    pub(crate) fn record_skew(&mut self, guard_id: &GuardId, observation: SkewObservation) {
801
        self.guards
802
            .modify_by_all_ids(guard_id, |guard| guard.note_skew(observation));
803
    }
804

            
805
    /// Return an iterator over all stored clock skew observations.
806
    pub(crate) fn skew_observations(&self) -> impl Iterator<Item = &SkewObservation> {
807
        self.guards.values().filter_map(|g| g.skew())
808
    }
809

            
810
    /// Return whether the circuit manager can be allowed to use a
811
    /// circuit with the `guard_id`.
812
    ///
813
    /// Return `Some(bool)` if the circuit is usable, and `None` if we
814
    /// cannot yet be sure.
815
10302
    pub(crate) fn circ_usability_status(
816
10302
        &self,
817
10302
        guard_id: &GuardId,
818
10302
        usage: &GuardUsage,
819
10302
        params: &GuardParams,
820
10302
        now: Instant,
821
10302
    ) -> Option<bool> {
822
        // TODO-SPEC: This isn't what the spec says.  The spec is phrased
823
        // in terms of circuits blocking circuits, whereas this algorithm is
824
        // about guards blocking guards.
825
        //
826
        // Also notably, the spec also says:
827
        //
828
        // * Among guards that do not appear in {CONFIRMED_GUARDS},
829
        // {is_pending}==true guards have higher priority.
830
        // * Among those, the guard with earlier {last_tried_connect} time
831
        // has higher priority.
832
        // * Finally, among guards that do not appear in
833
        // {CONFIRMED_GUARDS} with {is_pending==false}, all have equal
834
        // priority.
835
        //
836
        // I believe this approach is fine too, but we ought to document it.
837

            
838
10302
        if self.guard_is_primary(guard_id) {
839
            // Circuits built to primary guards are always usable immediately.
840
            //
841
            // This has to be a special case, since earlier primary guards
842
            // don't block later ones.
843
10292
            return Some(true);
844
10
        }
845

            
846
        // Assuming that the guard is _not_ primary, then the rule is
847
        // fairly simple: we can use the guard if all the guards we'd
848
        // _rather_ use are either down, or have had their circuit
849
        // attempts pending for too long.
850

            
851
        // We treat a more-preferred guard with an exploratory circuit created
852
        // _after_ this cutoff as preventing us from using `guard_id`.
853
10
        let cutoff = now.saturating_sub(params.np_connect_timeout);
854

            
855
10
        for (src, guard) in self.preference_order() {
856
26
            if guard.guard_id() == guard_id {
857
7
                return Some(true);
858
19
            }
859
19
            if guard.usable() && self.active_filter.permits(guard) && guard.conforms_to_usage(usage)
860
            {
861
19
                match (src, guard.reachable()) {
862
2
                    (_, Reachable::Reachable) => return Some(false),
863
16
                    (_, Reachable::Unreachable) => (),
864
                    (ListKind::Primary, Reachable::Untried | Reachable::Retriable) => {
865
                        return Some(false);
866
                    }
867
                    (_, Reachable::Untried | Reachable::Retriable) => {
868
1
                        if guard.exploratory_attempt_after(cutoff) {
869
1
                            return None;
870
                        }
871
                    }
872
                }
873
            }
874
        }
875

            
876
        // This guard is not even listed.
877
        Some(false)
878
10302
    }
879

            
880
    /// Try to select a guard for a given `usage`.
881
    ///
882
    /// On success, returns the kind of guard that we got, and its filtered
883
    /// representation in a form suitable for use as a first hop.
884
    ///
885
    /// Label the returned guard as having come from `sample_id`.
886
    //
887
    // NOTE (nickm): I wish that we didn't have to take sample_id as an input,
888
    // but the alternative would be storing it as a member of `GuardSet`, which
889
    // makes things very complicated.
890
565994
    pub(crate) fn pick_guard(
891
565994
        &self,
892
565994
        sample_id: &GuardSetSelector,
893
565994
        usage: &GuardUsage,
894
565994
        params: &GuardParams,
895
565994
        now: Instant,
896
565994
    ) -> Result<(ListKind, FirstHop), PickGuardError> {
897
565994
        let (list_kind, id) = self.pick_guard_id(usage, params, now)?;
898
555874
        let first_hop = self
899
555874
            .get(&id)
900
555874
            .expect("Somehow selected a guard we don't know!")
901
555874
            .get_external_rep(sample_id.clone());
902
555874
        let first_hop = self.active_filter.modify_hop(first_hop)?;
903

            
904
555874
        Ok((list_kind, first_hop))
905
565994
    }
906

            
907
    /// Try to select a guard for a given `usage`.
908
    ///
909
    /// On success, returns the kind of guard that we got, and its identity.
910
566074
    fn pick_guard_id(
911
566074
        &self,
912
566074
        usage: &GuardUsage,
913
566074
        params: &GuardParams,
914
566074
        now: Instant,
915
566074
    ) -> Result<(ListKind, GuardId), PickGuardError> {
916
566074
        debug_assert!(!self.primary_guards_invalidated);
917
566074
        let n_options = match usage.kind {
918
10900
            GuardUsageKind::OneHopDirectory => params.dir_parallelism,
919
555174
            GuardUsageKind::Data => params.data_parallelism,
920
        };
921

            
922
        // Counts of how many elements were rejected by which of the filters
923
        // below.
924
        //
925
        // Note that since we use `Iterator::take`, these counts won't cover the
926
        // whole guard sample on the successful case: only in the failing case,
927
        // when we fail to find any candidates.
928
566074
        let mut running = FilterCount::default();
929
566074
        let mut pending = FilterCount::default();
930
566074
        let mut suitable = FilterCount::default();
931
566074
        let mut filtered = FilterCount::default();
932

            
933
566074
        let mut options: Vec<_> = self
934
566074
            .preference_order()
935
            // Discard the guards that are down or unusable, and see if any
936
            // are left.
937
578318
            .filter_cnt(&mut running, |(_, g)| {
938
578318
                g.usable()
939
578318
                    && g.reachable() != Reachable::Unreachable
940
578138
                    && g.ready_for_usage(usage, now)
941
578318
            })
942
            // Now remove those that are excluded because we're already trying
943
            // them on an exploratory basis.
944
578132
            .filter_cnt(&mut pending, |(_, g)| !g.exploratory_circ_pending())
945
            // ...or because they don't support the operation we're
946
            // attempting...
947
578125
            .filter_cnt(&mut suitable, |(_, g)| g.conforms_to_usage(usage))
948
            // ... or because we specifically filtered them out.
949
577729
            .filter_cnt(&mut filtered, |(_, g)| self.active_filter.permits(*g))
950
            // We only consider the first n_options such guards.
951
566074
            .take(n_options)
952
            .collect();
953

            
954
566074
        if options.iter().any(|(src, _)| src.is_primary()) {
955
            // If there are any primary guards, we only consider those.
956
577712
            options.retain(|(src, _)| src.is_primary());
957
        } else {
958
            // If there are no primary guards, parallelism doesn't apply.
959
10138
            options.truncate(1);
960
        }
961

            
962
566074
        match options.choose(&mut rand::rng()) {
963
555953
            Some((src, g)) => Ok((*src, g.guard_id().clone())),
964
            None => {
965
10121
                let retry_at = if running.n_accepted == 0 {
966
10121
                    self.next_retry(usage)
967
                } else {
968
                    None
969
                };
970
10121
                Err(PickGuardError::AllGuardsDown {
971
10121
                    retry_at,
972
10121
                    running,
973
10121
                    pending,
974
10121
                    suitable,
975
10121
                    filtered,
976
10121
                })
977
            }
978
        }
979
566074
    }
980

            
981
    /// Return the guards whose bridge descriptors we should request, given our
982
    /// current configuration and status.
983
    ///
984
    /// (The output of this function is not reasonable unless this is a Bridge
985
    /// sample.)
986
    #[cfg(feature = "bridge-client")]
987
    pub(crate) fn descriptors_to_request(&self, now: Instant, params: &GuardParams) -> Vec<&Guard> {
988
        /// This constant is here to improve our odds that we can get a working
989
        /// bridge if we have any per-circuit filters that would prevent us from
990
        /// using our preferred bridge.
991
        const MINIMUM: usize = 2;
992

            
993
        let maximum = std::cmp::max(params.data_parallelism, MINIMUM);
994
        let data_usage = GuardUsage::default();
995

            
996
        // Here we duplicate some but not all of the restrictions above in
997
        // pick_guard_id.  We skip those restrictions that are specific to only
998
        // certain kinds of circuits, and those that are temporary restrictions
999
        // encouraging us to try more guards.
        //
        // TODO: we may want to refactor this code and the code in pick_guard_id
        // above to share a single function.  Before we do that, however, I want
        // to experiment with this logic a bit to make sure that it works and
        // doesn't give us surprising results.
        self.preference_order()
            .filter(|(_, g)| {
                g.usable()
                    && g.reachable() != Reachable::Unreachable
                    && g.ready_for_usage(&data_usage, now)
                    && self.active_filter.permits(*g)
            })
            .take(maximum)
            .map(|(_, g)| g)
            .collect()
    }
}
use serde::Serializer;
use tor_persist::JsonValue;
/// State object used to serialize and deserialize a [`GuardSet`].
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub(crate) struct GuardSample<'a> {
    /// Equivalent to `GuardSet.guards.values()`, except in sample order.
    guards: Vec<Cow<'a, Guard>>,
    /// The identities for the confirmed members of `guards`, in confirmed order.
    confirmed: Cow<'a, [GuardId]>,
    /// Other data from the state file that this version of Arti doesn't recognize.
    #[serde(flatten)]
    remaining: HashMap<String, JsonValue>,
}
impl Serialize for GuardSet {
18
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
18
    where
18
        S: Serializer,
    {
18
        GuardSample::from(self).serialize(serializer)
18
    }
}
impl<'a> From<&'a GuardSet> for GuardSample<'a> {
19
    fn from(guards: &'a GuardSet) -> Self {
19
        guards.get_state()
19
    }
}
impl<'a> From<GuardSample<'a>> for GuardSet {
19
    fn from(sample: GuardSample) -> Self {
19
        GuardSet::from_state(sample)
19
    }
}
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use tor_linkspec::{HasRelayIds, RelayIdType};
    use tor_netdir::NetDir;
    use tor_netdoc::doc::netstatus::RelayBandwidth;
    use tor_netdoc::types::relay_flags::RelayFlag;
    use web_time_compat::{InstantExt, SystemTimeExt};
    use super::*;
    use crate::FirstHopId;
    use std::time::Duration;
    fn netdir() -> NetDir {
        use tor_netdir::testnet;
        testnet::construct_netdir().unwrap_if_sufficient().unwrap()
    }
    #[test]
    fn sample_test() {
        // Make a test network that gives every relay equal weight, and which
        // has 20 viable (Guard + V2Dir + DirCache=2) candidates.  Otherwise the
        // calculation of collision probability at the end of this function is
        // too tricky.
        let netdir = tor_netdir::testnet::construct_custom_netdir(|idx, builder, _| {
            // Give every node equal bandwidth.
            builder.rs.weight(RelayBandwidth::Measured(1000));
            // The default network has 40 relays, and the first 10 are
            // not Guard by default.
            if idx >= 10 {
                builder.rs.add_flags(RelayFlag::Guard);
                if idx >= 20 {
                    builder.rs.protos("DirCache=2".parse().unwrap());
                } else {
                    builder.rs.protos("".parse().unwrap());
                }
            }
        })
        .unwrap()
        .unwrap_if_sufficient()
        .unwrap();
        // Make sure that we got the numbers we expected.
        assert_eq!(40, netdir.relays().count());
        assert_eq!(
            30,
            netdir
                .relays()
                .filter(|r| r.low_level_details().is_suitable_as_guard())
                .count()
        );
        assert_eq!(
            20,
            netdir
                .relays()
                .filter(|r| r.low_level_details().is_suitable_as_guard()
                    && r.low_level_details().is_dir_cache())
                .count()
        );
        let params = GuardParams {
            min_filtered_sample_size: 5,
            max_sample_bw_fraction: 1.0,
            ..GuardParams::default()
        };
        let mut samples: Vec<HashSet<GuardId>> = Vec::new();
        for _ in 0..3 {
            let mut guards = GuardSet::default();
            guards.extend_sample_as_needed(SystemTime::get(), &params, &netdir);
            assert_eq!(guards.guards.len(), params.min_filtered_sample_size);
            assert_eq!(guards.confirmed.len(), 0);
            assert_eq!(guards.primary.len(), 0);
            guards.assert_consistency();
            // make sure all the guards are okay.
            for guard in guards.guards.values() {
                let id = FirstHopId::in_sample(GuardSetSelector::Default, guard.guard_id().clone());
                let relay = id.get_relay(&netdir).unwrap();
                assert!(relay.low_level_details().is_suitable_as_guard());
                assert!(relay.low_level_details().is_dir_cache());
                assert!(guards.guards.by_all_ids(&relay).is_some());
                {
                    assert!(!guard.is_expired(&params, SystemTime::get()));
                }
            }
            // Make sure that the sample doesn't expand any further.
            guards.extend_sample_as_needed(SystemTime::get(), &params, &netdir);
            assert_eq!(guards.guards.len(), params.min_filtered_sample_size);
            guards.assert_consistency();
            samples.push(guards.sample.into_iter().collect());
        }
        // The probability of getting the same sample 3 times in a row is (20 choose 5)^-2,
        // which is pretty low.  (About 1 in 240 million.)
        assert!(samples[0] != samples[1] || samples[1] != samples[2]);
    }
    #[test]
    fn persistence() {
        let netdir = netdir();
        let params = GuardParams {
            min_filtered_sample_size: 5,
            ..GuardParams::default()
        };
        let t1 = SystemTime::get();
        let t2 = t1 + Duration::from_secs(20);
        let mut guards = GuardSet::default();
        guards.extend_sample_as_needed(t1, &params, &netdir);
        // Pick a guard and mark it as confirmed.
        let id1 = guards.sample[0].clone();
        guards.record_success(&id1, &params, None, t2);
        assert_eq!(&guards.confirmed, std::slice::from_ref(&id1));
        // Encode the guards, then decode them.
        let state: GuardSample = (&guards).into();
        let guards2: GuardSet = state.into();
        assert_eq!(&guards2.sample, &guards.sample);
        assert_eq!(&guards2.confirmed, &guards.confirmed);
        assert_eq!(&guards2.confirmed, &[id1]);
        assert_eq!(
            guards
                .guards
                .values()
                .map(Guard::guard_id)
                .collect::<HashSet<_>>(),
            guards2
                .guards
                .values()
                .map(Guard::guard_id)
                .collect::<HashSet<_>>()
        );
        for g in guards.guards.values() {
            let g2 = guards2.guards.by_all_ids(g.guard_id()).unwrap();
            assert_eq!(format!("{:?}", g), format!("{:?}", g2));
        }
    }
    #[test]
    fn select_primary() {
        let netdir = netdir();
        let params = GuardParams {
            min_filtered_sample_size: 5,
            n_primary: 4,
            ..GuardParams::default()
        };
        let t1 = SystemTime::get();
        let t2 = t1 + Duration::from_secs(20);
        let t3 = t2 + Duration::from_secs(30);
        let mut guards = GuardSet::default();
        guards.extend_sample_as_needed(t1, &params, &netdir);
        // Pick a guard and mark it as confirmed.
        let id3 = guards.sample[3].clone();
        guards.record_success(&id3, &params, None, t2);
        assert_eq!(&guards.confirmed, std::slice::from_ref(&id3));
        let id1 = guards.sample[1].clone();
        guards.record_success(&id1, &params, None, t3);
        assert_eq!(&guards.confirmed, &[id3.clone(), id1.clone()]);
        // Select primary guards and make sure we're obeying the rules.
        guards.select_primary_guards(&params);
        assert_eq!(guards.primary.len(), 4);
        assert_eq!(&guards.primary[0], &id3);
        assert_eq!(&guards.primary[1], &id1);
        let p3 = guards.primary[2].clone();
        let p4 = guards.primary[3].clone();
        assert_eq!(
            [id1.clone(), id3.clone(), p3.clone(), p4.clone()]
                .iter()
                .unique()
                .count(),
            4
        );
        // Mark another guard as confirmed and see that the list changes to put
        // that guard right after the previously confirmed guards, but we keep
        // one of the previous unconfirmed primary guards.
        guards.record_success(&p4, &params, None, t3);
        assert_eq!(&guards.confirmed, &[id3.clone(), id1.clone(), p4.clone()]);
        guards.select_primary_guards(&params);
        assert_eq!(guards.primary.len(), 4);
        assert_eq!(&guards.primary[0], &id3);
        assert_eq!(&guards.primary[1], &id1);
        assert_eq!(&guards.primary, &[id3, id1, p4, p3]);
    }
    #[test]
    fn expiration() {
        let netdir = netdir();
        let params = GuardParams::default();
        let t1 = SystemTime::get();
        let mut guards = GuardSet::default();
        guards.extend_sample_as_needed(t1, &params, &netdir);
        // note that there are only 10 Guard+V2Dir nodes in the netdir().
        assert_eq!(guards.sample.len(), 10);
        // Mark one guard as confirmed; it will have a different timeout.
        // Pick a guard and mark it as confirmed.
        let id1 = guards.sample[0].clone();
        guards.record_success(&id1, &params, None, t1);
        assert_eq!(&guards.confirmed, &[id1]);
        let one_day = Duration::from_secs(86400);
        guards.expire_old_guards(&params, t1 + one_day * 30);
        assert_eq!(guards.sample.len(), 10); // nothing has expired.
        // This is long enough to make sure that the confirmed guard has expired.
        guards.expire_old_guards(&params, t1 + one_day * 70);
        assert_eq!(guards.sample.len(), 9);
        guards.expire_old_guards(&params, t1 + one_day * 200);
        assert_eq!(guards.sample.len(), 0);
    }
    #[test]
    fn sampling_and_usage() {
        let netdir = netdir();
        let params = GuardParams {
            min_filtered_sample_size: 5,
            n_primary: 2,
            ..GuardParams::default()
        };
        let st1 = SystemTime::get();
        let i1 = Instant::get();
        let sec = Duration::from_secs(1);
        let mut guards = GuardSet::default();
        guards.extend_sample_as_needed(st1, &params, &netdir);
        guards.select_primary_guards(&params);
        // First guard: try it, and let it fail.
        let usage = crate::GuardUsageBuilder::default().build().unwrap();
        let id1 = guards.primary[0].clone();
        let id2 = guards.primary[1].clone();
        let (src, id) = guards.pick_guard_id(&usage, &params, i1).unwrap();
        assert_eq!(src, ListKind::Primary);
        assert_eq!(&id, &id1);
        guards.record_attempt(&id, i1);
        guards.record_failure(&id, None, i1 + sec);
        // Second guard: try it, and try it again, and have it fail.
        let (src, id) = guards.pick_guard_id(&usage, &params, i1 + sec).unwrap();
        assert_eq!(src, ListKind::Primary);
        assert_eq!(&id, &id2);
        guards.record_attempt(&id, i1 + sec);
        let (src, id_x) = guards.pick_guard_id(&usage, &params, i1 + sec).unwrap();
        // We get the same guard this (second) time that we pick it too, since
        // it is a primary guard, and is_pending won't block it.
        assert_eq!(id_x, id);
        assert_eq!(src, ListKind::Primary);
        guards.record_attempt(&id_x, i1 + sec * 2);
        guards.record_failure(&id_x, None, i1 + sec * 3);
        guards.record_failure(&id, None, i1 + sec * 4);
        // Third guard: this one won't be primary.
        let (src, id3) = guards.pick_guard_id(&usage, &params, i1 + sec * 4).unwrap();
        assert_eq!(src, ListKind::Sample);
        assert!(!guards.primary.contains(&id3));
        guards.record_attempt(&id3, i1 + sec * 5);
        // Fourth guard: Third guard will be pending, so a different one gets
        // handed out here.
        let (src, id4) = guards.pick_guard_id(&usage, &params, i1 + sec * 5).unwrap();
        assert_eq!(src, ListKind::Sample);
        assert!(id3 != id4);
        assert!(!guards.primary.contains(&id4));
        guards.record_attempt(&id4, i1 + sec * 6);
        // Look at usability status: primary guards should be usable
        // immediately; third guard should be too (since primary
        // guards are down).  Fourth should not have a known status,
        // since third is pending.
        assert_eq!(
            guards.circ_usability_status(&id1, &usage, &params, i1 + sec * 6),
            Some(true)
        );
        assert_eq!(
            guards.circ_usability_status(&id2, &usage, &params, i1 + sec * 6),
            Some(true)
        );
        assert_eq!(
            guards.circ_usability_status(&id3, &usage, &params, i1 + sec * 6),
            Some(true)
        );
        assert_eq!(
            guards.circ_usability_status(&id4, &usage, &params, i1 + sec * 6),
            None
        );
        // Have both guards succeed.
        guards.record_success(&id3, &params, None, st1 + sec * 7);
        guards.record_success(&id4, &params, None, st1 + sec * 8);
        // Check the impact of having both guards succeed.
        assert!(guards.primary_guards_invalidated);
        guards.select_primary_guards(&params);
        assert_eq!(&guards.primary, &[id3.clone(), id4.clone()]);
        // Next time we ask for a guard, we get a primary guard again.
        let (src, id) = guards
            .pick_guard_id(&usage, &params, i1 + sec * 10)
            .unwrap();
        assert_eq!(src, ListKind::Primary);
        assert_eq!(&id, &id3);
        // If we ask for a directory guard, we get one of the primaries.
        let mut found = HashSet::new();
        let usage = crate::GuardUsageBuilder::default()
            .kind(crate::GuardUsageKind::OneHopDirectory)
            .build()
            .unwrap();
        for _ in 0..64 {
            let (src, id) = guards
                .pick_guard_id(&usage, &params, i1 + sec * 10)
                .unwrap();
            assert_eq!(src, ListKind::Primary);
            assert_eq!(
                guards.circ_usability_status(&id, &usage, &params, i1 + sec * 10),
                Some(true)
            );
            guards.record_attempt_abandoned(&id);
            found.insert(id);
        }
        assert!(found.len() == 2);
        assert!(found.contains(&id3));
        assert!(found.contains(&id4));
        // Since the primaries are now up, other guards are not usable.
        assert_eq!(
            guards.circ_usability_status(&id1, &usage, &params, i1 + sec * 12),
            Some(false)
        );
        assert_eq!(
            guards.circ_usability_status(&id2, &usage, &params, i1 + sec * 12),
            Some(false)
        );
    }
    #[test]
    fn everybodys_down() {
        let netdir = netdir();
        let params = GuardParams {
            min_filtered_sample_size: 5,
            n_primary: 2,
            max_sample_bw_fraction: 1.0,
            ..GuardParams::default()
        };
        let mut st = SystemTime::get();
        let mut inst = Instant::get();
        let sec = Duration::from_secs(1);
        let usage = crate::GuardUsageBuilder::default().build().unwrap();
        let mut guards = GuardSet::default();
        guards.extend_sample_as_needed(st, &params, &netdir);
        guards.select_primary_guards(&params);
        assert_eq!(guards.sample.len(), 5);
        for _ in 0..5 {
            let (_, id) = guards.pick_guard_id(&usage, &params, inst).unwrap();
            guards.record_attempt(&id, inst);
            guards.record_failure(&id, None, inst + sec);
            inst += sec * 2;
            st += sec * 2;
        }
        let e = guards.pick_guard_id(&usage, &params, inst);
        assert!(matches!(e, Err(PickGuardError::AllGuardsDown { .. })));
        // Now in theory we should re-grow when we extend.
        guards.extend_sample_as_needed(st, &params, &netdir);
        guards.select_primary_guards(&params);
        assert_eq!(guards.sample.len(), 10);
    }
    #[test]
    fn retry_primary() {
        let netdir = netdir();
        let params = GuardParams {
            min_filtered_sample_size: 5,
            n_primary: 2,
            max_sample_bw_fraction: 1.0,
            ..GuardParams::default()
        };
        let usage = crate::GuardUsageBuilder::default().build().unwrap();
        let mut guards = GuardSet::default();
        guards.extend_sample_as_needed(SystemTime::get(), &params, &netdir);
        guards.select_primary_guards(&params);
        assert_eq!(guards.primary.len(), 2);
        assert!(!guards.all_primary_guards_are_unreachable());
        // Let one primary guard fail.
        let (kind, p_id1) = guards
            .pick_guard_id(&usage, &params, Instant::get())
            .unwrap();
        assert_eq!(kind, ListKind::Primary);
        guards.record_failure(&p_id1, None, Instant::get());
        assert!(!guards.all_primary_guards_are_unreachable());
        // Now let the other one fail.
        let (kind, p_id2) = guards
            .pick_guard_id(&usage, &params, Instant::get())
            .unwrap();
        assert_eq!(kind, ListKind::Primary);
        guards.record_failure(&p_id2, None, Instant::get());
        assert!(guards.all_primary_guards_are_unreachable());
        // Now mark the guards retriable.
        guards.mark_primary_guards_retriable();
        assert!(!guards.all_primary_guards_are_unreachable());
        let (kind, p_id3) = guards
            .pick_guard_id(&usage, &params, Instant::get())
            .unwrap();
        assert_eq!(kind, ListKind::Primary);
        assert_eq!(p_id3, p_id1);
    }
    #[test]
    fn count_missing_mds() {
        let netdir = netdir();
        let params = GuardParams {
            min_filtered_sample_size: 5,
            n_primary: 2,
            max_sample_bw_fraction: 1.0,
            ..GuardParams::default()
        };
        let usage = crate::GuardUsageBuilder::default().build().unwrap();
        let mut guards = GuardSet::default();
        guards.extend_sample_as_needed(SystemTime::get(), &params, &netdir);
        guards.select_primary_guards(&params);
        assert_eq!(guards.primary.len(), 2);
        let (_kind, p_id1) = guards
            .pick_guard_id(&usage, &params, Instant::get())
            .unwrap();
        guards.record_success(&p_id1, &params, None, SystemTime::get());
        assert_eq!(guards.n_primary_without_id_info_in(&netdir), 0);
        use tor_netdir::testnet;
        let netdir2 = testnet::construct_custom_netdir(|_idx, bld, _| {
            let md_so_far = bld.md.testing_md().expect("Couldn't build md?");
            if &p_id1.0.identity(RelayIdType::Ed25519).unwrap() == md_so_far.ed25519_id() {
                bld.omit_md = true;
            }
        })
        .unwrap()
        .unwrap_if_sufficient()
        .unwrap();
        assert_eq!(guards.n_primary_without_id_info_in(&netdir2), 1);
    }
    #[test]
    fn copy_status() {
        let netdir = netdir();
        let params = GuardParams {
            min_filtered_sample_size: 5,
            n_primary: 2,
            max_sample_bw_fraction: 1.0,
            ..GuardParams::default()
        };
        let mut guards1 = GuardSet::default();
        guards1.extend_sample_as_needed(SystemTime::get(), &params, &netdir);
        guards1.select_primary_guards(&params);
        let mut guards2 = guards1.clone();
        // Make a persistent change in guards1, and a different persistent change in guards2.
        let id1 = guards1.primary[0].clone();
        let id2 = guards1.primary[1].clone();
        guards1.record_success(&id1, &params, None, SystemTime::get());
        guards2.record_success(&id2, &params, None, SystemTime::get());
        // Make a non-persistent change in guards2.
        guards2.record_failure(&id2, None, Instant::get());
        // Copy status: make sure non-persistent status changed, and  persistent didn't.
        guards1.copy_ephemeral_status_into_newly_loaded_state(guards2);
        {
            let g1 = guards1.get(&id1).unwrap();
            let g2 = guards1.get(&id2).unwrap();
            assert!(g1.confirmed());
            assert!(!g2.confirmed());
            assert_eq!(g1.reachable(), Reachable::Untried);
            assert_eq!(g2.reachable(), Reachable::Unreachable);
        }
        // Now make a new set of unrelated guards, and make sure that copying
        // from it doesn't change the membership of guards1.
        let mut guards3 = GuardSet::default();
        let g1_set: HashSet<_> = guards1
            .guards
            .values()
            .map(|g| g.guard_id().clone())
            .collect();
        let mut g3_set: HashSet<_> = HashSet::new();
        for _ in 0..4 {
            // There is roughly a 1-in-5000 chance of getting the same set
            // twice, so we loop until that doesn't happen.
            guards3.extend_sample_as_needed(SystemTime::get(), &params, &netdir);
            guards3.select_primary_guards(&params);
            g3_set = guards3
                .guards
                .values()
                .map(|g| g.guard_id().clone())
                .collect();
            // There is roughly a 1-in-5000 chance of getting the same set twice, so
            if g1_set == g3_set {
                guards3 = GuardSet::default();
                continue;
            }
            break;
        }
        assert_ne!(g1_set, g3_set);
        // Do the copy; make sure that the membership is unchanged.
        guards1.copy_ephemeral_status_into_newly_loaded_state(guards3);
        let g1_set_new: HashSet<_> = guards1
            .guards
            .values()
            .map(|g| g.guard_id().clone())
            .collect();
        assert_eq!(g1_set, g1_set_new);
    }
    #[test]
    // This is far easier to test with bridge-client support.
    #[cfg(feature = "bridge-client")]
    fn partial_identity_collision() {
        use crate::bridge::BridgeSet;
        use std::sync::Arc;
        // Construct a configuration with 2 bridges whose IDs overlap partially:
        // Same RSA, but different Ed25519.
        let bc = Arc::new([
            "192.168.0.1:80 $0bac39417268b69b9f514e7f63fa6fba1a788958
             ed25519:S2Fya2F0ICBXaGF0ICBJcyAgSGUgIERvaW5nIEhlcmU"
                .parse()
                .unwrap(),
            "192.168.0.2:80 $0bac39417268b69b9f514e7f63fa6fba1a788958
             ed25519:dGhpcyBpcyBbpmNyZWRpYmx5IHNpbGx5ISEhISEhISA"
                .parse()
                .unwrap(),
        ]);
        let bs = BridgeSet::new(bc, None);
        // Here we rely on GuardSet not filtering out anything by default, and
        // on GuardParamas having a max_sample_size >=2.
        // Otherwise the test won't actually check for correct behavior here.
        let mut gs = GuardSet::default();
        let params = GuardParams::default();
        assert!(params.max_sample_size >= 2);
        assert_eq!(gs.active_filter, GuardFilter::unfiltered());
        gs.extend_sample_as_needed(SystemTime::get(), &params, &bs);
        gs.assert_consistency();
    }
}