From 8e550080fb292d7d5ea8f990efd01a6808e51902 Mon Sep 17 00:00:00 2001 From: Illia Kripaka Date: Tue, 3 Nov 2026 16:09:09 +0200 Subject: [PATCH 1/5] add fuzz entry in CI --- .github/workflows/tests.yml | 6 ++++++ .gitignore | 1 + Simplex.toml | 4 ++-- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 610a52e..5c875d1 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -60,6 +60,12 @@ jobs: run: | cargo build --workspace --all-features --verbose + - name: Fuzz + env: + SIMPLEX_TEST_VERBOSE: ${{ runner.debug == '1' && '-v' || '' }} + run: | + simplex test --fuzz --test-threads 4 "${SIMPLEX_TEST_VERBOSE}" -- --release + - 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/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 = "" From bca8391fbe9c83cb4f575e04d4cb1311d059bc41 Mon Sep 17 00:00:00 2001 From: Illia Kripaka Date: Wed, 4 Nov 2026 15:40:42 +0200 Subject: [PATCH 2/5] add secp fuzz tests --- tests/stdlib/common/fuzz.rs | 36 +++ tests/stdlib/common/mod.rs | 1 + tests/stdlib/secp256k1/operations.rs | 392 ++++++++++++++++++++++++--- 3 files changed, 394 insertions(+), 35 deletions(-) create mode 100644 tests/stdlib/common/fuzz.rs diff --git a/tests/stdlib/common/fuzz.rs b/tests/stdlib/common/fuzz.rs new file mode 100644 index 0000000..529ee79 --- /dev/null +++ b/tests/stdlib/common/fuzz.rs @@ -0,0 +1,36 @@ +use simplex::simplicityhl::{Arguments, WitnessValues}; + +use simplex::fuzz::proptest::strategy::Strategy; +use simplex::fuzz::{Expect, FuzzProgramTrait, Scenario}; +use simplex::{FuzzMode, TestContext}; + +pub fn run( + context: &TestContext, + strategy: impl Strategy + 'static, + name: &'static str, + expect: Expect, + scenario: Option, +) { + const DEFAULT_SPEND_PATH: usize = 0; + + let mut scenario = scenario.unwrap_or_default(); + scenario + .add::

(name) + .spends(DEFAULT_SPEND_PATH) + .custom_strategy(strategy.prop_map(Into::into)); + + 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..a25bd30 100644 --- a/tests/stdlib/common/mod.rs +++ b/tests/stdlib/common/mod.rs @@ -1,4 +1,5 @@ pub mod core; +pub mod fuzz; pub mod helper; pub mod u256_wrapper; pub mod uint; diff --git a/tests/stdlib/secp256k1/operations.rs b/tests/stdlib/secp256k1/operations.rs index 3bc6798..d8cf173 100644 --- a/tests/stdlib/secp256k1/operations.rs +++ b/tests/stdlib/secp256k1/operations.rs @@ -13,6 +13,18 @@ use simplicityhl_std::artifacts::tests::secp256k1::operations::derived_operation use FunctionToTest::*; +type U256Alias = [u8; 32]; +/// A **G**roup **E**lement, represented as an affine curve point (u256, u256) +type Ge = (U256Alias, U256Alias); +/// A **G**roup **E**lement, represented using **J**acobian coordinates ((X, Y), Z) +type Gej = (Ge, U256Alias); +/// A compressed curve point (y_parity, x) +type Point = (u8, U256Alias); +// **F**ield **e**lement +type Fe = U256Alias; +// A multiplier for curve points, with arithmetic modulo the group order **n** +type Scalar = U256Alias; + enum FunctionToTest { GeToPoint, PointToGej, @@ -43,6 +55,7 @@ fn program() -> Secp256k1OperationsTestProgram { } /// One dispatch arm of the contract, plus the witness it reads. +#[derive(Clone, Debug)] struct Case { witness: Secp256k1OperationsTestWitness, } @@ -51,85 +64,81 @@ 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]), + first_uint: U256Alias::default(), + second_uint: U256Alias::default(), + first_ge: Ge::default(), + second_ge: Ge::default(), + first_gej: Gej::default(), + second_gej: Gej::default(), + first_point: Point::default(), + expected_uint: U256Alias::default(), + expected_ge: Ge::default(), + expected_gej: Gej::default(), + expected_point: Point::default(), }, } } 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 { + fn uints(mut self, first_uint: U256Alias, second_uint: U256Alias) -> 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 { + fn ge(mut self, first_ge: Ge) -> 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 { + fn ges(mut self, first_ge: Ge, second_ge: Ge) -> 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 { + fn gej(mut self, first_gej: Gej) -> 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 { + fn gejs(mut self, first_gej: Gej, second_gej: Gej) -> 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 { + fn point(mut self, first_point: Point) -> 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 { + fn expect_uint(mut self, expected_uint: U256Alias) -> 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 { + fn expect_ge(mut self, expected_ge: Ge) -> 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 { + fn expect_gej(mut self, expected_gej: Gej) -> 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 { + fn expect_point(mut self, expected_point: Point) -> Self { self.witness.expected_point = expected_point; self } @@ -168,7 +177,7 @@ fn mod_n(x: &BigUint) -> BigUint { x % secp_n() } -fn fe_sub_ref(a: [u8; 32], b: [u8; 32]) -> [u8; 32] { +fn fe_sub_ref(a: Fe, b: Fe) -> Fe { let p = secp_p(); let a = BigUint::from_bytes_be(&a) % &p; let b = BigUint::from_bytes_be(&b) % &p; @@ -176,7 +185,7 @@ fn fe_sub_ref(a: [u8; 32], b: [u8; 32]) -> [u8; 32] { to_32_be(&((a + &p - b) % &p)) } -fn scalar_sub_ref(a: [u8; 32], b: [u8; 32]) -> [u8; 32] { +fn scalar_sub_ref(a: Scalar, b: Scalar) -> Scalar { let n = secp_n(); let a = BigUint::from_bytes_be(&a) % &n; let b = BigUint::from_bytes_be(&b) % &n; @@ -184,7 +193,7 @@ fn scalar_sub_ref(a: [u8; 32], b: [u8; 32]) -> [u8; 32] { to_32_be(&((a + &n - b) % &n)) } -fn fe_negate_ref(a: [u8; 32]) -> [u8; 32] { +fn fe_negate_ref(a: Fe) -> Fe { let p = secp_p(); let a = BigUint::from_bytes_be(&a) % &p; @@ -195,7 +204,7 @@ fn fe_negate_ref(a: [u8; 32]) -> [u8; 32] { } } -fn fe_mul_ref(a: [u8; 32], b: [u8; 32]) -> [u8; 32] { +fn fe_mul_ref(a: Fe, b: Fe) -> Fe { let p = secp_p(); let a = BigUint::from_bytes_be(&a); let b = BigUint::from_bytes_be(&b); @@ -211,15 +220,15 @@ fn random_uint_bytes() -> [u8; 32] { b } -fn random_fe_bytes() -> [u8; 32] { +fn random_fe_bytes() -> Fe { to_32_be(&mod_p(&BigUint::from_bytes_be(&random_uint_bytes()))) } -fn random_scalar_bytes() -> [u8; 32] { +fn random_scalar_bytes() -> Scalar { to_32_be(&mod_n(&BigUint::from_bytes_be(&random_uint_bytes()))) } -fn random_ge_bytes() -> ([u8; 32], [u8; 32]) { +fn random_ge_bytes() -> Ge { let secp = Secp256k1::new(); let sk = SecretKey::new(&mut SecpOsRng); let pk = PublicKey::from_secret_key(&secp, &sk); @@ -234,18 +243,18 @@ fn random_ge_bytes() -> ([u8; 32], [u8; 32]) { (x, y) } -fn ge_to_gej(ge: ([u8; 32], [u8; 32])) -> (([u8; 32], [u8; 32]), [u8; 32]) { +fn ge_to_gej(ge: Ge) -> Gej { let mut one = [0u8; 32]; one[31] = 1; (ge, one) } -fn compress(ge: ([u8; 32], [u8; 32])) -> (u8, [u8; 32]) { +fn compress(ge: Ge) -> Point { (ge.1[31] & 1, ge.0) } -fn pk_to_gej(pk: &PublicKey) -> (([u8; 32], [u8; 32]), [u8; 32]) { +fn pk_to_gej(pk: &PublicKey) -> Gej { let ser = pk.serialize_uncompressed(); let mut x = [0u8; 32]; @@ -432,3 +441,316 @@ fn safe_gej_normalize_roundtrip(context: simplex::TestContext) -> anyhow::Result .expect_ge(ge) .run(&context) } + +mod fuzz { + use super::*; + + use std::fmt::Debug; + + use simplex::simplicityhl::{Arguments, WitnessValues}; + + use simplex::fuzz::Expect; + use simplex::fuzz::proptest::prelude::{Just, any}; + use simplex::fuzz::proptest::strategy::{BoxedStrategy, Strategy}; + use simplex::{FuzzMode, TestContext}; + + use crate::common::fuzz; + + fn arb_fe() -> impl Strategy { + any::<[u8; 32]>().prop_filter("valid secp256k1 field element", |value| *value < SECP_P) + } + + fn arb_non_zero_fe() -> impl Strategy { + arb_fe().prop_filter("non-zero secp256k1 field element", |value| { + *value != [0; 32] + }) + } + + fn arb_scalar() -> impl Strategy { + any::<[u8; 32]>().prop_filter("valid secp256k1 scalar", |value| *value < SECP_N) + } + + fn arb_secret_key() -> impl Strategy { + any::<[u8; 32]>().prop_filter_map("valid secp256k1 secret key", |bytes| { + SecretKey::from_slice(&bytes).ok() + }) + } + + fn ge_from_secret_key(secret_key: SecretKey) -> Ge { + let secp = Secp256k1::new(); + let public_key = PublicKey::from_secret_key(&secp, &secret_key); + let serialized = public_key.serialize_uncompressed(); + + let mut x = [0; 32]; + x.copy_from_slice(&serialized[1..33]); + + let mut y = [0; 32]; + y.copy_from_slice(&serialized[33..65]); + + (x, y) + } + + fn arb_ge() -> impl Strategy { + arb_secret_key().prop_map(ge_from_secret_key) + } + + /// Fuzz counterparts for every `#[simplex::test]` case with randomized inputs. + /// Deterministic cases stay as regular tests. + struct CaseFuzz { + cases: BoxedStrategy, + context: TestContext, + test_name: &'static str, + expect: Expect, + } + + fn case_fuzz( + function: FunctionToTest, + context: TestContext, + test_name: &'static str, + ) -> CaseFuzz { + CaseFuzz { + cases: Just(case(function)).boxed(), + context, + test_name, + expect: Expect::Accept, + } + } + + impl CaseFuzz { + fn inject( + mut self, + values: impl Strategy + 'static, + inject: impl Fn(Case, T) -> Case + 'static, + ) -> Self + where + T: Debug + 'static, + { + self.cases = (self.cases, values) + .prop_map(move |(case, values)| inject(case, values)) + .boxed(); + self + } + + fn expect(mut self, expect: Expect) -> Self { + self.expect = expect; + self + } + + fn run(self) -> anyhow::Result<()> { + let strategy = self.cases.prop_map(|case| { + let arguments: Arguments = Secp256k1OperationsTestArguments {}.into(); + let witness: WitnessValues = case.witness.into(); + + (arguments, witness) + }); + + fuzz::run::( + &self.context, + strategy, + self.test_name, + self.expect, + None, + ); + + Ok(()) + } + } + + // 0. ge_to_point + #[simplex::fuzz] + fn ge_to_point_matches_parity(context: TestContext) -> anyhow::Result<()> { + // Sample one on-curve point; whatever parity it has, that's what we expect + // ge_to_point to produce. + case_fuzz(GeToPoint, context, "ge_to_point") + .inject(arb_ge(), |case, ge| { + let expected_parity = ge.1[31] & 1; // 0 (even y) or 1 (odd y) + + case.ge(ge).expect_point((expected_parity, ge.0)) + }) + .run() + } + + // 1. point_to_gej + #[simplex::fuzz] + fn point_to_gej_roundtrip(context: TestContext) -> anyhow::Result<()> { + case_fuzz(PointToGej, context, "point_to_gej") + .inject(arb_ge(), |case, ge| { + let point = compress(ge); + + case.point(point).expect_point(point) + }) + .run() + } + + // 2. fe_sub + #[simplex::fuzz] + fn fe_sub_is_zero(context: TestContext) -> anyhow::Result<()> { + case_fuzz(FeSub, context, "fe_sub self is zero") + .inject(arb_fe(), |case, a| case.uints(a, a).expect_uint([0u8; 32])) + .run() + } + + #[simplex::fuzz] + fn fe_sub(context: TestContext) -> anyhow::Result<()> { + case_fuzz(FeSub, context, "fe_sub") + .inject((arb_fe(), arb_fe()), |case, (a, b)| { + let exp = fe_sub_ref(a, b); + + case.uints(a, b).expect_uint(exp) + }) + .run() + } + + // 3. scalar_sub + #[simplex::fuzz] + fn scalar_sub(context: TestContext) -> anyhow::Result<()> { + case_fuzz(ScalarSub, context, "scalar_sub") + .inject((arb_scalar(), arb_scalar()), |case, (a, b)| { + let exp = scalar_sub_ref(a, b); + + case.uints(a, b).expect_uint(exp) + }) + .run() + } + + // 4. gej_sub + #[simplex::fuzz] + fn gej_sub(context: TestContext) -> anyhow::Result<()> { + case_fuzz(GejSub, context, "gej_sub") + .inject( + (arb_secret_key(), arb_secret_key()) + .prop_filter("distinct secp256k1 points", |(p, q)| p != q), + |case, (p_secret, q_secret)| { + let secp = Secp256k1::new(); + let p = PublicKey::from_secret_key(&secp, &p_secret); + let q = PublicKey::from_secret_key(&secp, &q_secret); + let diff = p.combine(&q.negate(&secp)).expect("p - q non-infinity"); + + case.gejs(pk_to_gej(&p), pk_to_gej(&q)) + .expect_gej(pk_to_gej(&diff)) + }, + ) + .run() + } + + // 4.1 gej_sub_gives_inf and fails + #[simplex::fuzz] + fn gej_sub_gives_inf(context: TestContext) -> anyhow::Result<()> { + case_fuzz(GejSub, context, "gej_sub") + .inject(arb_secret_key(), |case, p_secret| { + let secp = Secp256k1::new(); + let p = PublicKey::from_secret_key(&secp, &p_secret); + + // we expect zeroed arrays + case.gejs(pk_to_gej(&p), pk_to_gej(&p)) + .expect_gej(Default::default()) + }) + .expect(Expect::Accept) + .run() + } + + // 5. fe_eq + #[simplex::fuzz] + fn fe_eq_reflexive(context: TestContext) -> anyhow::Result<()> { + case_fuzz(FeEq, context, "fe_eq_reflexive") + .inject(arb_fe(), |case, value| case.uints(value, value)) + .run() + } + + // 6. scalar_eq has only a deterministic case and remains a regular test. + + // 7. ge_eq + #[simplex::fuzz] + fn ge_eq_rejects_negation(context: TestContext) -> anyhow::Result<()> { + case_fuzz(GeEq, context, "ge_eq negation") + .inject(arb_ge(), |case, ge| { + case.ges(ge, (ge.0, fe_negate_ref(ge.1))) + }) + .expect(Expect::Reject) + .run() + } + + // 8. gej_point_eq + #[simplex::fuzz] + fn gej_point_eq_rescaled(context: TestContext) -> anyhow::Result<()> { + case_fuzz(GejPointEq, context, "gej_point_eq_rescaled") + .inject((arb_ge(), arb_non_zero_fe()), |case, (ge, lambda)| { + let lambda_squared = fe_mul_ref(lambda, lambda); + let lambda_cubed = fe_mul_ref(lambda_squared, lambda); + + let gej: Gej = ( + ( + fe_mul_ref(ge.0, lambda_squared), + fe_mul_ref(ge.1, lambda_cubed), + ), + lambda, + ); + + case.gej(gej).point(compress(ge)) + }) + .run() + } + + #[simplex::fuzz] + fn gej_point_eq_rejects_negation(context: TestContext) -> anyhow::Result<()> { + case_fuzz(GejPointEq, context, "gej_point_eq negation") + .inject(arb_ge(), |case, ge| { + let (parity, x) = compress(ge); + + case.gej(ge_to_gej(ge)).point((parity ^ 1, x)) + }) + .expect(Expect::Reject) + .run() + } + + // 9. safe_gej_normalize + #[simplex::fuzz] + fn safe_gej_normalize_roundtrip(context: TestContext) -> anyhow::Result<()> { + case_fuzz(SafeGejNormalize, context, "safe_gej_normalize_roundtrip") + .inject((arb_ge(), arb_non_zero_fe()), |case, (ge, lambda)| { + let lambda_squared = fe_mul_ref(lambda, lambda); + let lambda_cubed = fe_mul_ref(lambda_squared, lambda); + + let gej: Gej = ( + ( + fe_mul_ref(ge.0, lambda_squared), + fe_mul_ref(ge.1, lambda_cubed), + ), + lambda, + ); + + case.gej(gej).expect_ge(ge) + }) + .run() + } + + #[simplex::fuzz] + fn gej_point_eq_off_curve_is_false(context: TestContext) -> anyhow::Result<()> { + case_fuzz( + GejPointEq, + context, + "gej_point_eq off-curve compressed point", + ) + .inject(arb_ge(), |case, ge| { + case.gej(ge_to_gej(ge)).point((0, [0; 32])) + }) + .expect(Expect::Reject) + .run() + } + + #[simplex::fuzz] + fn gej_point_eq_rejects_off_curve_gej(context: TestContext) -> anyhow::Result<()> { + case_fuzz(GejPointEq, context, "gej_point_eq off-curve Jacobian point") + .inject(arb_ge(), |case, ge| { + // Obtain (x, 0, 1) point. + let gej = ge_to_gej((ge.0, [0; 32])); + + // Obtain (0, x) point with order 2 (secp256k1 has odd prime order). + let compressed_point = (0, ge.0); + + case.gej(gej).point(compressed_point) + }) + .expect(Expect::Reject) + .run() + } +} From 3f7ac57e27ed36d911b750ec582a6ab944057e69 Mon Sep 17 00:00:00 2001 From: Illia Kripaka Date: Thu, 12 Nov 2026 16:03:39 +0200 Subject: [PATCH 3/5] refactor tests --- tests/stdlib/common/fuzz.rs | 77 ++- tests/stdlib/secp256k1/core.rs | 379 ++++++++++++ tests/stdlib/secp256k1/mod.rs | 4 +- tests/stdlib/secp256k1/operations.rs | 697 ++-------------------- tests/stdlib/secp256k1/operations_fuzz.rs | 215 +++++++ 5 files changed, 699 insertions(+), 673 deletions(-) create mode 100644 tests/stdlib/secp256k1/core.rs create mode 100644 tests/stdlib/secp256k1/operations_fuzz.rs diff --git a/tests/stdlib/common/fuzz.rs b/tests/stdlib/common/fuzz.rs index 529ee79..799464a 100644 --- a/tests/stdlib/common/fuzz.rs +++ b/tests/stdlib/common/fuzz.rs @@ -1,27 +1,80 @@ -use simplex::simplicityhl::{Arguments, WitnessValues}; +use std::fmt::Debug; + +use simplex::program::ProgramSchema; +use simplex::simplicityhl::Arguments; use simplex::fuzz::proptest::strategy::Strategy; -use simplex::fuzz::{Expect, FuzzProgramTrait, Scenario}; +use simplex::fuzz::{FuzzProgramTrait, FuzzProgramValues, Scenario}; use simplex::{FuzzMode, TestContext}; -pub fn run( +pub use simplex::fuzz::Expect; + +const DEFAULT_SPENT_INPUT: usize = 0; + +/// One call into a dispatch test contract (`function_index` + operands + expected values). +/// +/// Implemented once per test module for its `Case` builder, so fuzz tests only +/// describe how generated inputs become a case. +pub trait DispatchFuzzCase: 'static { + type Program: FuzzProgramTrait; + + /// Contract name used in fuzz scenarios and diagnostics. + const PROGRAM_NAME: &'static str; + + fn arguments() -> ::Arguments; + + fn into_witness(self) -> ::Witness; +} + +/// Fuzz `inputs` through `build`: every generated case must be accepted. +pub fn accepts( + context: &TestContext, + inputs: impl Strategy + 'static, + build: impl Fn(T) -> C + 'static, +) where + C: DispatchFuzzCase, + T: Debug + 'static, +{ + check(context, inputs, build, Expect::Accept); +} + +/// Fuzz `inputs` through `build`: every generated case must be rejected. +pub fn rejects( + context: &TestContext, + inputs: impl Strategy + 'static, + build: impl Fn(T) -> C + 'static, +) where + C: DispatchFuzzCase, + T: Debug + 'static, +{ + check(context, inputs, build, Expect::Reject); +} + +/// Fuzz `inputs` through `build` and expect `expect` for every generated case. +pub fn check( context: &TestContext, - strategy: impl Strategy + 'static, - name: &'static str, + inputs: impl Strategy + 'static, + build: impl Fn(T) -> C + 'static, expect: Expect, - scenario: Option, -) { - const DEFAULT_SPEND_PATH: usize = 0; +) where + C: DispatchFuzzCase, + 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.unwrap_or_default(); + let mut scenario = Scenario::default(); scenario - .add::

(name) - .spends(DEFAULT_SPEND_PATH) - .custom_strategy(strategy.prop_map(Into::into)); + .add::(C::PROGRAM_NAME) + .spends(DEFAULT_SPENT_INPUT) + .custom_strategy(values); run_scenario(context, scenario, expect); } +/// Run a hand-built scenario, for tests that need more than one program or custom bindings. pub fn run_scenario(context: &TestContext, scenario: Scenario, expect: Expect) { let engine = context.engine(scenario).spec(move |_| expect); diff --git a/tests/stdlib/secp256k1/core.rs b/tests/stdlib/secp256k1/core.rs new file mode 100644 index 0000000..dc10f6e --- /dev/null +++ b/tests/stdlib/secp256k1/core.rs @@ -0,0 +1,379 @@ +use num_bigint::BigUint; +use rand::{RngCore, rngs::OsRng}; +use secp256k1_zkp::{PublicKey, SecretKey, rand::rngs::OsRng as SecpOsRng}; + +use crate::common::core::{Expect, run}; +use crate::common::fuzz::DispatchFuzzCase; + +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, +}; + +pub const ZERO: U256 = [0; 32]; +pub const ONE: U256 = u256(1); + +/// A big-endian 256-bit value. +pub type U256 = [u8; 32]; +/// A **f**ield **e**lement, arithmetic modulo **p**. +pub type Fe = U256; +/// A multiplier for curve points, arithmetic modulo the group order **n**. +pub type Scalar = U256; +/// A **G**roup **E**lement, represented as an affine curve point (x, y). +pub type Ge = (Fe, Fe); +/// A **G**roup **E**lement, represented using **J**acobian coordinates ((X, Y), Z). +pub type Gej = (Ge, Fe); +/// A compressed curve point (y_parity, x). +pub type Point = (u8, Fe); + +pub enum FunctionToTest { + GeToPoint, + PointToGej, + FeSub, + ScalarSub, + GejSub, + FeEq, + ScalarEq, + GeEq, + GejPointEq, + SafeGejNormalize, +} + +// FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F +pub const SECP_P: U256 = [ + 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 +pub const SECP_N: U256 = [ + 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, +]; + +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 +} + +pub fn big(value: U256) -> BigUint { + BigUint::from_bytes_be(&value) +} + +/// # Panics +/// If `value` does not fit in 256 bits. +pub fn to_u256(value: &BigUint) -> U256 { + let bytes = value.to_bytes_be(); + assert!(bytes.len() <= 32, "{value:#x} does not fit in 256 bits"); + + let mut out = [0; 32]; + out[32 - bytes.len()..].copy_from_slice(&bytes); + out +} + +/// `a + b` as plain integers. +/// +/// # Panics +/// On overflow past 256 bits. +pub fn add_u256(a: U256, b: U256) -> U256 { + to_u256(&(big(a) + big(b))) +} + +/// `a - b (mod modulus)`, canonical. Operands may be non-canonical. +pub fn sub_mod(a: U256, b: U256, modulus: U256) -> U256 { + let m = big(modulus); + + let a = big(a) % &m + &m; + let b = big(b) % &m; + + to_u256(&((a - b) % &m)) +} + +pub fn fe_mul(a: Fe, b: Fe) -> Fe { + to_u256(&(big(a) * big(b) % big(SECP_P))) +} + +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_gej(ge: Ge) -> Gej { + (ge, ONE) +} + +pub fn ge_negate((x, y): Ge) -> Ge { + (x, sub_mod(ZERO, y, SECP_P)) +} + +pub fn compress((x, y): Ge) -> Point { + ( + y[31] & 1, // 0 (even y) or 1 (odd y) + x, + ) +} + +/// `(λ²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) +} + +fn random_mod(modulus: U256) -> U256 { + let mut bytes = [0; 32]; + OsRng.fill_bytes(&mut bytes); + + to_u256(&(big(bytes) % big(modulus))) +} + +pub fn random_fe() -> Fe { + random_mod(SECP_P) +} + +pub fn random_scalar() -> Scalar { + random_mod(SECP_N) +} + +pub fn random_public_key() -> PublicKey { + let secret_key = SecretKey::new(&mut SecpOsRng); + + PublicKey::from_secret_key(secp256k1_zkp::SECP256K1, &secret_key) +} + +pub fn random_ge() -> Ge { + pk_to_ge(&random_public_key()) +} + +/// One dispatch arm of the contract, plus the witness it reads. +#[derive(Clone, Debug)] +pub struct Case { + witness: Secp256k1OperationsTestWitness, +} + +pub fn case(function: FunctionToTest) -> Case { + Case { + 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(), + }, + } +} + +impl Case { + /// The two field or scalar operands, `first_uint` and `second_uint`. + pub fn uints(mut self, first_uint: U256, second_uint: U256) -> Self { + self.witness.first_uint = first_uint; + self.witness.second_uint = second_uint; + self + } + + /// Only `first_ge`. + pub fn ge(mut self, first_ge: Ge) -> Self { + self.witness.first_ge = first_ge; + self + } + + /// The two affine points, `first_ge` and `second_ge`. + pub fn ges(mut self, first_ge: Ge, second_ge: Ge) -> Self { + self.witness.first_ge = first_ge; + self.witness.second_ge = second_ge; + self + } + + /// Only `first_gej`. + pub fn gej(mut self, first_gej: Gej) -> Self { + self.witness.first_gej = first_gej; + self + } + + /// The two Jacobian points, `first_gej` and `second_gej`. + pub fn gejs(mut self, first_gej: Gej, second_gej: Gej) -> Self { + self.witness.first_gej = first_gej; + self.witness.second_gej = second_gej; + self + } + + /// `first_point`: a compressed point, parity byte and x coordinate. + pub fn point(mut self, first_point: Point) -> Self { + self.witness.first_point = first_point; + self + } + + /// `expected_uint`: the field or scalar the arm should produce. + pub fn expect_uint(mut self, expected_uint: U256) -> Self { + self.witness.expected_uint = expected_uint; + self + } + + /// `expected_ge`: the affine point the arm should produce. + pub fn expect_ge(mut self, expected_ge: Ge) -> Self { + self.witness.expected_ge = expected_ge; + self + } + + /// `expected_gej`: the Jacobian point the arm should produce. + pub fn expect_gej(mut self, expected_gej: Gej) -> Self { + self.witness.expected_gej = expected_gej; + self + } + + /// `expected_point`: the compressed point the arm should produce. + pub fn expect_point(mut self, expected_point: Point) -> Self { + self.witness.expected_point = expected_point; + self + } + + /// Fund, spend, and expect the spend to succeed. + pub fn run(self, context: &simplex::TestContext) -> anyhow::Result<()> { + self.expecting(context, Expect::Ok) + } + + /// Fund, spend, and expect `expect`. + pub fn expecting(self, context: &simplex::TestContext, expect: Expect) -> anyhow::Result<()> { + let program = Secp256k1OperationsTestProgram::new(Case::arguments()); + + run(context, program, self.witness, expect) + } +} + +impl DispatchFuzzCase for Case { + type Program = Secp256k1OperationsTestProgram; + + const PROGRAM_NAME: &'static str = "secp256k1::operations"; + + fn arguments() -> Secp256k1OperationsTestArguments { + Secp256k1OperationsTestArguments {} + } + + fn into_witness(self) -> Secp256k1OperationsTestWitness { + self.witness + } +} + +pub mod cases { + use super::*; + + use FunctionToTest::*; + + /// `ge_to_point` keeps x and takes the parity of y. + pub fn ge_to_point(ge: Ge) -> Case { + case(GeToPoint).ge(ge).expect_point(compress(ge)) + } + + /// `point_to_gej` decompresses to the same point. + pub fn point_to_gej(ge: Ge) -> Case { + let point = compress(ge); + + case(PointToGej).point(point).expect_point(point) + } + + /// `fe_sub` matches the reference, for any (also non-canonical) operands. + pub fn fe_sub(a: Fe, b: Fe) -> Case { + case(FeSub).uints(a, b).expect_uint(sub_mod(a, b, SECP_P)) + } + + /// `scalar_sub` matches the reference, for any (also non-canonical) operands. + pub fn scalar_sub(a: Scalar, b: Scalar) -> Case { + case(ScalarSub) + .uints(a, b) + .expect_uint(sub_mod(a, b, SECP_N)) + } + + /// `gej_sub` matches the reference, the point at infinity included (`p == q`). + pub fn gej_sub(p: PublicKey, q: PublicKey) -> Case { + let expected = if p == q { + // The expected witness for infinity uses all-zero coordinates. + Gej::default() + } else { + let difference = p + .combine(&q.negate(secp256k1_zkp::SECP256K1)) + .expect("p - q non-infinity"); + + ge_to_gej(pk_to_ge(&difference)) + }; + + case(GejSub) + .gejs(ge_to_gej(pk_to_ge(&p)), ge_to_gej(pk_to_ge(&q))) + .expect_gej(expected) + } + + /// `fe_eq(a, b)`, accepted iff `a ≡ b (mod p)`. + pub fn fe_eq(a: Fe, b: Fe) -> Case { + case(FeEq).uints(a, b) + } + + /// `scalar_eq(a, b)`, accepted iff `a ≡ b (mod n)`. + pub fn scalar_eq(a: Scalar, b: Scalar) -> Case { + case(ScalarEq).uints(a, b) + } + + /// `ge_eq(P, -P)`: must be rejected, y differs. + pub fn ge_eq_negation(ge: Ge) -> Case { + case(GeEq).ges(ge, ge_negate(ge)) + } + + /// `gej_point_eq` holds for any Jacobian representation `(λ²X, λ³Y, λ)` of P. + pub fn gej_point_eq_rescaled(ge: Ge, lambda: Fe) -> Case { + case(GejPointEq) + .gej(rescale(ge, lambda)) + .point(compress(ge)) + } + + /// `gej_point_eq(P, compress(-P))` must be false. + /// Flipping the parity bit keeps `x` and selects `(x, -y)`, the negation of `P`. + /// The contract asserts equality, so this witness must be rejected. + pub fn gej_point_eq_negation(ge: Ge) -> Case { + let (parity, x) = compress(ge); + + case(GejPointEq).gej(ge_to_gej(ge)).point((parity ^ 1, x)) + } + + /// `gej_point_eq(P, (0, x))` with an off-curve `x`: must be rejected. + pub fn gej_point_eq_off_curve_point(ge: Ge, x: Fe) -> Case { + case(GejPointEq).gej(ge_to_gej(ge)).point((0, x)) + } + + /// Compare an off-curve `(x, y, 1)` against a compressed point with the same x and parity. + /// + /// The caller supplies an x from a curve point and a y off the curve at that x. + /// Matching x and parity isolates the on-curve check. + pub fn gej_point_eq_off_curve_gej(x: Fe, y: Fe) -> Case { + let off_curve = (x, y); + + case(GejPointEq) + .gej(ge_to_gej(off_curve)) + .point(compress(off_curve)) + } + + /// `safe_gej_normalize` maps any Jacobian representation of P back to P. + pub fn safe_gej_normalize(ge: Ge, lambda: Fe) -> Case { + case(SafeGejNormalize) + .gej(rescale(ge, lambda)) + .expect_ge(ge) + } +} diff --git a/tests/stdlib/secp256k1/mod.rs b/tests/stdlib/secp256k1/mod.rs index 9045df1..418f35e 100644 --- a/tests/stdlib/secp256k1/mod.rs +++ b/tests/stdlib/secp256k1/mod.rs @@ -1 +1,3 @@ -mod operations; +pub(crate) mod core; +pub(crate) mod operations; +mod operations_fuzz; diff --git a/tests/stdlib/secp256k1/operations.rs b/tests/stdlib/secp256k1/operations.rs index d8cf173..24cd709 100644 --- a/tests/stdlib/secp256k1/operations.rs +++ b/tests/stdlib/secp256k1/operations.rs @@ -1,389 +1,93 @@ -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; -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::*; - -type U256Alias = [u8; 32]; -/// A **G**roup **E**lement, represented as an affine curve point (u256, u256) -type Ge = (U256Alias, U256Alias); -/// A **G**roup **E**lement, represented using **J**acobian coordinates ((X, Y), Z) -type Gej = (Ge, U256Alias); -/// A compressed curve point (y_parity, x) -type Point = (u8, U256Alias); -// **F**ield **e**lement -type Fe = U256Alias; -// A multiplier for curve points, with arithmetic modulo the group order **n** -type Scalar = U256Alias; - -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. -#[derive(Clone, Debug)] -struct Case { - witness: Secp256k1OperationsTestWitness, -} - -fn case(function: FunctionToTest) -> Case { - Case { - witness: Secp256k1OperationsTestWitness { - function_index: function as u8, - first_uint: U256Alias::default(), - second_uint: U256Alias::default(), - first_ge: Ge::default(), - second_ge: Ge::default(), - first_gej: Gej::default(), - second_gej: Gej::default(), - first_point: Point::default(), - expected_uint: U256Alias::default(), - expected_ge: Ge::default(), - expected_gej: Gej::default(), - expected_point: Point::default(), - }, - } -} - -impl Case { - /// The two field or scalar operands, `first_uint` and `second_uint`. - fn uints(mut self, first_uint: U256Alias, second_uint: U256Alias) -> Self { - self.witness.first_uint = first_uint; - self.witness.second_uint = second_uint; - self - } - - /// Only `first_ge`. - fn ge(mut self, first_ge: Ge) -> Self { - self.witness.first_ge = first_ge; - self - } - - /// The two affine points, `first_ge` and `second_ge`. - fn ges(mut self, first_ge: Ge, second_ge: Ge) -> Self { - self.witness.first_ge = first_ge; - self.witness.second_ge = second_ge; - self - } - - /// Only `first_gej`. - fn gej(mut self, first_gej: Gej) -> Self { - self.witness.first_gej = first_gej; - self - } - - /// The two Jacobian points, `first_gej` and `second_gej`. - fn gejs(mut self, first_gej: Gej, second_gej: Gej) -> 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: Point) -> 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: U256Alias) -> Self { - self.witness.expected_uint = expected_uint; - self - } - - /// `expected_ge`: the affine point the arm should produce. - fn expect_ge(mut self, expected_ge: Ge) -> Self { - self.witness.expected_ge = expected_ge; - self - } - - /// `expected_gej`: the Jacobian point the arm should produce. - fn expect_gej(mut self, expected_gej: Gej) -> Self { - self.witness.expected_gej = expected_gej; - self - } - - /// `expected_point`: the compressed point the arm should produce. - fn expect_point(mut self, expected_point: Point) -> 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: Fe, b: Fe) -> Fe { - 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: Scalar, b: Scalar) -> Scalar { - 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: Fe) -> Fe { - 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: Fe, b: Fe) -> Fe { - 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() -> Fe { - to_32_be(&mod_p(&BigUint::from_bytes_be(&random_uint_bytes()))) -} - -fn random_scalar_bytes() -> Scalar { - to_32_be(&mod_n(&BigUint::from_bytes_be(&random_uint_bytes()))) -} - -fn random_ge_bytes() -> Ge { - 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: Ge) -> Gej { - let mut one = [0u8; 32]; - one[31] = 1; - - (ge, one) -} - -fn compress(ge: Ge) -> Point { - (ge.1[31] & 1, ge.0) -} - -fn pk_to_gej(pk: &PublicKey) -> Gej { - 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)) -} +use super::core::*; // 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) + cases::ge_to_point(random_ge()).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) + cases::point_to_gej(random_ge()).run(&context) } // 2. fe_sub #[simplex::test] fn fe_sub_self_is_zero(context: simplex::TestContext) -> anyhow::Result<()> { - let a = random_fe_bytes(); + let a = random_fe(); - case(FeSub).uints(a, a).expect_uint([0u8; 32]).run(&context) + cases::fe_sub(a, a).expect_uint(ZERO).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) + cases::fe_sub(random_fe(), random_fe()).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) + cases::scalar_sub(random_scalar(), random_scalar()).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 = random_public_key(); + let mut q = random_public_key(); - 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"); + while q == p { + q = random_public_key(); + } - case(GejSub) - .gejs(pk_to_gej(&p), pk_to_gej(&q)) - .expect_gej(pk_to_gej(&diff)) - .run(&context) + cases::gej_sub(p, q).run(&context) } // 5. fe_eq #[simplex::test] fn fe_eq_reflexive(context: simplex::TestContext) -> anyhow::Result<()> { - let a = random_fe_bytes(); + let a = random_fe(); - case(FeEq).uints(a, a).run(&context) + cases::fe_eq(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) + cases::fe_eq(ZERO, 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); + let s = u256(5); - case(ScalarEq).uints(s, s_plus_n).run(&context) + cases::scalar_eq(s, add_u256(s, SECP_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) + cases::ge_eq_negation(random_ge()).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); + let mut lambda = random_fe(); - case(GejPointEq).gej(g).point(compress(ge)).run(&context) + while lambda == ZERO { + lambda = random_fe(); + } + + cases::gej_point_eq_rescaled(random_ge(), lambda).run(&context) } #[simplex::test] @@ -399,358 +103,31 @@ fn gej_point_eq_rejects_negation(context: simplex::TestContext) -> anyhow::Resul // 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) + cases::gej_point_eq_negation(random_ge()).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) + cases::gej_point_eq_off_curve_point(random_ge(), ZERO).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; + // (x, 1, 1) shares x with P but is off-curve. + // The compressed point shares x and odd parity, isolating the on-curve check. + let neg_one = sub_mod(ZERO, ONE, SECP_P); + let mut ge = random_ge(); + while ge.1 == ONE || ge.1 == neg_one { + ge = random_ge(); + } - case(GejPointEq) - .gej(((ge.0, one), one)) - .point(compress(ge)) - .expecting(&context, Expect::AssertFailed) + cases::gej_point_eq_off_curve_gej(ge.0, ONE).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) -} - -mod fuzz { - use super::*; - - use std::fmt::Debug; - - use simplex::simplicityhl::{Arguments, WitnessValues}; - - use simplex::fuzz::Expect; - use simplex::fuzz::proptest::prelude::{Just, any}; - use simplex::fuzz::proptest::strategy::{BoxedStrategy, Strategy}; - use simplex::{FuzzMode, TestContext}; - - use crate::common::fuzz; - - fn arb_fe() -> impl Strategy { - any::<[u8; 32]>().prop_filter("valid secp256k1 field element", |value| *value < SECP_P) - } - - fn arb_non_zero_fe() -> impl Strategy { - arb_fe().prop_filter("non-zero secp256k1 field element", |value| { - *value != [0; 32] - }) - } - - fn arb_scalar() -> impl Strategy { - any::<[u8; 32]>().prop_filter("valid secp256k1 scalar", |value| *value < SECP_N) - } - - fn arb_secret_key() -> impl Strategy { - any::<[u8; 32]>().prop_filter_map("valid secp256k1 secret key", |bytes| { - SecretKey::from_slice(&bytes).ok() - }) - } - - fn ge_from_secret_key(secret_key: SecretKey) -> Ge { - let secp = Secp256k1::new(); - let public_key = PublicKey::from_secret_key(&secp, &secret_key); - let serialized = public_key.serialize_uncompressed(); - - let mut x = [0; 32]; - x.copy_from_slice(&serialized[1..33]); - - let mut y = [0; 32]; - y.copy_from_slice(&serialized[33..65]); - - (x, y) - } - - fn arb_ge() -> impl Strategy { - arb_secret_key().prop_map(ge_from_secret_key) - } - - /// Fuzz counterparts for every `#[simplex::test]` case with randomized inputs. - /// Deterministic cases stay as regular tests. - struct CaseFuzz { - cases: BoxedStrategy, - context: TestContext, - test_name: &'static str, - expect: Expect, - } - - fn case_fuzz( - function: FunctionToTest, - context: TestContext, - test_name: &'static str, - ) -> CaseFuzz { - CaseFuzz { - cases: Just(case(function)).boxed(), - context, - test_name, - expect: Expect::Accept, - } - } - - impl CaseFuzz { - fn inject( - mut self, - values: impl Strategy + 'static, - inject: impl Fn(Case, T) -> Case + 'static, - ) -> Self - where - T: Debug + 'static, - { - self.cases = (self.cases, values) - .prop_map(move |(case, values)| inject(case, values)) - .boxed(); - self - } - - fn expect(mut self, expect: Expect) -> Self { - self.expect = expect; - self - } - - fn run(self) -> anyhow::Result<()> { - let strategy = self.cases.prop_map(|case| { - let arguments: Arguments = Secp256k1OperationsTestArguments {}.into(); - let witness: WitnessValues = case.witness.into(); - - (arguments, witness) - }); - - fuzz::run::( - &self.context, - strategy, - self.test_name, - self.expect, - None, - ); - - Ok(()) - } - } - - // 0. ge_to_point - #[simplex::fuzz] - fn ge_to_point_matches_parity(context: TestContext) -> anyhow::Result<()> { - // Sample one on-curve point; whatever parity it has, that's what we expect - // ge_to_point to produce. - case_fuzz(GeToPoint, context, "ge_to_point") - .inject(arb_ge(), |case, ge| { - let expected_parity = ge.1[31] & 1; // 0 (even y) or 1 (odd y) - - case.ge(ge).expect_point((expected_parity, ge.0)) - }) - .run() - } - - // 1. point_to_gej - #[simplex::fuzz] - fn point_to_gej_roundtrip(context: TestContext) -> anyhow::Result<()> { - case_fuzz(PointToGej, context, "point_to_gej") - .inject(arb_ge(), |case, ge| { - let point = compress(ge); - - case.point(point).expect_point(point) - }) - .run() - } - - // 2. fe_sub - #[simplex::fuzz] - fn fe_sub_is_zero(context: TestContext) -> anyhow::Result<()> { - case_fuzz(FeSub, context, "fe_sub self is zero") - .inject(arb_fe(), |case, a| case.uints(a, a).expect_uint([0u8; 32])) - .run() - } - - #[simplex::fuzz] - fn fe_sub(context: TestContext) -> anyhow::Result<()> { - case_fuzz(FeSub, context, "fe_sub") - .inject((arb_fe(), arb_fe()), |case, (a, b)| { - let exp = fe_sub_ref(a, b); - - case.uints(a, b).expect_uint(exp) - }) - .run() - } - - // 3. scalar_sub - #[simplex::fuzz] - fn scalar_sub(context: TestContext) -> anyhow::Result<()> { - case_fuzz(ScalarSub, context, "scalar_sub") - .inject((arb_scalar(), arb_scalar()), |case, (a, b)| { - let exp = scalar_sub_ref(a, b); - - case.uints(a, b).expect_uint(exp) - }) - .run() - } - - // 4. gej_sub - #[simplex::fuzz] - fn gej_sub(context: TestContext) -> anyhow::Result<()> { - case_fuzz(GejSub, context, "gej_sub") - .inject( - (arb_secret_key(), arb_secret_key()) - .prop_filter("distinct secp256k1 points", |(p, q)| p != q), - |case, (p_secret, q_secret)| { - let secp = Secp256k1::new(); - let p = PublicKey::from_secret_key(&secp, &p_secret); - let q = PublicKey::from_secret_key(&secp, &q_secret); - let diff = p.combine(&q.negate(&secp)).expect("p - q non-infinity"); - - case.gejs(pk_to_gej(&p), pk_to_gej(&q)) - .expect_gej(pk_to_gej(&diff)) - }, - ) - .run() - } - - // 4.1 gej_sub_gives_inf and fails - #[simplex::fuzz] - fn gej_sub_gives_inf(context: TestContext) -> anyhow::Result<()> { - case_fuzz(GejSub, context, "gej_sub") - .inject(arb_secret_key(), |case, p_secret| { - let secp = Secp256k1::new(); - let p = PublicKey::from_secret_key(&secp, &p_secret); - - // we expect zeroed arrays - case.gejs(pk_to_gej(&p), pk_to_gej(&p)) - .expect_gej(Default::default()) - }) - .expect(Expect::Accept) - .run() - } - - // 5. fe_eq - #[simplex::fuzz] - fn fe_eq_reflexive(context: TestContext) -> anyhow::Result<()> { - case_fuzz(FeEq, context, "fe_eq_reflexive") - .inject(arb_fe(), |case, value| case.uints(value, value)) - .run() - } - - // 6. scalar_eq has only a deterministic case and remains a regular test. - - // 7. ge_eq - #[simplex::fuzz] - fn ge_eq_rejects_negation(context: TestContext) -> anyhow::Result<()> { - case_fuzz(GeEq, context, "ge_eq negation") - .inject(arb_ge(), |case, ge| { - case.ges(ge, (ge.0, fe_negate_ref(ge.1))) - }) - .expect(Expect::Reject) - .run() - } - - // 8. gej_point_eq - #[simplex::fuzz] - fn gej_point_eq_rescaled(context: TestContext) -> anyhow::Result<()> { - case_fuzz(GejPointEq, context, "gej_point_eq_rescaled") - .inject((arb_ge(), arb_non_zero_fe()), |case, (ge, lambda)| { - let lambda_squared = fe_mul_ref(lambda, lambda); - let lambda_cubed = fe_mul_ref(lambda_squared, lambda); - - let gej: Gej = ( - ( - fe_mul_ref(ge.0, lambda_squared), - fe_mul_ref(ge.1, lambda_cubed), - ), - lambda, - ); - - case.gej(gej).point(compress(ge)) - }) - .run() - } - - #[simplex::fuzz] - fn gej_point_eq_rejects_negation(context: TestContext) -> anyhow::Result<()> { - case_fuzz(GejPointEq, context, "gej_point_eq negation") - .inject(arb_ge(), |case, ge| { - let (parity, x) = compress(ge); - - case.gej(ge_to_gej(ge)).point((parity ^ 1, x)) - }) - .expect(Expect::Reject) - .run() - } - - // 9. safe_gej_normalize - #[simplex::fuzz] - fn safe_gej_normalize_roundtrip(context: TestContext) -> anyhow::Result<()> { - case_fuzz(SafeGejNormalize, context, "safe_gej_normalize_roundtrip") - .inject((arb_ge(), arb_non_zero_fe()), |case, (ge, lambda)| { - let lambda_squared = fe_mul_ref(lambda, lambda); - let lambda_cubed = fe_mul_ref(lambda_squared, lambda); - - let gej: Gej = ( - ( - fe_mul_ref(ge.0, lambda_squared), - fe_mul_ref(ge.1, lambda_cubed), - ), - lambda, - ); - - case.gej(gej).expect_ge(ge) - }) - .run() - } - - #[simplex::fuzz] - fn gej_point_eq_off_curve_is_false(context: TestContext) -> anyhow::Result<()> { - case_fuzz( - GejPointEq, - context, - "gej_point_eq off-curve compressed point", - ) - .inject(arb_ge(), |case, ge| { - case.gej(ge_to_gej(ge)).point((0, [0; 32])) - }) - .expect(Expect::Reject) - .run() - } - - #[simplex::fuzz] - fn gej_point_eq_rejects_off_curve_gej(context: TestContext) -> anyhow::Result<()> { - case_fuzz(GejPointEq, context, "gej_point_eq off-curve Jacobian point") - .inject(arb_ge(), |case, ge| { - // Obtain (x, 0, 1) point. - let gej = ge_to_gej((ge.0, [0; 32])); - - // Obtain (0, x) point with order 2 (secp256k1 has odd prime order). - let compressed_point = (0, ge.0); - - case.gej(gej).point(compressed_point) - }) - .expect(Expect::Reject) - .run() - } + cases::safe_gej_normalize(random_ge(), ONE).run(&context) } diff --git a/tests/stdlib/secp256k1/operations_fuzz.rs b/tests/stdlib/secp256k1/operations_fuzz.rs new file mode 100644 index 0000000..4996745 --- /dev/null +++ b/tests/stdlib/secp256k1/operations_fuzz.rs @@ -0,0 +1,215 @@ +use secp256k1_zkp::{PublicKey, 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 super::core::{ + Fe, Ge, ONE, SECP_N, SECP_P, U256, ZERO, add_u256, big, cases, pk_to_ge, sub_mod, to_u256, u256, +}; + +/// Mix uniform 256-bit values with exact boundaries for `modulus`. +/// +/// Simplex's guided generator supports whole-word `u256` boundaries. This custom +/// strategy includes the secp256k1 modulus and its neighbours to exercise reduction +/// of non-canonical operands. +fn arb_u256_mod(modulus: U256) -> impl Strategy { + let edges = vec![ + ZERO, + ONE, + to_u256(&(big(modulus) - 1u32)), + modulus, + add_u256(modulus, ONE), + [u8::MAX; 32], + ]; + + prop_oneof![select(edges), any::()] +} + +/// A canonical field element, `< SECP_P`. +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_public_key() -> impl Strategy { + any::<[u8; 32]>() + .prop_filter_map("valid secret key", |bytes| { + SecretKey::from_slice(&bytes).ok() + }) + .prop_map(|secret_key| PublicKey::from_secret_key(secp256k1_zkp::SECP256K1, &secret_key)) +} + +fn arb_ge() -> impl Strategy { + arb_public_key().prop_map(|pk| pk_to_ge(&pk)) +} + +/// 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| { + let mut compressed = [0x02; 33]; + compressed[1..].copy_from_slice(x); + + // Filtering only off curve points. + PublicKey::from_slice(&compressed).is_err() + }) +} + +/// `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))) +} + +/// Two values that differ modulo `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(), cases::ge_to_point); +} + +// 1. point_to_gej +#[simplex::fuzz] +fn point_to_gej_roundtrip(context: TestContext) { + accepts(&context, arb_ge(), cases::point_to_gej); +} + +// 2. fe_sub +#[simplex::fuzz] +fn fe_sub_self_is_zero(context: TestContext) { + accepts(&context, arb_u256_mod(SECP_P), |a| { + cases::fe_sub(a, a).expect_uint(ZERO) + }); +} + +#[simplex::fuzz] +fn fe_sub_matches_reference(context: TestContext) { + accepts( + &context, + (arb_u256_mod(SECP_P), arb_u256_mod(SECP_P)), + |(a, b)| cases::fe_sub(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)| cases::scalar_sub(a, b), + ); +} + +// 4. gej_sub +#[simplex::fuzz] +fn gej_sub_matches_reference(context: TestContext) { + let distinct_points = (arb_public_key(), arb_public_key()) + .prop_filter("distinct secp256k1 points", |(p, q)| p != q); + + accepts(&context, distinct_points, |(p, q)| cases::gej_sub(p, q)); +} + +#[simplex::fuzz] +fn gej_sub_self_is_infinity(context: TestContext) { + accepts(&context, arb_public_key(), |p| cases::gej_sub(p, p)); +} + +// 5. fe_eq +#[simplex::fuzz] +fn fe_eq_reflexive(context: TestContext) { + accepts(&context, arb_u256_mod(SECP_P), |a| cases::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)| { + cases::fe_eq(a, b) + }); +} + +#[simplex::fuzz] +fn fe_eq_rejects_distinct(context: TestContext) { + rejects(&context, arb_distinct_mod(SECP_P), |(a, b)| { + cases::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)| { + cases::scalar_eq(a, b) + }); +} + +#[simplex::fuzz] +fn scalar_eq_rejects_distinct(context: TestContext) { + rejects(&context, arb_distinct_mod(SECP_N), |(a, b)| { + cases::scalar_eq(a, b) + }); +} + +// 7. ge_eq +#[simplex::fuzz] +fn ge_eq_rejects_negation(context: TestContext) { + rejects(&context, arb_ge(), cases::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)| { + cases::gej_point_eq_rescaled(ge, lambda) + }); +} + +#[simplex::fuzz] +fn gej_point_eq_rejects_negation(context: TestContext) { + rejects(&context, arb_ge(), cases::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)| { + cases::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, _)| { + cases::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)| { + cases::safe_gej_normalize(ge, lambda) + }); +} From 84a9a7beaaf0ef08016d19057f3dbad6e03fc781 Mon Sep 17 00:00:00 2001 From: Illia Kripaka Date: Wed, 18 Nov 2026 12:04:18 +0200 Subject: [PATCH 4/5] introduce unit tests * fix execution vectors --- .github/workflows/tests.yml | 6 + CHANGELOG.md | 2 + tests/stdlib/common/fuzz.rs | 2 +- tests/stdlib/common/mod.rs | 1 + tests/stdlib/common/unit.rs | 82 ++++++ tests/stdlib/secp256k1/core.rs | 129 ++++----- tests/stdlib/secp256k1/operations.rs | 327 +++++++++++++++++----- tests/stdlib/secp256k1/operations_fuzz.rs | 2 +- 8 files changed, 412 insertions(+), 139 deletions(-) create mode 100644 tests/stdlib/common/unit.rs diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 5c875d1..1e15d47 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -60,6 +60,12 @@ 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' || '' }} 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/tests/stdlib/common/fuzz.rs b/tests/stdlib/common/fuzz.rs index 799464a..64b3d48 100644 --- a/tests/stdlib/common/fuzz.rs +++ b/tests/stdlib/common/fuzz.rs @@ -7,7 +7,7 @@ use simplex::fuzz::proptest::strategy::Strategy; use simplex::fuzz::{FuzzProgramTrait, FuzzProgramValues, Scenario}; use simplex::{FuzzMode, TestContext}; -pub use simplex::fuzz::Expect; +use simplex::fuzz::Expect; const DEFAULT_SPENT_INPUT: usize = 0; diff --git a/tests/stdlib/common/mod.rs b/tests/stdlib/common/mod.rs index a25bd30..9cc5a19 100644 --- a/tests/stdlib/common/mod.rs +++ b/tests/stdlib/common/mod.rs @@ -3,4 +3,5 @@ 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..289036a --- /dev/null +++ b/tests/stdlib/common/unit.rs @@ -0,0 +1,82 @@ +use simplex::program::{Program, ProgramError, ProgramTrait}; +use simplex::provider::SimplicityNetwork; +use simplex::simplicityhl::WitnessValues; +use simplex::simplicityhl::elements::{OutPoint, Script, Txid}; +use simplex::transaction::{FinalTransaction, PartialInput, PartialOutput, ProgramInput, UTXO}; + +const AMOUNT: u64 = 1_000; + +pub struct Unit { + pub program: Program, + pub witness: WitnessValues, +} + +impl Unit { + #[track_caller] + pub fn accepts(self) { + accepts(&self.program, self.witness) + } + + #[track_caller] + pub fn rejects(self) { + rejects(&self.program, self.witness) + } +} + +/// A transaction whose only input spends a UTXO locked by `program`. +/// +/// Unit programs do not look at the transaction; it only gives them an environment to run in. +pub fn spend( + program: &Program, + witness: impl Into, + 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 +} + +/// Runs `program` on `witness` without a node. +pub fn run(program: &Program, witness: impl Into) -> Result<(), ProgramError> { + let network = SimplicityNetwork::default_regtest(); + let witness = witness.into(); + + let (pst, _) = spend(program, witness.clone(), network) + .extract_pst() + .expect("the unit transaction is explicit"); + + program.execute(&pst, &witness, 0, &network).map(|_| ()) +} + +#[track_caller] +pub fn accepts(program: &Program, witness: impl Into) { + if let Err(error) = run(program, witness) { + panic!("expected the program to accept, but it failed: {error}"); + } +} + +/// Asserts that `program` fails while running on `witness`. +/// +/// Any other error means the case is malformed and the function was never reached. +#[track_caller] +pub fn rejects(program: &Program, witness: impl Into) { + match run(program, witness) { + Err(ProgramError::Pruning(_) | ProgramError::Execution(_)) => {} + Err(other) => panic!("the case failed before the program ran: {other}"), + Ok(()) => panic!("expected the program to reject, but it accepted"), + } +} diff --git a/tests/stdlib/secp256k1/core.rs b/tests/stdlib/secp256k1/core.rs index dc10f6e..e4215b1 100644 --- a/tests/stdlib/secp256k1/core.rs +++ b/tests/stdlib/secp256k1/core.rs @@ -1,10 +1,8 @@ use num_bigint::BigUint; -use rand::{RngCore, rngs::OsRng}; -use secp256k1_zkp::{PublicKey, SecretKey, rand::rngs::OsRng as SecpOsRng}; +use secp256k1_zkp::{PublicKey, SecretKey}; -use crate::common::core::{Expect, run}; use crate::common::fuzz::DispatchFuzzCase; - +use crate::common::unit::Unit; use simplicityhl_std::artifacts::tests::secp256k1::operations::OperationsProgram as Secp256k1OperationsTestProgram; use simplicityhl_std::artifacts::tests::secp256k1::operations::derived_operations::{ OperationsArguments as Secp256k1OperationsTestArguments, @@ -12,19 +10,24 @@ use simplicityhl_std::artifacts::tests::secp256k1::operations::derived_operation }; pub const ZERO: U256 = [0; 32]; -pub const ONE: U256 = u256(1); +pub const ONE: U256 = secp256k1_zkp::constants::ONE; + +/// The point at infinity (Z = 0). The contract's expected witness uses all-zero coordinates. +pub const INFINITY: Gej = ((ZERO, ZERO), ZERO); -/// A big-endian 256-bit value. +// Mirror Simplicity's Fe / Scalar / Ge / Gej / Point types. + +/// Big-endian 256-bit integer. pub type U256 = [u8; 32]; -/// A **f**ield **e**lement, arithmetic modulo **p**. +/// Field element, mod p. pub type Fe = U256; -/// A multiplier for curve points, arithmetic modulo the group order **n**. +/// Scalar, mod the group order n. pub type Scalar = U256; -/// A **G**roup **E**lement, represented as an affine curve point (x, y). +/// Affine point (x, y). pub type Ge = (Fe, Fe); -/// A **G**roup **E**lement, represented using **J**acobian coordinates ((X, Y), Z). +/// Jacobian point ((X, Y), Z), representing affine (X/Z², Y/Z³). pub type Gej = (Ge, Fe); -/// A compressed curve point (y_parity, x). +/// Compressed point (y parity, x). pub type Point = (u8, Fe); pub enum FunctionToTest { @@ -40,17 +43,8 @@ pub enum FunctionToTest { SafeGejNormalize, } -// FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F -pub const SECP_P: U256 = [ - 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 -pub const SECP_N: U256 = [ - 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, -]; +pub const SECP_P: U256 = secp256k1_zkp::constants::FIELD_SIZE; +pub const SECP_N: U256 = secp256k1_zkp::constants::CURVE_ORDER; pub const fn u256(value: u128) -> U256 { let mut out = [0; 32]; @@ -134,29 +128,18 @@ pub fn rescale((x, y): Ge, lambda: Fe) -> Gej { ((fe_mul(x, lambda_squared), fe_mul(y, lambda_cubed)), lambda) } -fn random_mod(modulus: U256) -> U256 { - let mut bytes = [0; 32]; - OsRng.fill_bytes(&mut bytes); - - to_u256(&(big(bytes) % big(modulus))) -} - -pub fn random_fe() -> Fe { - random_mod(SECP_P) -} - -pub fn random_scalar() -> Scalar { - random_mod(SECP_N) -} - -pub fn random_public_key() -> PublicKey { - let secret_key = SecretKey::new(&mut SecpOsRng); - +/// `k·G`. +/// +/// # Panics +/// If `k` is zero. +pub fn public_key(k: u128) -> PublicKey { + let secret_key = SecretKey::from_slice(&u256(k)).expect("k must be non-zero"); PublicKey::from_secret_key(secp256k1_zkp::SECP256K1, &secret_key) } -pub fn random_ge() -> Ge { - pk_to_ge(&random_public_key()) +/// `k·G` in affine coordinates. +pub fn g_times(k: u128) -> Ge { + pk_to_ge(&public_key(k)) } /// One dispatch arm of the contract, plus the witness it reads. @@ -248,16 +231,13 @@ impl Case { self } - /// Fund, spend, and expect the spend to succeed. - pub fn run(self, context: &simplex::TestContext) -> anyhow::Result<()> { - self.expecting(context, Expect::Ok) - } - - /// Fund, spend, and expect `expect`. - pub fn expecting(self, context: &simplex::TestContext, expect: Expect) -> anyhow::Result<()> { - let program = Secp256k1OperationsTestProgram::new(Case::arguments()); - - run(context, program, self.witness, expect) + pub fn unit(self) -> Unit { + Unit { + program: Secp256k1OperationsTestProgram::new(Case::arguments()) + .as_ref() + .clone(), + witness: self.witness.into(), + } } } @@ -307,8 +287,7 @@ pub mod cases { /// `gej_sub` matches the reference, the point at infinity included (`p == q`). pub fn gej_sub(p: PublicKey, q: PublicKey) -> Case { let expected = if p == q { - // The expected witness for infinity uses all-zero coordinates. - Gej::default() + INFINITY } else { let difference = p .combine(&q.negate(secp256k1_zkp::SECP256K1)) @@ -317,9 +296,12 @@ pub mod cases { ge_to_gej(pk_to_ge(&difference)) }; - case(GejSub) - .gejs(ge_to_gej(pk_to_ge(&p)), ge_to_gej(pk_to_ge(&q))) - .expect_gej(expected) + gej_sub_jacobian(ge_to_gej(pk_to_ge(&p)), ge_to_gej(pk_to_ge(&q)), expected) + } + + /// `gej_sub(p, q) == expected` for any Jacobian operands, non-unit Z and infinity included. + pub fn gej_sub_jacobian(p: Gej, q: Gej, expected: Gej) -> Case { + case(GejSub).gejs(p, q).expect_gej(expected) } /// `fe_eq(a, b)`, accepted iff `a ≡ b (mod p)`. @@ -332,16 +314,24 @@ pub mod cases { case(ScalarEq).uints(a, b) } + /// `ge_eq(a, b)`, accepted iff both coordinates are equal mod p. + pub fn ge_eq(a: Ge, b: Ge) -> Case { + case(GeEq).ges(a, b) + } + /// `ge_eq(P, -P)`: must be rejected, y differs. pub fn ge_eq_negation(ge: Ge) -> Case { - case(GeEq).ges(ge, ge_negate(ge)) + ge_eq(ge, ge_negate(ge)) + } + + /// `gej_point_eq(gej, point)`, accepted iff `gej` is on the curve and is the point `point` encodes. + pub fn gej_point_eq(gej: Gej, point: Point) -> Case { + case(GejPointEq).gej(gej).point(point) } /// `gej_point_eq` holds for any Jacobian representation `(λ²X, λ³Y, λ)` of P. pub fn gej_point_eq_rescaled(ge: Ge, lambda: Fe) -> Case { - case(GejPointEq) - .gej(rescale(ge, lambda)) - .point(compress(ge)) + gej_point_eq(rescale(ge, lambda), compress(ge)) } /// `gej_point_eq(P, compress(-P))` must be false. @@ -350,12 +340,12 @@ pub mod cases { pub fn gej_point_eq_negation(ge: Ge) -> Case { let (parity, x) = compress(ge); - case(GejPointEq).gej(ge_to_gej(ge)).point((parity ^ 1, x)) + gej_point_eq(ge_to_gej(ge), (parity ^ 1, x)) } /// `gej_point_eq(P, (0, x))` with an off-curve `x`: must be rejected. pub fn gej_point_eq_off_curve_point(ge: Ge, x: Fe) -> Case { - case(GejPointEq).gej(ge_to_gej(ge)).point((0, x)) + gej_point_eq(ge_to_gej(ge), (0, x)) } /// Compare an off-curve `(x, y, 1)` against a compressed point with the same x and parity. @@ -365,15 +355,18 @@ pub mod cases { pub fn gej_point_eq_off_curve_gej(x: Fe, y: Fe) -> Case { let off_curve = (x, y); - case(GejPointEq) - .gej(ge_to_gej(off_curve)) - .point(compress(off_curve)) + gej_point_eq(ge_to_gej(off_curve), compress(off_curve)) } - /// `safe_gej_normalize` maps any Jacobian representation of P back to P. - pub fn safe_gej_normalize(ge: Ge, lambda: Fe) -> Case { + /// `safe_gej_normalize` maps any Jacobian representation `(λ²X, λ³Y, λ)` of P back to P. + pub fn safe_gej_normalize_rescaled(ge: Ge, lambda: Fe) -> Case { case(SafeGejNormalize) .gej(rescale(ge, lambda)) .expect_ge(ge) } + + /// `safe_gej_normalize(gej) == expected`. + pub fn safe_gej_normalize(gej: Gej, expected: Ge) -> Case { + case(SafeGejNormalize).gej(gej).expect_ge(expected) + } } diff --git a/tests/stdlib/secp256k1/operations.rs b/tests/stdlib/secp256k1/operations.rs index 24cd709..df19680 100644 --- a/tests/stdlib/secp256k1/operations.rs +++ b/tests/stdlib/secp256k1/operations.rs @@ -1,101 +1,245 @@ -use crate::common::core::Expect; +use secp256k1_zkp::PublicKey; use super::core::*; +/// The curve point with `x = 1` yields the smallest value that fits in 256 bits after +/// computing `x + p` (preventing overflow so modular reduction can be tested). +fn x_one() -> Ge { + let mut compressed = [0x02; 33]; + compressed[1..].copy_from_slice(&ONE); + + pk_to_ge(&PublicKey::from_slice(&compressed).expect("x = 1 is on the curve")) +} + // 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. +#[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); - cases::ge_to_point(random_ge()).run(&context) + cases::ge_to_point(g).unit().accepts(); + cases::ge_to_point(ge_negate(g)).unit().accepts(); } // 1. point_to_gej -#[simplex::test] -fn point_to_gej_roundtrip(context: simplex::TestContext) -> anyhow::Result<()> { - cases::point_to_gej(random_ge()).run(&context) +#[test] +fn point_to_gej_roundtrip() { + let g: Ge = g_times(1); + + cases::point_to_gej(g).unit().accepts(); + cases::point_to_gej(ge_negate(g)).unit().accepts() +} + +#[test] +fn point_to_gej_rejects_invalid_x() { + // Off-curve x: the point (0, 0). + cases::point_to_gej((ZERO, ZERO)).unit().rejects(); + + // Unreduced x: the point (0, p). p ≡ 0, so this is the same off-curve x. + cases::point_to_gej((SECP_P, ZERO)).unit().rejects(); +} + +#[test] +fn point_to_gej_reduces_x() { + let (x, y): (Fe, Fe) = x_one(); + let x_scaled: U256 = add_u256(x, SECP_P); + + // decompress reads x mod p: (parity, 1 + p) decompresses to the point with x = 1. + cases::point_to_gej((x_scaled, y)) + .expect_point(compress((x, y))) + .unit() + .accepts(); } // 2. fe_sub -#[simplex::test] -fn fe_sub_self_is_zero(context: simplex::TestContext) -> anyhow::Result<()> { - let a = random_fe(); +#[test] +fn fe_sub_self_is_zero() { + let a: U256 = [0xEF; 32]; - cases::fe_sub(a, a).expect_uint(ZERO).run(&context) + cases::fe_sub(a, a).expect_uint(ZERO).unit().accepts(); } -#[simplex::test] -fn fe_sub_matches_reference(context: simplex::TestContext) -> anyhow::Result<()> { - cases::fe_sub(random_fe(), random_fe()).run(&context) +#[test] +fn fe_sub_underflow_and_unreduced() { + let a: U256 = [0xFE; 32]; + let b: U256 = [0xFF; 32]; + + cases::fe_sub(a, ZERO).unit().accepts(); + cases::fe_sub(b, ZERO).unit().accepts(); + + cases::fe_sub(ZERO, ONE).unit().accepts(); + cases::fe_sub(SECP_P, ONE).unit().accepts(); + cases::fe_sub(ONE, SECP_P).unit().accepts(); +} + +#[test] +fn fe_sub_matches_reference() { + let a: U256 = [0xFE; 32]; + let b: U256 = [0xEF; 32]; + + cases::fe_sub(a, b).unit().accepts(); + cases::fe_sub(b, a).unit().accepts(); } // 3. scalar_sub -#[simplex::test] -fn scalar_sub_matches_reference(context: simplex::TestContext) -> anyhow::Result<()> { - cases::scalar_sub(random_scalar(), random_scalar()).run(&context) +#[test] +fn scalar_sub_matches_reference() { + let a: Scalar = [0xA5; 32]; + let b: Scalar = [0x5A; 32]; + + cases::scalar_sub(a, b).unit().accepts(); + cases::scalar_sub(b, a).unit().accepts(); +} + +#[test] +fn scalar_sub_is_zero() { + let a: Scalar = [0xA5; 32]; + + cases::scalar_sub(a, a).expect_uint(ZERO).unit().accepts(); +} + +#[test] +fn scalar_sub_underflow_and_unreduced() { + let a: Scalar = [0xFF; 32]; + + cases::scalar_sub(a, ZERO).unit().accepts(); + cases::scalar_sub(ZERO, ONE).unit().accepts(); + cases::scalar_sub(SECP_N, ONE).unit().accepts(); + cases::scalar_sub(ONE, SECP_N).unit().accepts(); } // 4. gej_sub -#[simplex::test] -fn gej_sub_matches_reference(context: simplex::TestContext) -> anyhow::Result<()> { - let p = random_public_key(); - let mut q = random_public_key(); +#[test] +fn gej_sub_matches_reference() { + let p = public_key(0x01); + let q = public_key(0x10); - while q == p { - q = random_public_key(); - } + cases::gej_sub(p, q).unit().accepts(); + cases::gej_sub(q, p).unit().accepts(); +} - cases::gej_sub(p, q).run(&context) +#[test] +fn gej_sub_edge_cases() { + let p = public_key(0x01); + let g: Ge = g_times(1); + let two_g: Gej = ge_to_gej(g_times(2)); + + // P - P = inf + cases::gej_sub(p, p).unit().accepts(); + + // G - (-G) = G + G = 2G + cases::gej_sub_jacobian(ge_to_gej(g), ge_to_gej(ge_negate(g)), two_g) + .unit() + .accepts(); + + // 3G - G = 2G + cases::gej_sub_jacobian( + rescale(g_times(3), [0x4E; 32]), + rescale(g, [0x2A; 32]), + two_g, + ) + .unit() + .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 + cases::gej_sub_jacobian(g, INFINITY, g).unit().accepts(); + + // inf - G = -G + cases::gej_sub_jacobian(INFINITY, g, minus_g) + .unit() + .accepts(); + + // inf - inf = inf + cases::gej_sub_jacobian(INFINITY, INFINITY, INFINITY) + .unit() + .accepts(); } // 5. fe_eq -#[simplex::test] -fn fe_eq_reflexive(context: simplex::TestContext) -> anyhow::Result<()> { - let a = random_fe(); +#[test] +fn fe_eq_reflexive() { + let a: Fe = [0xFE; 32]; + + cases::fe_eq(a, a).unit().accepts(); +} - cases::fe_eq(a, a).run(&context) +#[test] +fn fe_eq_zero_and_p_are_equal() { + cases::fe_eq(ZERO, SECP_P).unit().accepts(); } -#[simplex::test] -fn fe_eq_zero_and_p_are_equal(context: simplex::TestContext) -> anyhow::Result<()> { - cases::fe_eq(ZERO, SECP_P).run(&context) +#[test] +fn fe_eq_rejects_distinct() { + cases::fe_eq(ZERO, ONE).unit().rejects(); + // n ≢ 0 (mod p): catches reducing by the wrong modulus. + cases::fe_eq(ZERO, SECP_N).unit().rejects(); } // 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 s = u256(5); +#[test] +fn scalar_eq_s_and_s_plus_n_are_equal() { + let s: Scalar = u256(5); + + cases::scalar_eq(s, add_u256(s, SECP_N)).unit().accepts(); +} - cases::scalar_eq(s, add_u256(s, SECP_N)).run(&context) +#[test] +fn scalar_eq_rejects_distinct() { + cases::scalar_eq(ZERO, ONE).unit().rejects(); + // p ≢ 0 (mod n): catches reducing by the wrong modulus. + cases::scalar_eq(ZERO, SECP_P).unit().rejects(); } // 7. ge_eq -#[simplex::test] -fn ge_eq_rejects_negation(context: simplex::TestContext) -> anyhow::Result<()> { - cases::ge_eq_negation(random_ge()).expecting(&context, Expect::AssertFailed) +#[test] +fn ge_eq_reflexive() { + let g: Ge = g_times(1); + let (x, y): (Fe, Fe) = x_one(); + + cases::ge_eq(g, g).unit().accepts(); + + // Coordinates are compared mod p. + cases::ge_eq((x, y), (add_u256(x, SECP_P), y)) + .unit() + .accepts(); +} + +#[test] +fn ge_eq_rejects_negation() { + let ge: Ge = g_times(1); + + cases::ge_eq_negation(ge).unit().rejects(); +} + +#[test] +fn ge_eq_rejects_different_x() { + cases::ge_eq(g_times(1), g_times(2)).unit().rejects(); } // 8. gej_point_eq -#[simplex::test] -fn gej_point_eq_rescaled(context: simplex::TestContext) -> anyhow::Result<()> { +#[test] +fn gej_point_eq_rescaled() { // (λ²X, λ³Y, λZ) is the same affine point as (X, Y, 1). - let mut lambda = random_fe(); + let lambda: Fe = [0x4E; 32]; + let ge: Ge = g_times(1); - while lambda == ZERO { - lambda = random_fe(); - } - - cases::gej_point_eq_rescaled(random_ge(), lambda).run(&context) + cases::gej_point_eq_rescaled(ge, lambda).unit().accepts(); } -#[simplex::test] -fn gej_point_eq_rejects_negation(context: simplex::TestContext) -> anyhow::Result<()> { +#[test] +fn gej_point_eq_rejects_negation() { + let ge: Ge = g_times(1); + // Property under test: gej_point_eq(P, -P) == false. // // Construction: - // ge = random on-curve point P = (x, y) + // ge = on-curve point P = (x, y), here G // (parity, x) = compressed form of +P // ge_to_gej(ge) = Gej encoding of +P // (parity ^ 1, x) = compressed form of -P @@ -103,31 +247,76 @@ fn gej_point_eq_rejects_negation(context: simplex::TestContext) -> anyhow::Resul // 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. - - cases::gej_point_eq_negation(random_ge()).expecting(&context, Expect::AssertFailed) + cases::gej_point_eq_negation(ge).unit().rejects() } -#[simplex::test] -fn gej_point_eq_off_curve_is_false(context: simplex::TestContext) -> anyhow::Result<()> { +#[test] +fn gej_point_eq_off_curve_is_false() { + let ge: Ge = g_times(1); + // x = 0 is off-curve. - cases::gej_point_eq_off_curve_point(random_ge(), ZERO).expecting(&context, Expect::AssertFailed) + cases::gej_point_eq_off_curve_point(ge, ZERO) + .unit() + .rejects() } -#[simplex::test] -fn gej_point_eq_rejects_off_curve_gej(context: simplex::TestContext) -> anyhow::Result<()> { +#[test] +fn gej_point_eq_rejects_off_curve_gej() { + let ge: Ge = g_times(1); + // (x, 1, 1) shares x with P but is off-curve. // The compressed point shares x and odd parity, isolating the on-curve check. - let neg_one = sub_mod(ZERO, ONE, SECP_P); - let mut ge = random_ge(); - while ge.1 == ONE || ge.1 == neg_one { - ge = random_ge(); - } + cases::gej_point_eq_off_curve_gej(ge.0, ONE) + .unit() + .rejects() +} + +#[test] +fn gej_point_eq_rejects_infinity() { + let g_point: Point = compress(g_times(1)); + + cases::gej_point_eq(INFINITY, g_point).unit().rejects(); +} + +#[test] +fn gej_point_eq_rejects_other_point() { + let a: Gej = ge_to_gej(g_times(1)); + let b: Point = compress(g_times(2)); - cases::gej_point_eq_off_curve_gej(ge.0, ONE).expecting(&context, Expect::AssertFailed) + cases::gej_point_eq(a, b).unit().rejects(); +} + +#[test] +fn gej_point_eq_reduces_x() { + let (x, y) = x_one(); + let x_scaled = add_u256(x, SECP_P); + let (parity, _) = compress((x, y)); + + // Reduced Gej, unreduced point. + cases::gej_point_eq(ge_to_gej((x, y)), (parity, x_scaled)) + .unit() + .accepts(); + + // Unreduced Gej, reduced point. + cases::gej_point_eq(ge_to_gej((x_scaled, y)), (parity, x)) + .unit() + .accepts(); } // 9. safe_gej_normalize -#[simplex::test] -fn safe_gej_normalize_roundtrip(context: simplex::TestContext) -> anyhow::Result<()> { - cases::safe_gej_normalize(random_ge(), ONE).run(&context) +#[test] +fn safe_gej_normalize_roundtrip() { + let ge: Ge = g_times(1); + + cases::safe_gej_normalize_rescaled(ge, ONE).unit().accepts(); + cases::safe_gej_normalize_rescaled(ge, [0x4E; 32]) + .unit() + .accepts(); +} + +#[test] +fn safe_gej_normalize_rejects_infinity() { + cases::safe_gej_normalize(INFINITY, Ge::default()) + .unit() + .rejects(); } diff --git a/tests/stdlib/secp256k1/operations_fuzz.rs b/tests/stdlib/secp256k1/operations_fuzz.rs index 4996745..d57b36d 100644 --- a/tests/stdlib/secp256k1/operations_fuzz.rs +++ b/tests/stdlib/secp256k1/operations_fuzz.rs @@ -210,6 +210,6 @@ fn gej_point_eq_rejects_off_curve_gej(context: TestContext) { #[simplex::fuzz] fn safe_gej_normalize_roundtrip(context: TestContext) { accepts(&context, (arb_ge(), arb_non_zero_fe()), |(ge, lambda)| { - cases::safe_gej_normalize(ge, lambda) + cases::safe_gej_normalize_rescaled(ge, lambda) }); } From 66cda77f8a3d91e19b606e11ff1d8cf693ad6e67 Mon Sep 17 00:00:00 2001 From: Oleh Komendant Date: Fri, 20 Nov 2026 13:34:18 +0200 Subject: [PATCH 5/5] Update tests structure for the secp256 tests --- .github/workflows/tests.yml | 9 + Cargo.lock | 21 - Cargo.toml | 2 - tests/stdlib/common/case.rs | 40 ++ tests/stdlib/common/core.rs | 2 +- tests/stdlib/common/fuzz.rs | 30 +- tests/stdlib/common/mod.rs | 1 + tests/stdlib/common/unit.rs | 79 ++-- tests/stdlib/secp256k1/core.rs | 372 ------------------ tests/stdlib/secp256k1/math.rs | 136 +++++++ tests/stdlib/secp256k1/mod.rs | 5 +- tests/stdlib/secp256k1/operations.rs | 322 --------------- tests/stdlib/secp256k1/operations/case.rs | 229 +++++++++++ .../fuzz.rs} | 79 ++-- tests/stdlib/secp256k1/operations/mod.rs | 3 + tests/stdlib/secp256k1/operations/unit.rs | 262 ++++++++++++ 16 files changed, 754 insertions(+), 838 deletions(-) create mode 100644 tests/stdlib/common/case.rs delete mode 100644 tests/stdlib/secp256k1/core.rs create mode 100644 tests/stdlib/secp256k1/math.rs delete mode 100644 tests/stdlib/secp256k1/operations.rs create mode 100644 tests/stdlib/secp256k1/operations/case.rs rename tests/stdlib/secp256k1/{operations_fuzz.rs => operations/fuzz.rs} (68%) create mode 100644 tests/stdlib/secp256k1/operations/mod.rs create mode 100644 tests/stdlib/secp256k1/operations/unit.rs diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 1e15d47..31d4024 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -72,6 +72,15 @@ jobs: 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/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/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 index 64b3d48..3c60791 100644 --- a/tests/stdlib/common/fuzz.rs +++ b/tests/stdlib/common/fuzz.rs @@ -1,63 +1,46 @@ use std::fmt::Debug; -use simplex::program::ProgramSchema; use simplex::simplicityhl::Arguments; use simplex::fuzz::proptest::strategy::Strategy; -use simplex::fuzz::{FuzzProgramTrait, FuzzProgramValues, Scenario}; +use simplex::fuzz::{FuzzProgramValues, Scenario}; use simplex::{FuzzMode, TestContext}; use simplex::fuzz::Expect; -const DEFAULT_SPENT_INPUT: usize = 0; - -/// One call into a dispatch test contract (`function_index` + operands + expected values). -/// -/// Implemented once per test module for its `Case` builder, so fuzz tests only -/// describe how generated inputs become a case. -pub trait DispatchFuzzCase: 'static { - type Program: FuzzProgramTrait; - - /// Contract name used in fuzz scenarios and diagnostics. - const PROGRAM_NAME: &'static str; +use crate::common::case::DispatchCase; - fn arguments() -> ::Arguments; - - fn into_witness(self) -> ::Witness; -} +const DEFAULT_SPENT_INPUT: usize = 0; -/// Fuzz `inputs` through `build`: every generated case must be accepted. pub fn accepts( context: &TestContext, inputs: impl Strategy + 'static, build: impl Fn(T) -> C + 'static, ) where - C: DispatchFuzzCase, + C: DispatchCase, T: Debug + 'static, { check(context, inputs, build, Expect::Accept); } -/// Fuzz `inputs` through `build`: every generated case must be rejected. pub fn rejects( context: &TestContext, inputs: impl Strategy + 'static, build: impl Fn(T) -> C + 'static, ) where - C: DispatchFuzzCase, + C: DispatchCase, T: Debug + 'static, { check(context, inputs, build, Expect::Reject); } -/// Fuzz `inputs` through `build` and expect `expect` for every generated case. pub fn check( context: &TestContext, inputs: impl Strategy + 'static, build: impl Fn(T) -> C + 'static, expect: Expect, ) where - C: DispatchFuzzCase, + C: DispatchCase, T: Debug + 'static, { let arguments: Arguments = C::arguments().into(); @@ -74,7 +57,6 @@ pub fn check( run_scenario(context, scenario, expect); } -/// Run a hand-built scenario, for tests that need more than one program or custom bindings. pub fn run_scenario(context: &TestContext, scenario: Scenario, expect: Expect) { let engine = context.engine(scenario).spec(move |_| expect); diff --git a/tests/stdlib/common/mod.rs b/tests/stdlib/common/mod.rs index 9cc5a19..f1eaf86 100644 --- a/tests/stdlib/common/mod.rs +++ b/tests/stdlib/common/mod.rs @@ -1,3 +1,4 @@ +pub mod case; pub mod core; pub mod fuzz; pub mod helper; diff --git a/tests/stdlib/common/unit.rs b/tests/stdlib/common/unit.rs index 289036a..a87a6fe 100644 --- a/tests/stdlib/common/unit.rs +++ b/tests/stdlib/common/unit.rs @@ -2,33 +2,51 @@ 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 struct Unit { - pub program: Program, - pub witness: WitnessValues, +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(|_| ()) } -impl Unit { - #[track_caller] - pub fn accepts(self) { - accepts(&self.program, self.witness) +/// 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), + }; - #[track_caller] - pub fn rejects(self) { - rejects(&self.program, self.witness) + match execution { + ExecutionError::JetFailed(_) => Ok(Expect::AssertFailed), + ExecutionError::ReachedPrunedBranch(_) => Ok(Expect::PrunedBranch), + other => Err(ProgramError::Execution(other)), } } -/// A transaction whose only input spends a UTXO locked by `program`. -/// -/// Unit programs do not look at the transaction; it only gives them an environment to run in. -pub fn spend( +fn unit_transaction( program: &Program, - witness: impl Into, + witness: WitnessValues, network: SimplicityNetwork, ) -> FinalTransaction { let asset = network.policy_asset(); @@ -49,34 +67,3 @@ pub fn spend( ft } - -/// Runs `program` on `witness` without a node. -pub fn run(program: &Program, witness: impl Into) -> Result<(), ProgramError> { - let network = SimplicityNetwork::default_regtest(); - let witness = witness.into(); - - let (pst, _) = spend(program, witness.clone(), network) - .extract_pst() - .expect("the unit transaction is explicit"); - - program.execute(&pst, &witness, 0, &network).map(|_| ()) -} - -#[track_caller] -pub fn accepts(program: &Program, witness: impl Into) { - if let Err(error) = run(program, witness) { - panic!("expected the program to accept, but it failed: {error}"); - } -} - -/// Asserts that `program` fails while running on `witness`. -/// -/// Any other error means the case is malformed and the function was never reached. -#[track_caller] -pub fn rejects(program: &Program, witness: impl Into) { - match run(program, witness) { - Err(ProgramError::Pruning(_) | ProgramError::Execution(_)) => {} - Err(other) => panic!("the case failed before the program ran: {other}"), - Ok(()) => panic!("expected the program to reject, but it accepted"), - } -} diff --git a/tests/stdlib/secp256k1/core.rs b/tests/stdlib/secp256k1/core.rs deleted file mode 100644 index e4215b1..0000000 --- a/tests/stdlib/secp256k1/core.rs +++ /dev/null @@ -1,372 +0,0 @@ -use num_bigint::BigUint; -use secp256k1_zkp::{PublicKey, SecretKey}; - -use crate::common::fuzz::DispatchFuzzCase; -use crate::common::unit::Unit; -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, -}; - -pub const ZERO: U256 = [0; 32]; -pub const ONE: U256 = secp256k1_zkp::constants::ONE; - -/// The point at infinity (Z = 0). The contract's expected witness uses all-zero coordinates. -pub const INFINITY: Gej = ((ZERO, ZERO), ZERO); - -// Mirror Simplicity's Fe / Scalar / Ge / Gej / Point types. - -/// 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 enum FunctionToTest { - GeToPoint, - PointToGej, - FeSub, - ScalarSub, - GejSub, - FeEq, - ScalarEq, - GeEq, - GejPointEq, - SafeGejNormalize, -} - -pub const SECP_P: U256 = secp256k1_zkp::constants::FIELD_SIZE; -pub const SECP_N: U256 = secp256k1_zkp::constants::CURVE_ORDER; - -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 -} - -pub fn big(value: U256) -> BigUint { - BigUint::from_bytes_be(&value) -} - -/// # Panics -/// If `value` does not fit in 256 bits. -pub fn to_u256(value: &BigUint) -> U256 { - let bytes = value.to_bytes_be(); - assert!(bytes.len() <= 32, "{value:#x} does not fit in 256 bits"); - - let mut out = [0; 32]; - out[32 - bytes.len()..].copy_from_slice(&bytes); - out -} - -/// `a + b` as plain integers. -/// -/// # Panics -/// On overflow past 256 bits. -pub fn add_u256(a: U256, b: U256) -> U256 { - to_u256(&(big(a) + big(b))) -} - -/// `a - b (mod modulus)`, canonical. Operands may be non-canonical. -pub fn sub_mod(a: U256, b: U256, modulus: U256) -> U256 { - let m = big(modulus); - - let a = big(a) % &m + &m; - let b = big(b) % &m; - - to_u256(&((a - b) % &m)) -} - -pub fn fe_mul(a: Fe, b: Fe) -> Fe { - to_u256(&(big(a) * big(b) % big(SECP_P))) -} - -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_gej(ge: Ge) -> Gej { - (ge, ONE) -} - -pub fn ge_negate((x, y): Ge) -> Ge { - (x, sub_mod(ZERO, y, SECP_P)) -} - -pub fn compress((x, y): Ge) -> Point { - ( - y[31] & 1, // 0 (even y) or 1 (odd y) - x, - ) -} - -/// `(λ²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) -} - -/// `k·G`. -/// -/// # Panics -/// If `k` is zero. -pub fn public_key(k: u128) -> PublicKey { - let secret_key = SecretKey::from_slice(&u256(k)).expect("k must be non-zero"); - PublicKey::from_secret_key(secp256k1_zkp::SECP256K1, &secret_key) -} - -/// `k·G` in affine coordinates. -pub fn g_times(k: u128) -> Ge { - pk_to_ge(&public_key(k)) -} - -/// One dispatch arm of the contract, plus the witness it reads. -#[derive(Clone, Debug)] -pub struct Case { - witness: Secp256k1OperationsTestWitness, -} - -pub fn case(function: FunctionToTest) -> Case { - Case { - 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(), - }, - } -} - -impl Case { - /// The two field or scalar operands, `first_uint` and `second_uint`. - pub fn uints(mut self, first_uint: U256, second_uint: U256) -> Self { - self.witness.first_uint = first_uint; - self.witness.second_uint = second_uint; - self - } - - /// Only `first_ge`. - pub fn ge(mut self, first_ge: Ge) -> Self { - self.witness.first_ge = first_ge; - self - } - - /// The two affine points, `first_ge` and `second_ge`. - pub fn ges(mut self, first_ge: Ge, second_ge: Ge) -> Self { - self.witness.first_ge = first_ge; - self.witness.second_ge = second_ge; - self - } - - /// Only `first_gej`. - pub fn gej(mut self, first_gej: Gej) -> Self { - self.witness.first_gej = first_gej; - self - } - - /// The two Jacobian points, `first_gej` and `second_gej`. - pub fn gejs(mut self, first_gej: Gej, second_gej: Gej) -> Self { - self.witness.first_gej = first_gej; - self.witness.second_gej = second_gej; - self - } - - /// `first_point`: a compressed point, parity byte and x coordinate. - pub fn point(mut self, first_point: Point) -> Self { - self.witness.first_point = first_point; - self - } - - /// `expected_uint`: the field or scalar the arm should produce. - pub fn expect_uint(mut self, expected_uint: U256) -> Self { - self.witness.expected_uint = expected_uint; - self - } - - /// `expected_ge`: the affine point the arm should produce. - pub fn expect_ge(mut self, expected_ge: Ge) -> Self { - self.witness.expected_ge = expected_ge; - self - } - - /// `expected_gej`: the Jacobian point the arm should produce. - pub fn expect_gej(mut self, expected_gej: Gej) -> Self { - self.witness.expected_gej = expected_gej; - self - } - - /// `expected_point`: the compressed point the arm should produce. - pub fn expect_point(mut self, expected_point: Point) -> Self { - self.witness.expected_point = expected_point; - self - } - - pub fn unit(self) -> Unit { - Unit { - program: Secp256k1OperationsTestProgram::new(Case::arguments()) - .as_ref() - .clone(), - witness: self.witness.into(), - } - } -} - -impl DispatchFuzzCase for Case { - type Program = Secp256k1OperationsTestProgram; - - const PROGRAM_NAME: &'static str = "secp256k1::operations"; - - fn arguments() -> Secp256k1OperationsTestArguments { - Secp256k1OperationsTestArguments {} - } - - fn into_witness(self) -> Secp256k1OperationsTestWitness { - self.witness - } -} - -pub mod cases { - use super::*; - - use FunctionToTest::*; - - /// `ge_to_point` keeps x and takes the parity of y. - pub fn ge_to_point(ge: Ge) -> Case { - case(GeToPoint).ge(ge).expect_point(compress(ge)) - } - - /// `point_to_gej` decompresses to the same point. - pub fn point_to_gej(ge: Ge) -> Case { - let point = compress(ge); - - case(PointToGej).point(point).expect_point(point) - } - - /// `fe_sub` matches the reference, for any (also non-canonical) operands. - pub fn fe_sub(a: Fe, b: Fe) -> Case { - case(FeSub).uints(a, b).expect_uint(sub_mod(a, b, SECP_P)) - } - - /// `scalar_sub` matches the reference, for any (also non-canonical) operands. - pub fn scalar_sub(a: Scalar, b: Scalar) -> Case { - case(ScalarSub) - .uints(a, b) - .expect_uint(sub_mod(a, b, SECP_N)) - } - - /// `gej_sub` matches the reference, the point at infinity included (`p == q`). - pub fn gej_sub(p: PublicKey, q: PublicKey) -> Case { - let expected = if p == q { - INFINITY - } else { - let difference = p - .combine(&q.negate(secp256k1_zkp::SECP256K1)) - .expect("p - q non-infinity"); - - ge_to_gej(pk_to_ge(&difference)) - }; - - gej_sub_jacobian(ge_to_gej(pk_to_ge(&p)), ge_to_gej(pk_to_ge(&q)), expected) - } - - /// `gej_sub(p, q) == expected` for any Jacobian operands, non-unit Z and infinity included. - pub fn gej_sub_jacobian(p: Gej, q: Gej, expected: Gej) -> Case { - case(GejSub).gejs(p, q).expect_gej(expected) - } - - /// `fe_eq(a, b)`, accepted iff `a ≡ b (mod p)`. - pub fn fe_eq(a: Fe, b: Fe) -> Case { - case(FeEq).uints(a, b) - } - - /// `scalar_eq(a, b)`, accepted iff `a ≡ b (mod n)`. - pub fn scalar_eq(a: Scalar, b: Scalar) -> Case { - case(ScalarEq).uints(a, b) - } - - /// `ge_eq(a, b)`, accepted iff both coordinates are equal mod p. - pub fn ge_eq(a: Ge, b: Ge) -> Case { - case(GeEq).ges(a, b) - } - - /// `ge_eq(P, -P)`: must be rejected, y differs. - pub fn ge_eq_negation(ge: Ge) -> Case { - ge_eq(ge, ge_negate(ge)) - } - - /// `gej_point_eq(gej, point)`, accepted iff `gej` is on the curve and is the point `point` encodes. - pub fn gej_point_eq(gej: Gej, point: Point) -> Case { - case(GejPointEq).gej(gej).point(point) - } - - /// `gej_point_eq` holds for any Jacobian representation `(λ²X, λ³Y, λ)` of P. - pub fn gej_point_eq_rescaled(ge: Ge, lambda: Fe) -> Case { - gej_point_eq(rescale(ge, lambda), compress(ge)) - } - - /// `gej_point_eq(P, compress(-P))` must be false. - /// Flipping the parity bit keeps `x` and selects `(x, -y)`, the negation of `P`. - /// The contract asserts equality, so this witness must be rejected. - pub fn gej_point_eq_negation(ge: Ge) -> Case { - let (parity, x) = compress(ge); - - gej_point_eq(ge_to_gej(ge), (parity ^ 1, x)) - } - - /// `gej_point_eq(P, (0, x))` with an off-curve `x`: must be rejected. - pub fn gej_point_eq_off_curve_point(ge: Ge, x: Fe) -> Case { - gej_point_eq(ge_to_gej(ge), (0, x)) - } - - /// Compare an off-curve `(x, y, 1)` against a compressed point with the same x and parity. - /// - /// The caller supplies an x from a curve point and a y off the curve at that x. - /// Matching x and parity isolates the on-curve check. - pub 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)) - } - - /// `safe_gej_normalize` maps any Jacobian representation `(λ²X, λ³Y, λ)` of P back to P. - pub fn safe_gej_normalize_rescaled(ge: Ge, lambda: Fe) -> Case { - case(SafeGejNormalize) - .gej(rescale(ge, lambda)) - .expect_ge(ge) - } - - /// `safe_gej_normalize(gej) == expected`. - pub fn safe_gej_normalize(gej: Gej, expected: Ge) -> Case { - case(SafeGejNormalize).gej(gej).expect_ge(expected) - } -} 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 418f35e..b9fcd31 100644 --- a/tests/stdlib/secp256k1/mod.rs +++ b/tests/stdlib/secp256k1/mod.rs @@ -1,3 +1,2 @@ -pub(crate) mod core; -pub(crate) mod operations; -mod operations_fuzz; +mod math; +mod operations; diff --git a/tests/stdlib/secp256k1/operations.rs b/tests/stdlib/secp256k1/operations.rs deleted file mode 100644 index df19680..0000000 --- a/tests/stdlib/secp256k1/operations.rs +++ /dev/null @@ -1,322 +0,0 @@ -use secp256k1_zkp::PublicKey; - -use super::core::*; - -/// The curve point with `x = 1` yields the smallest value that fits in 256 bits after -/// computing `x + p` (preventing overflow so modular reduction can be tested). -fn x_one() -> Ge { - let mut compressed = [0x02; 33]; - compressed[1..].copy_from_slice(&ONE); - - pk_to_ge(&PublicKey::from_slice(&compressed).expect("x = 1 is on the curve")) -} - -// 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); - - cases::ge_to_point(g).unit().accepts(); - cases::ge_to_point(ge_negate(g)).unit().accepts(); -} - -// 1. point_to_gej -#[test] -fn point_to_gej_roundtrip() { - let g: Ge = g_times(1); - - cases::point_to_gej(g).unit().accepts(); - cases::point_to_gej(ge_negate(g)).unit().accepts() -} - -#[test] -fn point_to_gej_rejects_invalid_x() { - // Off-curve x: the point (0, 0). - cases::point_to_gej((ZERO, ZERO)).unit().rejects(); - - // Unreduced x: the point (0, p). p ≡ 0, so this is the same off-curve x. - cases::point_to_gej((SECP_P, ZERO)).unit().rejects(); -} - -#[test] -fn point_to_gej_reduces_x() { - let (x, y): (Fe, Fe) = x_one(); - let x_scaled: U256 = add_u256(x, SECP_P); - - // decompress reads x mod p: (parity, 1 + p) decompresses to the point with x = 1. - cases::point_to_gej((x_scaled, y)) - .expect_point(compress((x, y))) - .unit() - .accepts(); -} - -// 2. fe_sub -#[test] -fn fe_sub_self_is_zero() { - let a: U256 = [0xEF; 32]; - - cases::fe_sub(a, a).expect_uint(ZERO).unit().accepts(); -} - -#[test] -fn fe_sub_underflow_and_unreduced() { - let a: U256 = [0xFE; 32]; - let b: U256 = [0xFF; 32]; - - cases::fe_sub(a, ZERO).unit().accepts(); - cases::fe_sub(b, ZERO).unit().accepts(); - - cases::fe_sub(ZERO, ONE).unit().accepts(); - cases::fe_sub(SECP_P, ONE).unit().accepts(); - cases::fe_sub(ONE, SECP_P).unit().accepts(); -} - -#[test] -fn fe_sub_matches_reference() { - let a: U256 = [0xFE; 32]; - let b: U256 = [0xEF; 32]; - - cases::fe_sub(a, b).unit().accepts(); - cases::fe_sub(b, a).unit().accepts(); -} - -// 3. scalar_sub -#[test] -fn scalar_sub_matches_reference() { - let a: Scalar = [0xA5; 32]; - let b: Scalar = [0x5A; 32]; - - cases::scalar_sub(a, b).unit().accepts(); - cases::scalar_sub(b, a).unit().accepts(); -} - -#[test] -fn scalar_sub_is_zero() { - let a: Scalar = [0xA5; 32]; - - cases::scalar_sub(a, a).expect_uint(ZERO).unit().accepts(); -} - -#[test] -fn scalar_sub_underflow_and_unreduced() { - let a: Scalar = [0xFF; 32]; - - cases::scalar_sub(a, ZERO).unit().accepts(); - cases::scalar_sub(ZERO, ONE).unit().accepts(); - cases::scalar_sub(SECP_N, ONE).unit().accepts(); - cases::scalar_sub(ONE, SECP_N).unit().accepts(); -} - -// 4. gej_sub -#[test] -fn gej_sub_matches_reference() { - let p = public_key(0x01); - let q = public_key(0x10); - - cases::gej_sub(p, q).unit().accepts(); - cases::gej_sub(q, p).unit().accepts(); -} - -#[test] -fn gej_sub_edge_cases() { - let p = public_key(0x01); - let g: Ge = g_times(1); - let two_g: Gej = ge_to_gej(g_times(2)); - - // P - P = inf - cases::gej_sub(p, p).unit().accepts(); - - // G - (-G) = G + G = 2G - cases::gej_sub_jacobian(ge_to_gej(g), ge_to_gej(ge_negate(g)), two_g) - .unit() - .accepts(); - - // 3G - G = 2G - cases::gej_sub_jacobian( - rescale(g_times(3), [0x4E; 32]), - rescale(g, [0x2A; 32]), - two_g, - ) - .unit() - .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 - cases::gej_sub_jacobian(g, INFINITY, g).unit().accepts(); - - // inf - G = -G - cases::gej_sub_jacobian(INFINITY, g, minus_g) - .unit() - .accepts(); - - // inf - inf = inf - cases::gej_sub_jacobian(INFINITY, INFINITY, INFINITY) - .unit() - .accepts(); -} - -// 5. fe_eq -#[test] -fn fe_eq_reflexive() { - let a: Fe = [0xFE; 32]; - - cases::fe_eq(a, a).unit().accepts(); -} - -#[test] -fn fe_eq_zero_and_p_are_equal() { - cases::fe_eq(ZERO, SECP_P).unit().accepts(); -} - -#[test] -fn fe_eq_rejects_distinct() { - cases::fe_eq(ZERO, ONE).unit().rejects(); - // n ≢ 0 (mod p): catches reducing by the wrong modulus. - cases::fe_eq(ZERO, SECP_N).unit().rejects(); -} - -// 6. scalar_eq -#[test] -fn scalar_eq_s_and_s_plus_n_are_equal() { - let s: Scalar = u256(5); - - cases::scalar_eq(s, add_u256(s, SECP_N)).unit().accepts(); -} - -#[test] -fn scalar_eq_rejects_distinct() { - cases::scalar_eq(ZERO, ONE).unit().rejects(); - // p ≢ 0 (mod n): catches reducing by the wrong modulus. - cases::scalar_eq(ZERO, SECP_P).unit().rejects(); -} - -// 7. ge_eq -#[test] -fn ge_eq_reflexive() { - let g: Ge = g_times(1); - let (x, y): (Fe, Fe) = x_one(); - - cases::ge_eq(g, g).unit().accepts(); - - // Coordinates are compared mod p. - cases::ge_eq((x, y), (add_u256(x, SECP_P), y)) - .unit() - .accepts(); -} - -#[test] -fn ge_eq_rejects_negation() { - let ge: Ge = g_times(1); - - cases::ge_eq_negation(ge).unit().rejects(); -} - -#[test] -fn ge_eq_rejects_different_x() { - cases::ge_eq(g_times(1), g_times(2)).unit().rejects(); -} - -// 8. gej_point_eq -#[test] -fn gej_point_eq_rescaled() { - // (λ²X, λ³Y, λZ) is the same affine point as (X, Y, 1). - let lambda: Fe = [0x4E; 32]; - let ge: Ge = g_times(1); - - cases::gej_point_eq_rescaled(ge, lambda).unit().accepts(); -} - -#[test] -fn gej_point_eq_rejects_negation() { - let ge: Ge = g_times(1); - - // Property under test: gej_point_eq(P, -P) == false. - // - // Construction: - // ge = on-curve point P = (x, y), here G - // (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. - cases::gej_point_eq_negation(ge).unit().rejects() -} - -#[test] -fn gej_point_eq_off_curve_is_false() { - let ge: Ge = g_times(1); - - // x = 0 is off-curve. - cases::gej_point_eq_off_curve_point(ge, ZERO) - .unit() - .rejects() -} - -#[test] -fn gej_point_eq_rejects_off_curve_gej() { - let ge: Ge = g_times(1); - - // (x, 1, 1) shares x with P but is off-curve. - // The compressed point shares x and odd parity, isolating the on-curve check. - cases::gej_point_eq_off_curve_gej(ge.0, ONE) - .unit() - .rejects() -} - -#[test] -fn gej_point_eq_rejects_infinity() { - let g_point: Point = compress(g_times(1)); - - cases::gej_point_eq(INFINITY, g_point).unit().rejects(); -} - -#[test] -fn gej_point_eq_rejects_other_point() { - let a: Gej = ge_to_gej(g_times(1)); - let b: Point = compress(g_times(2)); - - cases::gej_point_eq(a, b).unit().rejects(); -} - -#[test] -fn gej_point_eq_reduces_x() { - let (x, y) = x_one(); - let x_scaled = add_u256(x, SECP_P); - let (parity, _) = compress((x, y)); - - // Reduced Gej, unreduced point. - cases::gej_point_eq(ge_to_gej((x, y)), (parity, x_scaled)) - .unit() - .accepts(); - - // Unreduced Gej, reduced point. - cases::gej_point_eq(ge_to_gej((x_scaled, y)), (parity, x)) - .unit() - .accepts(); -} - -// 9. safe_gej_normalize -#[test] -fn safe_gej_normalize_roundtrip() { - let ge: Ge = g_times(1); - - cases::safe_gej_normalize_rescaled(ge, ONE).unit().accepts(); - cases::safe_gej_normalize_rescaled(ge, [0x4E; 32]) - .unit() - .accepts(); -} - -#[test] -fn safe_gej_normalize_rejects_infinity() { - cases::safe_gej_normalize(INFINITY, Ge::default()) - .unit() - .rejects(); -} 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 similarity index 68% rename from tests/stdlib/secp256k1/operations_fuzz.rs rename to tests/stdlib/secp256k1/operations/fuzz.rs index d57b36d..167ffbb 100644 --- a/tests/stdlib/secp256k1/operations_fuzz.rs +++ b/tests/stdlib/secp256k1/operations/fuzz.rs @@ -1,4 +1,4 @@ -use secp256k1_zkp::{PublicKey, SecretKey}; +use secp256k1_zkp::{PublicKey, SECP256K1, SecretKey}; use simplex::fuzz::proptest::prelude::{Just, any}; use simplex::fuzz::proptest::prop_oneof; @@ -7,21 +7,19 @@ use simplex::fuzz::proptest::strategy::Strategy; use simplex::{FuzzMode, TestContext}; use crate::common::fuzz::{accepts, rejects}; - -use super::core::{ - Fe, Ge, ONE, SECP_N, SECP_P, U256, ZERO, add_u256, big, cases, pk_to_ge, sub_mod, to_u256, u256, +use crate::secp256k1::math::{ + Fe, Ge, ONE, SECP_N, SECP_P, U256, ZERO, add_u256, decompress, pk_to_ge, sub_mod, sub_u256, + u256, }; -/// Mix uniform 256-bit values with exact boundaries for `modulus`. -/// -/// Simplex's guided generator supports whole-word `u256` boundaries. This custom -/// strategy includes the secp256k1 modulus and its neighbours to exercise reduction -/// of non-canonical operands. +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, - to_u256(&(big(modulus) - 1u32)), + sub_u256(modulus, ONE), modulus, add_u256(modulus, ONE), [u8::MAX; 32], @@ -30,7 +28,6 @@ fn arb_u256_mod(modulus: U256) -> impl Strategy { prop_oneof![select(edges), any::()] } -/// A canonical field element, `< SECP_P`. fn arb_fe() -> impl Strategy { arb_u256_mod(SECP_P).prop_filter("canonical field element", |value| *value < SECP_P) } @@ -39,27 +36,17 @@ fn arb_non_zero_fe() -> impl Strategy { arb_fe().prop_filter("non-zero field element", |value| *value != ZERO) } -fn arb_public_key() -> impl Strategy { +fn arb_ge() -> impl Strategy { any::<[u8; 32]>() .prop_filter_map("valid secret key", |bytes| { SecretKey::from_slice(&bytes).ok() }) - .prop_map(|secret_key| PublicKey::from_secret_key(secp256k1_zkp::SECP256K1, &secret_key)) -} - -fn arb_ge() -> impl Strategy { - arb_public_key().prop_map(|pk| pk_to_ge(&pk)) + .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| { - let mut compressed = [0x02; 33]; - compressed[1..].copy_from_slice(x); - - // Filtering only off curve points. - PublicKey::from_slice(&compressed).is_err() - }) + 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. @@ -70,7 +57,6 @@ fn arb_shifted_pair( x.prop_map(move |x| (x, add_u256(x, modulus))) } -/// Two values that differ modulo `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 @@ -80,21 +66,19 @@ fn arb_distinct_mod(modulus: U256) -> impl Strategy { // 0. ge_to_point #[simplex::fuzz] fn ge_to_point_matches_parity(context: TestContext) { - accepts(&context, arb_ge(), cases::ge_to_point); + 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(), cases::point_to_gej); + 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| { - cases::fe_sub(a, a).expect_uint(ZERO) - }); + accepts(&context, arb_u256_mod(SECP_P), |a| case::fe_sub(a, a, ZERO)); } #[simplex::fuzz] @@ -102,7 +86,7 @@ fn fe_sub_matches_reference(context: TestContext) { accepts( &context, (arb_u256_mod(SECP_P), arb_u256_mod(SECP_P)), - |(a, b)| cases::fe_sub(a, b), + |(a, b)| case::fe_sub_reference(a, b), ); } @@ -112,28 +96,29 @@ fn scalar_sub_matches_reference(context: TestContext) { accepts( &context, (arb_u256_mod(SECP_N), arb_u256_mod(SECP_N)), - |(a, b)| cases::scalar_sub(a, b), + |(a, b)| case::scalar_sub_reference(a, b), ); } // 4. gej_sub #[simplex::fuzz] fn gej_sub_matches_reference(context: TestContext) { - let distinct_points = (arb_public_key(), arb_public_key()) - .prop_filter("distinct secp256k1 points", |(p, q)| p != q); + let distinct_points = (arb_ge(), arb_ge()).prop_filter("distinct points", |(p, q)| p != q); - accepts(&context, distinct_points, |(p, q)| cases::gej_sub(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_public_key(), |p| cases::gej_sub(p, p)); + 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| cases::fe_eq(a, a)); + accepts(&context, arb_u256_mod(SECP_P), |a| case::fe_eq(a, a)); } // Generalized case of fe_eq_zero_and_p_are_equal. @@ -143,14 +128,14 @@ fn fe_eq_x_and_x_plus_p_are_equal(context: TestContext) { let x = (0_u128..0x1_0000_03D1).prop_map(u256); accepts(&context, arb_shifted_pair(x, SECP_P), |(a, b)| { - cases::fe_eq(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)| { - cases::fe_eq(a, b) + case::fe_eq(a, b) }); } @@ -161,40 +146,40 @@ fn scalar_eq_s_and_s_plus_n_are_equal(context: TestContext) { let s = any::().prop_map(u256); accepts(&context, arb_shifted_pair(s, SECP_N), |(a, b)| { - cases::scalar_eq(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)| { - cases::scalar_eq(a, b) + case::scalar_eq(a, b) }); } // 7. ge_eq #[simplex::fuzz] fn ge_eq_rejects_negation(context: TestContext) { - rejects(&context, arb_ge(), cases::ge_eq_negation); + 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)| { - cases::gej_point_eq_rescaled(ge, lambda) + case::gej_point_eq_rescaled(ge, lambda) }); } #[simplex::fuzz] fn gej_point_eq_rejects_negation(context: TestContext) { - rejects(&context, arb_ge(), cases::gej_point_eq_negation); + 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)| { - cases::gej_point_eq_off_curve_point(ge, x) + case::gej_point_eq_off_curve_point(ge, x) }); } @@ -202,7 +187,7 @@ fn gej_point_eq_off_curve_is_false(context: TestContext) { 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, _)| { - cases::gej_point_eq_off_curve_gej(x, ZERO) + case::gej_point_eq_off_curve_gej(x, ZERO) }); } @@ -210,6 +195,6 @@ fn gej_point_eq_rejects_off_curve_gej(context: TestContext) { #[simplex::fuzz] fn safe_gej_normalize_roundtrip(context: TestContext) { accepts(&context, (arb_ge(), arb_non_zero_fe()), |(ge, lambda)| { - cases::safe_gej_normalize_rescaled(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); +}