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.
//! Laws of `Hop_i` (`circuit::hop`): paid, at most once, identity, and the client position.

use rings_core::dht::Did;

use super::super::admission::OnionAdmissionRejection;
use super::super::admission::OnionChargeRejection;
use super::super::hop::hop;
use super::super::hop::OnionHopDrop;
use super::super::hop::OnionHopOutcome;
use super::arguments;
use super::is_tag;
use super::Fixture;
use super::CLIENT;
use super::NOW_MS;
use crate::onion::circuit::OnionAdmissionLink;
use crate::onion::session::OnionSessionArguments;
use crate::onion::sphinx::cell::OnionCell;
use crate::onion::sphinx::cell::OnionStep;
use crate::onion::sphinx::class::OnionLoopClass;
use crate::onion::OnionServiceName;

/// A cell from a sender with no live link is refused before it is charged or peeled (Paid).
#[test]
fn test_a_cell_off_a_live_link_is_refused_unpeeled() {
    let mut fixture = Fixture::new();
    let built = fixture.build(1, b"value");

    assert!(matches!(
        fixture.hops[0].step(Did::from(7_u32), built.cell),
        OnionHopOutcome::Refused(OnionChargeRejection::LinkNotLive)
    ));
}

/// A cell of the right width whose header is noise is charged and dropped at the peel: cover
/// and garbage cost their sender the same as a real cell (Paid).
#[test]
fn test_noise_of_a_class_width_is_charged_then_dropped_at_the_peel() {
    let mut fixture = Fixture::new();
    let noise = OnionCell::parse(&vec![0x5a; OnionLoopClass::DEFAULT.cell_bytes()]).expect("width");

    assert!(matches!(
        fixture.hops[0].step(Did::from(CLIENT), noise),
        OnionHopOutcome::Dropped(OnionHopDrop::Peel(_))
    ));
    assert_eq!(
        fixture.hops[0].admission.sender_units(Did::from(CLIENT)),
        1,
        "charged u(b) exactly once"
    );
}

/// Paid, per class (#834 Tests): a class-`b` cell is charged `b / 16 KiB` units before its
/// header is read, and a refused one nothing.
#[test]
fn test_a_cell_is_charged_the_units_of_its_class() {
    let mut fixture = Fixture::new();
    let class = OnionLoopClass::MiB1;
    let noise = OnionCell::parse(&vec![0x5a; class.cell_bytes()]).expect("width");

    assert!(matches!(
        fixture.hops[0].step(Did::from(CLIENT), noise),
        OnionHopOutcome::Dropped(OnionHopDrop::Peel(_))
    ));
    assert_eq!(
        fixture.hops[0].admission.sender_units(Did::from(CLIENT)),
        class.units().get()
    );
    let refused = OnionCell::parse(&vec![0; OnionLoopClass::DEFAULT.cell_bytes()]).expect("width");
    assert!(matches!(
        fixture.hops[0].step(Did::from(7_u32), refused),
        OnionHopOutcome::Refused(_)
    ));
    assert_eq!(fixture.hops[0].admission.sender_units(Did::from(7_u32)), 0);
}

/// A layer is relayed once; the same cell again is its replay, charged and dropped (L9), and
/// the relayed cell keeps the received class and width (L1).
#[test]
fn test_a_relayed_layer_is_admitted_at_most_once_and_keeps_its_width() {
    let mut fixture = Fixture::new();
    let bytes = fixture.build(2, b"value").cell.into_bytes();
    let received = OnionCell::parse(&bytes).expect("width");
    let class = received.class();

    let OnionHopOutcome::Stepped(OnionStep::Relayed { next, cell }) =
        fixture.hops[0].step(Did::from(CLIENT), received)
    else {
        panic!("the guard relays");
    };
    assert_eq!(next, fixture.hops[1].did());
    assert_eq!(cell.class(), class);
    assert_eq!(cell.into_bytes().len(), bytes.len());
    assert!(matches!(
        fixture.hops[0].step(Did::from(CLIENT), OnionCell::parse(&bytes).expect("width")),
        OnionHopOutcome::Dropped(OnionHopDrop::Admission(OnionAdmissionRejection::Replayed))
    ));
}

/// A node that registers no `relay` drops a relay layer after admission (D1′).
#[test]
fn test_a_relay_layer_at_a_non_relay_is_dropped() {
    let mut fixture = Fixture::new();
    let built = fixture.build(3, b"value");
    let guard = &mut fixture.hops[0];

    assert!(matches!(
        hop(
            &mut guard.admission,
            std::slice::from_ref(&guard.key),
            false,
            |_| false,
            Did::from(CLIENT),
            NOW_MS,
            built.cell,
        ),
        OnionHopOutcome::Dropped(OnionHopDrop::NotRelay)
    ));
}

