rings-node 1.0.0-pre.8

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.
Documentation
//! Golden wire bytes of the loop data plane (#843).
//!
//! Law (#834 L10): every encoding below is fixed byte for byte. Writing `enc : T → Bytes`, each
//! test fixes one value `v₀` built only from constants and seeded generators and asserts
//! `enc(v₀) = golden`, with `dec ∘ enc (v₀) = v₀` where a decoder exists. A cell is pinned by its
//! SHA-256 digest `H(enc(v₀))` and its width, since it is `b` bytes.
//!
//! The generator is ChaCha20 from a fixed seed, which is portable across `rand` releases. The
//! frames, `ā`, the uniform layers, a reply block's reply cell and the descriptor are pure
//! functions of constants, so they pin the wire alone; the digests of a built loop cell and of a
//! built reply block also pin the order in which the builder draws its secrets, which is part of
//! a reproducible build of a cell, not of the wire, so a change there that keeps every other
//! golden is a refactor of the builder and is re-pinned with it.
//!
//! A failing test here is a wire cutover, never a fixture to refresh: a change to any of these
//! bytes is a total cutover of the network and also moves `crate::tests::test_wire_goldens`
//! (#1141), requiring a `WIRE_VERSION` bump under the rule of `rings_core::message::payload::frame`.

use rand::SeedableRng;
use rand_chacha::ChaCha20Rng;
use rings_core::delegation::DelegateeKey;
use rings_core::dht::Did;
use rings_core::ecc::PublicKey;
use rings_core::ecc::VerificationPublicKey;
use rings_core::message::MessageSigner;
use sha2::Digest;
use sha2::Sha256;

use super::super::OnionExpiry;
use super::super::OnionReplayNonce;
use super::super::ONION_CIRCUIT_NAMESPACE;
use crate::descriptor::SignedDescriptor;
use crate::descriptor::SignedDescriptorBody;
use crate::onion::session::frame::OnionFrame;
use crate::onion::session::frame::OnionSequence;
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::build_surb;
use crate::onion::sphinx::cell::OnionSurb;
use crate::onion::sphinx::class::OnionLoopClass;
use crate::onion::sphinx::header::OnionHeaderMac;
use crate::onion::sphinx::layer::OnionApplication;
use crate::onion::sphinx::layer::OnionLayer;
use crate::onion::sphinx::layer::OnionLayerApplication;
use crate::onion::sphinx::layer::OnionLayerHead;
use crate::onion::sphinx::seed::OnionCarrySeed;
use crate::onion::sphinx::seed::OnionSegmentSeed;
use crate::onion::tests::fixture::fixture_secret;
use crate::onion::tests::fixture::grid_expiry;
use crate::onion::tests::fixture::session_loop;
use crate::onion::OnionExitDescriptorBody;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionExitTarget;
use crate::onion::OnionLoop;
use crate::onion::OnionProcessEpoch;
use crate::onion::OnionRouteHop;
use crate::onion::OnionServiceName;
use crate::onion::ONION_EXITS_TOPIC;
use crate::online::OnlineNodeType;
use crate::tests::TEST_NETWORK_ID;

/// Pinned `enc(data(5, T, t = example.com:443, w′ = "ab"))`.
const GOLDEN_DATA_WITH_TARGET: &str = "000000000501000f6578616d706c652e636f6d3a3434336162";
/// Pinned `enc(data(6, 0, "xyz"))`.
const GOLDEN_DATA: &str = "00000000060078797a";
/// Pinned `enc(fin(7, 0))`.
const GOLDEN_FIN: &str = "010000000700";
/// Pinned `enc(fin(8, T, t = example.com:443))`: a `fin` sent before the first reply.
const GOLDEN_FIN_WITH_TARGET: &str = "010000000801000f6578616d706c652e636f6d3a343433";
/// Pinned `enc(abort(9))`.
const GOLDEN_ABORT: &str = "0300000009";
/// Pinned `H(enc(credit(m, υ)))` of the fixture reply block, `m = 0x01020304`.
const GOLDEN_CREDIT_DIGEST: &str =
    "f48d4af3690620c269caa1890cddebde6bba7d4d3500e696a672966516ee036f";
/// Pinned `ā = ς ‖ SHA-256(t) ‖ 0^16` of the fixture session.
const GOLDEN_SESSION_ARGUMENTS: &str =
    "515151515151515151515151515151512d92752e69614799ea8467c10d252c76f79c85845cf23d54406ef49ab463ff0c00000000000000000000000000000000";
