rings-node 0.20.0

Rings is a structured peer-to-peer network implementation using WebRTC, Chord algorithm, and full WebAssembly (WASM) support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
//! Onion route selection.

use std::collections::BTreeMap;
use std::collections::BTreeSet;

use rings_core::dht::Did;
use rings_core::ecc::PublicKey;
use rings_core::measure::PeerQuality;
use rings_core::message::DhtProtocolMode;

use super::circuit::MAX_ONION_CIRCUIT_HOPS;
use super::OnionExitDescriptor;
use super::OnionRouteError;
use super::OnionServiceName;
use super::ONION_RELAY_CAPABILITY;
use crate::error::Error;
use crate::error::Result;
use crate::online::OnlineNodeDescriptor;

/// Default number of DID hops in a production onion route, including the exit.
pub const DEFAULT_ONION_ROUTE_HOPS: usize = 3;

/// Route-building request for an onion circuit.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OnionRouteRequest {
    /// Exit service required by the route.
    pub service: OnionServiceName,
    /// Desired hop count including the exit. `0` uses [`DEFAULT_ONION_ROUTE_HOPS`].
    pub hop_count: usize,
    /// Whether a route may be shorter than `hop_count` when the network is too small.
    pub allow_short_paths: bool,
}

impl OnionRouteRequest {
    /// Build a route request from an untrusted service string.
    pub fn new(
        service: impl AsRef<str>,
        hop_count: usize,
        allow_short_paths: bool,
    ) -> Result<Self> {
        Ok(Self::from_service_name(
            parse_route_service(service)?,
            hop_count,
            allow_short_paths,
        ))
    }

    /// Build a route request from an already canonical service name.
    pub fn from_service_name(
        service: OnionServiceName,
        hop_count: usize,
        allow_short_paths: bool,
    ) -> Self {
        Self {
            service,
            hop_count,
            allow_short_paths,
        }
    }

    /// Return the canonical service selected by this request.
    pub fn service(&self) -> &str {
        self.service.as_str()
    }

    pub(crate) fn service_name(&self) -> &OnionServiceName {
        &self.service
    }

    fn target_hop_count(&self) -> usize {
        if self.hop_count == 0 {
            DEFAULT_ONION_ROUTE_HOPS
        } else {
            self.hop_count
        }
    }
}

/// One hop selected for encrypted onion routing.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct OnionRouteHop {
    /// Hop DID.
    pub did: Did,
    /// Hop session public key used for ElGamal-AEAD layers.
    pub session_public_key: PublicKey<33>,
}

impl OnionRouteHop {
    /// Build a route hop from its DID and session public key.
    pub const fn new(did: Did, session_public_key: PublicKey<33>) -> Self {
        Self {
            did,
            session_public_key,
        }
    }
}

/// Selected onion route.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OnionRoute {
    /// Exit service requested by the route.
    service: OnionServiceName,
    /// Ordered DIDs, ending with the exit DID.
    hops: Vec<Did>,
    /// Ordered encrypted route hops, ending with the exit hop.
    encryption_hops: Vec<OnionRouteHop>,
    /// Signed descriptor for the selected exit.
    exit: OnionExitDescriptor,
}

impl OnionRoute {
    /// Build a route after proving the hop and exit fields agree.
    ///
    /// Invariant: `hops == encryption_hops.map(|hop| hop.did)`, no DID repeats, and the last hop is
    /// the selected exit descriptor.
    ///
    /// Invariant: `service` is canonical, so route/payload service equality is ordinary value
    /// equality over [`OnionServiceName`], not caller-dependent string normalization.
    pub(crate) fn new(
        service: OnionServiceName,
        encryption_hops: Vec<OnionRouteHop>,
        exit: OnionExitDescriptor,
    ) -> Result<Self> {
        validate_route_hops(&service, &encryption_hops, &exit)?;
        let hops = encryption_hops
            .iter()
            .map(|hop| hop.did)
            .collect::<Vec<_>>();
        Ok(Self {
            service,
            hops,
            encryption_hops,
            exit,
        })
    }

    /// Return the service used to select this route.
    pub fn service(&self) -> &str {
        self.service.as_str()
    }

    /// Return the canonical service name used to select this route.
    pub fn service_name(&self) -> &OnionServiceName {
        &self.service
    }

    /// Return the ordered route DIDs, ending with the exit DID.
    pub fn hops(&self) -> &[Did] {
        self.hops.as_slice()
    }

    /// Return the ordered encrypted hops, ending with the exit hop.
    pub(crate) fn encryption_hops(&self) -> &[OnionRouteHop] {
        self.encryption_hops.as_slice()
    }

