diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 610a52e..31d4024 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -60,6 +60,27 @@ jobs: run: | cargo build --workspace --all-features --verbose + - name: Unit + env: + SIMPLEX_TEST_VERBOSE: ${{ runner.debug == '1' && '-v' || '' }} + run: | + simplex test --no-simplex --test-threads 4 "${SIMPLEX_TEST_VERBOSE}" -- --release + + - name: Fuzz + env: + SIMPLEX_TEST_VERBOSE: ${{ runner.debug == '1' && '-v' || '' }} + run: | + simplex test --fuzz --test-threads 4 "${SIMPLEX_TEST_VERBOSE}" -- --release + + # Each run draws a new seed: keep the persisted failing cases to reproduce them locally. + - name: Upload fuzz failures + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: fuzz-failures-${{ matrix.os }} + path: fuzz-failures/ + if-no-files-found: ignore + - name: Test env: SIMPLEX_TEST_VERBOSE: ${{ runner.debug == '1' && '-v' || '' }} diff --git a/.gitignore b/.gitignore index ddafd0a..ab9046a 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ target/ # Simplex output src/artifacts +/fuzz-failures # IDE/editors (optional but common minimal) **/.DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b54eb8..ca0e3c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,12 @@ - Extended functions for retrieving information from `OP_RETURN`. - Conversion and bit functions for `u2` and `u4`. - Functions for asserting script hashes. +- Fuzz tests for `secp256k1` operations. ### Changed - Bumped Simplex to 0.2.0. - Aligned existing testing API with changes in Simplex. +- `secp256k1` unit tests run without a node, on fixed values. ## [0.2.0] diff --git a/Cargo.lock b/Cargo.lock index e2e789a..c20a7ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1097,25 +1097,6 @@ dependencies = [ "pin-utils", ] -[[package]] -name = "num-bigint" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-integer" -version = "0.1.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" -dependencies = [ - "num-traits", -] - [[package]] name = "num-traits" version = "0.2.19" @@ -1671,8 +1652,6 @@ name = "simplicityhl-std" version = "0.2.0" dependencies = [ "anyhow", - "num-bigint", - "num-traits", "primitive-types", "rand 0.8.8", "secp256k1-zkp", diff --git a/Cargo.toml b/Cargo.toml index 083ed8d..5468186 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,8 +20,6 @@ smplx-std = { git = "https://github.com/BlockstreamResearch/smplx", branch = "fi anyhow = { version = "1.0.101" } rand = { version = "0.8.6" } primitive-types = { version = "0.14" } -num-bigint = { version = "0.5.1" } -num-traits = { version = "0.2.19" } secp256k1-zkp = { version = "0.11.0", features = ["rand"] } # TODO: Remove this patch only when SimplicityHL uses a simplicity-lang release with the pruning fix. diff --git a/Simplex.toml b/Simplex.toml index 555b27b..78db45e 100644 --- a/Simplex.toml +++ b/Simplex.toml @@ -25,8 +25,8 @@ # url = "" # network = "" -# [test.fuzz] -# cases = 10 +[test.fuzz] +cases = 100 # seed = 12345 # network = "" diff --git a/tests/stdlib/common/case.rs b/tests/stdlib/common/case.rs new file mode 100644 index 0000000..6849f2c --- /dev/null +++ b/tests/stdlib/common/case.rs @@ -0,0 +1,40 @@ +use simplex::program::{Program, ProgramSchema}; +use simplex::simplicityhl::Arguments; + +use simplex::fuzz::FuzzProgramTrait; + +use crate::common::core::Expect; +use crate::common::unit; + +pub trait DispatchCase: Sized + 'static { + type Program: FuzzProgramTrait; + + const PROGRAM_NAME: &'static str = "program"; + + fn arguments() -> ::Arguments; + + fn into_witness(self) -> ::Witness; + + fn program() -> Program { + let arguments: Arguments = Self::arguments().into(); + + Self::Program::build_program(&arguments) + .unwrap_or_else(|error| panic!("{} does not compile: {error}", Self::PROGRAM_NAME)) + } + + #[track_caller] + fn accepts(self) { + unit::check(&Self::program(), self.into_witness(), Expect::Ok); + } + + #[track_caller] + fn rejects(self, reason: Expect) { + assert_ne!( + reason, + Expect::Ok, + "use `accepts` for cases that must succeed" + ); + + unit::check(&Self::program(), self.into_witness(), reason); + } +} diff --git a/tests/stdlib/common/core.rs b/tests/stdlib/common/core.rs index b596c81..fed6f99 100644 --- a/tests/stdlib/common/core.rs +++ b/tests/stdlib/common/core.rs @@ -20,7 +20,7 @@ use simplicityhl_std::artifacts::tests::mock::derived_mock::MockWitness; use crate::common::utxo_helper::{DEFAULT_SEND_AMOUNT, search_utxo_by_txid}; -#[derive(Clone, Copy)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Expect { /// The spend succeeds. Ok, diff --git a/tests/stdlib/common/fuzz.rs b/tests/stdlib/common/fuzz.rs new file mode 100644 index 0000000..3c60791 --- /dev/null +++ b/tests/stdlib/common/fuzz.rs @@ -0,0 +1,71 @@ +use std::fmt::Debug; + +use simplex::simplicityhl::Arguments; + +use simplex::fuzz::proptest::strategy::Strategy; +use simplex::fuzz::{FuzzProgramValues, Scenario}; +use simplex::{FuzzMode, TestContext}; + +use simplex::fuzz::Expect; + +use crate::common::case::DispatchCase; + +const DEFAULT_SPENT_INPUT: usize = 0; + +pub fn accepts( + context: &TestContext, + inputs: impl Strategy + 'static, + build: impl Fn(T) -> C + 'static, +) where + C: DispatchCase, + T: Debug + 'static, +{ + check(context, inputs, build, Expect::Accept); +} + +pub fn rejects( + context: &TestContext, + inputs: impl Strategy + 'static, + build: impl Fn(T) -> C + 'static, +) where + C: DispatchCase, + T: Debug + 'static, +{ + check(context, inputs, build, Expect::Reject); +} + +pub fn check( + context: &TestContext, + inputs: impl Strategy + 'static, + build: impl Fn(T) -> C + 'static, + expect: Expect, +) where + C: DispatchCase, + T: Debug + 'static, +{ + let arguments: Arguments = C::arguments().into(); + let values = inputs.prop_map(move |input| { + FuzzProgramValues::from((arguments.clone(), build(input).into_witness().into())) + }); + + let mut scenario = Scenario::default(); + scenario + .add::(C::PROGRAM_NAME) + .spends(DEFAULT_SPENT_INPUT) + .custom_strategy(values); + + run_scenario(context, scenario, expect); +} + +pub fn run_scenario(context: &TestContext, scenario: Scenario, expect: Expect) { + let engine = context.engine(scenario).spec(move |_| expect); + + // Negative scenarios deliberately generate no accepting witness. + let engine = if expect == Expect::Reject { + engine.allow_unspendable() + } else { + engine + }; + + engine.run(); +} diff --git a/tests/stdlib/common/mod.rs b/tests/stdlib/common/mod.rs index 16f0294..f1eaf86 100644 --- a/tests/stdlib/common/mod.rs +++ b/tests/stdlib/common/mod.rs @@ -1,5 +1,8 @@ +pub mod case; pub mod core; +pub mod fuzz; pub mod helper; pub mod u256_wrapper; pub mod uint; +pub mod unit; pub mod utxo_helper; diff --git a/tests/stdlib/common/unit.rs b/tests/stdlib/common/unit.rs new file mode 100644 index 0000000..a87a6fe --- /dev/null +++ b/tests/stdlib/common/unit.rs @@ -0,0 +1,69 @@ +use simplex::program::{Program, ProgramError, ProgramTrait}; +use simplex::provider::SimplicityNetwork; +use simplex::simplicityhl::WitnessValues; +use simplex::simplicityhl::elements::{OutPoint, Script, Txid}; +use simplex::simplicityhl::simplicity::bit_machine::ExecutionError; +use simplex::transaction::{FinalTransaction, PartialInput, PartialOutput, ProgramInput, UTXO}; + +use crate::common::core::Expect; + +const AMOUNT: u64 = 1_000; + +pub fn run(program: &Program, witness: impl Into) -> Result<(), ProgramError> { + let network = SimplicityNetwork::default_regtest(); + let witness = witness.into(); + + let (pst, _) = unit_transaction(program, witness.clone(), network) + .extract_pst() + .expect("the unit transaction is explicit"); + + program.execute(&pst, &witness, 0, &network).map(|_| ()) +} + +/// A case that fails before the program runs (e.g. a malformed witness) panics instead of +/// matching `expect`. +#[track_caller] +pub fn check(program: &Program, witness: impl Into, expect: Expect) { + match outcome(run(program, witness)) { + Ok(actual) => assert_eq!(actual, expect, "unexpected program outcome"), + Err(error) => panic!("the case failed before the program ran: {error}"), + } +} + +fn outcome(result: Result<(), ProgramError>) -> Result { + let execution = match result { + Ok(()) => return Ok(Expect::Ok), + Err(ProgramError::Pruning(execution) | ProgramError::Execution(execution)) => execution, + Err(other) => return Err(other), + }; + + match execution { + ExecutionError::JetFailed(_) => Ok(Expect::AssertFailed), + ExecutionError::ReachedPrunedBranch(_) => Ok(Expect::PrunedBranch), + other => Err(ProgramError::Execution(other)), + } +} + +fn unit_transaction( + program: &Program, + witness: WitnessValues, + network: SimplicityNetwork, +) -> FinalTransaction { + let asset = network.policy_asset(); + let utxo = UTXO::explicit( + OutPoint::new(Txid::from_byte_array([0xf0; 32]), 0), + program.get_script_pubkey(&network), + AMOUNT, + asset, + ); + + let mut ft = FinalTransaction::new(); + ft.add_program_input( + PartialInput::new(utxo), + ProgramInput::new(Box::new(program.clone()), witness), + None, + ); + ft.add_output(PartialOutput::new(Script::from(vec![0x51]), AMOUNT, asset)); + + ft +} diff --git a/tests/stdlib/secp256k1/math.rs b/tests/stdlib/secp256k1/math.rs new file mode 100644 index 0000000..c285d57 --- /dev/null +++ b/tests/stdlib/secp256k1/math.rs @@ -0,0 +1,136 @@ +use primitive_types::{U256 as Uint, U512}; +use secp256k1_zkp::{PublicKey, SECP256K1, SecretKey, constants}; + +/// Big-endian 256-bit integer. +pub type U256 = [u8; 32]; +/// Field element, mod p. +pub type Fe = U256; +/// Scalar, mod the group order n. +pub type Scalar = U256; +/// Affine point (x, y). +pub type Ge = (Fe, Fe); +/// Jacobian point ((X, Y), Z), representing affine (X/Z², Y/Z³). +pub type Gej = (Ge, Fe); +/// Compressed point (y parity, x). +pub type Point = (u8, Fe); + +pub const ZERO: U256 = [0; 32]; +pub const ONE: U256 = constants::ONE; + +pub const SECP_P: U256 = constants::FIELD_SIZE; +pub const SECP_N: U256 = constants::CURVE_ORDER; + +pub const INFINITY: Gej = ((ZERO, ZERO), ZERO); + +pub const fn u256(value: u128) -> U256 { + let mut out = [0; 32]; + let bytes = value.to_be_bytes(); + let mut i = 0; + + while i < 16 { + out[16 + i] = bytes[i]; + i += 1; + } + + out +} + +fn int(value: U256) -> Uint { + Uint::from_big_endian(&value) +} + +pub fn add_u256(a: U256, b: U256) -> U256 { + int(a) + .checked_add(int(b)) + .expect("a + b overflows 256 bits") + .to_big_endian() +} + +pub fn sub_u256(a: U256, b: U256) -> U256 { + int(a) + .checked_sub(int(b)) + .expect("a - b underflows") + .to_big_endian() +} + +/// Operands may be non-canonical, the result is canonical. +pub fn sub_mod(a: U256, b: U256, modulus: U256) -> U256 { + let m = int(modulus); + let (a, b) = (int(a) % m, int(b) % m); + + let difference = if a >= b { a - b } else { m - (b - a) }; + difference.to_big_endian() +} + +pub fn fe_mul(a: Fe, b: Fe) -> Fe { + let product = int(a).full_mul(int(b)) % U512::from(int(SECP_P)); + + Uint::try_from(product) + .expect("reduced mod p") + .to_big_endian() +} + +pub fn pk_to_ge(pk: &PublicKey) -> Ge { + let serialized = pk.serialize_uncompressed(); // 0x04 || x(32) || y(32) + + ( + serialized[1..33].try_into().unwrap(), + serialized[33..65].try_into().unwrap(), + ) +} + +pub fn ge_to_pk((x, y): Ge) -> PublicKey { + let mut serialized = [0x04; 65]; + serialized[1..33].copy_from_slice(&x); + serialized[33..65].copy_from_slice(&y); + + PublicKey::from_slice(&serialized).expect("on-curve point") +} + +pub fn decompress((parity, x): Point) -> Option { + let mut serialized = [0x02 | (parity & 1); 33]; + serialized[1..].copy_from_slice(&x); + + PublicKey::from_slice(&serialized) + .ok() + .map(|pk| pk_to_ge(&pk)) +} + +pub fn compress((x, y): Ge) -> Point { + (y[31] & 1, x) +} + +pub fn ge_to_gej(ge: Ge) -> Gej { + (ge, ONE) +} + +pub fn ge_negate((x, y): Ge) -> Ge { + (x, sub_mod(ZERO, y, SECP_P)) +} + +/// `p - q`, `None` for the point at infinity (`p == q`). +pub fn ge_sub(p: Ge, q: Ge) -> Option { + ge_to_pk(p) + .combine(&ge_to_pk(q).negate(SECP256K1)) + .ok() + .map(|difference| pk_to_ge(&difference)) +} + +/// `(λ²X, λ³Y, λ)`: the same point as `(X, Y, 1)` for any non-zero λ. +pub fn rescale((x, y): Ge, lambda: Fe) -> Gej { + let lambda_squared = fe_mul(lambda, lambda); + let lambda_cubed = fe_mul(lambda_squared, lambda); + + ((fe_mul(x, lambda_squared), fe_mul(y, lambda_cubed)), lambda) +} + +pub fn g_times(k: u128) -> Ge { + let secret_key = SecretKey::from_slice(&u256(k)).expect("k must be non-zero"); + + pk_to_ge(&PublicKey::from_secret_key(SECP256K1, &secret_key)) +} + +/// `x + p` still fits in 256 bits, so x = 1 can be passed unreduced to test reduction mod p. +pub fn x_one() -> Ge { + decompress((0, ONE)).expect("x = 1 is on the curve") +} diff --git a/tests/stdlib/secp256k1/mod.rs b/tests/stdlib/secp256k1/mod.rs index 9045df1..b9fcd31 100644 --- a/tests/stdlib/secp256k1/mod.rs +++ b/tests/stdlib/secp256k1/mod.rs @@ -1 +1,2 @@ +mod math; mod operations; diff --git a/tests/stdlib/secp256k1/operations.rs b/tests/stdlib/secp256k1/operations.rs deleted file mode 100644 index 3bc6798..0000000 --- a/tests/stdlib/secp256k1/operations.rs +++ /dev/null @@ -1,434 +0,0 @@ -use num_bigint::BigUint; -use num_traits::Zero; -use rand::{RngCore, rngs::OsRng}; -use secp256k1_zkp::{PublicKey, Secp256k1, SecretKey, rand::rngs::OsRng as SecpOsRng}; - -use crate::common::core::{Expect, run}; - -use simplicityhl_std::artifacts::tests::secp256k1::operations::OperationsProgram as Secp256k1OperationsTestProgram; -use simplicityhl_std::artifacts::tests::secp256k1::operations::derived_operations::{ - OperationsArguments as Secp256k1OperationsTestArguments, - OperationsWitness as Secp256k1OperationsTestWitness, -}; - -use FunctionToTest::*; - -enum FunctionToTest { - GeToPoint, - PointToGej, - FeSub, - ScalarSub, - GejSub, - FeEq, - ScalarEq, - GeEq, - GejPointEq, - SafeGejNormalize, -} - -// FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F -const SECP_P: [u8; 32] = [ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFC, 0x2F, -]; - -// FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 -const SECP_N: [u8; 32] = [ - 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, - 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41, -]; - -fn program() -> Secp256k1OperationsTestProgram { - Secp256k1OperationsTestProgram::new(&Secp256k1OperationsTestArguments {}) -} - -/// One dispatch arm of the contract, plus the witness it reads. -struct Case { - witness: Secp256k1OperationsTestWitness, -} - -fn case(function: FunctionToTest) -> Case { - Case { - witness: Secp256k1OperationsTestWitness { - function_index: function as u8, - first_uint: [0; 32], - second_uint: [0; 32], - first_ge: ([0; 32], [0; 32]), - second_ge: ([0; 32], [0; 32]), - first_gej: (([0; 32], [0; 32]), [0; 32]), - second_gej: (([0; 32], [0; 32]), [0; 32]), - first_point: (0, [0; 32]), - expected_uint: [0; 32], - expected_ge: ([0; 32], [0; 32]), - expected_gej: (([0; 32], [0; 32]), [0; 32]), - expected_point: (0, [0; 32]), - }, - } -} - -impl Case { - /// The two field or scalar operands, `first_uint` and `second_uint`. - fn uints(mut self, first_uint: [u8; 32], second_uint: [u8; 32]) -> Self { - self.witness.first_uint = first_uint; - self.witness.second_uint = second_uint; - self - } - - /// Only `first_ge`. - fn ge(mut self, first_ge: ([u8; 32], [u8; 32])) -> Self { - self.witness.first_ge = first_ge; - self - } - - /// The two affine points, `first_ge` and `second_ge`. - fn ges(mut self, first_ge: ([u8; 32], [u8; 32]), second_ge: ([u8; 32], [u8; 32])) -> Self { - self.witness.first_ge = first_ge; - self.witness.second_ge = second_ge; - self - } - - /// Only `first_gej`. - fn gej(mut self, first_gej: (([u8; 32], [u8; 32]), [u8; 32])) -> Self { - self.witness.first_gej = first_gej; - self - } - - /// The two Jacobian points, `first_gej` and `second_gej`. - fn gejs( - mut self, - first_gej: (([u8; 32], [u8; 32]), [u8; 32]), - second_gej: (([u8; 32], [u8; 32]), [u8; 32]), - ) -> Self { - self.witness.first_gej = first_gej; - self.witness.second_gej = second_gej; - self - } - - /// `first_point`: a compressed point, parity byte and x coordinate. - fn point(mut self, first_point: (u8, [u8; 32])) -> Self { - self.witness.first_point = first_point; - self - } - - /// `expected_uint`: the field or scalar the arm should produce. - fn expect_uint(mut self, expected_uint: [u8; 32]) -> Self { - self.witness.expected_uint = expected_uint; - self - } - - /// `expected_ge`: the affine point the arm should produce. - fn expect_ge(mut self, expected_ge: ([u8; 32], [u8; 32])) -> Self { - self.witness.expected_ge = expected_ge; - self - } - - /// `expected_gej`: the Jacobian point the arm should produce. - fn expect_gej(mut self, expected_gej: (([u8; 32], [u8; 32]), [u8; 32])) -> Self { - self.witness.expected_gej = expected_gej; - self - } - - /// `expected_point`: the compressed point the arm should produce. - fn expect_point(mut self, expected_point: (u8, [u8; 32])) -> Self { - self.witness.expected_point = expected_point; - self - } - - /// Fund, spend, and expect the spend to succeed. - fn run(self, context: &simplex::TestContext) -> anyhow::Result<()> { - self.expecting(context, Expect::Ok) - } - - /// Fund, spend, and expect `expect`. - fn expecting(self, context: &simplex::TestContext, expect: Expect) -> anyhow::Result<()> { - run(context, program(), self.witness, expect) - } -} - -fn secp_p() -> BigUint { - BigUint::from_bytes_be(&SECP_P) -} -fn secp_n() -> BigUint { - BigUint::from_bytes_be(&SECP_N) -} - -fn to_32_be(x: &BigUint) -> [u8; 32] { - let b = x.to_bytes_be(); - - let mut out = [0u8; 32]; - out[32 - b.len()..].copy_from_slice(&b); - - out -} - -fn mod_p(x: &BigUint) -> BigUint { - x % secp_p() -} -fn mod_n(x: &BigUint) -> BigUint { - x % secp_n() -} - -fn fe_sub_ref(a: [u8; 32], b: [u8; 32]) -> [u8; 32] { - let p = secp_p(); - let a = BigUint::from_bytes_be(&a) % &p; - let b = BigUint::from_bytes_be(&b) % &p; - - to_32_be(&((a + &p - b) % &p)) -} - -fn scalar_sub_ref(a: [u8; 32], b: [u8; 32]) -> [u8; 32] { - let n = secp_n(); - let a = BigUint::from_bytes_be(&a) % &n; - let b = BigUint::from_bytes_be(&b) % &n; - - to_32_be(&((a + &n - b) % &n)) -} - -fn fe_negate_ref(a: [u8; 32]) -> [u8; 32] { - let p = secp_p(); - let a = BigUint::from_bytes_be(&a) % &p; - - if a.is_zero() { - [0u8; 32] - } else { - to_32_be(&(&p - &a)) - } -} - -fn fe_mul_ref(a: [u8; 32], b: [u8; 32]) -> [u8; 32] { - let p = secp_p(); - let a = BigUint::from_bytes_be(&a); - let b = BigUint::from_bytes_be(&b); - - to_32_be(&((a * b) % &p)) -} - -// Randomness helpers -fn random_uint_bytes() -> [u8; 32] { - let mut b = [0u8; 32]; - OsRng.fill_bytes(&mut b); - - b -} - -fn random_fe_bytes() -> [u8; 32] { - to_32_be(&mod_p(&BigUint::from_bytes_be(&random_uint_bytes()))) -} - -fn random_scalar_bytes() -> [u8; 32] { - to_32_be(&mod_n(&BigUint::from_bytes_be(&random_uint_bytes()))) -} - -fn random_ge_bytes() -> ([u8; 32], [u8; 32]) { - let secp = Secp256k1::new(); - let sk = SecretKey::new(&mut SecpOsRng); - let pk = PublicKey::from_secret_key(&secp, &sk); - let ser = pk.serialize_uncompressed(); // 0x04 || x(32) || y(32) - - let mut x = [0u8; 32]; - x.copy_from_slice(&ser[1..33]); - - let mut y = [0u8; 32]; - y.copy_from_slice(&ser[33..65]); - - (x, y) -} - -fn ge_to_gej(ge: ([u8; 32], [u8; 32])) -> (([u8; 32], [u8; 32]), [u8; 32]) { - let mut one = [0u8; 32]; - one[31] = 1; - - (ge, one) -} - -fn compress(ge: ([u8; 32], [u8; 32])) -> (u8, [u8; 32]) { - (ge.1[31] & 1, ge.0) -} - -fn pk_to_gej(pk: &PublicKey) -> (([u8; 32], [u8; 32]), [u8; 32]) { - let ser = pk.serialize_uncompressed(); - - let mut x = [0u8; 32]; - x.copy_from_slice(&ser[1..33]); - - let mut y = [0u8; 32]; - y.copy_from_slice(&ser[33..65]); - - ge_to_gej((x, y)) -} - -// 0. ge_to_point -#[simplex::test] -fn ge_to_point_matches_parity(context: simplex::TestContext) -> anyhow::Result<()> { - // Sample one on-curve point; whatever parity it has, that's what we expect - // ge_to_point to produce. Covers both parities across repeated runs. - let ge = random_ge_bytes(); - let expected_parity = ge.1[31] & 1; // 0 (even y) or 1 (odd y) - - case(GeToPoint) - .ge(ge) - .expect_point((expected_parity, ge.0)) - .run(&context) -} - -// 1. point_to_gej -#[simplex::test] -fn point_to_gej_roundtrip(context: simplex::TestContext) -> anyhow::Result<()> { - let ge = random_ge_bytes(); - let point = compress(ge); - - case(PointToGej) - .point(point) - .expect_point(point) - .run(&context) -} - -// 2. fe_sub -#[simplex::test] -fn fe_sub_self_is_zero(context: simplex::TestContext) -> anyhow::Result<()> { - let a = random_fe_bytes(); - - case(FeSub).uints(a, a).expect_uint([0u8; 32]).run(&context) -} - -#[simplex::test] -fn fe_sub_matches_reference(context: simplex::TestContext) -> anyhow::Result<()> { - let a = random_fe_bytes(); - let b = random_fe_bytes(); - let exp = fe_sub_ref(a, b); - - case(FeSub).uints(a, b).expect_uint(exp).run(&context) -} - -// 3. scalar_sub -#[simplex::test] -fn scalar_sub_matches_reference(context: simplex::TestContext) -> anyhow::Result<()> { - let a = random_scalar_bytes(); - let b = random_scalar_bytes(); - let exp = scalar_sub_ref(a, b); - - case(ScalarSub).uints(a, b).expect_uint(exp).run(&context) -} - -// 4. gej_sub -#[simplex::test] -fn gej_sub_matches_reference(context: simplex::TestContext) -> anyhow::Result<()> { - let secp = Secp256k1::new(); - let sk_p = SecretKey::new(&mut SecpOsRng); - let sk_q = SecretKey::new(&mut SecpOsRng); - - let p = PublicKey::from_secret_key(&secp, &sk_p); - let q = PublicKey::from_secret_key(&secp, &sk_q); - let diff = p.combine(&q.negate(&secp)).expect("p - q non-infinity"); - - case(GejSub) - .gejs(pk_to_gej(&p), pk_to_gej(&q)) - .expect_gej(pk_to_gej(&diff)) - .run(&context) -} - -// 5. fe_eq -#[simplex::test] -fn fe_eq_reflexive(context: simplex::TestContext) -> anyhow::Result<()> { - let a = random_fe_bytes(); - - case(FeEq).uints(a, a).run(&context) -} - -#[simplex::test] -fn fe_eq_zero_and_p_are_equal(context: simplex::TestContext) -> anyhow::Result<()> { - case(FeEq).uints([0u8; 32], SECP_P).run(&context) -} - -// 6. scalar_eq -#[simplex::test] -fn scalar_eq_s_and_s_plus_n_are_equal(context: simplex::TestContext) -> anyhow::Result<()> { - // s = 5. s + n has no carry past the low byte. - let mut s = [0u8; 32]; - s[31] = 5; - - let mut s_plus_n = SECP_N; - s_plus_n[31] = s_plus_n[31].wrapping_add(5); - - case(ScalarEq).uints(s, s_plus_n).run(&context) -} - -// 7. ge_eq -#[simplex::test] -fn ge_eq_rejects_negation(context: simplex::TestContext) -> anyhow::Result<()> { - let ge = random_ge_bytes(); - let neg_y = fe_negate_ref(ge.1); - - case(GeEq) - .ges(ge, (ge.0, neg_y)) - .expecting(&context, Expect::AssertFailed) -} - -// 8. gej_point_eq -#[simplex::test] -fn gej_point_eq_rescaled(context: simplex::TestContext) -> anyhow::Result<()> { - // (λ²X, λ³Y, λZ) is the same affine point as (X, Y, 1). - let ge = random_ge_bytes(); - let lambda = random_fe_bytes(); - let l2 = fe_mul_ref(lambda, lambda); - let l3 = fe_mul_ref(l2, lambda); - let g = ((fe_mul_ref(ge.0, l2), fe_mul_ref(ge.1, l3)), lambda); - - case(GejPointEq).gej(g).point(compress(ge)).run(&context) -} - -#[simplex::test] -fn gej_point_eq_rejects_negation(context: simplex::TestContext) -> anyhow::Result<()> { - // Property under test: gej_point_eq(P, -P) == false. - // - // Construction: - // ge = random on-curve point P = (x, y) - // (parity, x) = compressed form of +P - // ge_to_gej(ge) = Gej encoding of +P - // (parity ^ 1, x) = compressed form of -P - // - // decompress((parity ^ 1, x)) inside gej_point_eq recovers (x, -y) = -P. - // Since P ≠ -P on secp256k1, the equivalence must return false. - // expected_bool = false locks that in. - let ge = random_ge_bytes(); - let (parity, x) = compress(ge); - - case(GejPointEq) - .gej(ge_to_gej(ge)) - .point((parity ^ 1, x)) - .expecting(&context, Expect::AssertFailed) -} - -#[simplex::test] -fn gej_point_eq_off_curve_is_false(context: simplex::TestContext) -> anyhow::Result<()> { - // x = 0 is off-curve. - case(GejPointEq) - .gej(ge_to_gej(random_ge_bytes())) - .point((0, [0u8; 32])) - .expecting(&context, Expect::AssertFailed) -} - -#[simplex::test] -fn gej_point_eq_rejects_off_curve_gej(context: simplex::TestContext) -> anyhow::Result<()> { - // (x, 1, 1) shares x with P but is off-curve. The equivalence jet only - // rejects y = -P.y, so without an on-curve check this would pass. - let ge = random_ge_bytes(); - let mut one = [0u8; 32]; - one[31] = 1; - - case(GejPointEq) - .gej(((ge.0, one), one)) - .point(compress(ge)) - .expecting(&context, Expect::AssertFailed) -} - -// 9. safe_gej_normalize -#[simplex::test] -fn safe_gej_normalize_roundtrip(context: simplex::TestContext) -> anyhow::Result<()> { - let ge = random_ge_bytes(); - - case(SafeGejNormalize) - .gej(ge_to_gej(ge)) - .expect_ge(ge) - .run(&context) -} diff --git a/tests/stdlib/secp256k1/operations/case.rs b/tests/stdlib/secp256k1/operations/case.rs new file mode 100644 index 0000000..58ab593 --- /dev/null +++ b/tests/stdlib/secp256k1/operations/case.rs @@ -0,0 +1,229 @@ +use simplicityhl_std::artifacts::tests::secp256k1::operations::OperationsProgram as Secp256k1OperationsTestProgram; +use simplicityhl_std::artifacts::tests::secp256k1::operations::derived_operations::{ + OperationsArguments as Secp256k1OperationsTestArguments, + OperationsWitness as Secp256k1OperationsTestWitness, +}; + +use crate::common::case::DispatchCase; + +use crate::secp256k1::math::{ + Fe, Ge, Gej, INFINITY, Point, SECP_N, SECP_P, Scalar, U256, compress, ge_negate, ge_sub, + ge_to_gej, rescale, sub_mod, +}; + +/// Dispatch arms of the contract. Each index must match `is_selected(index, ..)` in the `.simf` test. +#[derive(Clone, Copy)] +enum FunctionToTest { + GeToPoint = 0, + PointToGej = 1, + FeSub = 2, + ScalarSub = 3, + GejSub = 4, + FeEq = 5, + ScalarEq = 6, + GeEq = 7, + GejPointEq = 8, + SafeGejNormalize = 9, +} + +pub(super) fn ge_to_point(ge: Ge, expected: Point) -> Case { + Case::new(FunctionToTest::GeToPoint) + .ge(ge) + .expect_point(expected) +} + +pub(super) fn ge_to_point_compresses(ge: Ge) -> Case { + ge_to_point(ge, compress(ge)) +} + +/// The Jacobian result is checked against a compressed point. +pub(super) fn point_to_gej(point: Point, expected: Point) -> Case { + Case::new(FunctionToTest::PointToGej) + .point(point) + .expect_point(expected) +} + +pub(super) fn point_to_gej_roundtrip(ge: Ge) -> Case { + point_to_gej(compress(ge), compress(ge)) +} + +pub(super) fn fe_sub(a: Fe, b: Fe, expected: Fe) -> Case { + Case::new(FunctionToTest::FeSub) + .uints(a, b) + .expect_uint(expected) +} + +pub(super) fn fe_sub_reference(a: Fe, b: Fe) -> Case { + fe_sub(a, b, sub_mod(a, b, SECP_P)) +} + +pub(super) fn scalar_sub(a: Scalar, b: Scalar, expected: Scalar) -> Case { + Case::new(FunctionToTest::ScalarSub) + .uints(a, b) + .expect_uint(expected) +} + +pub(super) fn scalar_sub_reference(a: Scalar, b: Scalar) -> Case { + scalar_sub(a, b, sub_mod(a, b, SECP_N)) +} + +pub(super) fn gej_sub(p: Gej, q: Gej, expected: Gej) -> Case { + Case::new(FunctionToTest::GejSub) + .gejs(p, q) + .expect_gej(expected) +} + +pub(super) fn gej_sub_reference(p: Ge, q: Ge) -> Case { + let expected = ge_sub(p, q).map_or(INFINITY, ge_to_gej); + + gej_sub(ge_to_gej(p), ge_to_gej(q), expected) +} + +/// Accepted iff `a ≡ b (mod p)`. +pub(super) fn fe_eq(a: Fe, b: Fe) -> Case { + Case::new(FunctionToTest::FeEq).uints(a, b) +} + +/// Accepted iff `a ≡ b (mod n)`. +pub(super) fn scalar_eq(a: Scalar, b: Scalar) -> Case { + Case::new(FunctionToTest::ScalarEq).uints(a, b) +} + +/// Accepted iff both coordinates are equal mod p. +pub(super) fn ge_eq(a: Ge, b: Ge) -> Case { + Case::new(FunctionToTest::GeEq).ges(a, b) +} + +pub(super) fn ge_eq_negation(ge: Ge) -> Case { + ge_eq(ge, ge_negate(ge)) +} + +/// Accepted iff `gej` is on the curve and is the point `point` encodes. +pub(super) fn gej_point_eq(gej: Gej, point: Point) -> Case { + Case::new(FunctionToTest::GejPointEq).gej(gej).point(point) +} + +pub(super) fn gej_point_eq_rescaled(ge: Ge, lambda: Fe) -> Case { + gej_point_eq(rescale(ge, lambda), compress(ge)) +} + +/// Flipping the parity keeps x and encodes -P. +pub(super) fn gej_point_eq_negation(ge: Ge) -> Case { + let (parity, x) = compress(ge); + + gej_point_eq(ge_to_gej(ge), (parity ^ 1, x)) +} + +pub(super) fn gej_point_eq_off_curve_point(ge: Ge, x: Fe) -> Case { + gej_point_eq(ge_to_gej(ge), (0, x)) +} + +/// Matching x and parity isolates the on-curve check. +pub(super) fn gej_point_eq_off_curve_gej(x: Fe, y: Fe) -> Case { + let off_curve = (x, y); + + gej_point_eq(ge_to_gej(off_curve), compress(off_curve)) +} + +pub(super) fn safe_gej_normalize(gej: Gej, expected: Ge) -> Case { + Case::new(FunctionToTest::SafeGejNormalize) + .gej(gej) + .expect_ge(expected) +} + +pub(super) fn safe_gej_normalize_rescaled(ge: Ge, lambda: Fe) -> Case { + safe_gej_normalize(rescale(ge, lambda), ge) +} + +#[derive(Clone, Debug)] +pub(super) struct Case { + witness: Secp256k1OperationsTestWitness, +} + +impl Case { + fn new(function: FunctionToTest) -> Self { + Self { + witness: Secp256k1OperationsTestWitness { + function_index: function as u8, + first_uint: U256::default(), + second_uint: U256::default(), + first_ge: Ge::default(), + second_ge: Ge::default(), + first_gej: Gej::default(), + second_gej: Gej::default(), + first_point: Point::default(), + expected_uint: U256::default(), + expected_ge: Ge::default(), + expected_gej: Gej::default(), + expected_point: Point::default(), + }, + } + } + + fn uints(mut self, first_uint: U256, second_uint: U256) -> Self { + self.witness.first_uint = first_uint; + self.witness.second_uint = second_uint; + self + } + + fn ge(mut self, first_ge: Ge) -> Self { + self.witness.first_ge = first_ge; + self + } + + fn ges(mut self, first_ge: Ge, second_ge: Ge) -> Self { + self.witness.first_ge = first_ge; + self.witness.second_ge = second_ge; + self + } + + fn gej(mut self, first_gej: Gej) -> Self { + self.witness.first_gej = first_gej; + self + } + + fn gejs(mut self, first_gej: Gej, second_gej: Gej) -> Self { + self.witness.first_gej = first_gej; + self.witness.second_gej = second_gej; + self + } + + fn point(mut self, first_point: Point) -> Self { + self.witness.first_point = first_point; + self + } + + fn expect_uint(mut self, expected_uint: U256) -> Self { + self.witness.expected_uint = expected_uint; + self + } + + fn expect_ge(mut self, expected_ge: Ge) -> Self { + self.witness.expected_ge = expected_ge; + self + } + + fn expect_gej(mut self, expected_gej: Gej) -> Self { + self.witness.expected_gej = expected_gej; + self + } + + fn expect_point(mut self, expected_point: Point) -> Self { + self.witness.expected_point = expected_point; + self + } +} + +impl DispatchCase for Case { + type Program = Secp256k1OperationsTestProgram; + + const PROGRAM_NAME: &'static str = "secp256k1::operations"; + + fn arguments() -> Secp256k1OperationsTestArguments { + Secp256k1OperationsTestArguments {} + } + + fn into_witness(self) -> Secp256k1OperationsTestWitness { + self.witness + } +} diff --git a/tests/stdlib/secp256k1/operations/fuzz.rs b/tests/stdlib/secp256k1/operations/fuzz.rs new file mode 100644 index 0000000..167ffbb --- /dev/null +++ b/tests/stdlib/secp256k1/operations/fuzz.rs @@ -0,0 +1,200 @@ +use secp256k1_zkp::{PublicKey, SECP256K1, SecretKey}; + +use simplex::fuzz::proptest::prelude::{Just, any}; +use simplex::fuzz::proptest::prop_oneof; +use simplex::fuzz::proptest::sample::select; +use simplex::fuzz::proptest::strategy::Strategy; +use simplex::{FuzzMode, TestContext}; + +use crate::common::fuzz::{accepts, rejects}; +use crate::secp256k1::math::{ + Fe, Ge, ONE, SECP_N, SECP_P, U256, ZERO, add_u256, decompress, pk_to_ge, sub_mod, sub_u256, + u256, +}; + +use super::case; + +/// Values at and above `modulus` are non-canonical and exercise reduction in the contract. +fn arb_u256_mod(modulus: U256) -> impl Strategy { + let edges = vec![ + ZERO, + ONE, + sub_u256(modulus, ONE), + modulus, + add_u256(modulus, ONE), + [u8::MAX; 32], + ]; + + prop_oneof![select(edges), any::()] +} + +fn arb_fe() -> impl Strategy { + arb_u256_mod(SECP_P).prop_filter("canonical field element", |value| *value < SECP_P) +} + +fn arb_non_zero_fe() -> impl Strategy { + arb_fe().prop_filter("non-zero field element", |value| *value != ZERO) +} + +fn arb_ge() -> impl Strategy { + any::<[u8; 32]>() + .prop_filter_map("valid secret key", |bytes| { + SecretKey::from_slice(&bytes).ok() + }) + .prop_map(|secret_key| pk_to_ge(&PublicKey::from_secret_key(SECP256K1, &secret_key))) +} + +/// A canonical x with no curve point: `x³ + 7` is not a square mod p. +fn arb_off_curve_x() -> impl Strategy { + prop_oneof![Just(ZERO), arb_fe()].prop_filter("off-curve x", |x| decompress((0, *x)).is_none()) +} + +/// `x` and `x + modulus`: equal modulo `modulus`, the second one non-canonical. +fn arb_shifted_pair( + x: impl Strategy, + modulus: U256, +) -> impl Strategy { + x.prop_map(move |x| (x, add_u256(x, modulus))) +} + +fn arb_distinct_mod(modulus: U256) -> impl Strategy { + (arb_u256_mod(modulus), arb_u256_mod(modulus)).prop_filter("distinct modulo", move |(a, b)| { + sub_mod(*a, *b, modulus) != ZERO + }) +} + +// 0. ge_to_point +#[simplex::fuzz] +fn ge_to_point_matches_parity(context: TestContext) { + accepts(&context, arb_ge(), case::ge_to_point_compresses); +} + +// 1. point_to_gej +#[simplex::fuzz] +fn point_to_gej_roundtrip(context: TestContext) { + accepts(&context, arb_ge(), case::point_to_gej_roundtrip); +} + +// 2. fe_sub +#[simplex::fuzz] +fn fe_sub_self_is_zero(context: TestContext) { + accepts(&context, arb_u256_mod(SECP_P), |a| case::fe_sub(a, a, ZERO)); +} + +#[simplex::fuzz] +fn fe_sub_matches_reference(context: TestContext) { + accepts( + &context, + (arb_u256_mod(SECP_P), arb_u256_mod(SECP_P)), + |(a, b)| case::fe_sub_reference(a, b), + ); +} + +// 3. scalar_sub +#[simplex::fuzz] +fn scalar_sub_matches_reference(context: TestContext) { + accepts( + &context, + (arb_u256_mod(SECP_N), arb_u256_mod(SECP_N)), + |(a, b)| case::scalar_sub_reference(a, b), + ); +} + +// 4. gej_sub +#[simplex::fuzz] +fn gej_sub_matches_reference(context: TestContext) { + let distinct_points = (arb_ge(), arb_ge()).prop_filter("distinct points", |(p, q)| p != q); + + accepts(&context, distinct_points, |(p, q)| { + case::gej_sub_reference(p, q) + }); +} + +#[simplex::fuzz] +fn gej_sub_self_is_infinity(context: TestContext) { + accepts(&context, arb_ge(), |p| case::gej_sub_reference(p, p)); +} + +// 5. fe_eq +#[simplex::fuzz] +fn fe_eq_reflexive(context: TestContext) { + accepts(&context, arb_u256_mod(SECP_P), |a| case::fe_eq(a, a)); +} + +// Generalized case of fe_eq_zero_and_p_are_equal. +#[simplex::fuzz] +fn fe_eq_x_and_x_plus_p_are_equal(context: TestContext) { + // x + p fits in 256 bits only for x < 2^256 - p = 0x1000003D1. + let x = (0_u128..0x1_0000_03D1).prop_map(u256); + + accepts(&context, arb_shifted_pair(x, SECP_P), |(a, b)| { + case::fe_eq(a, b) + }); +} + +#[simplex::fuzz] +fn fe_eq_rejects_distinct(context: TestContext) { + rejects(&context, arb_distinct_mod(SECP_P), |(a, b)| { + case::fe_eq(a, b) + }); +} + +// 6. scalar_eq +#[simplex::fuzz] +fn scalar_eq_s_and_s_plus_n_are_equal(context: TestContext) { + // s + n fits in 256 bits for any s < 2^128 (2^256 - n > 2^128). + let s = any::().prop_map(u256); + + accepts(&context, arb_shifted_pair(s, SECP_N), |(a, b)| { + case::scalar_eq(a, b) + }); +} + +#[simplex::fuzz] +fn scalar_eq_rejects_distinct(context: TestContext) { + rejects(&context, arb_distinct_mod(SECP_N), |(a, b)| { + case::scalar_eq(a, b) + }); +} + +// 7. ge_eq +#[simplex::fuzz] +fn ge_eq_rejects_negation(context: TestContext) { + rejects(&context, arb_ge(), case::ge_eq_negation); +} + +// 8. gej_point_eq +#[simplex::fuzz] +fn gej_point_eq_rescaled(context: TestContext) { + accepts(&context, (arb_ge(), arb_non_zero_fe()), |(ge, lambda)| { + case::gej_point_eq_rescaled(ge, lambda) + }); +} + +#[simplex::fuzz] +fn gej_point_eq_rejects_negation(context: TestContext) { + rejects(&context, arb_ge(), case::gej_point_eq_negation); +} + +#[simplex::fuzz] +fn gej_point_eq_off_curve_is_false(context: TestContext) { + rejects(&context, (arb_ge(), arb_off_curve_x()), |(ge, x)| { + case::gej_point_eq_off_curve_point(ge, x) + }); +} + +#[simplex::fuzz] +fn gej_point_eq_rejects_off_curve_gej(context: TestContext) { + // A point with y = 0 would have order two. The group has odd order. + rejects(&context, arb_ge(), |(x, _)| { + case::gej_point_eq_off_curve_gej(x, ZERO) + }); +} + +// 9. safe_gej_normalize +#[simplex::fuzz] +fn safe_gej_normalize_roundtrip(context: TestContext) { + accepts(&context, (arb_ge(), arb_non_zero_fe()), |(ge, lambda)| { + case::safe_gej_normalize_rescaled(ge, lambda) + }); +} diff --git a/tests/stdlib/secp256k1/operations/mod.rs b/tests/stdlib/secp256k1/operations/mod.rs new file mode 100644 index 0000000..3180816 --- /dev/null +++ b/tests/stdlib/secp256k1/operations/mod.rs @@ -0,0 +1,3 @@ +mod case; +mod fuzz; +mod unit; diff --git a/tests/stdlib/secp256k1/operations/unit.rs b/tests/stdlib/secp256k1/operations/unit.rs new file mode 100644 index 0000000..d569fcd --- /dev/null +++ b/tests/stdlib/secp256k1/operations/unit.rs @@ -0,0 +1,262 @@ +use crate::common::case::DispatchCase; +use crate::common::core::Expect::{AssertFailed, PrunedBranch}; +use crate::secp256k1::math::{ + Fe, Ge, Gej, INFINITY, ONE, SECP_N, SECP_P, Scalar, ZERO, add_u256, compress, g_times, + ge_negate, ge_to_gej, rescale, u256, x_one, +}; + +use super::case; + +// 0. ge_to_point +#[test] +fn ge_to_point_matches_parity() { + // G and -G have opposite y parity (p is odd), so both branches are covered. + let g: Ge = g_times(1); + + case::ge_to_point_compresses(g).accepts(); + case::ge_to_point_compresses(ge_negate(g)).accepts(); +} + +// 1. point_to_gej +#[test] +fn point_to_gej_roundtrip() { + let g: Ge = g_times(1); + + case::point_to_gej_roundtrip(g).accepts(); + case::point_to_gej_roundtrip(ge_negate(g)).accepts(); +} + +#[test] +fn point_to_gej_rejects_invalid_x() { + // Off-curve x = 0: `decompress` returns `None`. + case::point_to_gej((0, ZERO), (0, ZERO)).rejects(PrunedBranch); + + // Unreduced x = p ≡ 0: the same off-curve x. + case::point_to_gej((0, SECP_P), (0, ZERO)).rejects(PrunedBranch); +} + +#[test] +fn point_to_gej_reduces_x() { + let (parity, x) = compress(x_one()); + + // `decompress` reads x mod p: (parity, 1 + p) decompresses to the point with x = 1. + case::point_to_gej((parity, add_u256(x, SECP_P)), (parity, x)).accepts(); +} + +// 2. fe_sub +#[test] +fn fe_sub_self_is_zero() { + let a: Fe = [0xEF; 32]; + + case::fe_sub(a, a, ZERO).accepts(); +} + +#[test] +fn fe_sub_underflow_and_unreduced() { + case::fe_sub_reference([0xFE; 32], ZERO).accepts(); + case::fe_sub_reference([0xFF; 32], ZERO).accepts(); + + case::fe_sub_reference(ZERO, ONE).accepts(); + case::fe_sub_reference(SECP_P, ONE).accepts(); + case::fe_sub_reference(ONE, SECP_P).accepts(); +} + +#[test] +fn fe_sub_matches_reference() { + let a: Fe = [0xFE; 32]; + let b: Fe = [0xEF; 32]; + + case::fe_sub_reference(a, b).accepts(); + case::fe_sub_reference(b, a).accepts(); +} + +// 3. scalar_sub +#[test] +fn scalar_sub_matches_reference() { + let a: Scalar = [0xA5; 32]; + let b: Scalar = [0x5A; 32]; + + case::scalar_sub_reference(a, b).accepts(); + case::scalar_sub_reference(b, a).accepts(); +} + +#[test] +fn scalar_sub_self_is_zero() { + let a: Scalar = [0xA5; 32]; + + case::scalar_sub(a, a, ZERO).accepts(); +} + +#[test] +fn scalar_sub_underflow_and_unreduced() { + case::scalar_sub_reference([0xFF; 32], ZERO).accepts(); + case::scalar_sub_reference(ZERO, ONE).accepts(); + case::scalar_sub_reference(SECP_N, ONE).accepts(); + case::scalar_sub_reference(ONE, SECP_N).accepts(); +} + +// 4. gej_sub +#[test] +fn gej_sub_matches_reference() { + let p: Ge = g_times(0x01); + let q: Ge = g_times(0x10); + + case::gej_sub_reference(p, q).accepts(); + case::gej_sub_reference(q, p).accepts(); +} + +#[test] +fn gej_sub_edge_cases() { + let g: Ge = g_times(1); + let two_g: Gej = ge_to_gej(g_times(2)); + + // P - P = inf + case::gej_sub_reference(g, g).accepts(); + + // G - (-G) = G + G = 2G + case::gej_sub(ge_to_gej(g), ge_to_gej(ge_negate(g)), two_g).accepts(); + + // 3G - G = 2G, both operands with non-unit Z + case::gej_sub( + rescale(g_times(3), [0x4E; 32]), + rescale(g, [0x2A; 32]), + two_g, + ) + .accepts(); +} + +#[test] +fn gej_sub_infinity_operands() { + let g: Gej = ge_to_gej(g_times(1)); + let minus_g: Gej = ge_to_gej(ge_negate(g_times(1))); + + // G - inf = G + case::gej_sub(g, INFINITY, g).accepts(); + + // inf - G = -G + case::gej_sub(INFINITY, g, minus_g).accepts(); + + // inf - inf = inf + case::gej_sub(INFINITY, INFINITY, INFINITY).accepts(); +} + +// 5. fe_eq +#[test] +fn fe_eq_reflexive() { + let a: Fe = [0xFE; 32]; + + case::fe_eq(a, a).accepts(); +} + +#[test] +fn fe_eq_zero_and_p_are_equal() { + case::fe_eq(ZERO, SECP_P).accepts(); +} + +#[test] +fn fe_eq_rejects_distinct() { + case::fe_eq(ZERO, ONE).rejects(AssertFailed); + // n ≢ 0 (mod p): catches reducing by the wrong modulus. + case::fe_eq(ZERO, SECP_N).rejects(AssertFailed); +} + +// 6. scalar_eq +#[test] +fn scalar_eq_s_and_s_plus_n_are_equal() { + let s: Scalar = u256(5); + + case::scalar_eq(s, add_u256(s, SECP_N)).accepts(); +} + +#[test] +fn scalar_eq_rejects_distinct() { + case::scalar_eq(ZERO, ONE).rejects(AssertFailed); + // p ≢ 0 (mod n): catches reducing by the wrong modulus. + case::scalar_eq(ZERO, SECP_P).rejects(AssertFailed); +} + +// 7. ge_eq +#[test] +fn ge_eq_reflexive() { + let g: Ge = g_times(1); + + case::ge_eq(g, g).accepts(); +} + +#[test] +fn ge_eq_reduces_coordinates() { + let (x, y) = x_one(); + + case::ge_eq((x, y), (add_u256(x, SECP_P), y)).accepts(); +} + +#[test] +fn ge_eq_rejects_negation() { + case::ge_eq_negation(g_times(1)).rejects(AssertFailed); +} + +#[test] +fn ge_eq_rejects_different_x() { + case::ge_eq(g_times(1), g_times(2)).rejects(AssertFailed); +} + +// 8. gej_point_eq +#[test] +fn gej_point_eq_rescaled() { + case::gej_point_eq_rescaled(g_times(1), [0x4E; 32]).accepts(); +} + +#[test] +fn gej_point_eq_rejects_negation() { + case::gej_point_eq_negation(g_times(1)).rejects(AssertFailed); +} + +#[test] +fn gej_point_eq_off_curve_is_false() { + // x = 0 is off-curve: 7 is not a square mod p. + case::gej_point_eq_off_curve_point(g_times(1), ZERO).rejects(AssertFailed); +} + +#[test] +fn gej_point_eq_rejects_off_curve_gej() { + // (x, 1) shares x with G but is off-curve. + case::gej_point_eq_off_curve_gej(g_times(1).0, ONE).rejects(AssertFailed); +} + +#[test] +fn gej_point_eq_rejects_infinity() { + case::gej_point_eq(INFINITY, compress(g_times(1))).rejects(AssertFailed); +} + +#[test] +fn gej_point_eq_rejects_other_point() { + case::gej_point_eq(ge_to_gej(g_times(1)), compress(g_times(2))).rejects(AssertFailed); +} + +#[test] +fn gej_point_eq_reduces_x() { + let (x, y) = x_one(); + let x_unreduced = add_u256(x, SECP_P); + let (parity, _) = compress((x, y)); + + // Reduced Gej, unreduced point. + case::gej_point_eq(ge_to_gej((x, y)), (parity, x_unreduced)).accepts(); + + // Unreduced Gej, reduced point. + case::gej_point_eq(ge_to_gej((x_unreduced, y)), (parity, x)).accepts(); +} + +// 9. safe_gej_normalize +#[test] +fn safe_gej_normalize_roundtrip() { + let g: Ge = g_times(1); + + case::safe_gej_normalize_rescaled(g, ONE).accepts(); + case::safe_gej_normalize_rescaled(g, [0x4E; 32]).accepts(); +} + +#[test] +fn safe_gej_normalize_rejects_infinity() { + // `gej_normalize` returns `None` for infinity, so `unwrap` fails before the comparison. + case::safe_gej_normalize(INFINITY, Ge::default()).rejects(PrunedBranch); +}