/// Pinned `H(χ₁ ‖ y₀)` of the fixture loop's first cell.
const GOLDEN_LOOP_CELL_DIGEST: &str =
    "1462b1fa8ac44ac115baddb30d12215c7caed6c4df033efd0d8d8d7385125fea";
/// Pinned `t_⋄` of the fixture loop.
const GOLDEN_LOOP_REPLY_TAG: &str = "64542fdd8b597b71e4d95d989f31d1d0";
/// Pinned signing data of [`exit_descriptor_body`]: a lease, signing its freshness window and
/// end and no heartbeat (#918).
const GOLDEN_EXIT_DESCRIPTOR_SIGNING_DATA: &str =
    "000000000000000000000000000000000a0b0c0d00060606060606060606060606060606060606060606060606060606060606060606070707070707070707070707070707070707070707070707070707070707070707313131313131313131313131313131310101056874747073020f6578616d706c652e636f6d3a343433052a3a343433010b31302e302e302e313a32321080804080d095ffbc3190bf05a0dd9bffbc310c302e302e302d676f6c64656e";

/// The generator seed of every seeded golden.
const GOLDEN_SEED: [u8; 32] = [0x43; 32];
/// Pinned `enc(λ)` of a relay layer, before the header's stream cipher.
const GOLDEN_RELAY_LAYER: &str =
    "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010203043131313131313131313131313131313100000000000249f0232323232323232323232323232323232424242424242424242424242424242424242424242424242424242424242424252525252525252525252525252525252525252525252525252525252525252526262626262626262626262626262626";
/// Pinned `enc(λ)` of a symbol layer applying `tcp` to the fixture session (`code(tcp) = 121 = 0x79`).
const GOLDEN_SYMBOL_LAYER: &str =
    "79515151515151515151515151515151512d92752e69614799ea8467c10d252c76f79c85845cf23d54406ef49ab463ff0c0000000000000000000000000000000000000000000000000000000000000000010203043131313131313131313131313131313100000000000249f0232323232323232323232323232323232424242424242424242424242424242424242424242424242424242424242424252525252525252525252525252525252525252525252525252525252525252526262626262626262626262626262626";
/// Pinned `H(reply cell)` of the fixture reply block producing `golden reply`.
const GOLDEN_SURB_REPLY_DIGEST: &str =
    "3a314348bfb2f75467dcc5e2df8101b6f4694ed02c4938bde599cc3eda0601cf";

/// Frozen signing domain of onion-exit descriptors.
const EXIT_DESCRIPTOR_DOMAIN_TAG: &[u8] = b"rings-node:onion-exit-descriptor";
/// The fixture session's target.
const FIXTURE_TARGET: &[u8] = b"example.com:443";
/// The fixture loop's process epoch.
const FIXTURE_EPOCH: OnionProcessEpoch = OnionProcessEpoch::new([0x31; 16]);

/// Render bytes as lowercase hex so a golden mismatch prints a readable diff.
fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

/// `H(bytes)` in hex.
fn digest(bytes: &[u8]) -> String {
    hex(Sha256::digest(bytes).as_slice())
}

/// The route hop `seed`: DID and session key both fixed by `seed`.
fn hop(seed: u8) -> OnionRouteHop {
    OnionRouteHop::new(
        Did::from(u32::from(seed)),
        fixture_secret(seed).pubkey(),
        FIXTURE_EPOCH,
    )
}

/// The fixture loop `g = 1, r₀₂ = 2, h = 3, r₁₁ = 4, g = 1`.
fn fixture_loop() -> OnionLoop<OnionRouteHop> {
    session_loop([1, 2, 3, 4].map(hop))
}

/// The fixture expiry `x = 5Q`.
fn fixture_expiry() -> OnionExpiry {
    grid_expiry(5)
}

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

/// Assert `enc(frame) = golden` and that the encoding decodes to a frame encoding the same.
fn assert_frame(frame: &OnionFrame, golden: &str) {
    let encoded = frame
        .encode(OnionLoopClass::DEFAULT)
        .expect("the frame fits");
    assert_eq!(hex(encoded.as_slice()), golden);
    let decoded = OnionFrame::decode(OnionLoopClass::DEFAULT, encoded.as_slice()).expect("decode");
    assert_eq!(
        decoded.encode(OnionLoopClass::DEFAULT).expect("fits"),
        encoded
    );
}