    /// Return the selected exit descriptor.
    pub fn exit(&self) -> &OnionExitDescriptor {
        &self.exit
    }

    /// Return the selected exit DID.
    pub fn exit_did(&self) -> Did {
        self.exit.did
    }
}

pub(crate) trait RouteEntropy {
    fn next_u64(&mut self) -> u64;
}

pub(crate) struct SystemRouteEntropy;

impl SystemRouteEntropy {
    pub(crate) const fn new() -> Self {
        Self
    }
}

impl RouteEntropy for SystemRouteEntropy {
    fn next_u64(&mut self) -> u64 {
        rand::random()
    }
}

#[derive(Clone, Debug)]
pub(crate) struct OnionRouteCandidates {
    pub(in crate::onion) relays: Vec<OnionRouteHop>,
    pub(in crate::onion) exits: Vec<OnionExitDescriptor>,
}

impl OnionRouteCandidates {
    pub(crate) fn from_validated_descriptors(
        local: Did,
        dht_protocol: DhtProtocolMode,
        now_ms: u128,
        service: &OnionServiceName,
        online_nodes: impl IntoIterator<Item = OnlineNodeDescriptor>,
        exits: impl IntoIterator<Item = OnionExitDescriptor>,
    ) -> Self {
        let relays = eligible_relay_dids(dht_protocol, now_ms, local, online_nodes);
        let exits = eligible_exits(dht_protocol.network_id, now_ms, service, exits)
            .into_iter()
            .filter(|descriptor| descriptor.did != local)
            .collect();

        Self { relays, exits }
    }
}

/// Select an onion route from live presence and exit descriptors.
///
/// Invariant: the returned hop list contains no duplicate DID and always ends
/// in a descriptor from the exit registry.
pub fn select_onion_route(
    local: Did,
    dht_protocol: DhtProtocolMode,
    now_ms: u128,
    request: &OnionRouteRequest,
    online_nodes: impl IntoIterator<Item = OnlineNodeDescriptor>,
    exits: impl IntoIterator<Item = OnionExitDescriptor>,
    qualities: impl IntoIterator<Item = (Did, PeerQuality)>,
) -> Result<OnionRoute> {
    let candidates = OnionRouteCandidates {
        relays: eligible_relay_dids(dht_protocol, now_ms, local, online_nodes)
            .into_iter()
            .collect(),
        exits: eligible_exits(
            dht_protocol.network_id,
            now_ms,
            request.service_name(),
            exits,
        )
        .into_iter()
        .filter(|descriptor| descriptor.did != local)
        .collect(),
    };
    select_onion_route_from_candidates(
        request,
        candidates,
        qualities,
        &mut SystemRouteEntropy::new(),
    )
}

pub(crate) fn select_onion_route_from_candidates(
    request: &OnionRouteRequest,
    candidates: OnionRouteCandidates,
    qualities: impl IntoIterator<Item = (Did, PeerQuality)>,
    entropy: &mut impl RouteEntropy,
) -> Result<OnionRoute> {
    select_onion_route_from_candidates_with_first_hop(
        request,
        candidates,
        qualities,
        entropy,
        |_| true,
    )
}

