elligator2 0.1.0

Elligator2 for Curve25519: encode X25519 public keys as uniform random bit strings and back. Built on fiat-crypto's formally verified field arithmetic, differentially tested, no_std.
Documentation
//! Differential tests against an independent implementation.
//!
//! `curve25519-elligator2` is the Tor Project's fork of `curve25519-dalek`,
//! carrying the representative API used by the Rust obfs4/lyrebird stack. It is a
//! **dev-dependency only** and never ships. A hand-rolled cryptographic map is
//! only a defensible claim if an independent implementation agrees with it, and
//! this file is where that claim gets checked.
//!
//! # What each tier actually proves
//!
//! Our key *generator* and the oracle's are not byte-comparable end to end, and
//! it is worth being precise about why rather than papering over it. The oracle's
//! `Randomized::to_representative` takes a private key and builds its dirty point
//! with its own hard-coded low-order point selection; ours uses
//! `curve25519_dalek::constants::EIGHT_TORSION` indexed by the discarded clamping
//! bits. Both are uniform over the eight cosets and both are correct — the choice
//! of torsion point is a free parameter — so the two produce different points for
//! the same private key.
//!
//! The maps themselves are still pinned exactly, from both directions:
//!
//! | Tier | Compares | Pins |
//! |---|---|---|
//! | 1 | our decoder vs oracle decoder, random strings | the forward map, bit for bit |
//! | 2 | oracle decoder applied to *our* representatives | our inverse map is a true inverse of *their* forward map |
//! | 3 | our decoder applied to *oracle* representatives | their inverse map is a true inverse of *our* forward map |
//! | 4 | both encoders on the *same* point and tweak | the inverse map, bit for bit |
//!
//! Tier 1 fixes the forward map. Tiers 2 and 3 fix the inverse in both
//! directions; tier 4 pins it exactly. A bug in either map fails at least one
//! tier.
//!
//! Then [`our_points_are_not_always_prime_order`] covers the one failure that
//! none of the four would notice.

use curve25519_elligator2::{MapToPointVariant, MontgomeryPoint as OracleMontgomery, Randomized};
use elligator2::{from_representative, generate, to_representative};
use rand::Rng;

/// Decode with the oracle, returning the Montgomery u-coordinate.
fn oracle_decode(representative: &[u8; 32]) -> [u8; 32] {
    OracleMontgomery::from_representative::<Randomized>(representative)
        .expect("the forward map is total")
        .to_bytes()
}

/// Encode with the oracle, from a private key.
fn oracle_encode(secret: &[u8; 32], tweak: u8) -> Option<[u8; 32]> {
    Randomized::to_representative(secret, tweak).into()
}

// ── Tier 1: the forward map, bit for bit ────────────────────────────────────

/// Every 32-byte string must decode to the same point under both
/// implementations. This is the strictest available comparison and it covers the
/// whole input space by sampling.
#[test]
fn decoder_matches_the_oracle_on_random_strings() {
    let mut rng = rand::rng();
    for i in 0..2_000 {
        let mut r = [0u8; 32];
        rng.fill_bytes(&mut r);
        assert_eq!(
            from_representative(&r),
            oracle_decode(&r),
            "decoder diverged from the oracle on sample {i}: {}",
            hex(&r)
        );
    }
}

/// Structured inputs, where off-by-one and exceptional-case bugs live: zero, the
/// all-ones string, and values that exercise the high-bit masking.
#[test]
fn decoder_matches_the_oracle_on_edge_cases() {
    let mut cases: Vec<[u8; 32]> = vec![[0u8; 32], [0xff; 32], [1u8; 32]];
    for bit in 0..8 {
        let mut v = [0u8; 32];
        v[31] = 1 << bit;
        cases.push(v);
    }
    // 2r^2 == -1 is the exceptional case the forward map special-cases; drive the
    // neighbourhood of small values where the branch is reachable.
    for n in 0..16u8 {
        let mut v = [0u8; 32];
        v[0] = n;
        cases.push(v);
    }

    for r in cases {
        assert_eq!(
            from_representative(&r),
            oracle_decode(&r),
            "decoder diverged on edge case {}",
            hex(&r)
        );
    }
}

// ── Tier 2: our inverse map inverts their forward map ───────────────────────

/// The oracle must decode a representative *we* produced back to exactly the
/// point we encoded. This is the property a wire format depends on: the peer runs
/// a decoder, and it must land on the point we used.
#[test]
fn oracle_decodes_our_representatives_to_our_points() {
    let mut rng = rand::rng();
    for i in 0..500 {
        let e = generate(&mut rng).expect("generate");
        assert_eq!(
            oracle_decode(e.representative()),
            *e.point(),
            "the oracle recovered a different point from our representative (sample {i})"
        );
    }
}

/// The same property stated over the branch parameter: both values of the
/// branch-selection bit must produce representatives the oracle inverts
/// correctly. A branch bug would show up here and nowhere else.
#[test]
fn both_encoder_branches_invert_correctly() {
    let mut rng = rand::rng();
    let mut checked = [0u32; 2];
    for _ in 0..400 {
        let e = generate(&mut rng).expect("generate");
        let point = *e.point();
        for tweak in [0u8, 1u8] {
            if let Some(rep) = to_representative(&point, tweak) {
                assert_eq!(
                    oracle_decode(&rep),
                    point,
                    "branch {tweak} produced a representative that does not invert"
                );
                checked[usize::from(tweak)] += 1;
            }
        }
    }
    assert!(
        checked[0] > 0 && checked[1] > 0,
        "both branches must have been exercised: {checked:?}"
    );
}

// ── Tier 3: their inverse map inverts our forward map ───────────────────────