#[test]
fn test_session_frames_are_pinned() {
    assert_frame(
        &OnionFrame::Data {
            sequence: OnionSequence::new(5),
            target: Some(bytes::Bytes::from_static(FIXTURE_TARGET)),
            payload: bytes::Bytes::from_static(b"ab"),
        },
        GOLDEN_DATA_WITH_TARGET,
    );
    assert_frame(
        &OnionFrame::Data {
            sequence: OnionSequence::new(6),
            target: None,
            payload: bytes::Bytes::from_static(b"xyz"),
        },
        GOLDEN_DATA,
    );
    assert_frame(
        &OnionFrame::Fin {
            sequence: OnionSequence::new(7),
            target: None,
        },
        GOLDEN_FIN,
    );
    assert_frame(
        &OnionFrame::Fin {
            sequence: OnionSequence::new(8),
            target: Some(bytes::Bytes::from_static(FIXTURE_TARGET)),
        },
        GOLDEN_FIN_WITH_TARGET,
    );
    assert_frame(
        &OnionFrame::Abort {
            sequence: OnionSequence::new(9),
        },
        GOLDEN_ABORT,
    );
}

/// The uniform layer of `next`, applying `application`, with every other field a constant.
fn layer(application: OnionLayerApplication) -> OnionLayer {
    OnionLayer {
        head: OnionLayerHead {
            application,
            next: Did::from(0x0102_0304_u32),
            epoch: FIXTURE_EPOCH,
            expiry: fixture_expiry(),
            nonce: OnionReplayNonce::new([0x23; 16]),
        },
        inbound: OnionCarrySeed::new([0x24; 32]),
        outbound: OnionSegmentSeed::new([0x25; 32]),
    }
}

/// The plaintext uniform layer `λ` (#834 D6″), field by field, for a relay and for a symbol:
/// the one encoding every hop decodes.
#[test]
fn test_uniform_layers_are_pinned() {
    let mac = OnionHeaderMac::new([0x26; 16]);
    let relay = layer(OnionLayerApplication::Relay).encode(&mac);
    let symbol = layer(OnionLayerApplication::Apply(OnionApplication {
        symbol: OnionServiceName::tcp().into(),
        arguments: session_arguments().encode(),
    }))
    .encode(&mac);

    assert_eq!(hex(relay.as_slice()), GOLDEN_RELAY_LAYER);
    assert_eq!(hex(symbol.as_slice()), GOLDEN_SYMBOL_LAYER);
    let (decoded, decoded_mac) = OnionLayer::decode(symbol.as_slice()).expect("decodes");
    assert_eq!(decoded.encode(&decoded_mac).as_slice(), symbol.as_slice());
}

/// The reply cell a reply block produces from a fixed value.
#[test]
fn test_surb_reply_cell_is_pinned() {
    // υ = next ‖ χ_υ ‖ σ_υ ‖ x_υ from constants: the reply cell is a function of wire inputs only.
    let block = [
        [0x11; 20].as_slice(),
        vec![0x22; 2919].as_slice(),
        [0x33; 32].as_slice(),
        fixture_expiry().to_wire_ms().to_be_bytes().as_slice(),
    ]
    .concat();
    let surb = OnionSurb::decode(OnionLoopClass::DEFAULT, &block).expect("a reply block");
    let (next, cell) = surb.produce(b"golden reply").expect("produce");

    assert_eq!(next.to_string(), format!("0x{}", "11".repeat(20)));
    assert_eq!(
        digest(cell.into_bytes().as_slice()),
        GOLDEN_SURB_REPLY_DIGEST
    );
}

#[test]
fn test_credit_frame_is_pinned() {
    let (surb, _) = build_surb(
        fixture_loop().return_path(),
        Did::from(99_u32),
        OnionLoopClass::DEFAULT,
        fixture_expiry(),
        &mut ChaCha20Rng::from_seed(GOLDEN_SEED),
    )
    .expect("build the reply block");
    let encoded = OnionFrame::Credit {
        mark: OnionSequence::new(0x0102_0304),
        surbs: vec![surb],
    }
    .encode(OnionLoopClass::DEFAULT)
    .expect("one block fits");

    assert_eq!(hex(&encoded[..5]), "0201020304", "02 ‖ m:u32");
    assert_eq!(digest(encoded.as_slice()), GOLDEN_CREDIT_DIGEST);
    let decoded = OnionFrame::decode(OnionLoopClass::DEFAULT, encoded.as_slice()).expect("decodes");
    assert!(matches!(
        &decoded,
        OnionFrame::Credit { mark, surbs } if mark.value() == 0x0102_0304 && surbs.len() == 1
    ));
    assert_eq!(
        decoded
            .encode(OnionLoopClass::DEFAULT)
            .expect("re-encodes")
            .as_slice(),
        encoded.as_slice(),
        "dec ∘ enc = id"
    );
}