/// The loop reaches `h` as its application and the client's value, and the reply `h` produces
/// returns through `r₁₁, g` to the client, which recognises its tag without a peel (D6′).
#[test]
fn test_a_loop_runs_to_its_symbol_and_returns_to_the_client() {
    let mut fixture = Fixture::new();
    let built = fixture.build(4, b"client value");
    let cell = fixture.run_forward_segment(built.cell);
    let from = fixture.hops[1].did();

    let OnionHopOutcome::Stepped(OnionStep::Consumed {
        symbol,
        arguments: consumed,
        value,
        surb,
    }) = fixture.hops[2].step(from, cell)
    else {
        panic!("h consumes");
    };
    assert_eq!(symbol, OnionServiceName::tcp().into());
    assert_eq!(OnionSessionArguments::decode(&consumed), Some(arguments()));
    assert_eq!(value.as_slice(), b"client value");

    let (next, reply) = surb.produce(b"reply value").expect("produce the reply");
    assert_eq!(next, fixture.hops[3].did());
    let returned = fixture.run_return_segment(reply);
    assert_eq!(returned.loop_tag(), built.reply.tag);

    // The client, as a node, sees the cell arrive from its guard with a live tag: `Returned`,
    // even under a key that could not peel it.
    let mut client = super::Hop::new(0x63).linked(&[fixture.hops[0].did()]);
    let guard = fixture.hops[0].did();
    let OnionHopOutcome::Returned { tag, cell } = hop(
        &mut client.admission,
        std::slice::from_ref(&client.key),
        true,
        is_tag(built.reply.tag),
        guard,
        NOW_MS,
        returned,
    ) else {
        panic!("the client's own tag returns");
    };
    assert_eq!(tag, built.reply.tag);
    assert_eq!(
        cell.open(&built.reply.key).expect("opens").as_slice(),
        b"reply value"
    );
}

/// Adjacency: a relay layer whose `next` is not a live link of the hop is dropped before replay
/// admission, so it neither makes the hop emit toward an unlinked peer nor burns the layer's
/// replay nonce before that link finishes opening (#895 H1, #1262).
#[test]
fn test_a_relay_layer_to_a_peer_with_no_link_is_dropped() {
    let mut fixture = Fixture::new();
    let built = fixture.build(5, b"value");
    let cell_bytes = built.cell.into_bytes();
    let r02 = fixture.hops[1].did();
    let guard = &mut fixture.hops[0];
    guard
        .admission
        .link_closed(NOW_MS, OnionAdmissionLink::new(r02, 0));

    assert!(matches!(
        guard.step(
            Did::from(CLIENT),
            OnionCell::parse(&cell_bytes).expect("width"),
        ),
        OnionHopOutcome::Dropped(OnionHopDrop::NextNotLive)
    ));
    assert_eq!(
        guard.admission.sender_units(Did::from(CLIENT)),
        1,
        "Paid still charges u(b) on NextNotLive"
    );

    // Once the link to `next` opens, the unburned cell succeeds instead of failing Replayed.
    guard
        .admission
        .link_opened(NOW_MS, OnionAdmissionLink::new(r02, 1))
        .expect("reopen link");
    assert!(matches!(
        guard.step(
            Did::from(CLIENT),
            OnionCell::parse(&cell_bytes).expect("width"),
        ),
        OnionHopOutcome::Stepped(OnionStep::Relayed { next, .. }) if next == r02
    ));
}

/// In-process delegation renewal (#1153, #1223): a hop whose key ring holds `[current, retained]`
/// peels cells sealed to the retained pre-renewal key as well as cells sealed to `current`, and
/// drops cells sealed to the pre-renewal key once it is no longer in the ring.
#[test]
fn test_hop_peels_cells_sealed_to_retained_pre_renewal_key() {
    let mut fixture = Fixture::new();
    let built_pre_renewal = fixture.build(6, b"pre-renewal");
    let pre_renewal_bytes = built_pre_renewal.cell.into_bytes();

    // Rotate guard's delegatee key for the same account DID.
    let guard_secret = crate::onion::tests::fixture::fixture_secret(1);
    let renewed_key = rings_core::delegation::DelegateeKey::new_with_seckey_at(
        &guard_secret,
        600_000,
        NOW_MS + 1,
    )
    .expect("renewed guard delegation");
    assert_eq!(renewed_key.delegator_did(), fixture.hops[0].did());
    assert_ne!(
        renewed_key.delegatee_public_key(),
        fixture.hops[0].key.delegatee_public_key()
    );

    let retained_key = std::mem::replace(&mut fixture.hops[0].key, renewed_key.clone());
    let built_post_renewal = fixture.build(7, b"post-renewal");

    // With only `current` (`[renewed_key]`), the pre-renewal cell fails HMAC verification.
    assert!(matches!(
        hop(
            &mut fixture.hops[0].admission,
            std::slice::from_ref(&renewed_key),
            true,
            |_| false,
            Did::from(CLIENT),
            NOW_MS,
            OnionCell::parse(&pre_renewal_bytes).expect("width"),
        ),
        OnionHopOutcome::Dropped(OnionHopDrop::Peel(
            crate::onion::sphinx::header::OnionPeelError::Invalid
        ))
    ));

    // With `[renewed_key, retained_key]`, both pre-renewal and post-renewal cells peel and relay.
    let keys = [renewed_key, retained_key];
    let r02 = fixture.hops[1].did();
    let guard = &mut fixture.hops[0];
    assert!(matches!(
        hop(
            &mut guard.admission,
            &keys,
            true,
            |_| false,
            Did::from(CLIENT),
            NOW_MS,
            OnionCell::parse(&pre_renewal_bytes).expect("width"),
        ),
        OnionHopOutcome::Stepped(OnionStep::Relayed { next, .. }) if next == r02
    ));
    assert!(matches!(
        hop(
            &mut guard.admission,
            &keys,
            true,
            |_| false,
            Did::from(CLIENT),
            NOW_MS,
            built_post_renewal.cell,
        ),
        OnionHopOutcome::Stepped(OnionStep::Relayed { next, .. }) if next == r02
    ));
}