/// Representatives produced by the oracle must decode, under *our* map, to the
/// same point the oracle's own decoder gives. This closes the loop: tier 2 alone
/// would pass if both our maps were wrong in mutually cancelling ways.
#[test]
fn our_decoder_agrees_with_the_oracle_on_oracle_representatives() {
    let mut rng = rand::rng();
    let mut produced = 0;
    for _ in 0..1_000 {
        let mut sk = [0u8; 32];
        rng.fill_bytes(&mut sk);
        let mut tweak = [0u8; 1];
        rng.fill_bytes(&mut tweak);

        let Some(rep) = oracle_encode(&sk, tweak[0]) else {
            continue; // not representable; the oracle rejects ~half, as we do
        };
        produced += 1;
        assert_eq!(
            from_representative(&rep),
            oracle_decode(&rep),
            "our decoder diverged on an oracle-produced representative"
        );
    }
    assert!(
        produced > 300,
        "expected roughly half of 1000 keys to be representable, got {produced}"
    );
}

// ── Tier 4: the encoder, bit for bit ────────────────────────────────────────

/// The strongest comparison available, and stronger than the tiering above
/// suggested was possible.
///
/// The oracle's dirty-point construction, `EdwardsPoint::mul_base_clamped_dirty`,
/// is public. Feeding *its* point into *our* encoder makes the free parameter —
/// which torsion point gets added — no longer free, so the two encoders become
/// directly comparable: same point, same tweak, and therefore the same 32 bytes.
/// Anything less than exact equality here is a bug in one of the two maps.
///
/// Acceptance must agree per key as well, not merely on average: encodability
/// depends only on the point, never on the tweak.
#[test]
fn encoder_matches_the_oracle_byte_for_byte() {
    use curve25519_elligator2::edwards::EdwardsPoint as OracleEdwards;

    let mut rng = rand::rng();
    const TRIALS: usize = 1_000;
    let mut agreed = 0;
    let mut both_rejected = 0;

    for i in 0..TRIALS {
        let mut sk = [0u8; 32];
        rng.fill_bytes(&mut sk);
        let mut tweak = [0u8; 1];
        rng.fill_bytes(&mut tweak);

        // One point, produced by the oracle, handed to both encoders.
        let point = OracleEdwards::mul_base_clamped_dirty(sk)
            .to_montgomery()
            .to_bytes();

        let ours = to_representative(&point, tweak[0]);
        let theirs = oracle_encode(&sk, tweak[0]);

        match (ours, theirs) {
            (Some(a), Some(b)) => {
                assert_eq!(
                    a,
                    b,
                    "encoders diverged on sample {i}: point {}, tweak {:#04x}",
                    hex(&point),
                    tweak[0]
                );
                agreed += 1;
            }
            (None, None) => both_rejected += 1,
            (a, b) => panic!(
                "encoders disagreed on encodability at sample {i}: \
                 ours {:?}, oracle {:?}",
                a.is_some(),
                b.is_some()
            ),
        }
    }

    assert!(
        agreed > 300 && both_rejected > 300,
        "expected a roughly even split of accepted/rejected: \
         {agreed} agreed, {both_rejected} both-rejected of {TRIALS}"
    );
}

// ── The dirty-key property ──────────────────────────────────────────────────

/// **The test that catches the silent failure.**
///
/// If generated public keys were clean — `clamp(e)·B` with no torsion — then
/// every representative we emit would decode to a point of prime order L, while
/// genuinely random strings do so only about 1/8 of the time. That is an offline
/// distinguisher that no round-trip, no uniformity test, and none of the four
/// tiers above would ever notice: the map would be perfectly correct and the
/// output would still be fingerprintable.
///
/// A published Elligator2 crate without this test is a published Elligator2 crate
/// with a latent, undetectable flaw. Order is tested by `L·P == identity`,
/// evaluated through the oracle's own arithmetic so the check is independent of
/// our code.
#[test]
fn our_points_are_not_always_prime_order() {
    let mut rng = rand::rng();
    const TRIALS: usize = 400;

    let mut ours_prime_order = 0;
    let mut random_prime_order = 0;

    for _ in 0..TRIALS {
        let e = generate(&mut rng).expect("generate");
        if is_prime_order(e.representative()) {
            ours_prime_order += 1;
        }

        let mut r = [0u8; 32];
        rng.fill_bytes(&mut r);
        if is_prime_order(&r) {
            random_prime_order += 1;
        }
    }

    // A clean-key implementation scores 100% here. Random strings score ~12.5%.
    let ours_pct = ours_prime_order * 100 / TRIALS;
    let random_pct = random_prime_order * 100 / TRIALS;
    println!(
        "prime-order rate — ours: {ours_pct}% ({ours_prime_order}/{TRIALS}), \
         random strings: {random_pct}% ({random_prime_order}/{TRIALS})"
    );

    assert!(
        ours_pct < 30,
        "our representatives decode to prime-order points {ours_pct}% of the time; \
         clean (non-dirty) keys would give 100% and are trivially distinguishable"
    );
    assert!(
        (ours_pct as i64 - random_pct as i64).abs() < 15,
        "our subgroup distribution ({ours_pct}%) must match random strings ({random_pct}%)"
    );
}

/// True if the point decoded from `representative` has prime order L.
fn is_prime_order(representative: &[u8; 32]) -> bool {
    use curve25519_elligator2::edwards::EdwardsPoint;
    let point: EdwardsPoint =
        Randomized::from_representative(representative).expect("forward map is total");
    point.is_torsion_free()
}

fn hex(b: &[u8; 32]) -> String {
    b.iter().map(|x| format!("{x:02x}")).collect()
}