1
//! Functions for applying the correct weights to relays when choosing
2
//! a relay at random.
3
//!
4
//! The weight to use when picking a relay depends on several factors:
5
//!
6
//! - The relay's *apparent bandwidth*.  (This is ideally measured by a set of
7
//!   bandwidth authorities, but if no bandwidth authorities are running (as on
8
//!   a test network), we might fall back either to relays' self-declared
9
//!   values, or we might treat all relays as having equal bandwidth.)
10
//! - The role that we're selecting a relay to play.  (See [`WeightRole`]).
11
//! - The flags that a relay has in the consensus, and their scarcity.  If a
12
//!   relay provides particularly scarce functionality, we might choose not to
13
//!   use it for other roles, or to use it less commonly for them.
14

            
15
use crate::params::NetParameters;
16
use crate::ConsensusRelays;
17
use bitflags::bitflags;
18
use tor_netdoc::doc::netstatus::{self, MdConsensus, MdConsensusRouterStatus, NetParams};
19

            
20
/// Helper: Calculate the function we should use to find initial relay
21
/// bandwidths.
22
7520
fn pick_bandwidth_fn<'a, I>(mut weights: I) -> BandwidthFn
23
7520
where
24
7520
    I: Clone + Iterator<Item = &'a netstatus::RelayWeight>,