pub(crate) fn select_onion_route_from_candidates_with_first_hop(
    request: &OnionRouteRequest,
    candidates: OnionRouteCandidates,
    qualities: impl IntoIterator<Item = (Did, PeerQuality)>,
    entropy: &mut impl RouteEntropy,
    first_hop_permitted: impl Fn(Did) -> bool,
) -> Result<OnionRoute> {
    let target_hop_count = request.target_hop_count();
    if target_hop_count == 0 || target_hop_count > usize::from(MAX_ONION_CIRCUIT_HOPS) {
        return Err(Error::OnionRouteError(
            OnionRouteError::HopCountOutOfBounds {
                hop_count: target_hop_count,
                max_hops: MAX_ONION_CIRCUIT_HOPS,
            },
        ));
    }

    let quality_by_did = qualities.into_iter().collect::<BTreeMap<_, _>>();
    let mut exit_candidates = candidates.exits;
    let first_hop_permitted = &first_hop_permitted;
    let first_hop_exit_only = target_hop_count == 1;
    if exit_candidates.is_empty() {
        return Err(Error::OnionRouteError(OnionRouteError::NoLiveExit {
            service: request.service().to_string(),
        }));
    }
    if first_hop_exit_only {
        return select_direct_exit_route(
            request,
            exit_candidates,
            &quality_by_did,
            entropy,
            first_hop_permitted,
        );
    }

    let mut relay_candidates = candidates.relays.into_iter().collect::<Vec<_>>();
    let relay_hops_needed = target_hop_count.saturating_sub(1);
    let mut selected_relays = Vec::with_capacity(relay_hops_needed);
    if relay_hops_needed > 0 {
        let has_relay_candidates = !relay_candidates.is_empty();
        let Some(first_index) =
            pick_weighted_hop_index_where(&relay_candidates, &quality_by_did, entropy, |did| {
                first_hop_permitted(did)
                    && route_can_still_select_exit(&selected_relays, did, &exit_candidates)
            })
        else {
            if request.allow_short_paths {
                return select_direct_exit_route(
                    request,
                    exit_candidates,
                    &quality_by_did,
                    entropy,
                    first_hop_permitted,
                );
            }
            let error = if has_relay_candidates {
                OnionRouteError::NoPermittedFirstHop
            } else {
                OnionRouteError::NotEnoughRelays {
                    hop_count: target_hop_count,
                }
            };
            return Err(Error::OnionRouteError(error));
        };
        selected_relays.push(relay_candidates.remove(first_index));
        while selected_relays.len() < relay_hops_needed {
            let Some(next_index) =
                pick_weighted_hop_index_where(&relay_candidates, &quality_by_did, entropy, |did| {
                    route_can_still_select_exit(&selected_relays, did, &exit_candidates)
                })
            else {
                break;
            };
            selected_relays.push(relay_candidates.remove(next_index));
        }
    }

    if selected_relays.len() < relay_hops_needed && !request.allow_short_paths {
        return Err(Error::OnionRouteError(OnionRouteError::NotEnoughRelays {
            hop_count: target_hop_count,
        }));
    }

    let exit_index =
        pick_weighted_exit_index_where(&exit_candidates, &quality_by_did, entropy, |did| {
            !route_already_contains_did(&selected_relays, did)
        })
        .ok_or_else(|| {
            Error::OnionRouteError(OnionRouteError::NoLiveExit {
                service: request.service().to_string(),
            })
        })?;
    let exit = exit_candidates.remove(exit_index);
    let exit_did = exit.did;
    let mut encryption_hops = selected_relays;
    encryption_hops.push(OnionRouteHop::new(exit_did, exit.session_public_key));
    OnionRoute::new(request.service.clone(), encryption_hops, exit)
}

fn select_direct_exit_route(
    request: &OnionRouteRequest,
    mut exits: Vec<OnionExitDescriptor>,
    quality_by_did: &BTreeMap<Did, PeerQuality>,
    entropy: &mut impl RouteEntropy,
    first_hop_permitted: &impl Fn(Did) -> bool,
) -> Result<OnionRoute> {
    let exit_index =
        pick_weighted_exit_index_where(&exits, quality_by_did, entropy, first_hop_permitted)
            .ok_or(Error::OnionRouteError(OnionRouteError::NoPermittedFirstHop))?;
    let exit = exits.remove(exit_index);
    let encryption_hops = vec![OnionRouteHop::new(exit.did, exit.session_public_key)];
    OnionRoute::new(request.service.clone(), encryption_hops, exit)
}

fn route_can_still_select_exit(
    selected_relays: &[OnionRouteHop],
    candidate_relay: Did,
    exits: &[OnionExitDescriptor],
) -> bool {
    exits.iter().any(|exit| {
        exit.did != candidate_relay && !route_already_contains_did(selected_relays, exit.did)
    })
}

fn route_already_contains_did(selected_relays: &[OnionRouteHop], did: Did) -> bool {
    selected_relays.iter().any(|hop| hop.did == did)
}

fn pick_weighted_hop_index_where(
    hops: &[OnionRouteHop],
    quality_by_did: &BTreeMap<Did, PeerQuality>,
    entropy: &mut impl RouteEntropy,
    permitted: impl Fn(Did) -> bool,
) -> Option<usize> {
    let eligible = hops
        .iter()
        .enumerate()
        .filter_map(|(index, hop)| permitted(hop.did).then_some((index, hop.did)))
        .collect::<Vec<_>>();
    pick_weighted_candidate_index(eligible, quality_by_did, entropy)
}

fn pick_weighted_exit_index_where(
    exits: &[OnionExitDescriptor],
    quality_by_did: &BTreeMap<Did, PeerQuality>,
    entropy: &mut impl RouteEntropy,
    permitted: impl Fn(Did) -> bool,
) -> Option<usize> {
    let eligible = exits
        .iter()
        .enumerate()
        .filter_map(|(index, descriptor)| {
            permitted(descriptor.did).then_some((index, descriptor.did))
        })
        .collect::<Vec<_>>();
    pick_weighted_candidate_index(eligible, quality_by_did, entropy)
}