#[test]
fn test_session_arguments_are_pinned() {
    let arguments = session_arguments().encode();

    assert_eq!(hex(arguments.as_bytes()), GOLDEN_SESSION_ARGUMENTS);
    assert_eq!(
        OnionSessionArguments::decode(&arguments),
        Some(session_arguments())
    );
}

/// The whole first cell of a seeded loop: every header, carry and padding byte is a function
/// of the hops' keys, the applications, the value and the seed.
#[test]
fn test_loop_cell_is_pinned() {
    let built = build_loop(
        &fixture_loop(),
        &[OnionApplication {
            symbol: OnionServiceName::tcp().into(),
            arguments: session_arguments().encode(),
        }],
        Did::from(99_u32),
        OnionLoopClass::DEFAULT,
        fixture_expiry(),
        b"golden value",
        &mut ChaCha20Rng::from_seed(GOLDEN_SEED),
    )
    .expect("build the loop");

    assert_eq!(built.guard, Did::from(1_u32));
    let cell = built.cell.into_bytes();
    assert_eq!(cell.len(), OnionLoopClass::DEFAULT.cell_bytes());
    assert_eq!(digest(cell.as_slice()), GOLDEN_LOOP_CELL_DIGEST);
    assert_eq!(hex(built.reply.tag.as_bytes()), GOLDEN_LOOP_REPLY_TAG);
}

/// Exit-descriptor body whose every signed field is a distinct constant.
fn exit_descriptor_body() -> OnionExitDescriptorBody {
    OnionExitDescriptorBody {
        did: Did::from(0x0a0b_0c0d_u32),
        public_key: VerificationPublicKey::Secp256k1(PublicKey([0x06; 33])),
        delegatee_public_key: PublicKey([0x07; 33]),
        process_epoch: FIXTURE_EPOCH,
        node_type: OnlineNodeType::Native,
        network_id: TEST_NETWORK_ID,
        service: OnionServiceName::https(),
        policy: OnionExitPolicy {
            allowed_targets: vec![
                OnionExitTarget::parse("example.com:443").expect("target"),
                OnionExitTarget::parse("*:443").expect("target"),
            ],
            denied_targets: vec![OnionExitTarget::parse("10.0.0.1:22").expect("target")],
            max_sessions: 16,
            max_bytes_per_minute: 1_048_576,
        },
        started_at_ms: 1_700_000_000_000,
        fresh_for_ms: 90_000,
        expires_at_ms: 1_700_000_100_000,
        version: "0.0.0-golden".to_string(),
    }
}

#[test]
fn test_exit_descriptor_signing_data_is_pinned() {
    let body = exit_descriptor_body();
    let signing_data = body.body_signing_data().expect("descriptor signing data");
    let session = DelegateeKey::new_with_seckey(&fixture_secret(9)).expect("fixture delegation");
    let signature = MessageSigner::new(&session, TEST_NETWORK_ID)
        .sign(OnionExitDescriptorBody::DOMAIN_TAG, signing_data.as_slice())
        .expect("sign descriptor");
    let descriptor = body.into_signed_descriptor(signature);

    assert_eq!(
        hex(signing_data.as_slice()),
        GOLDEN_EXIT_DESCRIPTOR_SIGNING_DATA
    );
    assert_eq!(
        descriptor
            .descriptor_signing_data()
            .expect("descriptor signing data"),
        signing_data
    );
}

#[test]
fn test_frozen_onion_labels() {
    assert_eq!(
        OnionExitDescriptorBody::DOMAIN_TAG.as_bytes(),
        EXIT_DESCRIPTOR_DOMAIN_TAG
    );
    assert_eq!(ONION_EXITS_TOPIC, "onion_exits");
    assert_eq!(ONION_CIRCUIT_NAMESPACE, "onion-circuit");
}