rings-node 1.0.0-pre.6

Rings is a browser-native, structured peer-to-peer network: browser tabs and native daemons find each other by DID and talk over WebRTC, routed by a Chord DHT.
//! Law tests of the loop data plane (#843), one module per law set of the parent documentation.
//!
//! Every test is deterministic: randomness comes from seeded [`StdRng`]s, hop keys from fixed
//! scalars, and time is an argument, so a failure reproduces bit for bit.

mod test_hop;
mod test_session_ends;
mod test_tags;
mod test_wire_golden;

use std::num::NonZeroUsize;

use rand::rngs::StdRng;
use rand::SeedableRng;
use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;

use super::admission::OnionAdmissionState;
use super::admission::OnionReplayFilterKey;
use super::hop::hop;
use super::hop::OnionHopOutcome;
use super::OnionExpiry;
use crate::onion::circuit::OnionAdmissionLink;
use crate::onion::session::OnionSessionArguments;
use crate::onion::session::OnionSessionId;
use crate::onion::session::OnionTargetDigest;
use crate::onion::sphinx::builder::build_loop;
use crate::onion::sphinx::builder::OnionBuiltLoop;
use crate::onion::sphinx::cell::OnionCell;
use crate::onion::sphinx::cell::OnionStep;
use crate::onion::sphinx::class::OnionLoopClass;
use crate::onion::sphinx::header::OnionLoopTag;
use crate::onion::sphinx::layer::OnionApplication;
use crate::onion::tests::fixture::fixture_route_hop;
use crate::onion::tests::fixture::fixture_secret;
use crate::onion::tests::fixture::grid_expiry;
use crate::onion::tests::fixture::session_loop;
use crate::onion::OnionLoop;
use crate::onion::OnionProcessEpoch;
use crate::onion::OnionRouteHop;
use crate::onion::OnionServiceName;

/// The process epoch every fixture hop runs.
const EPOCH: OnionProcessEpoch = OnionProcessEpoch::new([0x43; 16]);

/// The arrival instant of every fixture cell: `2Q`.
const NOW_MS: u128 = 60_000;

/// The DID the fixture client receives at.
const CLIENT: u32 = 99;

/// The fixture loop's expiry `x = 5Q`, admissible at [`NOW_MS`].
fn expiry() -> OnionExpiry {
    grid_expiry(5)
}

/// One hop of the fixture loop: its key and its admission state.
struct Hop {
    /// `d_i`, the hop's session key.
    key: DelegateeKey,
    /// The hop's admission state, with its predecessor's link live.
    admission: OnionAdmissionState,
}

impl Hop {
    /// The hop with the fixed scalar `(seed)·0x0101…01`, with no link live yet.
    fn new(seed: u8) -> Self {
        Self {
            key: DelegateeKey::new_with_seckey(&fixture_secret(seed)).expect("fixture delegation"),
            admission: OnionAdmissionState::new(
                EPOCH,
                OnionReplayFilterKey::new([seed; 32]),
                NonZeroUsize::new(2).expect("non-zero"),
            ),
        }
    }

    /// The hop, with a live link to each of `peers`.
    fn linked(mut self, peers: &[Did]) -> Self {
        for peer in peers {
            self.admission
                .link_opened(NOW_MS, OnionAdmissionLink::new(*peer, 0))
                .expect("the fixture's table holds its links");
        }
        self
    }

    /// The hop's DID.
    fn did(&self) -> Did {
        self.key.delegator_did()
    }

    /// The hop's route entry.
    fn route_hop(&self) -> OnionRouteHop {
        fixture_route_hop(&self.key, EPOCH)
    }

    /// `Hop_i` of `cell` from `from` at [`NOW_MS`], as a relaying node that owns no loop tags.
    fn step(&mut self, from: Did, cell: OnionCell) -> OnionHopOutcome {
        hop(
            &mut self.admission,
            std::slice::from_ref(&self.key),
            true,
            |_| false,
            from,
            NOW_MS,
            cell,
        )
    }
}

/// The fixture loop `client → g → r₀₂ → h → r₁₁ → g → client`: its four hops, `[g, r₀₂, h,
/// r₁₁]`, each with its predecessor's and its successor's link live (a relay forwards only to a
/// live link). The guard has three neighbours: the client, `r₀₂` and `r₁₁`.
struct Fixture {
    /// `[g, r₀₂, h, r₁₁]`.
    hops: [Hop; 4],
}

impl Fixture {
    /// The fixture's hops.
    fn new() -> Self {
        let client = Did::from(CLIENT);
        let [g, r02, h, r11] = [1, 2, 3, 4].map(Hop::new);
        let dids = [g.did(), r02.did(), h.did(), r11.did()];
        Self {
            hops: [
                g.linked(&[client, dids[1], dids[3]]),
                r02.linked(&[dids[0], dids[2]]),
                h.linked(&[dids[1], dids[3]]),
                r11.linked(&[dids[2], dids[0]]),
            ],
        }
    }

    /// The route `g, r₀₂, h, r₁₁, g`.
    fn route(&self) -> OnionLoop<OnionRouteHop> {
        session_loop(self.hops.each_ref().map(Hop::route_hop))
    }

    /// A seeded loop applying `tcp` at `h` to `value`.
    fn build(&self, seed: u64, value: &[u8]) -> OnionBuiltLoop {
        build_loop(
            &self.route(),
            &[OnionApplication {
                symbol: OnionServiceName::tcp().into(),
                arguments: arguments().encode(),
            }],
            Did::from(CLIENT),
            OnionLoopClass::DEFAULT,
            expiry(),
            value,
            &mut StdRng::seed_from_u64(seed),
        )
        .expect("build the fixture loop")
    }

    /// Run the forward half `g, r₀₂` and return the cell as `h` receives it.
    fn run_forward_segment(&mut self, cell: OnionCell) -> OnionCell {
        let client = Did::from(CLIENT);
        let guard = self.hops[0].did();
        let cell = relayed(self.hops[0].step(client, cell), self.hops[1].did());
        relayed(self.hops[1].step(guard, cell), self.hops[2].did())
    }

    /// Run the return half `r₁₁, g` of a reply cell produced at `h`, and return it as the
    /// client receives it.
    fn run_return_segment(&mut self, cell: OnionCell) -> OnionCell {
        let h = self.hops[2].did();
        let r11 = self.hops[3].did();
        let cell = relayed(self.hops[3].step(h, cell), self.hops[0].did());
        relayed(self.hops[0].step(r11, cell), Did::from(CLIENT))
    }
}

/// The fixture session's arguments.
fn arguments() -> OnionSessionArguments {
    OnionSessionArguments {
        session: OnionSessionId::new([0x51; 16]),
        digest: OnionTargetDigest::of(b"example.com:443"),
    }
}

/// The cell of a `Relayed` outcome, which must go to `next`.
fn relayed(outcome: OnionHopOutcome, next: Did) -> OnionCell {
    match outcome {
        OnionHopOutcome::Stepped(OnionStep::Relayed { next: to, cell }) => {
            assert_eq!(to, next);
            cell
        }
        other => panic!("expected a relay to {next}, got {other:?}"),
    }
}

/// Whether `tag` is `expected`, as a client's tag table would answer.
fn is_tag(expected: OnionLoopTag) -> impl Fn(&OnionLoopTag) -> bool {
    move |tag| *tag == expected
}