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::ConsensusRelays;
16
use crate::params::NetParameters;
17
use bitflags::bitflags;
18
use tor_netdoc::doc::netstatus::{
19
    self, MdRouterStatus, ParamValues, md::NetworkStatus as MdConsensus,
20
};
21

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

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

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

            
67
impl BandwidthFn {
68
    /// Apply this function to the measured or unmeasured bandwidth
69
    /// of a single relay.
70
23789545
    fn apply(&self, w: &netstatus::RelayBandwidth) -> u32 {
71
        use BandwidthFn::*;
72
        use netstatus::RelayBandwidth::*;
73
23789545
        match (self, w) {
74
2540
            (Uniform, _) => 1,
75
4325
            (IncludeUnmeasured, Unmeasured(u)) => *u,
76
1
            (IncludeUnmeasured, Measured(m)) => *m,
77
62
            (MeasuredOnly, Unmeasured(_)) => 0,
78
23782617
            (MeasuredOnly, Measured(m)) => *m,
79
            (_, _) => 0,
80
        }
81
23789545
    }
82
}
83

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

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

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

            
145
impl RelayWeight {
146
    /// Return the largest weight that we give for this kind of relay.
147
    // The unwrap() is safe because array is nonempty.
148
    #[allow(clippy::unwrap_used)]
149
78000
    fn max_weight(&self) -> u32 {
150
78000
        [self.as_guard, self.as_middle, self.as_exit, self.as_dir]
151
78000
            .iter()
152
78000
            .max()
153
78000
            .copied()
154
78000
            .unwrap()
155
78000
    }
156
    /// Return the weight we should give this kind of relay's
157
    /// bandwidth for a given role.
158
23420964
    fn for_role(&self, role: WeightRole) -> u32 {
159
23420964
        match role {
160
1244656
            WeightRole::Guard => self.as_guard,
161
14143411
            WeightRole::Middle => self.as_middle,
162
7270457
            WeightRole::Exit => self.as_exit,
163
368577
            WeightRole::BeginDir => self.as_dir,
164
25286
            WeightRole::HsIntro => self.as_middle, // TODO SPEC is this right?
165
            WeightRole::HsRend => self.as_middle,  // TODO SPEC is this right?
166
368577
            WeightRole::Unweighted => 1,
167
        }
168
23420964
    }
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
23420963
    fn for_rs(rs: &MdRouterStatus) -> Self {
190
23420963
        let mut r = WeightKind::empty();
191
23420963
        if rs.is_flagged_guard() {
192
12032861
            r |= WeightKind::GUARD;
193
11388102
        }
194
23420963
        if rs.is_flagged_exit() {
195
14558148
            r |= WeightKind::EXIT;
196
8862815
        }
197
23420963
        if rs.is_flagged_v2dir() {
198
23420760
            r |= WeightKind::DIR;
199
203
        }
200
23420963
        r
201
23420963
    }
202
    /// Return the index to use for this kind of a relay within a WeightSet.
203
23420964
    fn idx(self) -> usize {
204
23420964
        self.bits() as usize
205
23420964
    }
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
23420958
    pub(crate) fn weight_rs_for_role(&self, rs: &MdRouterStatus, role: WeightRole) -> u64 {
242
23420958
        self.weight_bw_for_role(WeightKind::for_rs(rs), rs.bandwidth(), role)
243
23420958
    }
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
23420964
    fn weight_bw_for_role(
248
23420964
        &self,
249
23420964
        kind: WeightKind,
250
23420964
        relay_weight: &netstatus::RelayBandwidth,
251
23420964
        role: WeightRole,
252
23420964
    ) -> u64 {
253
23420964
        let ws = &self.w[kind.idx()];
254

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

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

            
269
9749
        let total_bw = consensus
270
9749
            .routers
271
9749
            .iter()
272
368575
            .map(|rs| u64::from(bandwidth_fn.apply(rs.bandwidth())))
273
            .sum();
274
9749
        let p = &consensus.footer.consensus.bandwidth_weights;
275

            
276
9749
        Self::from_parts(bandwidth_fn, total_bw, weight_scale, p).validate(consensus)
277
9749
    }
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
9750
    fn from_parts(
283
9750
        bandwidth_fn: BandwidthFn,
284
9750
        total_bw: u64,
285
9750
        weight_scale: u32,
286
9750
        p: &ParamValues<i32>,
287
9750
    ) -> 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
39000
        fn single(p: &ParamValues<i32>, g: &str, m: &str, e: &str, d: &str) -> RelayWeight {
295
39000
            RelayWeight {
296
39000
                as_guard: w_param(p, g),
297
39000
                as_middle: w_param(p, m),
298
39000
                as_exit: w_param(p, e),
299
39000
                as_dir: w_param(p, d),
300
39000
            }
301
39000
        }
302

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

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

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

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

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

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

            
350
    /// Assert that we have correctly computed our shift values so that
351
    /// our total weighted bws do not exceed u64::MAX.
352
9749
    fn validate(self, consensus: &MdConsensus) -> Self {
353
        use WeightRole::*;
354
9749
        for role in [Guard, Middle, Exit, BeginDir, Unweighted] {
355
48745
            let _: u64 = consensus
356
48745
                .c_relays()
357
48745
                .iter()
358
1842875
                .map(|rs| self.weight_rs_for_role(rs, role))
359
1842875
                .fold(0_u64, |a, b| {
360
1842875
                    a.checked_add(b)
361
1842875
                        .expect("Incorrect relay weight calculation: total exceeded u64::MAX!")
362
1842875
                });
363
        }
364
9749
        self
365
9749
    }
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
195000
fn w_param(p: &ParamValues<i32>, kwd: &str) -> u32 {
381
195000
    if kwd == "---" {
382
9750
        0
383
    } else {
384
185250
        clamp_to_pos(*p.get(kwd).unwrap_or(&DFLT_WEIGHT))
385
    }
386
195000
}
387

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

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

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

            
410
#[cfg(test)]
411
mod test {
412
    // @@ begin test lint list maintained by maint/add_warning @@
413
    #![allow(clippy::bool_assert_comparison)]
414
    #![allow(clippy::clone_on_copy)]
415
    #![allow(clippy::dbg_macro)]
416
    #![allow(clippy::mixed_attributes_style)]
417
    #![allow(clippy::print_stderr)]
418
    #![allow(clippy::print_stdout)]
419
    #![allow(clippy::single_char_pattern)]
420
    #![allow(clippy::unwrap_used)]
421
    #![allow(clippy::unchecked_time_subtraction)]
422
    #![allow(clippy::useless_vec)]
423
    #![allow(clippy::needless_pass_by_value)]
424
    #![allow(clippy::string_slice)] // See arti#2571
425
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
426
    use crate::testnet::simple_empty_consensus;
427

            
428
    use super::*;
429
    use netstatus::RelayBandwidth as RW;
430
    use std::net::SocketAddr;
431
    use std::time::{Duration, SystemTime};
432
    use tor_basic_utils::test_rng::testing_rng;
433
    use tor_netdoc::doc::netstatus::{Lifetime, MdRouterStatusBuilder};
434
    use tor_netdoc::types::relay_flags::{RelayFlag, RelayFlags};
435
    use web_time_compat::SystemTimeExt;
436

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

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

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

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

            
474
        let all_zero = [RW::Unmeasured(0), RW::Measured(0), RW::Unmeasured(0)];
475
        assert_eq!(pick_bandwidth_fn(all_zero.iter()), BandwidthFn::Uniform);
476

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

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

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

            
504
    #[test]
505
    fn t_apply_bwfn() {
506
        use BandwidthFn::*;
507
        use netstatus::RelayBandwidth::*;
508

            
509
        assert_eq!(Uniform.apply(&Measured(7)), 1);
510
        assert_eq!(Uniform.apply(&Unmeasured(0)), 1);
511

            
512
        assert_eq!(IncludeUnmeasured.apply(&Measured(7)), 7);
513
        assert_eq!(IncludeUnmeasured.apply(&Unmeasured(8)), 8);
514

            
515
        assert_eq!(MeasuredOnly.apply(&Measured(9)), 9);
516
        assert_eq!(MeasuredOnly.apply(&Unmeasured(10)), 0);
517
    }
518

            
519
    // From a fairly recent Tor consensus.
520
    const TESTVEC_PARAMS: &str = "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";
521

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

            
528
        assert_eq!(ws.bandwidth_fn, BandwidthFn::MeasuredOnly);
529
        assert_eq!(ws.shift, 0);
530

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

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

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

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

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

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

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

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

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

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

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

            
634
        let rs1 = rs_builder().set_flags(RelayFlag::V2Dir).build().unwrap();
635
        assert_eq!(WeightKind::for_rs(&rs1), WeightKind::DIR);
636

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

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

            
647
    #[test]
648
    fn weightset_from_consensus() {
649
        use rand::RngExt;
650
        let now = SystemTime::get();
651
        let one_hour = Duration::new(3600, 0);
652
        let mut rng = testing_rng();
653
        let mut consensus = simple_empty_consensus(Some(
654
            Lifetime::new(now, now + one_hour, now + 2 * one_hour).unwrap(),
655
        ))
656
        .unwrap();
657
        consensus.footer.consensus.bandwidth_weights = TESTVEC_PARAMS.parse().unwrap();
658

            
659
        // We're going to add a huge amount of unmeasured bandwidth,
660
        // and a reasonable amount of  measured bandwidth.
661
        for _ in 0..10 {
662
            let rs = rs_builder()
663
                .identity(rng.random::<[u8; 20]>().into()) // random id
664
                .weight(RW::Unmeasured(1_000_000))
665
                .set_flags(RelayFlag::Guard | RelayFlag::Exit)
666
                .build()
667
                .unwrap();
668
            consensus.routers.push(rs);
669
        }
670
        for n in 0..30 {
671
            let rs = rs_builder()
672
                .identity(rng.random::<[u8; 20]>().into()) // random id
673
                .weight(RW::Measured(1_000 * n))
674
                .set_flags(RelayFlag::Guard | RelayFlag::Exit)
675
                .build()
676
                .unwrap();
677
            consensus.routers.push(rs);
678
        }
679

            
680
        consensus.routers.sort_by_key(|r| *r.rsa_identity());
681

            
682
        let params = NetParameters::default();
683
        let ws = WeightSet::from_consensus(&consensus, &params);
684

            
685
        assert_eq!(ws.bandwidth_fn, BandwidthFn::MeasuredOnly);
686
        assert_eq!(ws.shift, 0);
687
        assert_eq!(ws.w[0].as_guard, 5904);
688
        assert_eq!(ws.w[5].as_guard, 5904);
689
        assert_eq!(ws.w[5].as_middle, 4096);
690
    }
691
}