25
7520
{
26
8021
    let has_measured = weights.clone().any(|w| w.is_measured());
27
7747
    let has_nonzero = weights.clone().any(|w| w.is_nonzero());
28
8023
    let has_nonzero_measured = weights.any(|w| w.is_measured() && w.is_nonzero());
29
7520

            
30
7520
    if !has_nonzero {
31
        // If every value is zero, we should just pretend everything has
32
        // bandwidth == 1.
33
49
        BandwidthFn::Uniform
34
7471
    } else if !has_measured {
35
        // If there are no measured values, then we can look at unmeasured
36
        // weights.
37
92
        BandwidthFn::IncludeUnmeasured
38
7379
    } else if has_nonzero_measured {
39
        // Otherwise, there are measured values; we should look at those only, if
40
        // any of them is nonzero.
41
7377
        BandwidthFn::MeasuredOnly
42
    } else {
43
        // This is a bit of an ugly case: We have measured values, but they're
44
        // all zero.  If this happens, the bandwidth authorities exist but they
45
        // very confused: we should fall back to uniform weighting.
46
2
        BandwidthFn::Uniform
47
    }
48
7520
}
49

            
50
/// Internal: how should we find the base bandwidth of each relay?  This
51
/// value is global over a whole directory, and depends on the bandwidth
52
/// weights in the consensus.
53
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
54
enum BandwidthFn {
55
    /// There are no weights at all in the consensus: weight every
56
    /// relay as 1.
57
    Uniform,
58
    /// There are no measured weights in the consensus: count
59
    /// unmeasured weights as the weights for relays.
60
    IncludeUnmeasured,
61
    /// There are measured relays in the consensus; only use those.
62
    MeasuredOnly,
63
}
64

            
65
impl BandwidthFn {
66
    /// Apply this function to the measured or unmeasured bandwidth
67
    /// of a single relay.
68
16088654
    fn apply(&self, w: &netstatus::RelayWeight) -> u32 {
69
        use netstatus::RelayWeight::*;
70
        use BandwidthFn::*;
71
16088654
        match (self, w) {
72
2434
            (Uniform, _) => 1,
73
4142
            (IncludeUnmeasured, Unmeasured(u)) => *u,
74
2
            (IncludeUnmeasured, Measured(m)) => *m,
75
124
            (MeasuredOnly, Unmeasured(_)) => 0,
76
16081952
            (MeasuredOnly, Measured(m)) => *m,
77
            (_, _) => 0,
78
        }
79
16088654
    }
80
}
81

            
82
/// Possible ways to weight relays when selecting them a random.
83
///
84
/// Relays are weighted by a function of their bandwidth that
85
/// depends on how scarce that "kind" of bandwidth is.  For
86
/// example, if Exit bandwidth is rare, then Exits should be
87
/// less likely to get chosen for the middle hop of a path.
88
#[derive(Clone, Debug, Copy)]
89
#[non_exhaustive]
90
pub enum WeightRole {
91
    /// Selecting a relay to use as a guard
92
    Guard,
93
    /// Selecting a relay to use as a middle relay in a circuit.
94
    Middle,
95
    /// Selecting a relay to use to deliver traffic to the internet.
96
    Exit,
97
    /// Selecting a relay for a one-hop BEGIN_DIR directory request.
98
    BeginDir,
99
    /// Selecting a relay with no additional weight beyond its bandwidth.
100
    Unweighted,
101
    /// Selecting a relay for use as a hidden service introduction point
102
    HsIntro,
103
    // Note: There is no `HsRend` role, since in practice when we want to pick a
104
    // rendezvous point we use a pre-built circuit from our circuit-pool, the
105
    // last hop of which was selected with the `Middle` weight.  Fortunately,
106
    // the weighting rules for picking rendezvous points are the same as for
107
    // picking middle relays.
108
}
109

            
110
/// Description for how to weight a single kind of relay for each WeightRole.
111
#[derive(Clone, Debug, Copy)]
112
struct RelayWeight {
113
    /// How to weight this kind of relay when picking a guard relay.
114
    as_guard: u32,
115
    /// How to weight this kind of relay when picking a middle relay.
116
    as_middle: u32,
117
    /// How to weight this kind of relay when picking a exit relay.
118
    as_exit: u32,
119
    /// How to weight this kind of relay when picking a one-hop BEGIN_DIR.
120
    as_dir: u32,
121
}
122

            
123
impl std::ops::Mul<u32> for RelayWeight {
124
    type Output = Self;
125
30048
    fn mul(self, rhs: u32) -> Self {
126
30048
        RelayWeight {
127
30048
            as_guard: self.as_guard * rhs,
128
30048
            as_middle: self.as_middle * rhs,
129
30048
            as_exit: self.as_exit * rhs,
130
30048
            as_dir: self.as_dir * rhs,
131
30048
        }
132
30048
    }
133
}
134
impl std::ops::Div<u32> for RelayWeight {
135
    type Output = Self;
136
30048
    fn div(self, rhs: u32) -> Self {
137
30048
        RelayWeight {
138
30048
            as_guard: self.as_guard / rhs,
139
30048
            as_middle: self.as_middle / rhs,
140
30048
            as_exit: self.as_exit / rhs,
141
30048
            as_dir: self.as_dir / rhs,
142
30048
        }
143
30048
    }
144
}
145

            
146
impl RelayWeight {
147
    /// Return the largest weight that we give for this kind of relay.
148
    // The unwrap() is safe because array is nonempty.
149
    #[allow(clippy::unwrap_used)]
150
60096
    fn max_weight(&self) -> u32 {
151
60096
        [self.as_guard, self.as_middle, self.as_exit, self.as_dir]
152
60096
            .iter()
153
60096
            .max()
154
60096
            .copied()
155
60096
            .unwrap()
156
60096
    }
157
    /// Return the weight we should give this kind of relay's
158
    /// bandwidth for a given role.
159
15808717
    fn for_role(&self, role: WeightRole) -> u32 {
160
15808717
        match role {
161
1030158
            WeightRole::Guard => self.as_guard,
162
9488012
            WeightRole::Middle => self.as_middle,
163
4706479
            WeightRole::Exit => self.as_exit,
164
279929
            WeightRole::BeginDir => self.as_dir,
165
24210
            WeightRole::HsIntro => self.as_middle, // TODO SPEC is this right?
166
279929
            WeightRole::Unweighted => 1,
167
        }
168
15808717
    }
169
}
170

            
171
bitflags! {
172
    /// A kind of relay, for the purposes of selecting a relay by weight.
173
    ///
174
    /// Relays can have or lack the Guard flag, the Exit flag, and the
175
    /// V2Dir flag. All together, this makes 8 kinds of relays.
176
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
177
    struct WeightKind: u8 {
178
        /// Flag in weightkind for Guard relays.
179
        const GUARD = 1 << 0;
180
        /// Flag in weightkind for Exit relays.
181
        const EXIT = 1 << 1;
182
        /// Flag in weightkind for V2Dir relays.
183
        const DIR = 1 << 2;
184
    }
185
}
186

            
187
impl WeightKind {
188
    /// Return the appropriate WeightKind for a relay.
189
15808715
    fn for_rs(rs: &MdConsensusRouterStatus) -> Self {
190
15808715
        let mut r = WeightKind::empty();
191
15808715
        if rs.is_flagged_guard() {
192
8260279
            r |= WeightKind::GUARD;
193
8260279
        }
194
15808715
        if rs.is_flagged_exit() {
195
9704428
            r |= WeightKind::EXIT;
196
9704428
        }
197
15808715
        if rs.is_flagged_v2dir() {
198
15808309
            r |= WeightKind::DIR;
199
15808309
        }
200
15808715
        r
201
15808715
    }
202
    /// Return the index to use for this kind of a relay within a WeightSet.
203
15808717
    fn idx(self) -> usize {
204
15808717
        self.bits() as usize
205
15808717
    }
206
}
207

            
208
/// Information derived from a consensus to use when picking relays by
209
/// weighted bandwidth.
210
#[derive(Debug, Clone)]
211
pub(crate) struct WeightSet {
212
    /// How to find the bandwidth to use when picking a relay by weighted
213
    /// bandwidth.
214
    ///
215
    /// (This tells us us whether to count unmeasured relays, whether
216
    /// to look at bandwidths at all, etc.)
217
    bandwidth_fn: BandwidthFn,
218
    /// Number of bits that we need to right-shift our weighted products
219
    /// so that their sum won't overflow u64::MAX.
220
    //
221
    // TODO: Perhaps we should use f64 to hold our weights instead,
222
    // so we don't need to keep this ad-hoc fixed-point implementation?
223
    // If we did so, we won't have to worry about overflows.
224
    // (When we call choose_multiple_weighted, it already converts into
225
    // f64 internally.  (Though choose_weighted doesn't.))
226
    // Before making this change, however,
227
    // we should think a little about performance and precision.
228
    shift: u8,
229
    /// A set of RelayWeight values, indexed by [`WeightKind::idx`], used
230
    /// to weight different kinds of relays.
231
    w: [RelayWeight; 8],
232
}
233

            
234
impl WeightSet {
235
    /// Find the actual 64-bit weight to use for a given routerstatus when
236
    /// considering it for a given role.
237
    ///
238
    /// NOTE: This function _does not_ consider whether the relay in question
239
    /// actually matches the given role.  For example, if `role` is Guard
240
    /// we don't check whether or not `rs` actually has the Guard flag.
241
15808705
    pub(crate) fn weight_rs_for_role(&self, rs: &MdConsensusRouterStatus, role: WeightRole) -> u64 {
242
15808705
        self.weight_bw_for_role(WeightKind::for_rs(rs), rs.weight(), role)
243
15808705
    }
244

            
245
    /// Find the 64-bit weight to report for a relay of `kind` whose weight in
246
    /// the consensus is `relay_weight` when using it for `role`.
247
15808717
    fn weight_bw_for_role(
248
15808717
        &self,
249
15808717
        kind: WeightKind,
250
15808717
        relay_weight: &netstatus::RelayWeight,
251
15808717
        role: WeightRole,
252
15808717
    ) -> u64 {
253
15808717
        let ws = &self.w[kind.idx()];
254
15808717

            
255
15808717
        let router_bw = self.bandwidth_fn.apply(relay_weight);
256
15808717
        // Note a subtlety here: we multiply the two values _before_
257
15808717
        // we shift, to improve accuracy.  We know that this will be
258
15808717
        // safe, since the inputs are both u32, and so cannot overflow
259
15808717
        // a u64.
260
15808717
        let router_weight = u64::from(router_bw) * u64::from(ws.for_role(role));
261
15808717
        router_weight >> self.shift
262
15808717
    }
263

            
264
    /// Compute the correct WeightSet for a provided MdConsensus.
265
7510
    pub(crate) fn from_consensus(consensus: &MdConsensus, params: &NetParameters) -> Self {
266
23931
        let bandwidth_fn = pick_bandwidth_fn(consensus.c_relays().iter().map(|rs| rs.weight()));
267
7510
        let weight_scale = params.bw_weight_scale.into();
268
7510

            
269
7510
        let total_bw = consensus
270
7510
            .c_relays()
271
7510
            .iter()
272
280111
            .map(|rs| u64::from(bandwidth_fn.apply(rs.weight())))
273
7510
            .sum();
274
7510
        let p = consensus.bandwidth_weights();
275
7510

            
276
7510
        Self::from_parts(bandwidth_fn, total_bw, weight_scale, p).validate(consensus)
277
7510
    }
278

            
279
    /// Compute the correct WeightSet given a bandwidth function, a
280
    /// weight-scaling parameter, a total amount of bandwidth for all
281
    /// relays in the consensus, and a set of bandwidth parameters.
282
7512
    fn from_parts(
283
7512
        bandwidth_fn: BandwidthFn,
284
7512
        total_bw: u64,
285
7512
        weight_scale: u32,
286
7512
        p: &NetParams<i32>,
287
7512
    ) -> Self {
288
        /// Find a single RelayWeight, given the names that its bandwidth
289
        /// parameters have. The `g` parameter is the weight as a guard, the
290
        /// `m` parameter is the weight as a middle relay, the `e` parameter is
291
        /// the weight as an exit, and the `d` parameter is the weight as a
292
        /// directory.
293
        #[allow(clippy::many_single_char_names)]
294
30048
        fn single(p: &NetParams<i32>, g: &str, m: &str, e: &str, d: &str) -> RelayWeight {
295
30048
            RelayWeight {
296
30048
                as_guard: w_param(p, g),
297
30048
                as_middle: w_param(p, m),
298
30048
                as_exit: w_param(p, e),
299
30048
                as_dir: w_param(p, d),
300
30048
            }
301
30048
        }
302

            
303
        // Prevent division by zero in case we're called with a bogus
304
        // input.  (That shouldn't be possible.)
305
7512
        let weight_scale = weight_scale.max(1);
306
7512

            
307
7512
        // For non-V2Dir relays, we have names for most of their weights.
308
7512
        //
309
7512
        // (There is no Wge, since we only use Guard relays as guards.  By the
310
7512
        // same logic, Wme has no reason to exist, but according to the spec it
311
7512
        // does.)
312
7512
        let w_none = single(p, "Wgm", "Wmm", "Wem", "Wbm");
313
7512
        let w_guard = single(p, "Wgg", "Wmg", "Weg", "Wbg");
314
7512
        let w_exit = single(p, "---", "Wme", "Wee", "Wbe");
315
7512
        let w_both = single(p, "Wgd", "Wmd", "Wed", "Wbd");
316
7512

            
317
7512
        // Note that the positions of the elements in this array need to
318
7512
        // match the values returned by WeightKind.as_idx().
319
7512
        let w = [
320
7512
            w_none,
321
7512
            w_guard,
322
7512
            w_exit,
323
7512
            w_both,
324
7512
            // The V2Dir values are the same as the non-V2Dir values, except
325
7512
            // each is multiplied by an additional factor.
326
7512
            //
327
7512
            // (We don't need to check for overflow here, since the
328
7512
            // authorities make sure that the inputs don't get too big.)
329
7512
            (w_none * w_param(p, "Wmb")) / weight_scale,
330
7512
            (w_guard * w_param(p, "Wgb")) / weight_scale,
331
7512
            (w_exit * w_param(p, "Web")) / weight_scale,
332
7512
            (w_both * w_param(p, "Wdb")) / weight_scale,
333
7512
        ];
334
7512

            
335
7512
        // This is the largest weight value.
336
7512
        // The unwrap() is safe because `w` is nonempty.
337
7512
        #[allow(clippy::unwrap_used)]
338
7512
        let w_max = w.iter().map(RelayWeight::max_weight).max().unwrap();
339
7512

            
340
7512
        // We want "shift" such that (total * w_max) >> shift <= u64::max
341
7512
        let shift = calculate_shift(total_bw, u64::from(w_max)) as u8;
342
7512

            
343
7512
        WeightSet {
344
7512
            bandwidth_fn,
345
7512
            shift,
346
7512
            w,
347
7512
        }
348
7512
    }
349

            
350
    /// Assert that we have correctly computed our shift values so that
351
    /// our total weighted bws do not exceed u64::MAX.
352
7510
    fn validate(self, consensus: &MdConsensus) -> Self {
353
        use WeightRole::*;
354
37550
        for role in [Guard, Middle, Exit, BeginDir, Unweighted] {
355
37550
            let _: u64 = consensus
356
37550
                .c_relays()
357
37550
                .iter()
358
1400555
                .map(|rs| self.weight_rs_for_role(rs, role))
359
1400555
                .fold(0_u64, |a, b| {
360
1399625
                    a.checked_add(b)
361
1399625
                        .expect("Incorrect relay weight calculation: total exceeded u64::MAX!")
362
1400555
                });
363
37550
        }
364
7510
        self
365
7510
    }
366
}
367

            
368
/// The value to return if a weight parameter is absent.
369
///
370
/// (If there are no weights at all, then it's correct to set them all to 1,
371
/// and just use the bandwidths.  If _some_ are present and some are absent,
372
/// then the spec doesn't say what to do, but this behavior appears
373
/// reasonable.)
374
const DFLT_WEIGHT: i32 = 1;
375

            
376
/// Return the weight param named 'kwd' in p.
377
///
378
/// Returns DFLT_WEIGHT if there is no such parameter, and 0
379
/// if `kwd` is "---".
380
150240
fn w_param(p: &NetParams<i32>, kwd: &str) -> u32 {
381
150240
    if kwd == "---" {
382
7512
        0
383
    } else {
384
142728
        clamp_to_pos(*p.get(kwd).unwrap_or(&DFLT_WEIGHT))
385
    }
386
150240
}
387

            
388
/// If `inp` is less than 0, return 0.  Otherwise return `inp` as a u32.
389
142738
fn clamp_to_pos(inp: i32) -> u32 {
390
142738
    // (The spec says that we might encounter negative values here, though
391
142738
    // we never actually generate them, and don't plan to generate them.)
392
142738
    if inp < 0 {
393
4
        0
394
    } else {
395
142734
        inp as u32
396
    }
397
142738
}
398

            
399
/// Compute a 'shift' value such that `(a * b) >> shift` will be contained
400
/// inside 64 bits.
401
7520
fn calculate_shift(a: u64, b: u64) -> u32 {
402
7520
    let bits_for_product = log2_upper(a) + log2_upper(b);
403
7520
    bits_for_product.saturating_sub(64)
404
7520
}
405

            
406
/// Return an upper bound for the log2 of n.
407
///
408
/// This function overestimates whenever n is a power of two, but that doesn't
409
/// much matter for the uses we're giving it here.
410
15050
fn log2_upper(n: u64) -> u32 {
411
15050
    64 - n.leading_zeros()
412
15050
}
413

            
414
#[cfg(test)]
415
mod test {
416
    // @@ begin test lint list maintained by maint/add_warning @@
417
    #![allow(clippy::bool_assert_comparison)]
418
    #![allow(clippy::clone_on_copy)]
419
    #![allow(clippy::dbg_macro)]
420
    #![allow(clippy::mixed_attributes_style)]
421
    #![allow(clippy::print_stderr)]
422
    #![allow(clippy::print_stdout)]
423
    #![allow(clippy::single_char_pattern)]
424
    #![allow(clippy::unwrap_used)]
425
    #![allow(clippy::unchecked_duration_subtraction)]
426
    #![allow(clippy::useless_vec)]
427
    #![allow(clippy::needless_pass_by_value)]
428
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
429
    use super::*;
430
    use netstatus::RelayWeight as RW;
431
    use std::net::SocketAddr;
432
    use std::time::{Duration, SystemTime};
433
    use tor_basic_utils::test_rng::testing_rng;
434
    use tor_netdoc::doc::netstatus::{Lifetime, RelayFlags, RouterStatusBuilder};
435

            
436
    #[test]
437
    fn t_clamp() {
438
        assert_eq!(clamp_to_pos(32), 32);
439
        assert_eq!(clamp_to_pos(i32::MAX), i32::MAX as u32);
440
        assert_eq!(clamp_to_pos(0), 0);
441
        assert_eq!(clamp_to_pos(-1), 0);
442
        assert_eq!(clamp_to_pos(i32::MIN), 0);
443
    }
444

            
445
    #[test]
446
    fn t_log2() {
447
        assert_eq!(log2_upper(u64::MAX), 64);
448
        assert_eq!(log2_upper(0), 0);
449
        assert_eq!(log2_upper(1), 1);
450
        assert_eq!(log2_upper(63), 6);
451
        assert_eq!(log2_upper(64), 7); // a little buggy but harmless.
452
    }
453

            
454
    #[test]
455
    fn t_calc_shift() {
456
        assert_eq!(calculate_shift(1 << 20, 1 << 20), 0);
457
        assert_eq!(calculate_shift(1 << 50, 1 << 10), 0);
458
        assert_eq!(calculate_shift(1 << 32, 1 << 33), 3);
459
        assert!(((1_u64 << 32) >> 3).checked_mul(1_u64 << 33).is_some());
460
        assert_eq!(calculate_shift(432 << 40, 7777 << 40), 38);
461
        assert!(((432_u64 << 40) >> 38)
462
            .checked_mul(7777_u64 << 40)
463
            .is_some());
464
    }
465

            
466
    #[test]
467
    fn t_pick_bwfunc() {
468
        let empty = [];
469
        assert_eq!(pick_bandwidth_fn(empty.iter()), BandwidthFn::Uniform);
470

            
471
        let all_zero = [RW::Unmeasured(0), RW::Measured(0), RW::Unmeasured(0)];
472
        assert_eq!(pick_bandwidth_fn(all_zero.iter()), BandwidthFn::Uniform);
473

            
474
        let all_unmeasured = [RW::Unmeasured(9), RW::Unmeasured(2222)];
475
        assert_eq!(
476
            pick_bandwidth_fn(all_unmeasured.iter()),
477
            BandwidthFn::IncludeUnmeasured
478
        );
479

            
480
        let some_measured = [
481
            RW::Unmeasured(10),
482
            RW::Measured(7),
483
            RW::Measured(4),
484
            RW::Unmeasured(0),
485
        ];
486
        assert_eq!(
487
            pick_bandwidth_fn(some_measured.iter()),
488
            BandwidthFn::MeasuredOnly
489
        );
490

            
491
        // This corresponds to an open question in
492
        // `pick_bandwidth_fn`, about what to do when the only nonzero
493
        // weights are unmeasured.
494
        let measured_all_zero = [RW::Unmeasured(10), RW::Measured(0)];
495
        assert_eq!(
496
            pick_bandwidth_fn(measured_all_zero.iter()),
497
            BandwidthFn::Uniform
498
        );
499
    }
500

            
501
    #[test]
502
    fn t_apply_bwfn() {
503
        use netstatus::RelayWeight::*;
504
        use BandwidthFn::*;
505

            
506
        assert_eq!(Uniform.apply(&Measured(7)), 1);
507
        assert_eq!(Uniform.apply(&Unmeasured(0)), 1);
508

            
509
        assert_eq!(IncludeUnmeasured.apply(&Measured(7)), 7);
510
        assert_eq!(IncludeUnmeasured.apply(&Unmeasured(8)), 8);
511

            
512
        assert_eq!(MeasuredOnly.apply(&Measured(9)), 9);
513
        assert_eq!(MeasuredOnly.apply(&Unmeasured(10)), 0);
514
    }
515

            
516
    // From a fairly recent Tor consensus.
517
    const TESTVEC_PARAMS: &str =
518
        "Wbd=0 Wbe=0 Wbg=4096 Wbm=10000 Wdb=10000 Web=10000 Wed=10000 Wee=10000 Weg=10000 Wem=10000 Wgb=10000 Wgd=0 Wgg=5904 Wgm=5904 Wmb=10000 Wmd=0 Wme=0 Wmg=4096 Wmm=10000";
519

            
520
    #[test]
521
    fn t_weightset_basic() {
522
        let total_bandwidth = 1_000_000_000;
523
        let params = TESTVEC_PARAMS.parse().unwrap();
524
        let ws = WeightSet::from_parts(BandwidthFn::MeasuredOnly, total_bandwidth, 10000, &params);
525

            
526
        assert_eq!(ws.bandwidth_fn, BandwidthFn::MeasuredOnly);
527
        assert_eq!(ws.shift, 0);
528

            
529
        assert_eq!(ws.w[0].as_guard, 5904);
530
        assert_eq!(ws.w[(WeightKind::GUARD.bits()) as usize].as_guard, 5904);
531
        assert_eq!(ws.w[(WeightKind::EXIT.bits()) as usize].as_exit, 10000);
532
        assert_eq!(
533
            ws.w[(WeightKind::EXIT | WeightKind::GUARD).bits() as usize].as_dir,
534
            0
535
        );
536
        assert_eq!(
537
            ws.w[(WeightKind::GUARD | WeightKind::DIR).bits() as usize].as_dir,
538
            4096
539
        );
540
        assert_eq!(
541
            ws.w[(WeightKind::GUARD | WeightKind::DIR).bits() as usize].as_dir,
542
            4096
543
        );
544

            
545
        assert_eq!(
546
            ws.weight_bw_for_role(
547
                WeightKind::GUARD | WeightKind::DIR,
548
                &RW::Unmeasured(7777),
549
                WeightRole::Guard
550
            ),
551
            0
552
        );
553

            
554
        assert_eq!(
555
            ws.weight_bw_for_role(
556
                WeightKind::GUARD | WeightKind::DIR,
557
                &RW::Measured(7777),
558
                WeightRole::Guard
559
            ),
560
            7777 * 5904
561
        );
562

            
563
        assert_eq!(
564
            ws.weight_bw_for_role(
565
                WeightKind::GUARD | WeightKind::DIR,
566
                &RW::Measured(7777),
567
                WeightRole::Middle
568
            ),
569
            7777 * 4096
570
        );
571

            
572
        assert_eq!(
573
            ws.weight_bw_for_role(
574
                WeightKind::GUARD | WeightKind::DIR,
575
                &RW::Measured(7777),
576
                WeightRole::Exit
577
            ),
578
            7777 * 10000
579
        );
580

            
581
        assert_eq!(
582
            ws.weight_bw_for_role(
583
                WeightKind::GUARD | WeightKind::DIR,
584
                &RW::Measured(7777),
585
                WeightRole::BeginDir
586
            ),
587
            7777 * 4096
588
        );
589

            
590
        assert_eq!(
591
            ws.weight_bw_for_role(
592
                WeightKind::GUARD | WeightKind::DIR,
593
                &RW::Measured(7777),
594
                WeightRole::Unweighted
595
            ),
596
            7777
597
        );
598

            
599
        // Now try those last few with routerstatuses.
600
        let rs = rs_builder()
601
            .set_flags(RelayFlags::GUARD | RelayFlags::V2DIR)
602
            .weight(RW::Measured(7777))
603
            .build()
604
            .unwrap();
605
        assert_eq!(ws.weight_rs_for_role(&rs, WeightRole::Exit), 7777 * 10000);
606
        assert_eq!(
607
            ws.weight_rs_for_role(&rs, WeightRole::BeginDir),
608
            7777 * 4096
609
        );
610
        assert_eq!(ws.weight_rs_for_role(&rs, WeightRole::Unweighted), 7777);
611
    }
612

            
613
    /// Return a routerstatus builder set up to deliver a routerstatus
614
    /// with most features disabled.
615
    fn rs_builder() -> RouterStatusBuilder<[u8; 32]> {
616
        MdConsensus::builder()
617
            .rs()
618
            .identity([9; 20].into())
619
            .add_or_port(SocketAddr::from(([127, 0, 0, 1], 9001)))
620
            .doc_digest([9; 32])
621
            .protos("".parse().unwrap())
622
            .clone()
623
    }
624

            
625
    #[test]
626
    fn weight_flags() {
627
        let rs1 = rs_builder().set_flags(RelayFlags::EXIT).build().unwrap();
628
        assert_eq!(WeightKind::for_rs(&rs1), WeightKind::EXIT);
629

            
630
        let rs1 = rs_builder().set_flags(RelayFlags::GUARD).build().unwrap();
631
        assert_eq!(WeightKind::for_rs(&rs1), WeightKind::GUARD);
632

            
633
        let rs1 = rs_builder().set_flags(RelayFlags::V2DIR).build().unwrap();
634
        assert_eq!(WeightKind::for_rs(&rs1), WeightKind::DIR);
635

            
636
        let rs1 = rs_builder().build().unwrap();
637
        assert_eq!(WeightKind::for_rs(&rs1), WeightKind::empty());
638

            
639
        let rs1 = rs_builder().set_flags(RelayFlags::all()).build().unwrap();
640
        assert_eq!(
641
            WeightKind::for_rs(&rs1),
642
            WeightKind::EXIT | WeightKind::GUARD | WeightKind::DIR
643
        );
644
    }
645

            
646
    #[test]
647
    fn weightset_from_consensus() {
648
        use rand::Rng;
649
        let now = SystemTime::now();
650
        let one_hour = Duration::new(3600, 0);
651
        let mut rng = testing_rng();
652
        let mut bld = MdConsensus::builder();
653
        bld.consensus_method(34)
654
            .lifetime(Lifetime::new(now, now + one_hour, now + 2 * one_hour).unwrap())
655
            .weights(TESTVEC_PARAMS.parse().unwrap());
656

            
657
        // We're going to add a huge amount of unmeasured bandwidth,
658
        // and a reasonable amount of  measured bandwidth.
659
        for _ in 0..10 {
660
            rs_builder()
661
                .identity(rng.random::<[u8; 20]>().into()) // random id
662
                .weight(RW::Unmeasured(1_000_000))
663
                .set_flags(RelayFlags::GUARD | RelayFlags::EXIT)
664
                .build_into(&mut bld)
665
                .unwrap();
666
        }
667
        for n in 0..30 {
668
            rs_builder()
669
                .identity(rng.random::<[u8; 20]>().into()) // random id
670
                .weight(RW::Measured(1_000 * n))
671
                .set_flags(RelayFlags::GUARD | RelayFlags::EXIT)
672
                .build_into(&mut bld)
673
                .unwrap();
674
        }
675

            
676
        let consensus = bld.testing_consensus().unwrap();
677
        let params = NetParameters::default();
678
        let ws = WeightSet::from_consensus(&consensus, &params);
679

            
680
        assert_eq!(ws.bandwidth_fn, BandwidthFn::MeasuredOnly);
681
        assert_eq!(ws.shift, 0);
682
        assert_eq!(ws.w[0].as_guard, 5904);
683
        assert_eq!(ws.w[5].as_guard, 5904);
684
        assert_eq!(ws.w[5].as_middle, 4096);
685
    }
686
}