fn pick_weighted_candidate_index(
    eligible: Vec<(usize, Did)>,
    quality_by_did: &BTreeMap<Did, PeerQuality>,
    entropy: &mut impl RouteEntropy,
) -> Option<usize> {
    let dids = eligible.iter().map(|(_, did)| *did).collect::<Vec<_>>();
    let selected = pick_weighted_index(&dids, quality_by_did, entropy)?;
    eligible.into_iter().nth(selected).map(|(index, _)| index)
}

fn pick_weighted_index(
    dids: &[Did],
    quality_by_did: &BTreeMap<Did, PeerQuality>,
    entropy: &mut impl RouteEntropy,
) -> Option<usize> {
    let total_weight = dids
        .iter()
        .map(|did| quality_weight(quality_by_did.get(did).copied()))
        .sum::<u64>();
    if total_weight == 0 {
        return None;
    }

    let mut roll = entropy.next_u64() % total_weight;
    for (index, did) in dids.iter().enumerate() {
        let weight = quality_weight(quality_by_did.get(did).copied());
        if roll < weight {
            return Some(index);
        }
        roll -= weight;
    }
    None
}

fn quality_weight(quality: Option<PeerQuality>) -> u64 {
    match quality {
        Some(PeerQuality::Healthy) => 8,
        Some(PeerQuality::Unknown) | None => 4,
        Some(PeerQuality::Degraded) => 1,
    }
}

fn eligible_exits(
    network_id: u32,
    now_ms: u128,
    service: &OnionServiceName,
    exits: impl IntoIterator<Item = OnionExitDescriptor>,
) -> Vec<OnionExitDescriptor> {
    OnionExitDescriptor::latest_valid_by_service_did(exits, now_ms, false)
        .into_iter()
        .filter(|descriptor| descriptor.matches_network(network_id))
        .filter(|descriptor| descriptor.offers_service(service.as_str()))
        .collect()
}

fn eligible_relay_dids(
    dht_protocol: DhtProtocolMode,
    now_ms: u128,
    local: Did,
    online_nodes: impl IntoIterator<Item = OnlineNodeDescriptor>,
) -> Vec<OnionRouteHop> {
    OnlineNodeDescriptor::latest_valid_by_did(online_nodes, now_ms, false)
        .into_iter()
        .filter(|descriptor| descriptor.matches_dht_protocol(dht_protocol))
        .filter(has_onion_relay_capability)
        .map(|descriptor| OnionRouteHop::new(descriptor.did, descriptor.session_public_key))
        .filter(|hop| hop.did != local)
        .map(|hop| (hop.did, hop))
        .collect::<BTreeMap<_, _>>()
        .into_values()
        .collect()
}

fn has_onion_relay_capability(descriptor: &OnlineNodeDescriptor) -> bool {
    descriptor
        .capabilities
        .iter()
        .any(|capability| capability == ONION_RELAY_CAPABILITY)
}

fn has_duplicate_dids(hops: &[Did]) -> bool {
    let mut seen = BTreeSet::new();
    hops.iter().any(|did| !seen.insert(*did))
}

fn validate_route_hops(
    service: &OnionServiceName,
    encryption_hops: &[OnionRouteHop],
    exit: &OnionExitDescriptor,
) -> Result<()> {
    if encryption_hops.is_empty() || encryption_hops.len() > usize::from(MAX_ONION_CIRCUIT_HOPS) {
        return Err(Error::OnionRouteError(
            OnionRouteError::HopCountOutOfBounds {
                hop_count: encryption_hops.len(),
                max_hops: MAX_ONION_CIRCUIT_HOPS,
            },
        ));
    }
    let Some(last) = encryption_hops.last() else {
        return Err(Error::OnionRouteError(OnionRouteError::RouteHasNoHops));
    };
    if last.did != exit.did || last.session_public_key != exit.session_public_key {
        return Err(Error::OnionRouteError(OnionRouteError::ExitHopMismatch));
    }
    let hops = encryption_hops
        .iter()
        .map(|hop| hop.did)
        .collect::<Vec<_>>();
    if has_duplicate_dids(&hops) {
        return Err(Error::OnionRouteError(OnionRouteError::DuplicateRouteHops));
    }
    if !exit.offers_service(service.as_str()) {
        return Err(Error::OnionRouteError(OnionRouteError::ExitServiceMismatch));
    }
    Ok(())
}

fn parse_route_service(service: impl AsRef<str>) -> Result<OnionServiceName> {
    let service = service.as_ref();
    if service.trim().is_empty() {
        return Err(Error::OnionRouteError(OnionRouteError::EmptyRouteService));
    }
    OnionServiceName::parse(service)
}

#[cfg(test)]
mod tests;