From b138162fa2dd8206d411d39e9dd25b49d458c9dc Mon Sep 17 00:00:00 2001 From: Mamy Ratsimbazafy Date: Wed, 26 Jun 2024 19:31:36 +0200 Subject: [PATCH] =?UTF-8?q?Named=20algebras=202=20(=E2=9A=A0=EF=B8=8F=20br?= =?UTF-8?q?eaking=20internals=E2=9D=97)=20(#402)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: delete type_ff * rename C: static Curve to Name: static Algebra, to prepare for non-curve algebraic objects like Stark fields * refactor: fields/curves property access part 1 * refactor: cosmetic changes * refactor: rename ECP_ShortW -> EC_ShortW * refactor: rename EC_TwEdwards -> EC_TwEdw * refactor: split low-level exports and rename madd to mixedSum * remove changes applied from PLANNING.md * broke threadpool cache-oblivious matmul bench * broke Vanstone name with renaming * broke Solinas, Mrabet, Tzannes with mass renaming --- PLANNING.md | 16 - benchmarks/bench_ec_g1.nim | 30 +- benchmarks/bench_ec_g1_batch.nim | 34 +- benchmarks/bench_ec_g1_scalar_mul.nim | 66 +-- benchmarks/bench_ec_g2.nim | 30 +- benchmarks/bench_ec_g2_scalar_mul.nim | 62 +-- benchmarks/bench_ec_msm_bandersnatch.nim | 2 +- benchmarks/bench_ec_msm_bls12_381_g1.nim | 2 +- benchmarks/bench_ec_msm_bls12_381_g2.nim | 2 +- benchmarks/bench_ec_msm_bn254_snarks_g1.nim | 2 +- benchmarks/bench_ec_msm_pasta.nim | 2 +- .../bench_elliptic_parallel_template.nim | 10 +- benchmarks/bench_elliptic_template.nim | 35 +- ...nch_eth_eip2537_subgroup_checks_impact.nim | 46 +- benchmarks/bench_eth_evm_precompiles.nim | 20 +- benchmarks/bench_fields_template.nim | 26 +- benchmarks/bench_fp_double_precision.nim | 6 +- benchmarks/bench_gmp_modexp.nim | 1 - benchmarks/bench_hash_to_curve.nim | 24 +- benchmarks/bench_pairing_template.nim | 252 +++++----- benchmarks/bench_summary_bls12_377.nim | 36 +- benchmarks/bench_summary_bls12_381.nim | 36 +- benchmarks/bench_summary_bn254_nogami.nim | 36 +- benchmarks/bench_summary_bn254_snarks.nim | 36 +- benchmarks/bench_summary_pasta.nim | 16 +- benchmarks/bench_summary_template.nim | 80 ++-- benchmarks/bench_verkle_primitives.nim | 48 +- bindings/c_curve_decls.nim | 90 ++-- bindings/c_curve_decls_parallel.nim | 22 +- bindings/lib_curves.nim | 36 +- bindings/lib_headers.nim | 24 +- constantine.nimble | 8 +- constantine/README.md | 9 +- constantine/commitments/eth_verkle_ipa.nim | 22 +- .../commitments/eth_verkle_transcripts.nim | 10 +- constantine/commitments/kzg.nim | 94 ++-- constantine/commitments/kzg_parallel.nim | 76 +-- .../commitments_setups/ethereum_kzg_srs.nim | 4 +- constantine/curves_primitives.nim | 249 ---------- constantine/ethereum_bls_signatures.nim | 9 +- ...hereum_eip2333_bls12381_key_derivation.nim | 10 +- constantine/ethereum_eip4844_kzg.nim | 42 +- constantine/ethereum_eip4844_kzg_parallel.nim | 18 +- constantine/ethereum_evm_precompiles.nim | 96 ++-- constantine/ethereum_verkle_ipa.nim | 26 +- .../hash_to_curve/h2c_hash_to_field.nim | 32 +- .../hash_to_curve/h2c_isogeny_maps.nim | 48 +- .../hash_to_curve/h2c_map_to_isocurve_swu.nim | 66 +-- constantine/hash_to_curve/hash_to_curve.nim | 64 +-- constantine/lowlevel_bigints.nim | 43 ++ constantine/lowlevel_elliptic_curves.nim | 87 ++++ ... => lowlevel_elliptic_curves_parallel.nim} | 17 +- constantine/lowlevel_extension_fields.nim | 89 ++++ constantine/lowlevel_fields.nim | 104 ++++ constantine/lowlevel_pairing_curves.nim | 64 +++ constantine/math/arithmetic/finite_fields.nim | 80 ++-- .../finite_fields_double_precision.nim | 24 +- .../arithmetic/finite_fields_square_root.nim | 70 +-- .../finite_fields_square_root_precomp.nim | 24 +- constantine/math/ec_shortweierstrass.nim | 16 +- constantine/math/ec_twistededwards.nim | 10 +- .../math/elliptic/ec_endomorphism_accel.nim | 16 +- .../math/elliptic/ec_multi_scalar_mul.nim | 20 +- .../elliptic/ec_multi_scalar_mul_parallel.nim | 28 +- .../ec_multi_scalar_mul_scheduler.nim | 4 +- constantine/math/elliptic/ec_scalar_mul.nim | 11 +- .../math/elliptic/ec_scalar_mul_vartime.nim | 6 +- .../elliptic/ec_shortweierstrass_affine.nim | 33 +- .../ec_shortweierstrass_batch_ops.nim | 74 +-- ...ec_shortweierstrass_batch_ops_parallel.nim | 18 +- .../elliptic/ec_shortweierstrass_jacobian.nim | 129 ++--- .../ec_shortweierstrass_jacobian_extended.nim | 76 +-- .../ec_shortweierstrass_projective.nim | 139 +++--- .../elliptic/ec_twistededwards_affine.nim | 107 +++-- .../elliptic/ec_twistededwards_batch_ops.nim | 12 +- .../elliptic/ec_twistededwards_projective.nim | 155 +++--- .../assembly/fp2_asm_x86_adx_bmi2.nim | 8 +- .../math/extension_fields/square_root_fp2.nim | 4 +- constantine/math/extension_fields/towers.nim | 152 +++--- constantine/math/io/io_ec.nim | 30 +- constantine/math/isogenies/frobenius.nim | 48 +- .../math/pairings/cyclotomic_subgroups.nim | 12 +- constantine/math/pairings/lines_eval.nim | 78 +-- .../math/pairings/miller_accumulators.nim | 8 +- constantine/math/pairings/miller_loops.nim | 74 +-- constantine/math/pairings/pairings_bls12.nim | 58 +-- constantine/math/pairings/pairings_bn.nim | 68 +-- .../math/pairings/pairings_bw6_761.nim | 48 +- .../math/pairings/pairings_generic.nim | 20 +- constantine/math/polynomials/fft.nim | 20 +- .../constants/bandersnatch_generators.nim | 2 +- .../constants/bandersnatch_subgroups.nim | 2 +- .../constants/banderwagon_generators.nim | 2 +- .../named/constants/banderwagon_subgroups.nim | 2 +- .../named/constants/bls12_377_pairings.nim | 12 +- .../named/constants/bls12_377_subgroups.nim | 32 +- .../named/constants/bls12_381_generators.nim | 4 +- .../named/constants/bls12_381_pairings.nim | 12 +- .../named/constants/bls12_381_subgroups.nim | 32 +- .../named/constants/bn254_nogami_pairings.nim | 12 +- .../constants/bn254_nogami_subgroups.nim | 28 +- .../constants/bn254_snarks_generators.nim | 4 +- .../constants/bn254_snarks_subgroups.nim | 28 +- .../named/constants/bw6_761_subgroups.nim | 4 +- .../named/constants/pallas_subgroups.nim | 4 +- .../named/constants/secp256k1_subgroups.nim | 4 +- .../named/constants/vesta_subgroups.nim | 4 +- constantine/named/deriv/derive_constants.nim | 2 +- constantine/named/deriv/parser_curves.nim | 4 +- constantine/named/deriv/parser_fields.nim | 4 +- constantine/named/properties_curves.nim | 82 ++-- constantine/named/properties_fields.nim | 119 +++-- constantine/named/zoo_constants.nim | 8 +- constantine/named/zoo_endomorphisms.nim | 16 +- constantine/named/zoo_frobenius.nim | 8 +- constantine/named/zoo_generators.nim | 6 +- constantine/named/zoo_hash_to_curve.nim | 8 +- constantine/named/zoo_pairings.nim | 4 +- constantine/named/zoo_square_roots.nim | 16 +- constantine/named/zoo_square_roots_fp2.nim | 4 +- constantine/named/zoo_subgroups.nim | 2 +- constantine/platforms/static_for.nim | 6 +- constantine/platforms/type_ff.nim | 44 -- .../serialization/codecs_banderwagon.nim | 54 +-- .../serialization/codecs_bls12_381.nim | 70 ++- constantine/signatures/bls_signatures.nim | 70 +-- .../signatures/bls_signatures_parallel.nim | 15 +- constantine/threadpool/threadpool.nim | 2 +- helpers/prng_unsafe.nim | 18 +- metering/eip2537.md | 18 +- metering/m_eip2537.nim | 18 +- metering/m_msm.nim | 6 +- metering/m_pairings.nim | 12 +- research/kzg/fft_fr.nim | 2 +- research/kzg/fft_g1.nim | 18 +- research/kzg/fft_lut.nim | 8 +- research/kzg/kzg_single_proofs.nim | 8 +- research/kzg/polynomials.nim | 8 +- tests/gpu/t_nvidia_fp.nim | 18 +- .../math_elliptic_curves/t_ec_conversion.nim | 16 +- tests/math_elliptic_curves/t_ec_frobenius.nim | 72 +-- .../t_ec_sage_bls12_377.nim | 10 +- .../t_ec_sage_bls12_381.nim | 10 +- .../t_ec_sage_bn254_nogami.nim | 10 +- .../t_ec_sage_bn254_snarks.nim | 10 +- .../t_ec_sage_bw6_761_g1.nim | 14 +- .../t_ec_sage_bw6_761_g2.nim | 14 +- .../math_elliptic_curves/t_ec_sage_pallas.nim | 6 +- .../t_ec_sage_template.nim | 28 +- .../math_elliptic_curves/t_ec_sage_vesta.nim | 6 +- .../t_ec_shortw_jac_g1_add_double.nim | 24 +- .../t_ec_shortw_jac_g1_mixed_add.nim | 12 +- .../t_ec_shortw_jac_g1_msm.nim | 4 +- .../t_ec_shortw_jac_g1_mul_distri.nim | 12 +- .../t_ec_shortw_jac_g1_mul_sanity.nim | 12 +- .../t_ec_shortw_jac_g1_mul_vs_ref.nim | 12 +- .../t_ec_shortw_jac_g1_sum_reduce.nim | 4 +- ..._ec_shortw_jac_g2_add_double_bls12_377.nim | 2 +- ..._ec_shortw_jac_g2_add_double_bls12_381.nim | 2 +- ..._shortw_jac_g2_add_double_bn254_snarks.nim | 2 +- .../t_ec_shortw_jac_g2_add_double_bw6_761.nim | 2 +- ...t_ec_shortw_jac_g2_mixed_add_bls12_377.nim | 2 +- ...t_ec_shortw_jac_g2_mixed_add_bls12_381.nim | 2 +- ...c_shortw_jac_g2_mixed_add_bn254_snarks.nim | 2 +- .../t_ec_shortw_jac_g2_mixed_add_bw6_761.nim | 2 +- ..._ec_shortw_jac_g2_mul_distri_bls12_377.nim | 2 +- ..._ec_shortw_jac_g2_mul_distri_bls12_381.nim | 2 +- ..._shortw_jac_g2_mul_distri_bn254_snarks.nim | 2 +- .../t_ec_shortw_jac_g2_mul_distri_bw6_761.nim | 2 +- ..._ec_shortw_jac_g2_mul_sanity_bls12_377.nim | 2 +- ..._ec_shortw_jac_g2_mul_sanity_bls12_381.nim | 2 +- ..._shortw_jac_g2_mul_sanity_bn254_snarks.nim | 2 +- .../t_ec_shortw_jac_g2_mul_sanity_bw6_761.nim | 2 +- ..._ec_shortw_jac_g2_mul_vs_ref_bls12_377.nim | 2 +- ..._ec_shortw_jac_g2_mul_vs_ref_bls12_381.nim | 2 +- ..._shortw_jac_g2_mul_vs_ref_bn254_snarks.nim | 2 +- .../t_ec_shortw_jac_g2_mul_vs_ref_bw6_761.nim | 2 +- .../t_ec_shortw_jacext_g1_add_double.nim | 12 +- .../t_ec_shortw_jacext_g1_mixed_add.nim | 12 +- .../t_ec_shortw_jacext_g1_sum_reduce.nim | 4 +- .../t_ec_shortw_prj_edge_case_345.nim | 6 +- .../t_ec_shortw_prj_edge_cases.nim | 8 +- .../t_ec_shortw_prj_g1_add_double.nim | 25 +- .../t_ec_shortw_prj_g1_mixed_add.nim | 12 +- .../t_ec_shortw_prj_g1_msm.nim | 4 +- .../t_ec_shortw_prj_g1_mul_distri.nim | 12 +- .../t_ec_shortw_prj_g1_mul_sanity.nim | 18 +- .../t_ec_shortw_prj_g1_mul_vs_ref.nim | 12 +- .../t_ec_shortw_prj_g1_sum_reduce.nim | 4 +- ..._ec_shortw_prj_g2_add_double_bls12_377.nim | 2 +- ..._ec_shortw_prj_g2_add_double_bls12_381.nim | 2 +- ..._shortw_prj_g2_add_double_bn254_snarks.nim | 2 +- .../t_ec_shortw_prj_g2_add_double_bw6_761.nim | 2 +- ...t_ec_shortw_prj_g2_mixed_add_bls12_377.nim | 2 +- ...t_ec_shortw_prj_g2_mixed_add_bls12_381.nim | 2 +- ...c_shortw_prj_g2_mixed_add_bn254_snarks.nim | 2 +- .../t_ec_shortw_prj_g2_mixed_add_bw6_761.nim | 2 +- ..._ec_shortw_prj_g2_mul_distri_bls12_377.nim | 2 +- ..._ec_shortw_prj_g2_mul_distri_bls12_381.nim | 2 +- ..._shortw_prj_g2_mul_distri_bn254_snarks.nim | 2 +- .../t_ec_shortw_prj_g2_mul_distri_bw6_761.nim | 2 +- ..._ec_shortw_prj_g2_mul_sanity_bls12_377.nim | 2 +- ..._ec_shortw_prj_g2_mul_sanity_bls12_381.nim | 2 +- ..._shortw_prj_g2_mul_sanity_bn254_snarks.nim | 2 +- .../t_ec_shortw_prj_g2_mul_sanity_bw6_761.nim | 2 +- ..._ec_shortw_prj_g2_mul_vs_ref_bls12_377.nim | 2 +- ..._ec_shortw_prj_g2_mul_vs_ref_bls12_381.nim | 2 +- ..._shortw_prj_g2_mul_vs_ref_bn254_snarks.nim | 2 +- .../t_ec_shortw_prj_g2_mul_vs_ref_bw6_761.nim | 2 +- .../t_ec_subgroups_bls12_377.nim | 4 +- .../t_ec_subgroups_bls12_381.nim | 4 +- .../t_ec_subgroups_bn254_nogami.nim | 4 +- .../t_ec_subgroups_bn254_snarks.nim | 4 +- tests/math_elliptic_curves/t_ec_template.nim | 206 ++++---- ...uble.nim => t_ec_twedw_prj_add_double.nim} | 8 +- ...rds_prj_msm.nim => t_ec_twedw_prj_msm.nim} | 2 +- ...stri.nim => t_ec_twedw_prj_mul_distri.nim} | 8 +- ...nity.nim => t_ec_twedw_prj_mul_sanity.nim} | 6 +- ..._ref.nim => t_ec_twedw_prj_mul_vs_ref.nim} | 6 +- .../t_fp12_exponentiation.nim | 34 +- tests/math_extension_fields/t_fp2_sqrt.nim | 6 +- .../t_fp_tower_frobenius_template.nim | 14 +- .../t_fp_tower_template.nim | 2 +- .../t_finite_fields_double_precision.nim | 36 +- .../math_fields/t_finite_fields_mulsquare.nim | 52 +- tests/math_fields/t_finite_fields_powinv.nim | 50 +- tests/math_fields/t_finite_fields_sqrt.nim | 34 +- tests/math_fields/t_finite_fields_vs_gmp.nim | 64 +-- tests/math_fields/t_fp_cubic_root.nim | 2 +- tests/math_fields/t_fr.nim | 34 +- .../t_pairing_bls12_377_line_functions.nim | 22 +- .../t_pairing_bls12_377_multi.nim | 4 +- .../t_pairing_bls12_377_optate.nim | 4 +- .../t_pairing_bls12_381_line_functions.nim | 22 +- .../t_pairing_bls12_381_multi.nim | 4 +- .../t_pairing_bls12_381_optate.nim | 4 +- .../t_pairing_bn254_nogami_multi.nim | 4 +- .../t_pairing_bn254_nogami_optate.nim | 4 +- .../t_pairing_bn254_snarks_multi.nim | 4 +- .../t_pairing_bn254_snarks_optate.nim | 4 +- .../t_pairing_bw6_761_optate.nim | 4 +- .../t_pairing_cyclotomic_subgroup.nim | 24 +- .../t_pairing_mul_fp12_by_lines.nim | 448 +++++++++--------- tests/math_pairings/t_pairing_template.nim | 18 +- .../t_ec_shortw_jac_g1_batch_add_parallel.nim | 4 +- .../t_ec_shortw_jac_g1_msm_parallel.nim | 4 +- .../t_ec_shortw_prj_g1_batch_add_parallel.nim | 4 +- .../t_ec_shortw_prj_g1_msm_parallel.nim | 4 +- tests/parallel/t_ec_template_parallel.nim | 18 +- .../t_ec_twedwards_prj_msm_parallel.nim | 2 +- tests/primitives/t_io_unsaturated.nim | 14 +- ...hereum_eip2333_bls12381_key_derivation.nim | 2 +- tests/t_ethereum_verkle_ipa_primitives.nim | 50 +- tests/t_ethereum_verkle_ipa_test_helper.nim | 4 +- tests/t_ethereum_verkle_primitives.nim | 48 +- tests/t_hash_to_curve.nim | 34 +- tests/t_hash_to_curve_random.nim | 14 +- 257 files changed, 3491 insertions(+), 3307 deletions(-) delete mode 100644 constantine/curves_primitives.nim create mode 100644 constantine/lowlevel_bigints.nim create mode 100644 constantine/lowlevel_elliptic_curves.nim rename constantine/{curves_primitives_parallel.nim => lowlevel_elliptic_curves_parallel.nim} (75%) create mode 100644 constantine/lowlevel_extension_fields.nim create mode 100644 constantine/lowlevel_fields.nim create mode 100644 constantine/lowlevel_pairing_curves.nim rename tests/math_elliptic_curves/{t_ec_twedwards_prj_add_double.nim => t_ec_twedw_prj_add_double.nim} (86%) rename tests/math_elliptic_curves/{t_ec_twedwards_prj_msm.nim => t_ec_twedw_prj_msm.nim} (95%) rename tests/math_elliptic_curves/{t_ec_twedwards_prj_mul_distri.nim => t_ec_twedw_prj_mul_distri.nim} (87%) rename tests/math_elliptic_curves/{t_ec_twedwards_prj_mul_sanity.nim => t_ec_twedw_prj_mul_sanity.nim} (89%) rename tests/math_elliptic_curves/{t_ec_twedwards_prj_mul_vs_ref.nim => t_ec_twedw_prj_mul_vs_ref.nim} (89%) diff --git a/PLANNING.md b/PLANNING.md index e48890a75..124e01347 100644 --- a/PLANNING.md +++ b/PLANNING.md @@ -36,18 +36,6 @@ Other tracks are stretch goals, contributions towards them are accepted. - Endomorphism splitting bounds guarantee: i.e. division-based vs lattice-based splitting - Fix optimized MSM -Internal API breakage, which might leak to others using internal APIs. - -- Expand the library to support named fields and not just curves - - move and rename the config & constant folder - - use field instead of curve - - "named_math/fields_and_curves" - - matchingOrderBigInt -> BigInt[foo.getOrder()] - - Delete Mod*(), replace by fieldMod -- In the future there will likely be named ciphersuites or other high-level protocols - - - ### Ethereum Consensus Track - Implement cryptography and erasure codes EIP-7594 PeerDAS @@ -130,10 +118,6 @@ Internal API breakage, which might leak to others using internal APIs. - https://github.com/rust-lang/rust/pull/76986 - https://github.com/rust-lang/rfcs/pull/2884 -- Shorter names: - - Rename to EC_ShortW - - Rename to EC_TwEdw - ### Technical marketing track - Create Python bindings diff --git a/benchmarks/bench_ec_g1.nim b/benchmarks/bench_ec_g1.nim index d1936ff23..e40909ed6 100644 --- a/benchmarks/bench_ec_g1.nim +++ b/benchmarks/bench_ec_g1.nim @@ -45,34 +45,34 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - addBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - addBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - addBench(ECP_ShortW_JacExt[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_JacExt[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_JacExt[Fp[curve], G1], Iters) + addBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + addBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + addBench(EC_ShortW_JacExt[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_JacExt[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_JacExt[Fp[curve], G1], Iters) separator() - affFromProjBench(ECP_ShortW_Prj[Fp[curve], G1], MulIters) - affFromJacBench(ECP_ShortW_Jac[Fp[curve], G1], MulIters) + affFromProjBench(EC_ShortW_Prj[Fp[curve], G1], MulIters) + affFromJacBench(EC_ShortW_Jac[Fp[curve], G1], MulIters) separator() for numPoints in [10, 100, 1000, 10000]: let batchIters = max(1, Iters div numPoints) - affFromProjBatchBench(ECP_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = false, batchIters) + affFromProjBatchBench(EC_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = false, batchIters) separator() for numPoints in [10, 100, 1000, 10000]: let batchIters = max(1, Iters div numPoints) - affFromProjBatchBench(ECP_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = true, batchIters) + affFromProjBatchBench(EC_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = true, batchIters) separator() for numPoints in [10, 100, 1000, 10000]: let batchIters = max(1, Iters div numPoints) - affFromJacBatchBench(ECP_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = false, batchIters) + affFromJacBatchBench(EC_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = false, batchIters) separator() for numPoints in [10, 100, 1000, 10000]: let batchIters = max(1, Iters div numPoints) - affFromJacBatchBench(ECP_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = true, batchIters) + affFromJacBatchBench(EC_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = true, batchIters) separator() separator() diff --git a/benchmarks/bench_ec_g1_batch.nim b/benchmarks/bench_ec_g1_batch.nim index ef53f6701..fc4ab760c 100644 --- a/benchmarks/bench_ec_g1_batch.nim +++ b/benchmarks/bench_ec_g1_batch.nim @@ -40,47 +40,47 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - addBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - addBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - addBench(ECP_ShortW_JacExt[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_JacExt[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_JacExt[Fp[curve], G1], Iters) + addBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + addBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + addBench(EC_ShortW_JacExt[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_JacExt[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_JacExt[Fp[curve], G1], Iters) separator() # for numPoints in testNumPoints: # let batchIters = max(1, Iters div numPoints) - # multiAddBench(ECP_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = false, batchIters) + # multiAddBench(EC_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = false, batchIters) # separator() # for numPoints in testNumPoints: # let batchIters = max(1, Iters div numPoints) - # multiAddBench(ECP_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = true, batchIters) + # multiAddBench(EC_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = true, batchIters) # separator() # for numPoints in testNumPoints: # let batchIters = max(1, Iters div numPoints) - # multiAddParallelBench(ECP_ShortW_Prj[Fp[curve], G1], numPoints, batchIters) + # multiAddParallelBench(EC_ShortW_Prj[Fp[curve], G1], numPoints, batchIters) # separator() for numPoints in testNumPoints: let batchIters = max(1, Iters div numPoints) - multiAddBench(ECP_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = false, batchIters) + multiAddBench(EC_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = false, batchIters) separator() for numPoints in testNumPoints: let batchIters = max(1, Iters div numPoints) - multiAddBench(ECP_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = true, batchIters) + multiAddBench(EC_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = true, batchIters) separator() for numPoints in testNumPoints: let batchIters = max(1, Iters div numPoints) - multiAddParallelBench(ECP_ShortW_Jac[Fp[curve], G1], numPoints, batchIters) + multiAddParallelBench(EC_ShortW_Jac[Fp[curve], G1], numPoints, batchIters) # separator() # for numPoints in testNumPoints: # let batchIters = max(1, Iters div numPoints) - # multiAddBench(ECP_ShortW_JacExt[Fp[curve], G1], numPoints, useBatching = false, batchIters) + # multiAddBench(EC_ShortW_JacExt[Fp[curve], G1], numPoints, useBatching = false, batchIters) # separator() # for numPoints in testNumPoints: # let batchIters = max(1, Iters div numPoints) - # multiAddBench(ECP_ShortW_JacExt[Fp[curve], G1], numPoints, useBatching = true, batchIters) + # multiAddBench(EC_ShortW_JacExt[Fp[curve], G1], numPoints, useBatching = true, batchIters) separator() separator() diff --git a/benchmarks/bench_ec_g1_scalar_mul.nim b/benchmarks/bench_ec_g1_scalar_mul.nim index 1bb078830..e53888a34 100644 --- a/benchmarks/bench_ec_g1_scalar_mul.nim +++ b/benchmarks/bench_ec_g1_scalar_mul.nim @@ -44,45 +44,45 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - const bits = curve.getCurveOrderBitwidth() - scalarMulVartimeDoubleAddBench(ECP_ShortW_Prj[Fp[curve], G1], bits, MulIters) - scalarMulVartimeDoubleAddBench(ECP_ShortW_Jac[Fp[curve], G1], bits, MulIters) + const bits = Fr[curve].bits() + scalarMulVartimeDoubleAddBench(EC_ShortW_Prj[Fp[curve], G1], bits, MulIters) + scalarMulVartimeDoubleAddBench(EC_ShortW_Jac[Fp[curve], G1], bits, MulIters) separator() - scalarMulVartimeMinHammingWeightRecodingBench(ECP_ShortW_Prj[Fp[curve], G1], bits, MulIters) - scalarMulVartimeMinHammingWeightRecodingBench(ECP_ShortW_Jac[Fp[curve], G1], bits, MulIters) + scalarMulVartimeMinHammingWeightRecodingBench(EC_ShortW_Prj[Fp[curve], G1], bits, MulIters) + scalarMulVartimeMinHammingWeightRecodingBench(EC_ShortW_Jac[Fp[curve], G1], bits, MulIters) separator() - scalarMulGenericBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 2, MulIters) - scalarMulGenericBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 3, MulIters) - scalarMulGenericBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 4, MulIters) - scalarMulGenericBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 5, MulIters) - scalarMulGenericBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 2, MulIters) - scalarMulGenericBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) - scalarMulGenericBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) - scalarMulGenericBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) + scalarMulGenericBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 2, MulIters) + scalarMulGenericBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 3, MulIters) + scalarMulGenericBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 4, MulIters) + scalarMulGenericBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 5, MulIters) + scalarMulGenericBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 2, MulIters) + scalarMulGenericBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) + scalarMulGenericBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) + scalarMulGenericBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) separator() - scalarMulVartimeWNAFBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 2, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 3, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 4, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 5, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 2, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 2, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 3, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 4, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 5, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 2, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) separator() when bits >= 196: # All endomorphisms constants are below this threshold - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 2, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 3, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 4, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Prj[Fp[curve], G1], bits, window = 5, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 2, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 2, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 3, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 4, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Prj[Fp[curve], G1], bits, window = 5, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 2, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) separator() - scalarMulEndo( ECP_ShortW_Prj[Fp[curve], G1], bits, MulIters) - scalarMulEndoWindow(ECP_ShortW_Prj[Fp[curve], G1], bits, MulIters) - scalarMulEndo( ECP_ShortW_Jac[Fp[curve], G1], bits, MulIters) - scalarMulEndoWindow(ECP_ShortW_Jac[Fp[curve], G1], bits, MulIters) + scalarMulEndo( EC_ShortW_Prj[Fp[curve], G1], bits, MulIters) + scalarMulEndoWindow(EC_ShortW_Prj[Fp[curve], G1], bits, MulIters) + scalarMulEndo( EC_ShortW_Jac[Fp[curve], G1], bits, MulIters) + scalarMulEndoWindow(EC_ShortW_Jac[Fp[curve], G1], bits, MulIters) separator() separator() diff --git a/benchmarks/bench_ec_g2.nim b/benchmarks/bench_ec_g2.nim index 969215104..a17f0bb71 100644 --- a/benchmarks/bench_ec_g2.nim +++ b/benchmarks/bench_ec_g2.nim @@ -46,34 +46,34 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - addBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - addBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - addBench(ECP_ShortW_JacExt[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_JacExt[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_JacExt[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + addBench(EC_ShortW_JacExt[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_JacExt[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_JacExt[Fp2[curve], G2], Iters) separator() - affFromProjBench(ECP_ShortW_Prj[Fp2[curve], G2], MulIters) - affFromJacBench(ECP_ShortW_Jac[Fp2[curve], G2], MulIters) + affFromProjBench(EC_ShortW_Prj[Fp2[curve], G2], MulIters) + affFromJacBench(EC_ShortW_Jac[Fp2[curve], G2], MulIters) separator() for numPoints in [10, 100, 1000, 10000]: let batchIters = max(1, Iters div numPoints) - affFromProjBatchBench(ECP_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = false, batchIters) + affFromProjBatchBench(EC_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = false, batchIters) separator() for numPoints in [10, 100, 1000, 10000]: let batchIters = max(1, Iters div numPoints) - affFromProjBatchBench(ECP_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = true, batchIters) + affFromProjBatchBench(EC_ShortW_Prj[Fp[curve], G1], numPoints, useBatching = true, batchIters) separator() for numPoints in [10, 100, 1000, 10000]: let batchIters = max(1, Iters div numPoints) - affFromJacBatchBench(ECP_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = false, batchIters) + affFromJacBatchBench(EC_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = false, batchIters) separator() for numPoints in [10, 100, 1000, 10000]: let batchIters = max(1, Iters div numPoints) - affFromJacBatchBench(ECP_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = true, batchIters) + affFromJacBatchBench(EC_ShortW_Jac[Fp[curve], G1], numPoints, useBatching = true, batchIters) separator() separator() diff --git a/benchmarks/bench_ec_g2_scalar_mul.nim b/benchmarks/bench_ec_g2_scalar_mul.nim index e63c35e80..1b05fdec9 100644 --- a/benchmarks/bench_ec_g2_scalar_mul.nim +++ b/benchmarks/bench_ec_g2_scalar_mul.nim @@ -43,43 +43,43 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - const bits = curve.getCurveOrderBitwidth() - scalarMulVartimeDoubleAddBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, MulIters) - scalarMulVartimeDoubleAddBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, MulIters) + const bits = Fr[curve].bits() + scalarMulVartimeDoubleAddBench(EC_ShortW_Prj[Fp2[curve], G2], bits, MulIters) + scalarMulVartimeDoubleAddBench(EC_ShortW_Jac[Fp2[curve], G2], bits, MulIters) separator() - scalarMulVartimeMinHammingWeightRecodingBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, MulIters) - scalarMulVartimeMinHammingWeightRecodingBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, MulIters) + scalarMulVartimeMinHammingWeightRecodingBench(EC_ShortW_Prj[Fp2[curve], G2], bits, MulIters) + scalarMulVartimeMinHammingWeightRecodingBench(EC_ShortW_Jac[Fp2[curve], G2], bits, MulIters) separator() - scalarMulGenericBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 2, MulIters) - scalarMulGenericBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 3, MulIters) - scalarMulGenericBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 4, MulIters) - scalarMulGenericBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 5, MulIters) - scalarMulGenericBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 2, MulIters) - scalarMulGenericBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) - scalarMulGenericBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) - scalarMulGenericBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 5, MulIters) + scalarMulGenericBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 2, MulIters) + scalarMulGenericBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 3, MulIters) + scalarMulGenericBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 4, MulIters) + scalarMulGenericBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 5, MulIters) + scalarMulGenericBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 2, MulIters) + scalarMulGenericBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) + scalarMulGenericBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) + scalarMulGenericBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 5, MulIters) separator() - scalarMulVartimeWNAFBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 2, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 3, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 4, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 5, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 2, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 5, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 2, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 3, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 4, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 5, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 2, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 5, MulIters) separator() when bits >= 196: # All endomorphisms constants are below this threshold - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 2, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 3, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 4, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Prj[Fp2[curve], G2], bits, window = 5, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 2, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 5, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 2, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 3, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 4, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Prj[Fp2[curve], G2], bits, window = 5, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 2, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 5, MulIters) separator() - scalarMulEndo(ECP_ShortW_Prj[Fp2[curve], G2], bits, MulIters) - scalarMulEndo(ECP_ShortW_Jac[Fp2[curve], G2], bits, MulIters) + scalarMulEndo(EC_ShortW_Prj[Fp2[curve], G2], bits, MulIters) + scalarMulEndo(EC_ShortW_Jac[Fp2[curve], G2], bits, MulIters) separator() separator() diff --git a/benchmarks/bench_ec_msm_bandersnatch.nim b/benchmarks/bench_ec_msm_bandersnatch.nim index b36266231..f9c776556 100644 --- a/benchmarks/bench_ec_msm_bandersnatch.nim +++ b/benchmarks/bench_ec_msm_bandersnatch.nim @@ -36,7 +36,7 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - var ctx = createBenchMsmContext(ECP_TwEdwards_Prj[Fp[curve]], testNumPoints) + var ctx = createBenchMsmContext(EC_TwEdw_Prj[Fp[curve]], testNumPoints) separator() for numPoints in testNumPoints: let batchIters = max(1, Iters div numPoints) diff --git a/benchmarks/bench_ec_msm_bls12_381_g1.nim b/benchmarks/bench_ec_msm_bls12_381_g1.nim index eb2b007cc..f05c3d9d8 100644 --- a/benchmarks/bench_ec_msm_bls12_381_g1.nim +++ b/benchmarks/bench_ec_msm_bls12_381_g1.nim @@ -39,7 +39,7 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - var ctx = createBenchMsmContext(ECP_ShortW_Jac[Fp[curve], G1], testNumPoints) + var ctx = createBenchMsmContext(EC_ShortW_Jac[Fp[curve], G1], testNumPoints) separator() for numPoints in testNumPoints: let batchIters = max(1, Iters div numPoints) diff --git a/benchmarks/bench_ec_msm_bls12_381_g2.nim b/benchmarks/bench_ec_msm_bls12_381_g2.nim index 1c97b2d74..79b0d2b7f 100644 --- a/benchmarks/bench_ec_msm_bls12_381_g2.nim +++ b/benchmarks/bench_ec_msm_bls12_381_g2.nim @@ -38,7 +38,7 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - var ctx = createBenchMsmContext(ECP_ShortW_Jac[Fp2[curve], G2], testNumPoints) + var ctx = createBenchMsmContext(EC_ShortW_Jac[Fp2[curve], G2], testNumPoints) separator() for numPoints in testNumPoints: let batchIters = max(1, Iters div numPoints) diff --git a/benchmarks/bench_ec_msm_bn254_snarks_g1.nim b/benchmarks/bench_ec_msm_bn254_snarks_g1.nim index 77fb06a41..4765e0bb2 100644 --- a/benchmarks/bench_ec_msm_bn254_snarks_g1.nim +++ b/benchmarks/bench_ec_msm_bn254_snarks_g1.nim @@ -38,7 +38,7 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - var ctx = createBenchMsmContext(ECP_ShortW_Jac[Fp[curve], G1], testNumPoints) + var ctx = createBenchMsmContext(EC_ShortW_Jac[Fp[curve], G1], testNumPoints) separator() for numPoints in testNumPoints: let batchIters = max(1, Iters div numPoints) diff --git a/benchmarks/bench_ec_msm_pasta.nim b/benchmarks/bench_ec_msm_pasta.nim index 02efd4e34..6200d3764 100644 --- a/benchmarks/bench_ec_msm_pasta.nim +++ b/benchmarks/bench_ec_msm_pasta.nim @@ -39,7 +39,7 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - var ctx = createBenchMsmContext(ECP_ShortW_Jac[Fp[curve], G1], testNumPoints) + var ctx = createBenchMsmContext(EC_ShortW_Jac[Fp[curve], G1], testNumPoints) separator() for numPoints in testNumPoints: let batchIters = max(1, Iters div numPoints) diff --git a/benchmarks/bench_elliptic_parallel_template.nim b/benchmarks/bench_elliptic_parallel_template.nim index eb3325a1e..d90154061 100644 --- a/benchmarks/bench_elliptic_parallel_template.nim +++ b/benchmarks/bench_elliptic_parallel_template.nim @@ -36,10 +36,10 @@ export bench_elliptic_template # ############################################################ proc multiAddParallelBench*(EC: typedesc, numInputs: int, iters: int) = - var points = newSeq[ECP_ShortW_Aff[EC.F, EC.G]](numInputs) + var points = newSeq[EC_ShortW_Aff[EC.F, EC.G]](numInputs) for i in 0 ..< numInputs: - points[i] = rng.random_unsafe(ECP_ShortW_Aff[EC.F, EC.G]) + points[i] = rng.random_unsafe(EC_ShortW_Aff[EC.F, EC.G]) var r{.noInit.}: EC @@ -56,14 +56,14 @@ proc multiAddParallelBench*(EC: typedesc, numInputs: int, iters: int) = type BenchMsmContext*[EC] = object tp: Threadpool numInputs: int - coefs: seq[matchingOrderBigInt(EC.F.C)] + coefs: seq[getBigInt(EC.F.Name, kScalarField)] points: seq[affine(EC)] proc createBenchMsmContext*(EC: typedesc, inputSizes: openArray[int]): BenchMsmContext[EC] = result.tp = Threadpool.new() let maxNumInputs = inputSizes.max() - const bits = EC.F.C.getCurveOrderBitwidth() + const bits = EC.getScalarField().bits() type ECaff = affine(EC) result.points = newSeq[ECaff](maxNumInputs) @@ -103,7 +103,7 @@ proc createBenchMsmContext*(EC: typedesc, inputSizes: openArray[int]): BenchMsmC stdout.write &"in {float64(inNanoSeconds(stop-start)) / 1e6:6.3f} ms\n" proc msmParallelBench*[EC](ctx: var BenchMsmContext[EC], numInputs: int, iters: int) = - const bits = EC.F.C.getCurveOrderBitwidth() + const bits = EC.getScalarField().bits() type ECaff = affine(EC) template coefs: untyped = ctx.coefs.toOpenArray(0, numInputs-1) diff --git a/benchmarks/bench_elliptic_template.nim b/benchmarks/bench_elliptic_template.nim index d36b23b55..faf4a36c8 100644 --- a/benchmarks/bench_elliptic_template.nim +++ b/benchmarks/bench_elliptic_template.nim @@ -45,10 +45,11 @@ macro fixEllipticDisplay(EC: typedesc): untyped = let instantiated = EC.getTypeInst() var name = $instantiated[1][0] # EllipticEquationFormCoordinates let fieldName = $instantiated[1][1][0] - let curveName = $Curve(instantiated[1][1][1].intVal) + let curve = Algebra(instantiated[1][1][1].intVal) + let curveName = $curve name.add "[" & fieldName & "[" & curveName & "]" & - (if family(Curve(instantiated[1][1][1].intVal)) != NoFamily: + (if family(curve) != NoFamily: ", " & $Subgroup(instantiated[1][2].intVal) else: "") & "]" @@ -66,17 +67,17 @@ template bench*(op: string, EC: typedesc, iters: int, body: untyped): untyped = measure(iters, startTime, stopTime, startClk, stopClk, body) report(op, fixEllipticDisplay(EC), startTime, stopTime, startClk, stopClk, iters) -func `+=`[F; G: static Subgroup](P: var ECP_ShortW_JacExt[F, G], Q: ECP_ShortW_JacExt[F, G]) {.inline.}= +func `+=`[F; G: static Subgroup](P: var EC_ShortW_JacExt[F, G], Q: EC_ShortW_JacExt[F, G]) {.inline.}= P.sum_vartime(P, Q) -func `+=`[F; G: static Subgroup](P: var ECP_ShortW_JacExt[F, G], Q: ECP_ShortW_Aff[F, G]) {.inline.}= - P.madd_vartime(P, Q) +func `+=`[F; G: static Subgroup](P: var EC_ShortW_JacExt[F, G], Q: EC_ShortW_Aff[F, G]) {.inline.}= + P.mixedSum_vartime(P, Q) proc addBench*(EC: typedesc, iters: int) = var r {.noInit.}: EC let P = rng.random_unsafe(EC) let Q = rng.random_unsafe(EC) - when EC is ECP_ShortW_JacExt: + when EC is EC_ShortW_JacExt: bench("EC Add vartime " & $EC.G, EC, iters): r.sum_vartime(P, Q) else: @@ -91,19 +92,19 @@ proc mixedAddBench*(EC: typedesc, iters: int) = var r {.noInit.}: EC let P = rng.random_unsafe(EC) let Q = rng.random_unsafe(EC) - var Qaff: ECP_ShortW_Aff[EC.F, EC.G] + var Qaff: EC_ShortW_Aff[EC.F, EC.G] Qaff.affine(Q) - when EC is ECP_ShortW_JacExt: + when EC is EC_ShortW_JacExt: bench("EC Mixed Addition vartime " & $EC.G, EC, iters): - r.madd_vartime(P, Qaff) + r.mixedSum_vartime(P, Qaff) else: block: bench("EC Mixed Addition " & $EC.G, EC, iters): - r.madd(P, Qaff) + r.mixedSum(P, Qaff) block: bench("EC Mixed Addition vartime " & $EC.G, EC, iters): - r.madd_vartime(P, Qaff) + r.mixedSum_vartime(P, Qaff) proc doublingBench*(EC: typedesc, iters: int) = var r {.noInit.}: EC @@ -112,13 +113,13 @@ proc doublingBench*(EC: typedesc, iters: int) = r.double(P) proc affFromProjBench*(EC: typedesc, iters: int) = - var r {.noInit.}: ECP_ShortW_Aff[EC.F, EC.G] + var r {.noInit.}: EC_ShortW_Aff[EC.F, EC.G] let P = rng.random_unsafe(EC) bench("EC Projective to Affine " & $EC.G, EC, iters): r.affine(P) proc affFromJacBench*(EC: typedesc, iters: int) = - var r {.noInit.}: ECP_ShortW_Aff[EC.F, EC.G] + var r {.noInit.}: EC_ShortW_Aff[EC.F, EC.G] let P = rng.random_unsafe(EC) bench("EC Jacobian to Affine " & $EC.G, EC, iters): r.affine(P) @@ -253,10 +254,10 @@ proc subgroupCheckScalarMulVartimeEndoWNAFBench*(EC: typedesc, bits, window: sta r.scalarMulEndo_minHammingWeight_windowed_vartime(exponent, window) proc multiAddBench*(EC: typedesc, numPoints: int, useBatching: bool, iters: int) = - var points = newSeq[ECP_ShortW_Aff[EC.F, EC.G]](numPoints) + var points = newSeq[EC_ShortW_Aff[EC.F, EC.G]](numPoints) for i in 0 ..< numPoints: - points[i] = rng.random_unsafe(ECP_ShortW_Aff[EC.F, EC.G]) + points[i] = rng.random_unsafe(EC_ShortW_Aff[EC.F, EC.G]) var r{.noInit.}: EC @@ -271,8 +272,8 @@ proc multiAddBench*(EC: typedesc, numPoints: int, useBatching: bool, iters: int) proc msmBench*(EC: typedesc, numPoints: int, iters: int) = - const bits = EC.F.C.getCurveOrderBitwidth() - var points = newSeq[ECP_ShortW_Aff[EC.F, EC.G]](numPoints) + const bits = EC.getScalarField().bits() + var points = newSeq[EC_ShortW_Aff[EC.F, EC.G]](numPoints) var scalars = newSeq[BigInt[bits]](numPoints) for i in 0 ..< numPoints: diff --git a/benchmarks/bench_eth_eip2537_subgroup_checks_impact.nim b/benchmarks/bench_eth_eip2537_subgroup_checks_impact.nim index ee06b9e9e..fa414c4f1 100644 --- a/benchmarks/bench_eth_eip2537_subgroup_checks_impact.nim +++ b/benchmarks/bench_eth_eip2537_subgroup_checks_impact.nim @@ -33,44 +33,44 @@ proc main() = separator() staticFor i, 0, AvailableCurves.len: const curve = AvailableCurves[i] - const bits = curve.getCurveOrderBitwidth() + const bits = Fr[curve].bits() # G1 separator() - scalarMulVartimeDoubleAddBench(ECP_ShortW_Jac[Fp[curve], G1], bits, MulIters) + scalarMulVartimeDoubleAddBench(EC_ShortW_Jac[Fp[curve], G1], bits, MulIters) separator() - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) separator() - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) separator() - scalarMulEndo( ECP_ShortW_Jac[Fp[curve], G1], bits, MulIters) - scalarMulEndoWindow(ECP_ShortW_Jac[Fp[curve], G1], bits, MulIters) + scalarMulEndo( EC_ShortW_Jac[Fp[curve], G1], bits, MulIters) + scalarMulEndoWindow(EC_ShortW_Jac[Fp[curve], G1], bits, MulIters) separator() - subgroupCheckBench(ECP_ShortW_Jac[Fp[curve], G1], MulIters) - subgroupCheckScalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) - subgroupCheckScalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) - subgroupCheckScalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) + subgroupCheckBench(EC_ShortW_Jac[Fp[curve], G1], MulIters) + subgroupCheckScalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 3, MulIters) + subgroupCheckScalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 4, MulIters) + subgroupCheckScalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp[curve], G1], bits, window = 5, MulIters) separator() # G2 separator() - scalarMulVartimeDoubleAddBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, MulIters) + scalarMulVartimeDoubleAddBench(EC_ShortW_Jac[Fp2[curve], G2], bits, MulIters) separator() - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) - scalarMulVartimeWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) + scalarMulVartimeWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) separator() - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) - scalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) + scalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) separator() - scalarMulEndo(ECP_ShortW_Jac[Fp2[curve], G2], bits, MulIters) + scalarMulEndo(EC_ShortW_Jac[Fp2[curve], G2], bits, MulIters) separator() - subgroupCheckBench(ECP_ShortW_Jac[Fp2[curve], G2], MulIters) - subgroupCheckScalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) - subgroupCheckScalarMulVartimeEndoWNAFBench(ECP_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) + subgroupCheckBench(EC_ShortW_Jac[Fp2[curve], G2], MulIters) + subgroupCheckScalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 3, MulIters) + subgroupCheckScalarMulVartimeEndoWNAFBench(EC_ShortW_Jac[Fp2[curve], G2], bits, window = 4, MulIters) separator() main() diff --git a/benchmarks/bench_eth_evm_precompiles.nim b/benchmarks/bench_eth_evm_precompiles.nim index 0998d3442..9ddf4ddba 100644 --- a/benchmarks/bench_eth_evm_precompiles.nim +++ b/benchmarks/bench_eth_evm_precompiles.nim @@ -78,20 +78,20 @@ func gasBls12PairingCheck(length: int): int = # Constructors # ----------------------------------------------------------------------------------------------------- -func clearCofactor[F; G: static Subgroup](ec: var ECP_ShortW_Aff[F, G]) = +func clearCofactor[F; G: static Subgroup](ec: var EC_ShortW_Aff[F, G]) = # For now we don't have any affine operation defined - var t {.noInit.}: ECP_ShortW_Prj[F, G] + var t {.noInit.}: EC_ShortW_Prj[F, G] t.fromAffine(ec) t.clearCofactor() ec.affine(t) proc createPairingInputsBN254(length: int): seq[byte] = var buf: array[32, byte] - const C = BN254_Snarks + const Name = BN254_Snarks for _ in 0 ..< length: - var P = rng.random_unsafe(ECP_ShortW_Aff[Fp[C], G1]) + var P = rng.random_unsafe(EC_ShortW_Aff[Fp[Name], G1]) P.clearCofactor() - var Q = rng.random_unsafe(ECP_ShortW_Aff[Fp2[C], G2]) + var Q = rng.random_unsafe(EC_ShortW_Aff[Fp2[Name], G2]) Q.clearCofactor() buf.marshal(P.x, bigEndian) @@ -114,11 +114,11 @@ proc createPairingInputsBN254(length: int): seq[byte] = proc createPairingInputsBLS12381(length: int): seq[byte] = var buf: array[64, byte] - const C = BLS12_381 + const Name = BLS12_381 for _ in 0 ..< length: - var P = rng.random_unsafe(ECP_ShortW_Aff[Fp[C], G1]) + var P = rng.random_unsafe(EC_ShortW_Aff[Fp[Name], G1]) P.clearCofactor() - var Q = rng.random_unsafe(ECP_ShortW_Aff[Fp2[C], G2]) + var Q = rng.random_unsafe(EC_ShortW_Aff[Fp2[Name], G2]) Q.clearCofactor() buf.marshal(P.x, bigEndian) @@ -311,7 +311,7 @@ proc main() = for i in 1..8: pairingCtxBLS.benchBls12PairingCheck(i, ItersPairing) separator() - let msmG1Ctx = createMsmInputs(ECP_ShortW_Jac[Fp[BLS12_381], G1], 128) + let msmG1Ctx = createMsmInputs(EC_ShortW_Jac[Fp[BLS12_381], G1], 128) msmG1Ctx.benchBls12MsmG1( 2, ItersMsm) msmG1Ctx.benchBls12MsmG1( 4, ItersMsm) msmG1Ctx.benchBls12MsmG1( 8, ItersMsm) @@ -320,7 +320,7 @@ proc main() = msmG1Ctx.benchBls12MsmG1( 64, ItersMsm) msmG1Ctx.benchBls12MsmG1(128, ItersMsm) separator() - let msmG2Ctx = createMsmInputs(ECP_ShortW_Jac[Fp2[BLS12_381], G2], 128) + let msmG2Ctx = createMsmInputs(EC_ShortW_Jac[Fp2[BLS12_381], G2], 128) msmG2Ctx.benchBls12MsmG2( 2, ItersMsm) msmG2Ctx.benchBls12MsmG2( 4, ItersMsm) msmG2Ctx.benchBls12MsmG2( 8, ItersMsm) diff --git a/benchmarks/bench_fields_template.nim b/benchmarks/bench_fields_template.nim index f0ac62c63..ca9c414ba 100644 --- a/benchmarks/bench_fields_template.nim +++ b/benchmarks/bench_fields_template.nim @@ -40,7 +40,7 @@ macro fixFieldDisplay(T: typedesc): untyped = # we get the Curve ID instead of the curve name. let instantiated = T.getTypeInst() var name = $instantiated[1][0] # 𝔽p - name.add "[" & $Curve(instantiated[1][1].intVal) & "]" + name.add "[" & $Algebra(instantiated[1][1].intVal) & "]" result = newLit name template bench(op: string, T: typedesc, iters: int, body: untyped): untyped = @@ -50,8 +50,8 @@ template bench(op: string, T: typedesc, iters: int, body: untyped): untyped = func random_unsafe(rng: var RngState, a: var FpDbl) = ## Initialize a standalone Double-Width field element ## we don't reduce it modulo p², this is only used for benchmark - let aHi = rng.random_unsafe(Fp[FpDbl.C]) - let aLo = rng.random_unsafe(Fp[FpDbl.C]) + let aHi = rng.random_unsafe(Fp[FpDbl.Name]) + let aLo = rng.random_unsafe(Fp[FpDbl.Name]) for i in 0 ..< aLo.mres.limbs.len: a.limbs2x[i] = aLo.mres.limbs[i] for i in 0 ..< aHi.mres.limbs.len: @@ -140,7 +140,7 @@ proc sumprodBench*(T: typedesc, iters: int) = r.sumprod([a, b], [u, v]) proc toBigBench*(T: typedesc, iters: int) = - var r: matchingBigInt(T.C) + var r: T.getBigInt() let x = rng.random_unsafe(T) preventOptimAway(r) bench("BigInt <- field conversion", T, iters): @@ -148,7 +148,7 @@ proc toBigBench*(T: typedesc, iters: int) = proc toFieldBench*(T: typedesc, iters: int) = var r: T - let x = rng.random_unsafe(matchingBigInt(T.C)) + let x = rng.random_unsafe(T.getBigInt()) preventOptimAway(r) bench("BigInt -> field conversion", T, iters): r.fromBig(x) @@ -176,14 +176,14 @@ proc sqrtBench*(T: typedesc, iters: int) = let x = rng.random_unsafe(T) const algoType = block: - when T.C.has_P_3mod4_primeModulus(): + when T.Name.has_P_3mod4_primeModulus(): "p ≡ 3 (mod 4)" - elif T.C.has_P_5mod8_primeModulus(): + elif T.Name.has_P_5mod8_primeModulus(): "p ≡ 5 (mod 8)" else: "Tonelli-Shanks" const addchain = block: - when T.C.hasSqrtAddchain() or T.C.hasTonelliShanksAddchain(): + when T.Name.hasSqrtAddchain() or T.Name.hasTonelliShanksAddchain(): "with addition chain" else: "without addition chain" @@ -203,14 +203,14 @@ proc sqrtVartimeBench*(T: typedesc, iters: int) = let x = rng.random_unsafe(T) const algoType = block: - when T.C.has_P_3mod4_primeModulus(): + when T.Name.has_P_3mod4_primeModulus(): "p ≡ 3 (mod 4)" - elif T.C.has_P_5mod8_primeModulus(): + elif T.Name.has_P_5mod8_primeModulus(): "p ≡ 5 (mod 8)" else: "Tonelli-Shanks" const addchain = block: - when T.C.hasSqrtAddchain() or T.C.hasTonelliShanksAddchain(): + when T.Name.hasSqrtAddchain() or T.Name.hasTonelliShanksAddchain(): "with addition chain" else: "without addition chain" @@ -228,14 +228,14 @@ proc sqrtRatioVartimeBench*(T: typedesc, iters: int) = proc powBench*(T: typedesc, iters: int) = let x = rng.random_unsafe(T) - let exponent = rng.random_unsafe(BigInt[T.C.getCurveOrderBitwidth()]) + let exponent = rng.random_unsafe(BigInt[Fr[T.Name].bits()]) bench("Exp curve order (constant-time) - " & $exponent.bits & "-bit", T, iters): var r = x r.pow(exponent) proc powUnsafeBench*(T: typedesc, iters: int) = let x = rng.random_unsafe(T) - let exponent = rng.random_unsafe(BigInt[T.C.getCurveOrderBitwidth()]) + let exponent = rng.random_unsafe(BigInt[Fr[T.Name].bits()]) bench("Exp curve order (Leak exponent bits) - " & $exponent.bits & "-bit", T, iters): var r = x r.pow_vartime(exponent) diff --git a/benchmarks/bench_fp_double_precision.nim b/benchmarks/bench_fp_double_precision.nim index bf7a360ed..c156ae9fa 100644 --- a/benchmarks/bench_fp_double_precision.nim +++ b/benchmarks/bench_fp_double_precision.nim @@ -219,12 +219,12 @@ proc reduce2x*(T: typedesc, iters: int) = proc reduce2xViaDivision*(T: typedesc, iters: int) = - const bits2x = 2 * T.C.getCurveBitWidth() - var r: matchingBigInt(T.C) + const bits2x = 2 * T.bits() + var r: T.getBigInt() let t = rng.random_unsafe(BigInt[bits2x]) bench("Reduction via division", $T & " <- " & $doublePrec(T), iters): - r.reduce(t, T.fieldMod()) + r.reduce(t, T.getModulus()) proc main() = separator() diff --git a/benchmarks/bench_gmp_modexp.nim b/benchmarks/bench_gmp_modexp.nim index 267344ff8..94bdde7b2 100644 --- a/benchmarks/bench_gmp_modexp.nim +++ b/benchmarks/bench_gmp_modexp.nim @@ -18,7 +18,6 @@ const # https://gmplib.org/manual/Integer-Import-and-Export.html GMP_MostSignificantWordFirst = 1'i32 GMP_LeastSignificantWordFirst = -1'i32 -# let M = Mod(BN254_Snarks) const bits = 256 const expBits = bits # Stint only supports same size args diff --git a/benchmarks/bench_hash_to_curve.nim b/benchmarks/bench_hash_to_curve.nim index 783587cf4..296571bab 100644 --- a/benchmarks/bench_hash_to_curve.nim +++ b/benchmarks/bench_hash_to_curve.nim @@ -29,15 +29,15 @@ proc report(op, curve: string, startTime, stopTime: MonoTime, startClk, stopClk: else: echo &"{op:<40} {curve:<15} {throughput:>15.3f} ops/s {ns:>9} ns/op" -template bench(op: string, C: static Curve, iters: int, body: untyped): untyped = +template bench(op: string, Name: static Algebra, iters: int, body: untyped): untyped = measure(iters, startTime, stopTime, startClk, stopClk, body) - report(op, $C, startTime, stopTime, startClk, stopClk, iters) + report(op, $Name, startTime, stopTime, startClk, stopClk, iters) proc bench_BLS12_381_hash_to_G1(iters: int) = const dst = "BLS_SIG_BLS12381G1-SHA256-SSWU-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Jac[Fp[BLS12_381], G1] + var P: EC_ShortW_Jac[Fp[BLS12_381], G1] bench("Hash to G1 (SSWU method - Draft #14)", BLS12_381, iters): sha256.hashToCurve( @@ -52,7 +52,7 @@ proc bench_BLS12_381_hash_to_G2(iters: int) = const dst = "BLS_SIG_BLS12381G2-SHA256-SSWU-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Jac[Fp2[BLS12_381], G2] + var P: EC_ShortW_Jac[Fp2[BLS12_381], G2] bench("Hash to G2 (SSWU method - Draft #14)", BLS12_381, iters): sha256.hashToCurve( @@ -67,7 +67,7 @@ proc bench_BLS12_381_hash_to_G1_SVDW(iters: int) = const dst = "BLS_SIG_BLS12381G1-SHA256-SVDW-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Jac[Fp[BLS12_381], G1] + var P: EC_ShortW_Jac[Fp[BLS12_381], G1] bench("Hash to G1 (SVDW method)", BLS12_381, iters): sha256.hashToCurve_svdw( @@ -82,7 +82,7 @@ proc bench_BLS12_381_hash_to_G2_SVDW(iters: int) = const dst = "BLS_SIG_BLS12381G2-SHA256-SVDW-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Jac[Fp2[BLS12_381], G2] + var P: EC_ShortW_Jac[Fp2[BLS12_381], G2] bench("Hash to G2 (SVDW method)", BLS12_381, iters): sha256.hashToCurve_svdw( @@ -97,7 +97,7 @@ proc bench_BN254_Snarks_hash_to_G1(iters: int) = const dst = "BLS_SIG_BN254SNARKSG1-SHA256-SVDW-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Jac[Fp[BN254_Snarks], G1] + var P: EC_ShortW_Jac[Fp[BN254_Snarks], G1] bench("Hash to G1 (SVDW method)", BN254_Snarks, iters): sha256.hashToCurve( @@ -112,7 +112,7 @@ proc bench_BN254_Snarks_hash_to_G2(iters: int) = const dst = "BLS_SIG_BN254SNARKSG2-SHA256-SVDW-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Jac[Fp2[BN254_Snarks], G2] + var P: EC_ShortW_Jac[Fp2[BN254_Snarks], G2] bench("Hash to G2 (SVDW method)", BN254_Snarks, iters): sha256.hashToCurve( @@ -128,8 +128,8 @@ proc bench_BLS12_381_G1_jac_aff_conversion(iters: int) = const dst = "BLS_SIG_BLS12381G1-SHA256-SSWU-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Jac[Fp[BLS12_381], G1] - var Paff: ECP_ShortW_Aff[Fp[BLS12_381], G1] + var P: EC_ShortW_Jac[Fp[BLS12_381], G1] + var Paff: EC_ShortW_Aff[Fp[BLS12_381], G1] sha256.hashToCurve( k = 128, @@ -146,8 +146,8 @@ proc bench_BLS12_381_G2_jac_aff_conversion(iters: int) = const dst = "BLS_SIG_BLS12381G2-SHA256-SSWU-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Jac[Fp2[BLS12_381], G2] - var Paff: ECP_ShortW_Aff[Fp2[BLS12_381], G2] + var P: EC_ShortW_Jac[Fp2[BLS12_381], G2] + var Paff: EC_ShortW_Aff[Fp2[BLS12_381], G2] sha256.hashToCurve( k = 128, diff --git a/benchmarks/bench_pairing_template.nim b/benchmarks/bench_pairing_template.nim index 4da2d4999..2c38e43a0 100644 --- a/benchmarks/bench_pairing_template.nim +++ b/benchmarks/bench_pairing_template.nim @@ -44,14 +44,14 @@ proc report(op, curve: string, startTime, stopTime: MonoTime, startClk, stopClk: else: echo &"{op:<40} {curve:<15} {throughput:>15.3f} ops/s {ns:>9} ns/op" -template bench(op: string, C: static Curve, iters: int, body: untyped): untyped = +template bench(op: string, Name: static Algebra, iters: int, body: untyped): untyped = measure(iters, startTime, stopTime, startClk, stopClk, body) - report(op, $C, startTime, stopTime, startClk, stopClk, iters) + report(op, $Name, startTime, stopTime, startClk, stopClk, iters) func clearCofactor[F; G: static Subgroup]( - ec: var ECP_ShortW_Aff[F, G]) = + ec: var EC_ShortW_Aff[F, G]) = # For now we don't have any affine operation defined - var t {.noInit.}: ECP_ShortW_Prj[F, G] + var t {.noInit.}: EC_ShortW_Prj[F, G] t.fromAffine(ec) t.clearCofactor() ec.affine(t) @@ -60,192 +60,192 @@ func random_point*(rng: var RngState, EC: typedesc): EC {.noInit.} = result = rng.random_unsafe(EC) result.clearCofactor() -proc lineDoubleBench*(C: static Curve, iters: int) = - var line: Line[Fp2[C]] - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2]) - let P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - bench("Line double", C, iters): +proc lineDoubleBench*(Name: static Algebra, iters: int) = + var line: Line[Fp2[Name]] + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2]) + let P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + bench("Line double", Name, iters): line.line_double(T, P) -proc lineAddBench*(C: static Curve, iters: int) = - var line: Line[Fp2[C]] - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2]) +proc lineAddBench*(Name: static Algebra, iters: int) = + var line: Line[Fp2[Name]] + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2]) let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) - bench("Line add", C, iters): + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) + bench("Line add", Name, iters): line.line_add(T, Q, P) -proc mulFp12byLine_Bench*(C: static Curve, iters: int) = - var line: Line[Fp2[C]] - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2]) - let P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) +proc mulFp12byLine_Bench*(Name: static Algebra, iters: int) = + var line: Line[Fp2[Name]] + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2]) + let P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) line.line_double(T, P) - var f = rng.random_unsafe(Fp12[C]) + var f = rng.random_unsafe(Fp12[Name]) - bench("Mul 𝔽p12 by line", C, iters): + bench("Mul 𝔽p12 by line", Name, iters): f.mul_by_line(line) -proc mulLinebyLine_Bench*(C: static Curve, iters: int) = - var l0, l1: Line[Fp2[C]] - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2]) - let P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) +proc mulLinebyLine_Bench*(Name: static Algebra, iters: int) = + var l0, l1: Line[Fp2[Name]] + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2]) + let P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) l0.line_double(T, P) l1.line_double(T, P) - var f {.noInit.}: Fp12[C] + var f {.noInit.}: Fp12[Name] - bench("Mul line by line", C, iters): + bench("Mul line by line", Name, iters): f.prod_from_2_lines(l0, l1) -proc mulFp12by_prod2lines_Bench*(C: static Curve, iters: int) = - var f = rng.random_unsafe(Fp12[C]) - let g = rng.random_unsafe(Fp12[C]) +proc mulFp12by_prod2lines_Bench*(Name: static Algebra, iters: int) = + var f = rng.random_unsafe(Fp12[Name]) + let g = rng.random_unsafe(Fp12[Name]) - bench("Mul 𝔽p12 by product of 2 lines", C, iters): + bench("Mul 𝔽p12 by product of 2 lines", Name, iters): f.mul_by_prod_of_2_lines(g) -proc mulFp12_by_2lines_v1_Bench*(C: static Curve, iters: int) = - var l0, l1: Line[Fp2[C]] - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2]) - let P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) +proc mulFp12_by_2lines_v1_Bench*(Name: static Algebra, iters: int) = + var l0, l1: Line[Fp2[Name]] + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2]) + let P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) l0.line_double(T, P) l1.line_double(T, P) - var f = rng.random_unsafe(Fp12[C]) + var f = rng.random_unsafe(Fp12[Name]) - bench("mulFp12 by 2 lines v1", C, iters): + bench("mulFp12 by 2 lines v1", Name, iters): f.mul_by_line(l0) f.mul_by_line(l1) -proc mulFp12_by_2lines_v2_Bench*(C: static Curve, iters: int) = - var l0, l1: Line[Fp2[C]] - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2]) - let P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) +proc mulFp12_by_2lines_v2_Bench*(Name: static Algebra, iters: int) = + var l0, l1: Line[Fp2[Name]] + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2]) + let P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) l0.line_double(T, P) l1.line_double(T, P) - var f = rng.random_unsafe(Fp12[C]) + var f = rng.random_unsafe(Fp12[Name]) - bench("mulFp12 by 2 lines v2", C, iters): - var f2 {.noInit.}: Fp12[C] + bench("mulFp12 by 2 lines v2", Name, iters): + var f2 {.noInit.}: Fp12[Name] f2.prod_from_2_lines(l0, l1) f.mul_by_prod_of_2_lines(f2) -proc mulBench*(C: static Curve, iters: int) = - var r: Fp12[C] - let x = rng.random_unsafe(Fp12[C]) - let y = rng.random_unsafe(Fp12[C]) +proc mulBench*(Name: static Algebra, iters: int) = + var r: Fp12[Name] + let x = rng.random_unsafe(Fp12[Name]) + let y = rng.random_unsafe(Fp12[Name]) preventOptimAway(r) - bench("Multiplication 𝔽p12", C, iters): + bench("Multiplication 𝔽p12", Name, iters): r.prod(x, y) -proc sqrBench*(C: static Curve, iters: int) = - var r: Fp12[C] - let x = rng.random_unsafe(Fp12[C]) +proc sqrBench*(Name: static Algebra, iters: int) = + var r: Fp12[Name] + let x = rng.random_unsafe(Fp12[Name]) preventOptimAway(r) - bench("Squaring 𝔽p12", C, iters): + bench("Squaring 𝔽p12", Name, iters): r.square(x) -proc cyclotomicSquare_Bench*(C: static Curve, iters: int) = - var f = rng.random_unsafe(Fp12[C]) +proc cyclotomicSquare_Bench*(Name: static Algebra, iters: int) = + var f = rng.random_unsafe(Fp12[Name]) - bench("Squaring 𝔽p12 in cyclotomic subgroup", C, iters): + bench("Squaring 𝔽p12 in cyclotomic subgroup", Name, iters): f.cyclotomic_square() -proc expCurveParamBench*(C: static Curve, iters: int) = - var f = rng.random_unsafe(Fp12[C]) +proc expCurveParamBench*(Name: static Algebra, iters: int) = + var f = rng.random_unsafe(Fp12[Name]) - bench("Cyclotomic Exp by curve parameter", C, iters): + bench("Cyclotomic Exp by curve parameter", Name, iters): f.cycl_exp_by_curve_param(f) -proc cyclotomicSquareCompressed_Bench*(C: static Curve, iters: int) = - var f = rng.random_unsafe(Fp12[C]) - var g: G2345[Fp2[C]] +proc cyclotomicSquareCompressed_Bench*(Name: static Algebra, iters: int) = + var f = rng.random_unsafe(Fp12[Name]) + var g: G2345[Fp2[Name]] g.fromFpk(f) - bench("Cyclotomic Compressed Squaring 𝔽p12", C, iters): + bench("Cyclotomic Compressed Squaring 𝔽p12", Name, iters): g.cyclotomic_square_compressed() -proc cyclotomicDecompression_Bench*(C: static Curve, iters: int) = - var f = rng.random_unsafe(Fp12[C]) - var gs: array[1, G2345[Fp2[C]]] +proc cyclotomicDecompression_Bench*(Name: static Algebra, iters: int) = + var f = rng.random_unsafe(Fp12[Name]) + var gs: array[1, G2345[Fp2[Name]]] gs[0].fromFpk(f) - var g1s_ratio: array[1, tuple[g1_num, g1_den: Fp2[C]]] - var g0s, g1s: array[1, Fp2[C]] + var g1s_ratio: array[1, tuple[g1_num, g1_den: Fp2[Name]]] + var g0s, g1s: array[1, Fp2[Name]] - bench("Cyclotomic Decompression 𝔽p12", C, iters): + bench("Cyclotomic Decompression 𝔽p12", Name, iters): recover_g1(g1s_ratio[0].g1_num, g1s_ratio[0].g1_den, gs[0]) g1s.batch_ratio_g1s(g1s_ratio) g0s[0].recover_g0(g1s[0], gs[0]) -proc millerLoopBLS12Bench*(C: static Curve, iters: int) = +proc millerLoopBLS12Bench*(Name: static Algebra, iters: int) = let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) - var f: Fp12[C] - bench("Miller Loop BLS12", C, iters): + var f: Fp12[Name] + bench("Miller Loop BLS12", Name, iters): f.millerLoopGenericBLS12(Q, P) -proc millerLoopBNBench*(C: static Curve, iters: int) = +proc millerLoopBNBench*(Name: static Algebra, iters: int) = let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) - var f: Fp12[C] - bench("Miller Loop BN", C, iters): + var f: Fp12[Name] + bench("Miller Loop BN", Name, iters): f.millerLoopGenericBN(Q, P) -proc finalExpEasyBench*(C: static Curve, iters: int) = - var r = rng.random_unsafe(Fp12[C]) - bench("Final Exponentiation Easy", C, iters): +proc finalExpEasyBench*(Name: static Algebra, iters: int) = + var r = rng.random_unsafe(Fp12[Name]) + bench("Final Exponentiation Easy", Name, iters): r.finalExpEasy() -proc finalExpHardBLS12Bench*(C: static Curve, iters: int) = - var r = rng.random_unsafe(Fp12[C]) +proc finalExpHardBLS12Bench*(Name: static Algebra, iters: int) = + var r = rng.random_unsafe(Fp12[Name]) r.finalExpEasy() - bench("Final Exponentiation Hard BLS12", C, iters): + bench("Final Exponentiation Hard BLS12", Name, iters): r.finalExpHard_BLS12() -proc finalExpHardBNBench*(C: static Curve, iters: int) = - var r = rng.random_unsafe(Fp12[C]) +proc finalExpHardBNBench*(Name: static Algebra, iters: int) = + var r = rng.random_unsafe(Fp12[Name]) r.finalExpEasy() - bench("Final Exponentiation Hard BN", C, iters): + bench("Final Exponentiation Hard BN", Name, iters): r.finalExpHard_BN() -proc finalExpBLS12Bench*(C: static Curve, iters: int) = - var r = rng.random_unsafe(Fp12[C]) - bench("Final Exponentiation BLS12", C, iters): +proc finalExpBLS12Bench*(Name: static Algebra, iters: int) = + var r = rng.random_unsafe(Fp12[Name]) + bench("Final Exponentiation BLS12", Name, iters): r.finalExpEasy() r.finalExpHard_BLS12() -proc finalExpBNBench*(C: static Curve, iters: int) = - var r = rng.random_unsafe(Fp12[C]) - bench("Final Exponentiation BN", C, iters): +proc finalExpBNBench*(Name: static Algebra, iters: int) = + var r = rng.random_unsafe(Fp12[Name]) + bench("Final Exponentiation BN", Name, iters): r.finalExpEasy() r.finalExpHard_BN() -proc pairingBLS12Bench*(C: static Curve, iters: int) = +proc pairingBLS12Bench*(Name: static Algebra, iters: int) = let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) - var f: Fp12[C] - bench("Pairing BLS12", C, iters): + var f: Fp12[Name] + bench("Pairing BLS12", Name, iters): f.pairing_bls12(P, Q) -proc pairing_multisingle_BLS12Bench*(C: static Curve, N: static int, iters: int) = +proc pairing_multisingle_BLS12Bench*(Name: static Algebra, N: static int, iters: int) = var - Ps {.noInit.}: array[N, ECP_ShortW_Aff[Fp[C], G1]] - Qs {.noInit.}: array[N, ECP_ShortW_Aff[Fp2[C], G2]] + Ps {.noInit.}: array[N, EC_ShortW_Aff[Fp[Name], G1]] + Qs {.noInit.}: array[N, EC_ShortW_Aff[Fp2[Name], G2]] - GTs {.noInit.}: array[N, Fp12[C]] + GTs {.noInit.}: array[N, Fp12[Name]] for i in 0 ..< N: Ps[i] = rng.random_unsafe(typeof(Ps[0])) Qs[i] = rng.random_unsafe(typeof(Qs[0])) - var f: Fp12[C] - bench("Pairing BLS12 non-batched: " & $N, C, iters): + var f: Fp12[Name] + bench("Pairing BLS12 non-batched: " & $N, Name, iters): for i in 0 ..< N: GTs[i].pairing_bls12(Ps[i], Qs[i]) @@ -253,41 +253,41 @@ proc pairing_multisingle_BLS12Bench*(C: static Curve, N: static int, iters: int) for i in 1 ..< N: f *= GTs[i] -proc pairing_multipairing_BLS12Bench*(C: static Curve, N: static int, iters: int) = +proc pairing_multipairing_BLS12Bench*(Name: static Algebra, N: static int, iters: int) = var - Ps {.noInit.}: array[N, ECP_ShortW_Aff[Fp[C], G1]] - Qs {.noInit.}: array[N, ECP_ShortW_Aff[Fp2[C], G2]] + Ps {.noInit.}: array[N, EC_ShortW_Aff[Fp[Name], G1]] + Qs {.noInit.}: array[N, EC_ShortW_Aff[Fp2[Name], G2]] for i in 0 ..< N: Ps[i] = rng.random_unsafe(typeof(Ps[0])) Qs[i] = rng.random_unsafe(typeof(Qs[0])) - var f: Fp12[C] - bench("Pairing BLS12 batched: " & $N, C, iters): + var f: Fp12[Name] + bench("Pairing BLS12 batched: " & $N, Name, iters): f.pairing_bls12(Ps, Qs) -proc pairingBNBench*(C: static Curve, iters: int) = +proc pairingBNBench*(Name: static Algebra, iters: int) = let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) - var f: Fp12[C] - bench("Pairing BN", C, iters): + var f: Fp12[Name] + bench("Pairing BN", Name, iters): f.pairing_bn(P, Q) -proc pairing_multisingle_BNBench*(C: static Curve, N: static int, iters: int) = +proc pairing_multisingle_BNBench*(Name: static Algebra, N: static int, iters: int) = var - Ps {.noInit.}: array[N, ECP_ShortW_Aff[Fp[C], G1]] - Qs {.noInit.}: array[N, ECP_ShortW_Aff[Fp2[C], G2]] + Ps {.noInit.}: array[N, EC_ShortW_Aff[Fp[Name], G1]] + Qs {.noInit.}: array[N, EC_ShortW_Aff[Fp2[Name], G2]] - GTs {.noInit.}: array[N, Fp12[C]] + GTs {.noInit.}: array[N, Fp12[Name]] for i in 0 ..< N: Ps[i] = rng.random_unsafe(typeof(Ps[0])) Qs[i] = rng.random_unsafe(typeof(Qs[0])) - var f: Fp12[C] - bench("Pairing BN non-batched: " & $N, C, iters): + var f: Fp12[Name] + bench("Pairing BN non-batched: " & $N, Name, iters): for i in 0 ..< N: GTs[i].pairing_bn(Ps[i], Qs[i]) @@ -295,15 +295,15 @@ proc pairing_multisingle_BNBench*(C: static Curve, N: static int, iters: int) = for i in 1 ..< N: f *= GTs[i] -proc pairing_multipairing_BNBench*(C: static Curve, N: static int, iters: int) = +proc pairing_multipairing_BNBench*(Name: static Algebra, N: static int, iters: int) = var - Ps {.noInit.}: array[N, ECP_ShortW_Aff[Fp[C], G1]] - Qs {.noInit.}: array[N, ECP_ShortW_Aff[Fp2[C], G2]] + Ps {.noInit.}: array[N, EC_ShortW_Aff[Fp[Name], G1]] + Qs {.noInit.}: array[N, EC_ShortW_Aff[Fp2[Name], G2]] for i in 0 ..< N: Ps[i] = rng.random_unsafe(typeof(Ps[0])) Qs[i] = rng.random_unsafe(typeof(Qs[0])) - var f: Fp12[C] - bench("Pairing BN batched: " & $N, C, iters): + var f: Fp12[Name] + bench("Pairing BN batched: " & $N, Name, iters): f.pairing_bn(Ps, Qs) diff --git a/benchmarks/bench_summary_bls12_377.nim b/benchmarks/bench_summary_bls12_377.nim index 6042218b8..ab42b71f3 100644 --- a/benchmarks/bench_summary_bls12_377.nim +++ b/benchmarks/bench_summary_bls12_377.nim @@ -50,34 +50,34 @@ proc main() = sqrBench(Fp12[curve], Iters) invBench(Fp12[curve], Iters) separator() - addBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) + addBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Prj[Fp[curve], G1], Iters) separator() - addBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + addBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() - addBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) separator() - addBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() - scalarMulBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - scalarMulBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() - scalarMulBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - scalarMulBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + scalarMulBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + scalarMulBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() millerLoopBLS12Bench(curve, Iters) finalExpBLS12Bench(curve, Iters) pairingBLS12Bench(curve, Iters) separator() - subgroupCheckBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - subgroupCheckBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + subgroupCheckBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + subgroupCheckBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() main() diff --git a/benchmarks/bench_summary_bls12_381.nim b/benchmarks/bench_summary_bls12_381.nim index 1558de295..9f75ed405 100644 --- a/benchmarks/bench_summary_bls12_381.nim +++ b/benchmarks/bench_summary_bls12_381.nim @@ -51,27 +51,27 @@ proc main() = sqrBench(Fp12[curve], Iters) invBench(Fp12[curve], Iters) separator() - addBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) + addBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Prj[Fp[curve], G1], Iters) separator() - addBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + addBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() - addBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) separator() - addBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() - scalarMulBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - scalarMulBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() - scalarMulBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - scalarMulBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + scalarMulBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + scalarMulBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() millerLoopBLS12Bench(curve, Iters) finalExpBLS12Bench(curve, Iters) @@ -80,8 +80,8 @@ proc main() = hashToCurveBLS12381G1Bench(Iters) hashToCurveBLS12381G2Bench(Iters) separator() - subgroupCheckBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - subgroupCheckBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + subgroupCheckBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + subgroupCheckBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() main() diff --git a/benchmarks/bench_summary_bn254_nogami.nim b/benchmarks/bench_summary_bn254_nogami.nim index 34ad4cb54..45b0a561e 100644 --- a/benchmarks/bench_summary_bn254_nogami.nim +++ b/benchmarks/bench_summary_bn254_nogami.nim @@ -50,34 +50,34 @@ proc main() = sqrBench(Fp12[curve], Iters) invBench(Fp12[curve], Iters) separator() - addBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) + addBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Prj[Fp[curve], G1], Iters) separator() - addBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + addBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() - addBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) separator() - addBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() - scalarMulBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - scalarMulBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() - scalarMulBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - scalarMulBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + scalarMulBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + scalarMulBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() millerLoopBNBench(curve, Iters) finalExpBNBench(curve, Iters) pairingBNBench(curve, Iters) separator() - subgroupCheckBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - subgroupCheckBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + subgroupCheckBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + subgroupCheckBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() main() diff --git a/benchmarks/bench_summary_bn254_snarks.nim b/benchmarks/bench_summary_bn254_snarks.nim index 867188f19..c327deb69 100644 --- a/benchmarks/bench_summary_bn254_snarks.nim +++ b/benchmarks/bench_summary_bn254_snarks.nim @@ -50,27 +50,27 @@ proc main() = sqrBench(Fp12[curve], Iters) invBench(Fp12[curve], Iters) separator() - addBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) + addBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Prj[Fp[curve], G1], Iters) separator() - addBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + addBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() - addBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) separator() - addBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) - doublingBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + addBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + mixedAddBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) + doublingBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() - scalarMulBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - scalarMulBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() - scalarMulBench(ECP_ShortW_Prj[Fp2[curve], G2], Iters) - scalarMulBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + scalarMulBench(EC_ShortW_Prj[Fp2[curve], G2], Iters) + scalarMulBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() millerLoopBNBench(curve, Iters) finalExpBNBench(curve, Iters) @@ -79,8 +79,8 @@ proc main() = hashToCurveBN254SnarksG1Bench(Iters) hashToCurveBN254SnarksG2Bench(Iters) separator() - subgroupCheckBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - subgroupCheckBench(ECP_ShortW_Jac[Fp2[curve], G2], Iters) + subgroupCheckBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + subgroupCheckBench(EC_ShortW_Jac[Fp2[curve], G2], Iters) separator() main() diff --git a/benchmarks/bench_summary_pasta.nim b/benchmarks/bench_summary_pasta.nim index 67203e2c7..c25e7d8df 100644 --- a/benchmarks/bench_summary_pasta.nim +++ b/benchmarks/bench_summary_pasta.nim @@ -40,16 +40,16 @@ proc main() = invBench(Fp[curve], Iters) sqrtBench(Fp[curve], Iters) separator() - addBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) + addBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Prj[Fp[curve], G1], Iters) separator() - addBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - mixedAddBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) - doublingBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + addBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + mixedAddBench(EC_ShortW_Jac[Fp[curve], G1], Iters) + doublingBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() - scalarMulBench(ECP_ShortW_Prj[Fp[curve], G1], Iters) - scalarMulBench(ECP_ShortW_Jac[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Prj[Fp[curve], G1], Iters) + scalarMulBench(EC_ShortW_Jac[Fp[curve], G1], Iters) separator() main() diff --git a/benchmarks/bench_summary_template.nim b/benchmarks/bench_summary_template.nim index b5ba52cfc..978de6156 100644 --- a/benchmarks/bench_summary_template.nim +++ b/benchmarks/bench_summary_template.nim @@ -58,7 +58,7 @@ macro fixEllipticDisplay(T: typedesc): untyped = let instantiated = T.getTypeInst() var name = $instantiated[1][0] # EllipticEquationFormCoordinates let fieldName = $instantiated[1][1][0] - let curveName = $Curve(instantiated[1][1][1].intVal) + let curveName = $Algebra(instantiated[1][1][1].intVal) name.add "[" & fieldName & "[" & curveName & "]]" result = newLit name @@ -67,18 +67,18 @@ macro fixFieldDisplay(T: typedesc): untyped = # we get the Curve ID instead of the curve name. let instantiated = T.getTypeInst() var name = $instantiated[1][0] # Fp - name.add "[" & $Curve(instantiated[1][1].intVal) & "]" + name.add "[" & $Algebra(instantiated[1][1].intVal) & "]" result = newLit name func fixDisplay(T: typedesc): string = - when T is (ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_Aff): + when T is (EC_ShortW_Prj or EC_ShortW_Jac or EC_ShortW_Aff): fixEllipticDisplay(T) elif T is (Fp or Fp2 or Fp4 or Fp6 or Fp12): fixFieldDisplay(T) else: $T -func fixDisplay(T: Curve): string = +func fixDisplay(T: Algebra): string = $T template bench(op: string, T: typed, iters: int, body: untyped): untyped = @@ -86,9 +86,9 @@ template bench(op: string, T: typed, iters: int, body: untyped): untyped = report(op, fixDisplay(T), startTime, stopTime, startClk, stopClk, iters) func clearCofactorReference[F; G: static Subgroup]( - ec: var ECP_ShortW_Aff[F, G]) = + ec: var EC_ShortW_Aff[F, G]) = # For now we don't have any affine operation defined - var t {.noInit.}: ECP_ShortW_Prj[F, G] + var t {.noInit.}: EC_ShortW_Prj[F, G] t.fromAffine(ec) t.clearCofactorReference() ec.affine(t) @@ -142,14 +142,14 @@ proc mixedAddBench*(T: typedesc, iters: int) = var r {.noInit.}: T let P = rng.random_unsafe(T) let Q = rng.random_unsafe(T) - var Qaff: ECP_ShortW_Aff[T.F, T.G] + var Qaff: EC_ShortW_Aff[T.F, T.G] Qaff.affine(Q) block: bench("EC Mixed Addition " & G1_or_G2, T, iters): - r.madd(P, Qaff) + r.mixedSum(P, Qaff) block: bench("EC Mixed Addition vartime " & G1_or_G2, T, iters): - r.madd_vartime(P, Qaff) + r.mixedSum_vartime(P, Qaff) proc doublingBench*(T: typedesc, iters: int) = const G1_or_G2 = when T.F is Fp: "G1" else: "G2" @@ -159,7 +159,7 @@ proc doublingBench*(T: typedesc, iters: int) = r.double(P) proc scalarMulBench*(T: typedesc, iters: int) = - const bits = T.F.C.getCurveOrderBitwidth() + const bits = T.getScalarField().bits() const G1_or_G2 = when T.F is Fp: "G1" else: "G2" var r {.noInit.}: T @@ -175,52 +175,52 @@ proc scalarMulBench*(T: typedesc, iters: int) = r = P r.scalarMul_vartime(exponent) -proc millerLoopBLS12Bench*(C: static Curve, iters: int) = +proc millerLoopBLS12Bench*(Name: static Algebra, iters: int) = let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) - var f: Fp12[C] - bench("Miller Loop BLS12", C, iters): + var f: Fp12[Name] + bench("Miller Loop BLS12", Name, iters): f.millerLoopGenericBLS12(Q, P) -proc millerLoopBNBench*(C: static Curve, iters: int) = +proc millerLoopBNBench*(Name: static Algebra, iters: int) = let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) - var f: Fp12[C] - bench("Miller Loop BN", C, iters): + var f: Fp12[Name] + bench("Miller Loop BN", Name, iters): f.millerLoopGenericBN(Q, P) -proc finalExpBLS12Bench*(C: static Curve, iters: int) = - var r = rng.random_unsafe(Fp12[C]) - bench("Final Exponentiation BLS12", C, iters): +proc finalExpBLS12Bench*(Name: static Algebra, iters: int) = + var r = rng.random_unsafe(Fp12[Name]) + bench("Final Exponentiation BLS12", Name, iters): r.finalExpEasy() r.finalExpHard_BLS12() -proc finalExpBNBench*(C: static Curve, iters: int) = - var r = rng.random_unsafe(Fp12[C]) - bench("Final Exponentiation BN", C, iters): +proc finalExpBNBench*(Name: static Algebra, iters: int) = + var r = rng.random_unsafe(Fp12[Name]) + bench("Final Exponentiation BN", Name, iters): r.finalExpEasy() r.finalExpHard_BN() -proc pairingBLS12Bench*(C: static Curve, iters: int) = +proc pairingBLS12Bench*(Name: static Algebra, iters: int) = let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) - var f: Fp12[C] - bench("Pairing BLS12", C, iters): + var f: Fp12[Name] + bench("Pairing BLS12", Name, iters): f.pairing_bls12(P, Q) -proc pairingBNBench*(C: static Curve, iters: int) = +proc pairingBNBench*(Name: static Algebra, iters: int) = let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) - var f: Fp12[C] - bench("Pairing BN", C, iters): + var f: Fp12[Name] + bench("Pairing BN", Name, iters): f.pairing_bn(P, Q) proc hashToCurveBLS12381G1Bench*(iters: int) = @@ -229,7 +229,7 @@ proc hashToCurveBLS12381G1Bench*(iters: int) = # 'CryptoHash' resolution issue const dst = "BLS_SIG_BLS12381G1-SHA256-SSWU-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Prj[Fp[BLS12_381], G1] + var P: EC_ShortW_Prj[Fp[BLS12_381], G1] bench("Hash to G1 (SSWU - Draft #14)", BLS12_381, iters): sha256.hashToCurve( @@ -246,7 +246,7 @@ proc hashToCurveBLS12381G2Bench*(iters: int) = # 'CryptoHash' resolution issue const dst = "BLS_SIG_BLS12381G2-SHA256-SSWU-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Prj[Fp2[BLS12_381], G2] + var P: EC_ShortW_Prj[Fp2[BLS12_381], G2] bench("Hash to G2 (SSWU - Draft #14)", BLS12_381, iters): sha256.hashToCurve( @@ -263,7 +263,7 @@ proc hashToCurveBN254SnarksG1Bench*(iters: int) = # 'CryptoHash' resolution issue const dst = "BLS_SIG_BN254SNARKSG1-SHA256-SVDW-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Prj[Fp[BN254_Snarks], G1] + var P: EC_ShortW_Prj[Fp[BN254_Snarks], G1] bench("Hash to G1 (SVDW - Draft #14)", BN254_Snarks, iters): sha256.hashToCurve( @@ -280,7 +280,7 @@ proc hashToCurveBN254SnarksG2Bench*(iters: int) = # 'CryptoHash' resolution issue const dst = "BLS_SIG_BN254SNARKSG2-SHA256-SVDW-RO_POP_" let msg = "Mr F was here" - var P: ECP_ShortW_Prj[Fp2[BN254_Snarks], G2] + var P: EC_ShortW_Prj[Fp2[BN254_Snarks], G2] bench("Hash to G2 (SVDW - Draft #14)", BN254_Snarks, iters): sha256.hashToCurve( diff --git a/benchmarks/bench_verkle_primitives.nim b/benchmarks/bench_verkle_primitives.nim index abb1e0d3d..792cb2047 100644 --- a/benchmarks/bench_verkle_primitives.nim +++ b/benchmarks/bench_verkle_primitives.nim @@ -43,7 +43,7 @@ macro fixEllipticDisplay(T: typedesc): untyped = let instantiated = T.getTypeInst() var name = $instantiated[1][0] # EllipticEquationFormCoordinates let fieldName = $instantiated[1][1][0] - let curveName = $Curve(instantiated[1][1][1].intVal) + let curveName = $Algebra(instantiated[1][1][1].intVal) name.add "[" & fieldName & "[" & curveName & "]]" result = newLit name @@ -52,18 +52,18 @@ macro fixFieldDisplay(T: typedesc): untyped = # we get the Curve ID instead of the curve name. let instantiated = T.getTypeInst() var name = $instantiated[1][0] # Fp - name.add "[" & $Curve(instantiated[1][1].intVal) & "]" + name.add "[" & $Algebra(instantiated[1][1].intVal) & "]" result = newLit name func fixDisplay(T: typedesc): string = - when T is (ECP_TwEdwards_Prj or ECP_TwEdwards_Aff): + when T is (EC_TwEdw_Prj or EC_TwEdw_Aff): fixEllipticDisplay(T) elif T is (Fp or Fp2 or Fp4 or Fp6 or Fp12): fixFieldDisplay(T) else: $T -func fixDisplay(T: Curve): string = +func fixDisplay(T: Algebra): string = $T template bench(op: string, T: typed, iters: int, body: untyped): untyped = @@ -71,11 +71,11 @@ template bench(op: string, T: typed, iters: int, body: untyped): untyped = report(op, fixDisplay(T), startTime, stopTime, startClk, stopClk, iters) proc equalityBench*(T: typedesc, iters: int) = - when T is ECP_TwEdwards_Prj[Fp[Banderwagon]]: + when T is EC_TwEdw_Prj[Fp[Banderwagon]]: let P = Banderwagon.getGenerator() let Q = Banderwagon.getGenerator() else: - var P, Q: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var P, Q: EC_TwEdw_Prj[Fp[Banderwagon]] P.setGenerator() Q.setGenerator() bench("Banderwagon Equality ", T, iters): @@ -84,7 +84,7 @@ proc equalityBench*(T: typedesc, iters: int) = proc serializeBench*(T: typedesc, iters: int) = var bytes: array[32, byte] - var P: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var P: EC_TwEdw_Prj[Fp[Banderwagon]] P.setGenerator() for i in 0 ..< 9: P.double() @@ -93,48 +93,48 @@ proc serializeBench*(T: typedesc, iters: int) = proc deserializeBench_vartime*(T: typedesc, iters: int) = var bytes: array[32, byte] - var P: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var P: EC_TwEdw_Prj[Fp[Banderwagon]] P.setGenerator() for i in 0 ..< 6: P.double() discard bytes.serialize(P) - var Q: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var Q: EC_TwEdw_Aff[Fp[Banderwagon]] bench("Banderwagon Deserialization (vartime)", T, iters): discard Q.deserialize_vartime(bytes) proc deserializeBenchUnchecked_vartime*(T: typedesc, iters: int) = var bytes: array[32, byte] - var P: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var P: EC_TwEdw_Prj[Fp[Banderwagon]] P.setGenerator() for i in 0 ..< 6: P.double() discard bytes.serialize(P) - var Q: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var Q: EC_TwEdw_Aff[Fp[Banderwagon]] bench("Banderwagon Deserialization Unchecked (vartime)", T, iters): discard Q.deserialize_unchecked_vartime(bytes) proc serializeUncompressedBench*(T: typedesc, iters: int) = var bytes: array[64, byte] - var P: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var P: EC_TwEdw_Prj[Fp[Banderwagon]] P.setGenerator() for i in 0 ..< 6: P.double() - var Q: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var Q: EC_TwEdw_Aff[Fp[Banderwagon]] Q.affine(P) bench("Banderwagon Serialization Uncompressed from affine point", T, iters): discard bytes.serializeUncompressed(Q) proc deserializeUncompressedBench*(T: typedesc, iters: int) = var bytes: array[64, byte] - var P: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var P: EC_TwEdw_Prj[Fp[Banderwagon]] P.setGenerator() for i in 0 ..< 6: P.double() - var Q: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var Q: EC_TwEdw_Aff[Fp[Banderwagon]] Q.affine(P) discard bytes.serializeUncompressed(Q) bench("Banderwagon Deserialization Uncompressed", T, iters): @@ -142,12 +142,12 @@ proc deserializeUncompressedBench*(T: typedesc, iters: int) = proc deserializeUncompressedBenchUnchecked*(T: typedesc, iters: int) = var bytes: array[64, byte] - var P: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var P: EC_TwEdw_Prj[Fp[Banderwagon]] P.setGenerator() for i in 0 ..< 6: P.double() - var Q: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var Q: EC_TwEdw_Aff[Fp[Banderwagon]] Q.affine(P) discard bytes.serializeUncompressed(Q) bench("Banderwagon Deserialization Uncompressed Unchecked", T, iters): @@ -155,16 +155,16 @@ proc deserializeUncompressedBenchUnchecked*(T: typedesc, iters: int) = proc main() = - equalityBench(ECP_TwEdwards_Prj[Fp[Banderwagon]], Iters) + equalityBench(EC_TwEdw_Prj[Fp[Banderwagon]], Iters) separator() - serializeBench(ECP_TwEdwards_Prj[Fp[Banderwagon]], Iters) + serializeBench(EC_TwEdw_Prj[Fp[Banderwagon]], Iters) separator() - deserializeBench_vartime(ECP_TwEdwards_Prj[Fp[Banderwagon]], Iters) - deserializeBenchUnchecked_vartime(ECP_TwEdwards_Prj[Fp[Banderwagon]], Iters) + deserializeBench_vartime(EC_TwEdw_Prj[Fp[Banderwagon]], Iters) + deserializeBenchUnchecked_vartime(EC_TwEdw_Prj[Fp[Banderwagon]], Iters) separator() - serializeUncompressedBench(ECP_TwEdwards_Prj[Fp[Banderwagon]], Iters) - deserializeUncompressedBench(ECP_TwEdwards_Prj[Fp[Banderwagon]], Iters) - deserializeUncompressedBenchUnchecked(ECP_TwEdwards_Prj[Fp[Banderwagon]], Iters) + serializeUncompressedBench(EC_TwEdw_Prj[Fp[Banderwagon]], Iters) + deserializeUncompressedBench(EC_TwEdw_Prj[Fp[Banderwagon]], Iters) + deserializeUncompressedBenchUnchecked(EC_TwEdw_Prj[Fp[Banderwagon]], Iters) main() notes() diff --git a/bindings/c_curve_decls.nim b/bindings/c_curve_decls.nim index 7a5fa45ce..d3fed8ac0 100644 --- a/bindings/c_curve_decls.nim +++ b/bindings/c_curve_decls.nim @@ -8,11 +8,17 @@ import constantine/named/algebras, - constantine/curves_primitives, + constantine/[ + lowlevel_bigints, + lowlevel_fields, + lowlevel_extension_fields, + lowlevel_elliptic_curves + ] - constantine/math/extension_fields # generic sandwich +export algebras, lowlevel_bigints, lowlevel_fields, lowlevel_extension_fields, lowlevel_elliptic_curves -export algebras, curves_primitives, extension_fields +import constantine/math/extension_fields # generic sandwich +export extension_fields # Overview # ------------------------------------------------------------ @@ -300,37 +306,37 @@ template genBindingsExtFieldSqrt*(Field: untyped) = {.pop} -template genBindings_EC_ShortW_Affine*(ECP, Field: untyped) = +template genBindings_EC_ShortW_Affine*(EC, Field: untyped) = when appType == "lib": {.push noconv, dynlib, exportc, raises: [].} # No exceptions allowed else: {.push noconv, exportc, raises: [].} # No exceptions allowed # -------------------------------------------------------------------------------------- - func `ctt _ ECP _ is_eq`(P, Q: ECP): SecretBool = + func `ctt _ EC _ is_eq`(P, Q: EC): SecretBool = P == Q - func `ctt _ ECP _ is_neutral`(P: ECP): SecretBool = + func `ctt _ EC _ is_neutral`(P: EC): SecretBool = P.isNeutral() - func `ctt _ ECP _ set_neutral`(P: var ECP) = + func `ctt _ EC _ set_neutral`(P: var EC) = P.setNeutral() - func `ctt _ ECP _ ccopy`(P: var ECP, Q: ECP, ctl: SecretBool) = + func `ctt _ EC _ ccopy`(P: var EC, Q: EC, ctl: SecretBool) = P.ccopy(Q, ctl) - func `ctt _ ECP _ is_on_curve`(x, y: Field): SecretBool = - isOnCurve(x, y, ECP.G) + func `ctt _ EC _ is_on_curve`(x, y: Field): SecretBool = + isOnCurve(x, y, EC.G) - func `ctt _ ECP _ neg`(P: var ECP, Q: ECP) = + func `ctt _ EC _ neg`(P: var EC, Q: EC) = P.neg(Q) - func `ctt _ ECP _ neg_in_place`(P: var ECP) = + func `ctt _ EC _ neg_in_place`(P: var EC) = P.neg() {.pop.} -template genBindings_EC_ShortW_NonAffine*(ECP, ECP_Aff, ScalarBig, ScalarField: untyped) = +template genBindings_EC_ShortW_NonAffine*(EC, EcAff, ScalarBig, ScalarField: untyped) = # TODO: remove the need of explicit ScalarBig and ScalarField when appType == "lib": @@ -339,82 +345,82 @@ template genBindings_EC_ShortW_NonAffine*(ECP, ECP_Aff, ScalarBig, ScalarField: {.push noconv, exportc, raises: [].} # No exceptions allowed # -------------------------------------------------------------------------------------- - func `ctt _ ECP _ is_eq`(P, Q: ECP): SecretBool = + func `ctt _ EC _ is_eq`(P, Q: EC): SecretBool = P == Q - func `ctt _ ECP _ is_neutral`(P: ECP): SecretBool = + func `ctt _ EC _ is_neutral`(P: EC): SecretBool = P.isNeutral() - func `ctt _ ECP _ set_neutral`(P: var ECP) = + func `ctt _ EC _ set_neutral`(P: var EC) = P.setNeutral() - func `ctt _ ECP _ ccopy`(P: var ECP, Q: ECP, ctl: SecretBool) = + func `ctt _ EC _ ccopy`(P: var EC, Q: EC, ctl: SecretBool) = P.ccopy(Q, ctl) - func `ctt _ ECP _ neg`(P: var ECP, Q: ECP) = + func `ctt _ EC _ neg`(P: var EC, Q: EC) = P.neg(Q) - func `ctt _ ECP _ neg_in_place`(P: var ECP) = + func `ctt _ EC _ neg_in_place`(P: var EC) = P.neg() - func `ctt _ ECP _ cneg_in_place`(P: var ECP, ctl: SecretBool) = + func `ctt _ EC _ cneg_in_place`(P: var EC, ctl: SecretBool) = P.neg() - func `ctt _ ECP _ sum`(r: var ECP, P, Q: ECP) = + func `ctt _ EC _ sum`(r: var EC, P, Q: EC) = r.sum(P, Q) - func `ctt _ ECP _ add_in_place`(P: var ECP, Q: ECP) = + func `ctt _ EC _ add_in_place`(P: var EC, Q: EC) = P += Q - func `ctt _ ECP _ diff`(r: var ECP, P, Q: ECP) = + func `ctt _ EC _ diff`(r: var EC, P, Q: EC) = r.diff(P, Q) - func `ctt _ ECP _ double`(r: var ECP, P: ECP) = + func `ctt _ EC _ double`(r: var EC, P: EC) = r.double(P) - func `ctt _ ECP _ double_in_place`(P: var ECP) = + func `ctt _ EC _ double_in_place`(P: var EC) = P.double() - func `ctt _ ECP _ affine`(dst: var ECP_Aff, src: ECP) = + func `ctt _ EC _ affine`(dst: var EcAff, src: EC) = dst.affine(src) - func `ctt _ ECP _ from_affine`(dst: var ECP, src: ECP_Aff) = + func `ctt _ EC _ from_affine`(dst: var EC, src: EcAff) = dst.fromAffine(src) - func `ctt _ ECP _ batch_affine`(dst: ptr UncheckedArray[ECP_Aff], src: ptr UncheckedArray[ECP], n: csize_t) = + func `ctt _ EC _ batch_affine`(dst: ptr UncheckedArray[EcAff], src: ptr UncheckedArray[EC], n: csize_t) = dst.batchAffine(src, cast[int](n)) - func `ctt _ ECP _ scalar_mul_big_coef`( - P: var ECP, scalar: ScalarBig) = + func `ctt _ EC _ scalar_mul_big_coef`( + P: var EC, scalar: ScalarBig) = P.scalarMul(scalar) - func `ctt _ ECP _ scalar_mul_fr_coef`( - P: var ECP, scalar: ScalarField) = + func `ctt _ EC _ scalar_mul_fr_coef`( + P: var EC, scalar: ScalarField) = P.scalarMul(scalar) - func `ctt _ ECP _ scalar_mul_big_coef_vartime`( - P: var ECP, scalar: ScalarBig) = + func `ctt _ EC _ scalar_mul_big_coef_vartime`( + P: var EC, scalar: ScalarBig) = P.scalarMul_vartime(scalar) - func `ctt _ ECP _ scalar_mul_fr_coef_vartime`( - P: var ECP, scalar: ScalarField) = + func `ctt _ EC _ scalar_mul_fr_coef_vartime`( + P: var EC, scalar: ScalarField) = P.scalarMul_vartime(scalar) - func `ctt _ ECP _ multi_scalar_mul_big_coefs_vartime`( - r: var ECP, + func `ctt _ EC _ multi_scalar_mul_big_coefs_vartime`( + r: var EC, coefs: ptr UncheckedArray[ScalarBig], - points: ptr UncheckedArray[ECP_Aff], + points: ptr UncheckedArray[EcAff], len: csize_t) = r.multiScalarMul_vartime(coefs, points, cast[int](len)) - func `ctt _ ECP _ multi_scalar_mul_fr_coefs_vartime`( - r: var ECP, + func `ctt _ EC _ multi_scalar_mul_fr_coefs_vartime`( + r: var EC, coefs: ptr UncheckedArray[ScalarField], - points: ptr UncheckedArray[ECP_Aff], + points: ptr UncheckedArray[EcAff], len: csize_t)= r.multiScalarMul_vartime(coefs, points, cast[int](len)) diff --git a/bindings/c_curve_decls_parallel.nim b/bindings/c_curve_decls_parallel.nim index 84716e32b..7ba5adaa6 100644 --- a/bindings/c_curve_decls_parallel.nim +++ b/bindings/c_curve_decls_parallel.nim @@ -7,14 +7,12 @@ # at your option. This file may not be copied, modified, or distributed except according to those terms. import - constantine/named/algebras, - constantine/curves_primitives_parallel, - constantine/platforms/allocs, + constantine/lowlevel_elliptic_curves_parallel, constantine/threadpool -export curves_primitives_parallel +export lowlevel_elliptic_curves_parallel -template genParallelBindings_EC_ShortW_NonAffine*(ECP, ECP_Aff, ScalarField: untyped) = +template genParallelBindings_EC_ShortW_NonAffine*(EC, EcAff, ScalarField: untyped) = # TODO: remove the need of explicit ScalarField # For some unknown reason {.push noconv.} @@ -30,18 +28,18 @@ template genParallelBindings_EC_ShortW_NonAffine*(ECP, ECP_Aff, ScalarField: unt {.pragma: libExport, exportc, raises: [].} # No exceptions allowed # -------------------------------------------------------------------------------------- - proc `ctt _ ECP _ multi_scalar_mul_big_coefs_vartime_parallel`( + proc `ctt _ EC _ multi_scalar_mul_big_coefs_vartime_parallel`( tp: Threadpool, - r: var ECP, - coefs: ptr UncheckedArray[BigInt[ECP.F.C.getCurveOrderBitwidth()]], - points: ptr UncheckedArray[ECP_Aff], + r: var EC, + coefs: ptr UncheckedArray[BigInt[ScalarField.bits()]], + points: ptr UncheckedArray[EcAff], len: csize_t) {.libExport.} = tp.multiScalarMul_vartime_parallel(r.addr, coefs, points, cast[int](len)) - proc `ctt _ ECP _ multi_scalar_mul_fr_coefs_vartime_parallel`( + proc `ctt _ EC _ multi_scalar_mul_fr_coefs_vartime_parallel`( tp: Threadpool, - r: var ECP, + r: var EC, coefs: ptr UncheckedArray[ScalarField], - points: ptr UncheckedArray[ECP_Aff], + points: ptr UncheckedArray[EcAff], len: csize_t) {.libExport.} = tp.multiScalarMul_vartime_parallel(r.addr, coefs, points, cast[int](len)) diff --git a/bindings/lib_curves.nim b/bindings/lib_curves.nim index ed2e6128c..8a2050998 100644 --- a/bindings/lib_curves.nim +++ b/bindings/lib_curves.nim @@ -34,12 +34,12 @@ type bls12_381_fr = Fr[BLS12_381] bls12_381_fp = Fp[BLS12_381] bls12_381_fp2 = Fp2[BLS12_381] - bls12_381_g1_aff = ECP_ShortW_Aff[Fp[BLS12_381], G1] - bls12_381_g1_jac = ECP_ShortW_Jac[Fp[BLS12_381], G1] - bls12_381_g1_prj = ECP_ShortW_Prj[Fp[BLS12_381], G1] - bls12_381_g2_aff = ECP_ShortW_Aff[Fp2[BLS12_381], G2] - bls12_381_g2_jac = ECP_ShortW_Jac[Fp2[BLS12_381], G2] - bls12_381_g2_prj = ECP_ShortW_Prj[Fp2[BLS12_381], G2] + bls12_381_g1_aff = EC_ShortW_Aff[Fp[BLS12_381], G1] + bls12_381_g1_jac = EC_ShortW_Jac[Fp[BLS12_381], G1] + bls12_381_g1_prj = EC_ShortW_Prj[Fp[BLS12_381], G1] + bls12_381_g2_aff = EC_ShortW_Aff[Fp2[BLS12_381], G2] + bls12_381_g2_jac = EC_ShortW_Jac[Fp2[BLS12_381], G2] + bls12_381_g2_prj = EC_ShortW_Prj[Fp2[BLS12_381], G2] collectBindings(cBindings_bls12_381): genBindingsField(big255, bls12_381_fr) @@ -63,12 +63,12 @@ type bn254_snarks_fr = Fr[BN254_Snarks] bn254_snarks_fp = Fp[BN254_Snarks] bn254_snarks_fp2 = Fp2[BN254_Snarks] - bn254_snarks_g1_aff = ECP_ShortW_Aff[Fp[BN254_Snarks], G1] - bn254_snarks_g1_jac = ECP_ShortW_Jac[Fp[BN254_Snarks], G1] - bn254_snarks_g1_prj = ECP_ShortW_Prj[Fp[BN254_Snarks], G1] - bn254_snarks_g2_aff = ECP_ShortW_Aff[Fp2[BN254_Snarks], G2] - bn254_snarks_g2_jac = ECP_ShortW_Jac[Fp2[BN254_Snarks], G2] - bn254_snarks_g2_prj = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2] + bn254_snarks_g1_aff = EC_ShortW_Aff[Fp[BN254_Snarks], G1] + bn254_snarks_g1_jac = EC_ShortW_Jac[Fp[BN254_Snarks], G1] + bn254_snarks_g1_prj = EC_ShortW_Prj[Fp[BN254_Snarks], G1] + bn254_snarks_g2_aff = EC_ShortW_Aff[Fp2[BN254_Snarks], G2] + bn254_snarks_g2_jac = EC_ShortW_Jac[Fp2[BN254_Snarks], G2] + bn254_snarks_g2_prj = EC_ShortW_Prj[Fp2[BN254_Snarks], G2] collectBindings(cBindings_bn254_snarks): genBindingsField(big254, bn254_snarks_fr) @@ -92,9 +92,9 @@ collectBindings(cBindings_bn254_snarks_parallel): type pallas_fr = Fr[Pallas] pallas_fp = Fp[Pallas] - pallas_ec_aff = ECP_ShortW_Aff[Fp[Pallas], G1] - pallas_ec_jac = ECP_ShortW_Jac[Fp[Pallas], G1] - pallas_ec_prj = ECP_ShortW_Prj[Fp[Pallas], G1] + pallas_ec_aff = EC_ShortW_Aff[Fp[Pallas], G1] + pallas_ec_jac = EC_ShortW_Jac[Fp[Pallas], G1] + pallas_ec_prj = EC_ShortW_Prj[Fp[Pallas], G1] collectBindings(cBindings_pallas): genBindingsField(big255, pallas_fr) @@ -111,9 +111,9 @@ collectBindings(cBindings_pallas_parallel): type vesta_fr = Fr[Vesta] vesta_fp = Fp[Vesta] - vesta_ec_aff = ECP_ShortW_Aff[Fp[Vesta], G1] - vesta_ec_jac = ECP_ShortW_Jac[Fp[Vesta], G1] - vesta_ec_prj = ECP_ShortW_Prj[Fp[Vesta], G1] + vesta_ec_aff = EC_ShortW_Aff[Fp[Vesta], G1] + vesta_ec_jac = EC_ShortW_Jac[Fp[Vesta], G1] + vesta_ec_prj = EC_ShortW_Prj[Fp[Vesta], G1] collectBindings(cBindings_vesta): genBindingsField(big255, vesta_fr) diff --git a/bindings/lib_headers.nim b/bindings/lib_headers.nim index b6dba9c7e..3a91fae72 100644 --- a/bindings/lib_headers.nim +++ b/bindings/lib_headers.nim @@ -69,24 +69,24 @@ proc writeHeader_pairingFriendly(filepath: string, curve: string, modBits, order writeFile(filepath, header) -proc writeHeader(dirPath: string, C: static Curve, curve_decls: string) = - const modBits = C.getCurveBitWidth() - const orderBits = C.getCurveOrderBitWidth() - let curve = ($C).toLowerASCII() +proc writeHeader(dirPath: string, Name: static Algebra, curve_decls: string) = + const modBits = Fp[Name].bits() + const orderBits = Fr[Name].bits() + let curve = ($Name).toLowerASCII() let relPath = dirPath/"constantine"/"curves"/curve & ".h" - when C.family() == NoFamily: + when Name.family() == NoFamily: relPath.writeHeader_classicCurve(curve, modBits, orderBits, curve_decls) else: - const g2_extfield = C.getEmbeddingDegree() div 6 # All pairing-friendly curves use a sextic twist + const g2_extfield = Name.getEmbeddingDegree() div 6 # All pairing-friendly curves use a sextic twist relPath.writeHeader_pairingFriendly(curve, modBits, orderBits, curve_decls, g2_extfield) echo "Generated header: ", relPath -proc writeParallelHeader(dirPath: string, C: static Curve, curve_decls: string) = - const modBits = C.getCurveBitWidth() - const orderBits = C.getCurveOrderBitWidth() - let curve = ($C).toLowerASCII() +proc writeParallelHeader(dirPath: string, Name: static Algebra, curve_decls: string) = + const modBits = Fp[Name].bits() + const orderBits = Fr[Name].bits() + let curve = ($Name).toLowerASCII() let relPath = dirPath/"constantine"/"curves"/curve & "_parallel.h" var includes: string @@ -154,8 +154,8 @@ proc writeCurveParallelHeaders(dir: string) = staticFor i, 0, curveMappings.len: writeParallelHeader(dir, curveMappings[i][0], curveMappings[i][1]) - bigSizes.incl(curveMappings[i][0].getCurveBitWidth()) - bigSizes.incl(curveMappings[i][0].getCurveOrderBitWidth()) + bigSizes.incl(Fp[curveMappings[i][0]].bits()) + bigSizes.incl(Fr[curveMappings[i][0]].bits()) dir.writeBigIntHeader(bigSizes, cBindings_big) diff --git a/constantine.nimble b/constantine.nimble index 906086e49..e00ca8ef8 100644 --- a/constantine.nimble +++ b/constantine.nimble @@ -421,9 +421,9 @@ const testDesc: seq[tuple[path: string, useGMP: bool]] = @[ ("tests/math_elliptic_curves/t_ec_shortw_jacext_g1_add_double.nim", false), ("tests/math_elliptic_curves/t_ec_shortw_jacext_g1_mixed_add.nim", false), - # ("tests/math_elliptic_curves/t_ec_twedwards_prj_add_double", false), - ("tests/math_elliptic_curves/t_ec_twedwards_prj_mul_sanity", false), - ("tests/math_elliptic_curves/t_ec_twedwards_prj_mul_distri", false), + # ("tests/math_elliptic_curves/t_ec_twedw_prj_add_double", false), + ("tests/math_elliptic_curves/t_ec_twedw_prj_mul_sanity", false), + ("tests/math_elliptic_curves/t_ec_twedw_prj_mul_distri", false), # Elliptic curve arithmetic G2 @@ -498,7 +498,7 @@ const testDesc: seq[tuple[path: string, useGMP: bool]] = @[ ("tests/math_elliptic_curves/t_ec_shortw_jacext_g1_sum_reduce.nim", false), ("tests/math_elliptic_curves/t_ec_shortw_prj_g1_msm.nim", false), ("tests/math_elliptic_curves/t_ec_shortw_jac_g1_msm.nim", false), - ("tests/math_elliptic_curves/t_ec_twedwards_prj_msm.nim", false), + ("tests/math_elliptic_curves/t_ec_twedw_prj_msm.nim", false), # Subgroups and cofactors # ---------------------------------------------------------- diff --git a/constantine/README.md b/constantine/README.md index 1eede7383..9a5ba9ed5 100644 --- a/constantine/README.md +++ b/constantine/README.md @@ -1,6 +1,13 @@ # Constantine-backed protocols -This folder stores protocol implemented on top of Constantine. +This folder stores protocols implemented on top of Constantine. + +It also provides low-level "Named math objects" like named elliptic curves or fields. + +Warning ⚠️: + The low-level APIs have no stability guarantee. + Use high-level protocols which are designed according to a stable specs + and with misuse resistance in mind. diff --git a/constantine/commitments/eth_verkle_ipa.nim b/constantine/commitments/eth_verkle_ipa.nim index 2e8b61072..9cbf0809a 100644 --- a/constantine/commitments/eth_verkle_ipa.nim +++ b/constantine/commitments/eth_verkle_ipa.nim @@ -11,11 +11,11 @@ import ./eth_verkle_transcripts, ./protocol_quotient_check, constantine/named/algebras, - ../math/polynomials/polynomials, - ../math/[arithmetic, ec_shortweierstrass, ec_twistededwards], - ../math/elliptic/ec_multi_scalar_mul, - ../math/io/io_fields, - ../platforms/[abstractions, views] + constantine/math/polynomials/polynomials, + constantine/math/[arithmetic, ec_shortweierstrass, ec_twistededwards], + constantine/math/elliptic/ec_multi_scalar_mul, + constantine/math/io/io_fields, + constantine/platforms/[abstractions, views] ## ############################################################ ## @@ -159,7 +159,7 @@ func ipa_prove*[N, logN: static int, EcAff, F]( doAssert N.uint.isPowerOf2_vartime() doAssert logN == N.uint.log2_vartime() - when EcAff is ECP_ShortW_Aff: + when EcAff is EC_ShortW_Aff: type EC = jacobian(EcAff) else: # Twisted Edwards type EC = projective(EcAff) @@ -192,7 +192,7 @@ func ipa_prove*[N, logN: static int, EcAff, F]( transcript.absorb("output point", eval_at_challenge) # "Random" basis for challenging the inner product proof. - var w {.noInit.}: matchingOrderBigInt(F.C) + var w {.noInit.}: F.getBigInt() var Q {.noInit.}: EC Q.setGenerator() transcript.squeezeChallenge("w", w) @@ -345,7 +345,7 @@ func ipa_verify*[N, logN: static int, EcAff, F]( doAssert N.uint.isPowerOf2_vartime() doAssert logN == N.uint.log2_vartime() - when EcAff is ECP_ShortW_Aff: + when EcAff is EC_ShortW_Aff: type EC = jacobian(EcAff) else: # Twisted Edwards type EC = projective(EcAff) @@ -616,7 +616,7 @@ func sumCommitmentsAndEvalsByChallenge[N: static int, F, ECaff]( q += count eidx += 1 - when EcAff is ECP_ShortW_Aff: + when EcAff is EC_ShortW_Aff: type EC = jacobian(EcAff) else: # Twisted Edwards type EC = projective(EcAff) @@ -675,7 +675,7 @@ func ipa_multi_prove*[N, logN: static int, EcAff, F]( doAssert polys.len == commitments.len, "Polynomials and commitments inputs must be of the same length" doAssert polys.len == opening_challenges_in_domain.len, "Polynomials and opening challenges inputs must be of the same length" - when EcAff is ECP_ShortW_Aff: + when EcAff is EC_ShortW_Aff: type EC = jacobian(EcAff) else: # Twisted Edwards type EC = projective(EcAff) @@ -851,7 +851,7 @@ func ipa_multi_verify*[N, logN: static int, EcAff, F]( doAssert commitments.len == opening_challenges.len, "Commitments and opening challenges inputs must be of the same length" doAssert commitments.len == evals_at_challenges.len, "Commitments and evaluations at challenges inputs must be of the same length" - when EcAff is ECP_ShortW_Aff: + when EcAff is EC_ShortW_Aff: type EC = jacobian(EcAff) else: # Twisted Edwards type EC = projective(EcAff) diff --git a/constantine/commitments/eth_verkle_transcripts.nim b/constantine/commitments/eth_verkle_transcripts.nim index 2699a35cb..9e69c3d5d 100644 --- a/constantine/commitments/eth_verkle_transcripts.nim +++ b/constantine/commitments/eth_verkle_transcripts.nim @@ -71,7 +71,7 @@ func absorb*(ctx: var EthVerkleTranscript, label: openArray[char], v: uint64) = ctx.update(label) ctx.update(v.toBytes(bigEndian)) -func absorb*(ctx: var EthVerkleTranscript, label: openArray[char], point: ECP_TwEdwards[Fp[Banderwagon]]) = +func absorb*(ctx: var EthVerkleTranscript, label: openArray[char], point: EC_TwEdw[Fp[Banderwagon]]) = var bytes {.noInit.}: array[32, byte] bytes.serialize(point) ctx.absorb(label, bytes) @@ -81,12 +81,12 @@ func absorb*(ctx: var EthVerkleTranscript, label: openArray[char], scalar: Fr[Ba bytes.serialize_fr(scalar, littleEndian) ctx.absorb(label, bytes) -func absorb(ctx: var EthVerkleTranscript, label: openArray[char], scalar: matchingOrderBigInt(Banderwagon)) = +func absorb(ctx: var EthVerkleTranscript, label: openArray[char], scalar: Fr[Banderwagon].getBigInt()) = var bytes {.noInit.}: array[32, byte] bytes.serialize_scalar(scalar, littleEndian) ctx.absorb(label, bytes) -func squeezeChallenge*(ctx: var EthVerkleTranscript, label: openArray[char], challenge: var matchingOrderBigInt(Banderwagon)) = +func squeezeChallenge*(ctx: var EthVerkleTranscript, label: openArray[char], challenge: var Fr[Banderwagon].getBigInt()) = ## Generating a challenge based on the Fiat-Shamir transform ctx.domainSeparator(label) @@ -96,7 +96,7 @@ func squeezeChallenge*(ctx: var EthVerkleTranscript, label: openArray[char], cha var big {.noInit.}: BigInt[32*8] big.unmarshal(digest, littleEndian) - discard challenge.reduce_vartime(big, Fr[Banderwagon].fieldMod()) + discard challenge.reduce_vartime(big, Fr[Banderwagon].getModulus()) # Reset the Transcript state & absorb the freshly generated challenge ctx.init() @@ -104,6 +104,6 @@ func squeezeChallenge*(ctx: var EthVerkleTranscript, label: openArray[char], cha func squeezeChallenge*(ctx: var EthVerkleTranscript, label: openArray[char], challenge: var Fr[Banderwagon]) = ## Generating a challenge based on the Fiat-Shamir transform - var big {.noInit.}: matchingOrderBigInt(Banderwagon) + var big {.noInit.}: Fr[Banderwagon].getBigInt() ctx.squeezeChallenge(label, big) challenge.fromBig(big) diff --git a/constantine/commitments/kzg.nim b/constantine/commitments/kzg.nim index d8ac5de44..cb06ef54f 100644 --- a/constantine/commitments/kzg.nim +++ b/constantine/commitments/kzg.nim @@ -13,7 +13,7 @@ import ../math/pairings/pairings_generic, ../named/zoo_generators, ../math/polynomials/polynomials, - ../platforms/[abstractions, views], + ../platforms/abstractions, ./protocol_quotient_check ## ############################################################ @@ -174,30 +174,30 @@ import # For now we assume that the input polynomial always has the same degree # as the powers of τ -func kzg_commit*[N, bits: static int, C: static Curve]( - powers_of_tau: PolynomialEval[N, ECP_ShortW_Aff[Fp[C], G1]], - commitment: var ECP_ShortW_Aff[Fp[C], G1], +func kzg_commit*[N, bits: static int, Name: static Algebra]( + powers_of_tau: PolynomialEval[N, EC_ShortW_Aff[Fp[Name], G1]], + commitment: var EC_ShortW_Aff[Fp[Name], G1], poly: PolynomialEval[N, BigInt[bits]]) {.tags:[Alloca, HeapAlloc, Vartime].} = - var commitmentJac {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] + var commitmentJac {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] commitmentJac.multiScalarMul_vartime(poly.evals, powers_of_tau.evals) commitment.affine(commitmentJac) -func kzg_prove*[N: static int, C: static Curve]( - powers_of_tau: PolynomialEval[N, ECP_ShortW_Aff[Fp[C], G1]], - domain: PolyEvalRootsDomain[N, Fr[C]], - eval_at_challenge: var Fr[C], - proof: var ECP_ShortW_Aff[Fp[C], G1], - poly: PolynomialEval[N, Fr[C]], - opening_challenge: Fr[C]) {.tags:[Alloca, HeapAlloc, Vartime].} = +func kzg_prove*[N: static int, Name: static Algebra]( + powers_of_tau: PolynomialEval[N, EC_ShortW_Aff[Fp[Name], G1]], + domain: PolyEvalRootsDomain[N, Fr[Name]], + eval_at_challenge: var Fr[Name], + proof: var EC_ShortW_Aff[Fp[Name], G1], + poly: PolynomialEval[N, Fr[Name]], + opening_challenge: Fr[Name]) {.tags:[Alloca, HeapAlloc, Vartime].} = - let quotientPoly = allocHeapAligned(PolynomialEval[N, Fr[C]], alignment = 64) + let quotientPoly = allocHeapAligned(PolynomialEval[N, Fr[Name]], alignment = 64) domain.getQuotientPoly( quotientPoly[], eval_at_challenge, poly, opening_challenge ) - var proofJac {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] + var proofJac {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] proofJac.multiScalarMul_vartime(quotientPoly.evals, powers_of_tau.evals) proof.affine(proofJac) @@ -206,12 +206,12 @@ func kzg_prove*[N: static int, C: static Curve]( # KZG - Verifier # ------------------------------------------------------------ -func kzg_verify*[F2; C: static Curve]( - commitment: ECP_ShortW_Aff[Fp[C], G1], - opening_challenge: BigInt, # matchingOrderBigInt(C), - eval_at_challenge: BigInt, # matchingOrderBigInt(C), - proof: ECP_ShortW_Aff[Fp[C], G1], - tauG2: ECP_ShortW_Aff[F2, G2]): bool {.tags:[Alloca, Vartime].} = +func kzg_verify*[F2; Name: static Algebra]( + commitment: EC_ShortW_Aff[Fp[Name], G1], + opening_challenge: BigInt, # Fr[Name].getBigInt(), + eval_at_challenge: BigInt, # Fr[Name].getBigInt(), + proof: EC_ShortW_Aff[Fp[Name], G1], + tauG2: EC_ShortW_Aff[F2, G2]): bool {.tags:[Alloca, Vartime].} = ## Verify a short KZG proof that ``p(opening_challenge) = eval_at_challenge`` ## without doing the whole p(opening_challenge) computation # @@ -236,16 +236,16 @@ func kzg_verify*[F2; C: static Curve]( # Finally # e([proof]₁, [τ]₂ - [opening_challenge]₂) . e([commitment]₁ - [eval_at_challenge]₁, [-1]₂) = 1 var - tau_minus_challenge_G2 {.noInit.}: ECP_ShortW_Jac[F2, G2] - commitment_minus_eval_at_challenge_G1 {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] - negG2 {.noInit.}: ECP_ShortW_Aff[F2, G2] + tau_minus_challenge_G2 {.noInit.}: EC_ShortW_Jac[F2, G2] + commitment_minus_eval_at_challenge_G1 {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] + negG2 {.noInit.}: EC_ShortW_Aff[F2, G2] - tauG2Jac {.noInit.}: ECP_ShortW_Jac[F2, G2] - commitmentJac {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] + tauG2Jac {.noInit.}: EC_ShortW_Jac[F2, G2] + commitmentJac {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] tau_minus_challenge_G2.setGenerator() commitment_minus_eval_at_challenge_G1.setGenerator() - negG2.neg(C.getGenerator("G2")) + negG2.neg(Name.getGenerator("G2")) tauG2Jac.fromAffine(tauG2) commitmentJac.fromAffine(commitment) @@ -255,25 +255,25 @@ func kzg_verify*[F2; C: static Curve]( commitment_minus_eval_at_challenge_G1.scalarMul_vartime(eval_at_challenge) commitment_minus_eval_at_challenge_G1.diff(commitmentJac, commitment_minus_eval_at_challenge_G1) - var tmzG2 {.noInit.}: ECP_ShortW_Aff[F2, G2] - var cmyG1 {.noInit.}: ECP_ShortW_Aff[Fp[C], G1] + var tmzG2 {.noInit.}: EC_ShortW_Aff[F2, G2] + var cmyG1 {.noInit.}: EC_ShortW_Aff[Fp[Name], G1] tmzG2.affine(tau_minus_challenge_G2) cmyG1.affine(commitment_minus_eval_at_challenge_G1) # e([proof]₁, [τ]₂ - [opening_challenge]₂) * e([commitment]₁ - [eval_at_challenge]₁, [-1]₂) - var gt {.noInit.}: C.getGT() + var gt {.noInit.}: Name.getGT() gt.pairing([proof, cmyG1], [tmzG2, negG2]) return gt.isOne().bool() -func kzg_verify_batch*[bits: static int, F2; C: static Curve]( - commitments: ptr UncheckedArray[ECP_ShortW_Aff[Fp[C], G1]], - challenges: ptr UncheckedArray[Fr[C]], +func kzg_verify_batch*[bits: static int, F2; Name: static Algebra]( + commitments: ptr UncheckedArray[EC_ShortW_Aff[Fp[Name], G1]], + challenges: ptr UncheckedArray[Fr[Name]], evals_at_challenges: ptr UncheckedArray[BigInt[bits]], - proofs: ptr UncheckedArray[ECP_ShortW_Aff[Fp[C], G1]], - linearIndepRandNumbers: ptr UncheckedArray[Fr[C]], + proofs: ptr UncheckedArray[EC_ShortW_Aff[Fp[Name], G1]], + linearIndepRandNumbers: ptr UncheckedArray[Fr[Name]], n: int, - tauG2: ECP_ShortW_Aff[F2, G2]): bool {.tags:[HeapAlloc, Alloca, Vartime].} = + tauG2: EC_ShortW_Aff[F2, G2]): bool {.tags:[HeapAlloc, Alloca, Vartime].} = ## Verify multiple KZG proofs efficiently ## ## Parameters @@ -315,16 +315,16 @@ func kzg_verify_batch*[bits: static int, F2; C: static Curve]( # https://eprint.iacr.org/2023/033 # - https://alinush.github.io/2021/06/17/Feist-Khovratovich-technique-for-computing-KZG-proofs-fast.html - static: doAssert BigInt[bits] is matchingOrderBigInt(C) + static: doAssert BigInt[bits] is Fr[Name].getBigInt() - var sums_jac {.noInit.}: array[2, ECP_ShortW_Jac[Fp[C], G1]] + var sums_jac {.noInit.}: array[2, EC_ShortW_Jac[Fp[Name], G1]] template sum_rand_proofs: untyped = sums_jac[0] template sum_commit_minus_evals_G1: untyped = sums_jac[1] - var sum_rand_challenge_proofs {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] + var sum_rand_challenge_proofs {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] # ∑ [rᵢ][proofᵢ]₁ # --------------- - let coefs = allocHeapArrayAligned(matchingOrderBigInt(C), n, alignment = 64) + let coefs = allocHeapArrayAligned(Fr[Name].getBigInt(), n, alignment = 64) coefs.batchFromField(linearIndepRandNumbers, n) sum_rand_proofs.multiScalarMul_vartime(coefs, proofs, n) @@ -337,12 +337,12 @@ func kzg_verify_batch*[bits: static int, F2; C: static Curve]( # but it's more important to minimize memory usage especially if we want to commit with 2^26+ points # # We dealloc in reverse alloc order, to avoid leaving holes in the allocator pages. - let commits_min_evals = allocHeapArrayAligned(ECP_ShortW_Aff[Fp[C], G1], n, alignment = 64) - let commits_min_evals_jac = allocHeapArrayAligned(ECP_ShortW_Jac[Fp[C], G1], n, alignment = 64) + let commits_min_evals = allocHeapArrayAligned(EC_ShortW_Aff[Fp[Name], G1], n, alignment = 64) + let commits_min_evals_jac = allocHeapArrayAligned(EC_ShortW_Jac[Fp[Name], G1], n, alignment = 64) for i in 0 ..< n: commits_min_evals_jac[i].fromAffine(commitments[i]) - var boxed_eval {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] + var boxed_eval {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] boxed_eval.setGenerator() boxed_eval.scalarMul_vartime(evals_at_challenges[i]) commits_min_evals_jac[i].diff_vartime(commits_min_evals_jac[i], boxed_eval) @@ -354,7 +354,7 @@ func kzg_verify_batch*[bits: static int, F2; C: static Curve]( # ∑[rᵢ][zᵢ][proofᵢ]₁ # ------------------ - var tmp {.noInit.}: Fr[C] + var tmp {.noInit.}: Fr[Name] for i in 0 ..< n: tmp.prod(linearIndepRandNumbers[i], challenges[i]) coefs[i].fromField(tmp) @@ -368,13 +368,13 @@ func kzg_verify_batch*[bits: static int, F2; C: static Curve]( sum_of_sums.sum_vartime(sum_commit_minus_evals_G1, sum_rand_challenge_proofs) - var sums {.noInit.}: array[2, ECP_ShortW_Aff[Fp[C], G1]] + var sums {.noInit.}: array[2, EC_ShortW_Aff[Fp[Name], G1]] sums.batchAffine(sums_jac) - var negG2 {.noInit.}: ECP_ShortW_Aff[F2, G2] - negG2.neg(C.getGenerator("G2")) + var negG2 {.noInit.}: EC_ShortW_Aff[F2, G2] + negG2.neg(Name.getGenerator("G2")) - var gt {.noInit.}: C.getGT() + var gt {.noInit.}: Name.getGT() gt.pairing(sums, [tauG2, negG2]) return gt.isOne().bool() diff --git a/constantine/commitments/kzg_parallel.nim b/constantine/commitments/kzg_parallel.nim index d854de8ad..361fec6b3 100644 --- a/constantine/commitments/kzg_parallel.nim +++ b/constantine/commitments/kzg_parallel.nim @@ -30,26 +30,26 @@ export kzg # KZG - Prover - Lagrange basis # ------------------------------------------------------------ -proc kzg_commit_parallel*[N, bits: static int, C: static Curve]( +proc kzg_commit_parallel*[N, bits: static int, Name: static Algebra]( tp: Threadpool, - powers_of_tau: PolynomialEval[N, ECP_ShortW_Aff[Fp[C], G1]], - commitment: var ECP_ShortW_Aff[Fp[C], G1], + powers_of_tau: PolynomialEval[N, EC_ShortW_Aff[Fp[Name], G1]], + commitment: var EC_ShortW_Aff[Fp[Name], G1], poly: PolynomialEval[N, BigInt[bits]], ) = ## KZG Commit to a polynomial in Lagrange / Evaluation form ## Parallelism: This only returns when computation is fully done - var commitmentJac {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] + var commitmentJac {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] tp.multiScalarMul_vartime_parallel(commitmentJac, poly.evals, powers_of_tau.evals) commitment.affine(commitmentJac) -proc kzg_prove_parallel*[N: static int, C: static Curve]( +proc kzg_prove_parallel*[N: static int, Name: static Algebra]( tp: Threadpool, - powers_of_tau: PolynomialEval[N, ECP_ShortW_Aff[Fp[C], G1]], - domain: PolyEvalRootsDomain[N, Fr[C]], - eval_at_challenge: var Fr[C], - proof: var ECP_ShortW_Aff[Fp[C], G1], - poly: PolynomialEval[N, Fr[C]], - opening_challenge: Fr[C]) = + powers_of_tau: PolynomialEval[N, EC_ShortW_Aff[Fp[Name], G1]], + domain: PolyEvalRootsDomain[N, Fr[Name]], + eval_at_challenge: var Fr[Name], + proof: var EC_ShortW_Aff[Fp[Name], G1], + poly: PolynomialEval[N, Fr[Name]], + opening_challenge: Fr[Name]) = ## KZG prove commitment to a polynomial in Lagrange / Evaluation form ## ## Outputs: @@ -64,28 +64,28 @@ proc kzg_prove_parallel*[N: static int, C: static Curve]( # # z = opening_challenge in the following code - let quotientPoly = allocHeapAligned(PolynomialEval[N, Fr[C]], alignment = 64) + let quotientPoly = allocHeapAligned(PolynomialEval[N, Fr[Name]], alignment = 64) tp.getQuotientPoly_parallel( domain, quotientPoly[], eval_at_challenge, poly, opening_challenge ) - var proofJac {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] + var proofJac {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] tp.multiScalarMul_vartime_parallel(proofJac, quotientPoly.evals, powers_of_tau.evals) proof.affine(proofJac) freeHeapAligned(quotientPoly) -proc kzg_verify_batch_parallel*[bits: static int, F2; C: static Curve]( +proc kzg_verify_batch_parallel*[bits: static int, F2; Name: static Algebra]( tp: Threadpool, - commitments: ptr UncheckedArray[ECP_ShortW_Aff[Fp[C], G1]], - opening_challenges: ptr UncheckedArray[Fr[C]], + commitments: ptr UncheckedArray[EC_ShortW_Aff[Fp[Name], G1]], + opening_challenges: ptr UncheckedArray[Fr[Name]], evals_at_challenges: ptr UncheckedArray[BigInt[bits]], - proofs: ptr UncheckedArray[ECP_ShortW_Aff[Fp[C], G1]], - linearIndepRandNumbers: ptr UncheckedArray[Fr[C]], + proofs: ptr UncheckedArray[EC_ShortW_Aff[Fp[Name], G1]], + linearIndepRandNumbers: ptr UncheckedArray[Fr[Name]], n: int, - tauG2: ECP_ShortW_Aff[F2, G2]): bool = + tauG2: EC_ShortW_Aff[F2, G2]): bool = ## Verify multiple KZG proofs efficiently ## ## Parameters @@ -121,16 +121,16 @@ proc kzg_verify_batch_parallel*[bits: static int, F2; C: static Curve]( ## ## Parallelism: This only returns when computation is fully done - static: doAssert BigInt[bits] is matchingOrderBigInt(C) + static: doAssert BigInt[bits] is Fr[Name].getBigInt() - var sums_jac {.noInit.}: array[2, ECP_ShortW_Jac[Fp[C], G1]] + var sums_jac {.noInit.}: array[2, EC_ShortW_Jac[Fp[Name], G1]] template sum_rand_proofs: untyped = sums_jac[0] template sum_commit_minus_evals_G1: untyped = sums_jac[1] - var sum_rand_challenge_proofs {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] + var sum_rand_challenge_proofs {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] # ∑ [rᵢ][proofᵢ]₁ # --------------- - let coefs = allocHeapArrayAligned(matchingOrderBigInt(C), n, alignment = 64) + let coefs = allocHeapArrayAligned(Fr[Name].getBigInt(), n, alignment = 64) syncScope: tp.parallelFor i in 0 ..< n: @@ -149,20 +149,20 @@ proc kzg_verify_batch_parallel*[bits: static int, F2; C: static Curve]( # # We dealloc in reverse alloc order, to avoid leaving holes in the allocator pages. proc compute_sum_commitments_minus_evals(tp: Threadpool, - sum_commit_minus_evals_G1: ptr ECP_ShortW_Jac[Fp[C], G1], - commitments: ptr UncheckedArray[ECP_ShortW_Aff[Fp[C], G1]], + sum_commit_minus_evals_G1: ptr EC_ShortW_Jac[Fp[Name], G1], + commitments: ptr UncheckedArray[EC_ShortW_Aff[Fp[Name], G1]], evals_at_challenges: ptr UncheckedArray[BigInt[bits]], coefs: ptr UncheckedArray[BigInt[bits]], n: int) {.nimcall.} = - let commits_min_evals = allocHeapArrayAligned(ECP_ShortW_Aff[Fp[C], G1], n, alignment = 64) - let commits_min_evals_jac = allocHeapArrayAligned(ECP_ShortW_Jac[Fp[C], G1], n, alignment = 64) + let commits_min_evals = allocHeapArrayAligned(EC_ShortW_Aff[Fp[Name], G1], n, alignment = 64) + let commits_min_evals_jac = allocHeapArrayAligned(EC_ShortW_Jac[Fp[Name], G1], n, alignment = 64) syncScope: tp.parallelFor i in 0 ..< n: captures: {commits_min_evals_jac, commitments, evals_at_challenges} commits_min_evals_jac[i].fromAffine(commitments[i]) - var boxed_eval {.noInit.}: ECP_ShortW_Jac[Fp[C], G1] + var boxed_eval {.noInit.}: EC_ShortW_Jac[Fp[Name], G1] boxed_eval.setGenerator() boxed_eval.scalarMul_vartime(evals_at_challenges[i]) commits_min_evals_jac[i].diff_vartime(commits_min_evals_jac[i], boxed_eval) @@ -182,14 +182,14 @@ proc kzg_verify_batch_parallel*[bits: static int, F2; C: static Curve]( # ∑[rᵢ][zᵢ][proofᵢ]₁ # ------------------ proc compute_sum_rand_challenge_proofs(tp: Threadpool, - sum_rand_challenge_proofs: ptr ECP_ShortW_Jac[Fp[C], G1], - linearIndepRandNumbers: ptr UncheckedArray[Fr[C]], - opening_challenges: ptr UncheckedArray[Fr[C]], - proofs: ptr UncheckedArray[ECP_ShortW_Aff[Fp[C], G1]], + sum_rand_challenge_proofs: ptr EC_ShortW_Jac[Fp[Name], G1], + linearIndepRandNumbers: ptr UncheckedArray[Fr[Name]], + opening_challenges: ptr UncheckedArray[Fr[Name]], + proofs: ptr UncheckedArray[EC_ShortW_Aff[Fp[Name], G1]], n: int) {.nimcall.} = - let rand_coefs = allocHeapArrayAligned(matchingOrderBigInt(C), n, alignment = 64) - let rand_coefs_fr = allocHeapArrayAligned(Fr[C], n, alignment = 64) + let rand_coefs = allocHeapArrayAligned(Fr[Name].getBigInt(), n, alignment = 64) + let rand_coefs_fr = allocHeapArrayAligned(Fr[Name], n, alignment = 64) syncScope: tp.parallelFor i in 0 ..< n: @@ -221,13 +221,13 @@ proc kzg_verify_batch_parallel*[bits: static int, F2; C: static Curve]( discard sync sum_rand_proofs_fv freeHeapAligned(coefs) - var sums {.noInit.}: array[2, ECP_ShortW_Aff[Fp[C], G1]] + var sums {.noInit.}: array[2, EC_ShortW_Aff[Fp[Name], G1]] sums.batchAffine(sums_jac) - var negG2 {.noInit.}: ECP_ShortW_Aff[F2, G2] - negG2.neg(C.getGenerator("G2")) + var negG2 {.noInit.}: EC_ShortW_Aff[F2, G2] + negG2.neg(Name.getGenerator("G2")) - var gt {.noInit.}: C.getGT() + var gt {.noInit.}: Name.getGT() gt.pairing(sums, [tauG2, negG2]) return gt.isOne().bool() diff --git a/constantine/commitments_setups/ethereum_kzg_srs.nim b/constantine/commitments_setups/ethereum_kzg_srs.nim index b298c7f05..99057ce79 100644 --- a/constantine/commitments_setups/ethereum_kzg_srs.nim +++ b/constantine/commitments_setups/ethereum_kzg_srs.nim @@ -120,7 +120,7 @@ type # Trusted setup, see https://vitalik.ca/general/2022/03/14/trustedsetup.html - srs_lagrange_g1*{.align: 64.}: PolynomialEval[FIELD_ELEMENTS_PER_BLOB, ECP_ShortW_Aff[Fp[BLS12_381], G1]] + srs_lagrange_g1*{.align: 64.}: PolynomialEval[FIELD_ELEMENTS_PER_BLOB, EC_ShortW_Aff[Fp[BLS12_381], G1]] # Part of the Structured Reference String (SRS) holding the 𝔾1 points # This is used for committing to polynomials and producing an opening proof at # a random value (chosen via Fiat-Shamir heuristic) @@ -138,7 +138,7 @@ type # # Conversion can be done with a discrete Fourier transform. - srs_monomial_g2*{.align: 64.}: PolynomialCoef[KZG_SETUP_G2_LENGTH, ECP_ShortW_Aff[Fp2[BLS12_381], G2]] + srs_monomial_g2*{.align: 64.}: PolynomialCoef[KZG_SETUP_G2_LENGTH, EC_ShortW_Aff[Fp2[BLS12_381], G2]] # Part of the SRS holding the 𝔾2 points # # Referring to the 𝔾2 generator as H, we store diff --git a/constantine/curves_primitives.nim b/constantine/curves_primitives.nim deleted file mode 100644 index 9c08d0e7f..000000000 --- a/constantine/curves_primitives.nim +++ /dev/null @@ -1,249 +0,0 @@ -# Constantine -# Copyright (c) 2018-2019 Status Research & Development GmbH -# Copyright (c) 2020-Present Mamy André-Ratsimbazafy -# Licensed and distributed under either of -# * MIT license (license terms in the root directory or at http://opensource.org/licenses/MIT). -# * Apache v2 license (license terms in the root directory or at http://www.apache.org/licenses/LICENSE-2.0). -# at your option. This file may not be copied, modified, or distributed except according to those terms. - -import - ./platforms/abstractions, - ./named/algebras, - ./named/[zoo_subgroups, zoo_generators, zoo_pairings], - ./math/[ - ec_shortweierstrass, - extension_fields, - arithmetic], - ./math/elliptic/[ - ec_scalar_mul_vartime, - ec_multi_scalar_mul], - ./math/io/[io_bigints, io_fields], - ./math/isogenies/frobenius, - ./math/pairings/[ - cyclotomic_subgroups, - lines_eval, - pairings_generic], - ./hash_to_curve/hash_to_curve - -# ############################################################ -# -# Generator for low-level primitives API -# -# ############################################################ - -{.push raises: [].} # No exceptions allowed in core cryptographic operations -{.push inline.} - -# Base types -# ------------------------------------------------------------ - -export - abstractions, - algebras.Curve - -# BigInt -# ------------------------------------------------------------ - -func unmarshalBE*(dst: var BigInt, src: openarray[byte]): bool = - ## Return true on success - ## Return false if destination is too small compared to source - return dst.unmarshal(src, bigEndian) - -func marshalBE*(dst: var openarray[byte], src: BigInt): bool = - ## Return true on success - ## Return false if destination is too small compared to source - return dst.marshal(src, bigEndian) - -# Scalar field Fr and Prime Field Fp -# ------------------------------------------------------------ - -export - algebras.Fp, - algebras.Fr, - algebras.FF - -func unmarshalBE*(dst: var FF, src: openarray[byte]): bool = - ## Return true on success - ## Return false if destination is too small compared to source - var raw {.noInit.}: typeof dst.mres - let ok = raw.unmarshal(src, bigEndian) - if not ok: - return false - dst.fromBig(raw) - return true - -func marshalBE*(dst: var openarray[byte], src: FF): bool = - ## Return true on success - ## Return false if destination is too small compared to source - var raw {.noInit.}: typeof src.mres - raw.fromField(src) - return dst.marshal(raw, bigEndian) - -export arithmetic.fromBig -export arithmetic.fromField - -export arithmetic.ccopy -export arithmetic.cswap - -export arithmetic.`==` -export arithmetic.isZero -export arithmetic.isOne -export arithmetic.isMinusOne - -export arithmetic.setZero -export arithmetic.setOne -export arithmetic.setMinusOne - -export arithmetic.neg -export arithmetic.sum -export arithmetic.`+=` -export arithmetic.diff -export arithmetic.`-=` -export arithmetic.double - -export arithmetic.prod -export arithmetic.`*=` -export arithmetic.square -export arithmetic.square_repeated - -export arithmetic.csetZero -export arithmetic.csetOne -export arithmetic.cneg -export arithmetic.cadd -export arithmetic.csub - -export arithmetic.div2 -export arithmetic.inv - -export arithmetic.isSquare -export arithmetic.invsqrt -export arithmetic.sqrt -export arithmetic.sqrt_invsqrt -export arithmetic.sqrt_invsqrt_if_square -export arithmetic.sqrt_if_square -export arithmetic.invsqrt_if_square -export arithmetic.sqrt_ratio_if_square - -# Elliptic curve -# ------------------------------------------------------------ - -export - ec_shortweierstrass.Subgroup, - ec_shortweierstrass.ECP_ShortW_Aff, - ec_shortweierstrass.ECP_ShortW_Jac, - ec_shortweierstrass.ECP_ShortW_Prj, - ec_shortweierstrass.ECP_ShortW - -export ec_shortweierstrass.`==` -export ec_shortweierstrass.isNeutral -export ec_shortweierstrass.setNeutral -export ec_shortweierstrass.setGenerator -export ec_shortweierstrass.ccopy -export ec_shortweierstrass.isOnCurve -export ec_shortweierstrass.neg -export ec_shortweierstrass.cneg - -export ec_shortweierstrass.affine -export ec_shortweierstrass.fromAffine -export ec_shortweierstrass.batchAffine - -export ec_shortweierstrass.sum -export ec_shortweierstrass.`+=` -export ec_shortweierstrass.double -export ec_shortweierstrass.diff -# export ec_shortweierstrass.madd - -export ec_shortweierstrass.scalarMul -export ec_scalar_mul_vartime.scalarMul_vartime -export ec_multi_scalar_mul.multiScalarMul_vartime - -export zoo_generators.getGenerator -export zoo_subgroups.clearCofactor -export zoo_subgroups.isInSubgroup - -export frobenius.frobenius_psi - -# Extension fields -# ------------------------------------------------------------ - -export - extension_fields.Fp2 - # TODO: deal with Fp2->Fp6 vs Fp3->Fp6 and Fp2->Fp6->Fp12 vs Fp2->Fp4->Fp12 - # extension_fields.Fp4, - # extension_fields.Fp6, - # extension_fields.Fp12 - -# Generic sandwich - https://github.com/nim-lang/Nim/issues/11225 -export extension_fields.c0, extension_fields.`c0=` -export extension_fields.c1, extension_fields.`c1=` -export extension_fields.c2, extension_fields.`c2=` - -export extension_fields.setZero -export extension_fields.setOne -export extension_fields.setMinusOne - -export extension_fields.`==` -export extension_fields.isZero -export extension_fields.isOne -export extension_fields.isMinusOne - -export extension_fields.ccopy - -export extension_fields.neg -export extension_fields.`+=` -export extension_fields.`-=` -export extension_fields.double -export extension_fields.div2 -export extension_fields.sum -export extension_fields.diff -export extension_fields.conj -export extension_fields.conjneg - -export extension_fields.csetZero -export extension_fields.csetOne -export extension_fields.cneg -export extension_fields.csub -export extension_fields.cadd - -export extension_fields.`*=` -export extension_fields.prod -export extension_fields.square -export extension_fields.inv - -export extension_fields.isSquare -export extension_fields.sqrt_if_square -export extension_fields.sqrt - -export frobenius.frobenius_map - -# Pairings -# ------------------------------------------------------------ - -export - lines_eval.Line - -export lines_eval.line_double -export lines_eval.line_add -export lines_eval.mul_by_line -export lines_eval.mul_by_2_lines - -export cyclotomic_subgroups.finalExpEasy -export cyclotomic_subgroups.cyclotomic_inv -export cyclotomic_subgroups.cyclotomic_square -export cyclotomic_subgroups.cycl_sqr_repeated -export cyclotomic_subgroups.cyclotomic_exp -export cyclotomic_subgroups.isInCyclotomicSubgroup - -export zoo_pairings.cycl_exp_by_curve_param -export zoo_pairings.cycl_exp_by_curve_param_div2 -export zoo_pairings.millerLoopAddchain -export zoo_pairings.isInPairingSubgroup - -export pairings_generic.pairing -export pairings_generic.millerLoop -export pairings_generic.finalExp - -# Hashing to Elliptic Curve -# ------------------------------------------------------------ - -export hash_to_curve.hash_to_curve diff --git a/constantine/ethereum_bls_signatures.nim b/constantine/ethereum_bls_signatures.nim index 18f3ff284..bd16980e7 100644 --- a/constantine/ethereum_bls_signatures.nim +++ b/constantine/ethereum_bls_signatures.nim @@ -73,7 +73,6 @@ import export abstractions, # generic sandwich on SecretBool and SecretBool in Jacobian sumImpl - algebras, # generic sandwich on matchingBigInt extension_fields, # generic sandwich on extension field access ec_shortweierstrass, # generic sandwich on affine @@ -90,15 +89,15 @@ const DomainSeparationTag = asBytes"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_" type SecretKey* {.byref, exportc: prefix_ffi & "seckey".} = object ## A BLS12_381 secret key - raw: matchingOrderBigInt(BLS12_381) + raw: Fr[BLS12_381].getBigInt() PublicKey* {.byref, exportc: prefix_ffi & "pubkey".} = object ## A BLS12_381 public key for BLS signature schemes with public keys on G1 and signatures on G2 - raw: ECP_ShortW_Aff[Fp[BLS12_381], G1] + raw: EC_ShortW_Aff[Fp[BLS12_381], G1] Signature* {.byref, exportc: prefix_ffi & "signature".} = object ## A BLS12_381 signature for BLS signature schemes with public keys on G1 and signatures on G2 - raw: ECP_ShortW_Aff[Fp2[BLS12_381], G2] + raw: EC_ShortW_Aff[Fp2[BLS12_381], G2] cttEthBlsStatus* = enum cttEthBls_Success @@ -108,7 +107,7 @@ type cttEthBls_PointAtInfinity BatchSigAccumulator* {.byref, exportc: prefix_ffi & "batch_sig_accumulator".} = object - raw: BLSBatchSigAccumulator[Sha256Context, Fp[BLS12_381], Fp2[BLS12_381], Fp12[BLS12_381], ECP_ShortW_Jac[Fp2[BLS12_381], G2], 128] + raw: BLSBatchSigAccumulator[Sha256Context, Fp[BLS12_381], Fp2[BLS12_381], Fp12[BLS12_381], EC_ShortW_Jac[Fp2[BLS12_381], G2], 128] # Comparisons # ------------------------------------------------------------------------------------------------ diff --git a/constantine/ethereum_eip2333_bls12381_key_derivation.nim b/constantine/ethereum_eip2333_bls12381_key_derivation.nim index f0aeefdcf..e291d17d0 100644 --- a/constantine/ethereum_eip2333_bls12381_key_derivation.nim +++ b/constantine/ethereum_eip2333_bls12381_key_derivation.nim @@ -22,7 +22,7 @@ import {.push raises: [], checks: off.} # No exceptions -type SecretKey = matchingOrderBigInt(BLS12_381) +type SecretKey = Fr[BLS12_381].getBigInt() func hkdf_mod_r(secretKey: var SecretKey, ikm: openArray[byte], key_info: openArray[byte]) = ## Ethereum 2 EIP-2333, extracts this from the BLS signature schemes @@ -61,14 +61,14 @@ func hkdf_mod_r(secretKey: var SecretKey, ikm: openArray[byte], key_info: openAr # With R ≡ (2^WordBitWidth)^numWords (mod M) # redc2xMont(a) computes a/R # mulMont(a, b) computes a.b.R⁻¹ - var seckeyDbl{.noInit.}: BigInt[2 * BLS12_381.getCurveOrderBitWidth()] + var seckeyDbl{.noInit.}: BigInt[2 * Fr[BLS12_381].bits()] seckeyDbl.unmarshal(okm, bigEndian) - # secretKey.reduce(seckeyDbl, BLS12_381.getCurveOrder()) + # secretKey.reduce(seckeyDbl, Fr[BLS12_381].getModulus()) secretKey.limbs.redc2xMont(seckeyDbl.limbs, # seckey/R - BLS12_381.getCurveOrder().limbs, Fr[BLS12_381].getNegInvModWord(), + Fr[BLS12_381].getModulus().limbs, Fr[BLS12_381].getNegInvModWord(), Fr[BLS12_381].getSpareBits()) secretKey.limbs.mulMont(secretKey.limbs, Fr[BLS12_381].getR2modP().limbs, # (seckey/R) * R² * R⁻¹ = seckey - BLS12_381.getCurveOrder().limbs, Fr[BLS12_381].getNegInvModWord(), + Fr[BLS12_381].getModulus().limbs, Fr[BLS12_381].getNegInvModWord(), Fr[BLS12_381].getSpareBits()) if bool secretKey.isZero(): diff --git a/constantine/ethereum_eip4844_kzg.nim b/constantine/ethereum_eip4844_kzg.nim index 451c52508..bbff67d95 100644 --- a/constantine/ethereum_eip4844_kzg.nim +++ b/constantine/ethereum_eip4844_kzg.nim @@ -76,9 +76,9 @@ type # Hence we don't need to explicitly use ptr Blob # to avoid a 4096 byte copy on {.exportc.} procs. - KZGCommitment* = distinct ECP_ShortW_Aff[Fp[BLS12_381], G1] + KZGCommitment* = distinct EC_ShortW_Aff[Fp[BLS12_381], G1] - KZGProof* = distinct ECP_ShortW_Aff[Fp[BLS12_381], G1] + KZGProof* = distinct EC_ShortW_Aff[Fp[BLS12_381], G1] cttEthKzgStatus* = enum cttEthKzg_Success @@ -105,21 +105,21 @@ func fromDigest(dst: var Fr[BLS12_381], src: array[32, byte]) = # and Fr[BLS12_381] being built on top of BigInt[255] # we use the low-level getMont instead of 'fromBig' getMont(dst.mres.limbs, scalar.limbs, - Fr[BLS12_381].fieldMod().limbs, + Fr[BLS12_381].getModulus().limbs, Fr[BLS12_381].getR2modP().limbs, Fr[BLS12_381].getNegInvModWord(), Fr[BLS12_381].getSpareBits()) -func fromDigest(dst: var matchingOrderBigInt(BLS12_381), src: array[32, byte]) = +func fromDigest(dst: var Fr[BLS12_381].getBigInt(), src: array[32, byte]) = ## Convert a SHA256 digest to an element in the scalar field Fr[BLS12-381] ## hash_to_bls_field: https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.1/specs/deneb/polynomial-commitments.md#hash_to_bls_field var scalar {.noInit.}: BigInt[256] scalar.unmarshal(src, bigEndian) - discard dst.reduce_vartime(scalar, Fr[BLS12_381].fieldMod()) + discard dst.reduce_vartime(scalar, Fr[BLS12_381].getModulus()) func fiatShamirChallenge( - dst: ptr (Fr[BLS12_381] or matchingOrderBigInt(BLS12_381)), + dst: ptr (Fr[BLS12_381] or Fr[BLS12_381].getBigInt()), blob: Blob, commitmentBytes: array[BYTES_PER_COMMITMENT, byte]) = ## Compute a Fiat-Shamir challenge @@ -143,7 +143,7 @@ func fiatShamirChallenge( # Conversion # ------------------------------------------------------------ -func bytes_to_bls_bigint(dst: var matchingOrderBigInt(BLS12_381), src: array[32, byte]): CttCodecScalarStatus = +func bytes_to_bls_bigint(dst: var Fr[BLS12_381].getBigInt(), src: array[32, byte]): CttCodecScalarStatus = ## Convert untrusted bytes to a trusted and validated BLS scalar field element. ## This function does not accept inputs greater than the BLS modulus. let status = dst.deserialize_scalar(src) @@ -154,7 +154,7 @@ func bytes_to_bls_bigint(dst: var matchingOrderBigInt(BLS12_381), src: array[32, func bytes_to_bls_field(dst: var Fr[BLS12_381], src: array[32, byte]): CttCodecScalarStatus = ## Convert untrusted bytes to a trusted and validated BLS scalar field element. ## This function does not accept inputs greater than the BLS modulus. - var scalar {.noInit.}: matchingOrderBigInt(BLS12_381) + var scalar {.noInit.}: Fr[BLS12_381].getBigInt() let status = scalar.deserialize_scalar(src) if status notin {cttCodecScalar_Success, cttCodecScalar_Zero}: return status @@ -178,7 +178,7 @@ func bytes_to_kzg_proof(dst: var KZGProof, src: array[48, byte]): CttCodecEccSta return status func blob_to_bigint_polynomial( - dst: ptr PolynomialEval[FIELD_ELEMENTS_PER_BLOB, matchingOrderBigInt(BLS12_381)], + dst: ptr PolynomialEval[FIELD_ELEMENTS_PER_BLOB, Fr[BLS12_381].getBigInt()], blob: Blob): CttCodecScalarStatus = ## Convert a blob to a polynomial in evaluation form @@ -288,12 +288,12 @@ func blob_to_kzg_commitment*( ## ## with proof = [(p(τ) - p(z)) / (τ-z)]₁ - let poly = allocHeapAligned(PolynomialEval[FIELD_ELEMENTS_PER_BLOB, matchingOrderBigInt(BLS12_381)], 64) + let poly = allocHeapAligned(PolynomialEval[FIELD_ELEMENTS_PER_BLOB, Fr[BLS12_381].getBigInt()], 64) block HappyPath: check HappyPath, poly.blob_to_bigint_polynomial(blob) - var r {.noinit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] + var r {.noinit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] kzg_commit(ctx.srs_lagrange_g1, r, poly[]) discard dst.serialize_g1_compressed(r) @@ -334,7 +334,7 @@ func compute_kzg_proof*( # KZG Prove var y {.noInit.}: Fr[BLS12_381] # y = p(z), eval at opening_challenge z - var proof {.noInit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] # [proof]₁ = [(p(τ) - p(z)) / (τ-z)]₁ + var proof {.noInit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] # [proof]₁ = [(p(τ) - p(z)) / (τ-z)]₁ kzg_prove( ctx.srs_lagrange_g1, @@ -361,18 +361,18 @@ func verify_kzg_proof*( var commitment {.noInit.}: KZGCommitment checkReturn commitment.bytes_to_kzg_commitment(commitment_bytes) - var opening_challenge {.noInit.}: matchingOrderBigInt(BLS12_381) + var opening_challenge {.noInit.}: Fr[BLS12_381].getBigInt() checkReturn opening_challenge.bytes_to_bls_bigint(z_bytes) - var eval_at_challenge {.noInit.}: matchingOrderBigInt(BLS12_381) + var eval_at_challenge {.noInit.}: Fr[BLS12_381].getBigInt() checkReturn eval_at_challenge.bytes_to_bls_bigint(y_bytes) var proof {.noInit.}: KZGProof checkReturn proof.bytes_to_kzg_proof(proof_bytes) - let verif = kzg_verify(ECP_ShortW_Aff[Fp[BLS12_381], G1](commitment), + let verif = kzg_verify(EC_ShortW_Aff[Fp[BLS12_381], G1](commitment), opening_challenge, eval_at_challenge, - ECP_ShortW_Aff[Fp[BLS12_381], G1](proof), + EC_ShortW_Aff[Fp[BLS12_381], G1](proof), ctx.srs_monomial_g2.coefs[1]) if verif: return cttEthKzg_Success @@ -403,7 +403,7 @@ func compute_blob_kzg_proof*( # KZG Prove var y {.noInit.}: Fr[BLS12_381] # y = p(z), eval at opening_challenge z - var proof {.noInit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] # [proof]₁ = [(p(τ) - p(z)) / (τ-z)]₁ + var proof {.noInit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] # [proof]₁ = [(p(τ) - p(z)) / (τ-z)]₁ kzg_prove( ctx.srs_lagrange_g1, @@ -445,9 +445,9 @@ func verify_blob_kzg_proof*( ctx.domain.evalPolyAt(eval_at_challenge, poly[], opening_challenge) # KZG verification - let verif = kzg_verify(ECP_ShortW_Aff[Fp[BLS12_381], G1](commitment), + let verif = kzg_verify(EC_ShortW_Aff[Fp[BLS12_381], G1](commitment), opening_challenge.toBig(), eval_at_challenge.toBig(), - ECP_ShortW_Aff[Fp[BLS12_381], G1](proof), + EC_ShortW_Aff[Fp[BLS12_381], G1](proof), ctx.srs_monomial_g2.coefs[1]) if verif: result = cttEthKzg_Success @@ -484,7 +484,7 @@ func verify_blob_kzg_proof_batch*( let commitments = allocHeapArrayAligned(KZGCommitment, n, alignment = 64) let opening_challenges = allocHeapArrayAligned(Fr[BLS12_381], n, alignment = 64) - let evals_at_challenges = allocHeapArrayAligned(matchingOrderBigInt(BLS12_381), n, alignment = 64) + let evals_at_challenges = allocHeapArrayAligned(Fr[BLS12_381].getBigInt(), n, alignment = 64) let proofs = allocHeapArrayAligned(KZGProof, n, alignment = 64) let poly = allocHeapAligned(PolynomialEval[FIELD_ELEMENTS_PER_BLOB, Fr[BLS12_381]], alignment = 64) @@ -523,7 +523,7 @@ func verify_blob_kzg_proof_batch*( let linearIndepRandNumbers = allocHeapArrayAligned(Fr[BLS12_381], n, alignment = 64) linearIndepRandNumbers.computePowers(randomBlindingFr, n) - type EcAffArray = ptr UncheckedArray[ECP_ShortW_Aff[Fp[BLS12_381], G1]] + type EcAffArray = ptr UncheckedArray[EC_ShortW_Aff[Fp[BLS12_381], G1]] let verif = kzg_verify_batch( cast[EcAffArray](commitments), opening_challenges, diff --git a/constantine/ethereum_eip4844_kzg_parallel.nim b/constantine/ethereum_eip4844_kzg_parallel.nim index 2cbd2beb2..23fd8defd 100644 --- a/constantine/ethereum_eip4844_kzg_parallel.nim +++ b/constantine/ethereum_eip4844_kzg_parallel.nim @@ -46,7 +46,7 @@ import ./zoo_exports proc blob_to_bigint_polynomial_parallel( tp: Threadpool, - dst: ptr PolynomialEval[FIELD_ELEMENTS_PER_BLOB, matchingOrderBigInt(BLS12_381)], + dst: ptr PolynomialEval[FIELD_ELEMENTS_PER_BLOB, Fr[BLS12_381].getBigInt()], blob: Blob): CttCodecScalarStatus = ## Convert a blob to a polynomial in evaluation form mixin globalStatus @@ -144,12 +144,12 @@ proc blob_to_kzg_commitment_parallel*( ## ## with proof = [(p(τ) - p(z)) / (τ-z)]₁ - let poly = allocHeapAligned(PolynomialEval[FIELD_ELEMENTS_PER_BLOB, matchingOrderBigInt(BLS12_381)], 64) + let poly = allocHeapAligned(PolynomialEval[FIELD_ELEMENTS_PER_BLOB, Fr[BLS12_381].getBigInt()], 64) block HappyPath: check HappyPath, tp.blob_to_bigint_polynomial_parallel(poly, blob) - var r {.noinit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] + var r {.noinit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] tp.kzg_commit_parallel(ctx.srs_lagrange_g1, r, poly[]) discard dst.serialize_g1_compressed(r) @@ -191,7 +191,7 @@ proc compute_kzg_proof_parallel*( # KZG Prove var y {.noInit.}: Fr[BLS12_381] # y = p(z), eval at challenge z - var proof {.noInit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] # [proof]₁ = [(p(τ) - p(z)) / (τ-z)]₁ + var proof {.noInit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] # [proof]₁ = [(p(τ) - p(z)) / (τ-z)]₁ tp.kzg_prove_parallel( ctx.srs_lagrange_g1, @@ -235,7 +235,7 @@ proc compute_blob_kzg_proof_parallel*( # KZG Prove var y {.noInit.}: Fr[BLS12_381] # y = p(z), eval at opening challenge z - var proof {.noInit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] # [proof]₁ = [(p(τ) - p(z)) / (τ-z)]₁ + var proof {.noInit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] # [proof]₁ = [(p(τ) - p(z)) / (τ-z)]₁ tp.kzg_prove_parallel( ctx.srs_lagrange_g1, @@ -285,9 +285,9 @@ proc verify_blob_kzg_proof_parallel*( tp.evalPolyAt_parallel(ctx.domain, eval_at_challenge, poly[], opening_challenge) # KZG verification - let verif = kzg_verify(ECP_ShortW_Aff[Fp[BLS12_381], G1](commitment), + let verif = kzg_verify(EC_ShortW_Aff[Fp[BLS12_381], G1](commitment), opening_challenge.toBig(), eval_at_challenge.toBig(), - ECP_ShortW_Aff[Fp[BLS12_381], G1](proof), + EC_ShortW_Aff[Fp[BLS12_381], G1](proof), ctx.srs_monomial_g2.coefs[1]) if verif: result = cttEthKzg_Success @@ -327,7 +327,7 @@ proc verify_blob_kzg_proof_batch_parallel*( let commitments = allocHeapArrayAligned(KZGCommitment, n, alignment = 64) let opening_challenges = allocHeapArrayAligned(Fr[BLS12_381], n, alignment = 64) - let evals_at_challenges = allocHeapArrayAligned(matchingOrderBigInt(BLS12_381), n, alignment = 64) + let evals_at_challenges = allocHeapArrayAligned(Fr[BLS12_381].getBigInt(), n, alignment = 64) let proofs = allocHeapArrayAligned(KZGProof, n, alignment = 64) let polys = allocHeapArrayAligned(PolynomialEval[FIELD_ELEMENTS_PER_BLOB, Fr[BLS12_381]], n, alignment = 64) @@ -398,7 +398,7 @@ proc verify_blob_kzg_proof_batch_parallel*( let linearIndepRandNumbers = allocHeapArrayAligned(Fr[BLS12_381], n, alignment = 64) linearIndepRandNumbers.computePowers(randomBlindingFr, n) - type EcAffArray = ptr UncheckedArray[ECP_ShortW_Aff[Fp[BLS12_381], G1]] + type EcAffArray = ptr UncheckedArray[EC_ShortW_Aff[Fp[BLS12_381], G1]] let verif = tp.kzg_verify_batch_parallel( cast[EcAffArray](commitments), opening_challenges, diff --git a/constantine/ethereum_evm_precompiles.nim b/constantine/ethereum_evm_precompiles.nim index cfabaecfd..69a32bcbc 100644 --- a/constantine/ethereum_evm_precompiles.nim +++ b/constantine/ethereum_evm_precompiles.nim @@ -196,8 +196,8 @@ func eth_evm_modexp*(r: var openArray[byte], inputs: openArray[byte]): CttEVMSta # Elliptic Curves # ---------------------------------------------------------------- -func parseRawUint[C: static Curve]( - dst: var Fp[C], +func parseRawUint[Name: static Algebra]( + dst: var Fp[Name], src: openarray[byte]): CttEVMStatus = ## Parse an unsigned integer from its canonical ## big-endian or little-endian unsigned representation @@ -205,17 +205,17 @@ func parseRawUint[C: static Curve]( ## ## Return false if the integer is larger than the field modulus. ## Returns true on success. - var big {.noInit.}: matchingBigInt(C) + var big {.noInit.}: Fp[Name].getBigInt() big.unmarshal(src, bigEndian) - if not bool(big < Mod(C)): + if not bool(big < Fp[Name].getModulus()): return cttEVM_IntLargerThanModulus dst.fromBig(big) return cttEVM_Success -func fromRawCoords[C: static Curve, G: static Subgroup]( - dst: var ECP_ShortW_Aff[Fp[C], G], +func fromRawCoords[Name: static Algebra, G: static Subgroup]( + dst: var EC_ShortW_Aff[Fp[Name], G], x, y: openarray[byte], checkSubgroup: bool): CttEVMStatus = @@ -248,8 +248,8 @@ func fromRawCoords[C: static Curve, G: static Subgroup]( return cttEVM_Success -func fromRawCoords[C: static Curve]( - dst: var ECP_ShortW_Aff[Fp2[C], G2], +func fromRawCoords[Name: static Algebra]( + dst: var EC_ShortW_Aff[Fp2[Name], G2], x0, x1, y0, y1: openarray[byte], checkSubgroup: bool): CttEVMStatus = @@ -289,23 +289,23 @@ func fromRawCoords[C: static Curve]( return cttEVM_Success -func fromRawCoords[C: static Curve, G: static Subgroup]( - dst: var ECP_ShortW_Jac[Fp[C], G], +func fromRawCoords[Name: static Algebra, G: static Subgroup]( + dst: var EC_ShortW_Jac[Fp[Name], G], x, y: openarray[byte], checkSubgroup: bool): CttEVMStatus = - var aff{.noInit.}: ECP_ShortW_Aff[Fp[C], G] + var aff{.noInit.}: EC_ShortW_Aff[Fp[Name], G] let status = aff.fromRawCoords(x, y, checkSubgroup) if status != cttEVM_Success: return status dst.fromAffine(aff) -func fromRawCoords[C: static Curve, G: static Subgroup]( - dst: var ECP_ShortW_Jac[Fp2[C], G], +func fromRawCoords[Name: static Algebra, G: static Subgroup]( + dst: var EC_ShortW_Jac[Fp2[Name], G], x0, x1, y0, y1: openarray[byte], checkSubgroup: bool): CttEVMStatus = - var aff{.noInit.}: ECP_ShortW_Aff[Fp2[C], G] + var aff{.noInit.}: EC_ShortW_Aff[Fp2[Name], G] let status = aff.fromRawCoords(x0, x1, y0, y1, checkSubgroup) if status != cttEVM_Success: return status @@ -345,7 +345,7 @@ func eth_evm_bn254_g1add*(r: var openArray[byte], inputs: openarray[byte]): CttE var padded: array[128, byte] padded.rawCopy(0, inputs, 0, min(inputs.len, padded.len)) - var P{.noInit.}, Q{.noInit.}, R{.noInit.}: ECP_ShortW_Jac[Fp[BN254_Snarks], G1] + var P{.noInit.}, Q{.noInit.}, R{.noInit.}: EC_ShortW_Jac[Fp[BN254_Snarks], G1] let statusP = P.fromRawCoords( x = padded.toOpenArray(0, 31), @@ -362,7 +362,7 @@ func eth_evm_bn254_g1add*(r: var openArray[byte], inputs: openarray[byte]): CttE return statusQ R.sum_vartime(P, Q) - var aff{.noInit.}: ECP_ShortW_Aff[Fp[BN254_Snarks], G1] + var aff{.noInit.}: EC_ShortW_Aff[Fp[BN254_Snarks], G1] aff.affine(R) r.toOpenArray(0, 31).marshal(aff.x, bigEndian) @@ -403,7 +403,7 @@ func eth_evm_bn254_g1mul*(r: var openArray[byte], inputs: openarray[byte]): CttE var padded: array[96, byte] padded.rawCopy(0, inputs, 0, min(inputs.len, padded.len)) - var P{.noInit.}: ECP_ShortW_Jac[Fp[BN254_Snarks], G1] + var P{.noInit.}: EC_ShortW_Jac[Fp[BN254_Snarks], G1] let statusP = P.fromRawCoords( x = padded.toOpenArray(0, 31), @@ -426,7 +426,7 @@ func eth_evm_bn254_g1mul*(r: var openArray[byte], inputs: openarray[byte]): CttE # Due to mismatch between the BigInt[256] input and the rest being BigInt[254] # we use the low-level getMont instead of 'fromBig' getMont(smod.mres.limbs, s.limbs, - Fr[BN254_Snarks].fieldMod().limbs, + Fr[BN254_Snarks].getModulus().limbs, Fr[BN254_Snarks].getR2modP().limbs, Fr[BN254_Snarks].getNegInvModWord(), Fr[BN254_Snarks].getSpareBits()) @@ -434,7 +434,7 @@ func eth_evm_bn254_g1mul*(r: var openArray[byte], inputs: openarray[byte]): CttE else: P.scalarMul_vartime(s) - var aff{.noInit.}: ECP_ShortW_Aff[Fp[BN254_Snarks], G1] + var aff{.noInit.}: EC_ShortW_Aff[Fp[BN254_Snarks], G1] aff.affine(P) r.toOpenArray(0, 31).marshal(aff.x, bigEndian) @@ -478,8 +478,8 @@ func eth_evm_bn254_ecpairingcheck*( r[r.len-1] = byte 1 return cttEVM_Success - var P{.noInit.}: ECP_ShortW_Aff[Fp[BN254_Snarks], G1] - var Q{.noInit.}: ECP_ShortW_Aff[Fp2[BN254_Snarks], G2] + var P{.noInit.}: EC_ShortW_Aff[Fp[BN254_Snarks], G1] + var Q{.noInit.}: EC_ShortW_Aff[Fp2[BN254_Snarks], G2] var acc {.noInit.}: MillerAccumulator[Fp[BN254_Snarks], Fp2[BN254_Snarks], Fp12[BN254_Snarks]] acc.init() @@ -562,7 +562,7 @@ func eth_evm_bls12381_g1add*(r: var openArray[byte], inputs: openarray[byte]): C # Note that it has not been confirmed whether the complete formulas for projective coordinates # return correct result if input is NOT in the correct subgroup. # Hence we use the Jacobian vartime formulas. - var P{.noInit.}, Q{.noInit.}, R{.noInit.}: ECP_ShortW_Jac[Fp[BLS12_381], G1] + var P{.noInit.}, Q{.noInit.}, R{.noInit.}: EC_ShortW_Jac[Fp[BLS12_381], G1] let statusP = P.fromRawCoords( x = inputs.toOpenArray( 0, 64-1), @@ -579,7 +579,7 @@ func eth_evm_bls12381_g1add*(r: var openArray[byte], inputs: openarray[byte]): C return statusQ R.sum_vartime(P, Q) - var aff{.noInit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] + var aff{.noInit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] aff.affine(R) r.toOpenArray(0, 64-1).marshal(aff.x, bigEndian) @@ -622,7 +622,7 @@ func eth_evm_bls12381_g2add*(r: var openArray[byte], inputs: openarray[byte]): C # Note that it has not been confirmed whether the complete formulas for projective coordinates # return correct result if input is NOT in the correct subgroup. # Hence we use the Jacobian vartime formulas. - var P{.noInit.}, Q{.noInit.}, R{.noInit.}: ECP_ShortW_Jac[Fp2[BLS12_381], G2] + var P{.noInit.}, Q{.noInit.}, R{.noInit.}: EC_ShortW_Jac[Fp2[BLS12_381], G2] let statusP = P.fromRawCoords( x0 = inputs.toOpenArray( 0, 64-1), @@ -643,7 +643,7 @@ func eth_evm_bls12381_g2add*(r: var openArray[byte], inputs: openarray[byte]): C return statusQ R.sum_vartime(P, Q) - var aff{.noInit.}: ECP_ShortW_Aff[Fp2[BLS12_381], G2] + var aff{.noInit.}: EC_ShortW_Aff[Fp2[BLS12_381], G2] aff.affine(R) r.toOpenArray( 0, 64-1).marshal(aff.x.c0, bigEndian) @@ -683,7 +683,7 @@ func eth_evm_bls12381_g1mul*(r: var openArray[byte], inputs: openarray[byte]): C if r.len != 128: return cttEVM_InvalidOutputSize - var P{.noInit.}: ECP_ShortW_Jac[Fp[BLS12_381], G1] + var P{.noInit.}: EC_ShortW_Jac[Fp[BLS12_381], G1] let statusP = P.fromRawCoords( x = inputs.toOpenArray( 0, 64-1), @@ -705,7 +705,7 @@ func eth_evm_bls12381_g1mul*(r: var openArray[byte], inputs: openarray[byte]): C # Due to mismatch between the BigInt[256] input and the rest being BigInt[255] # we use the low-level getMont instead of 'fromBig' getMont(smod.mres.limbs, s.limbs, - Fr[BLS12_381].fieldMod().limbs, + Fr[BLS12_381].getModulus().limbs, Fr[BLS12_381].getR2modP().limbs, Fr[BLS12_381].getNegInvModWord(), Fr[BLS12_381].getSpareBits()) @@ -713,7 +713,7 @@ func eth_evm_bls12381_g1mul*(r: var openArray[byte], inputs: openarray[byte]): C else: P.scalarMul_vartime(s) - var aff{.noInit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] + var aff{.noInit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] aff.affine(P) r.toOpenArray( 0, 64-1).marshal(aff.x, bigEndian) @@ -751,7 +751,7 @@ func eth_evm_bls12381_g2mul*(r: var openArray[byte], inputs: openarray[byte]): C if r.len != 256: return cttEVM_InvalidOutputSize - var P{.noInit.}: ECP_ShortW_Jac[Fp2[BLS12_381], G2] + var P{.noInit.}: EC_ShortW_Jac[Fp2[BLS12_381], G2] let statusP = P.fromRawCoords( x0 = inputs.toOpenArray( 0, 64-1), @@ -775,7 +775,7 @@ func eth_evm_bls12381_g2mul*(r: var openArray[byte], inputs: openarray[byte]): C # Due to mismatch between the BigInt[256] input and the rest being BigInt[255] # we use the low-level getMont instead of 'fromBig' getMont(smod.mres.limbs, s.limbs, - Fr[BLS12_381].fieldMod().limbs, + Fr[BLS12_381].getModulus().limbs, Fr[BLS12_381].getR2modP().limbs, Fr[BLS12_381].getNegInvModWord(), Fr[BLS12_381].getSpareBits()) @@ -783,7 +783,7 @@ func eth_evm_bls12381_g2mul*(r: var openArray[byte], inputs: openarray[byte]): C else: P.scalarMul_vartime(s) - var aff{.noInit.}: ECP_ShortW_Aff[Fp2[BLS12_381], G2] + var aff{.noInit.}: EC_ShortW_Aff[Fp2[BLS12_381], G2] aff.affine(P) r.toOpenArray( 0, 64-1).marshal(aff.x.c0, bigEndian) @@ -828,7 +828,7 @@ func eth_evm_bls12381_g1msm*(r: var openArray[byte], inputs: openarray[byte]): C let N = inputs.len div 160 let coefs_big = allocHeapArrayAligned(BigInt[255], N, alignment = 64) - let points = allocHeapArrayAligned(ECP_ShortW_Aff[Fp[BLS12_381], G1], N, alignment = 64) + let points = allocHeapArrayAligned(EC_ShortW_Aff[Fp[BLS12_381], G1], N, alignment = 64) for i in 0 ..< N: var smod{.noInit.}: Fr[BLS12_381] @@ -852,20 +852,20 @@ func eth_evm_bls12381_g1msm*(r: var openArray[byte], inputs: openarray[byte]): C # Due to mismatch between the BigInt[256] input and the rest being BigInt[255] # we use the low-level getMont instead of 'fromBig' getMont(smod.mres.limbs, s.limbs, - Fr[BLS12_381].fieldMod().limbs, + Fr[BLS12_381].getModulus().limbs, Fr[BLS12_381].getR2modP().limbs, Fr[BLS12_381].getNegInvModWord(), Fr[BLS12_381].getSpareBits()) coefs_big[i].fromField(smod) - var R{.noInit.}: ECP_ShortW_Jac[Fp[BLS12_381], G1] + var R{.noInit.}: EC_ShortW_Jac[Fp[BLS12_381], G1] R.multiScalarMul_vartime(coefs_big, points, N) freeHeapAligned(points) freeHeapAligned(coefs_big) - var aff{.noInit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] + var aff{.noInit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] aff.affine(R) r.toOpenArray( 0, 64-1).marshal(aff.x, bigEndian) @@ -908,7 +908,7 @@ func eth_evm_bls12381_g2msm*(r: var openArray[byte], inputs: openarray[byte]): C let N = inputs.len div 288 let coefs_big = allocHeapArrayAligned(BigInt[255], N, alignment = 64) - let points = allocHeapArrayAligned(ECP_ShortW_Aff[Fp2[BLS12_381], G2], N, alignment = 64) + let points = allocHeapArrayAligned(EC_ShortW_Aff[Fp2[BLS12_381], G2], N, alignment = 64) for i in 0 ..< N: var smod{.noInit.}: Fr[BLS12_381] @@ -934,20 +934,20 @@ func eth_evm_bls12381_g2msm*(r: var openArray[byte], inputs: openarray[byte]): C # Due to mismatch between the BigInt[256] input and the rest being BigInt[255] # we use the low-level getMont instead of 'fromBig' getMont(smod.mres.limbs, s.limbs, - Fr[BLS12_381].fieldMod().limbs, + Fr[BLS12_381].getModulus().limbs, Fr[BLS12_381].getR2modP().limbs, Fr[BLS12_381].getNegInvModWord(), Fr[BLS12_381].getSpareBits()) coefs_big[i].fromField(smod) - var R{.noInit.}: ECP_ShortW_Jac[Fp2[BLS12_381], G2] + var R{.noInit.}: EC_ShortW_Jac[Fp2[BLS12_381], G2] R.multiScalarMul_vartime(coefs_big, points, N) freeHeapAligned(points) freeHeapAligned(coefs_big) - var aff{.noInit.}: ECP_ShortW_Aff[Fp2[BLS12_381], G2] + var aff{.noInit.}: EC_ShortW_Aff[Fp2[BLS12_381], G2] aff.affine(R) r.toOpenArray( 0, 64-1).marshal(aff.x.c0, bigEndian) @@ -987,8 +987,8 @@ func eth_evm_bls12381_pairingcheck*(r: var openArray[byte], inputs: openarray[by # Spec doesn't allow empty inputs return cttEVM_InvalidInputSize - var P{.noInit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] - var Q{.noInit.}: ECP_ShortW_Aff[Fp2[BLS12_381], G2] + var P{.noInit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] + var Q{.noInit.}: EC_ShortW_Aff[Fp2[BLS12_381], G2] var acc {.noInit.}: MillerAccumulator[Fp[BLS12_381], Fp2[BLS12_381], Fp12[BLS12_381]] acc.init() @@ -1067,17 +1067,17 @@ func eth_evm_bls12381_map_fp_to_g1*(r: var openArray[byte], inputs: openarray[by if inputs[i] != 0: return cttEVM_IntLargerThanModulus discard u_big.unmarshal(inputs.toOpenArray(16, 64-1), bigEndian) - if bool(u_big >= BLS12_381.Mod()): + if bool(u_big >= Fp[BLS12_381].getModulus()): return cttEVM_IntLargerThanModulus var u {.noInit.}: Fp[BLS12_381] - var R {.noInit.}: ECP_ShortW_Jac[Fp[BLS12_381], G1] + var R {.noInit.}: EC_ShortW_Jac[Fp[BLS12_381], G1] u.fromBig(u_big) R.mapToCurve_sswu(u) R.clearCofactor() - var aff{.noInit.}: ECP_ShortW_Aff[Fp[BLS12_381], G1] + var aff{.noInit.}: EC_ShortW_Aff[Fp[BLS12_381], G1] aff.affine(R) r.toOpenArray( 0, 64-1).marshal(aff.x, bigEndian) @@ -1118,7 +1118,7 @@ func eth_evm_bls12381_map_fp2_to_g2*(r: var openArray[byte], inputs: openarray[b if inputs[i] != 0: return cttEVM_IntLargerThanModulus discard t.unmarshal(inputs.toOpenArray(16, 64-1), bigEndian) - if bool(t >= BLS12_381.Mod()): + if bool(t >= Fp[BLS12_381].getModulus()): return cttEVM_IntLargerThanModulus u.c0.fromBig(t) @@ -1126,16 +1126,16 @@ func eth_evm_bls12381_map_fp2_to_g2*(r: var openArray[byte], inputs: openarray[b if inputs[i] != 0: return cttEVM_IntLargerThanModulus discard t.unmarshal(inputs.toOpenArray(64+16, 64+64-1), bigEndian) - if bool(t >= BLS12_381.Mod()): + if bool(t >= Fp[BLS12_381].getModulus()): return cttEVM_IntLargerThanModulus u.c1.fromBig(t) - var R {.noInit.}: ECP_ShortW_Jac[Fp2[BLS12_381], G2] + var R {.noInit.}: EC_ShortW_Jac[Fp2[BLS12_381], G2] R.mapToCurve_sswu(u) R.clearCofactor() - var aff{.noInit.}: ECP_ShortW_Aff[Fp2[BLS12_381], G2] + var aff{.noInit.}: EC_ShortW_Aff[Fp2[BLS12_381], G2] aff.affine(R) r.toOpenArray( 0, 64-1).marshal(aff.x.c0, bigEndian) diff --git a/constantine/ethereum_verkle_ipa.nim b/constantine/ethereum_verkle_ipa.nim index 8a7b80c67..f5b9afb63 100644 --- a/constantine/ethereum_verkle_ipa.nim +++ b/constantine/ethereum_verkle_ipa.nim @@ -22,11 +22,11 @@ import const EthVerkleSeed* = "eth_verkle_oct_2021" -func generate_random_points*(r: var openArray[ECP_TwEdwards_Aff[Fp[Banderwagon]]]) = +func generate_random_points*(r: var openArray[EC_TwEdw_Aff[Fp[Banderwagon]]]) = ## generate_random_points generates random points on the curve with the hardcoded EthVerkleSeed - let points = allocHeapArrayAligned(ECP_TwEdwards_Aff[Fp[Banderwagon]], r.len, alignment = 64) + let points = allocHeapArrayAligned(EC_TwEdw_Aff[Fp[Banderwagon]], r.len, alignment = 64) - var points_found: seq[ECP_TwEdwards_Aff[Fp[Banderwagon]]] + var points_found: seq[EC_TwEdw_Aff[Fp[Banderwagon]]] var incrementer: uint64 = 0 var idx: int = 0 while true: @@ -39,7 +39,7 @@ func generate_random_points*(r: var openArray[ECP_TwEdwards_Aff[Fp[Banderwagon]] ctx.clear() var x {.noInit.}: Fp[Banderwagon] - var t {.noInit.}: matchingBigInt(Banderwagon) + var t {.noInit.}: Fp[Banderwagon].getBigInt() t.unmarshal(hash, bigEndian) x.fromBig(t) @@ -49,7 +49,7 @@ func generate_random_points*(r: var openArray[ECP_TwEdwards_Aff[Fp[Banderwagon]] var x_arr {.noInit.}: array[32, byte] x_arr.marshal(x, bigEndian) - var x_p {.noInit.}: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var x_p {.noInit.}: EC_TwEdw_Aff[Fp[Banderwagon]] let stat2 = x_p.deserialize_vartime(x_arr) if stat2 == cttCodecEcc_Success: points_found.add(x_p) @@ -139,8 +139,8 @@ template check(Section: untyped, evalExpr: CttCodecEccStatus): untyped {.dirty.} type EthVerkleIpaProofBytes* = array[544, byte] EthVerkleIpaMultiProofBytes* = array[576, byte] - EthVerkleIpaProof* = IpaProof[8, ECP_TwEdwards[Fp[Banderwagon]], Fr[Banderwagon]] - EthVerkleIpaMultiProof* = IpaMultiProof[8, ECP_TwEdwards[Fp[Banderwagon]], Fr[Banderwagon]] + EthVerkleIpaProof* = IpaProof[8, EC_TwEdw[Fp[Banderwagon]], Fr[Banderwagon]] + EthVerkleIpaMultiProof* = IpaMultiProof[8, EC_TwEdw[Fp[Banderwagon]], Fr[Banderwagon]] # The aliases may throw strange errors like: # - Error: invalid type: 'EthVerkleIpaProof' for var @@ -148,7 +148,7 @@ type # as of Nim v2.0.4 func serialize*(dst: var EthVerkleIpaProofBytes, - src: IpaProof[8, ECP_TwEdwards[Fp[Banderwagon]], Fr[Banderwagon]] + src: IpaProof[8, EC_TwEdw[Fp[Banderwagon]], Fr[Banderwagon]] ): cttEthVerkleIpaStatus {.discardable.} = # Note: We store 1 out of 2 coordinates of an EC point, so size(Fp[Banderwagon]) const fpb = sizeof(Fp[Banderwagon]) @@ -187,7 +187,7 @@ func deserialize*(dst: var EthVerkleIpaProof, return cttEthVerkleIpa_Success func serialize*(dst: var EthVerkleIpaMultiProofBytes, - src: IpaMultiProof[8, ECP_TwEdwards[Fp[Banderwagon]], Fr[Banderwagon]] + src: IpaMultiProof[8, EC_TwEdw[Fp[Banderwagon]], Fr[Banderwagon]] ): cttEthVerkleIpaStatus {.discardable.} = const frb = sizeof(Fr[Banderwagon]) @@ -213,9 +213,9 @@ func deserialize*(dst: var EthVerkleIpaMultiProof, # ------------------------------------------------------------------------------------ # TODO: refactor, this shouldn't use curves_primitives but internal functions -import ./curves_primitives +import ./lowlevel_fields -func mapToBaseField*(dst: var Fp[Banderwagon],p: ECP_TwEdwards[Fp[Banderwagon]]) = +func mapToBaseField*(dst: var Fp[Banderwagon],p: EC_TwEdw[Fp[Banderwagon]]) = ## The mapping chosen for the Banderwagon Curve is x/y ## ## This function takes a Banderwagon element & then @@ -227,7 +227,7 @@ func mapToBaseField*(dst: var Fp[Banderwagon],p: ECP_TwEdwards[Fp[Banderwagon]]) invY.inv(p.y) # invY = 1/Y dst.prod(p.x, invY) # dst = (X) * (1/Y) -func mapToScalarField*(res: var Fr[Banderwagon], p: ECP_TwEdwards[Fp[Banderwagon]]): bool {.discardable.} = +func mapToScalarField*(res: var Fr[Banderwagon], p: EC_TwEdw[Fp[Banderwagon]]): bool {.discardable.} = ## This function takes the x/y value from the above function as Fp element ## and convert that to bytes in Big Endian, ## and then load that to a Fr element @@ -246,7 +246,7 @@ func mapToScalarField*(res: var Fr[Banderwagon], p: ECP_TwEdwards[Fp[Banderwagon func batchMapToScalarField*( res: var openArray[Fr[Banderwagon]], - points: openArray[ECP_TwEdwards[Fp[Banderwagon]]]): bool {.discardable, noinline.} = + points: openArray[EC_TwEdw[Fp[Banderwagon]]]): bool {.discardable, noinline.} = ## This function performs the `mapToScalarField` operation ## on a batch of points ## diff --git a/constantine/hash_to_curve/h2c_hash_to_field.nim b/constantine/hash_to_curve/h2c_hash_to_field.nim index 5256db623..3d8628151 100644 --- a/constantine/hash_to_curve/h2c_hash_to_field.nim +++ b/constantine/hash_to_curve/h2c_hash_to_field.nim @@ -151,7 +151,7 @@ func expandMessageXMD*[len_in_bytes: static int]( func redc2x[FF](r: var FF, big2x: BigInt) {.inline.} = r.mres.limbs.redc2xMont( big2x.limbs, - FF.fieldMod().limbs, + FF.getModulus().limbs, FF.getNegInvModWord(), FF.getSpareBits() ) @@ -159,7 +159,7 @@ func redc2x[FF](r: var FF, big2x: BigInt) {.inline.} = func mulMont(r: var BigInt, a, b: BigInt, FF: type) {.inline.} = r.limbs.mulMont( a.limbs, b.limbs, - FF.fieldMod().limbs, + FF.getModulus().limbs, FF.getNegInvModWord(), FF.getSpareBits() ) @@ -195,14 +195,18 @@ func hashToField*[Field; count: static int]( ## If a domainSepTag larger than 255-bit is required, ## it is recommended to cache the reduced DST. - const - L = ceilDiv_vartime(Field.C.getCurveBitwidth() + k, 8) - m = block: - when Field is Fp: 1 - elif Field is Fp2: 2 - else: {.error: "Unconfigured".} + when Field is Fp: + const L = ceilDiv_vartime(Field.bits() + k, 8) + const m = 1 + type Big2x = BigInt[2 * Field.bits()] + elif Field is Fp2: + const L = ceilDiv_vartime(Fp[Field.Name].bits() + k, 8) + const m = 2 + type Big2x = BigInt[2 * Fp[Field.Name].bits()] + else: + {.error: "Unconfigured".} - len_in_bytes = count * m * L + const len_in_bytes = count * m * L var uniform_bytes{.noInit.}: array[len_in_bytes, byte] H.expandMessageXMD( @@ -217,7 +221,7 @@ func hashToField*[Field; count: static int]( let elm_offset = L * (j + i * m) template tv: untyped = uniform_bytes.toOpenArray(elm_offset, elm_offset + L-1) - var big2x {.noInit.}: BigInt[2 * getCurveBitwidth(Field.C)] + var big2x {.noInit.}: Big2x big2x.unmarshal(tv, bigEndian) # Reduces modulo p and output in Montgomery domain @@ -225,12 +229,12 @@ func hashToField*[Field; count: static int]( output[i].redc2x(big2x) output[i].mres.mulMont( output[i].mres, - Fp[Field.C].getR3ModP(), - Fp[Field.C]) + Fp[Field.Name].getR3ModP(), + Fp[Field.Name]) else: output[i].coords[j].redc2x(big2x) output[i].coords[j].mres.mulMont( output[i].coords[j].mres, - Fp[Field.C].getR3ModP(), - Fp[Field.C]) + Fp[Field.Name].getR3ModP(), + Fp[Field.Name]) diff --git a/constantine/hash_to_curve/h2c_isogeny_maps.nim b/constantine/hash_to_curve/h2c_isogeny_maps.nim index 0786060dd..a6d7cf8cb 100644 --- a/constantine/hash_to_curve/h2c_isogeny_maps.nim +++ b/constantine/hash_to_curve/h2c_isogeny_maps.nim @@ -92,10 +92,10 @@ func h2c_isogeny_map[F]( # xd^e with e in [1, N], for example [xd, xd², xd³] const maxdegree = max([ - h2cIsomapPoly(F.C, sswu, G, xnum).len, - h2cIsomapPoly(F.C, sswu, G, xden).len, - h2cIsomapPoly(F.C, sswu, G, ynum).len, - h2cIsomapPoly(F.C, sswu, G, yden).len, + h2cIsomapPoly(F.Name, sswu, G, xnum).len, + h2cIsomapPoly(F.Name, sswu, G, xden).len, + h2cIsomapPoly(F.Name, sswu, G, ynum).len, + h2cIsomapPoly(F.Name, sswu, G, yden).len, ]) var xd_pow{.noInit.}: array[maxdegree, F] xd_pow[0] = xd @@ -103,28 +103,28 @@ func h2c_isogeny_map[F]( for i in 2 ..< xd_pow.len: xd_pow[i].prod(xd_pow[i-1], xd_pow[0]) - const xnLen = h2cIsomapPoly(F.C, sswu, G, xnum).len - const ynLen = h2cIsomapPoly(F.C, sswu, G, ynum).len + const xnLen = h2cIsomapPoly(F.Name, sswu, G, xnum).len + const ynLen = h2cIsomapPoly(F.Name, sswu, G, ynum).len rxn.poly_eval_horner_scaled( xn, xd_pow, - h2cIsomapPoly(F.C, sswu, G, xnum), + h2cIsomapPoly(F.Name, sswu, G, xnum), xnLen ) rxd.poly_eval_horner_scaled( xn, xd_pow, - h2cIsomapPoly(F.C, sswu, G, xden), + h2cIsomapPoly(F.Name, sswu, G, xden), xnLen ) ryn.poly_eval_horner_scaled( xn, xd_pow, - h2cIsomapPoly(F.C, sswu, G, ynum), + h2cIsomapPoly(F.Name, sswu, G, ynum), ynLen ) ryd.poly_eval_horner_scaled( xn, xd_pow, - h2cIsomapPoly(F.C, sswu, G, yden), + h2cIsomapPoly(F.Name, sswu, G, yden), ynLen ) @@ -132,7 +132,7 @@ func h2c_isogeny_map[F]( ryn *= yn func h2c_isogeny_map*[F; G: static Subgroup]( - r: var ECP_ShortW_Prj[F, G], + r: var EC_ShortW_Prj[F, G], xn, xd, yn: F) = ## Given G2, the target prime order subgroup of E2, ## this function maps an element of @@ -167,7 +167,7 @@ func h2c_isogeny_map*[F; G: static Subgroup]( r.z *= t func h2c_isogeny_map*[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], + r: var EC_ShortW_Jac[F, G], xn, xd, yn: F) = ## Given G2, the target prime order subgroup of E2, ## this function maps an element of @@ -205,8 +205,8 @@ func h2c_isogeny_map*[F; G: static Subgroup]( r.y *= ryn # Y = yn * yd² * xd³ func h2c_isogeny_map*[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], - P: ECP_ShortW_Jac[F, G]) = + r: var EC_ShortW_Jac[F, G], + P: EC_ShortW_Jac[F, G]) = ## Map P in isogenous curve E'2 ## to r in E2 ## @@ -224,10 +224,10 @@ func h2c_isogeny_map*[F; G: static Subgroup]( # Z²^e with e in [1, N], for example [Z², Z⁴, Z⁶] const maxdegree = max([ - h2cIsomapPoly(F.C, sswu, G, xnum).len, - h2cIsomapPoly(F.C, sswu, G, xden).len, - h2cIsomapPoly(F.C, sswu, G, ynum).len, - h2cIsomapPoly(F.C, sswu, G, yden).len, + h2cIsomapPoly(F.Name, sswu, G, xnum).len, + h2cIsomapPoly(F.Name, sswu, G, xden).len, + h2cIsomapPoly(F.Name, sswu, G, ynum).len, + h2cIsomapPoly(F.Name, sswu, G, yden).len, ]) var ZZpow{.noInit.}: array[maxdegree, F] ZZpow[0].square(P.z) @@ -241,28 +241,28 @@ func h2c_isogeny_map*[F; G: static Subgroup]( else: ZZpow[i].prod(ZZpow[(i-1) shr 1], ZZpow[((i-1) shr 1) + 1]) - const xnLen = h2cIsomapPoly(F.C, sswu, G, xnum).len - const ynLen = h2cIsomapPoly(F.C, sswu, G, ynum).len + const xnLen = h2cIsomapPoly(F.Name, sswu, G, xnum).len + const ynLen = h2cIsomapPoly(F.Name, sswu, G, ynum).len xn.poly_eval_horner_scaled( P.x, ZZpow, - h2cIsomapPoly(F.C, sswu, G, xnum), + h2cIsomapPoly(F.Name, sswu, G, xnum), xnLen ) xd.poly_eval_horner_scaled( P.x, ZZpow, - h2cIsomapPoly(F.C, sswu, G, xden), + h2cIsomapPoly(F.Name, sswu, G, xden), xnLen ) yn.poly_eval_horner_scaled( P.x, ZZpow, - h2cIsomapPoly(F.C, sswu, G, ynum), + h2cIsomapPoly(F.Name, sswu, G, ynum), ynLen ) yd.poly_eval_horner_scaled( P.x, ZZpow, - h2cIsomapPoly(F.C, sswu, G, yden), + h2cIsomapPoly(F.Name, sswu, G, yden), ynLen ) diff --git a/constantine/hash_to_curve/h2c_map_to_isocurve_swu.nim b/constantine/hash_to_curve/h2c_map_to_isocurve_swu.nim index fd4105599..0aac33178 100644 --- a/constantine/hash_to_curve/h2c_map_to_isocurve_swu.nim +++ b/constantine/hash_to_curve/h2c_map_to_isocurve_swu.nim @@ -40,8 +40,8 @@ import # Test vector generator # - https://github.com/cfrg/draft-irtf-cfrg-hash-to-curve/blob/f7dd3761/poc/sswu_generic.sage -func invsqrt_if_square[C: static Curve]( - r: var Fp2[C], a: Fp2[C]): SecretBool = +func invsqrt_if_square[Name: static Algebra]( + r: var Fp2[Name], a: Fp2[Name]): SecretBool = ## If ``a`` is a square, compute the inverse square root of ``a`` ## and store it in r ## if not, ``r`` is unmodified. @@ -63,8 +63,8 @@ func invsqrt_if_square[C: static Curve]( # See discussion and optimization with Andy Polyakov # https://github.com/supranational/blst/issues/2#issuecomment-686656784 - var t1{.noInit.}, t2{.noInit.}, t3{.noInit.}: Fp[C] - var inp{.noInit.}: Fp2[C] + var t1{.noInit.}, t2{.noInit.}, t3{.noInit.}: Fp[Name] + var inp{.noInit.}: Fp2[Name] t1.square(a.c0) # a0² t2.square(a.c1) # - β a1² with β = 𝑖² in a complex extension field @@ -77,13 +77,13 @@ func invsqrt_if_square[C: static Curve]( result = t3.invsqrt_if_square(t1) # 1/sqrt(a0² - β a1²) # If input is not a square in Fp2, multiply by 1/Z³ - inp.prod(a, h2cConst(C, sswu, G2, inv_Z3)) # inp = a / Z³ + inp.prod(a, h2cConst(Name, sswu, G2, inv_Z3)) # inp = a / Z³ block: # Adjust t1 and t3 accordingly - var t0{.noInit.}: Fp[C] - t0.prod(t1, h2cConst(C, sswu, G2, squared_norm_inv_Z3)) # (a0² - β a1²) * ||1/Z³||² + var t0{.noInit.}: Fp[Name] + t0.prod(t1, h2cConst(Name, sswu, G2, squared_norm_inv_Z3)) # (a0² - β a1²) * ||1/Z³||² t1.ccopy(t0, not result) - t0.prod(t3, h2cConst(C, sswu, G2, inv_norm_inv_Z3)) # 1/sqrt(a0² - β a1²) * 1/||1/Z³|| + t0.prod(t3, h2cConst(Name, sswu, G2, inv_norm_inv_Z3)) # 1/sqrt(a0² - β a1²) * 1/||1/Z³|| t3.ccopy(t0, not result) inp.ccopy(a, result) @@ -113,9 +113,9 @@ func invsqrt_if_square[C: static Curve]( # return result -func mapToIsoCurve_sswuG2_opt9mod16*[C: static Curve]( - xn, xd, yn: var Fp2[C], - u: Fp2[C], xd3: var Fp2[C]) = +func mapToIsoCurve_sswuG2_opt9mod16*[Name: static Algebra]( + xn, xd, yn: var Fp2[Name], + u: Fp2[Name], xd3: var Fp2[Name]) = ## Given G2, the target prime order subgroup of E2 we want to hash to, ## this function maps any field element of Fp2 to E'2 ## a curve isogenous to E2 using the Simplified Shallue-van de Woestijne method. @@ -139,9 +139,9 @@ func mapToIsoCurve_sswuG2_opt9mod16*[C: static Curve]( # Formal verification: https://github.com/GaloisInc/BLST-Verification/blob/8e2efde4/spec/implementation/HashToG2.cry var - uu {.noInit.}, tv2 {.noInit.}: Fp2[C] - tv4 {.noInit.}, x2n {.noInit.}, gx1 {.noInit.}: Fp2[C] - y2 {.noInit.}: Fp2[C] + uu {.noInit.}, tv2 {.noInit.}: Fp2[Name] + tv4 {.noInit.}, x2n {.noInit.}, gx1 {.noInit.}: Fp2[Name] + y2 {.noInit.}: Fp2[Name] e1, e2: SecretBool # Aliases @@ -153,27 +153,27 @@ func mapToIsoCurve_sswuG2_opt9mod16*[C: static Curve]( # x numerators uu.square(u) # uu = u² - Zuu.prod(uu, h2cConst(C, sswu, G2, Z)) # Zuu = Z * uu + Zuu.prod(uu, h2cConst(Name, sswu, G2, Z)) # Zuu = Z * uu tv2.square(Zuu) # tv2 = Zuu² tv2 += Zuu # tv2 = tv2 + Zuu x1n.setOne() x1n += tv2 # x1n = tv2 + 1 - x1n *= h2cConst(C, sswu, G2, Bprime_E2) # x1n = x1n * B' + x1n *= h2cConst(Name, sswu, G2, Bprime_E2) # x1n = x1n * B' x2n.prod(Zuu, x1n) # x2n = Zuu * x1n # x denumerator - xd.prod(tv2, h2cConst(C, sswu, G2, minus_A)) # xd = -A * tv2 + xd.prod(tv2, h2cConst(Name, sswu, G2, minus_A)) # xd = -A * tv2 e1 = xd.isZero() # e1 = xd == 0 - xd.ccopy(h2cConst(C, sswu, G2, ZmulA), e1) # If xd == 0, set xd = Z*A + xd.ccopy(h2cConst(Name, sswu, G2, ZmulA), e1) # If xd == 0, set xd = Z*A # y numerators tv2.square(xd) gxd.prod(xd, tv2) # gxd = xd³ - tv2.mulCheckSparse(h2CConst(C, sswu, G2, Aprime_E2)) + tv2.mulCheckSparse(h2CConst(Name, sswu, G2, Aprime_E2)) gx1.square(x1n) gx1 += tv2 # x1n² + A * xd² gx1 *= x1n # x1n³ + A * x1n * xd² - tv2.prod(gxd, h2cConst(C, sswu, G2, Bprime_E2)) + tv2.prod(gxd, h2cConst(Name, sswu, G2, Bprime_E2)) gx1 += tv2 # gx1 = x1n³ + A * x1n * xd² + B * xd³ tv4.square(gxd) # tv4 = gxd² tv2.prod(gx1, gxd) # tv2 = gx1 * gxd @@ -195,9 +195,9 @@ func mapToIsoCurve_sswuG2_opt9mod16*[C: static Curve]( # yd.setOne() -func mapToIsoCurve_sswuG1_opt3mod4*[C: static Curve]( - xn, xd, yn: var Fp[C], - u: Fp[C], xd3: var Fp[C]) = +func mapToIsoCurve_sswuG1_opt3mod4*[Name: static Algebra]( + xn, xd, yn: var Fp[Name], + u: Fp[Name], xd3: var Fp[Name]) = ## Given G1, the target prime order subgroup of E1 we want to hash to, ## this function maps any field element of Fp to E'1 ## a curve isogenous to E1 using the Simplified Shallue-van de Woestijne method. @@ -221,9 +221,9 @@ func mapToIsoCurve_sswuG1_opt3mod4*[C: static Curve]( # Formal verification: https://github.com/GaloisInc/BLST-Verification/blob/8e2efde4/spec/implementation/HashToG1.cry var - uu {.noInit.}, tv2 {.noInit.}: Fp[C] - tv4 {.noInit.}, x2n {.noInit.}, gx1 {.noInit.}: Fp[C] - y2 {.noInit.}: Fp[C] + uu {.noInit.}, tv2 {.noInit.}: Fp[Name] + tv4 {.noInit.}, x2n {.noInit.}, gx1 {.noInit.}: Fp[Name] + y2 {.noInit.}: Fp[Name] e1, e2: SecretBool # Aliases @@ -235,27 +235,27 @@ func mapToIsoCurve_sswuG1_opt3mod4*[C: static Curve]( # x numerators uu.square(u) # uu = u² - Zuu.prod(uu, h2cConst(C, sswu, G1, Z)) # Zuu = Z * uu + Zuu.prod(uu, h2cConst(Name, sswu, G1, Z)) # Zuu = Z * uu tv2.square(Zuu) # tv2 = Zuu² tv2 += Zuu # tv2 = tv2 + Zuu x1n.setOne() x1n += tv2 # x1n = tv2 + 1 - x1n *= h2cConst(C, sswu, G1, Bprime_E1) # x1n = x1n * B' + x1n *= h2cConst(Name, sswu, G1, Bprime_E1) # x1n = x1n * B' x2n.prod(Zuu, x1n) # x2n = Zuu * x1n # x denumerator - xd.prod(tv2, h2cConst(C, sswu, G1, minus_A)) # xd = -A * tv2 + xd.prod(tv2, h2cConst(Name, sswu, G1, minus_A)) # xd = -A * tv2 e1 = xd.isZero() # e1 = xd == 0 - xd.ccopy(h2cConst(C, sswu, G1, ZmulA), e1) # If xd == 0, set xd = Z*A + xd.ccopy(h2cConst(Name, sswu, G1, ZmulA), e1) # If xd == 0, set xd = Z*A # y numerators tv2.square(xd) gxd.prod(xd, tv2) # gxd = xd³ - tv2 *= h2cConst(C, sswu, G1, Aprime_E1) + tv2 *= h2cConst(Name, sswu, G1, Aprime_E1) gx1.square(x1n) gx1 += tv2 # x1n² + A * xd² gx1 *= x1n # x1n³ + A * x1n * xd² - tv2.prod(gxd, h2cConst(C, sswu, G1, Bprime_E1)) + tv2.prod(gxd, h2cConst(Name, sswu, G1, Bprime_E1)) gx1 += tv2 # gx1 = x1n³ + A * x1n * xd² + B * xd³ tv4.square(gxd) # tv4 = gxd² tv2.prod(gx1, gxd) # tv2 = gx1 * gxd @@ -264,7 +264,7 @@ func mapToIsoCurve_sswuG1_opt3mod4*[C: static Curve]( # Start searching for sqrt(gx1) e2 = y1.invsqrt_if_square(tv4) # y1 = tv4^c1 = (gx1 * gxd³)^((p²-9)/16) y1 *= tv2 # y1 *= gx1*gxd - y2.prod(y1, h2cConst(C, sswu, G1, sqrt_minus_Z3)) + y2.prod(y1, h2cConst(Name, sswu, G1, sqrt_minus_Z3)) y2 *= uu y2 *= u diff --git a/constantine/hash_to_curve/hash_to_curve.nim b/constantine/hash_to_curve/hash_to_curve.nim index 2e0f755ba..2c89f525c 100644 --- a/constantine/hash_to_curve/hash_to_curve.nim +++ b/constantine/hash_to_curve/hash_to_curve.nim @@ -38,7 +38,7 @@ export abstractions, arithmetic # generic sandwich # ---------------------------------------------------------------- func mapToCurve_svdw[F, G]( - r: var ECP_ShortW_Aff[F, G], + r: var EC_ShortW_Aff[F, G], u: F) = ## Deterministically map a field element u ## to an elliptic curve point `r` @@ -51,29 +51,29 @@ func mapToCurve_svdw[F, G]( gx1{.noInit.}, gx2{.noInit.}: F tv1.square(u) - tv1 *= h2cConst(F.C, svdw, G, curve_eq_rhs_Z) + tv1 *= h2cConst(F.Name, svdw, G, curve_eq_rhs_Z) tv2 = tv1 when F is Fp: tv2 += F(mres: F.getMontyOne()) tv1.diff(F(mres: F.getMontyOne()), tv1) else: - tv2.c0 += Fp[F.F.C](mres: Fp[F.F.C].getMontyOne()) - tv1.c0.diff(Fp[F.F.C](mres: Fp[F.F.C].getMontyOne()), tv1.c0) + tv2.c0 += Fp[F.F.Name](mres: Fp[F.F.Name].getMontyOne()) + tv1.c0.diff(Fp[F.F.Name](mres: Fp[F.F.Name].getMontyOne()), tv1.c0) tv1.c1.neg() tv3.prod(tv1, tv2) tv3.inv() tv4.prod(u, tv1) tv4 *= tv3 - tv4.mulCheckSparse(h2cConst(F.C, svdw, G, z3)) + tv4.mulCheckSparse(h2cConst(F.Name, svdw, G, z3)) - x1.diff(h2cConst(F.C, svdw, G, minus_Z_div_2), tv4) - x2.sum(h2cConst(F.C, svdw, G, minus_Z_div_2), tv4) + x1.diff(h2cConst(F.Name, svdw, G, minus_Z_div_2), tv4) + x2.sum(h2cConst(F.Name, svdw, G, minus_Z_div_2), tv4) r.x.square(tv2) r.x *= tv3 r.x.square() - r.x *= h2cConst(F.C, svdw, G, z4) - r.x += h2cConst(F.C, svdw, G, Z) + r.x *= h2cConst(F.Name, svdw, G, z4) + r.x += h2cConst(F.Name, svdw, G, Z) # x³+ax+b gx1.curve_eq_rhs(x1, G) @@ -91,7 +91,7 @@ func mapToCurve_svdw[F, G]( r.y.cneg(sgn0(u) xor sgn0(r.y)) func mapToIsoCurve_sswuG1_opt3mod4[F]( - r: var ECP_ShortW_Jac[F, G1], + r: var EC_ShortW_Jac[F, G1], u: F) = var xn{.noInit.}, xd{.noInit.}: F @@ -109,7 +109,7 @@ func mapToIsoCurve_sswuG1_opt3mod4[F]( r.y.prod(yn, xd3) # Y = yZ³ = yn * xd³ func mapToIsoCurve_sswuG2_opt9mod16[F]( - r: var ECP_ShortW_Jac[F, G2], + r: var EC_ShortW_Jac[F, G2], u: F) = var xn{.noInit.}, xd{.noInit.}: F @@ -127,30 +127,30 @@ func mapToIsoCurve_sswuG2_opt9mod16[F]( r.y.prod(yn, xd3) # Y = yZ³ = yn * xd³ func mapToCurve_svdw_fusedAdd[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], + r: var EC_ShortW_Jac[F, G], u0, u1: F) = ## Map 2 elements of the ## finite or extension field F ## to an elliptic curve E ## and add them - var Q0{.noInit.}, Q1{.noInit.}: ECP_ShortW_Aff[F, G] + var Q0{.noInit.}, Q1{.noInit.}: EC_ShortW_Aff[F, G] Q0.mapToCurve_svdw(u0) Q1.mapToCurve_svdw(u1) r.fromAffine(Q0) r += Q1 -func mapToCurve_sswu*[F; G: static Subgroup](r: var ECP_ShortW_Jac[F, G], u: F) = +func mapToCurve_sswu*[F; G: static Subgroup](r: var EC_ShortW_Jac[F, G], u: F) = ## Map an element of the finite or extension field F to an elliptic curve E - when F.C.getCoefA() * F.C.getCoefB() == 0: + when F.Name.getCoefA() * F.Name.getCoefB() == 0: # https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-6.6.3 # Simplified Shallue-van de Woestijne-Ulas method for AB == 0 # 1. Map to E' isogenous to E - when F is Fp and F.C.has_P_3mod4_primeModulus(): + when F is Fp and F.Name.has_P_3mod4_primeModulus(): # 1. Map to E'1 isogenous to E1 r.mapToIsoCurve_sswuG1_opt3mod4(u) - elif F is Fp2 and F.C.has_Psquare_9mod16_primePower(): + elif F is Fp2 and F.Name.has_Psquare_9mod16_primePower(): # 1. Map to E'2 isogenous to E2 r.mapToIsoCurve_sswuG2_opt9mod16(u) else: @@ -162,7 +162,7 @@ func mapToCurve_sswu*[F; G: static Subgroup](r: var ECP_ShortW_Jac[F, G], u: F) {.error: "Not implemented".} func mapToCurve_sswu_fusedAdd[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], + r: var EC_ShortW_Jac[F, G], u0, u1: F) = ## Map 2 elements of the ## finite or extension field F @@ -181,23 +181,23 @@ func mapToCurve_sswu_fusedAdd[F; G: static Subgroup]( # unlike the complete projective formulae which heavily depends on it # So we use jacobian coordinates for computation on isogenies. - when F.C.getCoefA() * F.C.getCoefB() == 0: + when F.Name.getCoefA() * F.Name.getCoefB() == 0: # https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-6.6.3 # Simplified Shallue-van de Woestijne-Ulas method for AB == 0 - var Q0{.noInit.}, Q1{.noInit.}: ECP_ShortW_Jac[F, G] + var Q0{.noInit.}, Q1{.noInit.}: EC_ShortW_Jac[F, G] # 1. Map to E' isogenous to E - when F is Fp and F.C.has_P_3mod4_primeModulus(): + when F is Fp and F.Name.has_P_3mod4_primeModulus(): # 1. Map to E'1 isogenous to E1 Q0.mapToIsoCurve_sswuG1_opt3mod4(u0) Q1.mapToIsoCurve_sswuG1_opt3mod4(u1) - Q0.sum(Q0, Q1, h2CConst(F.C, sswu, G1, Aprime_E1)) - elif F is Fp2 and F.C.has_Psquare_9mod16_primePower(): + Q0.sum(Q0, Q1, h2CConst(F.Name, sswu, G1, Aprime_E1)) + elif F is Fp2 and F.Name.has_Psquare_9mod16_primePower(): # 1. Map to E'2 isogenous to E2 Q0.mapToIsoCurve_sswuG2_opt9mod16(u0) Q1.mapToIsoCurve_sswuG2_opt9mod16(u1) - Q0.sum(Q0, Q1, h2CConst(F.C, sswu, G2, Aprime_E2)) + Q0.sum(Q0, Q1, h2CConst(F.Name, sswu, G2, Aprime_E2)) else: {.error: "Not implemented".} @@ -212,7 +212,7 @@ func mapToCurve_sswu_fusedAdd[F; G: static Subgroup]( func hashToCurve_svdw*[F; G: static Subgroup]( H: type CryptoHash, k: static int, - output: var ECP_ShortW_Jac[F, G], + output: var EC_ShortW_Jac[F, G], augmentation: openArray[byte], message: openArray[byte], domainSepTag: openArray[byte]) {.genCharAPI.} = @@ -251,7 +251,7 @@ func hashToCurve_svdw*[F; G: static Subgroup]( func hashToCurve_sswu*[F; G: static Subgroup]( H: type CryptoHash, k: static int, - output: var ECP_ShortW_Jac[F, G], + output: var EC_ShortW_Jac[F, G], augmentation: openArray[byte], message: openArray[byte], domainSepTag: openArray[byte]) {.genCharAPI.} = @@ -290,7 +290,7 @@ func hashToCurve_sswu*[F; G: static Subgroup]( func hashToCurve*[F; G: static Subgroup]( H: type CryptoHash, k: static int, - output: var ECP_ShortW_Jac[F, G], + output: var EC_ShortW_Jac[F, G], augmentation: openArray[byte], message: openArray[byte], domainSepTag: openArray[byte]) {.inline, genCharAPI.} = @@ -313,10 +313,10 @@ func hashToCurve*[F; G: static Subgroup]( ## and `CoreVerify(PK, PK || message, signature)` ## - `message` is the message to hash ## - `domainSepTag` is the protocol domain separation tag (DST). - when F.C == BLS12_381: + when F.Name == BLS12_381: hashToCurve_sswu(H, k, output, augmentation, message, domainSepTag) - elif F.C == BN254_Snarks: + elif F.Name == BN254_Snarks: hashToCurve_svdw(H, k, output, augmentation, message, domainSepTag) else: @@ -325,7 +325,7 @@ func hashToCurve*[F; G: static Subgroup]( func hashToCurve*[F; G: static Subgroup]( H: type CryptoHash, k: static int, - output: var (ECP_ShortW_Prj[F, G] or ECP_ShortW_Aff[F, G]), + output: var (EC_ShortW_Prj[F, G] or EC_ShortW_Aff[F, G]), augmentation: openArray[byte], message: openArray[byte], domainSepTag: openArray[byte]) {.inline, genCharAPI.} = @@ -349,9 +349,9 @@ func hashToCurve*[F; G: static Subgroup]( ## - `message` is the message to hash ## - `domainSepTag` is the protocol domain separation tag (DST). - var Pjac{.noInit.}: ECP_ShortW_Jac[F, G] + var Pjac{.noInit.}: EC_ShortW_Jac[F, G] H.hashToCurve(k, Pjac, augmentation, message, domainSepTag) - when output is ECP_ShortW_Prj: + when output is EC_ShortW_Prj: output.projectiveFromJacobian(Pjac) else: output.affine(Pjac) diff --git a/constantine/lowlevel_bigints.nim b/constantine/lowlevel_bigints.nim new file mode 100644 index 000000000..fd67dfb88 --- /dev/null +++ b/constantine/lowlevel_bigints.nim @@ -0,0 +1,43 @@ +# Constantine +# Copyright (c) 2018-2019 Status Research & Development GmbH +# Copyright (c) 2020-Present Mamy André-Ratsimbazafy +# Licensed and distributed under either of +# * MIT license (license terms in the root directory or at http://opensource.org/licenses/MIT). +# * Apache v2 license (license terms in the root directory or at http://www.apache.org/licenses/LICENSE-2.0). +# at your option. This file may not be copied, modified, or distributed except according to those terms. + +import + ./platforms/abstractions, + ./math/io/io_bigints + +# ############################################################ +# +# Low-level named Finite Fields API +# +# ############################################################ + +# Warning ⚠️: +# The low-level APIs have no stability guarantee. +# Use high-level protocols which are designed according to a stable specs +# and with misuse resistance in mind. + +{.push raises: [].} # No exceptions allowed in core cryptographic operations +{.push inline.} + +# Base types +# ------------------------------------------------------------ + +export abstractions + +# BigInt +# ------------------------------------------------------------ + +func unmarshalBE*(dst: var BigInt, src: openarray[byte]): bool = + ## Return true on success + ## Return false if destination is too small compared to source + return dst.unmarshal(src, bigEndian) + +func marshalBE*(dst: var openarray[byte], src: BigInt): bool = + ## Return true on success + ## Return false if destination is too small compared to source + return dst.marshal(src, bigEndian) diff --git a/constantine/lowlevel_elliptic_curves.nim b/constantine/lowlevel_elliptic_curves.nim new file mode 100644 index 000000000..e1b39cc68 --- /dev/null +++ b/constantine/lowlevel_elliptic_curves.nim @@ -0,0 +1,87 @@ +# Constantine +# Copyright (c) 2018-2019 Status Research & Development GmbH +# Copyright (c) 2020-Present Mamy André-Ratsimbazafy +# Licensed and distributed under either of +# * MIT license (license terms in the root directory or at http://opensource.org/licenses/MIT). +# * Apache v2 license (license terms in the root directory or at http://www.apache.org/licenses/LICENSE-2.0). +# at your option. This file may not be copied, modified, or distributed except according to those terms. + +import + ./platforms/abstractions, + ./named/algebras, + ./named/[zoo_subgroups, zoo_generators], + ./math/ec_shortweierstrass, + ./math/elliptic/[ + ec_scalar_mul_vartime, + ec_multi_scalar_mul], + ./math/io/io_ec, + ./hash_to_curve/hash_to_curve + +# ############################################################ +# +# Low-level named Elliptic Curve API +# +# ############################################################ + +# Warning ⚠️: +# The low-level APIs have no stability guarantee. +# Use high-level protocols which are designed according to a stable specs +# and with misuse resistance in mind. + +{.push raises: [].} # No exceptions allowed in core cryptographic operations +{.push inline.} + +# Base types +# ------------------------------------------------------------ + +export + abstractions, + algebras.Algebra + +# Elliptic curve +# ------------------------------------------------------------ + +export + ec_shortweierstrass.Subgroup, + ec_shortweierstrass.EC_ShortW_Aff, + ec_shortweierstrass.EC_ShortW_Jac, + ec_shortweierstrass.EC_ShortW_Prj, + ec_shortweierstrass.EC_ShortW + +export ec_shortweierstrass.`==` +export ec_shortweierstrass.isNeutral +export ec_shortweierstrass.setNeutral +export ec_shortweierstrass.setGenerator +export ec_shortweierstrass.ccopy +export ec_shortweierstrass.isOnCurve +export ec_shortweierstrass.neg +export ec_shortweierstrass.cneg + +export ec_shortweierstrass.affine +export ec_shortweierstrass.fromAffine +export ec_shortweierstrass.batchAffine + +export ec_shortweierstrass.sum +export ec_shortweierstrass.sum_vartime +export ec_shortweierstrass.`+=` +export ec_shortweierstrass.`~+=` +export ec_shortweierstrass.double +export ec_shortweierstrass.diff +export ec_shortweierstrass.diff_vartime +export ec_shortweierstrass.`-=` +export ec_shortweierstrass.`~-=` +export ec_shortweierstrass.mixedSum +export ec_shortweierstrass.mixedDiff + +export ec_shortweierstrass.scalarMul +export ec_scalar_mul_vartime.scalarMul_vartime +export ec_multi_scalar_mul.multiScalarMul_vartime + +export zoo_generators.getGenerator +export zoo_subgroups.clearCofactor +export zoo_subgroups.isInSubgroup + +# Hashing to Elliptic Curve +# ------------------------------------------------------------ + +export hash_to_curve.hash_to_curve diff --git a/constantine/curves_primitives_parallel.nim b/constantine/lowlevel_elliptic_curves_parallel.nim similarity index 75% rename from constantine/curves_primitives_parallel.nim rename to constantine/lowlevel_elliptic_curves_parallel.nim index 77c023655..bb2d565d3 100644 --- a/constantine/curves_primitives_parallel.nim +++ b/constantine/lowlevel_elliptic_curves_parallel.nim @@ -15,10 +15,15 @@ import # ############################################################ # -# Generator for low-level parallel primitives API +# Low-level named Elliptic Curve Parallel API # # ############################################################ +# Warning ⚠️: +# The low-level APIs have no stability guarantee. +# Use high-level protocols which are designed according to a stable specs +# and with misuse resistance in mind. + # Threadpool # ------------------------------------------------------------ @@ -29,7 +34,7 @@ export threadpool.shutdown # Base types # ------------------------------------------------------------ -export algebras.Curve +export algebras.Algebra export abstractions.BigInt export algebras.Fp, @@ -41,10 +46,10 @@ export export ec_shortweierstrass.Subgroup, - ec_shortweierstrass.ECP_ShortW_Aff, - ec_shortweierstrass.ECP_ShortW_Jac, - ec_shortweierstrass.ECP_ShortW_Prj, - ec_shortweierstrass.ECP_ShortW + ec_shortweierstrass.EC_ShortW_Aff, + ec_shortweierstrass.EC_ShortW_Jac, + ec_shortweierstrass.EC_ShortW_Prj, + ec_shortweierstrass.EC_ShortW export ec_multi_scalar_mul_parallel.multiScalarMul_vartime_parallel diff --git a/constantine/lowlevel_extension_fields.nim b/constantine/lowlevel_extension_fields.nim new file mode 100644 index 000000000..23edabe5e --- /dev/null +++ b/constantine/lowlevel_extension_fields.nim @@ -0,0 +1,89 @@ +# Constantine +# Copyright (c) 2018-2019 Status Research & Development GmbH +# Copyright (c) 2020-Present Mamy André-Ratsimbazafy +# Licensed and distributed under either of +# * MIT license (license terms in the root directory or at http://opensource.org/licenses/MIT). +# * Apache v2 license (license terms in the root directory or at http://www.apache.org/licenses/LICENSE-2.0). +# at your option. This file may not be copied, modified, or distributed except according to those terms. + +import + ./platforms/abstractions, + ./named/algebras, + ./math/isogenies/frobenius, + ./math/extension_fields, + ./math/io/io_extfields + +# ############################################################ +# +# Low-level named math objects API +# +# ############################################################ + +# Warning ⚠️: +# The low-level APIs have no stability guarantee. +# Use high-level protocols which are designed according to a stable specs +# and with misuse resistance in mind. + +{.push raises: [].} # No exceptions allowed in core cryptographic operations +{.push inline.} + +# Base types +# ------------------------------------------------------------ + +export + abstractions, + algebras.Algebra + +# Extension fields +# ------------------------------------------------------------ + +export + extension_fields.Fp2 + # TODO: deal with Fp2->Fp6 vs Fp3->Fp6 and Fp2->Fp6->Fp12 vs Fp2->Fp4->Fp12 + # extension_fields.Fp4, + # extension_fields.Fp6, + # extension_fields.Fp12 + +# Generic sandwich - https://github.com/nim-lang/Nim/issues/11225 +export extension_fields.c0, extension_fields.`c0=` +export extension_fields.c1, extension_fields.`c1=` +export extension_fields.c2, extension_fields.`c2=` + +export extension_fields.setZero +export extension_fields.setOne +export extension_fields.setMinusOne + +export extension_fields.`==` +export extension_fields.isZero +export extension_fields.isOne +export extension_fields.isMinusOne + +export extension_fields.ccopy + +export extension_fields.neg +export extension_fields.`+=` +export extension_fields.`-=` +export extension_fields.double +export extension_fields.div2 +export extension_fields.sum +export extension_fields.diff +export extension_fields.conj +export extension_fields.conjneg + +export extension_fields.csetZero +export extension_fields.csetOne +export extension_fields.cneg +export extension_fields.csub +export extension_fields.cadd + +export extension_fields.`*=` +export extension_fields.prod +export extension_fields.square +export extension_fields.inv + +export extension_fields.isSquare +export extension_fields.sqrt_if_square +export extension_fields.sqrt + +export frobenius.frobenius_map + diff --git a/constantine/lowlevel_fields.nim b/constantine/lowlevel_fields.nim new file mode 100644 index 000000000..230dd3158 --- /dev/null +++ b/constantine/lowlevel_fields.nim @@ -0,0 +1,104 @@ +# Constantine +# Copyright (c) 2018-2019 Status Research & Development GmbH +# Copyright (c) 2020-Present Mamy André-Ratsimbazafy +# Licensed and distributed under either of +# * MIT license (license terms in the root directory or at http://opensource.org/licenses/MIT). +# * Apache v2 license (license terms in the root directory or at http://www.apache.org/licenses/LICENSE-2.0). +# at your option. This file may not be copied, modified, or distributed except according to those terms. + +import + ./platforms/abstractions, + ./named/algebras, + ./math/arithmetic, + ./math/io/[io_bigints, io_fields] + +# ############################################################ +# +# Low-level named Finite Fields API +# +# ############################################################ + +# Warning ⚠️: +# The low-level APIs have no stability guarantee. +# Use high-level protocols which are designed according to a stable specs +# and with misuse resistance in mind. + +{.push raises: [].} # No exceptions allowed in core cryptographic operations +{.push inline.} + +# Base types +# ------------------------------------------------------------ + +export + abstractions, + algebras.Algebra + +# Scalar field Fr and Prime Field Fp +# ------------------------------------------------------------ + +export + algebras.Fp, + algebras.Fr, + algebras.FF + +func unmarshalBE*(dst: var FF, src: openarray[byte]): bool = + ## Return true on success + ## Return false if destination is too small compared to source + var raw {.noInit.}: typeof dst.mres + let ok = raw.unmarshal(src, bigEndian) + if not ok: + return false + dst.fromBig(raw) + return true + +func marshalBE*(dst: var openarray[byte], src: FF): bool = + ## Return true on success + ## Return false if destination is too small compared to source + var raw {.noInit.}: typeof src.mres + raw.fromField(src) + return dst.marshal(raw, bigEndian) + +export arithmetic.fromBig +export arithmetic.fromField + +export arithmetic.ccopy +export arithmetic.cswap + +export arithmetic.`==` +export arithmetic.isZero +export arithmetic.isOne +export arithmetic.isMinusOne + +export arithmetic.setZero +export arithmetic.setOne +export arithmetic.setMinusOne + +export arithmetic.neg +export arithmetic.sum +export arithmetic.`+=` +export arithmetic.diff +export arithmetic.`-=` +export arithmetic.double + +export arithmetic.prod +export arithmetic.`*=` +export arithmetic.square +export arithmetic.square_repeated + +export arithmetic.csetZero +export arithmetic.csetOne +export arithmetic.cneg +export arithmetic.cadd +export arithmetic.csub + +export arithmetic.div2 +export arithmetic.inv + +export arithmetic.isSquare +export arithmetic.invsqrt +export arithmetic.sqrt +export arithmetic.sqrt_invsqrt +export arithmetic.sqrt_invsqrt_if_square +export arithmetic.sqrt_if_square +export arithmetic.invsqrt_if_square +export arithmetic.sqrt_ratio_if_square diff --git a/constantine/lowlevel_pairing_curves.nim b/constantine/lowlevel_pairing_curves.nim new file mode 100644 index 000000000..d4ef869c0 --- /dev/null +++ b/constantine/lowlevel_pairing_curves.nim @@ -0,0 +1,64 @@ +# Constantine +# Copyright (c) 2018-2019 Status Research & Development GmbH +# Copyright (c) 2020-Present Mamy André-Ratsimbazafy +# Licensed and distributed under either of +# * MIT license (license terms in the root directory or at http://opensource.org/licenses/MIT). +# * Apache v2 license (license terms in the root directory or at http://www.apache.org/licenses/LICENSE-2.0). +# at your option. This file may not be copied, modified, or distributed except according to those terms. + +import + ./platforms/abstractions, + ./named/algebras, + ./named/zoo_pairings, + ./math/isogenies/frobenius, + ./math/pairings/[ + cyclotomic_subgroups, + lines_eval, + pairings_generic] +# ############################################################ +# +# Low-level named Pairing-Friendly Curve API +# +# ############################################################ + +# Warning ⚠️: +# The low-level APIs have no stability guarantee. +# Use high-level protocols which are designed according to a stable specs +# and with misuse resistance in mind. + +{.push raises: [].} # No exceptions allowed in core cryptographic operations +{.push inline.} + +# Base types +# ------------------------------------------------------------ + +export + abstractions, + algebras.Algebra + +# Pairings +# ------------------------------------------------------------ + +export frobenius.frobenius_psi + +export lines_eval.Line +export lines_eval.line_double +export lines_eval.line_add +export lines_eval.mul_by_line +export lines_eval.mul_by_2_lines + +export cyclotomic_subgroups.finalExpEasy +export cyclotomic_subgroups.cyclotomic_inv +export cyclotomic_subgroups.cyclotomic_square +export cyclotomic_subgroups.cycl_sqr_repeated +export cyclotomic_subgroups.cyclotomic_exp +export cyclotomic_subgroups.isInCyclotomicSubgroup + +export zoo_pairings.cycl_exp_by_curve_param +export zoo_pairings.cycl_exp_by_curve_param_div2 +export zoo_pairings.millerLoopAddchain +export zoo_pairings.isInPairingSubgroup + +export pairings_generic.pairing +export pairings_generic.millerLoop +export pairings_generic.finalExp diff --git a/constantine/math/arithmetic/finite_fields.nim b/constantine/math/arithmetic/finite_fields.nim index 95890bfd3..e8210984a 100644 --- a/constantine/math/arithmetic/finite_fields.nim +++ b/constantine/math/arithmetic/finite_fields.nim @@ -27,8 +27,8 @@ # which requires a prime import - constantine/platforms/[abstractions, type_ff], - ../../serialization/endians, + constantine/platforms/abstractions, + constantine/serialization/endians, constantine/named/properties_fields, ./bigints, ./bigints_montgomery @@ -55,17 +55,17 @@ export Fp, Fr, FF func fromBig*(dst: var FF, src: BigInt) = ## Convert a BigInt to its Montgomery form when nimvm: - dst.mres.montyResidue_precompute(src, FF.fieldMod(), FF.getR2modP(), FF.getNegInvModWord()) + dst.mres.montyResidue_precompute(src, FF.getModulus(), FF.getR2modP(), FF.getNegInvModWord()) else: - dst.mres.getMont(src, FF.fieldMod(), FF.getR2modP(), FF.getNegInvModWord(), FF.getSpareBits()) + dst.mres.getMont(src, FF.getModulus(), FF.getR2modP(), FF.getNegInvModWord(), FF.getSpareBits()) -func fromBig*[C: static Curve](T: type FF[C], src: BigInt): FF[C] {.noInit.} = +func fromBig*[Name: static Algebra](T: type FF[Name], src: BigInt): FF[Name] {.noInit.} = ## Convert a BigInt to its Montgomery form result.fromBig(src) func fromField*(dst: var BigInt, src: FF) {.inline.} = ## Convert a finite-field element to a BigInt in natural representation - dst.fromMont(src.mres, FF.fieldMod(), FF.getNegInvModWord(), FF.getSpareBits()) + dst.fromMont(src.mres, FF.getModulus(), FF.getNegInvModWord(), FF.getSpareBits()) func toBig*(src: FF): auto {.noInit, inline.} = ## Convert a finite-field element to a BigInt in natural representation @@ -106,7 +106,7 @@ func cswap*(a, b: var FF, ctl: SecretBool) {.meter.} = # exist and can be implemented with compile-time specialization. # Note: for `+=`, double, sum -# not(a.mres < FF.fieldMod()) is unnecessary if the prime has the form +# not(a.mres < FF.getModulus()) is unnecessary if the prime has the form # (2^64)ʷ - 1 (if using uint64 words). # In practice I'm not aware of such prime being using in elliptic curves. # 2^127 - 1 and 2^521 - 1 are used but 127 and 521 are not multiple of 32/64 @@ -154,7 +154,7 @@ func setMinusOne*(a: var FF) = func neg*(r: var FF, a: FF) {.meter.} = ## Negate modulo p when UseASM_X86_64 and a.mres.limbs.len <= 6: # TODO: handle spilling - negmod_asm(r.mres.limbs, a.mres.limbs, FF.fieldMod().limbs) + negmod_asm(r.mres.limbs, a.mres.limbs, FF.getModulus().limbs) else: # If a = 0 we need r = 0 and not r = M # as comparison operator assume unicity @@ -162,7 +162,7 @@ func neg*(r: var FF, a: FF) {.meter.} = # Also make sure to handle aliasing where r.addr = a.addr var t {.noInit.}: FF let isZero = a.isZero() - discard t.mres.diff(FF.fieldMod(), a.mres) + discard t.mres.diff(FF.getModulus(), a.mres) t.mres.csetZero(isZero) r = t @@ -173,38 +173,38 @@ func neg*(a: var FF) {.meter.} = func `+=`*(a: var FF, b: FF) {.meter.} = ## In-place addition modulo p when UseASM_X86_64 and a.mres.limbs.len <= 6: # TODO: handle spilling - addmod_asm(a.mres.limbs, a.mres.limbs, b.mres.limbs, FF.fieldMod().limbs, FF.getSpareBits()) + addmod_asm(a.mres.limbs, a.mres.limbs, b.mres.limbs, FF.getModulus().limbs, FF.getSpareBits()) else: var overflowed = add(a.mres, b.mres) - overflowed = overflowed or not(a.mres < FF.fieldMod()) - discard csub(a.mres, FF.fieldMod(), overflowed) + overflowed = overflowed or not(a.mres < FF.getModulus()) + discard csub(a.mres, FF.getModulus(), overflowed) func `-=`*(a: var FF, b: FF) {.meter.} = ## In-place substraction modulo p when UseASM_X86_64 and a.mres.limbs.len <= 6: # TODO: handle spilling - submod_asm(a.mres.limbs, a.mres.limbs, b.mres.limbs, FF.fieldMod().limbs) + submod_asm(a.mres.limbs, a.mres.limbs, b.mres.limbs, FF.getModulus().limbs) else: let underflowed = sub(a.mres, b.mres) - discard cadd(a.mres, FF.fieldMod(), underflowed) + discard cadd(a.mres, FF.getModulus(), underflowed) func double*(a: var FF) {.meter.} = ## Double ``a`` modulo p when UseASM_X86_64 and a.mres.limbs.len <= 6: # TODO: handle spilling - addmod_asm(a.mres.limbs, a.mres.limbs, a.mres.limbs, FF.fieldMod().limbs, FF.getSpareBits()) + addmod_asm(a.mres.limbs, a.mres.limbs, a.mres.limbs, FF.getModulus().limbs, FF.getSpareBits()) else: var overflowed = double(a.mres) - overflowed = overflowed or not(a.mres < FF.fieldMod()) - discard csub(a.mres, FF.fieldMod(), overflowed) + overflowed = overflowed or not(a.mres < FF.getModulus()) + discard csub(a.mres, FF.getModulus(), overflowed) func sum*(r: var FF, a, b: FF) {.meter.} = ## Sum ``a`` and ``b`` into ``r`` modulo p ## r is initialized/overwritten when UseASM_X86_64 and a.mres.limbs.len <= 6: # TODO: handle spilling - addmod_asm(r.mres.limbs, a.mres.limbs, b.mres.limbs, FF.fieldMod().limbs, FF.getSpareBits()) + addmod_asm(r.mres.limbs, a.mres.limbs, b.mres.limbs, FF.getModulus().limbs, FF.getSpareBits()) else: var overflowed = r.mres.sum(a.mres, b.mres) - overflowed = overflowed or not(r.mres < FF.fieldMod()) - discard csub(r.mres, FF.fieldMod(), overflowed) + overflowed = overflowed or not(r.mres < FF.getModulus()) + discard csub(r.mres, FF.getModulus(), overflowed) func sumUnr*(r: var FF, a, b: FF) {.meter.} = ## Sum ``a`` and ``b`` into ``r`` without reduction @@ -215,10 +215,10 @@ func diff*(r: var FF, a, b: FF) {.meter.} = ## `r` is initialized/overwritten ## Requires r != b when UseASM_X86_64 and a.mres.limbs.len <= 6: # TODO: handle spilling - submod_asm(r.mres.limbs, a.mres.limbs, b.mres.limbs, FF.fieldMod().limbs) + submod_asm(r.mres.limbs, a.mres.limbs, b.mres.limbs, FF.getModulus().limbs) else: var underflowed = r.mres.diff(a.mres, b.mres) - discard cadd(r.mres, FF.fieldMod(), underflowed) + discard cadd(r.mres, FF.getModulus(), underflowed) func diffUnr*(r: var FF, a, b: FF) {.meter.} = ## Substract `b` from `a` and store the result into `r` @@ -229,20 +229,20 @@ func double*(r: var FF, a: FF) {.meter.} = ## Double ``a`` into ``r`` ## `r` is initialized/overwritten when UseASM_X86_64 and a.mres.limbs.len <= 6: # TODO: handle spilling - addmod_asm(r.mres.limbs, a.mres.limbs, a.mres.limbs, FF.fieldMod().limbs, FF.getSpareBits()) + addmod_asm(r.mres.limbs, a.mres.limbs, a.mres.limbs, FF.getModulus().limbs, FF.getSpareBits()) else: var overflowed = r.mres.double(a.mres) - overflowed = overflowed or not(r.mres < FF.fieldMod()) - discard csub(r.mres, FF.fieldMod(), overflowed) + overflowed = overflowed or not(r.mres < FF.getModulus()) + discard csub(r.mres, FF.getModulus(), overflowed) func prod*(r: var FF, a, b: FF, skipFinalSub: static bool = false) {.meter.} = ## Store the product of ``a`` by ``b`` modulo p into ``r`` ## ``r`` is initialized / overwritten - r.mres.mulMont(a.mres, b.mres, FF.fieldMod(), FF.getNegInvModWord(), FF.getSpareBits(), skipFinalSub) + r.mres.mulMont(a.mres, b.mres, FF.getModulus(), FF.getNegInvModWord(), FF.getSpareBits(), skipFinalSub) func square*(r: var FF, a: FF, skipFinalSub: static bool = false) {.meter.} = ## Squaring modulo p - r.mres.squareMont(a.mres, FF.fieldMod(), FF.getNegInvModWord(), FF.getSpareBits(), skipFinalSub) + r.mres.squareMont(a.mres, FF.getModulus(), FF.getNegInvModWord(), FF.getSpareBits(), skipFinalSub) func sumprod*[N: static int](r: var FF, a, b: array[N, FF], skipFinalSub: static bool = false) {.meter.} = ## Compute r <- ⅀aᵢ.bᵢ (mod M) (sum of products) @@ -250,7 +250,7 @@ func sumprod*[N: static int](r: var FF, a, b: array[N, FF], skipFinalSub: static r.mres.sumprodMont( cast[ptr array[N, typeof(a[0].mres)]](a.unsafeAddr)[], cast[ptr array[N, typeof(b[0].mres)]](b.unsafeAddr)[], - FF.fieldMod(), FF.getNegInvModWord(), FF.getSpareBits(), skipFinalSub) + FF.getModulus(), FF.getNegInvModWord(), FF.getSpareBits(), skipFinalSub) # ############################################################ # @@ -330,7 +330,7 @@ func inv*(r: var FF, a: FF) = ## Incidentally this avoids extra check ## to convert Jacobian and Projective coordinates ## to affine for elliptic curve - r.mres.invmod(a.mres, FF.getR2modP(), FF.fieldMod()) + r.mres.invmod(a.mres, FF.getR2modP(), FF.getModulus()) func inv*(a: var FF) = ## Inversion modulo p @@ -348,7 +348,7 @@ func inv_vartime*(r: var FF, a: FF) {.tags: [VarTime].} = ## Incidentally this avoids extra check ## to convert Jacobian and Projective coordinates ## to affine for elliptic curve - r.mres.invmod_vartime(a.mres, FF.getR2modP(), FF.fieldMod()) + r.mres.invmod_vartime(a.mres, FF.getR2modP(), FF.getModulus()) func inv_vartime*(a: var FF) {.tags: [VarTime].} = ## Variable-time Inversion modulo p @@ -513,7 +513,7 @@ func pow*(a: var FF, exponent: BigInt) = const windowSize = 5 # TODO: find best window size for each curves a.mres.powMont( exponent, - FF.fieldMod(), FF.getMontyOne(), + FF.getModulus(), FF.getMontyOne(), FF.getNegInvModWord(), windowSize, FF.getSpareBits() ) @@ -525,7 +525,7 @@ func pow*(a: var FF, exponent: openarray[byte]) = const windowSize = 5 # TODO: find best window size for each curves a.mres.powMont( exponent, - FF.fieldMod(), FF.getMontyOne(), + FF.getModulus(), FF.getMontyOne(), FF.getNegInvModWord(), windowSize, FF.getSpareBits() ) @@ -544,7 +544,7 @@ func pow_vartime*(a: var FF, exponent: BigInt) = const windowSize = 5 # TODO: find best window size for each curves a.mres.powMont_vartime( exponent, - FF.fieldMod(), FF.getMontyOne(), + FF.getModulus(), FF.getMontyOne(), FF.getNegInvModWord(), windowSize, FF.getSpareBits() ) @@ -563,7 +563,7 @@ func pow_vartime*(a: var FF, exponent: openarray[byte]) = const windowSize = 5 # TODO: find best window size for each curves a.mres.powMont_vartime( exponent, - FF.fieldMod(), FF.getMontyOne(), + FF.getModulus(), FF.getMontyOne(), FF.getNegInvModWord(), windowSize, FF.getSpareBits() ) @@ -700,9 +700,9 @@ func pow_vartime(a: var FF, exponent: SomeUnsignedInt) {.tags:[VarTime], meter.} else: a.pow_squareMultiply_vartime(exponent) -func computeSparsePowers_vartime*[C]( - dst: ptr UncheckedArray[FF[C]], - base: FF[C], +func computeSparsePowers_vartime*[Name]( + dst: ptr UncheckedArray[FF[Name]], + base: FF[Name], sparsePowers: ptr UncheckedArray[SomeUnsignedInt], len: int) = ## Compute sparse powers of base @@ -714,7 +714,7 @@ func computeSparsePowers_vartime*[C]( dst[i] = dst[i-1] dst[i].pow_vartime(sparsePowers[i]-sparsePowers[i-1]) -func computePowers*[C](dst: ptr UncheckedArray[FF[C]], base: FF[C], len: int) = +func computePowers*[Name](dst: ptr UncheckedArray[FF[Name]], base: FF[Name], len: int) = ## We need linearly independent random numbers ## for batch proof sampling. ## Powers are linearly independent. @@ -777,9 +777,9 @@ macro addchain*(fn: untyped): untyped = # # ############################################################ -func batchFromField*[N, C]( +func batchFromField*[N, Name]( dst: ptr UncheckedArray[BigInt[N]], - src: ptr UncheckedArray[FF[C]], + src: ptr UncheckedArray[FF[Name]], len: int) {.inline.} = for i in 0 ..< len: dst[i].fromField(src[i]) diff --git a/constantine/math/arithmetic/finite_fields_double_precision.nim b/constantine/math/arithmetic/finite_fields_double_precision.nim index 342df7500..55c49ec6a 100644 --- a/constantine/math/arithmetic/finite_fields_double_precision.nim +++ b/constantine/math/arithmetic/finite_fields_double_precision.nim @@ -18,7 +18,7 @@ import when UseASM_X86_64: import assembly/limbs_asm_modular_dbl_prec_x86 -type FpDbl*[C: static Curve] = object +type FpDbl*[Name: static Algebra] = object ## Double-precision Fp element ## A FpDbl is a partially-reduced double-precision element of Fp ## The allowed range is [0, 2ⁿp) @@ -28,11 +28,14 @@ type FpDbl*[C: static Curve] = object ## and so FpDbl would 768 bits. # We directly work with double the number of limbs, # instead of BigInt indirection. - limbs2x*: matchingLimbs2x(C) + limbs2x*: getLimbs2x(Name) + +template getModulus(Field: type FpDbl): untyped = + Fp[Field.Name].getModulus() template doublePrec*(T: type Fp): type = ## Return the double-precision type matching with Fp - FpDbl[T.C] + FpDbl[T.Name] # No exceptions allowed {.push raises: [].} @@ -75,7 +78,7 @@ func redc2x*(r: var Fp, a: FpDbl) = redc2xMont( r.mres.limbs, a.limbs2x, - Fp.C.Mod.limbs, + Fp.getModulus().limbs, Fp.getNegInvModWord(), Fp.getSpareBits() ) @@ -92,18 +95,17 @@ func diff2xMod*(r: var FpDbl, a, b: FpDbl) = ## Output is conditionally reduced by 2ⁿp ## to stay in the [0, 2ⁿp) range when UseASM_X86_64: - submod2x_asm(r.limbs2x, a.limbs2x, b.limbs2x, FpDbl.C.Mod.limbs) + submod2x_asm(r.limbs2x, a.limbs2x, b.limbs2x, FpDbl.getModulus().limbs) else: # Substraction step var underflowed = SecretBool r.limbs2x.diff(a.limbs2x, b.limbs2x) # Conditional reduction by 2ⁿp const N = r.limbs2x.len div 2 - const M = FpDbl.C.Mod var carry = Carry(0) var sum: SecretWord staticFor i, 0, N: - addC(carry, sum, r.limbs2x[i+N], M.limbs[i], carry) + addC(carry, sum, r.limbs2x[i+N], FpDbl.getModulus().limbs[i], carry) underflowed.ccopy(r.limbs2x[i+N], sum) func sum2xUnr*(r: var FpDbl, a, b: FpDbl) = @@ -118,13 +120,13 @@ func sum2xMod*(r: var FpDbl, a, b: FpDbl) = ## Output is conditionally reduced by 2ⁿp ## to stay in the [0, 2ⁿp) range when UseASM_X86_64: - addmod2x_asm(r.limbs2x, a.limbs2x, b.limbs2x, FpDbl.C.Mod.limbs, Fp[FpDbl.C].getSpareBits()) + addmod2x_asm(r.limbs2x, a.limbs2x, b.limbs2x, FpDbl.getModulus().limbs, Fp[FpDbl.Name].getSpareBits()) else: # Addition step var overflowed = SecretBool r.limbs2x.sum(a.limbs2x, b.limbs2x) const N = r.limbs2x.len div 2 - const M = FpDbl.C.Mod + const M = FpDbl.getModulus() # Test >= 2ⁿp var borrow = Borrow(0) var t{.noInit.}: Limbs[N] @@ -142,7 +144,7 @@ func neg2xMod*(r: var FpDbl, a: FpDbl) = ## Double-precision modular substraction ## Negate modulo 2ⁿp when UseASM_X86_64: - negmod2x_asm(r.limbs2x, a.limbs2x, FpDbl.C.Mod.limbs) + negmod2x_asm(r.limbs2x, a.limbs2x, FpDbl.getModulus().limbs) else: # If a = 0 we need r = 0 and not r = M # as comparison operator assume unicity @@ -151,7 +153,7 @@ func neg2xMod*(r: var FpDbl, a: FpDbl) = var t {.noInit.}: FpDbl let isZero = a.isZero() const N = r.limbs2x.len div 2 - const M = FpDbl.C.Mod + const M = FpDbl.getModulus() var borrow = Borrow(0) # 2ⁿp is filled with 0 in the first half staticFor i, 0, N: diff --git a/constantine/math/arithmetic/finite_fields_square_root.nim b/constantine/math/arithmetic/finite_fields_square_root.nim index 332908382..253d92162 100644 --- a/constantine/math/arithmetic/finite_fields_square_root.nim +++ b/constantine/math/arithmetic/finite_fields_square_root.nim @@ -45,8 +45,8 @@ func invsqrt_p3mod4(r: var Fp, a: Fp) = # a^((p-1)/2)) * a^-1 ≡ 1/a (mod p) # a^((p-3)/2)) ≡ 1/a (mod p) # a^((p-3)/4)) ≡ 1/√a (mod p) # Requires p ≡ 3 (mod 4) - static: doAssert Fp.C.has_P_3mod4_primeModulus() - when FP.C.hasSqrtAddchain(): + static: doAssert Fp.Name.has_P_3mod4_primeModulus() + when FP.Name.hasSqrtAddchain(): r.invsqrt_addchain(a) else: r = a @@ -105,13 +105,13 @@ func invsqrt_p5mod8(r: var Fp, a: Fp) = # # Hence we set β = (2a)^((p-1)/4) # and α = (β/2a)⁽¹⸍²⁾= (2a)^(((p-1)/4 - 1)/2) = (2a)^((p-5)/8) - static: doAssert Fp.C.has_P_5mod8_primeModulus() + static: doAssert Fp.Name.has_P_5mod8_primeModulus() var alpha{.noInit.}, beta{.noInit.}: Fp # α = (2a)^((p-5)/8) alpha.double(a) beta = alpha - when Fp.C.hasSqrtAddchain(): + when Fp.Name.hasSqrtAddchain(): alpha.invsqrt_addchain_pminus5over8(alpha) else: alpha.pow_vartime(Fp.getPrimeMinus5div8_BE()) @@ -137,11 +137,11 @@ func invsqrt_p5mod8(r: var Fp, a: Fp) = # ------------------------------------------------------------ func precompute_tonelli_shanks(a_pre_exp: var Fp, a: Fp) = - when FP.C.hasTonelliShanksAddchain(): + when FP.Name.hasTonelliShanksAddchain(): a_pre_exp.precompute_tonelli_shanks_addchain(a) else: a_pre_exp = a - a_pre_exp.pow_vartime(Fp.C.tonelliShanks(exponent)) + a_pre_exp.pow_vartime(Fp.Name.tonelliShanks(exponent)) func invsqrt_tonelli_shanks_pre( invsqrt: var Fp, @@ -154,13 +154,13 @@ func invsqrt_tonelli_shanks_pre( template z: untyped = a_pre_exp template r: untyped = invsqrt var t {.noInit.}: Fp - const e = Fp.C.tonelliShanks(twoAdicity) + const e = Fp.Name.tonelliShanks(twoAdicity) t.square(z) t *= a r = z var b {.noInit.} = t - var root {.noInit.} = Fp.C.tonelliShanks(root_of_unity) + var root {.noInit.} = Fp.Name.tonelliShanks(root_of_unity) var buf {.noInit.}: Fp @@ -196,7 +196,7 @@ func invsqrt_tonelli_shanks*(r: var Fp, a: Fp) = {.push inline.} -func invsqrt*[C](r: var Fp[C], a: Fp[C]) = +func invsqrt*[Name](r: var Fp[Name], a: Fp[Name]) = ## Compute the inverse square root of ``a`` ## ## This requires ``a`` to be a square @@ -207,14 +207,14 @@ func invsqrt*[C](r: var Fp[C], a: Fp[C]) = ## i.e. both x² == (-x)² ## This procedure returns a deterministic result ## This procedure is constant-time - when C.has_P_3mod4_primeModulus(): + when Name.has_P_3mod4_primeModulus(): r.invsqrt_p3mod4(a) - elif C.has_P_5mod8_primeModulus(): + elif Name.has_P_5mod8_primeModulus(): r.invsqrt_p5mod8(a) else: r.invsqrt_tonelli_shanks(a) -func invsqrt_vartime*[C](r: var Fp[C], a: Fp[C]) = +func invsqrt_vartime*[Name](r: var Fp[Name], a: Fp[Name]) = ## Compute the inverse square root of ``a`` ## ## This requires ``a`` to be a square @@ -226,16 +226,16 @@ func invsqrt_vartime*[C](r: var Fp[C], a: Fp[C]) = ## This procedure returns a deterministic result ## ## This procedure is NOT constant-time - when C.has_P_3mod4_primeModulus(): + when Name.has_P_3mod4_primeModulus(): r.invsqrt_p3mod4(a) - elif C.has_P_5mod8_primeModulus(): + elif Name.has_P_5mod8_primeModulus(): r.invsqrt_p5mod8(a) - elif C == Bandersnatch or C == Banderwagon: + elif Name == Bandersnatch or Name == Banderwagon: r.inv_sqrt_precomp_vartime(a) else: r.invsqrt_tonelli_shanks(a) -func sqrt*[C](a: var Fp[C]) = +func sqrt*[Name](a: var Fp[Name]) = ## Compute the square root of ``a`` ## ## This requires ``a`` to be a square @@ -246,11 +246,11 @@ func sqrt*[C](a: var Fp[C]) = ## i.e. both x² == (-x)² ## This procedure returns a deterministic result ## This procedure is constant-time - var t {.noInit.}: Fp[C] + var t {.noInit.}: Fp[Name] t.invsqrt(a) a *= t -func sqrt_vartime*[C](a: var Fp[C]) = +func sqrt_vartime*[Name](a: var Fp[Name]) = ## Compute the square root of ``a`` ## ## This requires ``a`` to be a square @@ -258,11 +258,11 @@ func sqrt_vartime*[C](a: var Fp[C]) = ## The result is undefined otherwise ## ## This is NOT constant-time - var t {.noInit.}: Fp[C] + var t {.noInit.}: Fp[Name] t.invsqrt_vartime(a) a *= t -func sqrt_invsqrt*[C](sqrt, invsqrt: var Fp[C], a: Fp[C]) = +func sqrt_invsqrt*[Name](sqrt, invsqrt: var Fp[Name], a: Fp[Name]) = ## Compute the square root and inverse square root of ``a`` ## ## This requires ``a`` to be a square @@ -275,7 +275,7 @@ func sqrt_invsqrt*[C](sqrt, invsqrt: var Fp[C], a: Fp[C]) = invsqrt.invsqrt(a) sqrt.prod(invsqrt, a) -func sqrt_invsqrt_vartime*[C](sqrt, invsqrt: var Fp[C], a: Fp[C]) = +func sqrt_invsqrt_vartime*[Name](sqrt, invsqrt: var Fp[Name], a: Fp[Name]) = ## Compute the square root of ``a`` and inverse square root of ``a`` ## ## This requires ``a`` to be a square @@ -286,7 +286,7 @@ func sqrt_invsqrt_vartime*[C](sqrt, invsqrt: var Fp[C], a: Fp[C]) = invsqrt.invsqrt_vartime(a) sqrt.prod(invsqrt, a) -func sqrt_invsqrt_if_square*[C](sqrt, invsqrt: var Fp[C], a: Fp[C]): SecretBool = +func sqrt_invsqrt_if_square*[Name](sqrt, invsqrt: var Fp[Name], a: Fp[Name]): SecretBool = ## Compute the square root and ivnerse square root of ``a`` ## ## This returns true if ``a`` is square and sqrt/invsqrt contains the square root/inverse square root @@ -297,11 +297,11 @@ func sqrt_invsqrt_if_square*[C](sqrt, invsqrt: var Fp[C], a: Fp[C]): SecretBool ## i.e. both x² == (-x)² ## This procedure returns a deterministic result sqrt_invsqrt(sqrt, invsqrt, a) - var test {.noInit.}: Fp[C] + var test {.noInit.}: Fp[Name] test.square(sqrt) result = test == a -func sqrt_invsqrt_if_square_vartime*[C](sqrt, invsqrt: var Fp[C], a: Fp[C]): SecretBool = +func sqrt_invsqrt_if_square_vartime*[Name](sqrt, invsqrt: var Fp[Name], a: Fp[Name]): SecretBool = ## Compute the square root and ivnerse square root of ``a`` ## ## This returns true if ``a`` is square and sqrt/invsqrt contains the square root/inverse square root @@ -310,11 +310,11 @@ func sqrt_invsqrt_if_square_vartime*[C](sqrt, invsqrt: var Fp[C], a: Fp[C]): Sec ## ## This is NOT constant-time sqrt_invsqrt_vartime(sqrt, invsqrt, a) - var test {.noInit.}: Fp[C] + var test {.noInit.}: Fp[Name] test.square(sqrt) result = test == a -func sqrt_if_square*[C](a: var Fp[C]): SecretBool = +func sqrt_if_square*[Name](a: var Fp[Name]): SecretBool = ## If ``a`` is a square, compute the square root of ``a`` ## if not, ``a`` is undefined. ## @@ -322,11 +322,11 @@ func sqrt_if_square*[C](a: var Fp[C]): SecretBool = ## i.e. both x² == (-x)² ## This procedure returns a deterministic result ## This procedure is constant-time - var sqrt{.noInit.}, invsqrt{.noInit.}: Fp[C] + var sqrt{.noInit.}, invsqrt{.noInit.}: Fp[Name] result = sqrt_invsqrt_if_square(sqrt, invsqrt, a) a = sqrt -func sqrt_if_square_vartime*[C](a: var Fp[C]): SecretBool = +func sqrt_if_square_vartime*[Name](a: var Fp[Name]): SecretBool = ## If ``a`` is a square, compute the square root of ``a`` ## if not, ``a`` is undefined. ## @@ -335,11 +335,11 @@ func sqrt_if_square_vartime*[C](a: var Fp[C]): SecretBool = ## This procedure returns a deterministic result ## ## This is NOT constant-time - var sqrt{.noInit.}, invsqrt{.noInit.}: Fp[C] + var sqrt{.noInit.}, invsqrt{.noInit.}: Fp[Name] result = sqrt_invsqrt_if_square_vartime(sqrt, invsqrt, a) a = sqrt -func invsqrt_if_square*[C](r: var Fp[C], a: Fp[C]): SecretBool = +func invsqrt_if_square*[Name](r: var Fp[Name], a: Fp[Name]): SecretBool = ## If ``a`` is a square, compute the inverse square root of ``a`` ## if not, ``a`` is undefined. ## @@ -347,15 +347,15 @@ func invsqrt_if_square*[C](r: var Fp[C], a: Fp[C]): SecretBool = ## i.e. both x² == (-x)² ## This procedure returns a deterministic result ## This procedure is constant-time - var sqrt{.noInit.}: Fp[C] + var sqrt{.noInit.}: Fp[Name] result = sqrt_invsqrt_if_square(sqrt, r, a) -func invsqrt_if_square_vartime*[C](r: var Fp[C], a: Fp[C]): SecretBool = +func invsqrt_if_square_vartime*[Name](r: var Fp[Name], a: Fp[Name]): SecretBool = ## If ``a`` is a square, compute the inverse square root of ``a`` ## if not, ``a`` is undefined. ## ## This procedure is NOT constant-time - var sqrt{.noInit.}: Fp[C] + var sqrt{.noInit.}: Fp[Name] result = sqrt_invsqrt_if_square_vartime(sqrt, r, a) # Legendre symbol / Euler's Criterion / Kronecker's symbol @@ -365,9 +365,9 @@ func isSquare*(a: Fp): SecretBool = ## Returns true if ``a`` is a square (quadratic residue) in 𝔽p ## ## Assumes that the prime modulus ``p`` is public. - var aa {.noInit.}: matchingBigInt(Fp.C) + var aa {.noInit.}: Fp.getBigInt() aa.fromField(a) - let symbol = legendre(aa.limbs, Fp.fieldMod().limbs, aa.bits) + let symbol = legendre(aa.limbs, Fp.getModulus().limbs, aa.bits) return not(symbol == MaxWord) {.pop.} # inline diff --git a/constantine/math/arithmetic/finite_fields_square_root_precomp.nim b/constantine/math/arithmetic/finite_fields_square_root_precomp.nim index aa6b6e772..5e3ee6024 100644 --- a/constantine/math/arithmetic/finite_fields_square_root_precomp.nim +++ b/constantine/math/arithmetic/finite_fields_square_root_precomp.nim @@ -29,13 +29,13 @@ import # NOTE: If x is not a root of unity as asserted, the behaviour is undefined. func sqrtAlg_NegDlogInSmallDyadicSubgroup_vartime(x: Fp): int {.tags:[VarTime], raises: [].} = let key = cast[int](x.mres.limbs[0] and SecretWord 0xFFFF) - return Fp.C.sqrtDlog(dlogLUT).getOrDefault(key, 0) + return Fp.Name.sqrtDlog(dlogLUT).getOrDefault(key, 0) # sqrtAlg_GetPrecomputedRootOfUnity sets target to g^(multiplier << (order * sqrtParam_BlockSize)), where g is the fixed primitive 2^32th root of unity. # # We assume that order 0 <= order*sqrtParam_BlockSize <= 32 and that multiplier is in [0, 1 <= L, "Cannot decompose a scalar smaller than a mini-scalar or the decomposition coefficient" # Equal when no window or no negative handling, greater otherwise static: doAssert L >= ceilDiv_vartime(scalBits, M) + 1 - const w = F.C.getCurveOrderBitwidth().wordsRequired() + const w = Fr[F.Name].bits().wordsRequired() # Upstream bug: # {.noInit.} variables must be {.inject.} as well @@ -326,8 +330,8 @@ func scalarMulEndo*[scalBits; EC]( ## - Cofactor to be cleared ## - 0 <= scalar < curve order mixin affine - const C = P.F.C # curve - static: doAssert scalBits <= C.getCurveOrderBitwidth(), "Do not use endomorphism to multiply beyond the curve order" + const C = P.F.Name # curve + static: doAssert scalBits <= EC.getScalarField().bits(), "Do not use endomorphism to multiply beyond the curve order" when P.F is Fp: const M = 2 # 1. Compute endomorphisms @@ -513,8 +517,8 @@ func scalarMulGLV_m2w2*[scalBits; EC](P0: var EC, scalar: BigInt[scalBits]) {.me ## - Cofactor to be cleared ## - 0 <= scalar < curve order mixin affine - const C = P0.F.C # curve - static: doAssert: scalBits <= C.getCurveOrderBitwidth() + const C = P0.F.Name # curve + static: doAssert: scalBits <= EC.getScalarField().bits() # 1. Compute endomorphisms when P0.G == G1: @@ -525,7 +529,7 @@ func scalarMulGLV_m2w2*[scalBits; EC](P0: var EC, scalar: BigInt[scalBits]) {.me P1.frobenius_psi(P0, 2) # 2. Decompose scalar into mini-scalars - const L = computeRecodedLength(C.getCurveOrderBitwidth(), 2) + const L = computeRecodedLength(EC.getScalarField().bits(), 2) var miniScalars {.noInit.}: array[2, BigInt[L]] var negatePoints {.noInit.}: array[2, SecretBool] miniScalars.decomposeEndo(negatePoints, scalar, P0.F) diff --git a/constantine/math/elliptic/ec_multi_scalar_mul.nim b/constantine/math/elliptic/ec_multi_scalar_mul.nim index c6b87af5f..d1068a317 100644 --- a/constantine/math/elliptic/ec_multi_scalar_mul.nim +++ b/constantine/math/elliptic/ec_multi_scalar_mul.nim @@ -147,7 +147,7 @@ func multiScalarMul_reference_vartime*[F, EC, ECaff]( ## Multiscalar multiplication: ## r <- [a₀]P₀ + [a₁]P₁ + ... + [aₙ₋₁]Pₙ₋₁ let n = cast[int](len) - let coefs_big = allocHeapArrayAligned(matchingOrderBigInt(F.C), n, alignment = 64) + let coefs_big = allocHeapArrayAligned(F.getBigInt(), n, alignment = 64) coefs_big.batchFromField(coefs, n) r.multiScalarMul_reference_vartime(coefs_big, points, n) @@ -412,7 +412,7 @@ proc applyEndomorphism[bits: static int, ECaff]( endoBasis[i][0] = points[i] when ECaff.F is Fp: - endoBasis[i][1].x.prod(points[i].x, ECaff.F.C.getCubicRootOfUnity_mod_p()) + endoBasis[i][1].x.prod(points[i].x, ECaff.F.Name.getCubicRootOfUnity_mod_p()) if negatePoints[1].bool: endoBasis[i][1].y.neg(points[i].y) else: @@ -428,13 +428,13 @@ proc applyEndomorphism[bits: static int, ECaff]( return (endoCoefs, endoPoints, M*N) -template withEndo[bits: static int, EC, ECaff]( +template withEndo[coefsBits: static int, EC, ECaff]( msmProc: untyped, r: var EC, - coefs: ptr UncheckedArray[BigInt[bits]], + coefs: ptr UncheckedArray[BigInt[coefsBits]], points: ptr UncheckedArray[ECaff], N: int, c: static int) = - when bits <= EC.F.C.getCurveOrderBitwidth() and hasEndomorphismAcceleration(EC.F.C): + when coefsBits <= EC.getScalarField().bits() and hasEndomorphismAcceleration(EC.F.Name): let (endoCoefs, endoPoints, endoN) = applyEndomorphism(coefs, points, N) # Given that bits and N changed, we are able to use a bigger `c` # but it has no significant impact on performance @@ -445,9 +445,9 @@ template withEndo[bits: static int, EC, ECaff]( msmProc(r, coefs, points, N, c) func multiScalarMul_dispatch_vartime[bits: static int, F, G]( - r: var (ECP_ShortW_Jac[F, G] or ECP_ShortW_Prj[F, G]), + r: var (EC_ShortW_Jac[F, G] or EC_ShortW_Prj[F, G]), coefs: ptr UncheckedArray[BigInt[bits]], - points: ptr UncheckedArray[ECP_ShortW_Aff[F, G]], N: int) = + points: ptr UncheckedArray[EC_ShortW_Aff[F, G]], N: int) = ## Multiscalar multiplication: ## r <- [a₀]P₀ + [a₁]P₁ + ... + [aₙ]Pₙ let c = bestBucketBitSize(N, bits, useSignedBuckets = true, useManualTuning = true) @@ -478,8 +478,8 @@ func multiScalarMul_dispatch_vartime[bits: static int, F, G]( unreachable() func multiScalarMul_dispatch_vartime[bits: static int, F]( - r: var ECP_TwEdwards_Prj[F], coefs: ptr UncheckedArray[BigInt[bits]], - points: ptr UncheckedArray[ECP_TwEdwards_Aff[F]], N: int) = + r: var EC_TwEdw_Prj[F], coefs: ptr UncheckedArray[BigInt[bits]], + points: ptr UncheckedArray[EC_TwEdw_Aff[F]], N: int) = ## Multiscalar multiplication: ## r <- [a₀]P₀ + [a₁]P₁ + ... + [aₙ]Pₙ @@ -539,7 +539,7 @@ func multiScalarMul_vartime*[F, EC, ECaff]( ## r <- [a₀]P₀ + [a₁]P₁ + ... + [aₙ₋₁]Pₙ₋₁ let n = cast[int](len) - let coefs_big = allocHeapArrayAligned(matchingOrderBigInt(F.C), n, alignment = 64) + let coefs_big = allocHeapArrayAligned(F.getBigInt(), n, alignment = 64) coefs_big.batchFromField(coefs, n) r.multiScalarMul_vartime(coefs_big, points, n) diff --git a/constantine/math/elliptic/ec_multi_scalar_mul_parallel.nim b/constantine/math/elliptic/ec_multi_scalar_mul_parallel.nim index cb2497ae0..03e6ff24d 100644 --- a/constantine/math/elliptic/ec_multi_scalar_mul_parallel.nim +++ b/constantine/math/elliptic/ec_multi_scalar_mul_parallel.nim @@ -281,7 +281,7 @@ proc bucketAccumReduce_parallel[bits: static int, EC, ECaff]( if kAffine in buckets.status[numBuckets-1]: if kNonAffine in buckets.status[numBuckets-1]: - accumBuckets.madd_vartime(buckets.pt[numBuckets-1], buckets.ptAff[numBuckets-1]) + accumBuckets.mixedSum_vartime(buckets.pt[numBuckets-1], buckets.ptAff[numBuckets-1]) else: accumBuckets.fromAffine(buckets.ptAff[numBuckets-1]) elif kNonAffine in buckets.status[numBuckets-1]: @@ -303,7 +303,7 @@ proc bucketAccumReduce_parallel[bits: static int, EC, ECaff]( if kAffine in buckets.status[k]: if kNonAffine in buckets.status[k]: var t{.noInit.}: EC - t.madd_vartime(buckets.pt[k], buckets.ptAff[k]) + t.mixedSum_vartime(buckets.pt[k], buckets.ptAff[k]) accumBuckets ~+= t else: accumBuckets ~+= buckets.ptAff[k] @@ -478,7 +478,7 @@ proc applyEndomorphism_parallel[bits: static int, ECaff]( endoBasis[i][0] = points[i] when ECaff.F is Fp: - endoBasis[i][1].x.prod(points[i].x, ECaff.F.C.getCubicRootOfUnity_mod_p()) + endoBasis[i][1].x.prod(points[i].x, ECaff.F.Name.getCubicRootOfUnity_mod_p()) if negatePoints[1].bool: endoBasis[i][1].y.neg(points[i].y) else: @@ -494,14 +494,14 @@ proc applyEndomorphism_parallel[bits: static int, ECaff]( return (endoCoefs, endoPoints, M*N) -template withEndo[bits: static int, EC, ECaff]( +template withEndo[coefsBits: static int, EC, ECaff]( msmProc: untyped, tp: Threadpool, r: ptr EC, - coefs: ptr UncheckedArray[BigInt[bits]], + coefs: ptr UncheckedArray[BigInt[coefsBits]], points: ptr UncheckedArray[ECaff], N: int, c: static int) = - when bits <= EC.F.C.getCurveOrderBitwidth() and hasEndomorphismAcceleration(EC.F.C): + when coefsBits <= EC.getScalarField().bits() and hasEndomorphismAcceleration(EC.F.Name): let (endoCoefs, endoPoints, endoN) = applyEndomorphism_parallel(tp, coefs, points, N) # Given that bits and N changed, we are able to use a bigger `c` # but it has no significant impact on performance @@ -511,14 +511,14 @@ template withEndo[bits: static int, EC, ECaff]( else: msmProc(tp, r, coefs, points, N, c) -template withEndo[bits: static int, EC, ECaff]( +template withEndo[coefsBits: static int, EC, ECaff]( msmProc: untyped, tp: Threadpool, r: ptr EC, - coefs: ptr UncheckedArray[BigInt[bits]], + coefs: ptr UncheckedArray[BigInt[coefsBits]], points: ptr UncheckedArray[ECaff], N: int, c: static int, useParallelBuckets: static bool) = - when bits <= EC.F.C.getCurveOrderBitwidth() and hasEndomorphismAcceleration(EC.F.C): + when coefsBits <= EC.getScalarField().bits() and hasEndomorphismAcceleration(EC.F.Name): let (endoCoefs, endoPoints, endoN) = applyEndomorphism_parallel(tp, coefs, points, N) # Given that bits and N changed, we are able to use a bigger `c` # but it has no significant impact on performance @@ -530,9 +530,9 @@ template withEndo[bits: static int, EC, ECaff]( proc multiScalarMul_dispatch_vartime_parallel[bits: static int, F, G]( tp: Threadpool, - r: ptr (ECP_ShortW_Jac[F, G] or ECP_ShortW_Prj[F, G]), + r: ptr (EC_ShortW_Jac[F, G] or EC_ShortW_Prj[F, G]), coefs: ptr UncheckedArray[BigInt[bits]], - points: ptr UncheckedArray[ECP_ShortW_Aff[F, G]], N: int) = + points: ptr UncheckedArray[EC_ShortW_Aff[F, G]], N: int) = ## Multiscalar multiplication: ## r <- [a₀]P₀ + [a₁]P₁ + ... + [aₙ]Pₙ let c = bestBucketBitSize(N, bits, useSignedBuckets = true, useManualTuning = true) @@ -566,8 +566,8 @@ proc multiScalarMul_dispatch_vartime_parallel[bits: static int, F, G]( proc multiScalarMul_dispatch_vartime_parallel[bits: static int, F]( tp: Threadpool, - r: ptr ECP_TwEdwards_Prj[F], coefs: ptr UncheckedArray[BigInt[bits]], - points: ptr UncheckedArray[ECP_TwEdwards_Aff[F]], N: int) = + r: ptr EC_TwEdw_Prj[F], coefs: ptr UncheckedArray[BigInt[bits]], + points: ptr UncheckedArray[EC_TwEdw_Aff[F]], N: int) = ## Multiscalar multiplication: ## r <- [a₀]P₀ + [a₁]P₁ + ... + [aₙ]Pₙ let c = bestBucketBitSize(N, bits, useSignedBuckets = true, useManualTuning = true) @@ -631,7 +631,7 @@ proc multiScalarMul_vartime_parallel*[F, EC, ECaff]( ## r <- [a₀]P₀ + [a₁]P₁ + ... + [aₙ₋₁]Pₙ₋₁ let n = cast[int](len) - let coefs_big = allocHeapArrayAligned(matchingOrderBigInt(F.C), n, alignment = 64) + let coefs_big = allocHeapArrayAligned(F.getBigInt(), n, alignment = 64) syncScope: tp.parallelFor i in 0 ..< n: diff --git a/constantine/math/elliptic/ec_multi_scalar_mul_scheduler.nim b/constantine/math/elliptic/ec_multi_scalar_mul_scheduler.nim index e37c26032..ea3eb083f 100644 --- a/constantine/math/elliptic/ec_multi_scalar_mul_scheduler.nim +++ b/constantine/math/elliptic/ec_multi_scalar_mul_scheduler.nim @@ -559,7 +559,7 @@ func bucketReduce*[N, EC, ECaff]( if kAffine in buckets.status[N-1]: if kNonAffine in buckets.status[N-1]: - accumBuckets.madd_vartime(buckets.pt[N-1], buckets.ptAff[N-1]) + accumBuckets.mixedSum_vartime(buckets.pt[N-1], buckets.ptAff[N-1]) else: accumBuckets.fromAffine(buckets.ptAff[N-1]) elif kNonAffine in buckets.status[N-1]: @@ -573,7 +573,7 @@ func bucketReduce*[N, EC, ECaff]( if kAffine in buckets.status[k]: if kNonAffine in buckets.status[k]: var t{.noInit.}: EC - t.madd_vartime(buckets.pt[k], buckets.ptAff[k]) + t.mixedSum_vartime(buckets.pt[k], buckets.ptAff[k]) accumBuckets ~+= t else: accumBuckets ~+= buckets.ptAff[k] diff --git a/constantine/math/elliptic/ec_scalar_mul.nim b/constantine/math/elliptic/ec_scalar_mul.nim index c661d1b3d..76b3de5f5 100644 --- a/constantine/math/elliptic/ec_scalar_mul.nim +++ b/constantine/math/elliptic/ec_scalar_mul.nim @@ -13,7 +13,12 @@ import constantine/math/extension_fields, constantine/math/io/io_bigints, constantine/named/zoo_endomorphisms, - ./ec_endomorphism_accel + ./ec_endomorphism_accel, + ./ec_shortweierstrass_affine, + ./ec_shortweierstrass_projective, + ./ec_shortweierstrass_jacobian, + ./ec_twistededwards_affine, + ./ec_twistededwards_projective # ############################################################ # # @@ -237,8 +242,8 @@ func scalarMul*[EC](P: var EC, scalar: BigInt) {.inline, meter.} = ## - Cofactor to be cleared ## - 0 <= scalar < curve order ## Those will be assumed to maintain constant-time property - when BigInt.bits <= EC.F.C.getCurveOrderBitwidth() and - EC.F.C.hasEndomorphismAcceleration(): + when BigInt.bits <= EC.getScalarField().bits() and + EC.F.Name.hasEndomorphismAcceleration(): # TODO, min amount of bits for endomorphisms? when EC.F is Fp: P.scalarMulGLV_m2w2(scalar) diff --git a/constantine/math/elliptic/ec_scalar_mul_vartime.nim b/constantine/math/elliptic/ec_scalar_mul_vartime.nim index 7062d4a06..accffd592 100644 --- a/constantine/math/elliptic/ec_scalar_mul_vartime.nim +++ b/constantine/math/elliptic/ec_scalar_mul_vartime.nim @@ -258,7 +258,7 @@ func scalarMulEndo_minHammingWeight_windowed_vartime*[scalBits: static int; EC]( var endomorphisms {.noInit.}: array[M-1, EC] when P.G == G1: endomorphisms[0] = P - endomorphisms[0].x *= EC.F.C.getCubicRootOfUnity_mod_p() + endomorphisms[0].x *= EC.F.Name.getCubicRootOfUnity_mod_p() else: endomorphisms[0].frobenius_psi(P, 2) @@ -351,8 +351,8 @@ func scalarMul_vartime*[scalBits; EC](P: var EC, scalar: BigInt[scalBits]) {.met let usedBits = scalar.limbs.getBits_LE_vartime() - when scalBits == EC.F.C.getCurveOrderBitwidth() and - EC.F.C.hasEndomorphismAcceleration(): + when scalBits == EC.getScalarField().bits() and + EC.F.Name.hasEndomorphismAcceleration(): if usedBits >= L: when EC.F is Fp: P.scalarMulEndo_minHammingWeight_windowed_vartime(scalar, window = 4) diff --git a/constantine/math/elliptic/ec_shortweierstrass_affine.nim b/constantine/math/elliptic/ec_shortweierstrass_affine.nim index d68a0aefc..53b9c9d0a 100644 --- a/constantine/math/elliptic/ec_shortweierstrass_affine.nim +++ b/constantine/math/elliptic/ec_shortweierstrass_affine.nim @@ -29,7 +29,7 @@ type G1 G2 - ECP_ShortW_Aff*[F; G: static Subgroup] = object + EC_ShortW_Aff*[F; G: static Subgroup] = object ## Elliptic curve point for a curve in Short Weierstrass form ## y² = x³ + a x + b ## @@ -38,25 +38,28 @@ type SexticNonResidue* = NonResidue -func `==`*(P, Q: ECP_ShortW_Aff): SecretBool = +template getScalarField*(EC: type EC_ShortW_Aff): untyped = + Fr[EC.F.Name] + +func `==`*(P, Q: EC_ShortW_Aff): SecretBool = ## Constant-time equality check result = P.x == Q.x result = result and (P.y == Q.y) -func isNeutral*(P: ECP_ShortW_Aff): SecretBool = +func isNeutral*(P: EC_ShortW_Aff): SecretBool = ## Returns true if P is the neutral element / identity element ## and false otherwise, i.e. ∀Q, P+Q == Q ## For Short Weierstrass curves, this is the infinity point. result = P.x.isZero() and P.y.isZero() -func setNeutral*(P: var ECP_ShortW_Aff) = +func setNeutral*(P: var EC_ShortW_Aff) = ## Set P to the neutral element / identity element ## i.e. ∀Q, P+Q == Q ## For Short Weierstrass curves, this is the infinity point. P.x.setZero() P.y.setZero() -func ccopy*(P: var ECP_ShortW_Aff, Q: ECP_ShortW_Aff, ctl: SecretBool) {.inline.} = +func ccopy*(P: var EC_ShortW_Aff, Q: EC_ShortW_Aff, ctl: SecretBool) {.inline.} = ## Constant-time conditional copy ## If ctl is true: Q is copied into P ## if ctl is false: Q is not copied and P is unmodified @@ -72,19 +75,19 @@ func curve_eq_rhs*[F](y2: var F, x: F, G: static Subgroup) = var t{.noInit.}: F t.square(x) - when F.C.getCoefA() != 0: - t += F.C.getCoefA() + when F.Name.getCoefA() != 0: + t += F.Name.getCoefA() t *= x when G == G1: - when F.C.getCoefB() >= 0: - y2.fromUint uint F.C.getCoefB() + when F.Name.getCoefB() >= 0: + y2.fromUint uint F.Name.getCoefB() y2 += t else: - y2.fromUint uint -F.C.getCoefB() + y2.fromUint uint -F.Name.getCoefB() y2.diff(t, y2) else: - y2.sum(F.C.getCoefB_G2(), t) + y2.sum(F.Name.getCoefB_G2(), t) func isOnCurve*[F](x, y: F, G: static Subgroup): SecretBool = ## Returns true if the (x, y) coordinates @@ -97,7 +100,7 @@ func isOnCurve*[F](x, y: F, G: static Subgroup): SecretBool = return y2 == rhs func trySetFromCoordX*[F, G]( - P: var ECP_ShortW_Aff[F, G], + P: var EC_ShortW_Aff[F, G], x: F): SecretBool = ## Try to create a point the elliptic curve ## y² = x³ + a x + b (affine coordinate) @@ -121,16 +124,16 @@ func trySetFromCoordX*[F, G]( result = sqrt_if_square(P.y) P.x = x -func neg*(P: var ECP_ShortW_Aff, Q: ECP_ShortW_Aff) = +func neg*(P: var EC_ShortW_Aff, Q: EC_ShortW_Aff) = ## Negate ``P`` P.x = Q.x P.y.neg(Q.y) -func neg*(P: var ECP_ShortW_Aff) = +func neg*(P: var EC_ShortW_Aff) = ## Negate ``P`` P.y.neg() -func cneg*(P: var ECP_ShortW_Aff, ctl: CTBool) = +func cneg*(P: var EC_ShortW_Aff, ctl: CTBool) = ## Conditional negation. ## Negate if ``ctl`` is true P.y.cneg(ctl) diff --git a/constantine/math/elliptic/ec_shortweierstrass_batch_ops.nim b/constantine/math/elliptic/ec_shortweierstrass_batch_ops.nim index f2b8f89b6..8ca885c19 100644 --- a/constantine/math/elliptic/ec_shortweierstrass_batch_ops.nim +++ b/constantine/math/elliptic/ec_shortweierstrass_batch_ops.nim @@ -26,8 +26,8 @@ import # ############################################################ func batchAffine*[F, G]( - affs: ptr UncheckedArray[ECP_ShortW_Aff[F, G]], - projs: ptr UncheckedArray[ECP_ShortW_Prj[F, G]], + affs: ptr UncheckedArray[EC_ShortW_Aff[F, G]], + projs: ptr UncheckedArray[EC_ShortW_Prj[F, G]], N: int) {.noInline, tags:[Alloca], meter.} = # Algorithm: Montgomery's batch inversion # - Speeding the Pollard and Elliptic Curve Methods of Factorization @@ -81,13 +81,13 @@ func batchAffine*[F, G]( affs[0].y.prod(projs[0].y, accInv) func batchAffine*[N: static int, F, G]( - affs: var array[N, ECP_ShortW_Aff[F, G]], - projs: array[N, ECP_ShortW_Prj[F, G]]) {.inline.} = + affs: var array[N, EC_ShortW_Aff[F, G]], + projs: array[N, EC_ShortW_Prj[F, G]]) {.inline.} = batchAffine(affs.asUnchecked(), projs.asUnchecked(), N) func batchAffine*[F, G]( - affs: ptr UncheckedArray[ECP_ShortW_Aff[F, G]], - jacs: ptr UncheckedArray[ECP_ShortW_Jac[F, G]], + affs: ptr UncheckedArray[EC_ShortW_Aff[F, G]], + jacs: ptr UncheckedArray[EC_ShortW_Jac[F, G]], N: int) {.noInline, tags:[Alloca], meter.} = # Algorithm: Montgomery's batch inversion # - Speeding the Pollard and Elliptic Curve Methods of Factorization @@ -147,18 +147,18 @@ func batchAffine*[F, G]( affs[0].y.prod(jacs[0].y, accInv) func batchAffine*[N: static int, F, G]( - affs: var array[N, ECP_ShortW_Aff[F, G]], - jacs: array[N, ECP_ShortW_Jac[F, G]]) {.inline.} = + affs: var array[N, EC_ShortW_Aff[F, G]], + jacs: array[N, EC_ShortW_Jac[F, G]]) {.inline.} = batchAffine(affs.asUnchecked(), jacs.asUnchecked(), N) func batchAffine*[M, N: static int, F, G]( - affs: var array[M, array[N, ECP_ShortW_Aff[F, G]]], - projs: array[M, array[N, ECP_ShortW_Prj[F, G]]]) {.inline.} = + affs: var array[M, array[N, EC_ShortW_Aff[F, G]]], + projs: array[M, array[N, EC_ShortW_Prj[F, G]]]) {.inline.} = batchAffine(affs[0].asUnchecked(), projs[0].asUnchecked(), M*N) func batchAffine*[M, N: static int, F, G]( - affs: var array[M, array[N, ECP_ShortW_Aff[F, G]]], - projs: array[M, array[N, ECP_ShortW_Jac[F, G]]]) {.inline.} = + affs: var array[M, array[N, EC_ShortW_Aff[F, G]]], + projs: array[M, array[N, EC_ShortW_Jac[F, G]]]) {.inline.} = batchAffine(affs[0].asUnchecked(), projs[0].asUnchecked(), M*N) # ############################################################ @@ -211,30 +211,30 @@ func batchAffine*[M, N: static int, F, G]( # Projective addition: 12M (for curves in the form y² = x³ + b) # Projective mixed addition: 11M (for curves in the form y² = x³ + b) -func lambdaAdd*[F; G: static Subgroup](lambda_num, lambda_den: var F, P, Q: ECP_ShortW_Aff[F, G]) {.inline.} = +func lambdaAdd*[F; G: static Subgroup](lambda_num, lambda_den: var F, P, Q: EC_ShortW_Aff[F, G]) {.inline.} = ## Compute the slope of the line (PQ) lambda_num.diff(Q.y, P.y) lambda_den.diff(Q.x, P.x) -func lambdaSub*[F; G: static Subgroup](lambda_num, lambda_den: var F, P, Q: ECP_ShortW_Aff[F, G]) {.inline.} = +func lambdaSub*[F; G: static Subgroup](lambda_num, lambda_den: var F, P, Q: EC_ShortW_Aff[F, G]) {.inline.} = ## Compute the slope of the line (PQ) lambda_num.neg(Q.y) lambda_num -= P.y lambda_den.diff(Q.x, P.x) -func lambdaDouble*[F; G: static Subgroup](lambda_num, lambda_den: var F, P: ECP_ShortW_Aff[F, G]) {.inline.} = +func lambdaDouble*[F; G: static Subgroup](lambda_num, lambda_den: var F, P: EC_ShortW_Aff[F, G]) {.inline.} = ## Compute the tangent at P lambda_num.square(P.x) lambda_num *= 3 - when F.C.getCoefA() != 0: - t += F.C.getCoefA() + when F.Name.getCoefA() != 0: + t += F.Name.getCoefA() lambda_den.double(P.y) func affineAdd*[F; G: static Subgroup]( - r{.noAlias.}: var ECP_ShortW_Aff[F, G], + r{.noAlias.}: var EC_ShortW_Aff[F, G], lambda: F, - P, Q: ECP_ShortW_Aff[F, G]) = + P, Q: EC_ShortW_Aff[F, G]) = ## `r` MUST NOT alias P or Q r.x.square(lambda) r.x -= P.x @@ -245,7 +245,7 @@ func affineAdd*[F; G: static Subgroup]( r.y -= P.y func accum_half_vartime[F; G: static Subgroup]( - points: ptr UncheckedArray[ECP_ShortW_Aff[F, G]], + points: ptr UncheckedArray[EC_ShortW_Aff[F, G]], len: int) {.noInline, tags:[VarTime, Alloca].} = ## Affine accumulation of half the points into the other half ## Warning ⚠️ : variable-time @@ -341,7 +341,7 @@ func accum_half_vartime[F; G: static Subgroup]( points[q].y.prod(points[q].y, lambdas[i].num, skipFinalSub = true) # Compute EC addition - var r{.noInit.}: ECP_ShortW_Aff[F, G] + var r{.noInit.}: EC_ShortW_Aff[F, G] r.affineAdd(lambda = points[q].y, points[p], points[q]) # Store result @@ -362,7 +362,7 @@ func accum_half_vartime[F; G: static Subgroup]( points[q].y.prod(lambdas[0].num, accInv, skipFinalSub = true) # Compute EC addition - var r{.noInit.}: ECP_ShortW_Aff[F, G] + var r{.noInit.}: EC_ShortW_Aff[F, G] r.affineAdd(lambda = points[q].y, points[p], points[q]) # Store result @@ -372,8 +372,8 @@ func accum_half_vartime[F; G: static Subgroup]( # ------------------------------------------------------------ func accumSum_chunk_vartime*[F; G: static Subgroup]( - r: var (ECP_ShortW_Jac[F, G] or ECP_ShortW_Prj[F, G] or ECP_ShortW_JacExt[F, G]), - points: ptr UncheckedArray[ECP_ShortW_Aff[F, G]], len: int) {.noInline, tags:[VarTime, Alloca].} = + r: var (EC_ShortW_Jac[F, G] or EC_ShortW_Prj[F, G] or EC_ShortW_JacExt[F, G]), + points: ptr UncheckedArray[EC_ShortW_Aff[F, G]], len: int) {.noInline, tags:[VarTime, Alloca].} = ## Accumulate `points` into r. ## `r` is NOT overwritten ## r += ∑ points @@ -381,8 +381,8 @@ func accumSum_chunk_vartime*[F; G: static Subgroup]( ## `len` should be chosen so that `len` points ## use cache efficiently - let accumulators = allocStackArray(ECP_ShortW_Aff[F, G], len) - let size = len * sizeof(ECP_ShortW_Aff[F, G]) + let accumulators = allocStackArray(EC_ShortW_Aff[F, G], len) + let size = len * sizeof(EC_ShortW_Aff[F, G]) copyMem(accumulators[0].addr, points[0].unsafeAddr, size) const minNumPointsSerial = 16 @@ -391,7 +391,7 @@ func accumSum_chunk_vartime*[F; G: static Subgroup]( while n >= minNumPointsSerial: if (n and 1) == 1: # odd number of points ## Accumulate the last - r.madd_vartime(r, points[n-1]) + r.mixedSum_vartime(r, points[n-1]) n -= 1 # Compute [0, n/2) += [n/2, n) @@ -402,11 +402,11 @@ func accumSum_chunk_vartime*[F; G: static Subgroup]( # Tail for i in 0 ..< n: - r.madd_vartime(r, points[i]) + r.mixedSum_vartime(r, points[i]) func accum_batch_vartime[F; G: static Subgroup]( - r: var (ECP_ShortW_Jac[F, G] or ECP_ShortW_Prj[F, G] or ECP_ShortW_JacExt[F, G]), - points: ptr UncheckedArray[ECP_ShortW_Aff[F, G]], pointsLen: int) = + r: var (EC_ShortW_Jac[F, G] or EC_ShortW_Prj[F, G] or EC_ShortW_JacExt[F, G]), + points: ptr UncheckedArray[EC_ShortW_Aff[F, G]], pointsLen: int) = ## Batch accumulation of `points` into `r` ## `r` is accumulated into @@ -430,15 +430,15 @@ func accum_batch_vartime[F; G: static Subgroup]( # as we halve after each chunk. const maxTempMem = 262144 # 2¹⁸ = 262144 - const maxStride = maxTempMem div sizeof(ECP_ShortW_Aff[F, G]) + const maxStride = maxTempMem div sizeof(EC_ShortW_Aff[F, G]) for i in countup(0, pointsLen-1, maxStride): let n = min(maxStride, pointsLen - i) r.accumSum_chunk_vartime(points +% i, n) func sum_reduce_vartime*[F; G: static Subgroup]( - r: var (ECP_ShortW_Jac[F, G] or ECP_ShortW_Prj[F, G] or ECP_ShortW_JacExt[F, G]), - points: ptr UncheckedArray[ECP_ShortW_Aff[F, G]], pointsLen: int) {.inline, tags:[VarTime, Alloca].} = + r: var (EC_ShortW_Jac[F, G] or EC_ShortW_Prj[F, G] or EC_ShortW_JacExt[F, G]), + points: ptr UncheckedArray[EC_ShortW_Aff[F, G]], pointsLen: int) {.inline, tags:[VarTime, Alloca].} = ## Batch addition of `points` into `r` ## `r` is overwritten r.setNeutral() @@ -447,8 +447,8 @@ func sum_reduce_vartime*[F; G: static Subgroup]( r.accum_batch_vartime(points, pointsLen) func sum_reduce_vartime*[F; G: static Subgroup]( - r: var (ECP_ShortW_Jac[F, G] or ECP_ShortW_Prj[F, G] or ECP_ShortW_JacExt[F, G]), - points: openArray[ECP_ShortW_Aff[F, G]]) {.inline, tags:[VarTime, Alloca].} = + r: var (EC_ShortW_Jac[F, G] or EC_ShortW_Prj[F, G] or EC_ShortW_JacExt[F, G]), + points: openArray[EC_ShortW_Aff[F, G]]) {.inline, tags:[VarTime, Alloca].} = ## Batch addition of `points` into `r` ## `r` is overwritten r.sum_reduce_vartime(points.asUnchecked(), points.len) @@ -469,7 +469,7 @@ type EcAddAccumulator_vartime*[EC, F; G: static Subgroup; AccumMax: static int] # Do we want alignment guarantees? len: uint32 accum: EC - buffer: array[AccumMax, ECP_ShortW_Aff[F, G]] + buffer: array[AccumMax, EC_ShortW_Aff[F, G]] func init*(ctx: var EcAddAccumulator_vartime) = static: doAssert EcAddAccumulator_vartime.AccumMax >= 16, "There is no point in a EcAddBatchAccumulator if the batch size is too small" @@ -486,7 +486,7 @@ func consumeBuffer[EC, F; G: static Subgroup; AccumMax: static int]( func update*[EC, F, G; AccumMax: static int]( ctx: var EcAddAccumulator_vartime[EC, F, G, AccumMax], - P: ECP_ShortW_Aff[F, G]) = + P: EC_ShortW_Aff[F, G]) = if P.isNeutral().bool: return diff --git a/constantine/math/elliptic/ec_shortweierstrass_batch_ops_parallel.nim b/constantine/math/elliptic/ec_shortweierstrass_batch_ops_parallel.nim index 0dcdb2491..66c608dcb 100644 --- a/constantine/math/elliptic/ec_shortweierstrass_batch_ops_parallel.nim +++ b/constantine/math/elliptic/ec_shortweierstrass_batch_ops_parallel.nim @@ -26,15 +26,15 @@ import proc sum_reduce_vartime_parallelChunks[F; G: static Subgroup]( tp: Threadpool, - r: var (ECP_ShortW_Jac[F, G] or ECP_ShortW_Prj[F, G]), - points: openArray[ECP_ShortW_Aff[F, G]]) {.noInline.} = + r: var (EC_ShortW_Jac[F, G] or EC_ShortW_Prj[F, G]), + points: openArray[EC_ShortW_Aff[F, G]]) {.noInline.} = ## Batch addition of `points` into `r` ## `r` is overwritten ## Scales better for large number of points # Chunking constants in ec_shortweierstrass_batch_ops.nim const maxTempMem = 262144 # 2¹⁸ = 262144 - const maxChunkSize = maxTempMem div sizeof(ECP_ShortW_Aff[F, G]) + const maxChunkSize = maxTempMem div sizeof(EC_ShortW_Aff[F, G]) const minChunkSize = (maxChunkSize * 60) div 100 # We want 60%~100% full chunks let chunkDesc = balancedChunksPrioSize( @@ -62,20 +62,20 @@ proc sum_reduce_vartime_parallelChunks[F; G: static Subgroup]( for i in 0 ..< chunkDesc.numChunks: r.sum_vartime(r, partialResults[i]) else: - let partialResultsAffine = allocStackArray(ECP_ShortW_Aff[F, G], chunkDesc.numChunks) + let partialResultsAffine = allocStackArray(EC_ShortW_Aff[F, G], chunkDesc.numChunks) partialResultsAffine.batchAffine(partialResults, chunkDesc.numChunks) r.sum_reduce_vartime(partialResultsAffine, chunkDesc.numChunks) proc sum_reduce_vartime_parallelAccums[F; G: static Subgroup]( tp: Threadpool, - r: var (ECP_ShortW_Jac[F, G] or ECP_ShortW_Prj[F, G]), - points: openArray[ECP_ShortW_Aff[F, G]]) = + r: var (EC_ShortW_Jac[F, G] or EC_ShortW_Prj[F, G]), + points: openArray[EC_ShortW_Aff[F, G]]) = ## Batch addition of `points` into `r` ## `r` is overwritten ## 2x faster for low number of points const maxTempMem = 1 shl 18 # 2¹⁸ = 262144 - const maxChunkSize = maxTempMem div sizeof(ECP_ShortW_Aff[F, G]) + const maxChunkSize = maxTempMem div sizeof(EC_ShortW_Aff[F, G]) type Acc = EcAddAccumulator_vartime[typeof(r), F, G, maxChunkSize] let ps = points.asUnchecked() @@ -109,8 +109,8 @@ proc sum_reduce_vartime_parallelAccums[F; G: static Subgroup]( proc sum_reduce_vartime_parallel*[F; G: static Subgroup]( tp: Threadpool, - r: var (ECP_ShortW_Jac[F, G] or ECP_ShortW_Prj[F, G]), - points: openArray[ECP_ShortW_Aff[F, G]]) {.inline.} = + r: var (EC_ShortW_Jac[F, G] or EC_ShortW_Prj[F, G]), + points: openArray[EC_ShortW_Aff[F, G]]) {.inline.} = ## Parallel Batch addition of `points` into `r` ## `r` is overwritten diff --git a/constantine/math/elliptic/ec_shortweierstrass_jacobian.nim b/constantine/math/elliptic/ec_shortweierstrass_jacobian.nim index ca22662d2..b944aae02 100644 --- a/constantine/math/elliptic/ec_shortweierstrass_jacobian.nim +++ b/constantine/math/elliptic/ec_shortweierstrass_jacobian.nim @@ -25,7 +25,7 @@ export Subgroup # # ############################################################ -type ECP_ShortW_Jac*[F; G: static Subgroup] = object +type EC_ShortW_Jac*[F; G: static Subgroup] = object ## Elliptic curve point for a curve in Short Weierstrass form ## y² = x³ + a x + b ## @@ -37,7 +37,10 @@ type ECP_ShortW_Jac*[F; G: static Subgroup] = object ## Note that jacobian coordinates are not unique x*, y*, z*: F -func isNeutral*(P: ECP_ShortW_Jac): SecretBool {.inline.} = +template getScalarField*(EC: type EC_ShortW_Jac): untyped = + Fr[EC.F.Name] + +func isNeutral*(P: EC_ShortW_Jac): SecretBool {.inline.} = ## Returns true if P is the neutral element / identity element ## and false otherwise, i.e. ∀Q, P+Q == Q ## For Short Weierstrass curves, this is the infinity point. @@ -49,7 +52,7 @@ func isNeutral*(P: ECP_ShortW_Jac): SecretBool {.inline.} = # (yZ³)² = (xZ²)³ which is true for any x, y coordinates result = P.z.isZero() -func setNeutral*(P: var ECP_ShortW_Jac) {.inline.} = +func setNeutral*(P: var EC_ShortW_Jac) {.inline.} = ## Set P to the neutral element / identity element ## i.e. ∀Q, P+Q == Q ## For Short Weierstrass curves, this is the infinity point. @@ -57,11 +60,11 @@ func setNeutral*(P: var ECP_ShortW_Jac) {.inline.} = P.y.setOne() P.z.setZero() -func `==`*(P, Q: ECP_ShortW_Jac): SecretBool {.meter.} = +func `==`*(P, Q: EC_ShortW_Jac): SecretBool {.meter.} = ## Constant-time equality check ## This is a costly operation # Reminder: the representation is not unique - type F = ECP_ShortW_Jac.F + type F = EC_ShortW_Jac.F var z1z1 {.noInit.}, z2z2 {.noInit.}: F var a{.noInit.}, b{.noInit.}: F @@ -82,7 +85,7 @@ func `==`*(P, Q: ECP_ShortW_Jac): SecretBool {.meter.} = # Ensure a zero-init point doesn't propagate 0s and match any result = result and not(P.isNeutral() xor Q.isNeutral()) -func ccopy*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Jac, ctl: SecretBool) {.inline.} = +func ccopy*(P: var EC_ShortW_Jac, Q: EC_ShortW_Jac, ctl: SecretBool) {.inline.} = ## Constant-time conditional copy ## If ctl is true: Q is copied into P ## if ctl is false: Q is not copied and P is unmodified @@ -91,7 +94,7 @@ func ccopy*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Jac, ctl: SecretBool) {.inline. ccopy(fP, fQ, ctl) func trySetFromCoordsXandZ*[F; G]( - P: var ECP_ShortW_Jac[F, G], + P: var EC_ShortW_Jac[F, G], x, z: F): SecretBool = ## Try to create a point the elliptic curve ## Y² = X³ + aXZ⁴ + bZ⁶ (Jacobian coordinates) @@ -121,7 +124,7 @@ func trySetFromCoordsXandZ*[F; G]( P.z = z func trySetFromCoordX*[F; G]( - P: var ECP_ShortW_Jac[F, G], + P: var EC_ShortW_Jac[F, G], x: F): SecretBool = ## Try to create a point the elliptic curve ## y² = x³ + a x + b (affine coordinate) @@ -147,26 +150,25 @@ func trySetFromCoordX*[F; G]( P.x = x P.z.setOne() -func neg*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Jac) {.inline.} = +func neg*(P: var EC_ShortW_Jac, Q: EC_ShortW_Jac) {.inline.} = ## Negate ``P`` P.x = Q.x P.y.neg(Q.y) P.z = Q.z -func neg*(P: var ECP_ShortW_Jac) {.inline.} = +func neg*(P: var EC_ShortW_Jac) {.inline.} = ## Negate ``P`` P.y.neg() -func cneg*(P: var ECP_ShortW_Jac, ctl: CTBool) {.inline.} = +func cneg*(P: var EC_ShortW_Jac, ctl: CTBool) {.inline.} = ## Conditional negation. ## Negate if ``ctl`` is true P.y.cneg(ctl) template sumImpl[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], - P, Q: ECP_ShortW_Jac[F, G], - CoefA: typed - ) {.dirty.} = + r: var EC_ShortW_Jac[F, G], + P, Q: EC_ShortW_Jac[F, G], + CoefA: typed) {.dirty.} = ## Elliptic curve point addition for Short Weierstrass curves in Jacobian coordinates ## with the curve ``a`` being a parameter for summing on isogenous curves. ## @@ -336,10 +338,9 @@ template sumImpl[F; G: static Subgroup]( r = o func sum*[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], - P, Q: ECP_ShortW_Jac[F, G], - CoefA: static F - ) {.meter.} = + r: var EC_ShortW_Jac[F, G], + P, Q: EC_ShortW_Jac[F, G], + CoefA: static F) {.meter.} = ## Elliptic curve point addition for Short Weierstrass curves in Jacobian coordinates ## with the curve ``a`` being a parameter for summing on isogenous curves. ## @@ -361,9 +362,8 @@ func sum*[F; G: static Subgroup]( r.sumImpl(P, Q, CoefA) func sum*[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], - P, Q: ECP_ShortW_Jac[F, G] - ) {.meter.} = + r: var EC_ShortW_Jac[F, G], + P, Q: EC_ShortW_Jac[F, G]) {.meter.} = ## Elliptic curve point addition for Short Weierstrass curves in Jacobian coordinates ## ## R = P + Q @@ -379,13 +379,12 @@ func sum*[F; G: static Subgroup]( ## that P == Q or P == -Q or P or Q are the infinity points ## to simple side-channel attacks (SCA) ## This is done by using a "complete" or "exception-free" addition law. - r.sumImpl(P, Q, F.C.getCoefA()) + r.sumImpl(P, Q, F.Name.getCoefA()) -func madd*[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], - P: ECP_ShortW_Jac[F, G], - Q: ECP_ShortW_Aff[F, G] - ) {.meter.} = +func mixedSum*[F; G: static Subgroup]( + r: var EC_ShortW_Jac[F, G], + P: EC_ShortW_Jac[F, G], + Q: EC_ShortW_Aff[F, G]) {.meter.} = ## Elliptic curve mixed addition for Short Weierstrass curves in Jacobian coordinates ## with the curve ``a`` being a parameter for summing on isogenous curves. ## @@ -434,7 +433,7 @@ func madd*[F; G: static Subgroup]( # "when" static evaluation doesn't shortcut booleans :/ # which causes issues when CoefA isn't an int but Fp or Fp2 - const CoefA = F.C.getCoefA() + const CoefA = F.Name.getCoefA() when CoefA is int: const CoefA_eq_zero = CoefA == 0 const CoefA_eq_minus3 {.used.} = CoefA == -3 @@ -557,7 +556,7 @@ func madd*[F; G: static Subgroup]( r = o -func double*[F; G: static Subgroup](r: var ECP_ShortW_Jac[F, G], P: ECP_ShortW_Jac[F, G]) {.meter.} = +func double*[F; G: static Subgroup](r: var EC_ShortW_Jac[F, G], P: EC_ShortW_Jac[F, G]) {.meter.} = ## Elliptic curve point doubling for Short Weierstrass curves in projective coordinate ## ## R = [2] P @@ -570,7 +569,7 @@ func double*[F; G: static Subgroup](r: var ECP_ShortW_Jac[F, G], P: ECP_ShortW_J ## ``r`` is initialized/overwritten with the sum ## ## Implementation is constant-time. - when F.C.getCoefA() == 0: + when F.Name.getCoefA() == 0: # "dbl-2009-l" doubling formula - https://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l # # Cost: 2M + 5S + 6add + 3*2 + 1*3 + 1*8. @@ -617,48 +616,52 @@ func double*[F; G: static Subgroup](r: var ECP_ShortW_Jac[F, G], P: ECP_ShortW_J else: {.error: "Not implemented.".} -func `+=`*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Jac) {.inline.} = +func `+=`*(P: var EC_ShortW_Jac, Q: EC_ShortW_Jac) {.inline.} = ## In-place point addition P.sum(P, Q) -func `+=`*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Aff) {.inline.} = +func `+=`*(P: var EC_ShortW_Jac, Q: EC_ShortW_Aff) {.inline.} = ## In-place mixed point addition - P.madd(P, Q) + P.mixedSum(P, Q) -func double*(P: var ECP_ShortW_Jac) {.inline.} = +func double*(P: var EC_ShortW_Jac) {.inline.} = ## In-place point doubling P.double(P) -func diff*(r: var ECP_ShortW_Jac, P, Q: ECP_ShortW_Jac) {.inline.} = +func diff*(r: var EC_ShortW_Jac, P, Q: EC_ShortW_Jac) {.inline.} = ## r = P - Q var nQ {.noInit.}: typeof(Q) nQ.neg(Q) r.sum(P, nQ) -func diff*(r: var ECP_ShortW_Jac, P: ECP_ShortW_Jac, Q: ECP_ShortW_Aff) {.inline.} = +func `-=`*(P: var EC_ShortW_Jac, Q: EC_ShortW_Jac) {.inline.} = + ## In-place point substraction + P.diff(P, Q) + +func mixedDiff*(r: var EC_ShortW_Jac, P: EC_ShortW_Jac, Q: EC_ShortW_Aff) {.inline.} = ## r = P - Q var nQ {.noInit.}: typeof(Q) nQ.neg(Q) - r.madd(P, nQ) + r.mixedSum(P, nQ) -func `-=`*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Jac or ECP_ShortW_Aff) {.inline.} = +func `-=`*(P: var EC_ShortW_Jac, Q: EC_ShortW_Aff) {.inline.} = ## In-place point substraction - P.diff(P, Q) + P.mixedDiff(P, Q) # Conversions # ----------- -template affine*[F, G](_: type ECP_ShortW_Jac[F, G]): typedesc = +template affine*[F, G](_: type EC_ShortW_Jac[F, G]): untyped = ## Returns the affine type that corresponds to the Jacobian type input - ECP_ShortW_Aff[F, G] + EC_ShortW_Aff[F, G] -template jacobian*[F, G](_: type ECP_ShortW_Aff[F, G]): typedesc = +template jacobian*[F, G](_: type EC_ShortW_Aff[F, G]): untyped = ## Returns the jacobian type that corresponds to the affine type input - ECP_ShortW_Jac[F, G] + EC_ShortW_Jac[F, G] func affine*[F; G]( - aff: var ECP_ShortW_Aff[F, G], - jac: ECP_ShortW_Jac[F, G]) {.meter.} = + aff: var EC_ShortW_Aff[F, G], + jac: EC_ShortW_Jac[F, G]) {.meter.} = var invZ {.noInit.}, invZ2{.noInit.}: F invZ.inv(jac.z) invZ2.square(invZ, skipFinalSub = true) @@ -668,8 +671,8 @@ func affine*[F; G]( aff.y.prod(jac.y, invZ) func fromAffine*[F; G]( - jac: var ECP_ShortW_Jac[F, G], - aff: ECP_ShortW_Aff[F, G]) {.inline.} = + jac: var EC_ShortW_Jac[F, G], + aff: EC_ShortW_Aff[F, G]) {.inline.} = jac.x = aff.x jac.y = aff.y jac.z.setOne() @@ -683,8 +686,8 @@ func fromAffine*[F; G]( # to hours of computations. Those primitives do not need constant-timeness. func sum_vartime*[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], - p, q: ECP_ShortW_Jac[F, G]) + r: var EC_ShortW_Jac[F, G], + p, q: EC_ShortW_Jac[F, G]) {.tags:[VarTime], meter.} = ## **Variable-time** Jacobian addition ## @@ -799,10 +802,10 @@ func sum_vartime*[F; G: static Subgroup]( r.z.prod(p.z, q.z, skipFinalSub = true) r.z *= H -func madd_vartime*[F; G: static Subgroup]( - r: var ECP_ShortW_Jac[F, G], - p: ECP_ShortW_Jac[F, G], - q: ECP_ShortW_Aff[F, G]) +func mixedSum_vartime*[F; G: static Subgroup]( + r: var EC_ShortW_Jac[F, G], + p: EC_ShortW_Jac[F, G], + q: EC_ShortW_Aff[F, G]) {.tags:[VarTime], meter.} = ## **Variable-time** Jacobian mixed addition ## @@ -899,7 +902,7 @@ func madd_vartime*[F; G: static Subgroup]( else: r.z.prod(H, p.z) -func diff_vartime*(r: var ECP_ShortW_Jac, P, Q: ECP_ShortW_Jac) {.inline.} = +func diff_vartime*(r: var EC_ShortW_Jac, P, Q: EC_ShortW_Jac) {.inline.} = ## r = P - Q ## ## This MUST NOT be used with secret data. @@ -909,7 +912,7 @@ func diff_vartime*(r: var ECP_ShortW_Jac, P, Q: ECP_ShortW_Jac) {.inline.} = nQ.neg(Q) r.sum_vartime(P, nQ) -func msub_vartime*(r: var ECP_ShortW_Jac, P: ECP_ShortW_Jac, Q: ECP_ShortW_Aff) {.inline.} = +func mixedDiff_vartime*(r: var EC_ShortW_Jac, P: EC_ShortW_Jac, Q: EC_ShortW_Aff) {.inline.} = ## r = P - Q ## ## This MUST NOT be used with secret data. @@ -917,18 +920,18 @@ func msub_vartime*(r: var ECP_ShortW_Jac, P: ECP_ShortW_Jac, Q: ECP_ShortW_Aff) ## This is highly VULNERABLE to timing attacks and power analysis attacks. var nQ {.noInit.}: typeof(Q) nQ.neg(Q) - r.madd_vartime(P, nQ) + r.mixedSum_vartime(P, nQ) -template `~+=`*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Jac) = +template `~+=`*(P: var EC_ShortW_Jac, Q: EC_ShortW_Jac) = ## Variable-time in-place point addition P.sum_vartime(P, Q) -template `~+=`*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Aff) = +template `~+=`*(P: var EC_ShortW_Jac, Q: EC_ShortW_Aff) = ## Variable-time in-place point mixed addition - P.madd_vartime(P, Q) + P.mixedSum_vartime(P, Q) -template `~-=`*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Jac) = +template `~-=`*(P: var EC_ShortW_Jac, Q: EC_ShortW_Jac) = P.diff_vartime(P, Q) -template `~-=`*(P: var ECP_ShortW_Jac, Q: ECP_ShortW_Aff) = - P.msub_vartime(P, Q) +template `~-=`*(P: var EC_ShortW_Jac, Q: EC_ShortW_Aff) = + P.mixedDiff_vartime(P, Q) diff --git a/constantine/math/elliptic/ec_shortweierstrass_jacobian_extended.nim b/constantine/math/elliptic/ec_shortweierstrass_jacobian_extended.nim index 916daa764..f73584b13 100644 --- a/constantine/math/elliptic/ec_shortweierstrass_jacobian_extended.nim +++ b/constantine/math/elliptic/ec_shortweierstrass_jacobian_extended.nim @@ -27,7 +27,7 @@ export Subgroup # # ############################################################ -type ECP_ShortW_JacExt*[F; G: static Subgroup] = object +type EC_ShortW_JacExt*[F; G: static Subgroup] = object ## Elliptic curve point for a curve in Short Weierstrass form ## y² = x³ + a x + b ## @@ -39,15 +39,15 @@ type ECP_ShortW_JacExt*[F; G: static Subgroup] = object ## Note that extended jacobian coordinates are not unique x*, y*, zz*, zzz*: F -func fromAffine*[F; G](jacext: var ECP_ShortW_JacExt[F, G], aff: ECP_ShortW_Aff[F, G]) {.inline.} +func fromAffine*[F; G](jacext: var EC_ShortW_JacExt[F, G], aff: EC_ShortW_Aff[F, G]) {.inline.} -func isNeutral*(P: ECP_ShortW_JacExt): SecretBool {.inline, meter.} = +func isNeutral*(P: EC_ShortW_JacExt): SecretBool {.inline, meter.} = ## Returns true if P is the neutral element / identity element ## and false otherwise, i.e. ∀Q, P+Q == Q ## For Short Weierstrass curves, this is the infinity point. result = P.zz.isZero() -func setNeutral*(P: var ECP_ShortW_JacExt) {.inline.} = +func setNeutral*(P: var EC_ShortW_JacExt) {.inline.} = ## Set P to the neutral element / identity element ## i.e. ∀Q, P+Q == Q ## For Short Weierstrass curves, this is the infinity point. @@ -56,11 +56,11 @@ func setNeutral*(P: var ECP_ShortW_JacExt) {.inline.} = P.zz.setZero() P.zzz.setZero() -func `==`*(P, Q: ECP_ShortW_JacExt): SecretBool {.meter.} = +func `==`*(P, Q: EC_ShortW_JacExt): SecretBool {.meter.} = ## Constant-time equality check ## This is a costly operation # Reminder: the representation is not unique - type F = ECP_ShortW_JacExt.F + type F = EC_ShortW_JacExt.F var a{.noInit.}, b{.noInit.}: F @@ -76,7 +76,7 @@ func `==`*(P, Q: ECP_ShortW_JacExt): SecretBool {.meter.} = result = result and not(P.isNeutral() xor Q.isNeutral()) func trySetFromCoordsXandZ*[F; G]( - P: var ECP_ShortW_JacExt[F, G], + P: var EC_ShortW_JacExt[F, G], x, z: F): SecretBool = ## Try to create a point the elliptic curve ## Y² = X³ + aXZ⁴ + bZ⁶ (Jacobian coordinates) @@ -105,7 +105,7 @@ func trySetFromCoordsXandZ*[F; G]( P.y.prod(P.y, P.zzz) func trySetFromCoordX*[F; G]( - P: var ECP_ShortW_JacExt[F, G], + P: var EC_ShortW_JacExt[F, G], x: F): SecretBool = ## Try to create a point the elliptic curve ## y² = x³ + a x + b (affine coordinate) @@ -132,18 +132,18 @@ func trySetFromCoordX*[F; G]( P.zz.setOne() P.zzz.setOne() -func neg*(P: var ECP_ShortW_JacExt, Q: ECP_ShortW_JacExt) {.inline.} = +func neg*(P: var EC_ShortW_JacExt, Q: EC_ShortW_JacExt) {.inline.} = ## Negate ``P`` P.x = Q.x P.y.neg(Q.y) P.zz = Q.zz P.zzz = Q.zzz -func neg*(P: var ECP_ShortW_JacExt) {.inline.} = +func neg*(P: var EC_ShortW_JacExt) {.inline.} = ## Negate ``P`` P.y.neg() -func double*[F; G: static Subgroup](r: var ECP_ShortW_JacExt[F, G], P: ECP_ShortW_JacExt[F, G]) {.meter.} = +func double*[F; G: static Subgroup](r: var EC_ShortW_JacExt[F, G], P: EC_ShortW_JacExt[F, G]) {.meter.} = # http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#doubling-dbl-2008-s-1 var U{.noInit.}, V{.noInit.}, W{.noinit.}, S{.noInit.}, M{.noInit.}: F @@ -153,7 +153,7 @@ func double*[F; G: static Subgroup](r: var ECP_ShortW_JacExt[F, G], P: ECP_Short S.prod(P.x, V) M.square(P.x) M *= 3 - when F.C.getCoefA() != 0: + when F.Name.getCoefA() != 0: {.error: "Not implemented.".} # aliasing, we don't use P.x and U anymore @@ -168,8 +168,8 @@ func double*[F; G: static Subgroup](r: var ECP_ShortW_JacExt[F, G], P: ECP_Short r.zzz.prod(P.zzz, W) func sum_vartime*[F; G: static Subgroup]( - r: var ECP_ShortW_JacExt[F, G], - p, q: ECP_ShortW_JacExt[F, G]) + r: var EC_ShortW_JacExt[F, G], + p, q: EC_ShortW_JacExt[F, G]) {.tags:[VarTime], meter.} = ## **Variable-time** Extended Jacobian addition ## @@ -226,7 +226,7 @@ func sum_vartime*[F; G: static Subgroup]( r.zzz.prod(p.zzz, q.zzz) r.zzz *= PPP -func mdouble*[F; G: static Subgroup](r: var ECP_ShortW_JacExt[F, G], P: ECP_ShortW_Aff[F, G]) {.meter.} = +func mdouble*[F; G: static Subgroup](r: var EC_ShortW_JacExt[F, G], P: EC_ShortW_Aff[F, G]) {.meter.} = ## Mixed EC point double # http://www.hyperelliptic.org/EFD/g1p/auto-shortw-xyzz.html#doubling-mdbl-2008-s-1 @@ -238,7 +238,7 @@ func mdouble*[F; G: static Subgroup](r: var ECP_ShortW_JacExt[F, G], P: ECP_Shor S.prod(P.x, V) M.square(P.x) M *= 3 - when F.C.getCoefA() != 0: + when F.Name.getCoefA() != 0: {.error: "Not implemented.".} # aliasing, we don't use P.x and U anymore @@ -252,10 +252,10 @@ func mdouble*[F; G: static Subgroup](r: var ECP_ShortW_JacExt[F, G], P: ECP_Shor r.zz = V r.zzz = W -func madd_vartime*[F; G: static Subgroup]( - r: var ECP_ShortW_JacExt[F, G], - p: ECP_ShortW_JacExt[F, G], - q: ECP_ShortW_Aff[F, G]) +func mixedSum_vartime*[F; G: static Subgroup]( + r: var EC_ShortW_JacExt[F, G], + p: EC_ShortW_JacExt[F, G], + q: EC_ShortW_Aff[F, G]) {.tags:[VarTime], meter.} = ## **Variable-time** Extended Jacobian mixed addition ## @@ -306,28 +306,28 @@ func madd_vartime*[F; G: static Subgroup]( r.zz.prod(p.zz, PP) r.zzz.prod(p.zzz, PPP) -func msub_vartime*[F; G: static Subgroup]( - r: var ECP_ShortW_JacExt[F, G], - p: ECP_ShortW_JacExt[F, G], - q: ECP_ShortW_Aff[F, G]) {.tags:[VarTime], inline.} = - var nQ {.noInit.}: ECP_ShortW_Aff[F, G] +func mixedDiff_vartime*[F; G: static Subgroup]( + r: var EC_ShortW_JacExt[F, G], + p: EC_ShortW_JacExt[F, G], + q: EC_ShortW_Aff[F, G]) {.tags:[VarTime], inline.} = + var nQ {.noInit.}: EC_ShortW_Aff[F, G] nQ.neg(q) - r.madd_vartime(p, nQ) + r.mixedSum_vartime(p, nQ) # Conversions # ----------- -template affine*[F, G](_: type ECP_ShortW_JacExt[F, G]): typedesc = +template affine*[F, G](_: type EC_ShortW_JacExt[F, G]): untyped = ## Returns the affine type that corresponds to the Extended Jacobian type input - ECP_ShortW_Aff[F, G] + EC_ShortW_Aff[F, G] -template jacobianExtended*[EC](_: typedesc[EC]): typedesc = +template jacobianExtended*[EC](_: typedesc[EC]): untyped = ## Returns the affine type that corresponds to the Extended Jacobian type input - ECP_ShortW_JacExt[EC.F, EC.G] + EC_ShortW_JacExt[EC.F, EC.G] func affine*[F; G]( - aff: var ECP_ShortW_Aff[F, G], - jacext: ECP_ShortW_JacExt[F, G]) {.meter.} = + aff: var EC_ShortW_Aff[F, G], + jacext: EC_ShortW_JacExt[F, G]) {.meter.} = var invZZ {.noInit.}, invZZZ{.noInit.}: F invZZZ.inv(jacext.zzz) invZZ.prod(jacext.zz, invZZZ, skipFinalSub = true) @@ -336,8 +336,8 @@ func affine*[F; G]( aff.y.prod(jacext.y, invZZZ) func fromAffine*[F; G]( - jacext: var ECP_ShortW_JacExt[F, G], - aff: ECP_ShortW_Aff[F, G]) {.inline, meter.} = + jacext: var EC_ShortW_JacExt[F, G], + aff: EC_ShortW_Aff[F, G]) {.inline, meter.} = jacext.x = aff.x jacext.y = aff.y jacext.zz.setOne() @@ -348,8 +348,8 @@ func fromAffine*[F; G]( jacext.zzz.csetZero(inf) func fromJacobianExtended_vartime*[F; G]( - prj: var ECP_ShortW_Prj[F, G], - jacext: ECP_ShortW_JacExt[F, G]) {.inline, meter, tags:[VarTime].} = + prj: var EC_ShortW_Prj[F, G], + jacext: EC_ShortW_JacExt[F, G]) {.inline, meter, tags:[VarTime].} = # Affine (x, y) # Jacobian extended (xZ², yZ³, Z², Z³) # Projective (xZ', yZ', Z') @@ -362,8 +362,8 @@ func fromJacobianExtended_vartime*[F; G]( prj.y.prod(jacext.y, jacext.zz) func fromJacobianExtended_vartime*[F; G]( - jac: var ECP_ShortW_Jac[F, G], - jacext: ECP_ShortW_JacExt[F, G]) {.inline, meter, tags:[VarTime].} = + jac: var EC_ShortW_Jac[F, G], + jacext: EC_ShortW_JacExt[F, G]) {.inline, meter, tags:[VarTime].} = # Affine (x, y) # Jacobian extended (xZ², yZ³, Z², Z³) # Jacobian (xZ'², yZ'³, Z') diff --git a/constantine/math/elliptic/ec_shortweierstrass_projective.nim b/constantine/math/elliptic/ec_shortweierstrass_projective.nim index 7f69354a5..0364ca5be 100644 --- a/constantine/math/elliptic/ec_shortweierstrass_projective.nim +++ b/constantine/math/elliptic/ec_shortweierstrass_projective.nim @@ -25,7 +25,7 @@ export Subgroup # # ############################################################ -type ECP_ShortW_Prj*[F; G: static Subgroup] = object +type EC_ShortW_Prj*[F; G: static Subgroup] = object ## Elliptic curve point for a curve in Short Weierstrass form ## y² = x³ + a x + b ## @@ -37,7 +37,10 @@ type ECP_ShortW_Prj*[F; G: static Subgroup] = object ## Note that projective coordinates are not unique x*, y*, z*: F -func isNeutral*(P: ECP_ShortW_Prj): SecretBool {.inline.} = +template getScalarField*(EC: type EC_ShortW_Prj): untyped = + Fr[EC.F.Name] + +func isNeutral*(P: EC_ShortW_Prj): SecretBool {.inline.} = ## Returns true if P is the neutral element / identity element ## and false otherwise, i.e. ∀Q, P+Q == Q ## For Short Weierstrass curves, this is the infinity point. @@ -47,7 +50,7 @@ func isNeutral*(P: ECP_ShortW_Prj): SecretBool {.inline.} = # Y can be anything result = P.x.isZero() and P.z.isZero() -func setNeutral*(P: var ECP_ShortW_Prj) {.inline.} = +func setNeutral*(P: var EC_ShortW_Prj) {.inline.} = ## Set P to the neutral element / identity element ## i.e. ∀Q, P+Q == Q ## For Short Weierstrass curves, this is the infinity point. @@ -55,11 +58,11 @@ func setNeutral*(P: var ECP_ShortW_Prj) {.inline.} = P.y.setOne() P.z.setZero() -func `==`*(P, Q: ECP_ShortW_Prj): SecretBool = +func `==`*(P, Q: EC_ShortW_Prj): SecretBool = ## Constant-time equality check ## This is a costly operation # Reminder: the representation is not unique - type F = ECP_ShortW_Prj.F + type F = EC_ShortW_Prj.F var a{.noInit.}, b{.noInit.}: F @@ -74,7 +77,7 @@ func `==`*(P, Q: ECP_ShortW_Prj): SecretBool = # Ensure a zero-init point doesn't propagate 0s and match any result = result and not(P.isNeutral() xor Q.isNeutral()) -func ccopy*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Prj, ctl: SecretBool) {.inline.} = +func ccopy*(P: var EC_ShortW_Prj, Q: EC_ShortW_Prj, ctl: SecretBool) {.inline.} = ## Constant-time conditional copy ## If ctl is true: Q is copied into P ## if ctl is false: Q is not copied and P is unmodified @@ -83,7 +86,7 @@ func ccopy*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Prj, ctl: SecretBool) {.inline. ccopy(fP, fQ, ctl) func trySetFromCoordsXandZ*[F; G]( - P: var ECP_ShortW_Prj[F, G], + P: var EC_ShortW_Prj[F, G], x, z: F): SecretBool = ## Try to create a point the elliptic curve ## Y²Z = X³ + aXZ² + bZ³ (projective coordinates) @@ -110,7 +113,7 @@ func trySetFromCoordsXandZ*[F; G]( P.z = z func trySetFromCoordX*[F; G]( - P: var ECP_ShortW_Prj[F, G], + P: var EC_ShortW_Prj[F, G], x: F): SecretBool = ## Try to create a point the elliptic curve ## y² = x³ + a x + b (affine coordinate) @@ -136,24 +139,24 @@ func trySetFromCoordX*[F; G]( P.x = x P.z.setOne() -func neg*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Prj) {.inline.} = +func neg*(P: var EC_ShortW_Prj, Q: EC_ShortW_Prj) {.inline.} = ## Negate ``P`` P.x = Q.x P.y.neg(Q.y) P.z = Q.z -func neg*(P: var ECP_ShortW_Prj) {.inline.} = +func neg*(P: var EC_ShortW_Prj) {.inline.} = ## Negate ``P`` P.y.neg() -func cneg*(P: var ECP_ShortW_Prj, ctl: CTBool) {.inline.} = +func cneg*(P: var EC_ShortW_Prj, ctl: CTBool) {.inline.} = ## Conditional negation. ## Negate if ``ctl`` is true P.y.cneg(ctl) func sum*[F; G: static Subgroup]( - r: var ECP_ShortW_Prj[F, G], - P, Q: ECP_ShortW_Prj[F, G] + r: var EC_ShortW_Prj[F, G], + P, Q: EC_ShortW_Prj[F, G] ) {.meter.} = ## Elliptic curve point addition for Short Weierstrass curves in projective coordinates ## @@ -190,10 +193,10 @@ func sum*[F; G: static Subgroup]( # # Cost: 12M + 3 mul(a) + 2 mul(3b) + 23 a - when F.C.getCoefA() == 0: + when F.Name.getCoefA() == 0: var t0 {.noInit.}, t1 {.noInit.}, t2 {.noInit.}, t3 {.noInit.}, t4 {.noInit.}: F var x3 {.noInit.}, y3 {.noInit.}, z3 {.noInit.}: F - const b3 = 3 * F.C.getCoefB() + const b3 = 3 * F.Name.getCoefB() # Algorithm 7 for curves: y² = x³ + b # 12M + 2 mul(3b) + 19A @@ -211,32 +214,32 @@ func sum*[F; G: static Subgroup]( t3 *= t4 # 6. t₃ <- t₃ * t₄ t4.sum(t0, t1) # 7. t₄ <- t₀ + t₁ t3 -= t4 # 8. t₃ <- t₃ - t₄ t₃ = (X₁ + Y₁)(X₂ + Y₂) - (X₁X₂ + Y₁Y₂) = X₁Y₂ + X₂Y₁ - when G == G2 and F.C.getSexticTwist() == D_Twist: + when G == G2 and F.Name.getSexticTwist() == D_Twist: t3 *= SexticNonResidue t4.sum(P.y, P.z) # 9. t₄ <- Y₁ + Z₁ x3.sum(Q.y, Q.z) # 10. X₃ <- Y₂ + Z₂ t4 *= x3 # 11. t₄ <- t₄ X₃ x3.sum(t1, t2) # 12. X₃ <- t₁ + t₂ X₃ = Y₁Y₂ + Z₁Z₂ t4 -= x3 # 13. t₄ <- t₄ - X₃ t₄ = (Y₁ + Z₁)(Y₂ + Z₂) - (Y₁Y₂ + Z₁Z₂) = Y₁Z₂ + Y₂Z₁ - when G == G2 and F.C.getSexticTwist() == D_Twist: + when G == G2 and F.Name.getSexticTwist() == D_Twist: t4 *= SexticNonResidue x3.sum(P.x, P.z) # 14. X₃ <- X₁ + Z₁ y3.sum(Q.x, Q.z) # 15. Y₃ <- X₂ + Z₂ x3 *= y3 # 16. X₃ <- X₃ Y₃ X₃ = (X₁+Z₁)(X₂+Z₂) y3.sum(t0, t2) # 17. Y₃ <- t₀ + t₂ Y₃ = X₁ X₂ + Z₁ Z₂ y3.diff(x3, y3) # 18. Y₃ <- X₃ - Y₃ Y₃ = (X₁ + Z₁)(X₂ + Z₂) - (X₁ X₂ + Z₁ Z₂) = X₁Z₂ + X₂Z₁ - when G == G2 and F.C.getSexticTwist() == D_Twist: + when G == G2 and F.Name.getSexticTwist() == D_Twist: t0 *= SexticNonResidue t1 *= SexticNonResidue x3.double(t0) # 19. X₃ <- t₀ + t₀ X₃ = 2 X₁X₂ t0 += x3 # 20. t₀ <- X₃ + t₀ t₀ = 3 X₁X₂ t2 *= b3 # 21. t₂ <- 3b t₂ t₂ = 3bZ₁Z₂ - when G == G2 and F.C.getSexticTwist() == M_Twist: + when G == G2 and F.Name.getSexticTwist() == M_Twist: t2 *= SexticNonResidue z3.sum(t1, t2) # 22. Z₃ <- t₁ + t₂ Z₃ = Y₁Y₂ + 3bZ₁Z₂ t1 -= t2 # 23. t₁ <- t₁ - t₂ t₁ = Y₁Y₂ - 3bZ₁Z₂ y3 *= b3 # 24. Y₃ <- 3b Y₃ Y₃ = 3b(X₁Z₂ + X₂Z₁) - when G == G2 and F.C.getSexticTwist() == M_Twist: + when G == G2 and F.Name.getSexticTwist() == M_Twist: y3 *= SexticNonResidue x3.prod(t4, y3) # 25. X₃ <- t₄ Y₃ X₃ = 3b(Y₁Z₂ + Y₂Z₁)(X₁Z₂ + X₂Z₁) t2.prod(t3, t1) # 26. t₂ <- t₃ t₁ t₂ = (X₁Y₂ + X₂Y₁) (Y₁Y₂ - 3bZ₁Z₂) @@ -250,10 +253,10 @@ func sum*[F; G: static Subgroup]( else: {.error: "Not implemented.".} -func madd*[F; G: static Subgroup]( - r: var ECP_ShortW_Prj[F, G], - P: ECP_ShortW_Prj[F, G], - Q: ECP_ShortW_Aff[F, G] +func mixedSum*[F; G: static Subgroup]( + r: var EC_ShortW_Prj[F, G], + P: EC_ShortW_Prj[F, G], + Q: EC_ShortW_Aff[F, G] ) {.meter.} = ## Elliptic curve mixed addition for Short Weierstrass curves ## with p in Projective coordinates and Q in affine coordinates @@ -262,10 +265,10 @@ func madd*[F; G: static Subgroup]( ## ## ``r`` may alias P - when F.C.getCoefA() == 0: + when F.Name.getCoefA() == 0: var t0 {.noInit.}, t1 {.noInit.}, t2 {.noInit.}, t3 {.noInit.}, t4 {.noInit.}: F var x3 {.noInit.}, y3 {.noInit.}, z3 {.noInit.}: F - const b3 = 3 * F.C.getCoefB() + const b3 = 3 * F.Name.getCoefB() # Algorithm 8 for curves: y² = x³ + b # X₃ = (X₁Y₂ + X₂Y₁)(Y₁Y₂ − 3bZ₁) @@ -284,27 +287,27 @@ func madd*[F; G: static Subgroup]( t3 *= t4 # 5. t₃ <- t₃ * t₄ t4.sum(t0, t1) # 6. t₄ <- t₀ + t₁ t3 -= t4 # 7. t₃ <- t₃ - t₄, t₃ = (X₁ + Y₁)(X₂ + Y₂) - (X₁ X₂ + Y₁ Y₂) = X₁Y₂ + X₂Y₁ - when G == G2 and F.C.getSexticTwist() == D_Twist: + when G == G2 and F.Name.getSexticTwist() == D_Twist: t3 *= SexticNonResidue t4.prod(Q.y, P.z) # 8. t₄ <- Y₂ Z₁ t4 += P.y # 9. t₄ <- t₄ + Y₁, t₄ = Y₁+Y₂Z₁ - when G == G2 and F.C.getSexticTwist() == D_Twist: + when G == G2 and F.Name.getSexticTwist() == D_Twist: t4 *= SexticNonResidue y3.prod(Q.x, P.z) # 10. Y₃ <- X₂ Z₁ y3 += P.x # 11. Y₃ <- Y₃ + X₁, Y₃ = X₁ + X₂Z₁ - when G == G2 and F.C.getSexticTwist() == D_Twist: + when G == G2 and F.Name.getSexticTwist() == D_Twist: t0 *= SexticNonResidue t1 *= SexticNonResidue x3.double(t0) # 12. X₃ <- t₀ + t₀ t0 += x3 # 13. t₀ <- X₃ + t₀, t₀ = 3X₁X₂ t2 = P.z t2 *= b3 # 14. t₂ <- 3bZ₁ - when G == G2 and F.C.getSexticTwist() == M_Twist: + when G == G2 and F.Name.getSexticTwist() == M_Twist: t2 *= SexticNonResidue z3.sum(t1, t2) # 15. Z₃ <- t₁ + t₂, Z₃ = Y₁Y₂ + 3bZ₁ t1 -= t2 # 16. t₁ <- t₁ - t₂, t₁ = Y₁Y₂ - 3bZ₁ y3 *= b3 # 17. Y₃ <- 3bY₃, Y₃ = 3b(X₁ + X₂Z₁) - when G == G2 and F.C.getSexticTwist() == M_Twist: + when G == G2 and F.Name.getSexticTwist() == M_Twist: y3 *= SexticNonResidue x3.prod(t4, y3) # 18. X₃ <- t₄ Y₃, X₃ = (Y₁ + Y₂Z₁) 3b(X₁ + X₂Z₁) t2.prod(t3, t1) # 19. t₂ <- t₃ t₁, t₂ = (X₁Y₂ + X₂Y₁)(Y₁Y₂ - 3bZ₁) @@ -330,8 +333,8 @@ func madd*[F; G: static Subgroup]( {.error: "Not implemented.".} func double*[F; G: static Subgroup]( - r: var ECP_ShortW_Prj[F, G], - P: ECP_ShortW_Prj[F, G] + r: var EC_ShortW_Prj[F, G], + P: EC_ShortW_Prj[F, G] ) {.meter.} = ## Elliptic curve point doubling for Short Weierstrass curves in projective coordinate ## @@ -365,10 +368,10 @@ func double*[F; G: static Subgroup]( # # Cost: 8M + 3S + 3 mul(a) + 2 mul(3b) + 15a - when F.C.getCoefA() == 0: + when F.Name.getCoefA() == 0: var t0 {.noInit.}, t1 {.noInit.}, t2 {.noInit.}: F var x3 {.noInit.}, y3 {.noInit.}, z3 {.noInit.}: F - const b3 = 3 * F.C.getCoefB() + const b3 = 3 * F.Name.getCoefB() # Algorithm 9 for curves: # 6M + 2S + 1 mul(3b) + 9a @@ -376,7 +379,7 @@ func double*[F; G: static Subgroup]( # X₃ = 2XY(Y² - 9bZ²) # Y₃ = (Y² - 9bZ²)(Y² + 3bZ²) + 24bY²Z² # Z₃ = 8Y³Z - when G == G2 and F.C.getSexticTwist() == D_Twist: + when G == G2 and F.Name.getSexticTwist() == D_Twist: var snrY {.noInit.}: F snrY.prod(P.y, SexticNonResidue) t0.square(P.y) @@ -390,7 +393,7 @@ func double*[F; G: static Subgroup]( t1.prod(snrY, P.z) # 5. t₁ <- Y Z t2.square(P.z) # 6. t₂ <- Z Z t2 *= b3 # 7. t₂ <- 3b t₂ - when G == G2 and F.C.getSexticTwist() == M_Twist: + when G == G2 and F.Name.getSexticTwist() == M_Twist: t2 *= SexticNonResidue x3.prod(t2, z3) # 8. X₃ <- t₂ Z₃ y3.sum(t0, t2) # 9. Y₃ <- t₀ + t₂ @@ -406,47 +409,47 @@ func double*[F; G: static Subgroup]( else: {.error: "Not implemented.".} -func `+=`*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Prj) {.inline.} = +func `+=`*(P: var EC_ShortW_Prj, Q: EC_ShortW_Prj) {.inline.} = ## In-place point addition P.sum(P, Q) -func `+=`*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Aff) {.inline.} = +func `+=`*(P: var EC_ShortW_Prj, Q: EC_ShortW_Aff) {.inline.} = ## In-place mixed point addition - P.madd(P, Q) + P.mixedSum(P, Q) -func double*(P: var ECP_ShortW_Prj) {.inline.} = +func double*(P: var EC_ShortW_Prj) {.inline.} = ## In-place EC doubling P.double(P) -func diff*(r: var ECP_ShortW_Prj, P, Q: ECP_ShortW_Prj) {.inline.} = +func diff*(r: var EC_ShortW_Prj, P, Q: EC_ShortW_Prj) {.inline.} = ## r = P - Q ## Can handle r and Q aliasing var nQ {.noInit.}: typeof(Q) nQ.neg(Q) r.sum(P, nQ) -func diff*(r: var ECP_ShortW_Prj, P: ECP_ShortW_Prj, Q: ECP_ShortW_Aff) {.inline.} = +func diff*(r: var EC_ShortW_Prj, P: EC_ShortW_Prj, Q: EC_ShortW_Aff) {.inline.} = ## r = P - Q var nQ {.noInit.}: typeof(Q) nQ.neg(Q) - r.madd(P, nQ) + r.mixedSum(P, nQ) -func `-=`*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Prj or ECP_ShortW_Aff) {.inline.} = +func `-=`*(P: var EC_ShortW_Prj, Q: EC_ShortW_Prj or EC_ShortW_Aff) {.inline.} = ## In-place point substraction P.diff(P, Q) -template affine*[F, G](_: type ECP_ShortW_Prj[F, G]): typedesc = +template affine*[F, G](_: type EC_ShortW_Prj[F, G]): untyped = ## Returns the affine type that corresponds to the Jacobian type input - ECP_ShortW_Aff[F, G] + EC_ShortW_Aff[F, G] -template projective*[F, G](_: type ECP_ShortW_Aff[F, G]): typedesc = +template projective*[F, G](_: type EC_ShortW_Aff[F, G]): untyped = ## Returns the projective type that corresponds to the affine type input - ECP_ShortW_Prj[F, G] + EC_ShortW_Prj[F, G] func affine*[F, G]( - aff: var ECP_ShortW_Aff[F, G], - proj: ECP_ShortW_Prj[F, G]) {.meter.} = + aff: var EC_ShortW_Aff[F, G], + proj: EC_ShortW_Prj[F, G]) {.meter.} = var invZ {.noInit.}: F invZ.inv(proj.z) @@ -454,8 +457,8 @@ func affine*[F, G]( aff.y.prod(proj.y, invZ) func fromAffine*[F, G]( - proj: var ECP_ShortW_Prj[F, G], - aff: ECP_ShortW_Aff[F, G]) {.inline.} = + proj: var EC_ShortW_Prj[F, G], + aff: EC_ShortW_Aff[F, G]) {.inline.} = proj.x = aff.x proj.y = aff.y proj.z.setOne() @@ -473,8 +476,8 @@ func fromAffine*[F, G]( # to hours of computations. Those primitives do not need constant-timeness. func sum_vartime*[F; G: static Subgroup]( - r: var ECP_ShortW_Prj[F, G], - p, q: ECP_ShortW_Prj[F, G]) + r: var EC_ShortW_Prj[F, G], + p, q: EC_ShortW_Prj[F, G]) {.tags:[VarTime], meter.} = ## **Variable-time** homogeneous projective addition ## @@ -573,10 +576,10 @@ func sum_vartime*[F; G: static Subgroup]( r.y *= R r.y -= Y1Z2 -func madd_vartime*[F; G: static Subgroup]( - r: var ECP_ShortW_Prj[F, G], - p: ECP_ShortW_Prj[F, G], - q: ECP_ShortW_Aff[F, G]) +func mixedSum_vartime*[F; G: static Subgroup]( + r: var EC_ShortW_Prj[F, G], + p: EC_ShortW_Prj[F, G], + q: EC_ShortW_Aff[F, G]) {.tags:[VarTime], meter.} = ## **Variable-time** homogeneous projective mixed addition ## @@ -662,7 +665,7 @@ func madd_vartime*[F; G: static Subgroup]( r.y *= R r.y -= Y1Z2 -func diff_vartime*(r: var ECP_ShortW_Prj, P, Q: ECP_ShortW_Prj) {.inline.} = +func diff_vartime*(r: var EC_ShortW_Prj, P, Q: EC_ShortW_Prj) {.inline.} = ## r = P - Q ## ## This MUST NOT be used with secret data. @@ -672,7 +675,7 @@ func diff_vartime*(r: var ECP_ShortW_Prj, P, Q: ECP_ShortW_Prj) {.inline.} = nQ.neg(Q) r.sum_vartime(P, nQ) -func msub_vartime*(r: var ECP_ShortW_Prj, P: ECP_ShortW_Prj, Q: ECP_ShortW_Aff) {.inline.} = +func mixedDiff_vartime*(r: var EC_ShortW_Prj, P: EC_ShortW_Prj, Q: EC_ShortW_Aff) {.inline.} = ## r = P - Q ## ## This MUST NOT be used with secret data. @@ -680,18 +683,18 @@ func msub_vartime*(r: var ECP_ShortW_Prj, P: ECP_ShortW_Prj, Q: ECP_ShortW_Aff) ## This is highly VULNERABLE to timing attacks and power analysis attacks. var nQ {.noInit.}: typeof(Q) nQ.neg(Q) - r.madd_vartime(P, nQ) + r.mixedSum_vartime(P, nQ) -template `~+=`*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Prj) = +template `~+=`*(P: var EC_ShortW_Prj, Q: EC_ShortW_Prj) = ## Variable-time in-place point addition P.sum_vartime(P, Q) -template `~+=`*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Aff) = +template `~+=`*(P: var EC_ShortW_Prj, Q: EC_ShortW_Aff) = ## Variable-time in-place point mixed addition - P.madd_vartime(P, Q) + P.mixedSum_vartime(P, Q) -template `~-=`*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Prj) = +template `~-=`*(P: var EC_ShortW_Prj, Q: EC_ShortW_Prj) = P.diff_vartime(P, Q) -template `~-=`*(P: var ECP_ShortW_Prj, Q: ECP_ShortW_Aff) = - P.msub_vartime(P, Q) +template `~-=`*(P: var EC_ShortW_Prj, Q: EC_ShortW_Aff) = + P.mixedDiff_vartime(P, Q) diff --git a/constantine/math/elliptic/ec_twistededwards_affine.nim b/constantine/math/elliptic/ec_twistededwards_affine.nim index dcc6861eb..247bc5049 100644 --- a/constantine/math/elliptic/ec_twistededwards_affine.nim +++ b/constantine/math/elliptic/ec_twistededwards_affine.nim @@ -20,7 +20,7 @@ import # # ############################################################ -type ECP_TwEdwards_Aff*[F] = object +type EC_TwEdw_Aff*[F] = object ## Elliptic curve point for a curve in Twisted Edwards form ## ax²+y²=1+dx²y² ## with a, d ≠ 0 and a ≠ d @@ -28,7 +28,10 @@ type ECP_TwEdwards_Aff*[F] = object ## over a field F x*, y*: F -func `==`*(P, Q: ECP_TwEdwards_Aff): SecretBool = +template getScalarField*(EC: type EC_TwEdw_Aff): untyped = + Fr[EC.F.Name] + +func `==`*(P, Q: EC_TwEdw_Aff): SecretBool = ## Constant-time equality check # Isogeny-based constructions to create # prime order curves overload this generic equality check. @@ -36,7 +39,7 @@ func `==`*(P, Q: ECP_TwEdwards_Aff): SecretBool = result = result and (P.y == Q.y) -func isNeutral*(P: ECP_TwEdwards_Aff): SecretBool = +func isNeutral*(P: EC_TwEdw_Aff): SecretBool = ## Returns true if P is the neutral element / identity element ## and false otherwise, i.e. ∀Q, P+Q == Q ## Contrary to Short Weierstrass curve, the neutral element is on the curve @@ -44,7 +47,7 @@ func isNeutral*(P: ECP_TwEdwards_Aff): SecretBool = # prime order curves overload this generic identity check. result = P.x.isZero() and P.y.isOne() -func setNeutral*(P: var ECP_TwEdwards_Aff) {.inline.} = +func setNeutral*(P: var EC_TwEdw_Aff) {.inline.} = ## Set P to the neutral element / identity element ## i.e. ∀Q, P+Q == Q. ## Contrary to Short Weierstrass curve, the neutral element is on the curve @@ -61,34 +64,34 @@ func isOnCurve*[F](x, y: F): SecretBool = t1.square(y) # ax²+y² - when F.C.getCoefA() is int: - when F.C.getCoefA() == -1: + when F.Name.getCoefA() is int: + when F.Name.getCoefA() == -1: t2.diff(t1, t0) else: - t2.prod(t0, F.C.getCoefA()) + t2.prod(t0, F.Name.getCoefA()) t2 += t1 else: - t2.prod(F.C.getCoefA(), t0) + t2.prod(F.Name.getCoefA(), t0) t2 += t1 # dx²y² t0 *= t1 - when F.C.getCoefD() is int: - when F.C.getCoefD >= 0: - t1.fromUint uint F.C.getCoefD() + when F.Name.getCoefD() is int: + when F.Name.getCoefD >= 0: + t1.fromUint uint F.Name.getCoefD() t0 *= t1 else: - t1.fromUint uint F.C.getCoefD() + t1.fromUint uint F.Name.getCoefD() t0 *= t1 t0.neg() else: - t0 *= F.C.getCoefD() + t0 *= F.Name.getCoefD() # ax²+y² - dx²y² =? 1 t2 -= t0 return t2.isOne() -func trySetFromCoordX*[F](P: var ECP_TwEdwards_Aff[F], x: F): SecretBool = +func trySetFromCoordX*[F](P: var EC_TwEdw_Aff[F], x: F): SecretBool = ## Try to create a point on the elliptic curve from X co-ordinate ## ax²+y²=1+dx²y² (affine coordinate) ## @@ -102,27 +105,27 @@ func trySetFromCoordX*[F](P: var ECP_TwEdwards_Aff[F], x: F): SecretBool = # (1 - dx²) t.square(x) - when F.C.getCoefD() is int: - when F.C.getCoefD() >= 0: - P.y.fromUint uint F.C.getCoefD() + when F.Name.getCoefD() is int: + when F.Name.getCoefD() >= 0: + P.y.fromUint uint F.Name.getCoefD() else: - P.y.fromUint uint -F.C.getCoefD() + P.y.fromUint uint -F.Name.getCoefD() P.y.neg() else: - P.y = F.C.getCoefD() + P.y = F.Name.getCoefD() P.y *= t P.y.neg() P.y += one # (1 - ax²) - when F.C.getCoefA() is int: - when F.C.getCoefA() >= 0: - P.x.fromUint uint F.C.getCoefA() + when F.Name.getCoefA() is int: + when F.Name.getCoefA() >= 0: + P.x.fromUint uint F.Name.getCoefA() else: - P.x.fromUint uint -F.C.getCoefA() + P.x.fromUint uint -F.Name.getCoefA() P.x.neg() else: - P.x = F.C.getCoefA() + P.x = F.Name.getCoefA() P.x *= t P.x.neg() P.x += one @@ -132,7 +135,7 @@ func trySetFromCoordX*[F](P: var ECP_TwEdwards_Aff[F], x: F): SecretBool = P.y = t P.x = x -func trySetFromCoordX_vartime*[F](P: var ECP_TwEdwards_Aff[F], x: F): SecretBool = +func trySetFromCoordX_vartime*[F](P: var EC_TwEdw_Aff[F], x: F): SecretBool = ## This is not in constant time ## Try to create a point on the elliptic curve from X co-ordinate ## ax²+y²=1+dx²y² (affine coordinate) @@ -147,27 +150,27 @@ func trySetFromCoordX_vartime*[F](P: var ECP_TwEdwards_Aff[F], x: F): SecretBool # (1 - dx²) t.square(x) - when F.C.getCoefD() is int: - when F.C.getCoefD() >= 0: - P.y.fromUint uint F.C.getCoefD() + when F.Name.getCoefD() is int: + when F.Name.getCoefD() >= 0: + P.y.fromUint uint F.Name.getCoefD() else: - P.y.fromUint uint -F.C.getCoefD() + P.y.fromUint uint -F.Name.getCoefD() P.y.neg() else: - P.y = F.C.getCoefD() + P.y = F.Name.getCoefD() P.y *= t P.y.neg() P.y += one # (1 - ax²) - when F.C.getCoefA() is int: - when F.C.getCoefA() >= 0: - P.x.fromUint uint F.C.getCoefA() + when F.Name.getCoefA() is int: + when F.Name.getCoefA() >= 0: + P.x.fromUint uint F.Name.getCoefA() else: - P.x.fromUint uint -F.C.getCoefA() + P.x.fromUint uint -F.Name.getCoefA() P.x.neg() else: - P.x = F.C.getCoefA() + P.x = F.Name.getCoefA() P.x *= t P.x.neg() P.x += one @@ -177,7 +180,7 @@ func trySetFromCoordX_vartime*[F](P: var ECP_TwEdwards_Aff[F], x: F): SecretBool P.y = t P.x = x -func trySetFromCoordY*[F](P: var ECP_TwEdwards_Aff[F], y: F): SecretBool = +func trySetFromCoordY*[F](P: var EC_TwEdw_Aff[F], y: F): SecretBool = ## Try to create a point the elliptic curve ## ax²+y²=1+dx²y² (affine coordinate) ## @@ -204,27 +207,27 @@ func trySetFromCoordY*[F](P: var ECP_TwEdwards_Aff[F], y: F): SecretBool = t.square(y) # (dy² − a) - when F.C.getCoefD() is int: - when F.C.getCoefD() >= 0: - P.y.fromUint uint F.C.getCoefD() + when F.Name.getCoefD() is int: + when F.Name.getCoefD() >= 0: + P.y.fromUint uint F.Name.getCoefD() else: - P.y.fromUint uint -F.C.getCoefD() + P.y.fromUint uint -F.Name.getCoefD() P.y.neg() else: - P.y = F.C.getCoefD() + P.y = F.Name.getCoefD() P.y *= t - when F.C.getCoefA() is int: - when F.C.getCoefA == -1: + when F.Name.getCoefA() is int: + when F.Name.getCoefA == -1: P.x.setOne() P.y += P.x - elif F.C.getCoefA >= 0: - P.x.fromUint uint F.C.getCoefA() + elif F.Name.getCoefA >= 0: + P.x.fromUint uint F.Name.getCoefA() P.y -= P.x else: - P.x.fromUint uint -F.C.getCoefA() + P.x.fromUint uint -F.Name.getCoefA() P.y += P.x else: - P.y -= F.C.getCoefA() + P.y -= F.Name.getCoefA() # y² − 1 P.x.setMinusOne() @@ -235,16 +238,16 @@ func trySetFromCoordY*[F](P: var ECP_TwEdwards_Aff[F], y: F): SecretBool = P.x = t P.y = y -func neg*(P: var ECP_TwEdwards_Aff, Q: ECP_TwEdwards_Aff) = +func neg*(P: var EC_TwEdw_Aff, Q: EC_TwEdw_Aff) = ## Negate ``P`` P.x.neg(Q.x) P.y = Q.y -func neg*(P: var ECP_TwEdwards_Aff) = +func neg*(P: var EC_TwEdw_Aff) = ## Negate ``P`` P.x.neg() -func cneg*(P: var ECP_TwEdwards_Aff, ctl: CTBool) = +func cneg*(P: var EC_TwEdw_Aff, ctl: CTBool) = ## Conditional negation. ## Negate if ``ctl`` is true P.x.cneg(ctl) @@ -255,7 +258,7 @@ func cneg*(P: var ECP_TwEdwards_Aff, ctl: CTBool) = # # ############################################################ -func `==`*(P, Q: ECP_TwEdwards_Aff[Fp[Banderwagon]]): SecretBool = +func `==`*(P, Q: EC_TwEdw_Aff[Fp[Banderwagon]]): SecretBool = ## Equality check for points in the Banderwagon Group ## The equality check is optimized for the quotient group ## This is a costly operation @@ -272,7 +275,7 @@ func `==`*(P, Q: ECP_TwEdwards_Aff[Fp[Banderwagon]]): SecretBool = rhs.prod(Q.x, P.y) result = result and lhs == rhs -func isNeutral*(P: ECP_TwEdwards_Aff[Fp[Banderwagon]]): SecretBool {.inline.} = +func isNeutral*(P: EC_TwEdw_Aff[Fp[Banderwagon]]): SecretBool {.inline.} = ## Returns true if P is the neutral/identity element ## in the Banderwagon group ## and false otherwise diff --git a/constantine/math/elliptic/ec_twistededwards_batch_ops.nim b/constantine/math/elliptic/ec_twistededwards_batch_ops.nim index 6fc72ffd9..3e0ff206e 100644 --- a/constantine/math/elliptic/ec_twistededwards_batch_ops.nim +++ b/constantine/math/elliptic/ec_twistededwards_batch_ops.nim @@ -23,8 +23,8 @@ import # ############################################################ func batchAffine*[F]( - affs: ptr UncheckedArray[ECP_TwEdwards_Aff[F]], - projs: ptr UncheckedArray[ECP_TwEdwards_Prj[F]], + affs: ptr UncheckedArray[EC_TwEdw_Aff[F]], + projs: ptr UncheckedArray[EC_TwEdw_Prj[F]], N: int) {.noInline, tags:[Alloca].} = # Algorithm: Montgomery's batch inversion # - Speeding the Pollard and Elliptic Curve Methods of Factorization @@ -78,11 +78,11 @@ func batchAffine*[F]( affs[0].y.prod(projs[0].y, accInv) func batchAffine*[N: static int, F]( - affs: var array[N, ECP_TwEdwards_Aff[F]], - projs: array[N, ECP_TwEdwards_Prj[F]]) {.inline.} = + affs: var array[N, EC_TwEdw_Aff[F]], + projs: array[N, EC_TwEdw_Prj[F]]) {.inline.} = batchAffine(affs.asUnchecked(), projs.asUnchecked(), N) func batchAffine*[M, N: static int, F]( - affs: var array[M, array[N, ECP_TwEdwards_Aff[F]]], - projs: array[M, array[N, ECP_TwEdwards_Prj[F]]]) {.inline.} = + affs: var array[M, array[N, EC_TwEdw_Aff[F]]], + projs: array[M, array[N, EC_TwEdw_Prj[F]]]) {.inline.} = batchAffine(affs[0].asUnchecked(), projs[0].asUnchecked(), M*N) diff --git a/constantine/math/elliptic/ec_twistededwards_projective.nim b/constantine/math/elliptic/ec_twistededwards_projective.nim index f6dcce048..e9ab8025e 100644 --- a/constantine/math/elliptic/ec_twistededwards_projective.nim +++ b/constantine/math/elliptic/ec_twistededwards_projective.nim @@ -21,7 +21,7 @@ import # # ############################################################ -type ECP_TwEdwards_Prj*[F] = object +type EC_TwEdw_Prj*[F] = object ## Elliptic curve point for a curve in Twisted Edwards form ## ax²+y²=1+dx²y² ## with a, d ≠ 0 and a ≠ d @@ -33,13 +33,16 @@ type ECP_TwEdwards_Prj*[F] = object ## hence (aX² + Y²)Z² = Z⁴ + dX²Y² x*, y*, z*: F -func `==`*(P, Q: ECP_TwEdwards_Prj): SecretBool = +template getScalarField*(EC: type EC_TwEdw_Prj): untyped = + Fr[EC.F.Name] + +func `==`*(P, Q: EC_TwEdw_Prj): SecretBool = ## Constant-time equality check ## This is a costly operation # Reminder: the representation is not unique # Isogeny-based constructions to create # prime order curves overload this generic equality check. - var a{.noInit.}, b{.noInit.}: ECP_TwEdwards_Prj.F + var a{.noInit.}, b{.noInit.}: EC_TwEdw_Prj.F a.prod(P.x, Q.z) b.prod(Q.x, P.z) @@ -49,7 +52,7 @@ func `==`*(P, Q: ECP_TwEdwards_Prj): SecretBool = b.prod(Q.y, P.z) result = result and a == b -func isNeutral*(P: ECP_TwEdwards_Prj): SecretBool {.inline.} = +func isNeutral*(P: EC_TwEdw_Prj): SecretBool {.inline.} = ## Returns true if P is the neutral element / identity element ## and false otherwise, i.e. ∀Q, P+Q == Q ## Contrary to Short Weierstrass curve, the neutral element is on the curve @@ -57,7 +60,7 @@ func isNeutral*(P: ECP_TwEdwards_Prj): SecretBool {.inline.} = # prime order curves overload this generic identity check. result = P.x.isZero() and (P.y == P.z) -func setNeutral*(P: var ECP_TwEdwards_Prj) {.inline.} = +func setNeutral*(P: var EC_TwEdw_Prj) {.inline.} = ## Set P to the neutral element / identity element ## i.e. ∀Q, P+Q == Q. ## Contrary to Short Weierstrass curve, the neutral element is on the curve @@ -65,7 +68,7 @@ func setNeutral*(P: var ECP_TwEdwards_Prj) {.inline.} = P.y.setOne() P.z.setOne() -func ccopy*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Prj, ctl: SecretBool) {.inline.} = +func ccopy*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Prj, ctl: SecretBool) {.inline.} = ## Constant-time conditional copy ## If ctl is true: Q is copied into P ## if ctl is false: Q is not copied and P is unmodified @@ -74,7 +77,7 @@ func ccopy*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Prj, ctl: SecretBool) {.i ccopy(fP, fQ, ctl) func trySetFromCoordX*[F]( - P: var ECP_TwEdwards_Prj[F], + P: var EC_TwEdw_Prj[F], x: F): SecretBool = ## Try to create a point on the elliptic curve from X co-ordinate ## ax²+y²=1+dx²y² (affine coordinate) @@ -84,7 +87,7 @@ func trySetFromCoordX*[F]( ## return true and update `P` if `y` leads to a valid point ## return false otherwise, in that case `P` is undefined. - var Q{.noInit.}: ECP_TwEdwards_Aff[F] + var Q{.noInit.}: EC_TwEdw_Aff[F] result = Q.trySetFromCoordX(x) P.x = Q.x @@ -92,7 +95,7 @@ func trySetFromCoordX*[F]( P.z.setOne() func trySetFromCoordX_vartime*[F]( - P: var ECP_TwEdwards_Prj[F], + P: var EC_TwEdw_Prj[F], x: F): SecretBool = ## this is not in constant time ## Try to create a point on the elliptic curve from X co-ordinate @@ -103,7 +106,7 @@ func trySetFromCoordX_vartime*[F]( ## return true and update `P` if `y` leads to a valid point ## return false otherwise, in that case `P` is undefined. - var Q{.noInit.}: ECP_TwEdwards_Aff[F] + var Q{.noInit.}: EC_TwEdw_Aff[F] result = Q.trySetFromCoordX_vartime(x) P.x = Q.x @@ -112,7 +115,7 @@ func trySetFromCoordX_vartime*[F]( func trySetFromCoordY*[F]( - P: var ECP_TwEdwards_Prj[F], + P: var EC_TwEdw_Prj[F], y: F): SecretBool = ## Try to create a point the elliptic curve ## ax²+y²=1+dx²y² (affine coordinate) @@ -134,7 +137,7 @@ func trySetFromCoordY*[F]( ## - a generator point is defined ## i.e. you can't test unless everything is already working - var Q{.noInit.}: ECP_TwEdwards_Aff[F] + var Q{.noInit.}: EC_TwEdw_Aff[F] result = Q.trySetFromCoordY(y) P.x = Q.x @@ -142,7 +145,7 @@ func trySetFromCoordY*[F]( P.z.setOne() func trySetFromCoordsYandZ*[F]( - P: var ECP_TwEdwards_Prj[F], + P: var EC_TwEdw_Prj[F], y, z: F): SecretBool = ## Try to create a point the elliptic curve ## ax²+y²=1+dx²y² (affine coordinate) @@ -162,31 +165,31 @@ func trySetFromCoordsYandZ*[F]( ## - a generator point is defined ## i.e. you can't test unless everything is already working - var Q{.noInit.}: ECP_TwEdwards_Aff[F] + var Q{.noInit.}: EC_TwEdw_Aff[F] result = Q.trySetFromCoordY(y) P.x.prod(Q.x, z) P.y.prod(Q.y, z) P.z = z -func neg*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Prj) {.inline.} = +func neg*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Prj) {.inline.} = ## Negate ``P`` P.x.neg(Q.x) P.y = Q.y P.z = Q.z -func neg*(P: var ECP_TwEdwards_Prj) {.inline.} = +func neg*(P: var EC_TwEdw_Prj) {.inline.} = ## Negate ``P`` P.x.neg() -func cneg*(P: var ECP_TwEdwards_Prj, ctl: CTBool) {.inline.} = +func cneg*(P: var EC_TwEdw_Prj, ctl: CTBool) {.inline.} = ## Conditional negation. ## Negate if ``ctl`` is true P.x.cneg(ctl) func sum*[F]( - r: var ECP_TwEdwards_Prj[F], - P, Q: ECP_TwEdwards_Prj[F]) = + r: var EC_TwEdw_Prj[F], + P, Q: EC_TwEdw_Prj[F]) = ## Elliptic curve point addition for Twisted Edwards curves in projective coordinates ## ## R = P + Q @@ -226,15 +229,15 @@ func sum*[F]( C.prod(P.x, Q.x) D.prod(P.y, Q.y) E.prod(C, D) - when F.C.getCoefD() is int: + when F.Name.getCoefD() is int: # conversion at compile-time const coefD = block: var d: F - d.fromInt F.C.getCoefD() + d.fromInt F.Name.getCoefD() d E *= coefD else: - E *= F.C.getCoefD() + E *= F.Name.getCoefD() F.diff(B, E) G.sum(B, E) @@ -248,10 +251,10 @@ func sum*[F]( E.sum(C, D) # E = C+D # Y3 = A*G*(D-a*C) - when F.C.getCoefA() == -1: + when F.Name.getCoefA() == -1: r.y = E # (D-a*C) = D+C else: - r.y.prod(C, F.C.getCoefA()) + r.y.prod(C, F.Name.getCoefA()) r.y.diff(D, r.y) r.y *= A r.y *= G @@ -264,10 +267,10 @@ func sum*[F]( # Z3 = F*G r.z.prod(F, G) -func madd*[F]( - r: var ECP_TwEdwards_Prj[F], - P: ECP_TwEdwards_Prj[F], - Q: ECP_TwEdwards_Aff[F]) = +func mixedSum*[F]( + r: var EC_TwEdw_Prj[F], + P: EC_TwEdw_Prj[F], + Q: EC_TwEdw_Aff[F]) = ## Elliptic curve point mixed addition for Twisted Edwards curves in projective coordinates ## ## R = P + Q @@ -285,7 +288,7 @@ func madd*[F]( ## to simple side-channel attacks (SCA) ## This is done by using a "complete" or "exception-free" addition law. # - # https://www.hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#addition-madd-2008-bbjlp + # https://www.hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#addition-mixedSum-2008-bbjlp # Cost: 9M + 1S + 1*a + 1*d + 7add. # B = Z1² # C = X1*X2 @@ -305,15 +308,15 @@ func madd*[F]( C.prod(P.x, Q.x) D.prod(P.y, Q.y) E.prod(C, D) - when F.C.getCoefD() is int: + when F.Name.getCoefD() is int: # conversion at compile-time const coefD = block: var d: F - d.fromInt F.C.getCoefD() + d.fromInt F.Name.getCoefD() d E *= coefD else: - E *= F.C.getCoefD() + E *= F.Name.getCoefD() F.diff(B, E) G.sum(B, E) @@ -327,10 +330,10 @@ func madd*[F]( E.sum(C, D) # E = C+D # Y3 = A*G*(D-a*C) - when F.C.getCoefA() == -1: + when F.Name.getCoefA() == -1: r.y = E # (D-a*C) = D+C else: - r.y.prod(C, F.C.getCoefA()) + r.y.prod(C, F.Name.getCoefA()) r.y.diff(D, r.y) r.y *= P.z r.y *= G @@ -343,7 +346,7 @@ func madd*[F]( # Z3 = F*G r.z.prod(F, G) -func double*[F](r: var ECP_TwEdwards_Prj[F], P: ECP_TwEdwards_Prj[F]) = +func double*[F](r: var EC_TwEdw_Prj[F], P: EC_TwEdw_Prj[F]) = ## Elliptic curve point doubling for Twisted Edwards curves in projective coordinates ## ## R = [2] P @@ -385,7 +388,7 @@ func double*[F](r: var ECP_TwEdwards_Prj[F], P: ECP_TwEdwards_Prj[F]) = r.x.double() D.square(P.y) - E *= F.C.getCoefA() + E *= F.Name.getCoefA() r.y.sum(E, D) # Ry stores F = E+D H.square(P.z) @@ -397,51 +400,51 @@ func double*[F](r: var ECP_TwEdwards_Prj[F], P: ECP_TwEdwards_Prj[F]) = E -= D # C stores E-D r.y *= E -func `+=`*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Prj) {.inline.} = +func `+=`*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Prj) {.inline.} = ## In-place point addition P.sum(P, Q) -func `+=`*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Aff) {.inline.} = +func `+=`*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Aff) {.inline.} = ## In-place point mixed addition - P.madd(P, Q) + P.mixedSum(P, Q) -func double*(P: var ECP_TwEdwards_Prj) {.inline.} = +func double*(P: var EC_TwEdw_Prj) {.inline.} = ## In-place EC doubling P.double(P) -func diff*(r: var ECP_TwEdwards_Prj, P, Q: ECP_TwEdwards_Prj) {.inline.} = +func diff*(r: var EC_TwEdw_Prj, P, Q: EC_TwEdw_Prj) {.inline.} = ## r = P - Q ## Can handle r and Q aliasing var nQ {.noInit.}: typeof(Q) nQ.neg(Q) r.sum(P, nQ) -func msub*(r: var ECP_TwEdwards_Prj, P: ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Aff) {.inline.} = +func mixedDiff*(r: var EC_TwEdw_Prj, P: EC_TwEdw_Prj, Q: EC_TwEdw_Aff) {.inline.} = ## r = P - Q ## Can handle r and Q aliasing var nQ {.noInit.}: typeof(Q) nQ.neg(Q) - r.madd(P, nQ) + r.mixedSum(P, nQ) -func `-=`*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Prj) {.inline.} = +func `-=`*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Prj) {.inline.} = ## In-place point substraction P.diff(P, Q) -func `-=`*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Aff) {.inline.} = +func `-=`*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Aff) {.inline.} = ## In-place point substraction - P.msub(P, Q) + P.mixedDiff(P, Q) -template affine*[F](_: type ECP_TwEdwards_Prj[F]): typedesc = +template affine*[F](_: type EC_TwEdw_Prj[F]): untyped = ## Returns the affine type that corresponds to the Jacobian type input - ECP_TwEdwards_Aff[F] + EC_TwEdw_Aff[F] -template projective*[F](_: type ECP_TwEdwards_Aff[F]): typedesc = +template projective*[F](_: type EC_TwEdw_Aff[F]): untyped = ## Returns the projective type that corresponds to the affine type input - ECP_TwEdwards_Prj[F] + EC_TwEdw_Prj[F] func affine*[F]( - aff: var ECP_TwEdwards_Aff[F], - proj: ECP_TwEdwards_Prj[F]) = + aff: var EC_TwEdw_Aff[F], + proj: EC_TwEdw_Prj[F]) = var invZ {.noInit.}: F invZ.inv(proj.z) @@ -449,8 +452,8 @@ func affine*[F]( aff.y.prod(proj.y, invZ) func fromAffine*[F]( - proj: var ECP_TwEdwards_Prj[F], - aff: ECP_TwEdwards_Aff[F]) {.inline.} = + proj: var EC_TwEdw_Prj[F], + aff: EC_TwEdw_Aff[F]) {.inline.} = proj.x = aff.x proj.y = aff.y proj.z.setOne() @@ -460,40 +463,40 @@ func fromAffine*[F]( # For generic vartime operations on both ShortWeierstrass curves and Twisted Edwards func sum_vartime*[F]( - r: var ECP_TwEdwards_Prj[F], - P, Q: ECP_TwEdwards_Prj[F]) {.inline.} = + r: var EC_TwEdw_Prj[F], + P, Q: EC_TwEdw_Prj[F]) {.inline.} = r.sum(P, Q) -func madd_vartime*[F]( - r: var ECP_TwEdwards_Prj[F], - P: ECP_TwEdwards_Prj[F], - Q: ECP_TwEdwards_Aff[F]) {.inline.} = - r.madd(P, Q) +func mixedSum_vartime*[F]( + r: var EC_TwEdw_Prj[F], + P: EC_TwEdw_Prj[F], + Q: EC_TwEdw_Aff[F]) {.inline.} = + r.mixedSum(P, Q) func diff_vartime*[F]( - r: var ECP_TwEdwards_Prj[F], - P, Q: ECP_TwEdwards_Prj[F]) {.inline.} = + r: var EC_TwEdw_Prj[F], + P, Q: EC_TwEdw_Prj[F]) {.inline.} = r.diff(P, Q) -func msub_vartime*[F]( - r: var ECP_TwEdwards_Prj[F], - P: ECP_TwEdwards_Prj[F], - Q: ECP_TwEdwards_Aff[F]) {.inline.} = - r.msub(P, Q) +func mixedDiff_vartime*[F]( + r: var EC_TwEdw_Prj[F], + P: EC_TwEdw_Prj[F], + Q: EC_TwEdw_Aff[F]) {.inline.} = + r.mixedDiff(P, Q) -template `~+=`*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Prj) = +template `~+=`*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Prj) = ## Variable-time in-place point addition P.sum_vartime(P, Q) -template `~+=`*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Aff) = +template `~+=`*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Aff) = ## Variable-time in-place point mixed addition - P.madd_vartime(P, Q) + P.mixedSum_vartime(P, Q) -template `~-=`*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Prj) = +template `~-=`*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Prj) = P.diff_vartime(P, Q) -template `~-=`*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Aff) = - P.msub_vartime(P, Q) +template `~-=`*(P: var EC_TwEdw_Prj, Q: EC_TwEdw_Aff) = + P.mixedDiff_vartime(P, Q) # ############################################################ # @@ -501,7 +504,7 @@ template `~-=`*(P: var ECP_TwEdwards_Prj, Q: ECP_TwEdwards_Aff) = # # ############################################################ -func `==`*(P, Q: ECP_TwEdwards_Prj[Fp[Banderwagon]]): SecretBool = +func `==`*(P, Q: EC_TwEdw_Prj[Fp[Banderwagon]]): SecretBool = ## Equality check for points in the Banderwagon Group ## The equality check is optimized for the quotient group ## This is a costly operation @@ -518,7 +521,7 @@ func `==`*(P, Q: ECP_TwEdwards_Prj[Fp[Banderwagon]]): SecretBool = rhs.prod(Q.x, P.y) result = result and lhs == rhs -func isNeutral*(P: ECP_TwEdwards_Prj[Fp[Banderwagon]]): SecretBool {.inline.} = +func isNeutral*(P: EC_TwEdw_Prj[Fp[Banderwagon]]): SecretBool {.inline.} = ## Returns true if P is the neutral/identity element ## in the Banderwagon group ## and false otherwise diff --git a/constantine/math/extension_fields/assembly/fp2_asm_x86_adx_bmi2.nim b/constantine/math/extension_fields/assembly/fp2_asm_x86_adx_bmi2.nim index 01171b020..ac25e67e4 100644 --- a/constantine/math/extension_fields/assembly/fp2_asm_x86_adx_bmi2.nim +++ b/constantine/math/extension_fields/assembly/fp2_asm_x86_adx_bmi2.nim @@ -75,8 +75,8 @@ func sqrx_complex_sparebit_asm_adx*( v2.double(a.c1) v0.diff(a.c0, a.c1) v1.sum(a.c0, a.c1) - r.c1.mres.limbs.mulMont_CIOS_sparebit_asm_adx(a.c0.mres.limbs, v2.mres.limbs, Fp.fieldMod().limbs, Fp.getNegInvModWord()) - r.c0.mres.limbs.mulMont_CIOS_sparebit_asm_adx(v0.mres.limbs, v1.mres.limbs, Fp.fieldMod().limbs, Fp.getNegInvModWord()) + r.c1.mres.limbs.mulMont_CIOS_sparebit_asm_adx(a.c0.mres.limbs, v2.mres.limbs, Fp.getModulus().limbs, Fp.getNegInvModWord()) + r.c0.mres.limbs.mulMont_CIOS_sparebit_asm_adx(v0.mres.limbs, v1.mres.limbs, Fp.getModulus().limbs, Fp.getNegInvModWord()) # 𝔽p2 multiplication # ------------------------------------------------------------ @@ -115,11 +115,11 @@ func mul_fp2_complex_asm_adx*( # see https://github.com/mratsim/constantine/issues/229 r.c0.mres.limbs.redcMont_asm_adx( d.c0.limbs2x, - Fp.fieldMod().limbs, + Fp.getModulus().limbs, Fp.getNegInvModWord(), Fp.getSpareBits()) r.c1.mres.limbs.redcMont_asm_adx( d.c1.limbs2x, - Fp.fieldMod().limbs, + Fp.getModulus().limbs, Fp.getNegInvModWord(), Fp.getSpareBits()) diff --git a/constantine/math/extension_fields/square_root_fp2.nim b/constantine/math/extension_fields/square_root_fp2.nim index 1f30ade1f..00ebc1d92 100644 --- a/constantine/math/extension_fields/square_root_fp2.nim +++ b/constantine/math/extension_fields/square_root_fp2.nim @@ -58,7 +58,7 @@ func sqrt_rotate_extension*( ## This requires the sqrt of sqrt of the quadratic non-residue ## to be in Fp2 var coeff{.noInit.}, cand2{.noInit.}, t{.noInit.}: Fp2 - const Curve = typeof(a.c0).C + const Curve = typeof(a.c0).Name # We name µ² the quadratic non-residue # if p ≡ 3 (mod 4), we have µ = 𝑖 = √-1 and µ² = -1 @@ -191,7 +191,7 @@ func sqrt_if_square*(a: var Fp2): SecretBool = ## ## The square root, if it exist is multivalued, ## i.e. both x² == (-x)² - when Fp2.C == BLS12_377: + when Fp2.Name == BLS12_377: # For BLS12_377, # the solution µ to x² - µ = 0 being a quadratic non-residue # is also a quadratic non-residue in Fp2, which means diff --git a/constantine/math/extension_fields/towers.nim b/constantine/math/extension_fields/towers.nim index 629ebac03..d2768473a 100644 --- a/constantine/math/extension_fields/towers.nim +++ b/constantine/math/extension_fields/towers.nim @@ -47,18 +47,18 @@ type ExtensionField*[F] = QuadraticExt[F] or CubicExt[F] - Fp2*[C: static Curve] = - QuadraticExt[Fp[C]] + Fp2*[Name: static Algebra] = + QuadraticExt[Fp[Name]] - Fp4*[C: static Curve] = - QuadraticExt[Fp2[C]] + Fp4*[Name: static Algebra] = + QuadraticExt[Fp2[Name]] - Fp6*[C: static Curve] = - CubicExt[Fp2[C]] + Fp6*[Name: static Algebra] = + CubicExt[Fp2[Name]] - Fp12*[C: static Curve] = - CubicExt[Fp4[C]] - # QuadraticExt[Fp6[C]] + Fp12*[Name: static Algebra] = + CubicExt[Fp4[Name]] + # QuadraticExt[Fp6[Name]] template c0*(a: ExtensionField): auto = a.coords[0] @@ -74,11 +74,11 @@ template `c1=`*(a: var ExtensionField, v: auto) = template `c2=`*(a: var CubicExt, v: auto) = a.coords[2] = v -template C*(E: type ExtensionField): Curve = - E.F.C +template Name*(E: type ExtensionField): Algebra = + E.F.Name -template fieldMod*(E: type ExtensionField): auto = - Mod(E.F.C) +template getModulus*(E: type ExtensionField): auto = + E.F.getModulus() # Initialization # ------------------------------------------------------------------- @@ -323,14 +323,14 @@ func has2extraBits*(F: type Fp): bool = func has1extraBit*(E: type ExtensionField): bool = ## We construct extensions only on Fp (and not Fr) - getSpareBits(Fp[E.F.C]) >= 1 + getSpareBits(Fp[E.F.Name]) >= 1 func has2extraBits*(E: type ExtensionField): bool = ## We construct extensions only on Fp (and not Fr) - getSpareBits(Fp[E.F.C]) >= 2 + getSpareBits(Fp[E.F.Name]) >= 2 -template C(E: type ExtensionField2x): Curve = - E.F.C +template A(E: type ExtensionField2x): Algebra = + E.F.Name template c0*(a: ExtensionField2x): auto = a.coords[0] @@ -418,20 +418,20 @@ func prod2x*(r: var ExtensionField2x, a: ExtensionField2x, b: static int) = func `*=`*(a: var Fp, _: type NonResidue) = ## Multiply an element of 𝔽p by the quadratic non-residue ## chosen to construct 𝔽p2 - static: doAssert Fp.C.getNonResidueFp() != -1, "𝔽p2 should be specialized for complex extension" - a *= Fp.C.getNonResidueFp() + static: doAssert Fp.Name.getNonResidueFp() != -1, "𝔽p2 should be specialized for complex extension" + a *= Fp.Name.getNonResidueFp() func prod*(r: var Fp, a: Fp, _: type NonResidue) = ## Multiply an element of 𝔽p by the quadratic non-residue ## chosen to construct 𝔽p2 - static: doAssert Fp.C.getNonResidueFp() != -1, "𝔽p2 should be specialized for complex extension" - r.prod(a, Fp.C.getNonResidueFp()) + static: doAssert Fp.Name.getNonResidueFp() != -1, "𝔽p2 should be specialized for complex extension" + r.prod(a, Fp.Name.getNonResidueFp()) func prod2x(r: var FpDbl, a: FpDbl, _: type NonResidue) = ## Multiply an element of 𝔽p by the quadratic non-residue ## chosen to construct 𝔽p2 - static: doAssert FpDbl.C.getNonResidueFp() != -1, "𝔽p2 should be specialized for complex extension" - r.prod2x(a, FpDbl.C.getNonResidueFp()) + static: doAssert FpDbl.Name.getNonResidueFp() != -1, "𝔽p2 should be specialized for complex extension" + r.prod2x(a, FpDbl.Name.getNonResidueFp()) # 𝔽p2 # ---------------------------------------------------------------- @@ -441,14 +441,14 @@ template fromComplexExtension*[F](elem: QuadraticExt[F]): static bool = ## i.e. the irreducible polynomial chosen is ## x² - µ with µ = -1 ## and so 𝔽p2 = 𝔽p[x] / x² - µ = 𝔽p[𝑖] - when F is Fp and F.C.getNonResidueFp() == -1: + when F is Fp and F.Name.getNonResidueFp() == -1: true else: false -func prod*[C: static Curve]( - r: var Fp2[C], - a: Fp2[C], +func prod*[Name: static Algebra]( + r: var Fp2[Name], + a: Fp2[Name], _: type NonResidue) = ## Multiply an element of 𝔽p2 by the non-residue ## chosen to construct the next extension or the twist: @@ -456,9 +456,9 @@ func prod*[C: static Curve]( ## - if cubic non-residue: 𝔽p6 ## - if sextic non-residue: 𝔽p4, 𝔽p6 or 𝔽p12 # Yet another const tuple unpacking bug - const u = C.getNonResidueFp2()[0] - const v = C.getNonResidueFp2()[1] - const Beta {.used.} = C.getNonResidueFp() + const u = Name.getNonResidueFp2()[0] + const v = Name.getNonResidueFp2()[1] + const Beta {.used.} = Name.getNonResidueFp() # ξ = u + v x # and x² = β # @@ -496,7 +496,7 @@ func prod*[C: static Curve]( else: {.error: "Unimplemented".} -func `*=`*[C: static Curve](a: var Fp2[C], _: type NonResidue) = +func `*=`*[Name: static Algebra](a: var Fp2[Name], _: type NonResidue) = ## Multiply an element of 𝔽p2 by the non-residue ## chosen to construct the next extension or the twist: ## - if quadratic non-residue: 𝔽p4 @@ -504,15 +504,15 @@ func `*=`*[C: static Curve](a: var Fp2[C], _: type NonResidue) = ## - if sextic non-residue: 𝔽p4, 𝔽p6 or 𝔽p12 a.prod(a, NonResidue) -func prod2x*[C: static Curve]( - r: var QuadraticExt2x[FpDbl[C]], - a: QuadraticExt2x[FpDbl[C]], +func prod2x*[Name: static Algebra]( + r: var QuadraticExt2x[FpDbl[Name]], + a: QuadraticExt2x[FpDbl[Name]], _: type NonResidue) = ## Multiplication by non-residue - const complex = C.getNonResidueFp() == -1 - const U = C.getNonResidueFp2()[0] - const V = C.getNonResidueFp2()[1] - const Beta {.used.} = C.getNonResidueFp() + const complex = Name.getNonResidueFp() == -1 + const U = Name.getNonResidueFp2()[0] + const V = Name.getNonResidueFp2()[1] + const Beta {.used.} = Name.getNonResidueFp() when complex and U == 1 and V == 1: let a1 {.noInit.} = a.c1 @@ -527,7 +527,7 @@ func prod2x*[C: static Curve]( # mul_sparse_by_0v # r0 = β a1 v # r1 = a0 v - var t {.noInit.}: FpDbl[C] + var t {.noInit.}: FpDbl[Name] t.prod2x(a.c1, V) r.c1.prod2x(a.c0, V) r.c0.prod2x(t, NonResidue) @@ -537,7 +537,7 @@ func prod2x*[C: static Curve]( # # (c0 + c1 x) (u + v x) => u c0 + (u c0 + u c1)x + v c1 x² # => u c0 + β v c1 + (v c0 + u c1) x - var t {.noInit.}: FpDbl[C] + var t {.noInit.}: FpDbl[Name] t.prod2x(a.c0, U) when V == 1 and Beta == -1: # Case BN254_Snarks @@ -554,7 +554,7 @@ func prod2x*[C: static Curve]( else: {.error: "Unimplemented".} -func `/=`*[C: static Curve](a: var Fp2[C], _: type NonResidue) = +func `/=`*[Name: static Algebra](a: var Fp2[Name], _: type NonResidue) = ## Divide an element of 𝔽p by the non-residue ## chosen to construct the next extension or the twist: ## - if quadratic non-residue: 𝔽p4 @@ -562,9 +562,9 @@ func `/=`*[C: static Curve](a: var Fp2[C], _: type NonResidue) = ## - if sextic non-residue: 𝔽p4, 𝔽p6 or 𝔽p12 # Yet another const tuple unpacking bug - const u = C.getNonresidueFp2()[0] # Sextic non-residue to construct 𝔽p12 - const v = C.getNonresidueFp2()[1] - const Beta = C.getNonResidueFp() # Quadratic non-residue to construct 𝔽p2 + const u = Name.getNonresidueFp2()[0] # Sextic non-residue to construct 𝔽p12 + const v = Name.getNonresidueFp2()[1] + const Beta = Name.getNonResidueFp() # Quadratic non-residue to construct 𝔽p2 # ξ = u + v x # and x² = β # @@ -716,13 +716,13 @@ func prefer_3sqr_over_2mul(F: type ExtensionField): bool {.compileTime.} = else: return false else: return false -func has_large_NR_norm(C: static Curve): bool = +func has_large_NR_norm(Name: static Algebra): bool = ## Returns true if the non-residue of the extension fields ## has a large norm - const j = C.getNonResidueFp() - const u = C.getNonResidueFp2()[0] - const v = C.getNonResidueFp2()[1] + const j = Name.getNonResidueFp() + const u = Name.getNonResidueFp2()[0] + const v = Name.getNonResidueFp2()[1] const norm2 = u*u + (j*v)*(j*v) @@ -733,10 +733,10 @@ func has_large_NR_norm(C: static Curve): bool = return norm > 5 -func has_large_field_elem*(C: static Curve): bool = +func has_large_field_elem*(Name: static Algebra): bool = ## Returns true if field element are large ## and necessitate custom routine for assembly in particular - let a = default(Fp[C]) + let a = default(Fp[Name]) return a.mres.limbs.len > 6 # ############################################################ @@ -913,7 +913,7 @@ func square_generic(r: var QuadraticExt, a: QuadraticExt) = when QuadraticExt.prefer_3sqr_over_2mul() or # Other path multiplies twice by non-residue - QuadraticExt.C.has_large_NR_norm(): + QuadraticExt.Name.has_large_NR_norm(): var v0 {.noInit.}, v1 {.noInit.}: typeof(r.c0) v0.square(a.c0) v1.square(a.c1) @@ -981,7 +981,7 @@ func square2x_disjoint*[Fdbl, F]( # Multiplications (specializations) # ------------------------------------------------------------------- -func prodImpl_fp4o2_complex_snr_1pi[C: static Curve](r: var Fp4[C], a, b: Fp4[C]) = +func prodImpl_fp4o2_complex_snr_1pi[Name: static Algebra](r: var Fp4[Name], a, b: Fp4[Name]) = ## Returns r = a * b ## For 𝔽p4/𝔽p2 with the following non-residue (NR) constraints: ## * -1 is a quadratic non-residue in 𝔽p hence 𝔽p2 has coordinates a+𝑖b with i = √-1. This implies p ≡ 3 (mod 4) @@ -990,13 +990,13 @@ func prodImpl_fp4o2_complex_snr_1pi[C: static Curve](r: var Fp4[C], a, b: Fp4[C] ## According to Benger-Scott 2009(https://eprint.iacr.org/2009/556.pdf) ## About 2/3 of the p ≡ 3 (mod 8) primes are in this case static: - doAssert C.getNonResidueFp() == -1 - doAssert C.getNonresidueFp2() == (1, 1) + doAssert Name.getNonResidueFp() == -1 + doAssert Name.getNonresidueFp2() == (1, 1) var - b10_m_b11{.noInit.}, b10_p_b11{.noInit.}: Fp[C] - n_a01{.noInit.}, n_a11{.noInit.}: Fp[C] + b10_m_b11{.noInit.}, b10_p_b11{.noInit.}: Fp[Name] + n_a01{.noInit.}, n_a11{.noInit.}: Fp[Name] - t{.noInit.}: Fp4[C] + t{.noInit.}: Fp4[Name] b10_m_b11.diff(b.c1.c0, b.c1.c1) b10_p_b11.sum(b.c1.c0, b.c1.c1) @@ -1314,7 +1314,7 @@ func inv2xImpl(r: var QuadraticExt, a: QuadraticExt, useVartime: static bool = f func square2x*(r: var QuadraticExt2x, a: QuadraticExt) = when a.fromComplexExtension(): - when UseASM_X86_64 and not QuadraticExt.C.has_large_field_elem(): + when UseASM_X86_64 and not QuadraticExt.Name.has_large_field_elem(): if ({.noSideEffect.}: hasAdx()): r.coords.sqrx2x_complex_asm_adx(a.coords) else: @@ -1339,7 +1339,7 @@ func square_disjoint*[F](r: var QuadraticExt[F], a0, a1: F) = func square*(r: var QuadraticExt, a: QuadraticExt) = when r.fromComplexExtension(): - when UseASM_X86_64 and not QuadraticExt.C.has_large_field_elem() and r.typeof.has1extraBit(): + when UseASM_X86_64 and not QuadraticExt.Name.has_large_field_elem() and r.typeof.has1extraBit(): if ({.noSideEffect.}: hasAdx()): r.coords.sqrx_complex_sparebit_asm_adx(a.coords) else: @@ -1347,7 +1347,7 @@ func square*(r: var QuadraticExt, a: QuadraticExt) = else: r.square_complex(a) else: - when QuadraticExt.C.has_large_field_elem(): + when QuadraticExt.Name.has_large_field_elem(): # BW6-761 requires too many registers for Dbl width path r.square_generic(a) elif QuadraticExt is Fp4[BLS12_377]: @@ -1364,7 +1364,7 @@ func prod*(r: var QuadraticExt, a, b: QuadraticExt) = ## Multiplication r <- a*b when r.fromComplexExtension(): - when UseASM_X86_64 and not QuadraticExt.C.has_large_field_elem(): + when UseASM_X86_64 and not QuadraticExt.Name.has_large_field_elem(): if ({.noSideEffect.}: hasAdx()): r.coords.mul_fp2_complex_asm_adx(a.coords, b.coords) else: @@ -1378,10 +1378,10 @@ func prod*(r: var QuadraticExt, a, b: QuadraticExt) = r.c0.redc2x(d.c0) r.c1.redc2x(d.c1) else: - when QuadraticExt is Fp12 or r.typeof.F.C.has_large_field_elem(): + when QuadraticExt is Fp12 or r.typeof.F.Name.has_large_field_elem(): # BW6-761 requires too many registers for Dbl width path r.prod_generic(a, b) - elif QuadraticExt is Fp4 and QuadraticExt.C.getNonResidueFp() == -1 and QuadraticExt.C.getNonResidueFp2() == (1, 1): + elif QuadraticExt is Fp4 and QuadraticExt.Name.getNonResidueFp() == -1 and QuadraticExt.Name.getNonResidueFp2() == (1, 1): r.prodImpl_fp4o2_complex_snr_1pi(a, b) else: var d {.noInit.}: doublePrec(typeof(r)) @@ -1403,7 +1403,7 @@ func prod2x_disjoint*[Fdbl, F]( func prod2x*(r: var QuadraticExt2x, a, b: QuadraticExt) = ## Double-precision multiplication r <- a*b when a.fromComplexExtension(): - when UseASM_X86_64 and not QuadraticExt.C.has_large_field_elem(): + when UseASM_X86_64 and not QuadraticExt.Name.has_large_field_elem(): if ({.noSideEffect.}: hasAdx()): r.coords.mul2x_fp2_complex_asm_adx(a.coords, b.coords) else: @@ -1639,7 +1639,7 @@ func square_Chung_Hasan_SQR3(r: var CubicExt, a: CubicExt) = # Multiplications (specializations) # ------------------------------------------------------------------- -func prodImpl_fp6o2_complex_snr_1pi[C: static Curve](r: var Fp6[C], a, b: Fp6[C]) = +func prodImpl_fp6o2_complex_snr_1pi[Name: static Algebra](r: var Fp6[Name], a, b: Fp6[Name]) = ## Returns r = a * b ## For 𝔽p4/𝔽p2 with the following non-residue (NR) constraints: ## * -1 is a quadratic non-residue in 𝔽p hence 𝔽p2 has coordinates a+𝑖b with i = √-1. This implies p ≡ 3 (mod 4) @@ -1649,15 +1649,15 @@ func prodImpl_fp6o2_complex_snr_1pi[C: static Curve](r: var Fp6[C], a, b: Fp6[C] ## About 2/3 of the p ≡ 3 (mod 8) primes are in this case # https://eprint.iacr.org/2022/367 - Equation 8 static: - doAssert C.getNonResidueFp() == -1 - doAssert C.getNonresidueFp2() == (1, 1) + doAssert Name.getNonResidueFp() == -1 + doAssert Name.getNonresidueFp2() == (1, 1) var - b10_p_b11{.noInit.}, b10_m_b11{.noInit.}: Fp[C] - b20_p_b21{.noInit.}, b20_m_b21{.noInit.}: Fp[C] + b10_p_b11{.noInit.}, b10_m_b11{.noInit.}: Fp[Name] + b20_p_b21{.noInit.}, b20_m_b21{.noInit.}: Fp[Name] - n_a01{.noInit.}, n_a11{.noInit.}, n_a21{.noInit.}: Fp[C] + n_a01{.noInit.}, n_a11{.noInit.}, n_a21{.noInit.}: Fp[Name] - t{.noInit.}: Fp6[C] + t{.noInit.}: Fp6[Name] b10_p_b11.sum(b.c1.c0, b.c1.c1) b10_m_b11.diff(b.c1.c0, b.c1.c1) @@ -2128,7 +2128,7 @@ func inv2xImpl(r: var CubicExt, a: CubicExt, useVartime: static bool = false) = func square*(r: var CubicExt, a: CubicExt) = ## Returns r = a² - when CubicExt.C.has_large_NR_norm() or CubicExt.C.has_large_field_elem(): + when CubicExt.Name.has_large_NR_norm() or CubicExt.Name.has_large_field_elem(): square_Chung_Hasan_SQR3(r, a) else: var d {.noInit.}: doublePrec(typeof(a)) @@ -2147,9 +2147,9 @@ func square2x*(r: var CubicExt2x, a: CubicExt) = func prod*(r: var CubicExt, a, b: CubicExt) = ## Out-of-place multiplication - when CubicExt.C.has_large_field_elem(): + when CubicExt.Name.has_large_field_elem(): r.prodImpl(a, b) - elif r is Fp6 and CubicExt.C.getNonResidueFp() == -1 and CubicExt.C.getNonResidueFp2() == (1, 1): + elif r is Fp6 and CubicExt.Name.getNonResidueFp() == -1 and CubicExt.Name.getNonResidueFp2() == (1, 1): r.prodImpl_fp6o2_complex_snr_1pi(a, b) else: var d {.noInit.}: doublePrec(typeof(r)) @@ -2173,7 +2173,7 @@ func inv*(r: var CubicExt, a: CubicExt) = ## Incidentally this avoids extra check ## to convert Jacobian and Projective coordinates ## to affine for elliptic curve - when CubicExt.C.has_large_field_elem() or r is Fp12: + when CubicExt.Name.has_large_field_elem() or r is Fp12: r.invImpl(a) else: r.inv2xImpl(a) @@ -2236,7 +2236,7 @@ func inv_vartime*(r: var CubicExt, a: CubicExt) {.tags:[VarTime].} = ## Incidentally this avoids extra check ## to convert Jacobian and Projective coordinates ## to affine for elliptic curve - when CubicExt.C.has_large_field_elem() or r is Fp12: + when CubicExt.Name.has_large_field_elem() or r is Fp12: r.invImpl(a, useVartime = true) else: r.inv2xImpl(a, useVartime = true) diff --git a/constantine/math/io/io_ec.nim b/constantine/math/io/io_ec.nim index 2e891818d..2b04ab10f 100644 --- a/constantine/math/io/io_ec.nim +++ b/constantine/math/io/io_ec.nim @@ -30,7 +30,7 @@ import # # ############################################################ -func toHex*[EC: ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_Aff or ECP_ShortW_JacExt](P: EC, indent: static int = 0): string = +func toHex*[EC: EC_ShortW_Prj or EC_ShortW_Jac or EC_ShortW_Aff or EC_ShortW_JacExt](P: EC, indent: static int = 0): string = ## Stringify an elliptic curve point to Hex ## Note. Leading zeros are not removed. ## Result is prefixed with 0x @@ -42,8 +42,8 @@ func toHex*[EC: ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_Aff or ECP_ShortW ## ## This proc output may change format in the future - var aff {.noInit.}: ECP_ShortW_Aff[EC.F, EC.G] - when EC isnot ECP_ShortW_Aff: + var aff {.noInit.}: EC_ShortW_Aff[EC.F, EC.G] + when EC isnot EC_ShortW_Aff: aff.affine(P) else: aff = P @@ -56,7 +56,7 @@ func toHex*[EC: ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_Aff or ECP_ShortW result.appendHex(aff.y) result &= "\n" & sp & ")" -func toHex*[EC: ECP_TwEdwards_Aff or ECP_TwEdwards_Prj](P: EC, indent: static int = 0): string = +func toHex*[EC: EC_TwEdw_Aff or EC_TwEdw_Prj](P: EC, indent: static int = 0): string = ## Stringify an elliptic curve point to Hex for Twisted Edwards Curve ## Note, leading zeros are not removed. ## Result is prefixed with 0x @@ -68,8 +68,8 @@ func toHex*[EC: ECP_TwEdwards_Aff or ECP_TwEdwards_Prj](P: EC, indent: static in ## ## This proc output may change format in the future - var aff {.noInit.}: ECP_TwEdwards_Aff[EC.F] - when EC isnot ECP_TwEdwards_Aff: + var aff {.noInit.}: EC_TwEdw_Aff[EC.F] + when EC isnot EC_TwEdw_Aff: aff.affine(P) else: aff = P @@ -82,7 +82,7 @@ func toHex*[EC: ECP_TwEdwards_Aff or ECP_TwEdwards_Prj](P: EC, indent: static in result.appendHex(aff.y) result &= "\n" & sp & ")" -func fromHex*(dst: var (ECP_ShortW_Prj or ECP_ShortW_Jac), x, y: string): bool = +func fromHex*(dst: var (EC_ShortW_Prj or EC_ShortW_Jac), x, y: string): bool = ## Convert hex strings to a G1 curve point ## Returns true if point exist or if input is the point at infinity (all 0) ## Returns `false` if there is no point with coordinates (`x`, `y`) on the curve @@ -95,7 +95,7 @@ func fromHex*(dst: var (ECP_ShortW_Prj or ECP_ShortW_Jac), x, y: string): bool = dst.z.csetZero(isNeutral) return bool(isOnCurve(dst.x, dst.y, dst.G) or isNeutral) -func fromHex*(dst: var (ECP_ShortW_Prj or ECP_ShortW_Jac), x0, x1, y0, y1: string): bool = +func fromHex*(dst: var (EC_ShortW_Prj or EC_ShortW_Jac), x0, x1, y0, y1: string): bool = ## Convert hex strings to a G2 curve point ## Returns `false` ## if there is no point with coordinates (`x`, `y`) on the curve @@ -108,7 +108,7 @@ func fromHex*(dst: var (ECP_ShortW_Prj or ECP_ShortW_Jac), x0, x1, y0, y1: strin dst.z.csetZero(isNeutral) return bool(isOnCurve(dst.x, dst.y, dst.G) or isNeutral) -func fromHex*(dst: var ECP_ShortW_Aff, x, y: string): bool = +func fromHex*(dst: var EC_ShortW_Aff, x, y: string): bool = ## Convert hex strings to a G1 curve point ## Returns true if point exist or if input is the point at infinity (all 0) ## Returns `false` if there is no point with coordinates (`x`, `y`) on the curve @@ -118,7 +118,7 @@ func fromHex*(dst: var ECP_ShortW_Aff, x, y: string): bool = dst.y.fromHex(y) return bool(isOnCurve(dst.x, dst.y, dst.G) or dst.isNeutral()) -func fromHex*(dst: var ECP_ShortW_Aff, x0, x1, y0, y1: string): bool = +func fromHex*(dst: var EC_ShortW_Aff, x0, x1, y0, y1: string): bool = ## Convert hex strings to a G2 curve point ## Returns true if point exist or if input is the point at infinity (all 0) ## Returns `false` if there is no point with coordinates (`x`, `y`) on the curve @@ -128,15 +128,15 @@ func fromHex*(dst: var ECP_ShortW_Aff, x0, x1, y0, y1: string): bool = dst.y.fromHex(y0, y1) return bool(isOnCurve(dst.x, dst.y, dst.G) or dst.isNeutral()) -func fromHex*[EC: ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_Aff]( +func fromHex*[EC: EC_ShortW_Prj or EC_ShortW_Jac or EC_ShortW_Aff]( _: type EC, x, y: string): EC = doAssert result.fromHex(x, y) -func fromHex*[EC: ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_Aff]( +func fromHex*[EC: EC_ShortW_Prj or EC_ShortW_Jac or EC_ShortW_Aff]( _: type EC, x0, x1, y0, y1: string): EC = doAssert result.fromHex(x0, x1, y0, y1) -func fromHex*(dst: var ECP_TwEdwards_Prj, x, y: string): bool = +func fromHex*(dst: var EC_TwEdw_Prj, x, y: string): bool = ## Convert hex strings to a curve point ## Returns true if point exist or if input is the point at infinity (all 0) ## Returns `false` if there is no point with coordinates (`x`, `y`) on the curve @@ -149,7 +149,7 @@ func fromHex*(dst: var ECP_TwEdwards_Prj, x, y: string): bool = dst.z.csetZero(isNeutral) return bool(isOnCurve(dst.x, dst.y) or isNeutral) -func fromHex*(dst: var ECP_TwEdwards_Aff, x, y: string): bool = +func fromHex*(dst: var EC_TwEdw_Aff, x, y: string): bool = ## Convert hex strings to a curve point ## Returns true if point exist or if input is the point at infinity (all 0) ## Returns `false` if there is no point with coordinates (`x`, `y`) on the curve @@ -159,6 +159,6 @@ func fromHex*(dst: var ECP_TwEdwards_Aff, x, y: string): bool = dst.y.fromHex(y) return bool(isOnCurve(dst.x, dst.y) or dst.isNeutral()) -func fromHex*[EC: ECP_TwEdwards_Aff or ECP_TwEdwards_Prj]( +func fromHex*[EC: EC_TwEdw_Aff or EC_TwEdw_Prj]( _: type EC, x, y: string): EC = doAssert result.fromHex(x, y) diff --git a/constantine/math/isogenies/frobenius.nim b/constantine/math/isogenies/frobenius.nim index 7e71717bd..6ae45e864 100644 --- a/constantine/math/isogenies/frobenius.nim +++ b/constantine/math/isogenies/frobenius.nim @@ -53,30 +53,30 @@ func frobenius_map*(r: var Fp2, a: Fp2, k: static int = 1) {.inline.} = # Frobenius map - on extension fields # ----------------------------------------------------------------- -func frobenius_map*[C](r: var Fp4[C], a: Fp4[C], k: static int = 1) {.inline.} = +func frobenius_map*[Name](r: var Fp4[Name], a: Fp4[Name], k: static int = 1) {.inline.} = ## Computes a^(pᵏ) ## The p-power frobenius automorphism on 𝔽p4 r.c0.frobenius_map(a.c0, k) r.c1.frobenius_map(a.c1, k) - r.c1.mulCheckSparse frobMapConst(C, 3, k) + r.c1.mulCheckSparse frobMapConst(Name, 3, k) -func frobenius_map*[C](r: var Fp6[C], a: Fp6[C], k: static int = 1) {.inline.} = +func frobenius_map*[Name](r: var Fp6[Name], a: Fp6[Name], k: static int = 1) {.inline.} = ## Computes a^(pᵏ) ## The p-power frobenius automorphism on 𝔽p6 r.c0.frobenius_map(a.c0, k) r.c1.frobenius_map(a.c1, k) r.c2.frobenius_map(a.c2, k) - when C.getEmbeddingDegree == 12: - r.c1.mulCheckSparse frobMapConst(C, 2, k) - r.c2.mulCheckSparse frobMapConst(C, 4, k) - elif C.getEmbeddingDegree == 6: - r.c1.mulCheckSparse frobMapConst(C, 1, k) - r.c2.mulCheckSparse frobMapConst(C, 2, k) + when Name.getEmbeddingDegree() == 12: + r.c1.mulCheckSparse frobMapConst(Name, 2, k) + r.c2.mulCheckSparse frobMapConst(Name, 4, k) + elif Name.getEmbeddingDegree() == 6: + r.c1.mulCheckSparse frobMapConst(Name, 1, k) + r.c2.mulCheckSparse frobMapConst(Name, 2, k) else: {.error: "Not Implemented".} -func frobenius_map*[C](r: var Fp12[C], a: Fp12[C], k: static int = 1) {.inline.} = +func frobenius_map*[Name](r: var Fp12[Name], a: Fp12[Name], k: static int = 1) {.inline.} = ## Computes a^(pᵏ) ## The p-power frobenius automorphism on 𝔽p12 staticFor i, 0, r.coords.len: @@ -84,19 +84,19 @@ func frobenius_map*[C](r: var Fp12[C], a: Fp12[C], k: static int = 1) {.inline.} r.coords[i].coords[j].frobenius_map(a.coords[i].coords[j], k) when r.c0 is Fp4: - r.c0.c0.mulCheckSparse frobMapConst(C, 0, k) - r.c0.c1.mulCheckSparse frobMapConst(C, 3, k) - r.c1.c0.mulCheckSparse frobMapConst(C, 1, k) - r.c1.c1.mulCheckSparse frobMapConst(C, 4, k) - r.c2.c0.mulCheckSparse frobMapConst(C, 2, k) - r.c2.c1.mulCheckSparse frobMapConst(C, 5, k) + r.c0.c0.mulCheckSparse frobMapConst(Name, 0, k) + r.c0.c1.mulCheckSparse frobMapConst(Name, 3, k) + r.c1.c0.mulCheckSparse frobMapConst(Name, 1, k) + r.c1.c1.mulCheckSparse frobMapConst(Name, 4, k) + r.c2.c0.mulCheckSparse frobMapConst(Name, 2, k) + r.c2.c1.mulCheckSparse frobMapConst(Name, 5, k) else: - r.c0.c0.mulCheckSparse frobMapConst(C, 0, k) - r.c0.c1.mulCheckSparse frobMapConst(C, 2, k) - r.c0.c2.mulCheckSparse frobMapConst(C, 4, k) - r.c1.c0.mulCheckSparse frobMapConst(C, 1, k) - r.c1.c1.mulCheckSparse frobMapConst(C, 3, k) - r.c1.c2.mulCheckSparse frobMapConst(C, 5, k) + r.c0.c0.mulCheckSparse frobMapConst(Name, 0, k) + r.c0.c1.mulCheckSparse frobMapConst(Name, 2, k) + r.c0.c2.mulCheckSparse frobMapConst(Name, 4, k) + r.c1.c0.mulCheckSparse frobMapConst(Name, 1, k) + r.c1.c1.mulCheckSparse frobMapConst(Name, 3, k) + r.c1.c2.mulCheckSparse frobMapConst(Name, 5, k) # ψ (Psi) - Untwist-Frobenius-Twist Endomorphisms on twisted curves # ----------------------------------------------------------------- @@ -112,5 +112,5 @@ func frobenius_psi*[PointG2](r: var PointG2, P: PointG2, k: static int = 1) = for coordR, coordP in fields(r, P): coordR.frobenius_map(coordP, k) - r.x.mulCheckSparse frobPsiConst(PointG2.F.C, psipow=k, coefpow=2) - r.y.mulCheckSparse frobPsiConst(PointG2.F.C, psipow=k, coefpow=3) + r.x.mulCheckSparse frobPsiConst(PointG2.F.Name, psipow=k, coefpow=2) + r.y.mulCheckSparse frobPsiConst(PointG2.F.Name, psipow=k, coefpow=3) diff --git a/constantine/math/pairings/cyclotomic_subgroups.nim b/constantine/math/pairings/cyclotomic_subgroups.nim index 959fcee79..63d4514c4 100644 --- a/constantine/math/pairings/cyclotomic_subgroups.nim +++ b/constantine/math/pairings/cyclotomic_subgroups.nim @@ -35,7 +35,7 @@ import # 𝔽pⁿ -> Gϕₙ - Mapping to Cyclotomic group # ---------------------------------------------------------------- -func finalExpEasy*[C: static Curve](f: var Fp6[C]) {.meter.} = +func finalExpEasy*[Name: static Algebra](f: var Fp6[Name]) {.meter.} = ## Easy part of the final exponentiation ## ## This maps the result of the Miller loop into the cyclotomic subgroup Gϕ₆ @@ -115,7 +115,7 @@ func finalExpEasy*[C: static Curve](f: var Fp6[C]) {.meter.} = f.frobenius_map(g) # f = f^((p³-1) p) f *= g # f = f^((p³-1) (p+1)) -func finalExpEasy*[C: static Curve](f: var Fp12[C]) {.meter.} = +func finalExpEasy*[Name: static Algebra](f: var Fp12[Name]) {.meter.} = ## Easy part of the final exponentiation ## ## This maps the result of the Miller loop into the cyclotomic subgroup Gϕ₁₂ @@ -411,10 +411,10 @@ func cyclotomic_exp*[FT](r: var FT, a: FT, exponent: static BigInt, invert: bool if invert: r.cyclotomic_inv() -func isInCyclotomicSubgroup*[C](a: Fp6[C]): SecretBool = +func isInCyclotomicSubgroup*[Name](a: Fp6[Name]): SecretBool = ## Check if a ∈ Fpⁿ: a^Φₙ(p) = 1 ## Φ₆(p) = p²-p+1 - var t{.noInit.}, p{.noInit.}: Fp6[C] + var t{.noInit.}, p{.noInit.}: Fp6[Name] t.frobenius_map(a, 2) # a^(p²) t *= a # a^(p²+1) @@ -422,10 +422,10 @@ func isInCyclotomicSubgroup*[C](a: Fp6[C]): SecretBool = return t == p and not a.isZero() -func isInCyclotomicSubgroup*[C](a: Fp12[C]): SecretBool = +func isInCyclotomicSubgroup*[Name](a: Fp12[Name]): SecretBool = ## Check if a ∈ Fpⁿ: a^Φₙ(p) = 1 ## Φ₁₂(p) = p⁴-p²+1 - var t{.noInit.}, p2{.noInit.}: Fp12[C] + var t{.noInit.}, p2{.noInit.}: Fp12[Name] p2.frobenius_map(a, 2) # a^(p²) t.frobenius_map(p2, 2) # a^(p⁴) diff --git a/constantine/math/pairings/lines_eval.nim b/constantine/math/pairings/lines_eval.nim index fb5a86cb4..631c9bc97 100644 --- a/constantine/math/pairings/lines_eval.nim +++ b/constantine/math/pairings/lines_eval.nim @@ -127,11 +127,11 @@ func toHex*(line: Line): string = # Line evaluation # ----------------------------------------------------------------------- -func line_update[F1, F2](line: var Line[F2], P: ECP_ShortW_Aff[F1, G1]) = +func line_update[F1, F2](line: var Line[F2], P: EC_ShortW_Aff[F1, G1]) = ## Update the line evaluation with P ## after addition or doubling ## P in G1 - static: doAssert F1.C == F2.C + static: doAssert F1.Name == F2.Name # D-Twist: line at P(xₚ, yₚ): # a.yₚ + b.xₚ w + c w³ # @@ -230,7 +230,7 @@ func line_update[F1, F2](line: var Line[F2], P: ECP_ShortW_Aff[F1, G1]) = func line_eval_fused_double[Field]( line: var Line[Field], - T: var ECP_ShortW_Prj[Field, G2]) = + T: var EC_ShortW_Prj[Field, G2]) = ## Fused line evaluation and elliptic point doubling # Grewal et al, 2012 adapted to Scott 2019 line notation @@ -247,13 +247,13 @@ func line_eval_fused_double[Field]( C.square(T.z) # C = Z² # E = 3b'Z² = 3bξ Z² (M-Twist) or 3b/ξ Z² (D-Twist) - when Field.C.getSexticTwist() == M_Twist and E.fromComplexExtension(): - const b3 = 3*Field.C.getCoefB() + when Field.Name.getSexticTwist() == M_Twist and E.fromComplexExtension(): + const b3 = 3*Field.Name.getCoefB() E.prod(C, b3) E *= SexticNonResidue else: E = C - E.mulCheckSparse(Field.C.getCoefB_G2_times_3()) + E.mulCheckSparse(Field.Name.getCoefB_G2_times_3()) F.prod(E, 3) # F = 3E = 9b'Z² G.sum(B, F) @@ -280,8 +280,8 @@ func line_eval_fused_double[Field]( func line_eval_fused_add[Field]( line: var Line[Field], - T: var ECP_ShortW_Prj[Field, G2], - Q: ECP_ShortW_Aff[Field, G2]) = + T: var EC_ShortW_Prj[Field, G2], + Q: EC_ShortW_Aff[Field, G2]) = ## Fused line evaluation and elliptic point addition # Grewal et al, 2012 adapted to Scott 2019 line notation var @@ -334,26 +334,26 @@ func line_eval_fused_add[Field]( func line_double*[F1, F2]( line: var Line[F2], - T: var ECP_ShortW_Prj[F2, G2], - P: ECP_ShortW_Aff[F1, G1]) {.meter.} = + T: var EC_ShortW_Prj[F2, G2], + P: EC_ShortW_Aff[F1, G1]) {.meter.} = ## Doubling step of the Miller loop ## T in G2, P in G1 ## ## Compute lt,t(P) - static: doAssert F1.C == F2.C + static: doAssert F1.Name == F2.Name line_eval_fused_double(line, T) line.line_update(P) func line_add*[F1, F2]( line: var Line[F2], - T: var ECP_ShortW_Prj[F2, G2], - Q: ECP_ShortW_Aff[F2, G2], - P: ECP_ShortW_Aff[F1, G1]) {.meter.} = + T: var EC_ShortW_Prj[F2, G2], + Q: EC_ShortW_Aff[F2, G2], + P: EC_ShortW_Aff[F1, G1]) {.meter.} = ## Addition step of the Miller loop ## T and Q in G2, P in G1 ## ## Compute lt,q(P) - static: doAssert F1.C == F2.C + static: doAssert F1.Name == F2.Name line_eval_fused_add(line, T, Q) line.line_update(P) @@ -405,13 +405,13 @@ func mul_sparse_by_line_a00bc0*[Fpk, Fpkdiv6](f: var Fpk, l: Line[Fpkdiv6]) = # = (a0 + a1) (b0 + b1) - a0 b0 - a1 b1 (Karatsuba) static: - doAssert Fpk.C.getSexticTwist() == D_Twist + doAssert Fpk.Name.getSexticTwist() == D_Twist doAssert f is QuadraticExt, "This assumes 𝔽pᵏ as a quadratic extension of 𝔽pᵏᐟ²" doAssert f.c0 is CubicExt, "This assumes 𝔽pᵏᐟ² as a cubic extension of 𝔽pᵏᐟ⁶" type Fpkdiv2 = typeof(f.c0) - when Fpk.C.has_large_field_elem(): + when Fpk.Name.has_large_field_elem(): var v0 {.noInit.}: Fpkdiv2 v1 {.noInit.}: Fpkdiv2 @@ -492,7 +492,7 @@ func prod_x00yz0_x00yz0_into_abcdefghij00*[Fpk, Fpkdiv6](f: var Fpk, l0, l1: Lin # Now we can apply Karasuba¹² for a total of 6 multiplications static: - doAssert Fpk.C.getSexticTwist() == D_Twist + doAssert Fpk.Name.getSexticTwist() == D_Twist doAssert f is QuadraticExt, "This assumes 𝔽pᵏ as a quadratic extension of 𝔽pᵏᐟ²" doAssert f.c0 is CubicExt, "This assumes 𝔽pᵏᐟ² as a cubic extension of 𝔽pᵏᐟ⁶" @@ -560,13 +560,13 @@ func mul_sparse_by_line_cb00a0*[Fpk, Fpkdiv6](f: var Fpk, l: Line[Fpkdiv6]) = # = (a0 + a1) (b0 + b1) - a0 b0 - a1 b1 (Karatsuba) static: - doAssert Fpk.C.getSexticTwist() == M_Twist + doAssert Fpk.Name.getSexticTwist() == M_Twist doAssert f is QuadraticExt, "This assumes 𝔽pᵏ as a quadratic extension of 𝔽pᵏᐟ²" doAssert f.c0 is CubicExt, "This assumes 𝔽pᵏᐟ² as a cubic extension of 𝔽pᵏᐟ⁶" type Fpkdiv2 = typeof(f.c0) - when Fpk.C.has_large_field_elem(): + when Fpk.Name.has_large_field_elem(): var v0 {.noInit.}: Fpkdiv2 v1 {.noInit.}: Fpkdiv2 @@ -646,7 +646,7 @@ func prod_zy00x0_zy00x0_into_abcdef00ghij*[Fpk, Fpkdiv6](f: var Fpk, l0, l1: Lin # Now we can apply Karasuba¹² for a total of 6 multiplications static: - doAssert Fpk.C.getSexticTwist() == M_Twist + doAssert Fpk.Name.getSexticTwist() == M_Twist doAssert f is QuadraticExt, "This assumes 𝔽pᵏ as a quadratic extension of 𝔽pᵏᐟ²" doAssert f.c0 is CubicExt, "This assumes 𝔽pᵏᐟ² as a cubic extension of 𝔽pᵏᐟ⁶" @@ -713,7 +713,7 @@ func mul_sparse_by_line_acb000*[Fpk, Fpkdiv6](f: var Fpk, l: Line[Fpkdiv6]) = ## with coordinate (a,b,c) matching 𝔽pᵏ coordinates acb000 static: - doAssert Fpk.C.getSexticTwist() == D_Twist + doAssert Fpk.Name.getSexticTwist() == D_Twist doAssert f is CubicExt, "This assumes 𝔽pᵏ as a cubic extension of 𝔽pᵏᐟ³" doAssert f.c0 is QuadraticExt, "This assumes 𝔽pᵏᐟ³ as a quadratic extension of 𝔽pᵏᐟ⁶" @@ -738,7 +738,7 @@ func mul_sparse_by_line_acb000*[Fpk, Fpkdiv6](f: var Fpk, l: Line[Fpkdiv6]) = # = a0 b0 + a2 b0 - v0 + v1 # = a2 b0 + v1 - when Fpk.C.has_large_field_elem(): + when Fpk.Name.has_large_field_elem(): var b0 {.noInit.}, v0{.noInit.}, v1{.noInit.}, t{.noInit.}: Fpkdiv3 b0.c0 = l.a @@ -825,7 +825,7 @@ func prod_xzy000_xzy000_into_abcdefghij00*[Fpk, Fpkdiv6](f: var Fpk, l0, l1: Lin # hence r1 can be compute for 2 extra muls in 𝔽pᵏᐟ⁶ only static: - doAssert Fpk.C.getSexticTwist() == D_Twist + doAssert Fpk.Name.getSexticTwist() == D_Twist doAssert f is CubicExt, "This assumes 𝔽pᵏ as a cubic extension of 𝔽pᵏᐟ³" doAssert f.c0 is QuadraticExt, "This assumes 𝔽pᵏᐟ³ as a quadratic extension of 𝔽pᵏᐟ⁶" @@ -883,7 +883,7 @@ func mul_sparse_by_line_ca00b0*[Fpk, Fpkdiv6](f: var Fpk, l: Line[Fpkdiv6]) = ## with coordinate (a,b,c) matching 𝔽pᵏ coordinates ca00b0 static: - doAssert Fpk.C.getSexticTwist() == M_Twist + doAssert Fpk.Name.getSexticTwist() == M_Twist doAssert f is CubicExt, "This assumes 𝔽pᵏ as a cubic extension of 𝔽pᵏᐟ³" doAssert f.c0 is QuadraticExt, "This assumes 𝔽pᵏᐟ³ as a cubic extension of 𝔽pᵏᐟ⁶" @@ -908,7 +908,7 @@ func mul_sparse_by_line_ca00b0*[Fpk, Fpkdiv6](f: var Fpk, l: Line[Fpkdiv6]) = # r2 = (a0 + a2) * (b0 + b2) - v0 - v2 + v1 # = (a0 + a2) * (b0 + b2) - v0 - v2 - when Fpk.C.has_large_field_elem(): + when Fpk.Name.has_large_field_elem(): var b0 {.noInit.}, v0{.noInit.}, v2{.noInit.}, t{.noInit.}: Fpkdiv3 b0.c0 = l.c @@ -997,7 +997,7 @@ func prod_zx00y0_zx00y0_into_abcd00efghij*[Fpk, Fpkdiv6](f: var Fpk, l0, l1: Lin # hence r2 can be compute for 2 extra muls in 𝔽pᵏᐟ⁶ only static: - doAssert Fpk.C.getSexticTwist() == M_Twist + doAssert Fpk.Name.getSexticTwist() == M_Twist doAssert f is CubicExt, "This assumes 𝔽pᵏ as a cubic extension of 𝔽pᵏᐟ³" doAssert f.c0 is QuadraticExt, "This assumes 𝔽pᵏᐟ³ as a quadratic extension of 𝔽pᵏᐟ⁶" @@ -1057,7 +1057,7 @@ func mul_sparse_by_abcdefghij00_quad_over_cube*[Fpk]( ## with each representing 𝔽pᵏᐟ⁶ coordinate static: - doAssert Fpk.C.getSexticTwist() == D_Twist + doAssert Fpk.Name.getSexticTwist() == D_Twist doAssert a is QuadraticExt, "This assumes 𝔽pᵏ as a quadratic extension of 𝔽pᵏᐟ²" doAssert a.c0 is CubicExt, "This assumes 𝔽pᵏᐟ² as a cubic extension of 𝔽pᵏᐟ⁶" @@ -1073,7 +1073,7 @@ func mul_sparse_by_abcdefghij00_quad_over_cube*[Fpk]( # r0 = a0 b0 + ξ a1 b1 # r1 = (a0 + a1) (b0 + b1) - a0 b0 - a1 b1 - when Fpk.C.has_large_field_elem(): + when Fpk.Name.has_large_field_elem(): var v0 {.noInit.}, v1 {.noInit.}, v2 {.noInit.}: Fpkdiv2 # v2 <- (a0 + a1)(b0 + b1) @@ -1131,7 +1131,7 @@ func mul_sparse_by_abcdef00ghij_quad_over_cube*[Fpk]( ## with each representing 𝔽pᵏᐟ⁶ coordinate static: - doAssert Fpk.C.getSexticTwist() == M_Twist + doAssert Fpk.Name.getSexticTwist() == M_Twist doAssert a is QuadraticExt, "This assumes 𝔽pᵏ as a quadratic extension of 𝔽pᵏᐟ²" doAssert a.c0 is CubicExt, "This assumes 𝔽pᵏᐟ² as a cubic extension of 𝔽pᵏᐟ⁶" @@ -1147,7 +1147,7 @@ func mul_sparse_by_abcdef00ghij_quad_over_cube*[Fpk]( # r0 = a0 b0 + ξ a1 b1 # r1 = (a0 + a1) (b0 + b1) - a0 b0 - a1 b1 - when Fpk.C.has_large_field_elem(): + when Fpk.Name.has_large_field_elem(): var v0 {.noInit.}, v1 {.noInit.}, v2 {.noInit.}: Fpkdiv2 # v2 <- (a0 + a1)(b0 + b1) @@ -1206,7 +1206,7 @@ func mul_sparse_by_abcd00efghij_cube_over_quad*[Fpk]( ## with each representing 𝔽pᵏᐟ⁶ coordinate static: - doAssert Fpk.C.getSexticTwist() == M_Twist + doAssert Fpk.Name.getSexticTwist() == M_Twist doAssert a is CubicExt, "This assumes 𝔽pᵏ as a cubic extension of 𝔽pᵏᐟ³" doAssert a.c0 is QuadraticExt, "This assumes 𝔽pᵏᐟ³ as a quadratic extension of 𝔽pᵏᐟ⁶" @@ -1277,7 +1277,7 @@ func mul_sparse_by_abcdefghij00_cube_over_quad*[Fpk]( ## with each representing 𝔽pᵏᐟ⁶ coordinate static: - doAssert Fpk.C.getSexticTwist() == D_Twist + doAssert Fpk.Name.getSexticTwist() == D_Twist doAssert a is CubicExt, "This assumes 𝔽pᵏ as a cubic extension of 𝔽pᵏᐟ³" doAssert a.c0 is QuadraticExt, "This assumes 𝔽pᵏᐟ³ as a quadratic extension of 𝔽pᵏᐟ⁶" @@ -1346,12 +1346,12 @@ func mul_sparse_by_abcdefghij00_cube_over_quad*[Fpk]( func mul_by_line*[Fpk, Fpkdiv6](f: var Fpk, line: Line[Fpkdiv6]) {.inline, meter.} = ## Multiply an element of Fp12 by a sparse line function - when Fpk.C.getSexticTwist() == D_Twist: + when Fpk.Name.getSexticTwist() == D_Twist: when f is CubicExt: f.mul_sparse_by_line_acb000(line) else: f.mul_sparse_by_line_a00bc0(line) - elif Fpk.C.getSexticTwist() == M_Twist: + elif Fpk.Name.getSexticTwist() == M_Twist: when f is CubicExt: f.mul_sparse_by_line_ca00b0(line) else: @@ -1363,12 +1363,12 @@ func prod_from_2_lines*[Fpk, Fpkdiv6](f: var Fpk, line0, line1: Line[Fpkdiv6]) { ## Multiply 2 lines function ## and store the result in f ## f is overwritten - when Fpk.C.getSexticTwist() == D_Twist: + when Fpk.Name.getSexticTwist() == D_Twist: when f is CubicExt: f.prod_xzy000_xzy000_into_abcdefghij00(line0, line1) else: f.prod_x00yz0_x00yz0_into_abcdefghij00(line0, line1) - elif Fpk.C.getSexticTwist() == M_Twist: + elif Fpk.Name.getSexticTwist() == M_Twist: when f is CubicExt: f.prod_zx00y0_zx00y0_into_abcd00efghij(line0, line1) else: @@ -1378,12 +1378,12 @@ func prod_from_2_lines*[Fpk, Fpkdiv6](f: var Fpk, line0, line1: Line[Fpkdiv6]) { func mul_by_prod_of_2_lines*[Fpk](f: var Fpk, g: Fpk) {.inline, meter.} = ## Multiply f by the somewhat sparse product of 2 lines - when Fpk.C.getSexticTwist() == D_Twist: + when Fpk.Name.getSexticTwist() == D_Twist: when f is CubicExt: f.mul_sparse_by_abcdefghij00_cube_over_quad(g) else: f.mul_sparse_by_abcdefghij00_quad_over_cube(g) - elif Fpk.C.getSexticTwist() == M_Twist: + elif Fpk.Name.getSexticTwist() == M_Twist: when f is CubicExt: f.mul_sparse_by_abcd00efghij_cube_over_quad(g) else: diff --git a/constantine/math/pairings/miller_accumulators.nim b/constantine/math/pairings/miller_accumulators.nim index f82079c61..b86538f11 100644 --- a/constantine/math/pairings/miller_accumulators.nim +++ b/constantine/math/pairings/miller_accumulators.nim @@ -28,7 +28,7 @@ import # See ./multi-pairing.md for 2 approaches to a miller loop accumulator: # # - Software Implementation, Algorithm 11.2 & 11.3 -# Aranha, Dominguez Perez, A. Mrabet, Schwabe, +# Aranha, Dominguez Perez, Mrabet, Schwabe, # Guide to Pairing-Based Cryptography, 2015 # # - Pairing Implementation Revisited @@ -63,8 +63,8 @@ const MillerAccumMax = 8 type MillerAccumulator*[FF1, FF2; FpK: ExtensionField] = object accum: FpK - Ps: array[MillerAccumMax, ECP_ShortW_Aff[FF1, G1]] - Qs: array[MillerAccumMax, ECP_ShortW_Aff[FF2, G2]] + Ps: array[MillerAccumMax, EC_ShortW_Aff[FF1, G1]] + Qs: array[MillerAccumMax, EC_ShortW_Aff[FF2, G2]] len: uint32 accOnce: bool @@ -85,7 +85,7 @@ func consumeBuffers[FF1, FF2, FpK](ctx: var MillerAccumulator[FF1, FF2, FpK]) = ctx.accOnce = true ctx.len = 0 -func update*[FF1, FF2, FpK](ctx: var MillerAccumulator[FF1, FF2, FpK], P: ECP_ShortW_Aff[FF1, G1], Q: ECP_ShortW_Aff[FF2, G2]): bool = +func update*[FF1, FF2, FpK](ctx: var MillerAccumulator[FF1, FF2, FpK], P: EC_ShortW_Aff[FF1, G1], Q: EC_ShortW_Aff[FF2, G2]): bool = ## Aggregate another set for pairing ## This returns `false` if P or Q are the infinity point ## diff --git a/constantine/math/pairings/miller_loops.nim b/constantine/math/pairings/miller_loops.nim index e3fd084f7..0d31362fa 100644 --- a/constantine/math/pairings/miller_loops.nim +++ b/constantine/math/pairings/miller_loops.nim @@ -41,9 +41,9 @@ func recodeNafForPairing(ate: BigInt): seq[int8] {.compileTime.} = func basicMillerLoop*[FT, F1, F2]( f: var FT, - T: var ECP_ShortW_Prj[F2, G2], - P: ECP_ShortW_Aff[F1, G1], - Q: ECP_ShortW_Aff[F2, G2], + T: var EC_ShortW_Prj[F2, G2], + P: EC_ShortW_Aff[F1, G1], + Q: EC_ShortW_Aff[F2, G2], ate_param: static BigInt) {.meter.} = ## Basic Miller loop iterations ## @@ -54,12 +54,12 @@ func basicMillerLoop*[FT, F1, F2]( ## in the general case. ## If further processing is required, `ate_param_isNeg` must be taken into account by the caller. static: - doAssert FT.C == F1.C - doAssert FT.C == F2.C + doAssert FT.Name == F1.Name + doAssert FT.Name == F2.Name const naf = ate_param.recodeNafForPairing() var line0 {.noInit.}, line1 {.noInit.}: Line[F2] - var nQ {.noInit.}: ECP_ShortW_Aff[F2, G2] + var nQ {.noInit.}: EC_ShortW_Aff[F2, G2] f.setOne() nQ.neg(Q) @@ -91,16 +91,16 @@ func basicMillerLoop*[FT, F1, F2]( func millerCorrectionBN*[FT, F1, F2]( f: var FT, - T: var ECP_ShortW_Prj[F2, G2], - Q: ECP_ShortW_Aff[F2, G2], - P: ECP_ShortW_Aff[F1, G1]) {.meter.} = + T: var EC_ShortW_Prj[F2, G2], + Q: EC_ShortW_Aff[F2, G2], + P: EC_ShortW_Aff[F1, G1]) {.meter.} = ## Ate pairing for BN curves need adjustment after basic Miller loop ## If `ate_param_isNeg` f must be cyclotomic inverted/conjugated ## and T must be negated by the caller. static: - doAssert FT.C == F1.C - doAssert FT.C == F2.C - doAssert FT.C.family() == BarretoNaehrig + doAssert FT.Name == F1.Name + doAssert FT.Name == F2.Name + doAssert FT.Name.family() == BarretoNaehrig var V {.noInit.}: typeof(Q) var line1 {.noInit.}, line2 {.noInit.}: Line[F2] @@ -121,7 +121,7 @@ func millerCorrectionBN*[FT, F1, F2]( # ############################################################ # # - Software Implementation, Algorithm 11.2 & 11.3 -# Aranha, Dominguez Perez, A. Mrabet, Schwabe, +# Aranha, Dominguez Perez, Mrabet, Schwabe, # Guide to Pairing-Based Cryptography, 2015 # # - Physical Attacks, @@ -144,9 +144,9 @@ func millerCorrectionBN*[FT, F1, F2]( func miller_init_double_then_add*[FT, F1, F2]( f: var FT, - T: var ECP_ShortW_Prj[F2, G2], - Q: ECP_ShortW_Aff[F2, G2], - P: ECP_ShortW_Aff[F1, G1], + T: var EC_ShortW_Prj[F2, G2], + Q: EC_ShortW_Aff[F2, G2], + P: EC_ShortW_Aff[F1, G1], numDoublings: static int) {.meter.} = ## Start a Miller Loop with ## - `numDoubling` doublings @@ -183,9 +183,9 @@ func miller_init_double_then_add*[FT, F1, F2]( func miller_accum_double_then_add*[FT, F1, F2]( f: var FT, - T: var ECP_ShortW_Prj[F2, G2], - Q: ECP_ShortW_Aff[F2, G2], - P: ECP_ShortW_Aff[F1, G1], + T: var EC_ShortW_Prj[F2, G2], + Q: EC_ShortW_Aff[F2, G2], + P: EC_ShortW_Aff[F1, G1], numDoublings: int, add = true) {.meter.} = ## Continue a Miller Loop with ## - `numDoubling` doublings @@ -223,8 +223,8 @@ func double_jToN[FT, F1, F2]( f: var FT, j: static int, lineOddRemainder: var Line[F2], - Ts: ptr UncheckedArray[ECP_ShortW_Prj[F2, G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[F1, G1]], + Ts: ptr UncheckedArray[EC_ShortW_Prj[F2, G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[F1, G1]], N: int) = ## Doubling steps for pairings j to N ## if N is odd, lineOddRemainder must be applied to `f` @@ -243,9 +243,9 @@ func add_jToN[FT, F1, F2]( f: var FT, j: static int, lineOddRemainder: var Line[F2], - Ts: ptr UncheckedArray[ECP_ShortW_Prj[F2, G2]], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[F2, G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[F1, G1]], + Ts: ptr UncheckedArray[EC_ShortW_Prj[F2, G2]], + Qs: ptr UncheckedArray[EC_ShortW_Aff[F2, G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[F1, G1]], N: int)= ## Addition steps for pairings 0 to N @@ -263,13 +263,13 @@ func add_jToN_negateQ[FT, F1, F2]( f: var FT, j: static int, lineOddRemainder: var Line[F2], - Ts: ptr UncheckedArray[ECP_ShortW_Prj[F2, G2]], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[F2, G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[F1, G1]], + Ts: ptr UncheckedArray[EC_ShortW_Prj[F2, G2]], + Qs: ptr UncheckedArray[EC_ShortW_Aff[F2, G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[F1, G1]], N: int)= ## Addition steps for pairings 0 to N - var nQ{.noInit.}: ECP_ShortW_Aff[F2, G2] + var nQ{.noInit.}: EC_ShortW_Aff[F2, G2] var line0{.noInit.}, line1{.noInit.}: Line[F2] # Sparse merge 2 by 2, starting from 0 for i in countup(j, N-2, 2): @@ -285,9 +285,9 @@ func add_jToN_negateQ[FT, F1, F2]( func basicMillerLoop*[FT, F1, F2]( f: var FT, - Ts: ptr UncheckedArray[ECP_ShortW_Prj[F2, G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[F1, G1]], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[F2, G2]], + Ts: ptr UncheckedArray[EC_ShortW_Prj[F2, G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[F1, G1]], + Qs: ptr UncheckedArray[EC_ShortW_Aff[F2, G2]], N: int, ate_param: static Bigint) {.meter.} = ## Basic Miller loop iterations @@ -322,9 +322,9 @@ func basicMillerLoop*[FT, F1, F2]( func miller_init_double_then_add*[FT, F1, F2]( f: var FT, - Ts: ptr UncheckedArray[ECP_ShortW_Prj[F2, G2]], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[F2, G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[F1, G1]], + Ts: ptr UncheckedArray[EC_ShortW_Prj[F2, G2]], + Qs: ptr UncheckedArray[EC_ShortW_Aff[F2, G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[F1, G1]], N: int, numDoublings: static int) = ## Start a Miller Loop @@ -363,9 +363,9 @@ func miller_init_double_then_add*[FT, F1, F2]( func miller_accum_double_then_add*[FT, F1, F2]( f: var FT, - Ts: ptr UncheckedArray[ECP_ShortW_Prj[F2, G2]], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[F2, G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[F1, G1]], + Ts: ptr UncheckedArray[EC_ShortW_Prj[F2, G2]], + Qs: ptr UncheckedArray[EC_ShortW_Aff[F2, G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[F1, G1]], N: int, numDoublings: int, add = true) {.meter.} = ## Continue a Miller Loop with diff --git a/constantine/math/pairings/pairings_bls12.nim b/constantine/math/pairings/pairings_bls12.nim index b0a4d9fda..f831e7f1a 100644 --- a/constantine/math/pairings/pairings_bls12.nim +++ b/constantine/math/pairings/pairings_bls12.nim @@ -51,41 +51,41 @@ export zoo_pairings # generic sandwich https://github.com/nim-lang/Nim/issues/11 # Generic pairing implementation # ---------------------------------------------------------------- -func millerLoopGenericBLS12*[C]( - f: var Fp12[C], - Q: ECP_ShortW_Aff[Fp2[C], G2], - P: ECP_ShortW_Aff[Fp[C], G1] +func millerLoopGenericBLS12*[Name]( + f: var Fp12[Name], + Q: EC_ShortW_Aff[Fp2[Name], G2], + P: EC_ShortW_Aff[Fp[Name], G1] ) {.meter.} = ## Generic Miller Loop for BLS12 curve ## Computes f{u,Q}(P) with u the BLS curve parameter - var T {.noInit.}: ECP_ShortW_Prj[Fp2[C], G2] + var T {.noInit.}: EC_ShortW_Prj[Fp2[Name], G2] T.fromAffine(Q) - basicMillerLoop(f, T, P, Q, pairing(C, ate_param)) + basicMillerLoop(f, T, P, Q, pairing(Name, ate_param)) -func millerLoopGenericBLS12*[C]( - f: var Fp12[C], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[Fp2[C], G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[Fp[C], G1]], +func millerLoopGenericBLS12*[Name]( + f: var Fp12[Name], + Qs: ptr UncheckedArray[EC_ShortW_Aff[Fp2[Name], G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[Fp[Name], G1]], N: int ) {.noinline, tags:[Alloca], meter.} = ## Generic Miller Loop for BLS12 curve ## Computes f{u,Q}(P) with u the BLS curve parameter - var Ts = allocStackArray(ECP_ShortW_Prj[Fp2[C], G2], N) + var Ts = allocStackArray(EC_ShortW_Prj[Fp2[Name], G2], N) for i in 0 ..< N: Ts[i].fromAffine(Qs[i]) - basicMillerLoop(f, Ts, Ps, Qs, N, pairing(C, ate_param)) + basicMillerLoop(f, Ts, Ps, Qs, N, pairing(Name, ate_param)) -func finalExpGeneric[C: static Curve](f: var Fp12[C]) = +func finalExpGeneric[Name: static Algebra](f: var Fp12[Name]) = ## A generic and slow implementation of final exponentiation ## for sanity checks purposes. - f.pow_vartime(C.pairing(finalexponent), window = 3) + f.pow_vartime(Name.pairing(finalexponent), window = 3) -func pairing_bls12_reference*[C]( - gt: var Fp12[C], - P: ECP_ShortW_Aff[Fp[C], G1], - Q: ECP_ShortW_Aff[Fp2[C], G2]) = +func pairing_bls12_reference*[Name]( + gt: var Fp12[Name], + P: EC_ShortW_Aff[Fp[Name], G1], + Q: EC_ShortW_Aff[Fp2[Name], G2]) = ## Compute the optimal Ate Pairing for BLS12 curves ## Input: P ∈ G1, Q ∈ G2 ## Output: e(P, Q) ∈ Gt @@ -97,7 +97,7 @@ func pairing_bls12_reference*[C]( # Optimized pairing implementation # ---------------------------------------------------------------- -func finalExpHard_BLS12*[C](f: var Fp12[C]) {.meter.} = +func finalExpHard_BLS12*[Name](f: var Fp12[Name]) {.meter.} = ## Hard part of the final exponentiation ## Specialized for BLS12 curves ## @@ -117,13 +117,13 @@ func finalExpHard_BLS12*[C](f: var Fp12[C]) {.meter.} = # - S₁₂ being cyclotomic squaring # - Fₙ being n Frobenius applications - var v0 {.noInit.}, v1 {.noInit.}, v2 {.noInit.}: Fp12[C] + var v0 {.noInit.}, v1 {.noInit.}, v2 {.noInit.}: Fp12[Name] # Save for f³ and (x−1)² v2.cyclotomic_square(f) # v2 = f² # (x−1)² - when C.pairing(ate_param).isEven().bool: + when Name.pairing(ate_param).isEven().bool: v0.cycl_exp_by_curve_param_div2(v2) # v0 = (f²)^(x/2) = f^x else: v0.cycl_exp_by_curve_param(f) @@ -152,10 +152,10 @@ func finalExpHard_BLS12*[C](f: var Fp12[C]) {.meter.} = # (x−1)².(x+p).(x²+p²−1) + 3 f *= v0 -func pairing_bls12*[C]( - gt: var Fp12[C], - P: ECP_ShortW_Aff[Fp[C], G1], - Q: ECP_ShortW_Aff[Fp2[C], G2]) {.meter.} = +func pairing_bls12*[Name]( + gt: var Fp12[Name], + P: EC_ShortW_Aff[Fp[Name], G1], + Q: EC_ShortW_Aff[Fp2[Name], G2]) {.meter.} = ## Compute the optimal Ate Pairing for BLS12 curves ## Input: P ∈ G1, Q ∈ G2 ## Output: e(P, Q) ∈ Gt @@ -163,10 +163,10 @@ func pairing_bls12*[C]( gt.finalExpEasy() gt.finalExpHard_BLS12() -func pairing_bls12*[N: static int, C]( - gt: var Fp12[C], - Ps: array[N, ECP_ShortW_Aff[Fp[C], G1]], - Qs: array[N, ECP_ShortW_Aff[Fp2[C], G2]]) {.meter.} = +func pairing_bls12*[N: static int, Name]( + gt: var Fp12[Name], + Ps: array[N, EC_ShortW_Aff[Fp[Name], G1]], + Qs: array[N, EC_ShortW_Aff[Fp2[Name], G2]]) {.meter.} = ## Compute the optimal Ate Pairing for BLS12 curves ## Input: an array of Ps ∈ G1 and Qs ∈ G2 ## Output: diff --git a/constantine/math/pairings/pairings_bn.nim b/constantine/math/pairings/pairings_bn.nim index 620210632..a732b4756 100644 --- a/constantine/math/pairings/pairings_bn.nim +++ b/constantine/math/pairings/pairings_bn.nim @@ -47,40 +47,40 @@ export zoo_pairings # generic sandwich https://github.com/nim-lang/Nim/issues/11 # Generic pairing implementation # ---------------------------------------------------------------- -func millerLoopGenericBN*[C]( - f: var Fp12[C], - Q: ECP_ShortW_Aff[Fp2[C], G2], - P: ECP_ShortW_Aff[Fp[C], G1], +func millerLoopGenericBN*[Name]( + f: var Fp12[Name], + Q: EC_ShortW_Aff[Fp2[Name], G2], + P: EC_ShortW_Aff[Fp[Name], G1], ) {.meter.} = ## Generic Miller Loop for BN curves ## Computes f{6u+2,Q}(P) with u the BN curve parameter - var T {.noInit.}: ECP_ShortW_Prj[Fp2[C], G2] + var T {.noInit.}: EC_ShortW_Prj[Fp2[Name], G2] T.fromAffine(Q) - basicMillerLoop(f, T, P, Q, pairing(C, ate_param)) + basicMillerLoop(f, T, P, Q, pairing(Name, ate_param)) - when pairing(C, ate_param_is_neg): + when pairing(Name, ate_param_is_neg): f.conj() T.neg() # Ate pairing for BN curves needs adjustment after basic Miller loop f.millerCorrectionBN(T, Q, P) -func millerLoopGenericBN*[C]( - f: var Fp12[C], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[Fp2[C], G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[Fp[C], G1]], +func millerLoopGenericBN*[Name]( + f: var Fp12[Name], + Qs: ptr UncheckedArray[EC_ShortW_Aff[Fp2[Name], G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[Fp[Name], G1]], N: int ) {.noinline, tags:[Alloca], meter.} = ## Generic Miller Loop for BN curves ## Computes f{6u+2,Q}(P) with u the BN curve parameter - var Ts = allocStackArray(ECP_ShortW_Prj[Fp2[C], G2], N) + var Ts = allocStackArray(EC_ShortW_Prj[Fp2[Name], G2], N) for i in 0 ..< N: Ts[i].fromAffine(Qs[i]) - basicMillerLoop(f, Ts, Ps, Qs, N, pairing(C, ate_param)) + basicMillerLoop(f, Ts, Ps, Qs, N, pairing(Name, ate_param)) - when pairing(C, ate_param_is_neg): + when pairing(Name, ate_param_is_neg): f.conj() for i in 0 ..< N: Ts[i].neg() @@ -89,15 +89,15 @@ func millerLoopGenericBN*[C]( for i in 0 ..< N: f.millerCorrectionBN(Ts[i], Qs[i], Ps[i]) -func finalExpGeneric[C: static Curve](f: var Fp12[C]) = +func finalExpGeneric[Name: static Algebra](f: var Fp12[Name]) = ## A generic and slow implementation of final exponentiation ## for sanity checks purposes. - f.pow_vartime(C.pairing(finalexponent), window = 3) + f.pow_vartime(Name.pairing(finalexponent), window = 3) -func pairing_bn_reference*[C]( - gt: var Fp12[C], - P: ECP_ShortW_Aff[Fp[C], G1], - Q: ECP_ShortW_Aff[Fp2[C], G2]) = +func pairing_bn_reference*[Name]( + gt: var Fp12[Name], + P: EC_ShortW_Aff[Fp[Name], G1], + Q: EC_ShortW_Aff[Fp2[Name], G2]) = ## Compute the optimal Ate Pairing for BN curves ## Input: P ∈ G1, Q ∈ G2 ## Output: e(P, Q) ∈ Gt @@ -109,7 +109,7 @@ func pairing_bn_reference*[C]( # Optimized pairing implementation # ---------------------------------------------------------------- -func finalExpHard_BN*[C: static Curve](f: var Fp12[C]) {.meter.} = +func finalExpHard_BN*[Name: static Algebra](f: var Fp12[Name]) {.meter.} = ## Hard part of the final exponentiation ## Specialized for BN curves ## @@ -125,7 +125,7 @@ func finalExpHard_BN*[C: static Curve](f: var Fp12[C]) {.meter.} = # memory saving optimization # as that variant has an exponentiation by -2u-1 # that requires another addition chain - var t0 {.noInit.}, t1 {.noinit.}, t2 {.noinit.}, t3 {.noinit.}, t4 {.noinit.}: Fp12[C] + var t0 {.noInit.}, t1 {.noinit.}, t2 {.noinit.}, t3 {.noinit.}, t4 {.noinit.}: Fp12[Name] t0.cycl_exp_by_curve_param(f, invert = false) # t0 = f^|u| t0.cyclotomic_square() # t0 = f^2|u| @@ -133,7 +133,7 @@ func finalExpHard_BN*[C: static Curve](f: var Fp12[C]) {.meter.} = t1 *= t0 # t1 = f^6|u| t2.cycl_exp_by_curve_param(t1, invert = false) # t2 = f^6u² - if C.pairing(ate_param_is_Neg): + if Name.pairing(ate_param_is_Neg): t3.cyclotomic_inv(t1) # t3 = f^6u else: t3 = t1 # t3 = f^6u @@ -142,7 +142,7 @@ func finalExpHard_BN*[C: static Curve](f: var Fp12[C]) {.meter.} = t4.cycl_exp_by_curve_param(t3) # t4 = f^12u³ t4 *= t1 # t4 = f^(6u + 6u² + 12u³) = f^λ₂ - if not C.pairing(ate_param_is_Neg): + if not Name.pairing(ate_param_is_Neg): t0.cyclotomic_inv() # t0 = f^-2u t3.prod(t4, t0) # t3 = f^(4u + 6u² + 12u³) @@ -161,30 +161,30 @@ func finalExpHard_BN*[C: static Curve](f: var Fp12[C]) {.meter.} = f.frobenius_map(t2, 3) # r = f^λ₃p³ f *= t0 # r = f^(λ₀ + λ₁p + λ₂p² + λ₃p³) = f^((p⁴-p²+1)/r) -func pairing_bn*[C]( - gt: var Fp12[C], - P: ECP_ShortW_Aff[Fp[C], G1], - Q: ECP_ShortW_Aff[Fp2[C], G2]) {.meter.} = +func pairing_bn*[Name]( + gt: var Fp12[Name], + P: EC_ShortW_Aff[Fp[Name], G1], + Q: EC_ShortW_Aff[Fp2[Name], G2]) {.meter.} = ## Compute the optimal Ate Pairing for BN curves ## Input: P ∈ G1, Q ∈ G2 ## Output: e(P, Q) ∈ Gt - when C == BN254_Nogami: + when Name == BN254_Nogami: gt.millerLoopAddChain(Q, P) else: gt.millerLoopGenericBN(Q, P) gt.finalExpEasy() gt.finalExpHard_BN() -func pairing_bn*[N: static int, C]( - gt: var Fp12[C], - Ps: array[N, ECP_ShortW_Aff[Fp[C], G1]], - Qs: array[N, ECP_ShortW_Aff[Fp2[C], G2]]) {.meter.} = +func pairing_bn*[N: static int, Name]( + gt: var Fp12[Name], + Ps: array[N, EC_ShortW_Aff[Fp[Name], G1]], + Qs: array[N, EC_ShortW_Aff[Fp2[Name], G2]]) {.meter.} = ## Compute the optimal Ate Pairing for BLS12 curves ## Input: an array of Ps ∈ G1 and Qs ∈ G2 ## Output: ## The product of pairings ## e(P₀, Q₀) * e(P₁, Q₁) * e(P₂, Q₂) * ... * e(Pₙ, Qₙ) ∈ Gt - when C == BN254_Nogami: + when Name == BN254_Nogami: gt.millerLoopAddChain(Qs.asUnchecked(), Ps.asUnchecked(), N) else: gt.millerLoopGenericBN(Qs.asUnchecked(), Ps.asUnchecked(), N) diff --git a/constantine/math/pairings/pairings_bw6_761.nim b/constantine/math/pairings/pairings_bw6_761.nim index 51b3704e3..110f94781 100644 --- a/constantine/math/pairings/pairings_bw6_761.nim +++ b/constantine/math/pairings/pairings_bw6_761.nim @@ -31,20 +31,20 @@ export zoo_pairings # generic sandwich https://github.com/nim-lang/Nim/issues/11 # Generic pairing implementation # ---------------------------------------------------------------- -func millerLoopBW6_761_naive[C]( - f: var Fp6[C], - Q: ECP_ShortW_Aff[Fp[C], G2], - P: ECP_ShortW_Aff[Fp[C], G1] +func millerLoopBW6_761_naive[Name]( + f: var Fp6[Name], + Q: EC_ShortW_Aff[Fp[Name], G2], + P: EC_ShortW_Aff[Fp[Name], G1] ) = ## Miller Loop for BW6_761 curve ## Computes f_{u+1,Q}(P)*Frobenius(f_{u*(u^2-u-1),Q}(P)) - var T {.noInit.}: ECP_ShortW_Prj[Fp[C], G2] + var T {.noInit.}: EC_ShortW_Prj[Fp[Name], G2] T.fromAffine(Q) basicMillerLoop( f, T, P, Q, - pairing(C, ate_param_1_unopt), pairing(C, ate_param_1_unopt_isNeg) + pairing(Name, ate_param_1_unopt), pairing(Name, ate_param_1_unopt_isNeg) ) var f2 {.noInit.}: typeof(f) @@ -53,42 +53,42 @@ func millerLoopBW6_761_naive[C]( basicMillerLoop( f2, T, P, Q, - pairing(C, ate_param_2_unopt), pairing(C, ate_param_2_unopt_isNeg) + pairing(Name, ate_param_2_unopt), pairing(Name, ate_param_2_unopt_isNeg) ) let t = f2 f2.frobenius_map(t) f *= f2 -func finalExpGeneric[C: static Curve](f: var Fp6[C]) = +func finalExpGeneric[Name: static Algebra](f: var Fp6[Name]) = ## A generic and slow implementation of final exponentiation ## for sanity checks purposes. - f.pow_vartime(C.pairing(finalexponent), window = 3) + f.pow_vartime(Name.pairing(finalexponent), window = 3) -func finalExpHard_BW6_761*[C: static Curve](f: var Fp6[C]) = +func finalExpHard_BW6_761*[Name: static Algebra](f: var Fp6[Name]) = ## A generic and slow implementation of final exponentiation ## for sanity checks purposes. - f.pow_vartime(C.pairing(finalexponent_hard), window = 3) + f.pow_vartime(Name.pairing(finalexponent_hard), window = 3) # Optimized pairing implementation # ---------------------------------------------------------------- -func millerLoopBW6_761_opt_to_debug[C]( - f: var Fp6[C], - Q: ECP_ShortW_Aff[Fp[C], G2], - P: ECP_ShortW_Aff[Fp[C], G1] +func millerLoopBW6_761_opt_to_debug[Name]( + f: var Fp6[Name], + Q: EC_ShortW_Aff[Fp[Name], G2], + P: EC_ShortW_Aff[Fp[Name], G1] ) {.used.} = ## Miller Loop Otpimized for BW6_761 curve # 1st part: f_{u,Q}(P) # ------------------------------ - var T {.noInit.}: ECP_ShortW_Prj[Fp[C], G2] - var line {.noInit.}: Line[Fp[C]] + var T {.noInit.}: EC_ShortW_Prj[Fp[Name], G2] + var line {.noInit.}: Line[Fp[Name]] T.fromAffine(Q) f.setOne() - template u: untyped = pairing(C, ate_param_1_opt) + template u: untyped = pairing(Name, ate_param_1_opt) for i in countdown(u.bits - 2, 1): square(f) line_double(line, T, P) @@ -119,8 +119,8 @@ func millerLoopBW6_761_opt_to_debug[C]( # We restart from `f` and `T` T.fromAffine(Qu) - template u: untyped = pairing(C, ate_param_2_opt) - var u3 = pairing(C, ate_param_2_opt) + template u: untyped = pairing(Name, ate_param_2_opt) + var u3 = pairing(Name, ate_param_2_opt) u3 *= 3 for i in countdown(u3.bits - 2, 1): square(f) @@ -146,10 +146,10 @@ func millerLoopBW6_761_opt_to_debug[C]( # Public # ---------------------------------------------------------------- -func pairing_bw6_761_reference*[C]( - gt: var Fp6[C], - P: ECP_ShortW_Aff[Fp[C], G1], - Q: ECP_ShortW_Aff[Fp[C], G2]) = +func pairing_bw6_761_reference*[Name]( + gt: var Fp6[Name], + P: EC_ShortW_Aff[Fp[Name], G1], + Q: EC_ShortW_Aff[Fp[Name], G2]) = ## Compute the optimal Ate Pairing for BW6 curves ## Input: P ∈ G1, Q ∈ G2 ## Output: e(P, Q) ∈ Gt diff --git a/constantine/math/pairings/pairings_generic.nim b/constantine/math/pairings/pairings_generic.nim index 76605b1b0..893891c18 100644 --- a/constantine/math/pairings/pairings_generic.nim +++ b/constantine/math/pairings/pairings_generic.nim @@ -13,25 +13,25 @@ import constantine/math/extension_fields, constantine/named/zoo_pairings -func pairing*[C](gt: var Fp12[C], P, Q: auto) {.inline.} = - when family(C) == BarretoNaehrig: +func pairing*[Name](gt: var Fp12[Name], P, Q: auto) {.inline.} = + when family(Name) == BarretoNaehrig: pairing_bn(gt, P, Q) - elif family(C) == BarretoLynnScott: + elif family(Name) == BarretoLynnScott: pairing_bls12(gt, P, Q) else: - {.error: "Pairing not implemented for " & $C.} + {.error: "Pairing not implemented for " & $Name.} -func millerLoop*[C](gt: var Fp12[C], Q, P: auto, n: int) {.inline.} = - when C == BN254_Snarks: +func millerLoop*[Name](gt: var Fp12[Name], Q, P: auto, n: int) {.inline.} = + when Name == BN254_Snarks: gt.millerLoopGenericBN(Q, P, n) else: gt.millerLoopAddchain(Q, P, n) -func finalExp*[C](gt: var Fp12[C]){.inline.} = +func finalExp*[Name](gt: var Fp12[Name]){.inline.} = gt.finalExpEasy() - when family(C) == BarretoNaehrig: + when family(Name) == BarretoNaehrig: gt.finalExpHard_BN() - elif family(C) == BarretoLynnScott: + elif family(Name) == BarretoLynnScott: gt.finalExpHard_BLS12() else: - {.error: "Final Exponentiation not implemented for " & $C.} + {.error: "Final Exponentiation not implemented for " & $Name.} diff --git a/constantine/math/polynomials/fft.nim b/constantine/math/polynomials/fft.nim index 595aac4da..8af0af95a 100644 --- a/constantine/math/polynomials/fft.nim +++ b/constantine/math/polynomials/fft.nim @@ -32,12 +32,12 @@ type ECFFT_Descriptor*[EC] = object ## Metadata for FFT on Elliptic Curve order*: int - rootsOfUnity*: ptr UncheckedArray[matchingOrderBigInt(EC.F.C)] + rootsOfUnity*: ptr UncheckedArray[getBigInt(EC.F.Name, kScalarField)] ## domain, starting and ending with 1, length is cardinality+1 ## This allows FFT and inverse FFT to use the same buffer for roots. func computeRootsOfUnity[EC](ctx: var ECFFT_Descriptor[EC], generatorRootOfUnity: auto) = - static: doAssert typeof(generatorRootOfUnity) is Fr[EC.F.C] + static: doAssert typeof(generatorRootOfUnity) is Fr[EC.F.Name] ctx.rootsOfUnity[0].setOne() @@ -50,7 +50,7 @@ func computeRootsOfUnity[EC](ctx: var ECFFT_Descriptor[EC], generatorRootOfUnity func new*(T: type ECFFT_Descriptor, order: int, generatorRootOfUnity: auto): T = result.order = order - result.rootsOfUnity = allocHeapArrayAligned(matchingOrderBigInt(T.EC.F.C), order+1, alignment = 64) + result.rootsOfUnity = allocHeapArrayAligned(T.EC.getScalarField().getBigInt(), order+1, alignment = 64) result.computeRootsOfUnity(generatorRootOfUnity) @@ -137,9 +137,9 @@ func ifft_vartime*[EC]( var voutput = output.toStridedView() fft_internal(voutput, vals.toStridedView(), rootz) - var invLen {.noInit.}: matchingOrderBigInt(EC.F.C) + var invLen {.noInit.}: EC.F.getBigInt() invLen.fromUint(vals.len.uint64) - invLen.invmod_vartime(invLen, EC.F.C.getCurveOrder()) + invLen.invmod_vartime(invLen, EC.F.getModulus()) for i in 0 ..< output.len: output[i].scalarMul_vartime(invLen) @@ -346,7 +346,7 @@ when isMainModule: Fr[BLS12_381].fromHex"0x4b5371495990693fad1715b02e5713b5f070bb00e28a193d63e7cb4906ffc93f" ] - type EC_G1 = ECP_ShortW_Prj[Fp[BLS12_381], G1] + type EC_G1 = EC_ShortW_Prj[Fp[BLS12_381], G1] proc roundtrip() = let fftDesc = ECFFT_Descriptor[EC_G1].new(order = 1 shl 4, ctt_eth_kzg_fr_pow2_roots_of_unity[4]) @@ -355,7 +355,7 @@ when isMainModule: var data = newSeq[EC_G1](fftDesc.order) data[0].setGenerator() for i in 1 ..< fftDesc.order: - data[i].madd(data[i-1], BLS12_381.getGenerator("G1")) + data[i].mixedSum(data[i-1], BLS12_381.getGenerator("G1")) var coefs = newSeq[EC_G1](data.len) let fftOk = fft_vartime(fftDesc, coefs, data) @@ -406,7 +406,7 @@ when isMainModule: var data = newSeq[EC_G1](fftDesc.order) data[0].setGenerator() for i in 1 ..< fftDesc.order: - data[i].madd(data[i-1], BLS12_381.getGenerator("G1")) + data[i].mixedSum(data[i-1], BLS12_381.getGenerator("G1")) var coefsOut = newSeq[EC_G1](data.len) @@ -456,8 +456,8 @@ when isMainModule: echo "optimal tile size for uint64: ", optTile, "x", optTile," (", sizeof(uint64) * optTile * optTile, " bytes)" block: - let optTile = 1 shl optimalLogTileSize(ECP_ShortW_Aff[Fp[BLS12_381], G1]) - echo "optimal tile size for ECP_ShortW_Aff[Fp[BLS12_381], G1]: ", optTile, "x", optTile," (", sizeof(ECP_ShortW_Aff[Fp[BLS12_381], G1]) * optTile * optTile, " bytes)" + let optTile = 1 shl optimalLogTileSize(EC_ShortW_Aff[Fp[BLS12_381], G1]) + echo "optimal tile size for EC_ShortW_Aff[Fp[BLS12_381], G1]: ", optTile, "x", optTile," (", sizeof(EC_ShortW_Aff[Fp[BLS12_381], G1]) * optTile * optTile, " bytes)" roundtrip() warmup() diff --git a/constantine/named/constants/bandersnatch_generators.nim b/constantine/named/constants/bandersnatch_generators.nim index e77166e62..15b6e2955 100644 --- a/constantine/named/constants/bandersnatch_generators.nim +++ b/constantine/named/constants/bandersnatch_generators.nim @@ -17,7 +17,7 @@ import # ----------------------------------------------------------------- # https://eprint.iacr.org/2021/1152.pdf -const Bandersnatch_generator* = ECP_TwEdwards_Aff[Fp[Bandersnatch]]( +const Bandersnatch_generator* = EC_TwEdw_Aff[Fp[Bandersnatch]]( x: Fp[Bandersnatch].fromHex"0x29c132cc2c0b34c5743711777bbe42f32b79c022ad998465e1e71866a252ae18", y: Fp[Bandersnatch].fromHex"0x2a6c669eda123e0f157d8b50badcd586358cad81eee464605e3167b6cc974166" ) diff --git a/constantine/named/constants/bandersnatch_subgroups.nim b/constantine/named/constants/bandersnatch_subgroups.nim index defdac903..ab1cf8923 100644 --- a/constantine/named/constants/bandersnatch_subgroups.nim +++ b/constantine/named/constants/bandersnatch_subgroups.nim @@ -18,7 +18,7 @@ import # # ############################################################ -func clearCofactorReference*(P: var ECP_TwEdwards_Prj[Fp[Bandersnatch]]) {.inline.} = +func clearCofactorReference*(P: var EC_TwEdw_Prj[Fp[Bandersnatch]]) {.inline.} = ## Clear the cofactor of Bandersnatch # https://hackmd.io/@6iQDuIePQjyYBqDChYw_jg/BJBNcv9fq#Bandersnatch-Subgroup # diff --git a/constantine/named/constants/banderwagon_generators.nim b/constantine/named/constants/banderwagon_generators.nim index c53f3b6e0..1bea0250a 100644 --- a/constantine/named/constants/banderwagon_generators.nim +++ b/constantine/named/constants/banderwagon_generators.nim @@ -17,7 +17,7 @@ import # ----------------------------------------------------------------- # https://eprint.iacr.org/2021/1152.pdf -const Banderwagon_generator* = ECP_TwEdwards_Aff[Fp[Banderwagon]]( +const Banderwagon_generator* = EC_TwEdw_Aff[Fp[Banderwagon]]( x: Fp[Banderwagon].fromHex("29c132cc2c0b34c5743711777bbe42f32b79c022ad998465e1e71866a252ae18"), y: Fp[Banderwagon].fromHex("2a6c669eda123e0f157d8b50badcd586358cad81eee464605e3167b6cc974166") ) diff --git a/constantine/named/constants/banderwagon_subgroups.nim b/constantine/named/constants/banderwagon_subgroups.nim index b4a8c9d5d..4d5b3fe30 100644 --- a/constantine/named/constants/banderwagon_subgroups.nim +++ b/constantine/named/constants/banderwagon_subgroups.nim @@ -19,7 +19,7 @@ import # # ############################################################ -func isInSubgroup*(P: ECP_TwEdwards_Aff[Fp[Banderwagon]]): SecretBool = +func isInSubgroup*(P: EC_TwEdw_Aff[Fp[Banderwagon]]): SecretBool = ## Checks if the point is in the quotient subgroup ## The group law does not change because what we quotiented by was a subgroup. ## These are still points on the bandersnatch curve and form a group under point addition. diff --git a/constantine/named/constants/bls12_377_pairings.nim b/constantine/named/constants/bls12_377_pairings.nim index d059b55ae..ccebc3cc4 100644 --- a/constantine/named/constants/bls12_377_pairings.nim +++ b/constantine/named/constants/bls12_377_pairings.nim @@ -43,13 +43,13 @@ const BLS12_377_pairing_finalexponent* = block: func millerLoopAddchain*( f: var Fp12[BLS12_377], - Q: ECP_ShortW_Aff[Fp2[BLS12_377], G2], - P: ECP_ShortW_Aff[Fp[BLS12_377], G1] + Q: EC_ShortW_Aff[Fp2[BLS12_377], G2], + P: EC_ShortW_Aff[Fp[BLS12_377], G1] ) = ## Miller Loop for BLS12-377 curve ## Computes f{u,Q}(P) with u the BLS curve parameter - var T {.noInit.}: ECP_ShortW_Prj[Fp2[BLS12_377], G2] + var T {.noInit.}: EC_ShortW_Prj[Fp2[BLS12_377], G2] f.miller_init_double_then_add(T, Q, P, 5) # 0b100001 f.miller_accum_double_then_add(T, Q, P, 2) # 0b10000101 @@ -60,14 +60,14 @@ func millerLoopAddchain*( func millerLoopAddchain*( f: var Fp12[BLS12_377], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[Fp2[BLS12_377], G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[Fp[BLS12_377], G1]], + Qs: ptr UncheckedArray[EC_ShortW_Aff[Fp2[BLS12_377], G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[Fp[BLS12_377], G1]], N: int ) {.noInline.} = ## Miller Loop for BLS12-377 curve ## Computes f{u,Q}(P) with u the BLS curve parameter - var Ts = allocStackArray(ECP_ShortW_Prj[Fp2[BLS12_377], G2], N) + var Ts = allocStackArray(EC_ShortW_Prj[Fp2[BLS12_377], G2], N) f.miller_init_double_then_add( Ts, Qs, Ps, N, 5) # 0b100001 f.miller_accum_double_then_add(Ts, Qs, Ps, N, 2) # 0b10000101 diff --git a/constantine/named/constants/bls12_377_subgroups.nim b/constantine/named/constants/bls12_377_subgroups.nim index f120ea7b6..6cc5b77ad 100644 --- a/constantine/named/constants/bls12_377_subgroups.nim +++ b/constantine/named/constants/bls12_377_subgroups.nim @@ -17,8 +17,8 @@ import constantine/math/isogenies/frobenius, constantine/named/zoo_endomorphisms -func pow_bls12_377_abs_x[ECP: ECP_ShortW[Fp[BLS12_377], G1] or - ECP_ShortW[Fp2[BLS12_377], G2]]( +func pow_bls12_377_abs_x[ECP: EC_ShortW[Fp[BLS12_377], G1] or + EC_ShortW[Fp2[BLS12_377], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) = @@ -48,8 +48,8 @@ func pow_bls12_377_abs_x[ECP: ECP_ShortW[Fp[BLS12_377], G1] or r.double_repeated(46) r += P -func pow_bls12_377_x[ECP: ECP_ShortW[Fp[BLS12_377], G1] or - ECP_ShortW[Fp2[BLS12_377], G2]]( +func pow_bls12_377_x[ECP: EC_ShortW[Fp[BLS12_377], G1] or + EC_ShortW[Fp2[BLS12_377], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) {.inline.}= @@ -59,8 +59,8 @@ func pow_bls12_377_x[ECP: ECP_ShortW[Fp[BLS12_377], G1] or ## Requires r and P to not alias pow_bls12_377_abs_x(r, P) -func pow_bls12_377_minus_x[ECP: ECP_ShortW[Fp[BLS12_377], G1] or - ECP_ShortW[Fp2[BLS12_377], G2]]( +func pow_bls12_377_minus_x[ECP: EC_ShortW[Fp[BLS12_377], G1] or + EC_ShortW[Fp2[BLS12_377], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) {.inline.}= @@ -85,13 +85,13 @@ const Cofactor_Eff_BLS12_377_G2 = BigInt[629].fromHex"0x1f60243677e30653648d3d95 ## Effective cofactor from Budroni et al https://eprint.iacr.org/2017/419.pdf ## (3x² − 3)*cofactor -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp[BLS12_377], G1]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp[BLS12_377], G1]) {.inline.} = ## Clear the cofactor of BLS12_377 G1 # Endomorphism acceleration cannot be used if cofactor is not cleared P.scalarMulGeneric(Cofactor_Eff_BLS12_377_G1) P.neg() -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp2[BLS12_377], G2]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp2[BLS12_377], G2]) {.inline.} = ## Clear the cofactor of BLS12_377 G2 # Endomorphism acceleration cannot be used if cofactor is not cleared P.scalarMulGeneric(Cofactor_Eff_BLS12_377_G2) @@ -105,7 +105,7 @@ func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp2[BLS12_377], G2]) {.inline # BLS12 G1 # ------------------------------------------------------------ -func clearCofactorFast*(P: var ECP_ShortW[Fp[BLS12_377], G1]) = +func clearCofactorFast*(P: var EC_ShortW[Fp[BLS12_377], G1]) = ## Clear the cofactor of BLS12_377 G1 ## ## Wahby et al "Fast and simple constant-time hashing to the BLS12-377 elliptic curve", https://eprint.iacr.org/2019/403 @@ -144,7 +144,7 @@ func clearCofactorFast*(P: var ECP_ShortW[Fp[BLS12_377], G1]) = # with Psi (ψ) - untwist-Frobenius-Twist function # and x the curve BLS parameter -func clearCofactorFast*(P: var ECP_ShortW[Fp2[BLS12_377], G2]) = +func clearCofactorFast*(P: var EC_ShortW[Fp2[BLS12_377], G2]) = ## Clear the cofactor of BLS12_377 G2 ## Optimized using endomorphisms ## P -> [x²-x-1]P + [x-1] ψ(P) + ψ²([2]P) @@ -172,7 +172,7 @@ func clearCofactorFast*(P: var ECP_ShortW[Fp2[BLS12_377], G2]) = # # ############################################################ -func isInSubgroup*(P: ECP_ShortW[Fp[BLS12_377], G1]): SecretBool = +func isInSubgroup*(P: EC_ShortW[Fp[BLS12_377], G1]): SecretBool = ## Returns true if P is in G1 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. @@ -195,7 +195,7 @@ func isInSubgroup*(P: ECP_ShortW[Fp[BLS12_377], G1]): SecretBool = return t0 == t1 -func isInSubgroup*(P: ECP_ShortW[Fp2[BLS12_377], G2]): SecretBool = +func isInSubgroup*(P: EC_ShortW[Fp2[BLS12_377], G2]): SecretBool = ## Returns true if P is in G2 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. @@ -211,23 +211,23 @@ func isInSubgroup*(P: ECP_ShortW[Fp2[BLS12_377], G2]): SecretBool = return t0 == t1 -func isInSubgroup*(P: ECP_ShortW_Aff[Fp[BLS12_377], G1]): SecretBool = +func isInSubgroup*(P: EC_ShortW_Aff[Fp[BLS12_377], G1]): SecretBool = ## Returns true if P is in 𝔾1 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. ## ## Warning ⚠: Assumes that P is on curve - var t{.noInit.}: ECP_ShortW_Prj[Fp[BLS12_377], G1] + var t{.noInit.}: EC_ShortW_Prj[Fp[BLS12_377], G1] t.fromAffine(P) return t.isInSubgroup() -func isInSubgroup*(P: ECP_ShortW_Aff[Fp2[BLS12_377], G2]): SecretBool = +func isInSubgroup*(P: EC_ShortW_Aff[Fp2[BLS12_377], G2]): SecretBool = ## Returns true if P is in 𝔾2 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. ## ## Warning ⚠: Assumes that P is on curve - var t{.noInit.}: ECP_ShortW_Jac[Fp2[BLS12_377], G2] + var t{.noInit.}: EC_ShortW_Jac[Fp2[BLS12_377], G2] t.fromAffine(P) return t.isInSubgroup() diff --git a/constantine/named/constants/bls12_381_generators.nim b/constantine/named/constants/bls12_381_generators.nim index 14baf7b11..d02d41a10 100644 --- a/constantine/named/constants/bls12_381_generators.nim +++ b/constantine/named/constants/bls12_381_generators.nim @@ -17,12 +17,12 @@ import # ----------------------------------------------------------------- # https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-10#section-4.2.1 -const BLS12_381_generator_G1* = ECP_ShortW_Aff[Fp[BLS12_381], G1]( +const BLS12_381_generator_G1* = EC_ShortW_Aff[Fp[BLS12_381], G1]( x: Fp[BLS12_381].fromHex"0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb", y: Fp[BLS12_381].fromHex"0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1" ) -const BLS12_381_generator_G2* = ECP_ShortW_Aff[Fp2[BLS12_381], G2]( +const BLS12_381_generator_G2* = EC_ShortW_Aff[Fp2[BLS12_381], G2]( x: Fp2[BLS12_381].fromHex( "0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8", "0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e" diff --git a/constantine/named/constants/bls12_381_pairings.nim b/constantine/named/constants/bls12_381_pairings.nim index 1223d9c3d..5e5ef5645 100644 --- a/constantine/named/constants/bls12_381_pairings.nim +++ b/constantine/named/constants/bls12_381_pairings.nim @@ -41,13 +41,13 @@ const BLS12_381_pairing_finalexponent* = block: func millerLoopAddchain*( f: var Fp12[BLS12_381], - Q: ECP_ShortW_Aff[Fp2[BLS12_381], G2], - P: ECP_ShortW_Aff[Fp[BLS12_381], G1] + Q: EC_ShortW_Aff[Fp2[BLS12_381], G2], + P: EC_ShortW_Aff[Fp[BLS12_381], G1] ) {.meter.} = ## Miller Loop for BLS12-381 curve ## Computes f{u,Q}(P) with u the BLS curve parameter - var T {.noInit.}: ECP_ShortW_Prj[Fp2[BLS12_381], G2] + var T {.noInit.}: EC_ShortW_Prj[Fp2[BLS12_381], G2] f.miller_init_double_then_add(T, Q, P, 1) # 0b11 f.miller_accum_double_then_add(T, Q, P, 2) # 0b1101 @@ -61,14 +61,14 @@ func millerLoopAddchain*( func millerLoopAddchain*( f: var Fp12[BLS12_381], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[Fp2[BLS12_381], G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[Fp[BLS12_381], G1]], + Qs: ptr UncheckedArray[EC_ShortW_Aff[Fp2[BLS12_381], G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[Fp[BLS12_381], G1]], N: int ) {.noInline, meter.} = ## Generic Miller Loop for BLS12 curve ## Computes f{u,Q}(P) with u the BLS curve parameter - var Ts = allocStackArray(ECP_ShortW_Prj[Fp2[BLS12_381], G2], N) + var Ts = allocStackArray(EC_ShortW_Prj[Fp2[BLS12_381], G2], N) # Ate param addition chain # Hex: 0xd201000000010000 diff --git a/constantine/named/constants/bls12_381_subgroups.nim b/constantine/named/constants/bls12_381_subgroups.nim index b12b0e2c8..d176f0606 100644 --- a/constantine/named/constants/bls12_381_subgroups.nim +++ b/constantine/named/constants/bls12_381_subgroups.nim @@ -17,8 +17,8 @@ import constantine/math/isogenies/frobenius, constantine/named/zoo_endomorphisms -func pow_bls12_381_abs_x[ECP: ECP_ShortW[Fp[BLS12_381], G1] or - ECP_ShortW[Fp2[BLS12_381], G2]]( +func pow_bls12_381_abs_x[ECP: EC_ShortW[Fp[BLS12_381], G1] or + EC_ShortW[Fp2[BLS12_381], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) = @@ -46,8 +46,8 @@ func pow_bls12_381_abs_x[ECP: ECP_ShortW[Fp[BLS12_381], G1] or # 0b1101001000000001000000000000000000000000000000010000000000000000 r.double_repeated(16) -func pow_bls12_381_x[ECP: ECP_ShortW[Fp[BLS12_381], G1] or - ECP_ShortW[Fp2[BLS12_381], G2]]( +func pow_bls12_381_x[ECP: EC_ShortW[Fp[BLS12_381], G1] or + EC_ShortW[Fp2[BLS12_381], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) {.inline.}= @@ -58,8 +58,8 @@ func pow_bls12_381_x[ECP: ECP_ShortW[Fp[BLS12_381], G1] or pow_bls12_381_abs_x(r, P) r.neg() -func pow_bls12_381_minus_x[ECP: ECP_ShortW[Fp[BLS12_381], G1] or - ECP_ShortW[Fp2[BLS12_381], G2]]( +func pow_bls12_381_minus_x[ECP: EC_ShortW[Fp[BLS12_381], G1] or + EC_ShortW[Fp2[BLS12_381], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) {.inline.}= @@ -81,11 +81,11 @@ const Cofactor_Eff_BLS12_381_G1 = BigInt[64].fromHex"0xd201000000010001" const Cofactor_Eff_BLS12_381_G2 = BigInt[636].fromHex"0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551" ## P -> (x^2 - x - 1) P + (x - 1) ψ(P) + ψ(ψ(2P)) -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp[BLS12_381], G1]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp[BLS12_381], G1]) {.inline.} = ## Clear the cofactor of BLS12_381 𝔾1 P.scalarMulGeneric(Cofactor_Eff_BLS12_381_G1) -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp2[BLS12_381], G2]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp2[BLS12_381], G2]) {.inline.} = ## Clear the cofactor of BLS12_381 𝔾2 # Endomorphism acceleration cannot be used if cofactor is not cleared P.scalarMulGeneric(Cofactor_Eff_BLS12_381_G2) @@ -99,7 +99,7 @@ func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp2[BLS12_381], G2]) {.inline # BLS12 𝔾1 # ------------------------------------------------------------ -func clearCofactorFast*(P: var ECP_ShortW[Fp[BLS12_381], G1]) = +func clearCofactorFast*(P: var EC_ShortW[Fp[BLS12_381], G1]) = ## Clear the cofactor of BLS12_381 𝔾1 ## ## Wahby et al "Fast and simple constant-time hashing to the BLS12-381 elliptic curve", https://eprint.iacr.org/2019/403 @@ -138,7 +138,7 @@ func clearCofactorFast*(P: var ECP_ShortW[Fp[BLS12_381], G1]) = # with Psi (ψ) - untwist-Frobenius-Twist function # and x the curve BLS parameter -func clearCofactorFast*(P: var ECP_ShortW[Fp2[BLS12_381], G2]) = +func clearCofactorFast*(P: var EC_ShortW[Fp2[BLS12_381], G2]) = ## Clear the cofactor of BLS12_381 𝔾2 ## Optimized using endomorphisms ## P -> [x²-x-1]P + [x-1] ψ(P) + ψ²([2]P) @@ -166,7 +166,7 @@ func clearCofactorFast*(P: var ECP_ShortW[Fp2[BLS12_381], G2]) = # # ############################################################ -func isInSubgroup*(P: ECP_ShortW[Fp[BLS12_381], G1]): SecretBool = +func isInSubgroup*(P: EC_ShortW[Fp[BLS12_381], G1]): SecretBool = ## Returns true if P is in 𝔾1 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. @@ -189,7 +189,7 @@ func isInSubgroup*(P: ECP_ShortW[Fp[BLS12_381], G1]): SecretBool = return t0 == t1 -func isInSubgroup*(P: ECP_ShortW[Fp2[BLS12_381], G2]): SecretBool = +func isInSubgroup*(P: EC_ShortW[Fp2[BLS12_381], G2]): SecretBool = ## Returns true if P is in 𝔾2 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. @@ -205,23 +205,23 @@ func isInSubgroup*(P: ECP_ShortW[Fp2[BLS12_381], G2]): SecretBool = return t0 == t1 -func isInSubgroup*(P: ECP_ShortW_Aff[Fp[BLS12_381], G1]): SecretBool = +func isInSubgroup*(P: EC_ShortW_Aff[Fp[BLS12_381], G1]): SecretBool = ## Returns true if P is in 𝔾1 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. ## ## Warning ⚠: Assumes that P is on curve - var t{.noInit.}: ECP_ShortW_Prj[Fp[BLS12_381], G1] + var t{.noInit.}: EC_ShortW_Prj[Fp[BLS12_381], G1] t.fromAffine(P) return t.isInSubgroup() -func isInSubgroup*(P: ECP_ShortW_Aff[Fp2[BLS12_381], G2]): SecretBool = +func isInSubgroup*(P: EC_ShortW_Aff[Fp2[BLS12_381], G2]): SecretBool = ## Returns true if P is in 𝔾2 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. ## ## Warning ⚠: Assumes that P is on curve - var t{.noInit.}: ECP_ShortW_Jac[Fp2[BLS12_381], G2] + var t{.noInit.}: EC_ShortW_Jac[Fp2[BLS12_381], G2] t.fromAffine(P) return t.isInSubgroup() diff --git a/constantine/named/constants/bn254_nogami_pairings.nim b/constantine/named/constants/bn254_nogami_pairings.nim index 17f2a11e3..689538807 100644 --- a/constantine/named/constants/bn254_nogami_pairings.nim +++ b/constantine/named/constants/bn254_nogami_pairings.nim @@ -39,12 +39,12 @@ const BN254_Nogami_pairing_finalexponent* = block: func millerLoopAddchain*( f: var Fp12[BN254_Nogami], - Q: ECP_ShortW_Aff[Fp2[BN254_Nogami], G2], - P: ECP_ShortW_Aff[Fp[BN254_Nogami], G1] + Q: EC_ShortW_Aff[Fp2[BN254_Nogami], G2], + P: EC_ShortW_Aff[Fp[BN254_Nogami], G1] ) = ## Miller Loop for BN254-Nogami curve ## Computes f{6u+2,Q}(P) with u the BLS curve parameter - var T {.noInit.}: ECP_ShortW_Prj[Fp2[BN254_Nogami], G2] + var T {.noInit.}: EC_ShortW_Prj[Fp2[BN254_Nogami], G2] f.miller_init_double_then_add(T, Q, P, 1) # 0b11 f.miller_accum_double_then_add(T, Q, P, 6) # 0b11000001 @@ -61,13 +61,13 @@ func millerLoopAddchain*( func millerLoopAddchain*( f: var Fp12[BN254_Nogami], - Qs: ptr UncheckedArray[ECP_ShortW_Aff[Fp2[BN254_Nogami], G2]], - Ps: ptr UncheckedArray[ECP_ShortW_Aff[Fp[BN254_Nogami], G1]], + Qs: ptr UncheckedArray[EC_ShortW_Aff[Fp2[BN254_Nogami], G2]], + Ps: ptr UncheckedArray[EC_ShortW_Aff[Fp[BN254_Nogami], G1]], N: int ) {.noInline.} = ## Miller Loop for BN254-Nogami curve ## Computes f{6u+2,Q}(P) with u the BLS curve parameter - var Ts = allocStackArray(ECP_ShortW_Prj[Fp2[BN254_Nogami], G2], N) + var Ts = allocStackArray(EC_ShortW_Prj[Fp2[BN254_Nogami], G2], N) f.miller_init_double_then_add( Ts, Qs, Ps, N, 1) # 0b11 f.miller_accum_double_then_add(Ts, Qs, Ps, N, 6) # 0b11000001 diff --git a/constantine/named/constants/bn254_nogami_subgroups.nim b/constantine/named/constants/bn254_nogami_subgroups.nim index fd9cb3d08..944917ecc 100644 --- a/constantine/named/constants/bn254_nogami_subgroups.nim +++ b/constantine/named/constants/bn254_nogami_subgroups.nim @@ -16,8 +16,8 @@ import constantine/math/io/io_bigints, constantine/math/isogenies/frobenius -func pow_BN254_Nogami_abs_u*[ECP: ECP_ShortW[Fp[BN254_Nogami], G1] or - ECP_ShortW[Fp2[BN254_Nogami], G2]]( +func pow_BN254_Nogami_abs_u*[ECP: EC_ShortW[Fp[BN254_Nogami], G1] or + EC_ShortW[Fp2[BN254_Nogami], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) = @@ -29,8 +29,8 @@ func pow_BN254_Nogami_abs_u*[ECP: ECP_ShortW[Fp[BN254_Nogami], G1] or r.double_repeated(55) r += P -func pow_BN254_Nogami_u[ECP: ECP_ShortW[Fp[BN254_Nogami], G1] or - ECP_ShortW[Fp2[BN254_Nogami], G2]]( +func pow_BN254_Nogami_u[ECP: EC_ShortW[Fp[BN254_Nogami], G1] or + EC_ShortW[Fp2[BN254_Nogami], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) {.inline.}= @@ -39,8 +39,8 @@ func pow_BN254_Nogami_u[ECP: ECP_ShortW[Fp[BN254_Nogami], G1] or pow_BN254_Nogami_abs_u(r, P) r.neg() -func pow_BN254_Nogami_minus_u[ECP: ECP_ShortW[Fp[BN254_Nogami], G1] or - ECP_ShortW[Fp2[BN254_Nogami], G2]]( +func pow_BN254_Nogami_minus_u[ECP: EC_ShortW[Fp[BN254_Nogami], G1] or + EC_ShortW[Fp2[BN254_Nogami], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) {.inline, used.}= @@ -61,12 +61,12 @@ const Cofactor_Eff_BN254_Nogami_G2 = BigInt[444].fromHex"0xab11da940a5bd10e25327 # Effective cofactor from Fuentes-Casteneda et al # −(18x³ + 12x² + 3x + 1)*cofactor -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp[BN254_Nogami], G1]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp[BN254_Nogami], G1]) {.inline.} = ## Clear the cofactor of BN254_Nogami G1 ## BN curves have a G1 cofactor of 1 so this is a no-op discard -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp2[BN254_Nogami], G2]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp2[BN254_Nogami], G2]) {.inline.} = ## Clear the cofactor of BN254_Nogami G2 # Endomorphism acceleration cannot be used if cofactor is not cleared P.scalarMulGeneric(Cofactor_Eff_BN254_Nogami_G2) @@ -80,7 +80,7 @@ func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp2[BN254_Nogami], G2]) {.inl # BN G1 # ------------------------------------------------------------ -func clearCofactorFast*(P: var ECP_ShortW[Fp[BN254_Nogami], G1]) {.inline.} = +func clearCofactorFast*(P: var EC_ShortW[Fp[BN254_Nogami], G1]) {.inline.} = ## Clear the cofactor of BN254_Nogami G1 ## BN curves have a prime order r hence all points on curve are in G1 ## Hence this is a no-op @@ -92,7 +92,7 @@ func clearCofactorFast*(P: var ECP_ShortW[Fp[BN254_Nogami], G1]) {.inline.} = # Implementation # Fuentes-Castaneda et al, "Fast Hashing to G2 on Pairing-Friendly Curves", https://doi.org/10.1007/978-3-642-28496-0_25* -func clearCofactorFast*(P: var ECP_ShortW[Fp2[BN254_Nogami], G2]) {.inline.} = +func clearCofactorFast*(P: var EC_ShortW[Fp2[BN254_Nogami], G2]) {.inline.} = ## Clear the cofactor of BN254_Nogami G2 ## Optimized using endomorphisms ## P' → [x]P + [3x]ψ(P) + [x]ψ²(P) + ψ³(P) @@ -114,7 +114,7 @@ func clearCofactorFast*(P: var ECP_ShortW[Fp2[BN254_Nogami], G2]) {.inline.} = # # ############################################################ -func isInSubgroup*(P: ECP_ShortW[Fp[BN254_Nogami], G1]): SecretBool {.inline.} = +func isInSubgroup*(P: EC_ShortW[Fp[BN254_Nogami], G1]): SecretBool {.inline.} = ## Returns true if P is in G1 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. @@ -123,7 +123,7 @@ func isInSubgroup*(P: ECP_ShortW[Fp[BN254_Nogami], G1]): SecretBool {.inline.} = ## Warning ⚠: Assumes that P is on curve return CtTrue -func isInSubgroup*(P: ECP_ShortW_Jac[Fp2[BN254_Nogami], G2] or ECP_ShortW_Prj[Fp2[BN254_Nogami], G2]): SecretBool = +func isInSubgroup*(P: EC_ShortW_Jac[Fp2[BN254_Nogami], G2] or EC_ShortW_Prj[Fp2[BN254_Nogami], G2]): SecretBool = ## Returns true if P is in G2 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. @@ -151,12 +151,12 @@ func isInSubgroup*(P: ECP_ShortW_Jac[Fp2[BN254_Nogami], G2] or ECP_ShortW_Prj[Fp return t0 == t1 -func isInSubgroup*(P: ECP_ShortW_Aff[Fp2[BN254_Nogami], G2]): SecretBool = +func isInSubgroup*(P: EC_ShortW_Aff[Fp2[BN254_Nogami], G2]): SecretBool = ## Returns true if P is in 𝔾2 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. ## ## Warning ⚠: Assumes that P is on curve - var t{.noInit.}: ECP_ShortW_Jac[Fp2[BN254_Nogami], G2] + var t{.noInit.}: EC_ShortW_Jac[Fp2[BN254_Nogami], G2] t.fromAffine(P) return t.isInSubgroup() diff --git a/constantine/named/constants/bn254_snarks_generators.nim b/constantine/named/constants/bn254_snarks_generators.nim index 842bf7a26..a2e505d1e 100644 --- a/constantine/named/constants/bn254_snarks_generators.nim +++ b/constantine/named/constants/bn254_snarks_generators.nim @@ -20,7 +20,7 @@ import # The group G_1 is defined on the curve Y^2 = X^3 + 3 over the field F_p # with p = 21888242871839275222246405745257275088696311157297823662689037894645226208583 # with generator P1 = (1, 2). -const BN254_Snarks_generator_G1* = ECP_ShortW_Aff[Fp[BN254_Snarks], G1]( +const BN254_Snarks_generator_G1* = EC_ShortW_Aff[Fp[BN254_Snarks], G1]( x: Fp[BN254_Snarks].fromHex"0x1", y: Fp[BN254_Snarks].fromHex"0x2" ) @@ -34,7 +34,7 @@ const BN254_Snarks_generator_G1* = ECP_ShortW_Aff[Fp[BN254_Snarks], G1]( # 4082367875863433681332203403145435568316851327593401208105741076214120093531 * i + # 8495653923123431417604973247489272438418190587263600148770280649306958101930 # ) -const BN254_Snarks_generator_G2* = ECP_ShortW_Aff[Fp2[BN254_Snarks], G2]( +const BN254_Snarks_generator_G2* = EC_ShortW_Aff[Fp2[BN254_Snarks], G2]( x: Fp2[BN254_Snarks].fromHex( "0x1800DEEF121F1E76426A00665E5C4479674322D4F75EDADD46DEBD5CD992F6ED", "0x198E9393920D483A7260BFB731FB5D25F1AA493335A9E71297E485B7AEF312C2" diff --git a/constantine/named/constants/bn254_snarks_subgroups.nim b/constantine/named/constants/bn254_snarks_subgroups.nim index 8d4bab7fc..8b4d9d9ef 100644 --- a/constantine/named/constants/bn254_snarks_subgroups.nim +++ b/constantine/named/constants/bn254_snarks_subgroups.nim @@ -16,8 +16,8 @@ import constantine/math/io/io_bigints, constantine/math/isogenies/frobenius -func pow_bn254_snarks_abs_u*[ECP: ECP_ShortW[Fp[BN254_Snarks], G1] or - ECP_ShortW[Fp2[BN254_Snarks], G2]]( +func pow_bn254_snarks_abs_u*[ECP: EC_ShortW[Fp[BN254_Snarks], G1] or + EC_ShortW[Fp2[BN254_Snarks], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) = @@ -93,8 +93,8 @@ func pow_bn254_snarks_abs_u*[ECP: ECP_ShortW[Fp[BN254_Snarks], G1] or r.double_repeated(16) r += r20 -func pow_bn254_snarks_u[ECP: ECP_ShortW[Fp[BN254_Snarks], G1] or - ECP_ShortW[Fp2[BN254_Snarks], G2]]( +func pow_bn254_snarks_u[ECP: EC_ShortW[Fp[BN254_Snarks], G1] or + EC_ShortW[Fp2[BN254_Snarks], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) {.inline.}= @@ -102,8 +102,8 @@ func pow_bn254_snarks_u[ECP: ECP_ShortW[Fp[BN254_Snarks], G1] or ## with u the BN curve parameter pow_bn254_snarks_abs_u(r, P) -func pow_bn254_snarks_minus_u[ECP: ECP_ShortW[Fp[BN254_Snarks], G1] or - ECP_ShortW[Fp2[BN254_Snarks], G2]]( +func pow_bn254_snarks_minus_u[ECP: EC_ShortW[Fp[BN254_Snarks], G1] or + EC_ShortW[Fp2[BN254_Snarks], G2]]( r{.noalias.}: var ECP, P{.noalias.}: ECP ) {.inline, used.}= @@ -125,12 +125,12 @@ const Cofactor_Eff_BN254_Snarks_G2 = BigInt[445].fromHex"0x10fdac342d9d118eaade4 # Effective cofactor from Fuentes-Casteneda et al # -(18x³ + 12x² + 3x + 1)*cofactor -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp[BN254_Snarks], G1]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp[BN254_Snarks], G1]) {.inline.} = ## Clear the cofactor of BN254_Snarks G1 ## BN curves have a G1 cofactor of 1 so this is a no-op discard -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp2[BN254_Snarks], G2]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp2[BN254_Snarks], G2]) {.inline.} = ## Clear the cofactor of BN254_Snarks G2 # Endomorphism acceleration cannot be used if cofactor is not cleared P.scalarMulGeneric(Cofactor_Eff_BN254_Snarks_G2) @@ -145,7 +145,7 @@ func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp2[BN254_Snarks], G2]) {.inl # BN G1 # ------------------------------------------------------------ -func clearCofactorFast*(P: var ECP_ShortW[Fp[BN254_Snarks], G1]) {.inline.} = +func clearCofactorFast*(P: var EC_ShortW[Fp[BN254_Snarks], G1]) {.inline.} = ## Clear the cofactor of BN254_Snarks G1 ## BN curves have a prime order r hence all points on curve are in G1 ## Hence this is a no-op @@ -157,7 +157,7 @@ func clearCofactorFast*(P: var ECP_ShortW[Fp[BN254_Snarks], G1]) {.inline.} = # Implementation # Fuentes-Castaneda et al, "Fast Hashing to G2 on Pairing-Friendly Curves", https://doi.org/10.1007/978-3-642-28496-0_25* -func clearCofactorFast*(P: var ECP_ShortW[Fp2[BN254_Snarks], G2]) {.inline.} = +func clearCofactorFast*(P: var EC_ShortW[Fp2[BN254_Snarks], G2]) {.inline.} = ## Clear the cofactor of BN254_Snarks G2 ## Optimized using endomorphisms ## P' → [x]P + [3x]ψ(P) + [x]ψ²(P) + ψ³(P) @@ -179,7 +179,7 @@ func clearCofactorFast*(P: var ECP_ShortW[Fp2[BN254_Snarks], G2]) {.inline.} = # # ############################################################ -func isInSubgroup*(P: ECP_ShortW[Fp[BN254_Snarks], G1]): SecretBool {.inline.} = +func isInSubgroup*(P: EC_ShortW[Fp[BN254_Snarks], G1]): SecretBool {.inline.} = ## Returns true if P is in G1 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. @@ -188,7 +188,7 @@ func isInSubgroup*(P: ECP_ShortW[Fp[BN254_Snarks], G1]): SecretBool {.inline.} = ## Warning ⚠: Assumes that P is on curve return CtTrue -func isInSubgroup*(P: ECP_ShortW_Jac[Fp2[BN254_Snarks], G2] or ECP_ShortW_Prj[Fp2[BN254_Snarks], G2]): SecretBool = +func isInSubgroup*(P: EC_ShortW_Jac[Fp2[BN254_Snarks], G2] or EC_ShortW_Prj[Fp2[BN254_Snarks], G2]): SecretBool = ## Returns true if P is in G2 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. @@ -216,12 +216,12 @@ func isInSubgroup*(P: ECP_ShortW_Jac[Fp2[BN254_Snarks], G2] or ECP_ShortW_Prj[Fp return t0 == t1 -func isInSubgroup*(P: ECP_ShortW_Aff[Fp2[BN254_Snarks], G2]): SecretBool = +func isInSubgroup*(P: EC_ShortW_Aff[Fp2[BN254_Snarks], G2]): SecretBool = ## Returns true if P is in 𝔾2 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. ## ## Warning ⚠: Assumes that P is on curve - var t{.noInit.}: ECP_ShortW_Jac[Fp2[BN254_Snarks], G2] + var t{.noInit.}: EC_ShortW_Jac[Fp2[BN254_Snarks], G2] t.fromAffine(P) return t.isInSubgroup() diff --git a/constantine/named/constants/bw6_761_subgroups.nim b/constantine/named/constants/bw6_761_subgroups.nim index 083def590..7e29fed06 100644 --- a/constantine/named/constants/bw6_761_subgroups.nim +++ b/constantine/named/constants/bw6_761_subgroups.nim @@ -30,11 +30,11 @@ const Cofactor_Eff_BW6_761_G1 = BigInt[384].fromHex"0xad1972339049ce762c77d5ac34 const Cofactor_Eff_BW6_761_G2 = BigInt[384].fromHex"0xad1972339049ce762c77d5ac34cb12efc856a0853c9db94cc61c554757551c0c832ba4061000003b3de580000000007c" ## P -> (103([u³]P) − 83([u²]P) − 143([u]P) + 27P) + ψ(7([u²]P) − 117([u]P) − 109P) -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp[BW6_761], G1]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp[BW6_761], G1]) {.inline.} = ## Clear the cofactor of BW6_761 G1 P.scalarMulGeneric(Cofactor_Eff_BW6_761_G1) -func clearCofactorReference*(P: var ECP_ShortW_Prj[Fp[BW6_761], G2]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW_Prj[Fp[BW6_761], G2]) {.inline.} = ## Clear the cofactor of BW6_761 G2 # Endomorphism acceleration cannot be used if cofactor is not cleared P.scalarMulGeneric(Cofactor_Eff_BW6_761_G2) diff --git a/constantine/named/constants/pallas_subgroups.nim b/constantine/named/constants/pallas_subgroups.nim index 6881bce0a..1e69d5332 100644 --- a/constantine/named/constants/pallas_subgroups.nim +++ b/constantine/named/constants/pallas_subgroups.nim @@ -19,7 +19,7 @@ import # # ############################################################ -func clearCofactorReference*(P: var ECP_ShortW[Fp[Pallas], G1]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW[Fp[Pallas], G1]) {.inline.} = ## Clear the cofactor of Pallas G1 ## The Pasta curves have a prime-order group so this is a no-op discard @@ -30,7 +30,7 @@ func clearCofactorReference*(P: var ECP_ShortW[Fp[Pallas], G1]) {.inline.} = # # ############################################################ -func isInSubgroup*(P: ECP_ShortW[Fp[Pallas], G1]): SecretBool {.inline.} = +func isInSubgroup*(P: EC_ShortW[Fp[Pallas], G1]): SecretBool {.inline.} = ## Returns true if P is in G1 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. diff --git a/constantine/named/constants/secp256k1_subgroups.nim b/constantine/named/constants/secp256k1_subgroups.nim index ec31f4f58..7a6eaa7ef 100644 --- a/constantine/named/constants/secp256k1_subgroups.nim +++ b/constantine/named/constants/secp256k1_subgroups.nim @@ -19,7 +19,7 @@ import # # ############################################################ -func clearCofactorReference*(P: var ECP_ShortW[Fp[Secp256k1], G1]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW[Fp[Secp256k1], G1]) {.inline.} = ## Clear the cofactor of Secp256k1 ## The secp256k1 curve has a prime-order group so this is a no-op discard @@ -30,7 +30,7 @@ func clearCofactorReference*(P: var ECP_ShortW[Fp[Secp256k1], G1]) {.inline.} = # # ############################################################ -func isInSubgroup*(P: ECP_ShortW[Fp[Secp256k1], G1]): SecretBool {.inline.} = +func isInSubgroup*(P: EC_ShortW[Fp[Secp256k1], G1]): SecretBool {.inline.} = ## This is a no-op, all points on curve are in the correct subgroup. ## ## Warning ⚠: Assumes that P is on curve diff --git a/constantine/named/constants/vesta_subgroups.nim b/constantine/named/constants/vesta_subgroups.nim index ea041be83..9ef8606d1 100644 --- a/constantine/named/constants/vesta_subgroups.nim +++ b/constantine/named/constants/vesta_subgroups.nim @@ -19,7 +19,7 @@ import # # ############################################################ -func clearCofactorReference*(P: var ECP_ShortW[Fp[Vesta], G1]) {.inline.} = +func clearCofactorReference*(P: var EC_ShortW[Fp[Vesta], G1]) {.inline.} = ## Clear the cofactor of Vesta G1 ## The Pasta curves have a prime-order group so this is a no-op discard @@ -30,7 +30,7 @@ func clearCofactorReference*(P: var ECP_ShortW[Fp[Vesta], G1]) {.inline.} = # # ############################################################ -func isInSubgroup*(P: ECP_ShortW[Fp[Vesta], G1]): SecretBool {.inline.} = +func isInSubgroup*(P: EC_ShortW[Fp[Vesta], G1]): SecretBool {.inline.} = ## Returns true if P is in G1 subgroup, i.e. P is a point of order r. ## A point may be on a curve but not on the prime order r subgroup. ## Not checking subgroup exposes a protocol to small subgroup attacks. diff --git a/constantine/named/deriv/derive_constants.nim b/constantine/named/deriv/derive_constants.nim index a151c355d..f0aeac074 100644 --- a/constantine/named/deriv/derive_constants.nim +++ b/constantine/named/deriv/derive_constants.nim @@ -46,7 +46,7 @@ macro genDerivedConstants*(mode: static DerivedConstantMode): untyped = let ff = if mode == kModulus: "_Fp" else: "_Fr" - for curveSym in low(Curve) .. high(Curve): + for curveSym in low(Algebra) .. high(Algebra): let curve = $curveSym let M = if mode == kModulus: bindSym(curve & "_Modulus") else: bindSym(curve & "_Order") diff --git a/constantine/named/deriv/parser_curves.nim b/constantine/named/deriv/parser_curves.nim index bd99b492a..be0d68217 100644 --- a/constantine/named/deriv/parser_curves.nim +++ b/constantine/named/deriv/parser_curves.nim @@ -9,12 +9,12 @@ import # Standard library std/macros, # Internal - constantine/platforms/type_ff, constantine/math/io/[io_bigints, io_fields], ../config_fields_and_curves, + ../properties_fields, ./parser_fields -export CurveFamily, Curve, SexticTwist +export Algebra, CurveFamily, SexticTwist # ############################################################ # diff --git a/constantine/named/deriv/parser_fields.nim b/constantine/named/deriv/parser_fields.nim index ea3dd6d54..e21be82a0 100644 --- a/constantine/named/deriv/parser_fields.nim +++ b/constantine/named/deriv/parser_fields.nim @@ -303,9 +303,9 @@ proc genFieldsConstants(defs: seq[CurveParams]): NimNode = result = newStmtList() # type Curve = enum - let Curve = ident"Curve" + let Algebra = ident"Algebra" result.add newEnum( - name = Curve, + name = Algebra, fields = Curves, public = true, pure = false diff --git a/constantine/named/properties_curves.nim b/constantine/named/properties_curves.nim index c24724a7d..0ad8621c3 100644 --- a/constantine/named/properties_curves.nim +++ b/constantine/named/properties_curves.nim @@ -12,7 +12,7 @@ import ./config_fields_and_curves, ./deriv/parser_curves -export CurveFamily, Curve, SexticTwist +export Algebra, CurveFamily, SexticTwist # ############################################################ # @@ -22,58 +22,62 @@ export CurveFamily, Curve, SexticTwist {.experimental: "dynamicBindSym".} -template getCurveBitwidth*(C: Curve): int = - ## Returns the number of bits taken by the curve modulus - CurveBitWidth[C] - -macro getCurveOrder*(C: static Curve): untyped = - ## Get the curve order `r` - ## i.e. the number of points on the elliptic curve - result = bindSym($C & "_Order") - -macro getCurveOrderBitwidth*(C: static Curve): untyped = - ## Get the curve order `r` - ## i.e. the number of points on the elliptic curve - result = nnkDotExpr.newTree( - getAST(getCurveOrder(C)), - ident"bits" - ) - -template family*(C: Curve): CurveFamily = - CurveFamilies[C] - -macro getEquationForm*(C: static Curve): untyped = +type FieldKind* = enum + kBaseField + kScalarField + +template getBigInt*(Name: static Algebra, kind: static FieldKind): untyped = + # Workaround: + # in `ptr UncheckedArray[BigInt[EC.getScalarField().bits()]] + # EC.getScalarField is not accepted by the compiler + # + # and `ptr UncheckedArray[BigInt[Fr[EC.F.Name].bits]]` gets undeclared field: 'Name' + when kind == kBaseField: + BigInt[Fp[Name].bits()] + else: + BigInt[Fr[Name].bits()] + +template getField*(Name: static Algebra, kind: static FieldKind): untyped = + when kind == kBaseField: + Fp[Name] + else: + Fr[Name] + +template family*(Name: Algebra): CurveFamily = + CurveFamilies[Name] + +macro getEquationForm*(Name: static Algebra): untyped = ## Returns the equation form ## (ShortWeierstrass, Montgomery, Twisted Edwards, Weierstrass, ...) - result = bindSym($C & "_equation_form") + result = bindSym($Name & "_equation_form") -macro getCoefA*(C: static Curve): untyped = +macro getCoefA*(Name: static Algebra): untyped = ## Returns the A coefficient of the curve ## The return type is polymorphic, it can be an int ## or a bigInt depending on the curve - result = bindSym($C & "_coef_A") + result = bindSym($Name & "_coef_A") -macro getCoefB*(C: static Curve): untyped = +macro getCoefB*(Name: static Algebra): untyped = ## Returns the B coefficient of the curve ## The return type is polymorphic, it can be an int ## or a bigInt depending on the curve - result = bindSym($C & "_coef_B") + result = bindSym($Name & "_coef_B") -macro getCoefD*(C: static Curve): untyped = +macro getCoefD*(Name: static Algebra): untyped = ## Returns the D coefficient of the curve ## The return type is polymorphic, it can be an int ## or a bigInt depending on the curve - result = bindSym($C & "_coef_D") + result = bindSym($Name & "_coef_D") -macro getNonResidueFp*(C: static Curve): untyped = +macro getNonResidueFp*(Name: static Algebra): untyped = ## Returns the tower extension (and twist) non-residue for 𝔽p ## Depending on the curve it might be: ## - not a square (quadratic non-residue to construct Fp2) ## - not a cube (cubic non-residue to construct Fp3) ## - neither a square or cube (sextic non-residue to construct Fp2, Fp3 or Fp6) - result = bindSym($C & "_nonresidue_fp") + result = bindSym($Name & "_nonresidue_fp") -macro getNonResidueFp2*(C: static Curve): untyped = +macro getNonResidueFp2*(Name: static Algebra): untyped = ## Returns the tower extension (and twist) non-residue for 𝔽p² ## Depending on the curve it might be: ## - not a square (quadratic non-residue to construct Fp4) @@ -85,24 +89,24 @@ macro getNonResidueFp2*(C: static Curve): untyped = ## with 𝑗 choosen for 𝑗² - QNR_Fp == 0 ## i.e. if -1 is chosen as a quadratic non-residue 𝑗 = √-1 ## if -2 is chosen as a quadratic non-residue 𝑗 = √-2 - result = bindSym($C & "_nonresidue_fp2") + result = bindSym($Name & "_nonresidue_fp2") -macro getEmbeddingDegree*(C: static Curve): untyped = +macro getEmbeddingDegree*(Name: static Algebra): untyped = ## Returns the prime embedding degree, ## i.e. the smallest k such that r|𝑝^𝑘−1 ## equivalently 𝑝^𝑘 ≡ 1 (mod r) ## with r the curve order and p its field modulus - result = bindSym($C & "_embedding_degree") + result = bindSym($Name & "_embedding_degree") -macro getSexticTwist*(C: static Curve): untyped = +macro getSexticTwist*(Name: static Algebra): untyped = ## Returns if D-Twist or M-Twist - result = bindSym($C & "_sexticTwist") + result = bindSym($Name & "_sexticTwist") -macro getGT*(C: static Curve): untyped = +macro getGT*(Name: static Algebra): untyped = ## Returns the GT extension field template gt(embdegree: static int): untyped = `Fp embdegree` result = quote do: - `gt`(getEmbeddingDegree(Curve(`C`)))[Curve(`C`)] + `gt`(getEmbeddingDegree(Algebra(`Name`)))[Algebra(`Name`)] diff --git a/constantine/named/properties_fields.nim b/constantine/named/properties_fields.nim index 0c94942b8..a1c1f4896 100644 --- a/constantine/named/properties_fields.nim +++ b/constantine/named/properties_fields.nim @@ -10,11 +10,65 @@ import # Standard library std/macros, # Internal - ../platforms/[abstractions, type_ff], + ../platforms/abstractions, ./config_fields_and_curves, ./deriv/derive_constants -export Curve, type_ff +export Algebra + +# ############################################################ +# +# Field types +# +# ############################################################ + +template matchingBigInt*(Name: static Algebra): untyped = + ## BigInt type necessary to store the prime field Fp + # Workaround: https://github.com/nim-lang/Nim/issues/16774 + # as we cannot do array accesses in type section. + # Due to generic sandwiches, it must be exported. + BigInt[CurveBitWidth[Name]] + +template matchingOrderBigInt*(Name: static Algebra): untyped = + ## BigInt type necessary to store the scalar field Fr + # Workaround: https://github.com/nim-lang/Nim/issues/16774 + # as we cannot do array accesses in type section. + # Due to generic sandwiches, it must be exported. + BigInt[CurveOrderBitWidth[Name]] + +type + Fp*[Name: static Algebra] = object + ## All operations on a Fp field are modulo P + ## P being the prime modulus of the Curve C + ## Internally, data is stored in Montgomery n-residue form + ## with the magic constant chosen for convenient division (a power of 2 depending on P bitsize) + # TODO, pseudo mersenne primes like 2²⁵⁵-19 have very fast modular reduction + # and don't need Montgomery representation + mres*: matchingBigInt(Name) + + Fr*[Name: static Algebra] = object + ## All operations on a field are modulo `r` + ## `r` being the prime curve order or subgroup order + ## Internally, data is stored in Montgomery n-residue form + ## with the magic constant chosen for convenient division (a power of 2 depending on P bitsize) + mres*: matchingOrderBigInt(Name) + + FF*[Name: static Algebra] = Fp[Name] or Fr[Name] + +debug: + # Those MUST not be enabled in production to avoiding the compiler auto-conversion and printing SecretWord by mistake, for example in crash logs. + + func `$`*[Name: static Algebra](a: Fp[Name]): string = + result = "Fp[" & $Name + result.add "](" + result.add $a.mres + result.add ')' + + func `$`*[Name: static Algebra](a: Fr[Name]): string = + result = "Fr[" & $Name + result.add "](" + result.add $a.mres + result.add ')' # ############################################################ # @@ -24,32 +78,47 @@ export Curve, type_ff {.experimental: "dynamicBindSym".} -export matchingBigInt -export matchingOrderBigInt +macro baseFieldModulus(Name: static Algebra): untyped = + result = bindSym($Name & "_Modulus") -macro Mod*(C: static Curve): untyped = - ## Get the Modulus associated to a curve - result = bindSym($C & "_Modulus") +macro scalarFieldModulus(Name: static Algebra): untyped = + result = bindSym($Name & "_Order") -template matchingLimbs2x*(C: Curve): untyped = - const N2 = wordsRequired(CurveBitWidth[C]) * 2 # TODO upstream, not precomputing N2 breaks semcheck +template getModulus*[Name: static Algebra](F: type FF[Name]): untyped = + # We use a template to ensure the caller directly reads + # the data from ROM, and reduce chances of Nim duplicating the constant. + # Also `F is Fp` has issues in macros + when F is Fp: + baseFieldModulus(Name) + else: + scalarFieldModulus(Name) + +template getBigInt*[Name: static Algebra](T: type FF[Name]): untyped = + ## Get the underlying BigInt type. + typeof(default(T).mres) + +func bits*[Name: static Algebra](T: type FF[Name]): static int = + T.getBigInt().bits + +template getLimbs2x*(Name: static Algebra): typedesc = + const N2 = wordsRequired(CurveBitWidth[Name]) * 2 # TODO upstream, not precomputing N2 breaks semcheck array[N2, SecretWord] # TODO upstream, using Limbs[N2] breaks semcheck -func has_P_3mod4_primeModulus*(C: static Curve): static bool = +func has_P_3mod4_primeModulus*(Name: static Algebra): static bool = ## Returns true iff p ≡ 3 (mod 4) - (BaseType(C.Mod.limbs[0]) and 3) == 3 + (BaseType(Name.baseFieldModulus().limbs[0]) and 3) == 3 -func has_P_5mod8_primeModulus*(C: static Curve): static bool = +func has_P_5mod8_primeModulus*(Name: static Algebra): static bool = ## Returns true iff p ≡ 5 (mod 8) - (BaseType(C.Mod.limbs[0]) and 7) == 5 + (BaseType(Name.baseFieldModulus().limbs[0]) and 7) == 5 -func has_P_9mod16_primeModulus*(C: static Curve): static bool = +func has_P_9mod16_primeModulus*(Name: static Algebra): static bool = ## Returns true iff p ≡ 9 (mod 16) - (BaseType(C.Mod.limbs[0]) and 15) == 9 + (BaseType(Name.baseFieldModulus().limbs[0]) and 15) == 9 -func has_Psquare_9mod16_primePower*(C: static Curve): static bool = +func has_Psquare_9mod16_primePower*(Name: static Algebra): static bool = ## Returns true iff p² ≡ 9 (mod 16) - ((BaseType(C.Mod.limbs[0]) * BaseType(C.Mod.limbs[0])) and 15) == 9 + ((BaseType(Name.baseFieldModulus().limbs[0]) * BaseType(Name.baseFieldModulus().limbs[0])) and 15) == 9 # ############################################################ # @@ -63,7 +132,7 @@ genDerivedConstants(kOrder) proc bindConstant(ff: NimNode, property: string): NimNode = # Need to workaround https://github.com/nim-lang/Nim/issues/14021 - # which prevents checking if a type FF[C] = Fp[C] or Fr[C] + # which prevents checking if a type FF[Name] = Fp[Name] or Fr[Name] # was instantiated with Fp or Fr. # getTypeInst only returns FF and sameType doesn't work. # so quote do + when checks. @@ -75,7 +144,7 @@ proc bindConstant(ff: NimNode, property: string): NimNode = if T[1].kind == nnkBracketExpr: # typedesc[Fp[BLS12_381]] as used internally # doAssert T[1][0].eqIdent"Fp" or T[1][0].eqIdent"Fr", "Found ident: '" & $T[1][0] & "' instead of 'Fp' or 'Fr'" T[1][1].expectKind(nnkIntLit) # static enum are ints in the VM - $Curve(T[1][1].intVal) + $Algebra(T[1][1].intVal) else: # typedesc[bls12381_fp] alias as used for C exports let T1 = getTypeInst(T[1].getImpl()[2]) if T1.kind != nnkBracketExpr or @@ -85,7 +154,7 @@ proc bindConstant(ff: NimNode, property: string): NimNode = echo getTypeInst(T1).treerepr() error "getTypeInst didn't return the full instantiation." & " Dealing with types in macros is hard, complain at https://github.com/nim-lang/RFCs/issues/44" - $Curve(T1[1].intVal) + $Algebra(T1[1].intVal) let curve_fp = bindSym(curve & "_Fp_" & property) let curve_fr = bindSym(curve & "_Fr_" & property) @@ -97,12 +166,6 @@ proc bindConstant(ff: NimNode, property: string): NimNode = else: {.error: "Unreachable, received type: " & $`ff`.} -template fieldMod*(Field: type FF): auto = - when Field is Fp: - Mod(Field.C) - else: - getCurveOrder(Field.C) - macro getSpareBits*(ff: type FF): untyped = ## Returns the number of extra bits ## in the modulus M representation. @@ -161,7 +224,7 @@ macro getPrimeMinus5div8_BE*(ff: type FF): untyped = # ############################################################ macro debugConsts(): untyped {.used.} = - let curves = bindSym("Curve") + let curves = bindSym("Algebra") let E = curves.getImpl[2] result = newStmtList() @@ -173,7 +236,7 @@ macro debugConsts(): untyped {.used.} = let negInvModWord = bindSym(curveName & "_Fp_NegInvModWord") result.add quote do: - echo "Curve ", `curveName`,':' + echo "Algebra ", `curveName`,':' echo " Field Modulus: ", `modulus` echo " Montgomery R² (mod P): ", `r2modp` echo " Montgomery -1/P[0] (mod 2^", WordBitWidth, "): ", `negInvModWord` diff --git a/constantine/named/zoo_constants.nim b/constantine/named/zoo_constants.nim index 4d8aebe79..c3e005919 100644 --- a/constantine/named/zoo_constants.nim +++ b/constantine/named/zoo_constants.nim @@ -17,20 +17,20 @@ import {.experimental: "dynamicBindSym".} -macro getCoefB_G2*(C: static Curve): untyped = +macro getCoefB_G2*(Name: static Algebra): untyped = ## A pairing curve has the following equation on G1 ## y² = x³ + b ## and on G2 ## y² = x³ + b/µ (D-Twist) ## y² = x³ + b*µ (M-Twist) ## with µ the non-residue (sextic non-residue with a sextic twist) - return bindSym($C & "_coefB_G2") + return bindSym($Name & "_coefB_G2") -macro getCoefB_G2_times_3*(C: static Curve): untyped = +macro getCoefB_G2_times_3*(Name: static Algebra): untyped = ## A pairing curve has the following equation on G1 ## y² = x³ + b ## and on G2 ## y² = x³ + b/µ (D-Twist) ## y² = x³ + b*µ (M-Twist) ## with µ the non-residue (sextic non-residue with a sextic twist) - return bindSym($C & "_coefB_G2_times_3") + return bindSym($Name & "_coefB_G2_times_3") diff --git a/constantine/named/zoo_endomorphisms.nim b/constantine/named/zoo_endomorphisms.nim index e1dccd363..f0251c6db 100644 --- a/constantine/named/zoo_endomorphisms.nim +++ b/constantine/named/zoo_endomorphisms.nim @@ -20,27 +20,27 @@ import {.experimental: "dynamicBindSym".} -macro dispatch(C: static Curve, tag: static string, G: static string): untyped = - result = bindSym($C & "_" & tag & "_" & G) +macro dispatch(Name: static Algebra, tag: static string, G: static string): untyped = + result = bindSym($Name & "_" & tag & "_" & G) template babai*(F: typedesc[Fp or Fp2]): untyped = ## Return the GLV Babai roundings vector const G = if F is Fp: "G1" else: "G2" - dispatch(F.C, "Babai", G) + dispatch(F.Name, "Babai", G) template lattice*(F: typedesc[Fp or Fp2]): untyped = ## Returns the GLV Decomposition Lattice const G = if F is Fp: "G1" else: "G2" - dispatch(F.C, "Lattice", G) + dispatch(F.Name, "Lattice", G) -macro getCubicRootOfUnity_mod_p*(C: static Curve): untyped = +macro getCubicRootOfUnity_mod_p*(Name: static Algebra): untyped = ## Get a non-trivial cubic root of unity (mod p) with p the prime field - result = bindSym($C & "_cubicRootOfUnity_mod_p") + result = bindSym($Name & "_cubicRootOfUnity_mod_p") -func hasEndomorphismAcceleration*(C: static Curve): bool = - C in { +func hasEndomorphismAcceleration*(Name: static Algebra): bool = + Name in { BN254_Nogami, BN254_Snarks, BLS12_377, diff --git a/constantine/named/zoo_frobenius.nim b/constantine/named/zoo_frobenius.nim index b4160ef41..65445a1ee 100644 --- a/constantine/named/zoo_frobenius.nim +++ b/constantine/named/zoo_frobenius.nim @@ -17,7 +17,7 @@ import {.experimental: "dynamicBindSym".} -macro frobMapConst*(C: static Curve, coef, p_pow: static int): untyped = +macro frobMapConst*(Name: static Algebra, coef, p_pow: static int): untyped = ## Access the field Frobenius map a -> a^(p^p_pow) ## Call with ## frobMapConst(Curve, coef, p_pow) @@ -25,11 +25,11 @@ macro frobMapConst*(C: static Curve, coef, p_pow: static int): untyped = ## With pow the return nnkBracketExpr.newTree( nnkBracketExpr.newTree( - bindSym($C & "_FrobeniusMapCoefficients"), + bindSym($Name & "_FrobeniusMapCoefficients"), newLit(p_pow-1) ), newLit coef ) -macro frobPsiConst*(C: static Curve, psipow, coefpow: static int): untyped = - return bindSym($C & "_FrobeniusPsi_psi" & $psipow & "_coef" & $coefpow) +macro frobPsiConst*(Name: static Algebra, psipow, coefpow: static int): untyped = + return bindSym($Name & "_FrobeniusPsi_psi" & $psipow & "_coef" & $coefpow) diff --git a/constantine/named/zoo_generators.nim b/constantine/named/zoo_generators.nim index 8eea251be..d462bf6af 100644 --- a/constantine/named/zoo_generators.nim +++ b/constantine/named/zoo_generators.nim @@ -16,10 +16,10 @@ import {.experimental: "dynamicbindsym".} -macro getGenerator*(C: static Curve, subgroup: static string = ""): untyped = +macro getGenerator*(Name: static Algebra, subgroup: static string = ""): untyped = ## Returns the curve subgroup generator. ## Pairing-friendly curves expect G1 or G2 if subgroup == "": - return bindSym($C & "_generator") + return bindSym($Name & "_generator") else: - return bindSym($C & "_generator_" & subgroup) + return bindSym($Name & "_generator_" & subgroup) diff --git a/constantine/named/zoo_hash_to_curve.nim b/constantine/named/zoo_hash_to_curve.nim index e9c83bd83..d0b531d36 100644 --- a/constantine/named/zoo_hash_to_curve.nim +++ b/constantine/named/zoo_hash_to_curve.nim @@ -17,17 +17,17 @@ import {.experimental: "dynamicBindSym".} -macro h2cConst*(C: static Curve, mapping: untyped, group: static Subgroup, value: untyped): untyped = +macro h2cConst*(Name: static Algebra, mapping: untyped, group: static Subgroup, value: untyped): untyped = ## Get a Hash-to-Curve constant ## for mapping to a elliptic curve group (G1 or G2) - return bindSym($C & "_h2c_" & $mapping & "_" & $group & "_" & $value) + return bindSym($Name & "_h2c_" & $mapping & "_" & $group & "_" & $value) -macro h2cIsomapPoly*(C: static Curve, +macro h2cIsomapPoly*(Name: static Algebra, mapping: untyped, group: static Subgroup, value: untyped): untyped = ## Get an isogeny map polynomial ## for mapping to a elliptic curve group (G1 or G2) - return bindSym($C & "_h2c_" & + return bindSym($Name & "_h2c_" & $mapping & "_" & $group & "_isogeny_map_" & $value) diff --git a/constantine/named/zoo_pairings.nim b/constantine/named/zoo_pairings.nim index 1f8b47367..0f69fcdcf 100644 --- a/constantine/named/zoo_pairings.nim +++ b/constantine/named/zoo_pairings.nim @@ -17,8 +17,8 @@ import {.experimental: "dynamicBindSym".} -macro pairing*(C: static Curve, value: untyped): untyped = +macro pairing*(Name: static Algebra, value: untyped): untyped = ## Get pairing related constants - return bindSym($C & "_pairing_" & $value) + return bindSym($Name & "_pairing_" & $value) export cycl_exp_by_curve_param, cycl_exp_by_curve_param_div2, millerLoopAddchain, isInPairingSubgroup diff --git a/constantine/named/zoo_square_roots.nim b/constantine/named/zoo_square_roots.nim index 3ab2568f2..85e9ab77f 100644 --- a/constantine/named/zoo_square_roots.nim +++ b/constantine/named/zoo_square_roots.nim @@ -34,24 +34,24 @@ export pallas_sqrt, vesta_sqrt -func hasSqrtAddchain*(C: static Curve): static bool = - when C in {BLS12_381, BN254_Nogami, BN254_Snarks, BW6_761, Edwards25519}: +func hasSqrtAddchain*(Name: static Algebra): static bool = + when Name in {BLS12_381, BN254_Nogami, BN254_Snarks, BW6_761, Edwards25519}: true else: false {.experimental: "dynamicBindSym".} -macro tonelliShanks*(C: static Curve, value: untyped): untyped = +macro tonelliShanks*(Name: static Algebra, value: untyped): untyped = ## Get Square Root via Tonelli-Shanks related constants - return bindSym($C & "_TonelliShanks_" & $value) + return bindSym($Name & "_TonelliShanks_" & $value) -macro sqrtDlog*(C: static Curve, value: untyped): untyped = +macro sqrtDlog*(Name: static Algebra, value: untyped): untyped = ## Get Square Root via Square Root Dlog related constants - return bindSym($C & "_SqrtDlog_" & $value) + return bindSym($Name & "_SqrtDlog_" & $value) -func hasTonelliShanksAddchain*(C: static Curve): static bool = - when C in {Bandersnatch, Banderwagon, BLS12_377}: +func hasTonelliShanksAddchain*(Name: static Algebra): static bool = + when Name in {Bandersnatch, Banderwagon, BLS12_377}: true else: false diff --git a/constantine/named/zoo_square_roots_fp2.nim b/constantine/named/zoo_square_roots_fp2.nim index 78c50d453..f1799e4bb 100644 --- a/constantine/named/zoo_square_roots_fp2.nim +++ b/constantine/named/zoo_square_roots_fp2.nim @@ -14,6 +14,6 @@ import ./constants/bn254_snarks_sqrt_fp2 {.experimental: "dynamicBindSym".} -macro sqrt_fp2*(C: static Curve, value: untyped): untyped = +macro sqrt_fp2*(Name: static Algebra, value: untyped): untyped = ## Get square_root constants - return bindSym($C & "_sqrt_fp2_" & $value) + return bindSym($Name & "_sqrt_fp2_" & $value) diff --git a/constantine/named/zoo_subgroups.nim b/constantine/named/zoo_subgroups.nim index d5a135690..1be5a22d5 100644 --- a/constantine/named/zoo_subgroups.nim +++ b/constantine/named/zoo_subgroups.nim @@ -31,7 +31,7 @@ export func clearCofactor*[ECP](P: var ECP) {.inline.} = ## Clear the cofactor of a point on the curve ## From a point on the curve, returns a point on the subgroup of order r - when ECP.F.C in {BN254_Nogami, BN254_Snarks, BLS12_377, BLS12_381}: + when ECP.F.Name in {BN254_Nogami, BN254_Snarks, BLS12_377, BLS12_381}: P.clearCofactorFast() else: P.clearCofactorReference() diff --git a/constantine/platforms/static_for.nim b/constantine/platforms/static_for.nim index 7f5aa8f03..c83ba3630 100644 --- a/constantine/platforms/static_for.nim +++ b/constantine/platforms/static_for.nim @@ -63,7 +63,7 @@ macro staticFor*(ident: untyped{nkIdent}, choices: typed, body: untyped): untype choices result = newStmtList() - for choice in choices: + for i in 0 ..< choices.len: result.add nnkBlockStmt.newTree( - nnkAccQuoted.newTree(ident, ident("_"), choice), - body.replaceNodes(ident, choice)) + nnkAccQuoted.newTree(ident, ident("_"), ident($i)), + body.replaceNodes(ident, choices[i])) diff --git a/constantine/platforms/type_ff.nim b/constantine/platforms/type_ff.nim index 446efa840..8ce6fb327 100644 --- a/constantine/platforms/type_ff.nim +++ b/constantine/platforms/type_ff.nim @@ -11,47 +11,3 @@ import ../named/config_fields_and_curves # TODO: Keep internal and use bigint(Fp[Foo]) and bigint(Fr[Foo]) - -template matchingBigInt*(C: static Curve): untyped = - ## BigInt type necessary to store the prime field Fp - # Workaround: https://github.com/nim-lang/Nim/issues/16774 - BigInt[CurveBitWidth[C]] - -template matchingOrderBigInt*(C: static Curve): untyped = - ## BigInt type necessary to store the scalar field Fr - # Workaround: https://github.com/nim-lang/Nim/issues/16774 - BigInt[CurveOrderBitWidth[C]] - -type - Fp*[C: static Curve] = object - ## All operations on a Fp field are modulo P - ## P being the prime modulus of the Curve C - ## Internally, data is stored in Montgomery n-residue form - ## with the magic constant chosen for convenient division (a power of 2 depending on P bitsize) - # TODO, pseudo mersenne primes like 2²⁵⁵-19 have very fast modular reduction - # and don't need Montgomery representation - mres*: matchingBigInt(C) - - Fr*[C: static Curve] = object - ## All operations on a field are modulo `r` - ## `r` being the prime curve order or subgroup order - ## Internally, data is stored in Montgomery n-residue form - ## with the magic constant chosen for convenient division (a power of 2 depending on P bitsize) - mres*: matchingOrderBigInt(C) - - FF*[C: static Curve] = Fp[C] or Fr[C] - -debug: - # Those MUST not be enabled in production to avoiding the compiler auto-conversion and printing SecretWord by mistake, for example in crash logs. - - func `$`*[C: static Curve](a: Fp[C]): string = - result = "Fp[" & $C - result.add "](" - result.add $a.mres - result.add ')' - - func `$`*[C: static Curve](a: Fr[C]): string = - result = "Fr[" & $C - result.add "](" - result.add $a.mres - result.add ')' diff --git a/constantine/serialization/codecs_banderwagon.nim b/constantine/serialization/codecs_banderwagon.nim index 4c4bbd274..3a7745871 100644 --- a/constantine/serialization/codecs_banderwagon.nim +++ b/constantine/serialization/codecs_banderwagon.nim @@ -32,13 +32,13 @@ import # Input validation # ------------------------------------------------------------------------------------------------ -func validate_scalar*(scalar: matchingOrderBigInt(Banderwagon)): CttCodecScalarStatus = +func validate_scalar*(scalar: Fr[Banderwagon].getBigInt()): CttCodecScalarStatus = ## Validate a scalar ## Regarding timing attacks, this will leak information ## if the scalar is 0 or larger than the curve order. if scalar.isZero().bool(): return cttCodecScalar_Zero - if bool(scalar >= Banderwagon.getCurveOrder()): + if bool(scalar >= Fr[Banderwagon].getModulus()): return cttCodecScalar_ScalarLargerThanCurveOrder return cttCodecScalar_Success @@ -46,7 +46,7 @@ func validate_scalar*(scalar: matchingOrderBigInt(Banderwagon)): CttCodecScalarS func serialize_scalar*( dst: var array[32, byte], - scalar: matchingOrderBigInt(Banderwagon), + scalar: Fr[Banderwagon].getBigInt(), order: static Endianness = bigEndian): CttCodecScalarStatus {.discardable.} = ## Serialize a scalar ## Returns cttCodecScalar_Success if successful @@ -61,7 +61,7 @@ func serialize_fr*( ## Returns cttCodecScalar_Success if successful return dst.serialize_scalar(scalar.toBig(), order) -func deserialize_scalar*(dst: var matchingOrderBigInt(Banderwagon), src: array[32, byte], order: static Endianness = bigEndian): CttCodecScalarStatus = +func deserialize_scalar*(dst: var Fr[Banderwagon].getBigInt(), src: array[32, byte], order: static Endianness = bigEndian): CttCodecScalarStatus = ## Deserialize a scalar ## Also validates the scalar range ## @@ -87,7 +87,7 @@ func deserialize_fr*( scalar.unmarshal(src, order) getMont(dst.mres.limbs, scalar.limbs, - Fr[Banderwagon].fieldMod().limbs, + Fr[Banderwagon].getModulus().limbs, Fr[Banderwagon].getR2modP().limbs, Fr[Banderwagon].getNegInvModWord(), Fr[Banderwagon].getSpareBits()) @@ -101,7 +101,7 @@ func deserialize_fr*( ## ############################################################ -func serialize*(dst: var array[32, byte], P: ECP_TwEdwards_Aff[Fp[Banderwagon]]): CttCodecEccStatus {.discardable.} = +func serialize*(dst: var array[32, byte], P: EC_TwEdw_Aff[Fp[Banderwagon]]): CttCodecEccStatus {.discardable.} = ## Serialize a Banderwagon point(x, y) in the format ## ## serialize = bigEndian( sign(y) * x ) @@ -124,7 +124,7 @@ func serialize*(dst: var array[32, byte], P: ECP_TwEdwards_Aff[Fp[Banderwagon]]) dst.marshal(X, bigEndian) return cttCodecEcc_Success -func serialize*(dst: var array[32, byte], P: ECP_TwEdwards_Prj[Fp[Banderwagon]]): CttCodecEccStatus {.discardable.} = +func serialize*(dst: var array[32, byte], P: EC_TwEdw_Prj[Fp[Banderwagon]]): CttCodecEccStatus {.discardable.} = ## Serialize a Banderwagon point(x, y) in the format ## ## serialize = bigEndian( sign(y) * x ) @@ -136,12 +136,12 @@ func serialize*(dst: var array[32, byte], P: ECP_TwEdwards_Prj[Fp[Banderwagon]]) ## Spec: https://hackmd.io/@6iQDuIePQjyYBqDChYw_jg/BJBNcv9fq#Serialisation # Convert the projective points into affine format before encoding - var aff {.noInit.}: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var aff {.noInit.}: EC_TwEdw_Aff[Fp[Banderwagon]] aff.affine(P) return dst.serialize(aff) -func deserialize_unchecked_vartime*(dst: var ECP_TwEdwards_Aff[Fp[Banderwagon]], src: array[32, byte]): CttCodecEccStatus = +func deserialize_unchecked_vartime*(dst: var EC_TwEdw_Aff[Fp[Banderwagon]], src: array[32, byte]): CttCodecEccStatus = ## Deserialize a Banderwagon point (x, y) in format ## ## if y is not lexicographically largest @@ -164,10 +164,10 @@ func deserialize_unchecked_vartime*(dst: var ECP_TwEdwards_Aff[Fp[Banderwagon]], dst.setNeutral() return cttCodecEcc_PointAtInfinity - var t{.noInit.}: matchingBigInt(Banderwagon) + var t{.noInit.}: Fp[Banderwagon].getBigInt() t.unmarshal(src, bigEndian) - if bool(t >= Banderwagon.Mod()): + if bool(t >= Fp[Banderwagon].getModulus()): return cttCodecEcc_CoordinateGreaterThanOrEqualModulus var x{.noInit.}: Fp[Banderwagon] @@ -182,7 +182,7 @@ func deserialize_unchecked_vartime*(dst: var ECP_TwEdwards_Aff[Fp[Banderwagon]], return cttCodecEcc_Success -func deserialize_vartime*(dst: var ECP_TwEdwards_Aff[Fp[Banderwagon]], src: array[32, byte]): CttCodecEccStatus = +func deserialize_vartime*(dst: var EC_TwEdw_Aff[Fp[Banderwagon]], src: array[32, byte]): CttCodecEccStatus = ## Deserialize a Banderwagon point (x, y) in format ## ## Also checks if the point lies in the banderwagon scheme subgroup @@ -203,7 +203,7 @@ func deserialize_vartime*(dst: var ECP_TwEdwards_Aff[Fp[Banderwagon]], src: arra # Debugging # ------------------------------------------------------------------------------------------------ -func toHex*(P: ECP_TwEdwards_Aff[Fp[Banderwagon]], canonicalize: static bool = true, indent: static int = 0): string = +func toHex*(P: EC_TwEdw_Aff[Fp[Banderwagon]], canonicalize: static bool = true, indent: static int = 0): string = ## Stringify an elliptic curve point to Hex for Banderwagon ## (x, y) and (-x, -y) are in the same equivalence class for Banderwagon. ## By default, we negate the hex encoding if y is not the lexicographically largest. @@ -211,7 +211,7 @@ func toHex*(P: ECP_TwEdwards_Aff[Fp[Banderwagon]], canonicalize: static bool = t ## ## This is intended for debugging - var aff {.noInit.}: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var aff {.noInit.}: EC_TwEdw_Aff[Fp[Banderwagon]] aff = P const sp = spaces(indent) @@ -220,20 +220,20 @@ func toHex*(P: ECP_TwEdwards_Aff[Fp[Banderwagon]], canonicalize: static bool = t aff.x.cneg(not lexicographicallyLargest) aff.y.cneg(not lexicographicallyLargest) - result = sp & $ECP_TwEdwards_Aff[Fp[Banderwagon]] & "(\n" & sp & " x: " + result = sp & $EC_TwEdw_Aff[Fp[Banderwagon]] & "(\n" & sp & " x: " result.appendHex(aff.x) result &= ",\n" & sp & " y: " result.appendHex(aff.y) result &= "\n" & sp & ")" -func toHex*(P: ECP_TwEdwards_Prj[Fp[Banderwagon]], canonicalize: static bool = true, indent: static int = 0): string = +func toHex*(P: EC_TwEdw_Prj[Fp[Banderwagon]], canonicalize: static bool = true, indent: static int = 0): string = ## Stringify an elliptic curve point to Hex for Banderwagon ## (x, y) and (-x, -y) are in the same equivalence class for Banderwagon. ## By default, we negate the hex encoding if y is not the lexicographically largest. ## Pass `canonicalize` = false to get usual Twisted Edwards hex encoding. ## ## This is intended for debugging - var aff {.noInit.}: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var aff {.noInit.}: EC_TwEdw_Aff[Fp[Banderwagon]] aff.affine(P) return aff.toHex(canonicalize, indent) @@ -245,7 +245,7 @@ func toHex*(P: ECP_TwEdwards_Prj[Fp[Banderwagon]], canonicalize: static bool = t func serializeBatch_vartime*( dst: ptr UncheckedArray[array[32, byte]], - points: ptr UncheckedArray[ECP_TwEdwards_Prj[Fp[Banderwagon]]], + points: ptr UncheckedArray[EC_TwEdw_Prj[Fp[Banderwagon]]], N: int, ) : CttCodecEccStatus {.noInline.} = @@ -274,7 +274,7 @@ func serializeBatch_vartime*( func serializeBatchUncompressed_vartime*( dst: ptr UncheckedArray[array[64, byte]], - points: ptr UncheckedArray[ECP_TwEdwards_Prj[Fp[Banderwagon]]], + points: ptr UncheckedArray[EC_TwEdw_Prj[Fp[Banderwagon]]], N: int) : CttCodecEccStatus {.noInline.} = ## Batch Serialization of Banderwagon Points ## In uncompressed format @@ -309,12 +309,12 @@ func serializeBatchUncompressed_vartime*( func serializeBatchUncompressed_vartime*[N: static int]( dst: var array[N, array[64, byte]], - points: array[N, ECP_TwEdwards_Prj[Fp[Banderwagon]]]): CttCodecEccStatus {.inline.} = + points: array[N, EC_TwEdw_Prj[Fp[Banderwagon]]]): CttCodecEccStatus {.inline.} = return serializeBatchUncompressed_vartime(dst.asUnchecked(), points.asUnchecked(), N) func serializeBatch_vartime*[N: static int]( dst: var array[N, array[32, byte]], - points: array[N, ECP_TwEdwards_Prj[Fp[Banderwagon]]]): CttCodecEccStatus {.inline.} = + points: array[N, EC_TwEdw_Prj[Fp[Banderwagon]]]): CttCodecEccStatus {.inline.} = return serializeBatch_vartime(dst.asUnchecked(), points.asUnchecked(), N) ## ############################################################ @@ -323,7 +323,7 @@ func serializeBatch_vartime*[N: static int]( ## ## ############################################################ -func serializeUncompressed*(dst: var array[64, byte], P: ECP_TwEdwards_Aff[Fp[Banderwagon]]): CttCodecEccStatus = +func serializeUncompressed*(dst: var array[64, byte], P: EC_TwEdw_Aff[Fp[Banderwagon]]): CttCodecEccStatus = ## Serialize a Banderwagon point(x, y) in the format ## ## serialize = [ bigEndian( x ) , bigEndian( y ) ] @@ -340,7 +340,7 @@ func serializeUncompressed*(dst: var array[64, byte], P: ECP_TwEdwards_Aff[Fp[Ba return cttCodecEcc_Success -func deserializeUncompressed_unchecked*(dst: var ECP_TwEdwards_Aff[Fp[Banderwagon]], src: array[64, byte]): CttCodecEccStatus = +func deserializeUncompressed_unchecked*(dst: var EC_TwEdw_Aff[Fp[Banderwagon]], src: array[64, byte]): CttCodecEccStatus = ## Deserialize a Banderwagon point (x, y) in format ## Doesn't check if the point is in the banderwagon scheme subgroup ## Returns cttCodecEcc_Success if successful @@ -351,22 +351,22 @@ func deserializeUncompressed_unchecked*(dst: var ECP_TwEdwards_Aff[Fp[Banderwago xSerialized[i] = src[i] ySerialized[i] = src[i + 32] - var t{.noInit.}: matchingBigInt(Banderwagon) + var t{.noInit.}: Fp[Banderwagon].getBigInt() t.unmarshal(xSerialized, bigEndian) - if bool(t >= Banderwagon.Mod()): + if bool(t >= Fp[Banderwagon].getModulus()): return cttCodecEcc_CoordinateGreaterThanOrEqualModulus dst.x.fromBig(t) t.unmarshal(ySerialized, bigEndian) - if bool(t >= Banderwagon.Mod()): + if bool(t >= Fp[Banderwagon].getModulus()): return cttCodecEcc_CoordinateGreaterThanOrEqualModulus dst.y.fromBig(t) return cttCodecEcc_Success -func deserializeUncompressed*(dst: var ECP_TwEdwards_Aff[Fp[Banderwagon]], src: array[64, byte]): CttCodecEccStatus = +func deserializeUncompressed*(dst: var EC_TwEdw_Aff[Fp[Banderwagon]], src: array[64, byte]): CttCodecEccStatus = ## Deserialize a Banderwagon point (x, y) in format ## ## Also checks if the point lies in the banderwagon scheme subgroup diff --git a/constantine/serialization/codecs_bls12_381.nim b/constantine/serialization/codecs_bls12_381.nim index 30b115bbf..ca57cdb39 100644 --- a/constantine/serialization/codecs_bls12_381.nim +++ b/constantine/serialization/codecs_bls12_381.nim @@ -48,60 +48,54 @@ import constantine/math/io/[io_bigints, io_fields], ./codecs_status_codes -type - Scalar = matchingOrderBigInt(BLS12_381) - G1P = ECP_ShortW_Aff[Fp[BLS12_381], G1] - G2P = ECP_ShortW_Aff[Fp2[BLS12_381], G2] - - const pre = "ctt_bls12_381_" import ../zoo_exports # Input validation # ------------------------------------------------------------------------------------------------ -func validate_scalar*(scalar: Scalar): CttCodecScalarStatus {.libPrefix: pre.} = +func validate_scalar*(scalar: Fr[BLS12_381].getBigInt()): CttCodecScalarStatus {.libPrefix: pre.} = ## Validate a scalar ## Regarding timing attacks, this will leak information ## if the scalar is 0 or larger than the curve order. if scalar.isZero().bool(): return cttCodecScalar_Zero - if bool(scalar >= BLS12_381.getCurveOrder()): + if bool(scalar >= Fr[BLS12_381].getModulus()): return cttCodecScalar_ScalarLargerThanCurveOrder return cttCodecScalar_Success -func validate_g1*(g1Point: G1P): CttCodecEccStatus {.libPrefix: pre.} = +func validate_g1*(g1P: EC_ShortW_Aff[Fp[BLS12_381], G1]): CttCodecEccStatus {.libPrefix: pre.} = ## Validate a G1 point ## This is an expensive operation that can be cached - if g1Point.isNeutral().bool(): + if g1P.isNeutral().bool(): return cttCodecEcc_PointAtInfinity - if not isOnCurve(g1Point.x, g1Point.y, G1).bool(): + if not isOnCurve(g1P.x, g1P.y, G1).bool(): return cttCodecEcc_PointNotOnCurve - if not g1Point.isInSubgroup().bool(): + if not g1P.isInSubgroup().bool(): return cttCodecEcc_PointNotInSubgroup return cttCodecEcc_Success -func validate_g2*(g2Point: G2P): CttCodecEccStatus {.libPrefix: pre.} = +func validate_g2*(g2P: EC_ShortW_Aff[Fp2[BLS12_381], G2]): CttCodecEccStatus {.libPrefix: pre.} = ## Validate a G2 point. ## This is an expensive operation that can be cached - if g2Point.isNeutral().bool(): + if g2P.isNeutral().bool(): return cttCodecEcc_PointAtInfinity - if not isOnCurve(g2Point.x, g2Point.y, G2).bool(): + if not isOnCurve(g2P.x, g2P.y, G2).bool(): return cttCodecEcc_PointNotOnCurve - if not g2Point.isInSubgroup().bool(): + if not g2P.isInSubgroup().bool(): return cttCodecEcc_PointNotInSubgroup return cttCodecEcc_Success # Codecs # ------------------------------------------------------------------------------------------------ -func serialize_scalar*(dst: var array[32, byte], scalar: Scalar): CttCodecScalarStatus {.libPrefix: pre, discardable.} = +func serialize_scalar*(dst: var array[32, byte], scalar: Fr[BLS12_381].getBigInt()): CttCodecScalarStatus {.libPrefix: pre, discardable.} = ## Serialize a scalar ## Returns cttCodecScalar_Success if successful dst.marshal(scalar, bigEndian) return cttCodecScalar_Success -func deserialize_scalar*(dst: var Scalar, src: array[32, byte]): CttCodecScalarStatus {.libPrefix: pre.} = +func deserialize_scalar*(dst: var Fr[BLS12_381].getBigInt(), src: array[32, byte]): CttCodecScalarStatus {.libPrefix: pre.} = ## Deserialize a scalar ## Also validates the scalar range ## @@ -118,17 +112,17 @@ func deserialize_scalar*(dst: var Scalar, src: array[32, byte]): CttCodecScalarS return cttCodecScalar_Success -func serialize_g1_compressed*(dst: var array[48, byte], g1Point: G1P): CttCodecEccStatus {.libPrefix: pre, discardable.} = +func serialize_g1_compressed*(dst: var array[48, byte], g1P: EC_ShortW_Aff[Fp[BLS12_381], G1]): CttCodecEccStatus {.libPrefix: pre, discardable.} = ## Serialize a BLS12-381 G1 point in compressed (Zcash) format ## ## Returns cttCodecEcc_Success if successful - if g1Point.isNeutral().bool(): + if g1P.isNeutral().bool(): for i in 0 ..< dst.len: dst[i] = byte 0 dst[0] = byte 0b11000000 # Compressed + Infinity return cttCodecEcc_Success - dst.marshal(g1Point.x, bigEndian) + dst.marshal(g1P.x, bigEndian) # The curve equation has 2 solutions for y² = x³ + 4 with y unknown and x known # The lexicographically largest will have bit 381 set to 1 # (and bit 383 for the compressed representation) @@ -136,12 +130,12 @@ func serialize_g1_compressed*(dst: var array[48, byte], g1Point: G1P): CttCodecE # The field contains [0, p-1] hence lexicographically largest # are numbers greater or equal (p-1)/2 # https://github.com/zkcrypto/bls12_381/blob/0.7.0/src/fp.rs#L271-L277 - let lexicographicallyLargest = byte(g1Point.y.toBig() >= Fp[BLS12_381].getPrimeMinus1div2()) + let lexicographicallyLargest = byte(g1P.y.toBig() >= Fp[BLS12_381].getPrimeMinus1div2()) dst[0] = dst[0] or (0b10000000 or (lexicographicallyLargest shl 5)) return cttCodecEcc_Success -func deserialize_g1_compressed_unchecked*(dst: var G1P, src: array[48, byte]): CttCodecEccStatus {.libPrefix: pre.} = +func deserialize_g1_compressed_unchecked*(dst: var EC_ShortW_Aff[Fp[BLS12_381], G1], src: array[48, byte]): CttCodecEccStatus {.libPrefix: pre.} = ## Deserialize a BLS12-381 G1 point in compressed (Zcash) format. ## ## Warning ⚠: @@ -165,11 +159,11 @@ func deserialize_g1_compressed_unchecked*(dst: var G1P, src: array[48, byte]): C return cttCodecEcc_PointAtInfinity # General case - var t{.noInit.}: matchingBigInt(BLS12_381) + var t{.noInit.}: Fp[BLS12_381].getBigInt() t.unmarshal(src, bigEndian) t.limbs[t.limbs.len-1] = t.limbs[t.limbs.len-1] and (MaxWord shr 3) # The first 3 bytes contain metadata to mask out - if bool(t >= BLS12_381.Mod()): + if bool(t >= Fp[BLS12_381].getModulus()): return cttCodecEcc_CoordinateGreaterThanOrEqualModulus var x{.noInit.}: Fp[BLS12_381] @@ -185,7 +179,7 @@ func deserialize_g1_compressed_unchecked*(dst: var G1P, src: array[48, byte]): C return cttCodecEcc_Success -func deserialize_g1_compressed*(dst: var G1P, src: array[48, byte]): CttCodecEccStatus {.libPrefix: pre.} = +func deserialize_g1_compressed*(dst: var EC_ShortW_Aff[Fp[BLS12_381], G1], src: array[48, byte]): CttCodecEccStatus {.libPrefix: pre.} = ## Deserialize a BLS12-381 G1 point in compressed (Zcash) format ## This also validates the G1 point ## @@ -201,29 +195,29 @@ func deserialize_g1_compressed*(dst: var G1P, src: array[48, byte]): CttCodecEcc return cttCodecEcc_Success -func serialize_g2_compressed*(dst: var array[96, byte], g2Point: G2P): CttCodecEccStatus {.libPrefix: pre.} = +func serialize_g2_compressed*(dst: var array[96, byte], g2P: EC_ShortW_Aff[Fp2[BLS12_381], G2]): CttCodecEccStatus {.libPrefix: pre.} = ## Serialize a BLS12-381 G2 point in compressed (Zcash) format ## ## Returns cttCodecEcc_Success if successful - if g2Point.isNeutral().bool(): + if g2P.isNeutral().bool(): for i in 0 ..< dst.len: dst[i] = byte 0 dst[0] = byte 0b11000000 # Compressed + Infinity return cttCodecEcc_Success - dst.toOpenArray(0, 48-1).marshal(g2Point.x.c1, bigEndian) - dst.toOpenArray(48, 96-1).marshal(g2Point.x.c0, bigEndian) + dst.toOpenArray(0, 48-1).marshal(g2P.x.c1, bigEndian) + dst.toOpenArray(48, 96-1).marshal(g2P.x.c0, bigEndian) let isLexicographicallyLargest = - if g2Point.y.c1.isZero().bool(): - byte(g2Point.y.c0.toBig() >= Fp[BLS12_381].getPrimePlus1div2()) + if g2P.y.c1.isZero().bool(): + byte(g2P.y.c0.toBig() >= Fp[BLS12_381].getPrimePlus1div2()) else: - byte(g2Point.y.c1.toBig() >= Fp[BLS12_381].getPrimePlus1div2()) + byte(g2P.y.c1.toBig() >= Fp[BLS12_381].getPrimePlus1div2()) dst[0] = dst[0] or (byte 0b10000000 or (isLexicographicallyLargest shl 5)) return cttCodecEcc_Success -func deserialize_g2_compressed_unchecked*(dst: var G2P, src: array[96, byte]): CttCodecEccStatus {.libPrefix: pre.} = +func deserialize_g2_compressed_unchecked*(dst: var EC_ShortW_Aff[Fp2[BLS12_381], G2], src: array[96, byte]): CttCodecEccStatus {.libPrefix: pre.} = ## Deserialize a BLS12-381 G2 point in compressed (Zcash) format. ## ## Warning ⚠: @@ -247,18 +241,18 @@ func deserialize_g2_compressed_unchecked*(dst: var G2P, src: array[96, byte]): C return cttCodecEcc_PointAtInfinity # General case - var t{.noInit.}: matchingBigInt(BLS12_381) + var t{.noInit.}: Fp[BLS12_381].getBigInt() t.unmarshal(src.toOpenArray(0, 48-1), bigEndian) t.limbs[t.limbs.len-1] = t.limbs[t.limbs.len-1] and (MaxWord shr 3) # The first 3 bytes contain metadata to mask out - if bool(t >= BLS12_381.Mod()): + if bool(t >= Fp[BLS12_381].getModulus()): return cttCodecEcc_CoordinateGreaterThanOrEqualModulus var x{.noInit.}: Fp2[BLS12_381] x.c1.fromBig(t) t.unmarshal(src.toOpenArray(48, 96-1), bigEndian) - if bool(t >= BLS12_381.Mod()): + if bool(t >= Fp[BLS12_381].getModulus()): return cttCodecEcc_CoordinateGreaterThanOrEqualModulus x.c0.fromBig(t) @@ -278,7 +272,7 @@ func deserialize_g2_compressed_unchecked*(dst: var G2P, src: array[96, byte]): C return cttCodecEcc_Success -func deserialize_g2_compressed*(dst: var G2P, src: array[96, byte]): CttCodecEccStatus {.libPrefix: pre.} = +func deserialize_g2_compressed*(dst: var EC_ShortW_Aff[Fp2[BLS12_381], G2], src: array[96, byte]): CttCodecEccStatus {.libPrefix: pre.} = ## Deserialize a BLS12-381 G2 point in compressed (Zcash) format ## ## Returns cttCodecEcc_Success if successful diff --git a/constantine/signatures/bls_signatures.nim b/constantine/signatures/bls_signatures.nim index b645f4986..153f54e1f 100644 --- a/constantine/signatures/bls_signatures.nim +++ b/constantine/signatures/bls_signatures.nim @@ -41,9 +41,9 @@ func derivePubkey*[Pubkey, SecKey](pubkey: var Pubkey, seckey: SecKey) = ## 0 is INVALID const Group = Pubkey.G type Field = Pubkey.F - const EC = Field.C + const EC = Field.Name - var pk {.noInit.}: ECP_ShortW_Jac[Field, Group] + var pk {.noInit.}: EC_ShortW_Jac[Field, Group] pk.setGenerator() pk.scalarMul(seckey) pubkey.affine(pk) @@ -79,7 +79,7 @@ func coreSign*[Sig, SecKey]( ## - `message` is the message to hash ## - `domainSepTag` is the protocol domain separation tag (DST). - type ECP_Jac = ECP_ShortW_Jac[Sig.F, Sig.G] + type ECP_Jac = EC_ShortW_Jac[Sig.F, Sig.G] var sig {.noInit.}: ECP_Jac H.hashToCurve(k, sig, augmentation, message, domainSepTag) @@ -100,16 +100,16 @@ func coreVerify*[Pubkey, Sig]( ## This assumes that the PublicKey and Signatures ## have been pre-checked for non-infinity and being in the correct subgroup ## (likely on deserialization) - var Q {.noInit.}: ECP_ShortW_Aff[Sig.F, Sig.G] - var negG {.noInit.}: ECP_ShortW_Aff[Pubkey.F, Pubkey.G] + var Q {.noInit.}: EC_ShortW_Aff[Sig.F, Sig.G] + var negG {.noInit.}: EC_ShortW_Aff[Pubkey.F, Pubkey.G] - negG.neg(Pubkey.F.C.getGenerator($Pubkey.G)) + negG.neg(Pubkey.F.Name.getGenerator($Pubkey.G)) H.hashToCurve(k, Q, augmentation, message, domainSepTag) - when Sig.F.C.getEmbeddingDegree() == 12: - var gt {.noInit.}: Fp12[Sig.F.C] + when Sig.F.Name.getEmbeddingDegree() == 12: + var gt {.noInit.}: Fp12[Sig.F.Name] else: - {.error: "Not implemented: signature on k=" & $Sig.F.C.getEmbeddingDegree() & " for curve " & $$Sig.F.C.} + {.error: "Not implemented: signature on k=" & $Sig.F.Name.getEmbeddingDegree() & " for curve " & $$Sig.F.Name.} # e(PK, H(msg))*e(sig, -G) == 1 when Sig.G == G2: @@ -175,7 +175,7 @@ func init*(ctx: var BLSAggregateSigAccumulator, domainSepTag: openArray[byte]) { for i in ctx.dst_len ..< ctx.domainSepTag.len: ctx.domainSepTag[i] = byte 0 -func update*[Pubkey: ECP_ShortW_Aff]( +func update*[Pubkey: EC_ShortW_Aff]( ctx: var BLSAggregateSigAccumulator, pubkey: Pubkey, message: openArray[byte]): bool {.genCharAPI.} = @@ -192,7 +192,7 @@ func update*[Pubkey: ECP_ShortW_Aff]( when Pubkey.G == G1: # Pubkey on G1, H(message) and Signature on G2 type FF2 = BLSAggregateSigAccumulator.FF2 - var hmsgG2_aff {.noInit.}: ECP_ShortW_Aff[FF2, G2] + var hmsgG2_aff {.noInit.}: EC_ShortW_Aff[FF2, G2] H.hashToCurve( k, output = hmsgG2_aff, augmentation = "", message, @@ -203,7 +203,7 @@ func update*[Pubkey: ECP_ShortW_Aff]( else: # Pubkey on G2, H(message) and Signature on G1 type FF1 = BLSAggregateSigAccumulator.FF1 - var hmsgG1_aff {.noInit.}: ECP_ShortW_Aff[FF1, G1] + var hmsgG1_aff {.noInit.}: EC_ShortW_Aff[FF1, G1] H.hashToCurve( k, output = hmsgG1_aff, augmentation = "", message, @@ -211,7 +211,7 @@ func update*[Pubkey: ECP_ShortW_Aff]( return ctx.millerAccum.update(hmsgG1_aff, pubkey) -func update*[Pubkey: ECP_ShortW_Aff]( +func update*[Pubkey: EC_ShortW_Aff]( ctx: var BLSAggregateSigAccumulator, pubkey: Pubkey, message: View[byte]): bool {.inline.} = @@ -229,7 +229,7 @@ func merge*(ctxDst: var BLSAggregateSigAccumulator, ctxSrc: BLSAggregateSigAccum ctxDst.millerAccum.merge(ctxSrc.millerAccum) return true -func finalVerify*[F, G](ctx: var BLSAggregateSigAccumulator, aggregateSignature: ECP_ShortW_Aff[F, G]): bool = +func finalVerify*[F, G](ctx: var BLSAggregateSigAccumulator, aggregateSignature: EC_ShortW_Aff[F, G]): bool = ## Finish batch and/or aggregate signature verification and returns the final result. ## ## Returns false if nothing was accumulated @@ -240,12 +240,12 @@ func finalVerify*[F, G](ctx: var BLSAggregateSigAccumulator, aggregateSignature: type Fpk = BLSAggregateSigAccumulator.Fpk when G == G2: - type PubKey = ECP_ShortW_Aff[FF1, G1] + type PubKey = EC_ShortW_Aff[FF1, G1] else: - type PubKey = ECP_ShortW_Aff[FF2, G2] + type PubKey = EC_ShortW_Aff[FF2, G2] var negG {.noInit.}: Pubkey - negG.neg(Pubkey.F.C.getGenerator($Pubkey.G)) + negG.neg(Pubkey.F.Name.getGenerator($Pubkey.G)) when G == G2: if not ctx.millerAccum.update(negG, aggregateSignature): @@ -263,7 +263,7 @@ func finalVerify*[F, G](ctx: var BLSAggregateSigAccumulator, aggregateSignature: # ------------------------------------------------------------ type - BLSBatchSigAccumulator*[H: CryptoHash, FF1, FF2; Fpk: ExtensionField; SigAccum: ECP_ShortW_Jac, k: static int] = object + BLSBatchSigAccumulator*[H: CryptoHash, FF1, FF2; Fpk: ExtensionField; SigAccum: EC_ShortW_Jac, k: static int] = object ## An accumulator for Batched BLS signature verification # An accumulator for the Miller loops @@ -356,7 +356,7 @@ func init*( H.hash(ctx.secureBlinding, secureRandomBytes, accumSepTag) -func update*[Pubkey, Sig: ECP_ShortW_Aff]( +func update*[Pubkey, Sig: EC_ShortW_Aff]( ctx: var BLSBatchSigAccumulator, pubkey: Pubkey, message: openArray[byte], @@ -412,8 +412,8 @@ func update*[Pubkey, Sig: ECP_ShortW_Aff]( when Pubkey.G == G1: # Pubkey on G1, H(message) and Signature on G2 - var pkG1_jac {.noInit.}: ECP_ShortW_Jac[Pubkey.F, Pubkey.G] - var sigG2_jac {.noInit.}: ECP_ShortW_Jac[Sig.F, Sig.G] + var pkG1_jac {.noInit.}: EC_ShortW_Jac[Pubkey.F, Pubkey.G] + var sigG2_jac {.noInit.}: EC_ShortW_Jac[Sig.F, Sig.G] pkG1_jac.fromAffine(pubkey) sigG2_jac.fromAffine(signature) @@ -430,11 +430,11 @@ func update*[Pubkey, Sig: ECP_ShortW_Aff]( ctx.aggSig += sigG2_jac type FF1 = BLSBatchSigAccumulator.FF1 - var pkG1_aff {.noInit.}: ECP_ShortW_Aff[FF1, G1] + var pkG1_aff {.noInit.}: EC_ShortW_Aff[FF1, G1] pkG1_aff.affine(pkG1_jac) type FF2 = BLSBatchSigAccumulator.FF2 - var hmsgG2_aff {.noInit.}: ECP_ShortW_Aff[FF2, G2] + var hmsgG2_aff {.noInit.}: EC_ShortW_Aff[FF2, G2] H.hashToCurve( k, output = hmsgG2_aff, augmentation = "", message, @@ -444,8 +444,8 @@ func update*[Pubkey, Sig: ECP_ShortW_Aff]( else: # Pubkey on G2, H(message) and Signature on G1 - var hmsgG1_jac {.noInit.}: ECP_ShortW_Jac[Sig.F, Sig.G] - var sigG1_jac {.noInit.}: ECP_ShortW_Jac[Sig.F, Sig.G] + var hmsgG1_jac {.noInit.}: EC_ShortW_Jac[Sig.F, Sig.G] + var sigG1_jac {.noInit.}: EC_ShortW_Jac[Sig.F, Sig.G] H.hashToCurve( k, output = hmsgG1_jac, @@ -466,11 +466,11 @@ func update*[Pubkey, Sig: ECP_ShortW_Aff]( ctx.aggSig += sigG1_jac type FF1 = BLSBatchSigAccumulator.FF1 - var hmsgG1_aff {.noInit.}: ECP_ShortW_Aff[FF1, G1] + var hmsgG1_aff {.noInit.}: EC_ShortW_Aff[FF1, G1] hmsgG1_aff.affine(hmsgG1_jac) return ctx.millerAccum.update(hmsgG1_aff, pubkey) -func update*[Pubkey, Sig: ECP_ShortW_Aff]( +func update*[Pubkey, Sig: EC_ShortW_Aff]( ctx: var BLSBatchSigAccumulator, pubkey: Pubkey, message: View[byte], @@ -523,12 +523,12 @@ func finalVerify*(ctx: var BLSBatchSigAccumulator): bool = type Fpk = BLSBatchSigAccumulator.Fpk when BLSBatchSigAccumulator.SigAccum.G == G2: - type PubKey = ECP_ShortW_Aff[FF1, G1] + type PubKey = EC_ShortW_Aff[FF1, G1] else: - type PubKey = ECP_ShortW_Aff[FF2, G2] + type PubKey = EC_ShortW_Aff[FF2, G2] var negG {.noInit.}: Pubkey - negG.neg(Pubkey.F.C.getGenerator($Pubkey.G)) + negG.neg(Pubkey.F.Name.getGenerator($Pubkey.G)) var aggSig {.noInit.}: ctx.aggSig.typeof().affine() aggSig.affine(ctx.aggSig) @@ -552,9 +552,9 @@ func finalVerify*(ctx: var BLSBatchSigAccumulator): bool = # # ############################################################ -func aggregate*[T: ECP_ShortW_Aff](r: var T, points: openarray[T]) = +func aggregate*[T: EC_ShortW_Aff](r: var T, points: openarray[T]) = ## Aggregate pubkeys or signatures - var accum {.noinit.}: ECP_ShortW_Jac[T.F, T.G] + var accum {.noinit.}: EC_ShortW_Jac[T.F, T.G] accum.sum_reduce_vartime(points) r.affine(accum) @@ -601,7 +601,7 @@ func aggregateVerify*[Msg, Pubkey, Sig]( type FF1 = Pubkey.F type FF2 = Sig.F - type FpK = Sig.F.C.getGT() + type FpK = Sig.F.Name.getGT() var accum {.noinit.}: BLSAggregateSigAccumulator[H, FF1, FF2, Fpk, k] accum.init(domainSepTag) @@ -644,9 +644,9 @@ func batchVerify*[Msg, Pubkey, Sig]( type FF1 = Pubkey.F type FF2 = Sig.F - type FpK = Sig.F.C.getGT() + type FpK = Sig.F.Name.getGT() - var accum {.noinit.}: BLSBatchSigAccumulator[H, FF1, FF2, Fpk, ECP_ShortW_Jac[Sig.F, Sig.G], k] + var accum {.noinit.}: BLSBatchSigAccumulator[H, FF1, FF2, Fpk, EC_ShortW_Jac[Sig.F, Sig.G], k] accum.init(domainSepTag, secureRandomBytes, accumSepTag = "serial") for i in 0 ..< pubkeys.len: diff --git a/constantine/signatures/bls_signatures_parallel.nim b/constantine/signatures/bls_signatures_parallel.nim index cf83356c4..223be8cfd 100644 --- a/constantine/signatures/bls_signatures_parallel.nim +++ b/constantine/signatures/bls_signatures_parallel.nim @@ -24,11 +24,12 @@ import # Standard library std/atomics, # Constantine - ../threadpool/[threadpool, partitioners], - ../platforms/[abstractions, allocs, views], - ../serialization/endians, - ../hashes, - ../math/ec_shortweierstrass + constantine/threadpool/threadpool, + constantine/platforms/[abstractions, allocs, views], + constantine/serialization/endians, + constantine/hashes, + constantine/math/ec_shortweierstrass, + constantine/named/algebras # No exceptions allowed in core cryptographic operations {.push raises: [].} @@ -104,13 +105,13 @@ proc batchVerify_parallel*[Msg, Pubkey, Sig]( type FF1 = Pubkey.F type FF2 = Sig.F - type FpK = Sig.F.C.getGT() + type FpK = Sig.F.Name.getGT() # Stage 0a: Setup per-thread accumulators debug: doAssert pubkeys.len <= 1 shl 32 let N = pubkeys.len.uint32 let numAccums = min(N, tp.numThreads.uint32) - let accums = allocHeapArray(BLSBatchSigAccumulator[H, FF1, FF2, Fpk, ECP_ShortW_Jac[Sig.F, Sig.G], k], numAccums) + let accums = allocHeapArray(BLSBatchSigAccumulator[H, FF1, FF2, Fpk, EC_ShortW_Jac[Sig.F, Sig.G], k], numAccums) # Stage 0b: Setup synchronization var currentItem {.noInit.}: Atomic[uint32] diff --git a/constantine/threadpool/threadpool.nim b/constantine/threadpool/threadpool.nim index a68e1cd77..075fe26a1 100644 --- a/constantine/threadpool/threadpool.nim +++ b/constantine/threadpool/threadpool.nim @@ -425,7 +425,7 @@ proc schedule(ctx: var WorkerContext, task: ptr Task, forceWake = false) {.inlin # Inpired by # - Lazy binary-splitting: a run-time adaptive work-stealing scheduler. -# Tzannes, A., G. C. Caragea, R. Barua, and U. Vishkin. +# A. Tzannes, G. C. Caragea, R. Barua, and U. Vishkin. # In PPoPP ’10, Bangalore, India, January 2010. ACM, pp. 179–190. # https://user.eng.umd.edu/~barua/ppopp164.pdf # - Embracing Explicit Communication in Work-Stealing Runtime Systems. diff --git a/helpers/prng_unsafe.nim b/helpers/prng_unsafe.nim index a0cdfd0cf..3e21ebba2 100644 --- a/helpers/prng_unsafe.nim +++ b/helpers/prng_unsafe.nim @@ -147,7 +147,7 @@ func sample_unsafe*[T](rng: var RngState, src: openarray[T]): T = # a deviation of an estimate from the quantity under observation func reduceViaMont[N: static int, F](reduced: var array[N, SecretWord], unreduced: array[2*N, SecretWord], _: typedesc[F]) = - # reduced.reduce(unreduced, FF.fieldMod()) + # reduced.reduce(unreduced, FF.getModulus()) # ---------------------------------------- # With R ≡ (2^WordBitWidth)^numWords (mod p) # redc2xMont(a) computes a/R (mod p) @@ -157,10 +157,10 @@ func reduceViaMont[N: static int, F](reduced: var array[N, SecretWord], unreduce # so for 384-bit prime (6-words on 64-bit CPUs), so 6*6 = 36, twice for multiplication and reduction # significantly faster than division which works bit-by-bit due to constant-time requirement reduced.redc2xMont(unreduced, # a/R - F.fieldMod().limbs, F.getNegInvModWord(), + F.getModulus().limbs, F.getNegInvModWord(), F.getSpareBits()) reduced.mulMont(reduced, F.getR2modP().limbs, # (a/R) * R² * R⁻¹ ≡ a (mod p) - F.fieldMod().limbs, F.getNegInvModWord(), + F.getModulus().limbs, F.getNegInvModWord(), F.getSpareBits()) func random_unsafe(rng: var RngState, a: var Limbs) = @@ -286,19 +286,19 @@ func random_long01Seq(rng: var RngState, a: var ExtensionField) = # Elliptic curves # ------------------------------------------------------------ -type ECP = ECP_ShortW_Aff or ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_JacExt or - ECP_TwEdwards_Aff or ECP_TwEdwards_Prj -type ECP_ext = ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_JacExt or - ECP_TwEdwards_Prj +type ECP = EC_ShortW_Aff or EC_ShortW_Prj or EC_ShortW_Jac or EC_ShortW_JacExt or + EC_TwEdw_Aff or EC_TwEdw_Prj +type ECP_ext = EC_ShortW_Prj or EC_ShortW_Jac or EC_ShortW_JacExt or + EC_TwEdw_Prj template trySetFromCoord[F](a: ECP, fieldElem: F): SecretBool = - when a is (ECP_ShortW_Aff or ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_JacExt): + when a is (EC_ShortW_Aff or EC_ShortW_Prj or EC_ShortW_Jac or EC_ShortW_JacExt): trySetFromCoordX(a, fieldElem) else: trySetFromCoordY(a, fieldElem) template trySetFromCoords[F](a: ECP, fieldElem, scale: F): SecretBool = - when a is (ECP_ShortW_Prj or ECP_ShortW_Jac or ECP_ShortW_JacExt): + when a is (EC_ShortW_Prj or EC_ShortW_Jac or EC_ShortW_JacExt): trySetFromCoordsXandZ(a, fieldElem, scale) else: trySetFromCoordsYandZ(a, fieldElem, scale) diff --git a/metering/eip2537.md b/metering/eip2537.md index 42324405f..96caee89b 100644 --- a/metering/eip2537.md +++ b/metering/eip2537.md @@ -137,7 +137,7 @@ The CPU Cycle Count is indicative only. It cannot be used to compare across syst | `*=`*(a: var FF; b: FF) | 354 | 7933839.844 | 44.619 | 0.126 | 113.256 | 0.320 | | square*(a: var FF; skipFinalSub: static bool = false) | 129 | 7914110.429 | 16.300 | 0.126 | 41.481 | 0.322 | | sum*(r: var ECP_ShortW_Jac[F, G]; P, Q: ECP_ShortW_Jac[F ... | 8 | 291194.991 | 27.473 | 3.434 | 89.826 | 11.228 | -| madd*(r: var ECP_ShortW_Jac[F, G]; P: ECP_ShortW_Jac[F, ... | 64 | 337156.193 | 189.823 | 2.966 | 619.014 | 9.672 | +| mixedSum*(r: var ECP_ShortW_Jac[F, G]; P: ECP_ShortW_Jac[F, ... | 64 | 337156.193 | 189.823 | 2.966 | 619.014 | 9.672 | | double*(r: var ECP_ShortW_Jac[F, G]; P: ECP_ShortW_Jac[F ... | 129 | 578076.127 | 223.154 | 1.730 | 722.271 | 5.599 | | batchAffine*(affs: ptr UncheckedArray[ECP_ShortW_Aff[F, ... | 1 | 112397.437 | 8.897 | 8.897 | 29.205 | 29.205 | | scalarMulGLV_m2w2*(P0: var EC; scalar: BigInt[scalBits]) | 1 | 1831.267 | 546.070 | 546.070 | 1798.533 | 1798.533 | @@ -166,7 +166,7 @@ The CPU Cycle Count is indicative only. It cannot be used to compare across syst | cneg*(a: var FF; ctl: SecretBool) | 66 | 4113943.776 | 16.043 | 0.243 | 46.365 | 0.703 | | `*=`*(a: var FF; b: FF) | 506 | 7906867.724 | 63.995 | 0.126 | 161.898 | 0.320 | | sum*(r: var ECP_ShortW_Prj[F, G]; P, Q: ECP_ShortW_Prj[F ... | 8 | 296066.023 | 27.021 | 3.378 | 88.209 | 11.026 | -| madd*(r: var ECP_ShortW_Prj[F, G]; P: ECP_ShortW_Prj[F, ... | 64 | 338126.988 | 189.278 | 2.957 | 617.199 | 9.644 | +| mixedSum*(r: var ECP_ShortW_Prj[F, G]; P: ECP_ShortW_Prj[F, ... | 64 | 338126.988 | 189.278 | 2.957 | 617.199 | 9.644 | | double*(r: var ECP_ShortW_Prj[F, G]; P: ECP_ShortW_Prj[F ... | 129 | 595210.631 | 216.730 | 1.680 | 701.382 | 5.437 | | batchAffine*(affs: ptr UncheckedArray[ECP_ShortW_Aff[F, ... | 1 | 193798.450 | 5.160 | 5.160 | 16.896 | 16.896 | | scalarMulGLV_m2w2*(P0: var EC; scalar: BigInt[scalBits]) | 1 | 1878.347 | 532.383 | 532.383 | 1753.389 | 1753.389 | @@ -194,7 +194,7 @@ The CPU Cycle Count is indicative only. It cannot be used to compare across syst | square*(a: var FF; skipFinalSub: static bool = false) | 129 | 7915567.282 | 16.297 | 0.126 | 41.283 | 0.320 | | double*(r: var ECP_ShortW_Jac[F, G]; P: ECP_ShortW_Jac[F ... | 129 | 577954.400 | 223.201 | 1.730 | 722.403 | 5.600 | | sum_vartime*(r: var ECP_ShortW_Jac[F, G]; p, q: ECP_Shor ... | 6 | 418205.897 | 14.347 | 2.391 | 46.728 | 7.788 | -| madd_vartime*(r: var ECP_ShortW_Jac[F, G]; p: ECP_ShortW ... | 49 | 558188.280 | 87.784 | 1.792 | 284.097 | 5.798 | +| mixedSum_vartime*(r: var ECP_ShortW_Jac[F, G]; p: ECP_ShortW ... | 49 | 558188.280 | 87.784 | 1.792 | 284.097 | 5.798 | | batchAffine*(affs: ptr UncheckedArray[ECP_ShortW_Aff[F, ... | 1 | 154750.851 | 6.462 | 6.462 | 21.186 | 21.186 | | scalarMulEndo_minHammingWeight_windowed_vartime*(P: var ... | 1 | 2937.910 | 340.378 | 340.378 | 1121.010 | 1121.010 | | scalarMul_vartime*(P: var EC; scalar: BigInt[scalBits]) | 1 | 2937.220 | 340.458 | 340.458 | 1121.274 | 1121.274 | @@ -221,7 +221,7 @@ The CPU Cycle Count is indicative only. It cannot be used to compare across syst | `*=`*(a: var FF; b: FF) | 347 | 7342361.405 | 47.260 | 0.136 | 121.506 | 0.350 | | double*(r: var ECP_ShortW_Prj[F, G]; P: ECP_ShortW_Prj[F ... | 128 | 594950.359 | 215.144 | 1.681 | 696.036 | 5.438 | | sum_vartime*(r: var ECP_ShortW_Prj[F, G]; p, q: ECP_Shor ... | 6 | 472255.018 | 12.705 | 2.118 | 41.217 | 6.869 | -| madd_vartime*(r: var ECP_ShortW_Prj[F, G]; p: ECP_ShortW ... | 47 | 553990.500 | 84.839 | 1.805 | 274.428 | 5.839 | +| mixedSum_vartime*(r: var ECP_ShortW_Prj[F, G]; p: ECP_ShortW ... | 47 | 553990.500 | 84.839 | 1.805 | 274.428 | 5.839 | | batchAffine*(affs: ptr UncheckedArray[ECP_ShortW_Aff[F, ... | 1 | 196078.431 | 5.100 | 5.100 | 16.698 | 16.698 | | scalarMulEndo_minHammingWeight_windowed_vartime*(P: var ... | 1 | 3072.385 | 325.480 | 325.480 | 1071.939 | 1071.939 | | scalarMul_vartime*(P: var EC; scalar: BigInt[scalBits]) | 1 | 3071.630 | 325.560 | 325.560 | 1072.203 | 1072.203 | @@ -290,7 +290,7 @@ The CPU Cycle Count is indicative only. It cannot be used to compare across syst | csub*(a: var FF; b: FF; ctl: SecretBool) | 144 | 5656153.030 | 25.459 | 0.177 | 70.059 | 0.487 | | div2*(a: var FF) | 144 | 23410827.508 | 6.151 | 0.043 | 6.897 | 0.048 | | sum*(r: var ECP_ShortW_Jac[F, G]; P, Q: ECP_ShortW_Jac[F ... | 8 | 143143.430 | 55.888 | 6.986 | 183.348 | 22.919 | -| madd*(r: var ECP_ShortW_Jac[F, G]; P: ECP_ShortW_Jac[F, ... | 64 | 166594.649 | 384.166 | 6.003 | 1259.247 | 19.676 | +| mixedSum*(r: var ECP_ShortW_Jac[F, G]; P: ECP_ShortW_Jac[F, ... | 64 | 166594.649 | 384.166 | 6.003 | 1259.247 | 19.676 | | double*(r: var ECP_ShortW_Jac[F, G]; P: ECP_ShortW_Jac[F ... | 64 | 278754.143 | 229.593 | 3.587 | 750.123 | 11.721 | | batchAffine*(affs: ptr UncheckedArray[ECP_ShortW_Aff[F, ... | 1 | 70536.785 | 14.177 | 14.177 | 46.596 | 46.596 | | scalarMulEndo*(P: var EC; scalar: BigInt[scalBits]) | 1 | 1152.096 | 867.983 | 867.983 | 2858.790 | 2858.790 | @@ -320,7 +320,7 @@ The CPU Cycle Count is indicative only. It cannot be used to compare across syst | cneg*(r: var FF; a: FF; ctl: SecretBool) | 136 | 5655591.134 | 24.047 | 0.177 | 65.835 | 0.484 | | cneg*(a: var FF; ctl: SecretBool) | 136 | 4113359.344 | 33.063 | 0.243 | 95.832 | 0.705 | | sum*(r: var ECP_ShortW_Prj[F, G]; P, Q: ECP_ShortW_Prj[F ... | 8 | 155315.679 | 51.508 | 6.439 | 168.828 | 21.104 | -| madd*(r: var ECP_ShortW_Prj[F, G]; P: ECP_ShortW_Prj[F, ... | 64 | 171729.097 | 372.680 | 5.823 | 1221.429 | 19.085 | +| mixedSum*(r: var ECP_ShortW_Prj[F, G]; P: ECP_ShortW_Prj[F, ... | 64 | 171729.097 | 372.680 | 5.823 | 1221.429 | 19.085 | | double*(r: var ECP_ShortW_Prj[F, G]; P: ECP_ShortW_Prj[F ... | 64 | 235903.825 | 271.297 | 4.239 | 887.238 | 13.863 | | batchAffine*(affs: ptr UncheckedArray[ECP_ShortW_Aff[F, ... | 1 | 98823.994 | 10.119 | 10.119 | 33.231 | 33.231 | | scalarMulEndo*(P: var EC; scalar: BigInt[scalBits]) | 1 | 1124.767 | 889.073 | 889.073 | 2928.222 | 2928.222 | @@ -348,7 +348,7 @@ The CPU Cycle Count is indicative only. It cannot be used to compare across syst | square*(r: var FF; a: FF; skipFinalSub: static bool = false) | 2 | 16666666.667 | 0.120 | 0.060 | 0.198 | 0.099 | | double*(r: var ECP_ShortW_Jac[F, G]; P: ECP_ShortW_Jac[F ... | 67 | 278583.962 | 240.502 | 3.590 | 785.268 | 11.720 | | sum_vartime*(r: var ECP_ShortW_Jac[F, G]; p, q: ECP_Shor ... | 4 | 220337.116 | 18.154 | 4.538 | 59.367 | 14.842 | -| madd_vartime*(r: var ECP_ShortW_Jac[F, G]; p: ECP_ShortW ... | 69 | 296900.616 | 232.401 | 3.368 | 758.835 | 10.998 | +| mixedSum_vartime*(r: var ECP_ShortW_Jac[F, G]; p: ECP_ShortW ... | 69 | 296900.616 | 232.401 | 3.368 | 758.835 | 10.998 | | batchAffine*(affs: ptr UncheckedArray[ECP_ShortW_Aff[F, ... | 1 | 73389.109 | 13.626 | 13.626 | 44.748 | 44.748 | | scalarMulEndo_minHammingWeight_windowed_vartime*(P: var ... | 1 | 1933.436 | 517.214 | 517.214 | 1703.460 | 1703.460 | | scalarMul_vartime*(P: var EC; scalar: BigInt[scalBits]) | 1 | 1933.137 | 517.294 | 517.294 | 1703.691 | 1703.691 | @@ -375,7 +375,7 @@ The CPU Cycle Count is indicative only. It cannot be used to compare across syst | square*(r: var FF; a: FF; skipFinalSub: static bool = false) | 2 | 16666666.667 | 0.120 | 0.060 | 0.198 | 0.099 | | double*(r: var ECP_ShortW_Prj[F, G]; P: ECP_ShortW_Prj[F ... | 67 | 242212.156 | 276.617 | 4.129 | 904.695 | 13.503 | | sum_vartime*(r: var ECP_ShortW_Prj[F, G]; p, q: ECP_Shor ... | 4 | 247662.683 | 16.151 | 4.038 | 52.734 | 13.184 | -| madd_vartime*(r: var ECP_ShortW_Prj[F, G]; p: ECP_ShortW ... | 62 | 300657.081 | 206.215 | 3.326 | 672.903 | 10.853 | +| mixedSum_vartime*(r: var ECP_ShortW_Prj[F, G]; p: ECP_ShortW ... | 62 | 300657.081 | 206.215 | 3.326 | 672.903 | 10.853 | | batchAffine*(affs: ptr UncheckedArray[ECP_ShortW_Aff[F, ... | 1 | 99611.515 | 10.039 | 10.039 | 32.967 | 32.967 | | scalarMulEndo_minHammingWeight_windowed_vartime*(P: var ... | 1 | 1918.421 | 521.262 | 521.262 | 1716.825 | 1716.825 | | scalarMul_vartime*(P: var EC; scalar: BigInt[scalBits]) | 1 | 1918.127 | 521.342 | 521.342 | 1717.056 | 1717.056 | @@ -423,4 +423,4 @@ The CPU Cycle Count is indicative only. It cannot be used to compare across syst | cycl_exp_by_curve_param_div2*(r: var Fp12[BLS12_381]; a: ... | 1 | 3133.048 | 319.178 | 319.178 | 1051.182 | 1051.182 | | cycl_exp_by_curve_param*(r: var Fp12[BLS12_381]; a: Fp12 ... | 4 | 3162.810 | 1264.698 | 316.175 | 4165.161 | 1041.290 | | finalExpHard_BLS12*(f: var Fp12[C]) | 1 | 607.702 | 1645.543 | 1645.543 | 5419.854 | 5419.854 | -| pairing_bls12*(gt: var Fp12[C]; P: ECP_ShortW_Aff[Fp[C], ... | 1 | 379.418 | 2635.618 | 2635.618 | 8680.881 | 8680.881 | \ No newline at end of file +| pairing_bls12*(gt: var Fp12[C]; P: ECP_ShortW_Aff[Fp[A], ... | 1 | 379.418 | 2635.618 | 2635.618 | 8680.881 | 8680.881 | diff --git a/metering/m_eip2537.nim b/metering/m_eip2537.nim index a16509543..72349d252 100644 --- a/metering/m_eip2537.nim +++ b/metering/m_eip2537.nim @@ -31,23 +31,23 @@ let seed = uint32(getTime().toUnix() and (1'i64 shl 32 - 1)) # unixTime mod 2^32 rng.seed(seed) echo "bench xoshiro512** seed: ", seed -func random_point*(rng: var RngState, EC: typedesc[ECP_ShortW_Aff]): EC {.noInit.} = - var jac = rng.random_unsafe(ECP_ShortW_Jac[EC.F, EC.G]) +func random_point*(rng: var RngState, EC: typedesc[EC_ShortW_Aff]): EC {.noInit.} = + var jac = rng.random_unsafe(EC_ShortW_Jac[EC.F, EC.G]) jac.clearCofactor() result.affine(jac) -func random_point*(rng: var RngState, EC: typedesc[ECP_ShortW_Jac or ECP_ShortW_Prj]): EC {.noInit.} = +func random_point*(rng: var RngState, EC: typedesc[EC_ShortW_Jac or EC_ShortW_Prj]): EC {.noInit.} = var P = rng.random_unsafe(EC) P.clearCofactor() result = P type - G1aff = ECP_ShortW_Aff[Fp[BLS12_381], G1] - G2aff = ECP_ShortW_Aff[Fp2[BLS12_381], G2] - G1jac = ECP_ShortW_Jac[Fp[BLS12_381], G1] - G2jac = ECP_ShortW_Jac[Fp2[BLS12_381], G2] - G1prj = ECP_ShortW_Prj[Fp[BLS12_381], G1] - G2prj = ECP_ShortW_Prj[Fp2[BLS12_381], G2] + G1aff = EC_ShortW_Aff[Fp[BLS12_381], G1] + G2aff = EC_ShortW_Aff[Fp2[BLS12_381], G2] + G1jac = EC_ShortW_Jac[Fp[BLS12_381], G1] + G2jac = EC_ShortW_Jac[Fp2[BLS12_381], G2] + G1prj = EC_ShortW_Prj[Fp[BLS12_381], G1] + G2prj = EC_ShortW_Prj[Fp2[BLS12_381], G2] proc g1addMeter(EC: typedesc) = let diff --git a/metering/m_msm.nim b/metering/m_msm.nim index 2000aacae..56f0dfb62 100644 --- a/metering/m_msm.nim +++ b/metering/m_msm.nim @@ -23,8 +23,8 @@ rng.seed(seed) echo "bench xoshiro512** seed: ", seed proc msmMeter*(EC: typedesc, numPoints: int) = - const bits = EC.F.C.getCurveOrderBitwidth() - var points = newSeq[ECP_ShortW_Aff[EC.F, EC.G]](numPoints) + const bits = EC.getScalarField().bits() + var points = newSeq[EC_ShortW_Aff[EC.F, EC.G]](numPoints) var scalars = newSeq[BigInt[bits]](numPoints) for i in 0 ..< numPoints: @@ -39,6 +39,6 @@ proc msmMeter*(EC: typedesc, numPoints: int) = r.multiScalarMul_vartime(scalars, points) resetMetering() -msmMeter(ECP_ShortW_Jac[Fp[BLS12_381], G1], 10000) +msmMeter(EC_ShortW_Jac[Fp[BLS12_381], G1], 10000) const flags = if UseASM_X86_64 or UseASM_X86_32: "UseAssembly" else: "NoAssembly" reportCli(Metrics, flags) diff --git a/metering/m_pairings.nim b/metering/m_pairings.nim index 7cbfbacee..d1e4434a1 100644 --- a/metering/m_pairings.nim +++ b/metering/m_pairings.nim @@ -22,17 +22,17 @@ let seed = uint32(getTime().toUnix() and (1'i64 shl 32 - 1)) # unixTime mod 2^32 rng.seed(seed) echo "bench xoshiro512** seed: ", seed -func random_point*(rng: var RngState, EC: typedesc[ECP_ShortW_Aff]): EC {.noInit.} = - var jac = rng.random_unsafe(ECP_ShortW_Jac[EC.F, EC.G]) +func random_point*(rng: var RngState, EC: typedesc[EC_ShortW_Aff]): EC {.noInit.} = + var jac = rng.random_unsafe(EC_ShortW_Jac[EC.F, EC.G]) jac.clearCofactor() result.affine(jac) -proc pairingBLS12Meter*(C: static Curve) = +proc pairingBLS12Meter*(Name: static Algebra) = let - P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1]) - Q = rng.random_point(ECP_ShortW_Aff[Fp2[C], G2]) + P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1]) + Q = rng.random_point(EC_ShortW_Aff[Fp2[Name], G2]) - var f: Fp12[C] + var f: Fp12[Name] resetMetering() f.pairing(P, Q) diff --git a/research/kzg/fft_fr.nim b/research/kzg/fft_fr.nim index 74b3cd9c4..a24375faa 100644 --- a/research/kzg/fft_fr.nim +++ b/research/kzg/fft_fr.nim @@ -181,7 +181,7 @@ func ifft*[F]( proc init*(T: type FFTDescriptor, maxScale: uint8): T = result.maxWidth = 1 shl maxScale - result.rootOfUnity = scaleToRootOfUnity(T.F.C)[maxScale] + result.rootOfUnity = scaleToRootOfUnity(T.F.Name)[maxScale] result.expandedRootsOfUnity = result.rootOfUnity.expandRootOfUnity() # Aren't you tired of reading about unity? diff --git a/research/kzg/fft_g1.nim b/research/kzg/fft_g1.nim index 0af9d4530..19f20fad0 100644 --- a/research/kzg/fft_g1.nim +++ b/research/kzg/fft_g1.nim @@ -62,9 +62,9 @@ type FFTDescriptor*[EC] = object ## Metadata for FFT on Elliptic Curve maxWidth: int - rootOfUnity: matchingOrderBigInt(EC.F.C) + rootOfUnity: EC.F.getBigInt() ## The root of unity that generates all roots - expandedRootsOfUnity: seq[matchingOrderBigInt(EC.F.C)] + expandedRootsOfUnity: seq[EC.F.getBigInt()] ## domain, starting and ending with 1 func expandRootOfUnity[F](rootOfUnity: F): auto {.noInit.} = @@ -77,7 +77,7 @@ func expandRootOfUnity[F](rootOfUnity: F): auto {.noInit.} = # so embrace heap (re-)allocations. # Figuring out how to do to right size the buffers # in production will be fun. - var r: seq[matchingOrderBigInt(F.C)] + var r: seq[F.getBigInt()] r.setLen(2) r[0].setOne() r[1] = rootOfUnity.toBig() @@ -176,7 +176,7 @@ func ifft_vartime*[EC]( var voutput = output.toView() fft_internal(voutput, vals.toView(), rootz) - var invLen {.noInit.}: Fr[EC.F.C] + var invLen {.noInit.}: Fr[EC.F.Name] invLen.fromUint(vals.len.uint64) invLen.inv_vartime() let inv = invLen.toBig() @@ -192,7 +192,7 @@ func ifft_vartime*[EC]( proc init*(T: type FFTDescriptor, maxScale: uint8): T = result.maxWidth = 1 shl maxScale - let root = scaleToRootOfUnity(T.EC.F.C)[maxScale] + let root = scaleToRootOfUnity(T.EC.F.Name)[maxScale] result.rootOfUnity = root.toBig() result.expandedRootsOfUnity = root.expandRootOfUnity() # Aren't you tired of reading about unity? @@ -208,8 +208,8 @@ when isMainModule: std/[times, monotimes, strformat], helpers/prng_unsafe - type EC_G1 = ECP_ShortW_Prj[Fp[BLS12_381], G1] - var Generator1: ECP_ShortW_Aff[Fp[BLS12_381], G1] + type EC_G1 = EC_ShortW_Prj[Fp[BLS12_381], G1] + var Generator1: EC_ShortW_Aff[Fp[BLS12_381], G1] doAssert Generator1.fromHex( "0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb", "0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1" @@ -220,7 +220,7 @@ when isMainModule: var data = newSeq[EC_G1](fftDesc.maxWidth) data[0].fromAffine(Generator1) for i in 1 ..< fftDesc.maxWidth: - data[i].madd(data[i-1], Generator1) + data[i].mixedSum(data[i-1], Generator1) var coefs = newSeq[EC_G1](data.len) let fftOk = fft_vartime(fftDesc, coefs, data) @@ -271,7 +271,7 @@ when isMainModule: var data = newSeq[EC_G1](desc.maxWidth) data[0].fromAffine(Generator1) for i in 1 ..< desc.maxWidth: - data[i].madd(data[i-1], Generator1) + data[i].mixedSum(data[i-1], Generator1) var coefsOut = newSeq[EC_G1](data.len) diff --git a/research/kzg/fft_lut.nim b/research/kzg/fft_lut.nim index ea800eb78..b5b491c01 100644 --- a/research/kzg/fft_lut.nim +++ b/research/kzg/fft_lut.nim @@ -22,8 +22,8 @@ const BLS12_381_Fr_primitive_root = 7 func buildRootLUT(F: type Fr): array[32, F] = ## [pow(PRIMITIVE_ROOT, (MODULUS - 1) // (2**i), MODULUS) for i in range(32)] - var exponent {.noInit.}: BigInt[F.C.getCurveOrderBitwidth()] - exponent = F.C.getCurveOrder() + var exponent {.noInit.}: BigInt[F.bits()] + exponent = F.getModulus() exponent -= One # Start by the end @@ -44,5 +44,5 @@ func buildRootLUT(F: type Fr): array[32, F] = let BLS12_381_Fr_ScaleToRootOfUnity* = buildRootLUT(Fr[BLS12_381]) {.experimental: "dynamicBindSym".} -macro scaleToRootOfUnity*(C: static Curve): untyped = - return bindSym($C & "_Fr_ScaleToRootOfUnity") +macro scaleToRootOfUnity*(Name: static Algebra): untyped = + return bindSym($Name & "_Fr_ScaleToRootOfUnity") diff --git a/research/kzg/kzg_single_proofs.nim b/research/kzg/kzg_single_proofs.nim index 1bab8d340..9cd7b5b41 100644 --- a/research/kzg/kzg_single_proofs.nim +++ b/research/kzg/kzg_single_proofs.nim @@ -18,8 +18,8 @@ import ./fft_fr type - G1 = ECP_ShortW_Prj[Fp[BLS12_381], G1] - G2 = ECP_ShortW_Prj[Fp2[BLS12_381], G2] + G1 = EC_ShortW_Prj[Fp[BLS12_381], G1] + G2 = EC_ShortW_Prj[Fp2[BLS12_381], G2] KZGDescriptor = object fftDesc: FFTDescriptor[Fr[BLS12_381]] @@ -29,13 +29,13 @@ type # [b.multiply(b.G2, pow(s, i, MODULUS)) for i in range(WIDTH+1)] secretG2: seq[G2] -var Generator1: ECP_ShortW_Aff[Fp[BLS12_381], G1] +var Generator1: EC_ShortW_Aff[Fp[BLS12_381], G1] doAssert Generator1.fromHex( "0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb", "0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1" ) -var Generator2: ECP_ShortW_Aff[Fp2[BLS12_381], G2] +var Generator2: EC_ShortW_Aff[Fp2[BLS12_381], G2] doAssert Generator2.fromHex( "0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8", "0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e", diff --git a/research/kzg/polynomials.nim b/research/kzg/polynomials.nim index debd2432a..5dd38b1ac 100644 --- a/research/kzg/polynomials.nim +++ b/research/kzg/polynomials.nim @@ -15,10 +15,10 @@ import ] type - G1 = ECP_ShortW_Prj[Fp[BLS12_381], G1] - G2 = ECP_ShortW_Prj[Fp2[BLS12_381], G2] - G1aff = ECP_ShortW_Aff[Fp[BLS12_381], G1] - G2aff = ECP_ShortW_Aff[Fp2[BLS12_381], G2] + G1 = EC_ShortW_Prj[Fp[BLS12_381], G1] + G2 = EC_ShortW_Prj[Fp2[BLS12_381], G2] + G1aff = EC_ShortW_Aff[Fp[BLS12_381], G1] + G2aff = EC_ShortW_Aff[Fp2[BLS12_381], G2] GT = Fp12[BLS12_381] func linear_combination*( diff --git a/tests/gpu/t_nvidia_fp.nim b/tests/gpu/t_nvidia_fp.nim index f2152e004..e43b65128 100644 --- a/tests/gpu/t_nvidia_fp.nim +++ b/tests/gpu/t_nvidia_fp.nim @@ -28,14 +28,14 @@ echo "test_nvidia_fp xoshiro512** seed: ", seed const Iters = 10 -proc init(T: type CurveMetadata, asy: Assembler_LLVM, curve: static Curve, wordSize: WordSize): T = +proc init(T: type CurveMetadata, asy: Assembler_LLVM, name: static Algebra, wordSize: WordSize): T = CurveMetadata.init( asy.ctx, - $curve & "_", wordSize, - fpBits = uint32 curve.getCurveBitwidth(), - fpMod = curve.Mod().toHex(), - frBits = uint32 curve.getCurveOrderBitwidth(), - frMod = curve.getCurveOrder().toHex()) + $name & "_", wordSize, + fpBits = uint32 Fp[name].bits(), + fpMod = Fp[name].getModulus().toHex(), + frBits = uint32 Fr[name].bits(), + frMod = Fr[name].getModulus().toHex()) proc genFieldAddPTX(asy: Assembler_LLVM, cm: CurveMetadata) = let fpAdd = asy.field_add_gen(cm, fp) @@ -67,7 +67,7 @@ var sm: tuple[major, minor: int32] check cuDeviceGetAttribute(sm.major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, cudaDevice) check cuDeviceGetAttribute(sm.minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, cudaDevice) -proc t_field_add(curve: static Curve) = +proc t_field_add(name: static Algebra) = # Codegen # ------------------------- let asy = Assembler_LLVM.new(bkNvidiaPTX, cstring("t_nvidia_" & $curve)) @@ -121,7 +121,7 @@ proc t_field_add(curve: static Curve) = doAssert bool(rCPU == rGPU_32) doAssert bool(rCPU == rGPU_64) -proc t_field_sub(curve: static Curve) = +proc t_field_sub(name: static Algebra) = # Codegen # ------------------------- let asy = Assembler_LLVM.new(bkNvidiaPTX, cstring("t_nvidia_" & $curve)) @@ -175,7 +175,7 @@ proc t_field_sub(curve: static Curve) = doAssert bool(rCPU == rGPU_32) doAssert bool(rCPU == rGPU_64) -proc t_field_mul(curve: static Curve) = +proc t_field_mul(name: static Algebra) = # Codegen # ------------------------- let asy = Assembler_LLVM.new(bkNvidiaPTX, cstring("t_nvidia_" & $curve)) diff --git a/tests/math_elliptic_curves/t_ec_conversion.nim b/tests/math_elliptic_curves/t_ec_conversion.nim index d1bc15033..ea632a6d9 100644 --- a/tests/math_elliptic_curves/t_ec_conversion.nim +++ b/tests/math_elliptic_curves/t_ec_conversion.nim @@ -22,42 +22,42 @@ run_EC_conversion_failures( ) run_EC_affine_conversion( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_conversion_shortw_affine_jacobian_g1_" & $BN254_Snarks ) run_EC_affine_conversion( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_conversion_shortw_affine_projective_g1_" & $BN254_Snarks ) run_EC_affine_conversion( - ec = ECP_ShortW_Jac[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Jac[Fp2[BN254_Snarks], G2], Iters = Iters, moduleName = "test_ec_conversion_shortw_affine_jacobian_g2_" & $BN254_Snarks ) run_EC_affine_conversion( - ec = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], Iters = Iters, moduleName = "test_ec_conversion_shortw_affine_projective_g2_" & $BN254_Snarks ) run_EC_affine_conversion( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_conversion_shortw_affine_jacobian_g1_" & $BLS12_381 ) run_EC_affine_conversion( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_conversion_shortw_affine_projective_g1_" & $BLS12_381 ) run_EC_affine_conversion( - ec = ECP_ShortW_Jac[Fp2[BLS12_381], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_381], G2], Iters = Iters, moduleName = "test_ec_conversion_shortw_affine_jacobian_g2_" & $BLS12_381 ) run_EC_affine_conversion( - ec = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_381], G2], Iters = Iters, moduleName = "test_ec_conversion_shortw_affine_projective_g2_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_frobenius.nim b/tests/math_elliptic_curves/t_ec_frobenius.nim index eec553419..ee0c06495 100644 --- a/tests/math_elliptic_curves/t_ec_frobenius.nim +++ b/tests/math_elliptic_curves/t_ec_frobenius.nim @@ -31,7 +31,7 @@ echo "frobenius xoshiro512** seed: ", seed proc test( id: int, - EC: typedesc[ECP_ShortW_Prj], + EC: typedesc[EC_ShortW_Prj], Px0, Px1, Py0, Py1: string, Qx0, Qx1, Qy0, Qy1: string ) = @@ -56,7 +56,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" # - sage sage/frobenius_bls12_381.sage test( id = 0, - EC = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + EC = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], Px0 = "598e4c8c14c24c90834f2debedee4db3d31fed98a5134177704bfec14f46cb5", Px1 = "c6fffa61daeb7caaf96983e70f164931d958c6820b205cdde19f2fa1eaaa7b1", Py0 = "2f5fa252a27df56f5ca2e9c3382c17e531d317d50396f3fe952704304946a5a", @@ -69,7 +69,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 1, - EC = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + EC = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], Px0 = "21014830dd88a0e7961e704cea531200866c5df46cb25aa3e2aac8d4fec64c6e", Px1 = "1db17d8364def10443beab6e4a055c210d3e49c7c3af31e9cfb66d829938dca7", Py0 = "1394ab8c346ad3eba14fa14789d3bbfc2deed5a7a510da8e9418580515d27bda", @@ -82,7 +82,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 2, - EC = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + EC = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], Px0 = "46f2a2be9a3e19c1bb484fc37703ff64c3d7379de22249ccf0881037948beec", Px1 = "10a5aaae14cb028f4ff4b81d41b712038b9f620a99e208c23504887e56831806", Py0 = "2e6c3ebe0f3dada0063dc59f85fe2264dc3502bf65206336106a8d39d838a7b2", @@ -95,7 +95,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 3, - EC = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + EC = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], Px0 = "1cf3af1d41e89d8df378aa81463a978c021f27f4a48387e74655ce2cf5c1f298", Px1 = "36553e80e5c7c7360c7a2ae6bf1b8f68eb48804fc7eba7d2f56f09e87bbb0b1", Py0 = "25f03e551d74b6be3268bf001905dfbe0bcbe43a2d1aac645a3ca8650b52e551", @@ -110,7 +110,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 0, - EC = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + EC = EC_ShortW_Prj[Fp2[BLS12_377], G2], Px0 = "112de13b7cd42bccdb005f2d4dc2726f360243103335ef6cf5e217e777554ae7c1deff5ddb5bcbb581fc9f13728a439", Px1 = "10d1a8963e5c6854d5e610ece9914f9b5619c27652be1e9ec3e87687d63ed5d45b449bf59c2481e18ac6159f75966ac", Py0 = "8aaf3a8660cf0edd6e97a2cd7837af1c63ec89e18f9bf4c64638662a661636b928a4f8097e6a2e8dfa11e13c51b075", @@ -123,7 +123,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 1, - EC = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + EC = EC_ShortW_Prj[Fp2[BLS12_377], G2], Px0 = "2f9318360b53c2d706061f527571e91679e6086a72ce8203ba1a04850f83bb192b29307e9b2d63feb1d23979e3f632", Px1 = "3cbab0789968a3a35fa5d2e2326baa40c34d11a4af05a4109350944300ce32eef74dc5e47ba46717bd8bf87604696d", Py0 = "14ea84922f76f2681fec869dce26141392975dcdb4f21d5fa8aec06b37bf71ba6249c219ecbaef4a266196dafb4ad19", @@ -136,7 +136,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 2, - EC = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + EC = EC_ShortW_Prj[Fp2[BLS12_377], G2], Px0 = "833ca23630be463c388ea6cfcff5b0e3b055065702a84310d2c726aee14d9e140cba05be79b5cb0441816d9e8c8370", Px1 = "264a9755524baac8d9e53b0a45789e9dafcb6b453e965061fcfa20bb12a27d9b9417d5277ae2a499b1cfe567d75e2d", Py0 = "5b670b9789825e2b48101b5b6e660cf9117e29c521dad54640cb356b674b3946c98cb43909c3495fb6d6d231891b7e", @@ -149,7 +149,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 3, - EC = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + EC = EC_ShortW_Prj[Fp2[BLS12_377], G2], Px0 = "14cd89e2e2755ddc086f63fd62e1f9904c3c1497243455c578a963e81b389f04e95ceafc4f47dc777579cdc82eca79b", Px1 = "ba8801beba0654f20ccb78783efa7a911d182ec0eb99abe10f9a3d26b46fb7f90552e4ff6beb4df4611a9072be648b", Py0 = "12e23bc97d891f2a047bac9c90e728cb89760c812156f96c95e36c40f1c830cf6ecbb5d407b189070d48a92eb461ea6", @@ -164,7 +164,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 0, - EC = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + EC = EC_ShortW_Prj[Fp2[BLS12_381], G2], Px0 = "d6904be428a0310dbd6e15a744a774bcf9800abe27536267a5383f1ddbd7783e1dc20098a8e045e3cca66b83f6d7f0f", Px1 = "12107f6ef71d0d1e3bcba9e00a0675d3080519dd1b6c086bd660eb2d2bca8f276e283a891b5c0615064d7886af625cf2", Py0 = "c592a3546d2d61d671070909e97860822db0a389e351c1744bdbb2c472cf52f3ca3e94068b0b6f3b0121923659131f5", @@ -177,7 +177,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 1, - EC = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + EC = EC_ShortW_Prj[Fp2[BLS12_381], G2], Px0 = "112de130b7cd42bccdb005f2d4dc2726f360243103335ef6cf5e217e777554ae7c1deff5ddb5bcbb581fc9f13728a439", Px1 = "10d1a89a63e5c6854d5e610ece9914f9b5619c27652be1e9ec3e87687d63ed5d45b449bf59c2481e18ac6159f75966ac", Py0 = "11261c8fcb0f4f560479547fe6b2a1c1e8b648d87e54c39f299eba8729294e99b415851d134ca31e8bb861c42e6f1022", @@ -190,7 +190,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 2, - EC = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + EC = EC_ShortW_Prj[Fp2[BLS12_381], G2], Px0 = "2f93183360b53c2d706061f527571e91679e6086a72ce8203ba1a04850f83bb192b29307e9b2d63feb1d23979e3f632", Px1 = "3cbab0c789968a3a35fa5d2e2326baa40c34d11a4af05a4109350944300ce32eef74dc5e47ba46717bd8bf87604696d", Py0 = "2b8d995b0f2114442b7bbdbe5732fbf94430d6d413e1f388031f3abb956e598cb6764275a75832c1670868c458378b6", @@ -203,7 +203,7 @@ suite "ψ (Psi) - Untwist-Frobenius-Twist Endomorphism on G2 vs SageMath" & " [" test( id = 3, - EC = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + EC = EC_ShortW_Prj[Fp2[BLS12_381], G2], Px0 = "d7d1c55ddf8bd03b7a15c3ea4f8f69aee37bf282d4aac82b7bd1fd47139250b9c708997a7ff8f603e48f0471c2cfe03", Px1 = "d145a91934a6ad865d24ab556ae1e6c42decdd05d676b80e53365a6ff7536332859c9682e7200e40515f675415d71a3", Py0 = "6de67fa12af93813a42612b1e9449c7b1f160c5de004ec26ea61010e48ba38dcf158d2692f347fdc6c6332bbec7106f", @@ -241,34 +241,34 @@ suite "ψ - psi(psi(P)) == psi2(P) - (Untwist-Frobenius-Twist Endomorphism)" & " test(EC, randZ = false, gen = Long01Sequence) test(EC, randZ = true, gen = Long01Sequence) - testAll(ECP_ShortW_Prj[Fp2[BN254_Nogami], G2]) - testAll(ECP_ShortW_Prj[Fp2[BN254_Snarks], G2]) - testAll(ECP_ShortW_Prj[Fp2[BLS12_377], G2]) - testAll(ECP_ShortW_Prj[Fp2[BLS12_381], G2]) - testAll(ECP_ShortW_Prj[Fp[BW6_761], G2]) + testAll(EC_ShortW_Prj[Fp2[BN254_Nogami], G2]) + testAll(EC_ShortW_Prj[Fp2[BN254_Snarks], G2]) + testAll(EC_ShortW_Prj[Fp2[BLS12_377], G2]) + testAll(EC_ShortW_Prj[Fp2[BLS12_381], G2]) + testAll(EC_ShortW_Prj[Fp[BW6_761], G2]) suite "ψ²(P) - [t]ψ(P) + [p]P = Inf" & " [" & $WordBitWidth & "-bit words]": const Iters = 10 - proc trace(C: static Curve): auto = + proc trace(Name: static Algebra): auto = # Returns (abs(trace), isNegativeSign) - when C == BN254_Snarks: + when Name == BN254_Snarks: # x = "0x44E992B44A6909F1" # t = 6x²+1 return (BigInt[127].fromHex"0x6f4d8248eeb859fbf83e9682e87cfd47", false) - elif C == BN254_Nogami: + elif Name == BN254_Nogami: # x = "-0x4080000000000001" # t = 6x²+1 return (BigInt[127].fromHex"0x61818000000000030600000000000007", false) - elif C == BLS12_377: + elif Name == BLS12_377: # x = 3 * 2^46 * (7 * 13 * 499) + 1 # x = 0x8508c00000000001 # t = x+1 return (BigInt[64].fromHex"8508c00000000002", false) - elif C == BLS12_381: + elif Name == BLS12_381: # x = "-(2^63 + 2^62 + 2^60 + 2^57 + 2^48 + 2^16)" # t = x+1 return (BigInt[64].fromHex"0xd20100000000ffff", true) - elif C == BW6_761: + elif Name == BW6_761: # x = 3 * 2^46 * (7 * 13 * 499) + 1 # x = 0x8508c00000000001 # t = x^5 - 3*x^4 + 3*x^3 - x + 3 + cofactor_trace*r @@ -278,7 +278,7 @@ suite "ψ²(P) - [t]ψ(P) + [p]P = Inf" & " [" & $WordBitWidth & "-bit words]": {.error: "Not implemented".} proc test(EC: typedesc, randZ: static bool, gen: static RandomGen) = - let trace = trace(EC.F.C) + let trace = trace(EC.F.Name) for i in 0 ..< Iters: let P = rng.random_point(EC, randZ, gen) @@ -291,7 +291,7 @@ suite "ψ²(P) - [t]ψ(P) + [p]P = Inf" & " [" & $WordBitWidth & "-bit words]": if trace[1]: # negative trace tpsi.neg() pP = P - pP.scalarMulGeneric(EC.F.C.Mod) # Multiply beyond curve order, invalid for GLS + pP.scalarMulGeneric(EC.F.getModulus()) # Multiply beyond curve order, invalid for GLS # ψ²(P) - [t]ψ(P) + [p]P = InfinityPoint r.diff(psi2, tpsi) @@ -308,11 +308,11 @@ suite "ψ²(P) - [t]ψ(P) + [p]P = Inf" & " [" & $WordBitWidth & "-bit words]": test(EC, randZ = false, gen = Long01Sequence) test(EC, randZ = true, gen = Long01Sequence) - testAll(ECP_ShortW_Prj[Fp2[BN254_Nogami], G2]) - testAll(ECP_ShortW_Prj[Fp2[BN254_Snarks], G2]) - testAll(ECP_ShortW_Prj[Fp2[BLS12_377], G2]) - testAll(ECP_ShortW_Prj[Fp2[BLS12_381], G2]) - testAll(ECP_ShortW_Prj[Fp[BW6_761], G2]) + testAll(EC_ShortW_Prj[Fp2[BN254_Nogami], G2]) + testAll(EC_ShortW_Prj[Fp2[BN254_Snarks], G2]) + testAll(EC_ShortW_Prj[Fp2[BLS12_377], G2]) + testAll(EC_ShortW_Prj[Fp2[BLS12_381], G2]) + testAll(EC_ShortW_Prj[Fp[BW6_761], G2]) suite "ψ⁴(P) - ψ²(P) + P = Inf (k-th cyclotomic polynomial with embedding degree k=12)" & " [" & $WordBitWidth & "-bit words]": const Iters = 10 @@ -339,10 +339,10 @@ suite "ψ⁴(P) - ψ²(P) + P = Inf (k-th cyclotomic polynomial with embedding d test(EC, randZ = false, gen = Long01Sequence) test(EC, randZ = true, gen = Long01Sequence) - testAll(ECP_ShortW_Prj[Fp2[BN254_Nogami], G2]) - testAll(ECP_ShortW_Prj[Fp2[BN254_Snarks], G2]) - testAll(ECP_ShortW_Prj[Fp2[BLS12_377], G2]) - testAll(ECP_ShortW_Prj[Fp2[BLS12_381], G2]) + testAll(EC_ShortW_Prj[Fp2[BN254_Nogami], G2]) + testAll(EC_ShortW_Prj[Fp2[BN254_Snarks], G2]) + testAll(EC_ShortW_Prj[Fp2[BLS12_377], G2]) + testAll(EC_ShortW_Prj[Fp2[BLS12_381], G2]) suite "ψ²(P) - ψ(P) + P = Inf (k-th cyclotomic polynomial with embedding degree k=6)" & " [" & $WordBitWidth & "-bit words]": const Iters = 10 @@ -369,4 +369,4 @@ suite "ψ²(P) - ψ(P) + P = Inf (k-th cyclotomic polynomial with embedding degr test(EC, randZ = false, gen = Long01Sequence) test(EC, randZ = true, gen = Long01Sequence) - testAll(ECP_ShortW_Prj[Fp[BW6_761], G2]) + testAll(EC_ShortW_Prj[Fp[BW6_761], G2]) diff --git a/tests/math_elliptic_curves/t_ec_sage_bls12_377.nim b/tests/math_elliptic_curves/t_ec_sage_bls12_377.nim index 274d12370..8971f33a1 100644 --- a/tests/math_elliptic_curves/t_ec_sage_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_sage_bls12_377.nim @@ -15,23 +15,23 @@ import # Test utilities ./t_ec_sage_template -staticFor(bits, [32, 64, 128, BLS12_377.getCurveOrderBitwidth()]): +staticFor(bits, [32, 64, 128, Fr[BLS12_377].bits()]): run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp[BLS12_377], G1], bits, + EC_ShortW_Prj[Fp[BLS12_377], G1], bits, "t_ec_sage_bls12_377_g1_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp[BLS12_377], G1], bits, + EC_ShortW_Jac[Fp[BLS12_377], G1], bits, "t_ec_sage_bls12_377_g1_jacobian" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp2[BLS12_377], G2], bits, + EC_ShortW_Prj[Fp2[BLS12_377], G2], bits, "t_ec_sage_bls12_377_g2_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp2[BLS12_377], G2], bits, + EC_ShortW_Jac[Fp2[BLS12_377], G2], bits, "t_ec_sage_bls12_377_g2_jacobian" ) diff --git a/tests/math_elliptic_curves/t_ec_sage_bls12_381.nim b/tests/math_elliptic_curves/t_ec_sage_bls12_381.nim index 2dddf4634..09e2c9654 100644 --- a/tests/math_elliptic_curves/t_ec_sage_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_sage_bls12_381.nim @@ -15,23 +15,23 @@ import # Test utilities ./t_ec_sage_template -staticFor(bits, [32, 64, 128, BLS12_381.getCurveOrderBitwidth()]): +staticFor(bits, [32, 64, 128, Fr[BLS12_381].bits()]): run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp[BLS12_381], G1], bits, + EC_ShortW_Prj[Fp[BLS12_381], G1], bits, "t_ec_sage_bls12_381_g1_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp[BLS12_381], G1], bits, + EC_ShortW_Jac[Fp[BLS12_381], G1], bits, "t_ec_sage_bls12_381_g1_jacobian" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp2[BLS12_381], G2], bits, + EC_ShortW_Prj[Fp2[BLS12_381], G2], bits, "t_ec_sage_bls12_381_g2_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp2[BLS12_381], G2], bits, + EC_ShortW_Jac[Fp2[BLS12_381], G2], bits, "t_ec_sage_bls12_381_g2_jacobian" ) diff --git a/tests/math_elliptic_curves/t_ec_sage_bn254_nogami.nim b/tests/math_elliptic_curves/t_ec_sage_bn254_nogami.nim index 6edf959f9..1d0217faa 100644 --- a/tests/math_elliptic_curves/t_ec_sage_bn254_nogami.nim +++ b/tests/math_elliptic_curves/t_ec_sage_bn254_nogami.nim @@ -15,23 +15,23 @@ import # Test utilities ./t_ec_sage_template -staticFor(bits, [BN254_Nogami.getCurveOrderBitwidth()]): +staticFor(bits, [Fr[BN254_Nogami].bits()]): run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp[BN254_Nogami], G1], bits, + EC_ShortW_Prj[Fp[BN254_Nogami], G1], bits, "t_ec_sage_bn254_nogami_g1_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp[BN254_Nogami], G1], bits, + EC_ShortW_Jac[Fp[BN254_Nogami], G1], bits, "t_ec_sage_bn254_nogami_g1_jacobian" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp2[BN254_Nogami], G2], bits, + EC_ShortW_Prj[Fp2[BN254_Nogami], G2], bits, "t_ec_sage_bn254_nogami_g2_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp2[BN254_Nogami], G2], bits, + EC_ShortW_Jac[Fp2[BN254_Nogami], G2], bits, "t_ec_sage_bn254_nogami_g2_jacobian" ) diff --git a/tests/math_elliptic_curves/t_ec_sage_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_sage_bn254_snarks.nim index 9a6a291e8..d56c66c49 100644 --- a/tests/math_elliptic_curves/t_ec_sage_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_sage_bn254_snarks.nim @@ -15,23 +15,23 @@ import # Test utilities ./t_ec_sage_template -staticFor(bits, [32, 64, 128, BN254_Snarks.getCurveOrderBitwidth()]): +staticFor(bits, [32, 64, 128, Fr[BN254_Snarks].bits()]): run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp[BN254_Snarks], G1], bits, + EC_ShortW_Prj[Fp[BN254_Snarks], G1], bits, "t_ec_sage_bn254_snarks_g1_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp[BN254_Snarks], G1], bits, + EC_ShortW_Jac[Fp[BN254_Snarks], G1], bits, "t_ec_sage_bn254_snarks_g1_jacobian" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], bits, + EC_ShortW_Prj[Fp2[BN254_Snarks], G2], bits, "t_ec_sage_bn254_snarks_g2_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp2[BN254_Snarks], G2], bits, + EC_ShortW_Jac[Fp2[BN254_Snarks], G2], bits, "t_ec_sage_bn254_snarks_g2_jacobian" ) diff --git a/tests/math_elliptic_curves/t_ec_sage_bw6_761_g1.nim b/tests/math_elliptic_curves/t_ec_sage_bw6_761_g1.nim index fca32ef0e..034084bca 100644 --- a/tests/math_elliptic_curves/t_ec_sage_bw6_761_g1.nim +++ b/tests/math_elliptic_curves/t_ec_sage_bw6_761_g1.nim @@ -14,29 +14,29 @@ import # Test utilities ./t_ec_sage_template -# When ECP_ShortW_Aff[Fp[Foo], G1] -# and ECP_ShortW_Aff[Fp[Foo], G2] +# When EC_ShortW_Aff[Fp[Foo], G1] +# and EC_ShortW_Aff[Fp[Foo], G2] # are generated in the same file (i.e. twists and base curve are both on Fp) # this creates bad codegen, in the C code, the `value`parameter gets the wrong type # TODO: upstream -staticFor(bits, [BW6_761.getCurveOrderBitwidth()]): +staticFor(bits, [Fr[BW6_761].bits()]): run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp[BW6_761], G1], bits, + EC_ShortW_Prj[Fp[BW6_761], G1], bits, "t_ec_sage_bw6_761_g1_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp[BW6_761], G1], bits, + EC_ShortW_Jac[Fp[BW6_761], G1], bits, "t_ec_sage_bw6_761_g1_jacobian" ) # run_scalar_mul_test_vs_sage( - # ECP_ShortW_Prj[Fp[BW6_761], G2], bits, + # EC_ShortW_Prj[Fp[BW6_761], G2], bits, # "t_ec_sage_bw6_761_g2_projective" # ) # run_scalar_mul_test_vs_sage( - # ECP_ShortW_Jac[Fp[BW6_761], G2], bits, + # EC_ShortW_Jac[Fp[BW6_761], G2], bits, # "t_ec_sage_bw6_761_g2_jacobian" # ) diff --git a/tests/math_elliptic_curves/t_ec_sage_bw6_761_g2.nim b/tests/math_elliptic_curves/t_ec_sage_bw6_761_g2.nim index 505c460aa..2365a4f87 100644 --- a/tests/math_elliptic_curves/t_ec_sage_bw6_761_g2.nim +++ b/tests/math_elliptic_curves/t_ec_sage_bw6_761_g2.nim @@ -14,29 +14,29 @@ import # Test utilities ./t_ec_sage_template -# When ECP_ShortW_Aff[Fp[Foo], G1] -# and ECP_ShortW_Aff[Fp[Foo], G2] +# When EC_ShortW_Aff[Fp[Foo], G1] +# and EC_ShortW_Aff[Fp[Foo], G2] # are generated in the same file (i.e. twists and base curve are both on Fp) # this creates bad codegen, in the C code, the `value`parameter gets the wrong type # TODO: upstream -staticFor(bits, [BW6_761.getCurveOrderBitwidth()]): +staticFor(bits, [Fr[BW6_761].bits()]): # run_scalar_mul_test_vs_sage( - # ECP_ShortW_Prj[Fp[BW6_761], G1], bits, + # EC_ShortW_Prj[Fp[BW6_761], G1], bits, # "t_ec_sage_bw6_761_g1_projective" # ) # run_scalar_mul_test_vs_sage( - # ECP_ShortW_Jac[Fp[BW6_761], G1], bits, + # EC_ShortW_Jac[Fp[BW6_761], G1], bits, # "t_ec_sage_bw6_761_g1_jacobian" # ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp[BW6_761], G2], bits, + EC_ShortW_Prj[Fp[BW6_761], G2], bits, "t_ec_sage_bw6_761_g2_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp[BW6_761], G2], bits, + EC_ShortW_Jac[Fp[BW6_761], G2], bits, "t_ec_sage_bw6_761_g2_jacobian" ) diff --git a/tests/math_elliptic_curves/t_ec_sage_pallas.nim b/tests/math_elliptic_curves/t_ec_sage_pallas.nim index 6ec98100f..1632d587c 100644 --- a/tests/math_elliptic_curves/t_ec_sage_pallas.nim +++ b/tests/math_elliptic_curves/t_ec_sage_pallas.nim @@ -15,13 +15,13 @@ import # Test utilities ./t_ec_sage_template -staticFor(bits, [Pallas.getCurveOrderBitwidth()]): +staticFor(bits, [Fr[Pallas].bits()]): run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp[Pallas], G1], bits, + EC_ShortW_Prj[Fp[Pallas], G1], bits, "t_ec_sage_pallas_g1_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp[Pallas], G1], bits, + EC_ShortW_Jac[Fp[Pallas], G1], bits, "t_ec_sage_pallas_g1_jacobian" ) diff --git a/tests/math_elliptic_curves/t_ec_sage_template.nim b/tests/math_elliptic_curves/t_ec_sage_template.nim index 486235a20..965fdc417 100644 --- a/tests/math_elliptic_curves/t_ec_sage_template.nim +++ b/tests/math_elliptic_curves/t_ec_sage_template.nim @@ -31,7 +31,7 @@ export unittest, abstractions, arithmetic # Generic sandwich # -------------------------------------------------------------------------- type - TestVector*[EC: ECP_ShortW_Aff, bits: static int] = object + TestVector*[EC: EC_ShortW_Aff, bits: static int] = object id: int P: EC scalarBits: int @@ -50,7 +50,7 @@ type x: Fp2_hex y: Fp2_hex - ScalarMulTestG1[EC: ECP_ShortW_Aff, bits: static int] = object + ScalarMulTestG1[EC: EC_ShortW_Aff, bits: static int] = object curve: string group: string modulus: string @@ -62,7 +62,7 @@ type # vectors ------------------ vectors: seq[TestVector[EC, bits]] - ScalarMulTestG2[EC: ECP_ShortW_Aff, bits: static int] = object + ScalarMulTestG2[EC: EC_ShortW_Aff, bits: static int] = object curve: string group: string modulus: string @@ -92,21 +92,21 @@ proc parseHook*(src: string, pos: var int, value: var BigInt) = parseHook(src, pos, str) value.fromHex(str) -proc parseHook*(src: string, pos: var int, value: var ECP_ShortW_Aff) = +proc parseHook*(src: string, pos: var int, value: var EC_ShortW_Aff) = # Note when nim-serialization was used: - # When ECP_ShortW_Aff[Fp[Foo], G1] - # and ECP_ShortW_Aff[Fp[Foo], G2] + # When EC_ShortW_Aff[Fp[Foo], G1] + # and EC_ShortW_Aff[Fp[Foo], G2] # are generated in the same file (i.e. twists and base curve are both on Fp) # this creates bad codegen, in the C code, the `value`parameter gets the wrong type # TODO: upstream - when ECP_ShortW_Aff.F is Fp: + when EC_ShortW_Aff.F is Fp: var P: EC_G1_hex parseHook(src, pos, P) let ok = value.fromHex(P.x, P.y) doAssert ok, "\nDeserialization error on G1 for\n" & " P.x: " & P.x & "\n" & " P.y: " & P.x & "\n" - elif ECP_ShortW_Aff.F is Fp2: + elif EC_ShortW_Aff.F is Fp2: var P: EC_G2_hex parseHook(src, pos, P) let ok = value.fromHex(P.x.c0, P.x.c1, P.y.c0, P.y.c1) @@ -121,7 +121,7 @@ proc parseHook*(src: string, pos: var int, value: var ECP_ShortW_Aff) = proc loadVectors(TestType: typedesc): TestType = const group = when TestType.EC.G == G1: "G1" else: "G2" - const filename = "tv_" & $TestType.EC.F.C & "_scalar_mul_" & group & "_" & $TestType.bits & "bit.json" + const filename = "tv_" & $TestType.EC.F.Name & "_scalar_mul_" & group & "_" & $TestType.bits & "bit.json" echo "Loading: ", filename let content = readFile(TestVectorsDir/filename) result = content.fromJson(TestType) @@ -138,15 +138,15 @@ proc run_scalar_mul_test_vs_sage*( when EC.G == G1: const G1_or_G2 = "G1" - let vec = loadVectors(ScalarMulTestG1[ECP_ShortW_Aff[EC.F, EC.G], bits]) + let vec = loadVectors(ScalarMulTestG1[EC_ShortW_Aff[EC.F, EC.G], bits]) else: const G1_or_G2 = "G2" - let vec = loadVectors(ScalarMulTestG2[ECP_ShortW_Aff[EC.F, EC.G], bits]) + let vec = loadVectors(ScalarMulTestG2[EC_ShortW_Aff[EC.F, EC.G], bits]) - const coord = when EC is ECP_ShortW_Prj: " Projective coordinates " - elif EC is ECP_ShortW_Jac: " Jacobian coordinates " + const coord = when EC is EC_ShortW_Prj: " Projective coordinates " + elif EC is EC_ShortW_Jac: " Jacobian coordinates " - const testSuiteDesc = "Scalar Multiplication " & $EC.F.C & " " & G1_or_G2 & " " & coord & " vs SageMath - " & $bits & "-bit scalar" + const testSuiteDesc = "Scalar Multiplication " & $EC.F.Name & " " & G1_or_G2 & " " & coord & " vs SageMath - " & $bits & "-bit scalar" suite testSuiteDesc & " [" & $WordBitWidth & "-bit words]": for i in 0 ..< vec.vectors.len: diff --git a/tests/math_elliptic_curves/t_ec_sage_vesta.nim b/tests/math_elliptic_curves/t_ec_sage_vesta.nim index e977f61cf..3e45eb7c0 100644 --- a/tests/math_elliptic_curves/t_ec_sage_vesta.nim +++ b/tests/math_elliptic_curves/t_ec_sage_vesta.nim @@ -15,13 +15,13 @@ import # Test utilities ./t_ec_sage_template -staticFor(bits, [Vesta.getCurveOrderBitwidth()]): +staticFor(bits, [Fr[Vesta].bits()]): run_scalar_mul_test_vs_sage( - ECP_ShortW_Prj[Fp[Vesta], G1], bits, + EC_ShortW_Prj[Fp[Vesta], G1], bits, "t_ec_sage_vesta_g1_projective" ) run_scalar_mul_test_vs_sage( - ECP_ShortW_Jac[Fp[Vesta], G1], bits, + EC_ShortW_Jac[Fp[Vesta], G1], bits, "t_ec_sage_vesta_g1_jacobian" ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_add_double.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_add_double.nim index 507454c99..7aae070ad 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_add_double.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_add_double.nim @@ -17,73 +17,73 @@ const Iters = 6 run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_" & $BN254_Snarks ) run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_" & $BLS12_381 ) run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp[BLS12_377], G1], + ec = EC_ShortW_Jac[Fp[BLS12_377], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_" & $BLS12_377 ) run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp[BW6_761], G1], + ec = EC_ShortW_Jac[Fp[BW6_761], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_" & $BW6_761 ) run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp[Pallas], G1], + ec = EC_ShortW_Jac[Fp[Pallas], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_" & $Pallas ) run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp[Vesta], G1], + ec = EC_ShortW_Jac[Fp[Vesta], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_" & $Vesta ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_vartime_" & $BN254_Snarks ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_vartime_" & $BLS12_381 ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Jac[Fp[BLS12_377], G1], + ec = EC_ShortW_Jac[Fp[BLS12_377], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_vartime_" & $BLS12_377 ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Jac[Fp[BW6_761], G1], + ec = EC_ShortW_Jac[Fp[BW6_761], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_vartime_" & $BW6_761 ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Jac[Fp[Pallas], G1], + ec = EC_ShortW_Jac[Fp[Pallas], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_vartime_" & $Pallas ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Jac[Fp[Vesta], G1], + ec = EC_ShortW_Jac[Fp[Vesta], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g1_add_double_vartime_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mixed_add.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mixed_add.nim index 6b0f74d10..3e2eea043 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mixed_add.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mixed_add.nim @@ -18,37 +18,37 @@ const Iters = 6 run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $BN254_Snarks ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $BLS12_381 ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp[BLS12_377], G1], + ec = EC_ShortW_Jac[Fp[BLS12_377], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $BLS12_377 ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp[BW6_761], G1], + ec = EC_ShortW_Jac[Fp[BW6_761], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $BW6_761 ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp[Pallas], G1], + ec = EC_ShortW_Jac[Fp[Pallas], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $Pallas ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp[Vesta], G1], + ec = EC_ShortW_Jac[Fp[Vesta], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_msm.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_msm.nim index d33471dfc..eaf44f27a 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_msm.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_msm.nim @@ -17,13 +17,13 @@ import const numPoints = [1, 2, 8, 16, 32, 64, 128, 1024, 2048, 16384] # 32768, 262144, 1048576] run_EC_multi_scalar_mul_impl( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_multi_scalar_mul_" & $BN254_Snarks ) run_EC_multi_scalar_mul_impl( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_multi_scalar_mul_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_distri.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_distri.nim index 5f831476b..6a9da2e8b 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_distri.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_distri.nim @@ -18,37 +18,37 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_distributive_" & $BN254_Snarks ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_distributive_" & $BLS12_381 ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp[BLS12_377], G1], + ec = EC_ShortW_Jac[Fp[BLS12_377], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_distributive_" & $BLS12_377 ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp[BW6_761], G1], + ec = EC_ShortW_Jac[Fp[BW6_761], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_distributive_" & $BW6_761 ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp[Pallas], G1], + ec = EC_ShortW_Jac[Fp[Pallas], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_distributive_" & $Pallas ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp[Vesta], G1], + ec = EC_ShortW_Jac[Fp[Vesta], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_distributive_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_sanity.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_sanity.nim index d96ee6bcb..e781154ee 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_sanity.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_sanity.nim @@ -24,7 +24,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_sanity_" & $BN254_Snarks ) @@ -43,7 +43,7 @@ suite "Order checks on BN254_Snarks": else: let a = rng.random_unsafe(EC) - let exponent = EC.F.C.getCurveOrder() + let exponent = Fr[EC.F].getModulus() var impl = a @@ -56,8 +56,8 @@ suite "Order checks on BN254_Snarks": bool(impl.isNeutral()) bool(reference.isNeutral()) - test(ECP_ShortW_Jac[Fp[BN254_Snarks], G1], bits = BN254_Snarks.getCurveOrderBitwidth(), randZ = false) - test(ECP_ShortW_Jac[Fp[BN254_Snarks], G1], bits = BN254_Snarks.getCurveOrderBitwidth(), randZ = true) + test(EC_ShortW_Jac[Fp[BN254_Snarks], G1], bits = BN254_Snarks.bits(), randZ = false) + test(EC_ShortW_Jac[Fp[BN254_Snarks], G1], bits = BN254_Snarks.bits(), randZ = true) test "Not a point on the curve / not a square - #67": var ax, ay: Fp[BN254_Snarks] @@ -69,13 +69,13 @@ suite "Order checks on BN254_Snarks": bool not ay.sqrt_if_square() run_EC_mul_sanity_tests( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_sanity_" & $BLS12_381 ) run_EC_mul_sanity_tests( - ec = ECP_ShortW_Jac[Fp[BLS12_377], G1], + ec = EC_ShortW_Jac[Fp[BLS12_377], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_sanity_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_vs_ref.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_vs_ref.nim index a69506575..253094d7e 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_vs_ref.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_mul_vs_ref.nim @@ -18,37 +18,37 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_vs_ref_" & $BN254_Snarks ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_vs_ref_" & $BLS12_381 ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp[BLS12_377], G1], + ec = EC_ShortW_Jac[Fp[BLS12_377], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_vs_ref_" & $BLS12_377 ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp[BW6_761], G1], + ec = EC_ShortW_Jac[Fp[BW6_761], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_vs_ref_" & $BW6_761 ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp[Pallas], G1], + ec = EC_ShortW_Jac[Fp[Pallas], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_vs_ref_" & $Pallas ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp[Vesta], G1], + ec = EC_ShortW_Jac[Fp[Vesta], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g1_mul_vs_ref_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_sum_reduce.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_sum_reduce.nim index e0b3af90b..863b5b65e 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g1_sum_reduce.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g1_sum_reduce.nim @@ -17,13 +17,13 @@ import const numPoints = [1, 2, 8, 16, 128, 1024, 2048, 16384, 32768] # 262144, 1048576] run_EC_batch_add_impl( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_batch_add_" & $BN254_Snarks ) run_EC_batch_add_impl( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_batch_add_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bls12_377.nim index 4545ca6d5..604baf56b 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bls12_377.nim @@ -18,7 +18,7 @@ const Iters = 8 run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp2[BLS12_377], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_377], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g2_add_double_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bls12_381.nim index 8ac12ba41..03e0efc17 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bls12_381.nim @@ -18,7 +18,7 @@ const Iters = 8 run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp2[BLS12_381], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_381], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g2_add_double_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bn254_snarks.nim index 1cac7e6a4..bd45ce802 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bn254_snarks.nim @@ -18,7 +18,7 @@ const Iters = 8 run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Jac[Fp2[BN254_Snarks], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g2_add_double_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bw6_761.nim index 17d5eb491..4123fa376 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_add_double_bw6_761.nim @@ -17,7 +17,7 @@ const Iters = 8 run_EC_addition_tests( - ec = ECP_ShortW_Jac[Fp[BW6_761], G2], + ec = EC_ShortW_Jac[Fp[BW6_761], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_g2_add_double_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bls12_377.nim index 473bba2b1..8507f6eff 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bls12_377.nim @@ -18,7 +18,7 @@ const Iters = 12 run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp2[BLS12_377], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_377], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bls12_381.nim index 7a9a8940d..94c7ffb38 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bls12_381.nim @@ -18,7 +18,7 @@ const Iters = 12 run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp2[BLS12_381], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_381], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bn254_snarks.nim index 074ec9c29..02d180125 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bn254_snarks.nim @@ -18,7 +18,7 @@ const Iters = 12 run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Jac[Fp2[BN254_Snarks], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bw6_761.nim index e7c8926a8..22156ff16 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mixed_add_bw6_761.nim @@ -17,7 +17,7 @@ const Iters = 12 run_EC_mixed_add_impl( - ec = ECP_ShortW_Jac[Fp[BW6_761], G2], + ec = EC_ShortW_Jac[Fp[BW6_761], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_mixed_add_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bls12_377.nim index e6dcb7fb3..90a7b1c0a 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bls12_377.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp2[BLS12_377], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_377], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_distributive_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bls12_381.nim index 99397113d..61333f99a 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bls12_381.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp2[BLS12_381], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_381], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_distributive_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bn254_snarks.nim index bb8e6dc06..1afa21403 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bn254_snarks.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Jac[Fp2[BN254_Snarks], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_distributive_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bw6_761.nim index 615de9aa6..7a52a9a67 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_distri_bw6_761.nim @@ -18,7 +18,7 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Jac[Fp[BW6_761], G2], + ec = EC_ShortW_Jac[Fp[BW6_761], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_distributive_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bls12_377.nim index 115b406c6..73c7d3f3f 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bls12_377.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Jac[Fp2[BLS12_377], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_377], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_sanity_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bls12_381.nim index f0fe933e4..f8227bedd 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bls12_381.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Jac[Fp2[BLS12_381], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_381], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_sanity_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bn254_snarks.nim index 9dca22c82..bcebb3d0b 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bn254_snarks.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Jac[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Jac[Fp2[BN254_Snarks], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_sanity_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bw6_761.nim index 4c8ad9f9f..8382deeb0 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_sanity_bw6_761.nim @@ -18,7 +18,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Jac[Fp[BW6_761], G2], + ec = EC_ShortW_Jac[Fp[BW6_761], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_sanity_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bls12_377.nim index 61ba208c3..28f784f1d 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bls12_377.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp2[BLS12_377], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_377], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_vs_ref_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bls12_381.nim index 0a7f98384..b16875e00 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bls12_381.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp2[BLS12_381], G2], + ec = EC_ShortW_Jac[Fp2[BLS12_381], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_vs_ref_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bn254_snarks.nim index cabecaceb..8d43e638d 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bn254_snarks.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Jac[Fp2[BN254_Snarks], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_vs_ref_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bw6_761.nim index d16472386..b95e9f044 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jac_g2_mul_vs_ref_bw6_761.nim @@ -18,7 +18,7 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Jac[Fp[BW6_761], G2], + ec = EC_ShortW_Jac[Fp[BW6_761], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_jacobian_g2_mul_vs_ref_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_add_double.nim b/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_add_double.nim index 9a61f260e..7f5ecfb0c 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_add_double.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_add_double.nim @@ -17,37 +17,37 @@ const Iters = 6 run_EC_addition_tests( - ec = ECP_ShortW_JacExt[Fp[BN254_Snarks], G1], + ec = EC_ShortW_JacExt[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extended_g1_add_double_" & $BN254_Snarks ) run_EC_addition_tests( - ec = ECP_ShortW_JacExt[Fp[BLS12_381], G1], + ec = EC_ShortW_JacExt[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extended_g1_add_double_" & $BLS12_381 ) run_EC_addition_tests( - ec = ECP_ShortW_JacExt[Fp[BLS12_377], G1], + ec = EC_ShortW_JacExt[Fp[BLS12_377], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extended_g1_add_double_" & $BLS12_377 ) run_EC_addition_tests( - ec = ECP_ShortW_JacExt[Fp[BW6_761], G1], + ec = EC_ShortW_JacExt[Fp[BW6_761], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extended_g1_add_double_" & $BW6_761 ) run_EC_addition_tests( - ec = ECP_ShortW_JacExt[Fp[Pallas], G1], + ec = EC_ShortW_JacExt[Fp[Pallas], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extended_g1_add_double_" & $Pallas ) run_EC_addition_tests( - ec = ECP_ShortW_JacExt[Fp[Vesta], G1], + ec = EC_ShortW_JacExt[Fp[Vesta], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extended_g1_add_double_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_mixed_add.nim b/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_mixed_add.nim index e2af5bde9..b4455d18e 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_mixed_add.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_mixed_add.nim @@ -18,37 +18,37 @@ const Iters = 6 run_EC_mixed_add_impl( - ec = ECP_ShortW_JacExt[Fp[BN254_Snarks], G1], + ec = EC_ShortW_JacExt[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extendedmixed_add_" & $BN254_Snarks ) run_EC_mixed_add_impl( - ec = ECP_ShortW_JacExt[Fp[BLS12_381], G1], + ec = EC_ShortW_JacExt[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extendedmixed_add_" & $BLS12_381 ) run_EC_mixed_add_impl( - ec = ECP_ShortW_JacExt[Fp[BLS12_377], G1], + ec = EC_ShortW_JacExt[Fp[BLS12_377], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extendedmixed_add_" & $BLS12_377 ) run_EC_mixed_add_impl( - ec = ECP_ShortW_JacExt[Fp[BW6_761], G1], + ec = EC_ShortW_JacExt[Fp[BW6_761], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extendedmixed_add_" & $BW6_761 ) run_EC_mixed_add_impl( - ec = ECP_ShortW_JacExt[Fp[Pallas], G1], + ec = EC_ShortW_JacExt[Fp[Pallas], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extendedmixed_add_" & $Pallas ) run_EC_mixed_add_impl( - ec = ECP_ShortW_JacExt[Fp[Vesta], G1], + ec = EC_ShortW_JacExt[Fp[Vesta], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_jacobian_extendedmixed_add_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_sum_reduce.nim b/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_sum_reduce.nim index 01d8088f2..6d5979ca7 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_sum_reduce.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_jacext_g1_sum_reduce.nim @@ -17,13 +17,13 @@ import const numPoints = [1, 2, 8, 16, 128, 1024, 2048, 16384, 32768] # 262144, 1048576] run_EC_batch_add_impl( - ec = ECP_ShortW_JacExt[Fp[BN254_Snarks], G1], + ec = EC_ShortW_JacExt[Fp[BN254_Snarks], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_extended_batch_add_" & $BN254_Snarks ) run_EC_batch_add_impl( - ec = ECP_ShortW_JacExt[Fp[BLS12_381], G1], + ec = EC_ShortW_JacExt[Fp[BLS12_381], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_extended_batch_add_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_edge_case_345.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_edge_case_345.nim index fbb82be04..dbb317900 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_edge_case_345.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_edge_case_345.nim @@ -15,7 +15,7 @@ import constantine/math/elliptic/ec_scalar_mul_vartime type B = BigInt[254] type F = Fp[BN254Snarks] type F2 = QuadraticExt[F] -type G = ECP_ShortW_Prj[F2, G2] +type G = EC_ShortW_Prj[F2, G2] #------------------------------------------------------------------------------- @@ -67,7 +67,7 @@ proc printF2( z: F2) = proc printG( pt: G ) = - var aff : ECP_ShortW_Aff[F2, G2]; + var aff : EC_ShortW_Aff[F2, G2]; aff.affine(pt) echo(" affine x coord: "); printF2( aff.x ) echo(" affine y coord: "); printF2( aff.y ) @@ -142,7 +142,7 @@ Fp = GF(p) Fr = GF(r) A = Fp(0) B = Fp(3) -E = EllipticCurve(Fp,[A,B]) +E = EllipticCurve(Fp,[Name,B]) gx = Fp(1) gy = Fp(2) gen = E(gx,gy) # subgroup generator diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_edge_cases.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_edge_cases.nim index 7282b490c..f3dbd1962 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_edge_cases.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_edge_cases.nim @@ -24,7 +24,7 @@ import constantine/math/elliptic/ec_shortweierstrass_projective func testAddAssociativity[EC](a, b, c: EC) = - var tmp1{.noInit.}, tmp2{.noInit.}: ECP_ShortW_Prj[Fp2[BLS12_381], G2] + var tmp1{.noInit.}, tmp2{.noInit.}: EC_ShortW_Prj[Fp2[BLS12_381], G2] # r0 = (a + b) + c tmp1.sum(a, b) @@ -61,7 +61,7 @@ func testAddAssociativity[EC](a, b, c: EC) = suite "Short Weierstrass Elliptic Curve - Edge cases [" & $WordBitWidth & "-bit mode]": test "EC Add G2 is associative - #60": - var a, b, c: ECP_ShortW_Prj[Fp2[BLS12_381], G2] + var a, b, c: EC_ShortW_Prj[Fp2[BLS12_381], G2] var ax, az, bx, bz, cx, cz: Fp2[BLS12_381] ax.fromHex( @@ -99,7 +99,7 @@ suite "Short Weierstrass Elliptic Curve - Edge cases [" & $WordBitWidth & "-bit test "EC Add G2 is associative - #65-1": - var a, b, c: ECP_ShortW_Prj[Fp2[BLS12_381], G2] + var a, b, c: EC_ShortW_Prj[Fp2[BLS12_381], G2] var ax, az, bx, bz, cx, cz: Fp2[BLS12_381] ax.fromHex( @@ -137,7 +137,7 @@ suite "Short Weierstrass Elliptic Curve - Edge cases [" & $WordBitWidth & "-bit test "EC Add G2 is associative - #65-2": - var a, b, c: ECP_ShortW_Prj[Fp2[BLS12_381], G2] + var a, b, c: EC_ShortW_Prj[Fp2[BLS12_381], G2] var ax, az, bx, bz, cx, cz: Fp2[BLS12_381] ax.fromHex( diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_add_double.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_add_double.nim index ef16dd55d..a68f838de 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_add_double.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_add_double.nim @@ -9,7 +9,6 @@ import # Internals constantine/named/algebras, - constantine/platforms/type_ff, constantine/math/elliptic/ec_shortweierstrass_projective, # Test utilities ./t_ec_template @@ -18,73 +17,73 @@ const Iters = 6 run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_" & $BN254_Snarks ) run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_" & $BLS12_381 ) run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp[BLS12_377], G1], + ec = EC_ShortW_Prj[Fp[BLS12_377], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_" & $BLS12_377 ) run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp[BW6_761], G1], + ec = EC_ShortW_Prj[Fp[BW6_761], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_" & $BW6_761 ) run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp[Pallas], G1], + ec = EC_ShortW_Prj[Fp[Pallas], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_" & $Pallas ) run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp[Vesta], G1], + ec = EC_ShortW_Prj[Fp[Vesta], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_" & $Vesta ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_vartime_" & $BN254_Snarks ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_vartime_" & $BLS12_381 ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Prj[Fp[BLS12_377], G1], + ec = EC_ShortW_Prj[Fp[BLS12_377], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_vartime_" & $BLS12_377 ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Prj[Fp[BW6_761], G1], + ec = EC_ShortW_Prj[Fp[BW6_761], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_vartime_" & $BW6_761 ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Prj[Fp[Pallas], G1], + ec = EC_ShortW_Prj[Fp[Pallas], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_vartime_" & $Pallas ) run_EC_addition_vartime_tests( - ec = ECP_ShortW_Prj[Fp[Vesta], G1], + ec = EC_ShortW_Prj[Fp[Vesta], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g1_add_double_vartime_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mixed_add.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mixed_add.nim index 1e35dae49..f8e895741 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mixed_add.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mixed_add.nim @@ -18,37 +18,37 @@ const Iters = 8 run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $BN254_Snarks ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $BLS12_381 ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_377], G1], + ec = EC_ShortW_Prj[Fp[BLS12_377], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $BLS12_377 ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp[BW6_761], G1], + ec = EC_ShortW_Prj[Fp[BW6_761], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $BW6_761 ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp[Pallas], G1], + ec = EC_ShortW_Prj[Fp[Pallas], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $Pallas ) run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp[Vesta], G1], + ec = EC_ShortW_Prj[Fp[Vesta], G1], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_msm.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_msm.nim index 04ce98142..ba9485434 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_msm.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_msm.nim @@ -17,13 +17,13 @@ import const numPoints = [1, 2, 8, 16, 128, 1024, 2048, 16384] # 32768, 262144, 1048576] run_EC_multi_scalar_mul_impl( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_projective_multi_scalar_mul_" & $BN254_Snarks ) run_EC_multi_scalar_mul_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_projective_multi_scalar_mul_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_distri.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_distri.nim index df510b71e..2e9752266 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_distri.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_distri.nim @@ -18,37 +18,37 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_distributive_" & $BN254_Snarks ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_distributive_" & $BLS12_381 ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp[BLS12_377], G1], + ec = EC_ShortW_Prj[Fp[BLS12_377], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_distributive_" & $BLS12_377 ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp[BW6_761], G1], + ec = EC_ShortW_Prj[Fp[BW6_761], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_distributive_" & $BW6_761 ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp[Pallas], G1], + ec = EC_ShortW_Prj[Fp[Pallas], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_distributive_" & $Pallas ) run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp[Vesta], G1], + ec = EC_ShortW_Prj[Fp[Vesta], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_distributive_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_sanity.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_sanity.nim index 6257c063e..c85916e71 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_sanity.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_sanity.nim @@ -23,7 +23,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_sanity_" & $BN254_Snarks ) @@ -42,7 +42,7 @@ suite "Order checks on BN254_Snarks": else: let a = rng.random_unsafe(EC) - let exponent = EC.F.C.getCurveOrder() + let exponent = Fr[EC.F].getModulus() var impl = a @@ -55,8 +55,8 @@ suite "Order checks on BN254_Snarks": bool(impl.isNeutral()) bool(reference.isNeutral()) - test(ECP_ShortW_Prj[Fp[BN254_Snarks], G1], bits = BN254_Snarks.getCurveOrderBitwidth(), randZ = false) - test(ECP_ShortW_Prj[Fp[BN254_Snarks], G1], bits = BN254_Snarks.getCurveOrderBitwidth(), randZ = true) + test(EC_ShortW_Prj[Fp[BN254_Snarks], G1], bits = BN254_Snarks.bits(), randZ = false) + test(EC_ShortW_Prj[Fp[BN254_Snarks], G1], bits = BN254_Snarks.bits(), randZ = true) test "Not a point on the curve / not a square - #67": var ax, ay: Fp[BN254_Snarks] @@ -68,31 +68,31 @@ suite "Order checks on BN254_Snarks": bool not ay.sqrt_if_square() run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_sanity_" & $BLS12_381 ) run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp[BLS12_377], G1], + ec = EC_ShortW_Prj[Fp[BLS12_377], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_sanity_" & $BLS12_377 ) run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp[BW6_761], G1], + ec = EC_ShortW_Prj[Fp[BW6_761], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_sanity_" & $BW6_761 ) run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp[Pallas], G1], + ec = EC_ShortW_Prj[Fp[Pallas], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_sanity_" & $Pallas ) run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp[Vesta], G1], + ec = EC_ShortW_Prj[Fp[Vesta], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_sanity_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_vs_ref.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_vs_ref.nim index d9f053f0e..047739cfc 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_vs_ref.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_mul_vs_ref.nim @@ -18,37 +18,37 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_vs_ref_" & $BN254_Snarks ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_vs_ref_" & $BLS12_381 ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_377], G1], + ec = EC_ShortW_Prj[Fp[BLS12_377], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_vs_ref_" & $BLS12_377 ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp[BW6_761], G1], + ec = EC_ShortW_Prj[Fp[BW6_761], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_vs_ref_" & $BW6_761 ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp[Pallas], G1], + ec = EC_ShortW_Prj[Fp[Pallas], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_vs_ref_" & $Pallas ) run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp[Vesta], G1], + ec = EC_ShortW_Prj[Fp[Vesta], G1], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g1_mul_vs_ref_" & $Vesta ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_sum_reduce.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_sum_reduce.nim index e6fd296bb..5cc4a24dd 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g1_sum_reduce.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g1_sum_reduce.nim @@ -17,13 +17,13 @@ import const numPoints = [1, 2, 8, 16, 128, 1024, 2048, 16384, 32768] # 262144, 1048576] run_EC_batch_add_impl( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_projective_batch_add_" & $BN254_Snarks ) run_EC_batch_add_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_projective_batch_add_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bls12_377.nim index 447fe8ded..f41ab68c8 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bls12_377.nim @@ -18,7 +18,7 @@ const Iters = 8 run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_377], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g2_add_double_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bls12_381.nim index c07d70d65..b1f258b04 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bls12_381.nim @@ -18,7 +18,7 @@ const Iters = 8 run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_381], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g2_add_double_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bn254_snarks.nim index 2c763ac7d..bb59ee208 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bn254_snarks.nim @@ -18,7 +18,7 @@ const Iters = 8 run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g2_add_double_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bw6_761.nim index 42cf11aa7..8d7f71f4b 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_add_double_bw6_761.nim @@ -17,7 +17,7 @@ const Iters = 8 run_EC_addition_tests( - ec = ECP_ShortW_Prj[Fp[BW6_761], G2], + ec = EC_ShortW_Prj[Fp[BW6_761], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_g2_add_double_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bls12_377.nim index f50be5a83..d63b0a07e 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bls12_377.nim @@ -18,7 +18,7 @@ const Iters = 12 run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_377], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bls12_381.nim index 73bc3491a..95ab05e74 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bls12_381.nim @@ -18,7 +18,7 @@ const Iters = 12 run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_381], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bn254_snarks.nim index 5e8052088..95a9a99d6 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bn254_snarks.nim @@ -18,7 +18,7 @@ const Iters = 12 run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bw6_761.nim index 34f5ff5bf..567827d86 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mixed_add_bw6_761.nim @@ -17,7 +17,7 @@ const Iters = 12 run_EC_mixed_add_impl( - ec = ECP_ShortW_Prj[Fp[BW6_761], G2], + ec = EC_ShortW_Prj[Fp[BW6_761], G2], Iters = Iters, moduleName = "test_ec_shortweierstrass_projective_mixed_add_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bls12_377.nim index a9d1f257d..bee662dec 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bls12_377.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_377], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_distributive_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bls12_381.nim index 60da00a83..1193a7164 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bls12_381.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_381], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_distributive_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bn254_snarks.nim index 96b56d43f..caffd7786 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bn254_snarks.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_distributive_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bw6_761.nim index fcfecd9cc..02e476478 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_distri_bw6_761.nim @@ -18,7 +18,7 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_ShortW_Prj[Fp[BW6_761], G2], + ec = EC_ShortW_Prj[Fp[BW6_761], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_distributive_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bls12_377.nim index 4fc0ad39f..3af9262e5 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bls12_377.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_377], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_sanity_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bls12_381.nim index e40122c1d..13c1556a7 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bls12_381.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_381], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_sanity_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bn254_snarks.nim index 6439f83c6..a3b35c71c 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bn254_snarks.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_sanity_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bw6_761.nim index 607ad839f..ac28ba12a 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_sanity_bw6_761.nim @@ -18,7 +18,7 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_ShortW_Prj[Fp[BW6_761], G2], + ec = EC_ShortW_Prj[Fp[BW6_761], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_sanity_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bls12_377.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bls12_377.nim index 7955a925e..c0fac02a7 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bls12_377.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_377], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_vs_ref_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bls12_381.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bls12_381.nim index 82b63bae0..39da17530 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bls12_381.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_381], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_vs_ref_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bn254_snarks.nim index 9dbc04176..7b711d537 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bn254_snarks.nim @@ -19,7 +19,7 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_vs_ref_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bw6_761.nim b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bw6_761.nim index a9d8bf912..fc5b21cf9 100644 --- a/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bw6_761.nim +++ b/tests/math_elliptic_curves/t_ec_shortw_prj_g2_mul_vs_ref_bw6_761.nim @@ -18,7 +18,7 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_ShortW_Prj[Fp[BW6_761], G2], + ec = EC_ShortW_Prj[Fp[BW6_761], G2], ItersMul = ItersMul, moduleName = "test_ec_shortweierstrass_projective_g2_mul_vs_ref_" & $BW6_761 ) diff --git a/tests/math_elliptic_curves/t_ec_subgroups_bls12_377.nim b/tests/math_elliptic_curves/t_ec_subgroups_bls12_377.nim index 911e7d726..29fc15f4d 100644 --- a/tests/math_elliptic_curves/t_ec_subgroups_bls12_377.nim +++ b/tests/math_elliptic_curves/t_ec_subgroups_bls12_377.nim @@ -19,13 +19,13 @@ const ItersMul = Iters div 4 run_EC_subgroups_cofactors_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_377], G1], + ec = EC_ShortW_Prj[Fp[BLS12_377], G1], ItersMul = ItersMul, moduleName = "test_ec_subgroups_g1_" & $BLS12_377 ) run_EC_subgroups_cofactors_impl( - ec = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_377], G2], ItersMul = ItersMul, moduleName = "test_ec_subgroups_g2_" & $BLS12_377 ) diff --git a/tests/math_elliptic_curves/t_ec_subgroups_bls12_381.nim b/tests/math_elliptic_curves/t_ec_subgroups_bls12_381.nim index c8c1c4b5d..c358f207a 100644 --- a/tests/math_elliptic_curves/t_ec_subgroups_bls12_381.nim +++ b/tests/math_elliptic_curves/t_ec_subgroups_bls12_381.nim @@ -19,13 +19,13 @@ const ItersMul = Iters div 4 run_EC_subgroups_cofactors_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], ItersMul = ItersMul, moduleName = "test_ec_subgroups_g1_" & $BLS12_381 ) run_EC_subgroups_cofactors_impl( - ec = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + ec = EC_ShortW_Prj[Fp2[BLS12_381], G2], ItersMul = ItersMul, moduleName = "test_ec_subgroups_g2_" & $BLS12_381 ) diff --git a/tests/math_elliptic_curves/t_ec_subgroups_bn254_nogami.nim b/tests/math_elliptic_curves/t_ec_subgroups_bn254_nogami.nim index ee35da443..597530fec 100644 --- a/tests/math_elliptic_curves/t_ec_subgroups_bn254_nogami.nim +++ b/tests/math_elliptic_curves/t_ec_subgroups_bn254_nogami.nim @@ -19,13 +19,13 @@ const ItersMul = Iters div 4 run_EC_subgroups_cofactors_impl( - ec = ECP_ShortW_Prj[Fp[BN254_Nogami], G1], + ec = EC_ShortW_Prj[Fp[BN254_Nogami], G1], ItersMul = ItersMul, moduleName = "test_ec_subgroups_g1_" & $BN254_Nogami ) run_EC_subgroups_cofactors_impl( - ec = ECP_ShortW_Prj[Fp2[BN254_Nogami], G2], + ec = EC_ShortW_Prj[Fp2[BN254_Nogami], G2], ItersMul = ItersMul, moduleName = "test_ec_subgroups_g2_" & $BN254_Nogami ) diff --git a/tests/math_elliptic_curves/t_ec_subgroups_bn254_snarks.nim b/tests/math_elliptic_curves/t_ec_subgroups_bn254_snarks.nim index d099997b8..79a59ae21 100644 --- a/tests/math_elliptic_curves/t_ec_subgroups_bn254_snarks.nim +++ b/tests/math_elliptic_curves/t_ec_subgroups_bn254_snarks.nim @@ -19,13 +19,13 @@ const ItersMul = Iters div 4 run_EC_subgroups_cofactors_impl( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], ItersMul = ItersMul, moduleName = "test_ec_subgroups_g1_" & $BN254_Snarks ) run_EC_subgroups_cofactors_impl( - ec = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + ec = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], ItersMul = ItersMul, moduleName = "test_ec_subgroups_g2_" & $BN254_Snarks ) diff --git a/tests/math_elliptic_curves/t_ec_template.nim b/tests/math_elliptic_curves/t_ec_template.nim index 902b45cda..aab7ff835 100644 --- a/tests/math_elliptic_curves/t_ec_template.nim +++ b/tests/math_elliptic_curves/t_ec_template.nim @@ -43,22 +43,22 @@ export unittest, abstractions, arithmetic # Generic sandwich # Hence we do not expose `sum` or `+=` for extended jacobian operation to prevent `vartime` mistakes # we create a local `sum` or `+=` for this module only -func sum[F; G: static Subgroup](r: var ECP_ShortW_JacExt[F, G], P, Q: ECP_ShortW_JacExt[F, G]) = +func sum[F; G: static Subgroup](r: var EC_ShortW_JacExt[F, G], P, Q: EC_ShortW_JacExt[F, G]) = r.sum_vartime(P, Q) -func `+=`[F; G: static Subgroup](P: var ECP_ShortW_JacExt[F, G], Q: ECP_ShortW_JacExt[F, G]) = +func `+=`[F; G: static Subgroup](P: var EC_ShortW_JacExt[F, G], Q: EC_ShortW_JacExt[F, G]) = P.sum_vartime(P, Q) -func madd[F; G: static Subgroup](r: var ECP_ShortW_JacExt[F, G], P: ECP_ShortW_JacExt[F, G], Q: ECP_ShortW_Aff[F, G]) = - r.madd_vartime(P, Q) -func `+=`[F; G: static Subgroup](P: var ECP_ShortW_JacExt[F, G], Q: ECP_ShortW_Aff[F, G]) = - P.madd_vartime(P, Q) +func mixedSum[F; G: static Subgroup](r: var EC_ShortW_JacExt[F, G], P: EC_ShortW_JacExt[F, G], Q: EC_ShortW_Aff[F, G]) = + r.mixedSum_vartime(P, Q) +func `+=`[F; G: static Subgroup](P: var EC_ShortW_JacExt[F, G], Q: EC_ShortW_Aff[F, G]) = + P.mixedSum_vartime(P, Q) # Twisted Edwards bindings # ---------------------------------- -template G(EC: type ECP_TwEdwards_Prj): string = +template G(EC: type EC_TwEdw_Prj): string = ## Twisted Edwards curve don't have a G parameter "" -template sum_vartime(r: var ECP_TwEdwards_Prj, P, Q: ECP_TwEdwards_Prj) = +template sum_vartime(r: var EC_TwEdw_Prj, P, Q: EC_TwEdw_Prj) = r.sum(P, Q) # ---------------------------------- @@ -70,7 +70,7 @@ type Long01Sequence func random_point*(rng: var RngState, EC: typedesc, randZ: bool, gen: RandomGen): EC {.noInit.} = - when EC is ECP_ShortW_Aff: + when EC is EC_ShortW_Aff: if gen == Uniform: result = rng.random_unsafe(EC) elif gen == HighHammingWeight: @@ -103,7 +103,7 @@ proc run_EC_addition_tests*( echo "\n------------------------------------------------------\n" echo moduleName, " xoshiro512** seed: ", seed - const testSuiteDesc = "Elliptic curve in " & $ec.F.C.getEquationForm() & " form" + const testSuiteDesc = "Elliptic curve in " & $ec.F.Name.getEquationForm() & " form" suite testSuiteDesc & " - " & $ec & " - [" & $WordBitWidth & "-bit mode]": test "The infinity point is the neutral element w.r.t. to EC " & " addition": @@ -290,7 +290,7 @@ proc run_EC_addition_vartime_tests*( echo "\n------------------------------------------------------\n" echo moduleName, " xoshiro512** seed: ", seed - const testSuiteDesc = "Elliptic curve in " & $ec.F.C.getEquationForm() & " form" + const testSuiteDesc = "Elliptic curve in " & $ec.F.Name.getEquationForm() & " form" suite testSuiteDesc & " - " & $ec & " (vartime) - [" & $WordBitWidth & "-bit mode]": test "The infinity point is the neutral element w.r.t. to EC " & $ec.G & " addition (vartime)": @@ -477,7 +477,7 @@ proc run_EC_mul_sanity_tests*( echo "\n------------------------------------------------------\n" echo moduleName, " xoshiro512** seed: ", seed - const testSuiteDesc = "Elliptic curve in " & $ec.F.C.getEquationForm() & " form" + const testSuiteDesc = "Elliptic curve in " & $ec.F.Name.getEquationForm() & " form" suite testSuiteDesc & " - " & $ec & " - [" & $WordBitWidth & "-bit mode]": test "EC " & " mul [0]P == Inf": @@ -510,12 +510,12 @@ proc run_EC_mul_sanity_tests*( # refWNaf(bits, w = 8) # refWNaf(bits, w = 13) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Long01Sequence) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Long01Sequence) test "EC " & " mul [1]P == P": proc test(EC: typedesc, bits: static int, randZ: bool, gen: RandomGen) = @@ -536,12 +536,12 @@ proc run_EC_mul_sanity_tests*( bool(impl == a) bool(reference == a) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Long01Sequence) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Long01Sequence) test "EC " & " mul [2]P == P.double()": proc test(EC: typedesc, bits: static int, randZ: bool, gen: RandomGen) = @@ -564,12 +564,12 @@ proc run_EC_mul_sanity_tests*( bool(impl == doubleA) bool(reference == doubleA) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Long01Sequence) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Long01Sequence) proc run_EC_mul_distributive_tests*( ec: typedesc, @@ -582,7 +582,7 @@ proc run_EC_mul_distributive_tests*( echo "\n------------------------------------------------------\n" echo moduleName, " xoshiro512** seed: ", seed - const testSuiteDesc = "Elliptic curve in " & $ec.F.C.getEquationForm() & " form" + const testSuiteDesc = "Elliptic curve in " & $ec.F.Name.getEquationForm() & " form" suite testSuiteDesc & " - " & $ec & " - [" & $WordBitWidth & "-bit mode]": @@ -627,12 +627,12 @@ proc run_EC_mul_distributive_tests*( bool(fReference == kakbRef) bool(fImpl == fReference) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Long01Sequence) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Long01Sequence) proc run_EC_mul_vs_ref_impl*( ec: typedesc, @@ -645,7 +645,7 @@ proc run_EC_mul_vs_ref_impl*( echo "\n------------------------------------------------------\n" echo moduleName, " xoshiro512** seed: ", seed - const testSuiteDesc = "Elliptic curve in " & $ec.F.C.getEquationForm() & " form" + const testSuiteDesc = "Elliptic curve in " & $ec.F.Name.getEquationForm() & " form" suite testSuiteDesc & " - " & $ec & " - [" & $WordBitWidth & "-bit mode]": test "EC " & $ec.G & " mul constant-time is equivalent to a simple double-and-add and recoded algorithms": @@ -678,41 +678,41 @@ proc run_EC_mul_vs_ref_impl*( refWNaf(3) refWNaf(5) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = false, gen = Long01Sequence) - test(ec, bits = ec.F.C.getCurveOrderBitwidth(), randZ = true, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Uniform) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits(), randZ = false, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits(), randZ = true, gen = Long01Sequence) # Scalars that doesn't uses the full bit length - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 2, randZ = false, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 2, randZ = true, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 2, randZ = false, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 2, randZ = true, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 2, randZ = false, gen = Long01Sequence) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 2, randZ = true, gen = Long01Sequence) - - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 4, randZ = false, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 4, randZ = true, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 4, randZ = false, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 4, randZ = true, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 4, randZ = false, gen = Long01Sequence) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() - 4, randZ = true, gen = Long01Sequence) - - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 2, randZ = false, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 2, randZ = true, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 2, randZ = false, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 2, randZ = true, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 2, randZ = false, gen = Long01Sequence) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 2, randZ = true, gen = Long01Sequence) - - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 4, randZ = false, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 4, randZ = true, gen = Uniform) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 4, randZ = false, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 4, randZ = true, gen = HighHammingWeight) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 4, randZ = false, gen = Long01Sequence) - test(ec, bits = ec.F.C.getCurveOrderBitwidth() div 4, randZ = true, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits() - 2, randZ = false, gen = Uniform) + test(ec, bits = ec.getScalarField().bits() - 2, randZ = true, gen = Uniform) + test(ec, bits = ec.getScalarField().bits() - 2, randZ = false, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits() - 2, randZ = true, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits() - 2, randZ = false, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits() - 2, randZ = true, gen = Long01Sequence) + + test(ec, bits = ec.getScalarField().bits() - 4, randZ = false, gen = Uniform) + test(ec, bits = ec.getScalarField().bits() - 4, randZ = true, gen = Uniform) + test(ec, bits = ec.getScalarField().bits() - 4, randZ = false, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits() - 4, randZ = true, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits() - 4, randZ = false, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits() - 4, randZ = true, gen = Long01Sequence) + + test(ec, bits = ec.getScalarField().bits() div 2, randZ = false, gen = Uniform) + test(ec, bits = ec.getScalarField().bits() div 2, randZ = true, gen = Uniform) + test(ec, bits = ec.getScalarField().bits() div 2, randZ = false, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits() div 2, randZ = true, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits() div 2, randZ = false, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits() div 2, randZ = true, gen = Long01Sequence) + + test(ec, bits = ec.getScalarField().bits() div 4, randZ = false, gen = Uniform) + test(ec, bits = ec.getScalarField().bits() div 4, randZ = true, gen = Uniform) + test(ec, bits = ec.getScalarField().bits() div 4, randZ = false, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits() div 4, randZ = true, gen = HighHammingWeight) + test(ec, bits = ec.getScalarField().bits() div 4, randZ = false, gen = Long01Sequence) + test(ec, bits = ec.getScalarField().bits() div 4, randZ = true, gen = Long01Sequence) proc run_EC_mixed_add_impl*( ec: typedesc, @@ -733,7 +733,7 @@ proc run_EC_mixed_add_impl*( for _ in 0 ..< Iters: let a = rng.random_point(EC, randZ, gen) let b = rng.random_point(EC, randZ, gen) - var bAff: ECP_ShortW_Aff[EC.F, EC.G] + var bAff: EC_ShortW_Aff[EC.F, EC.G] var bz1: EC bAff.affine(b) bz1.fromAffine(bAff) # internals special-case Z=1 @@ -741,10 +741,10 @@ proc run_EC_mixed_add_impl*( var r_generic, r_mixed, r_vartime, r_vartime2, r_vartime3: EC r_generic.sum(a, b) - r_mixed.madd(a, bAff) + r_mixed.mixedSum(a, bAff) r_vartime.sum_vartime(a, bz1) r_vartime2.sum_vartime(a, b) - r_vartime3.madd_vartime(a, bAff) + r_vartime3.mixedSum_vartime(a, bAff) check: bool(r_generic == r_mixed) @@ -763,7 +763,7 @@ proc run_EC_mixed_add_impl*( proc test(EC: typedesc, randZ: bool, gen: RandomGen) = for _ in 0 ..< Iters: let a = rng.random_point(EC, randZ, gen) - var aAff: ECP_ShortW_Aff[EC.F, EC.G] + var aAff: EC_ShortW_Aff[EC.F, EC.G] var az1: EC aAff.affine(a) az1.fromAffine(aAff) @@ -771,10 +771,10 @@ proc run_EC_mixed_add_impl*( var r_generic, r_mixed, r_vartime, r_vartime2, r_vartime3: EC r_generic.double(a) - r_mixed.madd(a, aAff) + r_mixed.mixedSum(a, aAff) r_vartime.sum_vartime(a, a) r_vartime2.sum_vartime(a, az1) - r_vartime3.madd_vartime(a, aAff) + r_vartime3.mixedSum_vartime(a, aAff) check: bool(r_generic == r_mixed) bool(r_generic == r_vartime) @@ -789,7 +789,7 @@ proc run_EC_mixed_add_impl*( r_vartime2 = az1 r_vartime2.sum_vartime(r_vartime2, az1) r_vartime3 = a - r_vartime3.madd_vartime(r_vartime3, aAff) + r_vartime3.mixedSum_vartime(r_vartime3, aAff) check: bool(r_generic == r_mixed) bool(r_generic == r_vartime) @@ -808,12 +808,12 @@ proc run_EC_mixed_add_impl*( for _ in 0 ..< Iters: var a{.noInit.}: EC a.setNeutral() - let bAff = rng.random_point(ECP_ShortW_Aff[EC.F, EC.G], randZ = false, gen) + let bAff = rng.random_point(EC_ShortW_Aff[EC.F, EC.G], randZ = false, gen) var r_mixed{.noInit.}: EC - r_mixed.madd(a, bAff) + r_mixed.mixedSum(a, bAff) - var r{.noInit.}: ECP_ShortW_Aff[EC.F, EC.G] + var r{.noInit.}: EC_ShortW_Aff[EC.F, EC.G] r.affine(r_mixed) # Aliasing test @@ -830,7 +830,7 @@ proc run_EC_mixed_add_impl*( a.setNeutral() r_vartime.sum_vartime(a, b) - r_vartime2.madd_vartime(a, bAff) + r_vartime2.mixedSum_vartime(a, bAff) check: bool(r_vartime == r_mixed) @@ -854,11 +854,11 @@ proc run_EC_mixed_add_impl*( proc test(EC: typedesc, randZ: bool, gen: RandomGen) = for _ in 0 ..< Iters: let a = rng.random_point(EC, randZ, gen) - var bAff{.noInit.}: ECP_ShortW_Aff[EC.F, EC.G] + var bAff{.noInit.}: EC_ShortW_Aff[EC.F, EC.G] bAff.setNeutral() var r{.noInit.}: EC - r.madd(a, bAff) + r.mixedSum(a, bAff) check: bool(r == a) @@ -872,7 +872,7 @@ proc run_EC_mixed_add_impl*( b.fromAffine(bAff) r_vartime.sum_vartime(a, b) - r_vartime2.madd_vartime(a, bAff) + r_vartime2.mixedSum_vartime(a, bAff) check: bool(r_vartime == r) @@ -899,12 +899,12 @@ proc run_EC_mixed_add_impl*( proc test(EC: typedesc, randZ: bool, gen: RandomGen) = for _ in 0 ..< Iters: let a = rng.random_point(EC, randZ, gen) - var naAff{.noInit.}: ECP_ShortW_Aff[EC.F, EC.G] + var naAff{.noInit.}: EC_ShortW_Aff[EC.F, EC.G] naAff.affine(a) naAff.neg() var r{.noInit.}: EC - r.madd(a, naAff) + r.mixedSum(a, naAff) check: r.isNeutral().bool @@ -919,7 +919,7 @@ proc run_EC_mixed_add_impl*( na.fromAffine(naAff) r_vartime.sum_vartime(a, na) - r_vartime2.madd_vartime(a, naAff) + r_vartime2.mixedSum_vartime(a, naAff) check: bool(r_vartime == r) @@ -929,7 +929,7 @@ proc run_EC_mixed_add_impl*( r_vartime = a r_vartime.sum_vartime(r_vartime, na) r_vartime2 = a - r_vartime2.madd_vartime(r_vartime2, naAff) + r_vartime2.mixedSum_vartime(r_vartime2, naAff) check: bool(r_vartime == r) @@ -983,7 +983,7 @@ proc run_EC_subgroups_cofactors_impl*( for _ in 0 ..< ItersMul: let P = rng.random_point(EC, randZ, gen) var rP = P - rP.scalarMulGeneric(EC.F.C.getCurveOrder()) + rP.scalarMulGeneric(Fr[EC.F].getModulus()) if bool rP.isNeutral(): inSubgroup += 1 doAssert bool P.isInSubgroup(), "Subgroup check issue on " & $EC & " with P: " & P.toHex() @@ -995,7 +995,7 @@ proc run_EC_subgroups_cofactors_impl*( var rQ: typeof(rP) Q.clearCofactor() rQ = Q - rQ.scalarMulGeneric(EC.F.C.getCurveOrder()) + rQ.scalarMulGeneric(Fr[EC.F].getModulus()) doAssert bool rQ.isNeutral(), "Cofactor clearing issue on " & $EC & " with Q: " & Q.toHex() doAssert bool Q.isInSubgroup(), "Subgroup check issue on " & $EC & " with Q: " & Q.toHex() @@ -1024,7 +1024,7 @@ proc run_EC_affine_conversion*( echo "\n------------------------------------------------------\n" echo moduleName, " xoshiro512** seed: ", seed - const testSuiteDesc = "Elliptic curve in " & $ec.F.C.getEquationForm() & " form" + const testSuiteDesc = "Elliptic curve in " & $ec.F.Name.getEquationForm() & " form" suite testSuiteDesc & " - " & $ec & " - [" & $WordBitWidth & "-bit mode]": test "EC " & $ec.G & " batchAffine is consistent with single affine conversion": @@ -1078,7 +1078,7 @@ proc run_EC_conversion_failures*( suite moduleName & " - [" & $WordBitWidth & "-bit mode]": test "EC batchAffine fuzzing failures ": proc test_bn254_snarks_g1(ECP: type) = - type ECP_Aff = ECP_ShortW_Aff[Fp[BN254_Snarks], G1] + type ECP_Aff = EC_ShortW_Aff[Fp[BN254_Snarks], G1] let Ps = [ ECP.fromHex( @@ -1171,8 +1171,8 @@ proc run_EC_conversion_failures*( for i in 0 ..< 10: doAssert bool(Qs[i] == Rs[i]) - test_bn254_snarks_g1(ECP_ShortW_Prj[Fp[BN254_Snarks], G1]) - test_bn254_snarks_g1(ECP_ShortW_Jac[Fp[BN254_Snarks], G1]) + test_bn254_snarks_g1(EC_ShortW_Prj[Fp[BN254_Snarks], G1]) + test_bn254_snarks_g1(EC_ShortW_Jac[Fp[BN254_Snarks], G1]) proc run_EC_batch_add_impl*[N: static int]( ec: typedesc, @@ -1191,10 +1191,10 @@ proc run_EC_batch_add_impl*[N: static int]( for n in numPoints: test $ec & " sum reduction (N=" & $n & ")": proc test(EC: typedesc, gen: RandomGen) = - var points = newSeq[ECP_ShortW_Aff[EC.F, EC.G]](n) + var points = newSeq[EC_ShortW_Aff[EC.F, EC.G]](n) for i in 0 ..< n: - points[i] = rng.random_point(ECP_ShortW_Aff[EC.F, EC.G], randZ = false, gen) + points[i] = rng.random_point(EC_ShortW_Aff[EC.F, EC.G], randZ = false, gen) var r_batch{.noinit.}, r_ref{.noInit.}: EC @@ -1213,19 +1213,19 @@ proc run_EC_batch_add_impl*[N: static int]( test "EC " & $ec.G & " sum reduction (N=" & $n & ") - special cases": proc test(EC: typedesc, gen: RandomGen) = - var points = newSeq[ECP_ShortW_Aff[EC.F, EC.G]](n) + var points = newSeq[EC_ShortW_Aff[EC.F, EC.G]](n) let halfN = n div 2 for i in 0 ..< halfN: - points[i] = rng.random_point(ECP_ShortW_Aff[EC.F, EC.G], randZ = false, gen) + points[i] = rng.random_point(EC_ShortW_Aff[EC.F, EC.G], randZ = false, gen) for i in halfN ..< n: # The special cases test relies on internal knowledge that we sum(points[i], points[i+n/2] # It should be changed if scheduling change, for example if we sum(points[2*i], points[2*i+1]) let c = rng.random_unsafe(3) if c == 0: - points[i] = rng.random_point(ECP_ShortW_Aff[EC.F, EC.G], randZ = false, gen) + points[i] = rng.random_point(EC_ShortW_Aff[EC.F, EC.G], randZ = false, gen) elif c == 1: points[i] = points[i-halfN] else: @@ -1260,17 +1260,17 @@ proc run_EC_multi_scalar_mul_impl*[N: static int]( suite testSuiteDesc & " - " & $ec & " - [" & $WordBitWidth & "-bit mode]": for n in numPoints: - let bucketBits = bestBucketBitSize(n, ec.F.C.getCurveOrderBitwidth(), useSignedBuckets = false, useManualTuning = false) + let bucketBits = bestBucketBitSize(n, ec.getScalarField().bits(), useSignedBuckets = false, useManualTuning = false) test $ec & " Multi-scalar-mul (N=" & $n & ", bucket bits: " & $bucketBits & ")": proc test(EC: typedesc, gen: RandomGen) = var points = newSeq[affine(EC)](n) - var coefs = newSeq[BigInt[EC.F.C.getCurveOrderBitwidth()]](n) + var coefs = newSeq[BigInt[EC.getScalarField().bits()]](n) for i in 0 ..< n: var tmp = rng.random_unsafe(EC) tmp.clearCofactor() points[i].affine(tmp) - coefs[i] = rng.random_unsafe(BigInt[EC.F.C.getCurveOrderBitwidth()]) + coefs[i] = rng.random_unsafe(BigInt[EC.getScalarField().bits()]) var naive, naive_tmp: EC naive.setNeutral() diff --git a/tests/math_elliptic_curves/t_ec_twedwards_prj_add_double.nim b/tests/math_elliptic_curves/t_ec_twedw_prj_add_double.nim similarity index 86% rename from tests/math_elliptic_curves/t_ec_twedwards_prj_add_double.nim rename to tests/math_elliptic_curves/t_ec_twedw_prj_add_double.nim index 7c9edc543..cfd9092b4 100644 --- a/tests/math_elliptic_curves/t_ec_twedwards_prj_add_double.nim +++ b/tests/math_elliptic_curves/t_ec_twedw_prj_add_double.nim @@ -17,25 +17,25 @@ const Iters = 8 run_EC_addition_tests( - ec = ECP_TwEdwards_Prj[Fp[Edwards25519]], + ec = EC_TwEdw_Prj[Fp[Edwards25519]], Iters = Iters, moduleName = "test_ec_twistededwards_projective_add_double_" & $Edwards25519 ) run_EC_addition_tests( - ec = ECP_TwEdwards_Prj[Fp[Jubjub]], + ec = EC_TwEdw_Prj[Fp[Jubjub]], Iters = Iters, moduleName = "test_ec_twistededwards_projective_add_double_" & $Jubjub ) run_EC_addition_tests( - ec = ECP_TwEdwards_Prj[Fp[Bandersnatch]], + ec = EC_TwEdw_Prj[Fp[Bandersnatch]], Iters = Iters, moduleName = "test_ec_twistededwards_projective_add_double_" & $Bandersnatch ) run_EC_addition_tests( - ec = ECP_TwEdwards_Prj[Fp[Banderwagon]], + ec = EC_TwEdw_Prj[Fp[Banderwagon]], Iters = Iters, moduleName = "test_ec_twistededwards_projective_add_double_" & $Banderwagon ) diff --git a/tests/math_elliptic_curves/t_ec_twedwards_prj_msm.nim b/tests/math_elliptic_curves/t_ec_twedw_prj_msm.nim similarity index 95% rename from tests/math_elliptic_curves/t_ec_twedwards_prj_msm.nim rename to tests/math_elliptic_curves/t_ec_twedw_prj_msm.nim index 5fcf9a4cc..ba0b5ec69 100644 --- a/tests/math_elliptic_curves/t_ec_twedwards_prj_msm.nim +++ b/tests/math_elliptic_curves/t_ec_twedw_prj_msm.nim @@ -17,7 +17,7 @@ import const numPoints = [1, 2, 8, 16, 32, 64, 128, 1024, 2048, 16384] # 32768, 262144, 1048576] run_EC_multi_scalar_mul_impl( - ec = ECP_TwEdwards_Prj[Fp[Bandersnatch]], + ec = EC_TwEdw_Prj[Fp[Bandersnatch]], numPoints = numPoints, moduleName = "test_ec_twistededwards_prj_multi_scalar_mul_" & $Bandersnatch ) diff --git a/tests/math_elliptic_curves/t_ec_twedwards_prj_mul_distri.nim b/tests/math_elliptic_curves/t_ec_twedw_prj_mul_distri.nim similarity index 87% rename from tests/math_elliptic_curves/t_ec_twedwards_prj_mul_distri.nim rename to tests/math_elliptic_curves/t_ec_twedw_prj_mul_distri.nim index c09a4adda..a70f1d037 100644 --- a/tests/math_elliptic_curves/t_ec_twedwards_prj_mul_distri.nim +++ b/tests/math_elliptic_curves/t_ec_twedw_prj_mul_distri.nim @@ -18,25 +18,25 @@ const ItersMul = Iters div 4 run_EC_mul_distributive_tests( - ec = ECP_TwEdwards_Prj[Fp[Edwards25519]], + ec = EC_TwEdw_Prj[Fp[Edwards25519]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_distributive_" & $Edwards25519 ) run_EC_mul_distributive_tests( - ec = ECP_TwEdwards_Prj[Fp[Jubjub]], + ec = EC_TwEdw_Prj[Fp[Jubjub]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_distributive_" & $Jubjub ) run_EC_mul_distributive_tests( - ec = ECP_TwEdwards_Prj[Fp[Bandersnatch]], + ec = EC_TwEdw_Prj[Fp[Bandersnatch]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_distributive_" & $Bandersnatch ) run_EC_mul_distributive_tests( - ec = ECP_TwEdwards_Prj[Fp[Banderwagon]], + ec = EC_TwEdw_Prj[Fp[Banderwagon]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_distributive_" & $Banderwagon ) diff --git a/tests/math_elliptic_curves/t_ec_twedwards_prj_mul_sanity.nim b/tests/math_elliptic_curves/t_ec_twedw_prj_mul_sanity.nim similarity index 89% rename from tests/math_elliptic_curves/t_ec_twedwards_prj_mul_sanity.nim rename to tests/math_elliptic_curves/t_ec_twedw_prj_mul_sanity.nim index c993d5a99..e040b1e73 100644 --- a/tests/math_elliptic_curves/t_ec_twedwards_prj_mul_sanity.nim +++ b/tests/math_elliptic_curves/t_ec_twedw_prj_mul_sanity.nim @@ -18,19 +18,19 @@ const ItersMul = Iters div 4 run_EC_mul_sanity_tests( - ec = ECP_TwEdwards_Prj[Fp[Edwards25519]], + ec = EC_TwEdw_Prj[Fp[Edwards25519]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_sanity_" & $Edwards25519 ) run_EC_mul_sanity_tests( - ec = ECP_TwEdwards_Prj[Fp[Jubjub]], + ec = EC_TwEdw_Prj[Fp[Jubjub]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_sanity_" & $Jubjub ) run_EC_mul_sanity_tests( - ec = ECP_TwEdwards_Prj[Fp[Bandersnatch]], + ec = EC_TwEdw_Prj[Fp[Bandersnatch]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_sanity_" & $Bandersnatch ) diff --git a/tests/math_elliptic_curves/t_ec_twedwards_prj_mul_vs_ref.nim b/tests/math_elliptic_curves/t_ec_twedw_prj_mul_vs_ref.nim similarity index 89% rename from tests/math_elliptic_curves/t_ec_twedwards_prj_mul_vs_ref.nim rename to tests/math_elliptic_curves/t_ec_twedw_prj_mul_vs_ref.nim index 97e2373ac..22e09444d 100644 --- a/tests/math_elliptic_curves/t_ec_twedwards_prj_mul_vs_ref.nim +++ b/tests/math_elliptic_curves/t_ec_twedw_prj_mul_vs_ref.nim @@ -18,19 +18,19 @@ const ItersMul = Iters div 4 run_EC_mul_vs_ref_impl( - ec = ECP_TwEdwards_Prj[Fp[Edwards25519]], + ec = EC_TwEdw_Prj[Fp[Edwards25519]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_vs_ref_" & $Edwards25519 ) run_EC_mul_vs_ref_impl( - ec = ECP_TwEdwards_Prj[Fp[Jubjub]], + ec = EC_TwEdw_Prj[Fp[Jubjub]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_vs_ref_" & $Jubjub ) run_EC_mul_vs_ref_impl( - ec = ECP_TwEdwards_Prj[Fp[Bandersnatch]], + ec = EC_TwEdw_Prj[Fp[Bandersnatch]], ItersMul = ItersMul, moduleName = "test_ec_twistededwards_projective_mul_vs_ref_" & $Bandersnatch ) diff --git a/tests/math_extension_fields/t_fp12_exponentiation.nim b/tests/math_extension_fields/t_fp12_exponentiation.nim index 044e113d3..25351073b 100644 --- a/tests/math_extension_fields/t_fp12_exponentiation.nim +++ b/tests/math_extension_fields/t_fp12_exponentiation.nim @@ -45,9 +45,9 @@ func random_elem(rng: var RngState, F: typedesc, gen: RandomGen): F {.inline, no else: result = rng.random_long01Seq(F) -proc test_sameBaseProduct(C: static Curve, gen: RandomGen) = +proc test_sameBaseProduct(Name: static Algebra, gen: RandomGen) = ## xᴬ xᴮ = xᴬ⁺ᴮ - product of power - let x = rng.random_elem(Fp12[C], gen) + let x = rng.random_elem(Fp12[Name], gen) var a = rng.random_elem(BigInt[128], gen) var b = rng.random_elem(BigInt[128], gen) @@ -70,9 +70,9 @@ proc test_sameBaseProduct(C: static Curve, gen: RandomGen) = xa *= xb doAssert: bool(xa == xapb) -proc test_powpow(C: static Curve, gen: RandomGen) = +proc test_powpow(Name: static Algebra, gen: RandomGen) = ## (xᴬ)ᴮ = xᴬᴮ - power of power - var x = rng.random_elem(Fp12[C], gen) + var x = rng.random_elem(Fp12[Name], gen) var a = rng.random_elem(BigInt[128], gen) var b = rng.random_elem(BigInt[128], gen) @@ -88,14 +88,14 @@ proc test_powpow(C: static Curve, gen: RandomGen) = y.pow_vartime(ab, window = 3) doAssert: bool(x == y) -proc test_powprod(C: static Curve, gen: RandomGen) = +proc test_powprod(Name: static Algebra, gen: RandomGen) = ## (xy)ᴬ = xᴬyᴬ - power of product - var x = rng.random_elem(Fp12[C], gen) - var y = rng.random_elem(Fp12[C], gen) + var x = rng.random_elem(Fp12[Name], gen) + var y = rng.random_elem(Fp12[Name], gen) let a = rng.random_elem(BigInt[128], gen) - var xy{.noInit.}: Fp12[C] + var xy{.noInit.}: Fp12[Name] xy.prod(x, y) xy.pow_vartime(a, window=3) @@ -107,25 +107,25 @@ proc test_powprod(C: static Curve, gen: RandomGen) = doAssert: bool(x == xy) -proc test_pow0(C: static Curve, gen: RandomGen) = +proc test_pow0(Name: static Algebra, gen: RandomGen) = ## x⁰ = 1 - var x = rng.random_elem(Fp12[C], gen) + var x = rng.random_elem(Fp12[Name], gen) var a: BigInt[128] # 0-init x.pow_vartime(a, window=3) doAssert: bool x.isOne() -proc test_0pow0(C: static Curve, gen: RandomGen) = +proc test_0pow0(Name: static Algebra, gen: RandomGen) = ## 0⁰ = 1 - var x: Fp12[C] # 0-init + var x: Fp12[Name] # 0-init var a: BigInt[128] # 0-init x.pow_vartime(a, window=3) doAssert: bool x.isOne() -proc test_powinv(C: static Curve, gen: RandomGen) = +proc test_powinv(Name: static Algebra, gen: RandomGen) = ## xᴬ / xᴮ = xᴬ⁻ᴮ - quotient of power - let x = rng.random_elem(Fp12[C], gen) + let x = rng.random_elem(Fp12[Name], gen) var a = rng.random_elem(BigInt[128], gen) var b = rng.random_elem(BigInt[128], gen) @@ -152,10 +152,10 @@ proc test_powinv(C: static Curve, gen: RandomGen) = doAssert: bool(xa == xamb) -proc test_invpow(C: static Curve, gen: RandomGen) = +proc test_invpow(Name: static Algebra, gen: RandomGen) = ## (x / y)ᴬ = xᴬ / yᴬ - power of quotient - let x = rng.random_elem(Fp12[C], gen) - let y = rng.random_elem(Fp12[C], gen) + let x = rng.random_elem(Fp12[Name], gen) + let y = rng.random_elem(Fp12[Name], gen) var a = rng.random_elem(BigInt[128], gen) diff --git a/tests/math_extension_fields/t_fp2_sqrt.nim b/tests/math_extension_fields/t_fp2_sqrt.nim index 85a77beb0..427826539 100644 --- a/tests/math_extension_fields/t_fp2_sqrt.nim +++ b/tests/math_extension_fields/t_fp2_sqrt.nim @@ -47,10 +47,10 @@ func random_elem(rng: var RngState, F: typedesc, gen: RandomGen): F {.inline, no else: result = rng.random_long01Seq(F) -proc randomSqrtCheck(C: static Curve, gen: RandomGen) = +proc randomSqrtCheck(Name: static Algebra, gen: RandomGen) = for _ in 0 ..< Iters: - let a = rng.random_elem(Fp2[C], gen) - var na{.noInit.}: Fp2[C] + let a = rng.random_elem(Fp2[Name], gen) + var na{.noInit.}: Fp2[Name] na.neg(a) var a2 = a diff --git a/tests/math_extension_fields/t_fp_tower_frobenius_template.nim b/tests/math_extension_fields/t_fp_tower_frobenius_template.nim index e927fd08f..c3f6bed46 100644 --- a/tests/math_extension_fields/t_fp_tower_frobenius_template.nim +++ b/tests/math_extension_fields/t_fp_tower_frobenius_template.nim @@ -29,7 +29,7 @@ export unittest # Generic sandwich echo "\n------------------------------------------------------\n" -template ExtField(degree: static int, curve: static Curve): untyped = +template ExtField(degree: static int, name: static Algebra): untyped = when degree == 2: Fp2[curve] elif degree == 4: @@ -74,7 +74,7 @@ proc runFrobeniusTowerTests*[N]( var a = rng.random_elem(Field, gen) var fa {.noInit.}: typeof(a) fa.frobenius_map(a, k = 1) - a.pow_vartime(Field.fieldMod(), window = 3) + a.pow_vartime(Field.getModulus(), window = 3) check: bool(a == fa) staticFor(curve, TestCurves): @@ -90,8 +90,8 @@ proc runFrobeniusTowerTests*[N]( var fa {.noInit.}: typeof(a) fa.frobenius_map(a, k = 2) - a.pow_vartime(Field.fieldMod(), window = 3) - a.pow_vartime(Field.fieldMod(), window = 3) + a.pow_vartime(Field.getModulus(), window = 3) + a.pow_vartime(Field.getModulus(), window = 3) check: bool(a == fa) @@ -109,9 +109,9 @@ proc runFrobeniusTowerTests*[N]( var fa {.noInit.}: typeof(a) fa.frobenius_map(a, k = 3) - a.pow_vartime(Field.fieldMod(), window = 3) - a.pow_vartime(Field.fieldMod(), window = 3) - a.pow_vartime(Field.fieldMod(), window = 3) + a.pow_vartime(Field.getModulus(), window = 3) + a.pow_vartime(Field.getModulus(), window = 3) + a.pow_vartime(Field.getModulus(), window = 3) check: bool(a == fa) staticFor(curve, TestCurves): diff --git a/tests/math_extension_fields/t_fp_tower_template.nim b/tests/math_extension_fields/t_fp_tower_template.nim index a039d6b44..8073a8845 100644 --- a/tests/math_extension_fields/t_fp_tower_template.nim +++ b/tests/math_extension_fields/t_fp_tower_template.nim @@ -29,7 +29,7 @@ export unittest # Generic sandwich echo "\n------------------------------------------------------\n" -template ExtField(degree: static int, curve: static Curve): untyped = +template ExtField(degree: static int, name: static Algebra): untyped = when degree == 2: Fp2[curve] elif degree == 4: diff --git a/tests/math_fields/t_finite_fields_double_precision.nim b/tests/math_fields/t_finite_fields_double_precision.nim index badc4a166..83ced8d60 100644 --- a/tests/math_fields/t_finite_fields_double_precision.nim +++ b/tests/math_fields/t_finite_fields_double_precision.nim @@ -26,14 +26,14 @@ echo "\n------------------------------------------------------\n" echo "test_finite_fields_double_precision xoshiro512** seed: ", seed template addsubnegTest(rng_gen: untyped): untyped = - proc `addsubneg _ rng_gen`(C: static Curve) = + proc `addsubneg _ rng_gen`(Name: static Algebra) = # Try to exercise all code paths for in-place/out-of-place add/sum/sub/diff/double/neg # (1 - (-a) - b + (-a) - 2a) + (2a + 2b + (-b)) == 1 - let aFp = rng_gen(rng, Fp[C]) - let bFp = rng_gen(rng, Fp[C]) - var accumFp {.noInit.}: Fp[C] - var OneFp {.noInit.}: Fp[C] - var accum {.noInit.}, One {.noInit.}, a{.noInit.}, na{.noInit.}, b{.noInit.}, nb{.noInit.}, a2 {.noInit.}, b2 {.noInit.}: FpDbl[C] + let aFp = rng_gen(rng, Fp[Name]) + let bFp = rng_gen(rng, Fp[Name]) + var accumFp {.noInit.}: Fp[Name] + var OneFp {.noInit.}: Fp[Name] + var accum {.noInit.}, One {.noInit.}, a{.noInit.}, na{.noInit.}, b{.noInit.}, nb{.noInit.}, a2 {.noInit.}, b2 {.noInit.}: FpDbl[Name] OneFp.setOne() One.prod2x(OneFp, OneFp) @@ -41,7 +41,7 @@ template addsubnegTest(rng_gen: untyped): untyped = b.prod2x(bFp, OneFp) block: # sanity check - var t: Fp[C] + var t: Fp[Name] t.redc2x(One) doAssert bool t.isOne() @@ -49,7 +49,7 @@ template addsubnegTest(rng_gen: untyped): untyped = na.neg2xMod(a) block: # sanity check - var t0, t1: Fp[C] + var t0, t1: Fp[Name] t0.redc2x(na) t1.neg(aFp) doAssert bool(t0 == t1), @@ -59,7 +59,7 @@ template addsubnegTest(rng_gen: untyped): untyped = " t1: " & t1.toHex() & "\n" block: # sanity check - var t0, t1: Fp[C] + var t0, t1: Fp[Name] t0.redc2x(a2) t1.double(aFp) doAssert bool(t0 == t1), @@ -76,7 +76,7 @@ template addsubnegTest(rng_gen: untyped): untyped = accum.sum2xMod(accum, na) accum.diff2xMod(accum, a2) - var t{.noInit.}: FpDbl[C] + var t{.noInit.}: FpDbl[Name] t.sum2xMod(a2, b2) t.sum2xMod(t, nb) @@ -88,12 +88,12 @@ template addsubnegTest(rng_gen: untyped): untyped = " accumFp: " & accumFp.toHex() template mulTest(rng_gen: untyped): untyped = - proc `mul _ rng_gen`(C: static Curve) = - let a = rng_gen(rng, Fp[C]) - let b = rng_gen(rng, Fp[C]) + proc `mul _ rng_gen`(Name: static Algebra) = + let a = rng_gen(rng, Fp[Name]) + let b = rng_gen(rng, Fp[Name]) - var r_fp{.noInit.}, r_fpDbl{.noInit.}: Fp[C] - var tmpDbl{.noInit.}: FpDbl[C] + var r_fp{.noInit.}, r_fpDbl{.noInit.}: Fp[Name] + var tmpDbl{.noInit.}: FpDbl[Name] r_fp.prod(a, b) tmpDbl.prod2x(a, b) @@ -102,10 +102,10 @@ template mulTest(rng_gen: untyped): untyped = doAssert bool(r_fp == r_fpDbl) template sqrTest(rng_gen: untyped): untyped = - proc `sqr _ rng_gen`(C: static Curve) = - let a = rng_gen(rng, Fp[C]) + proc `sqr _ rng_gen`(Name: static Algebra) = + let a = rng_gen(rng, Fp[Name]) - var mulDbl{.noInit.}, sqrDbl{.noInit.}: FpDbl[C] + var mulDbl{.noInit.}, sqrDbl{.noInit.}: FpDbl[Name] mulDbl.prod2x(a, a) sqrDbl.square2x(a) diff --git a/tests/math_fields/t_finite_fields_mulsquare.nim b/tests/math_fields/t_finite_fields_mulsquare.nim index d1131cb11..821bfbbd5 100644 --- a/tests/math_fields/t_finite_fields_mulsquare.nim +++ b/tests/math_fields/t_finite_fields_mulsquare.nim @@ -27,16 +27,16 @@ echo "test_finite_fields_mulsquare xoshiro512** seed: ", seed static: doAssert defined(CTT_TEST_CURVES), "This modules requires the -d:CTT_TEST_CURVES compile option" -proc sanity(C: static Curve) = - test "Squaring 0,1,2 with " & $Curve(C) & " [FastSquaring = " & $(Fp[C].getSpareBits() >= 2) & "]": +proc sanity(Name: static Algebra) = + test "Squaring 0,1,2 with " & $Algebra(C) & " [FastSquaring = " & $(Fp[Name].getSpareBits() >= 2) & "]": block: # 0² mod - var n: Fp[C] + var n: Fp[Name] n.fromUint(0'u32) let expected = n # Out-of-place - var r: Fp[C] + var r: Fp[Name] r.square(n) # In-place n.square() @@ -46,13 +46,13 @@ proc sanity(C: static Curve) = bool(n == expected) block: # 1² mod - var n: Fp[C] + var n: Fp[Name] n.fromUint(1'u32) let expected = n # Out-of-place - var r: Fp[C] + var r: Fp[Name] r.square(n) # In-place n.square() @@ -62,13 +62,13 @@ proc sanity(C: static Curve) = bool(n == expected) block: # 2² mod - var n, expected: Fp[C] + var n, expected: Fp[Name] n.fromUint(2'u32) expected.fromUint(4'u32) # Out-of-place - var r: Fp[C] + var r: Fp[Name] r.square(n) # In-place n.square() @@ -113,10 +113,10 @@ proc mainSelectCases() = mainSelectCases() -proc randomCurve(C: static Curve) = - let a = rng.random_unsafe(Fp[C]) +proc randomCurve(Name: static Algebra) = + let a = rng.random_unsafe(Fp[Name]) - var r_mul, r_sqr: Fp[C] + var r_mul, r_sqr: Fp[Name] r_mul.prod(a, a) r_sqr.square(a) @@ -125,10 +125,10 @@ proc randomCurve(C: static Curve) = "\nMul: " & r_mul.toHex() & "\nSqr: " & r_sqr.toHex() -proc randomHighHammingWeight(C: static Curve) = - let a = rng.random_highHammingWeight(Fp[C]) +proc randomHighHammingWeight(Name: static Algebra) = + let a = rng.random_highHammingWeight(Fp[Name]) - var r_mul, r_sqr: Fp[C] + var r_mul, r_sqr: Fp[Name] r_mul.prod(a, a) r_sqr.square(a) @@ -137,10 +137,10 @@ proc randomHighHammingWeight(C: static Curve) = "\nMul: " & r_mul.toHex() & "\nSqr: " & r_sqr.toHex() -proc random_long01Seq(C: static Curve) = - let a = rng.random_long01Seq(Fp[C]) +proc random_long01Seq(Name: static Algebra) = + let a = rng.random_long01Seq(Fp[Name]) - var r_mul, r_sqr: Fp[C] + var r_mul, r_sqr: Fp[Name] r_mul.prod(a, a) r_sqr.square(a) @@ -320,17 +320,17 @@ suite "Modular squaring - bugs highlighted by property-based testing": bool(a2sqr == expected) -proc random_sumprod(C: static Curve, N: static int) = +proc random_sumprod(Name: static Algebra, N: static int) = template sumprod_test(random_instancer: untyped) = block: - var a: array[N, Fp[C]] - var b: array[N, Fp[C]] + var a: array[N, Fp[Name]] + var b: array[N, Fp[Name]] for i in 0 ..< N: - a[i] = rng.random_instancer(Fp[C]) - b[i] = rng.random_instancer(Fp[C]) + a[i] = rng.random_instancer(Fp[Name]) + b[i] = rng.random_instancer(Fp[Name]) - var r, r_ref, t: Fp[C] + var r, r_ref, t: Fp[Name] r_ref.prod(a[0], b[0]) for i in 1 ..< N: @@ -343,14 +343,14 @@ proc random_sumprod(C: static Curve, N: static int) = template sumProdMax() = block: - var a: array[N, Fp[C]] - var b: array[N, Fp[C]] + var a: array[N, Fp[Name]] + var b: array[N, Fp[Name]] for i in 0 ..< N: a[i].setMinusOne() b[i].setMinusOne() - var r, r_ref, t: Fp[C] + var r, r_ref, t: Fp[Name] r_ref.prod(a[0], b[0]) for i in 1 ..< N: diff --git a/tests/math_fields/t_finite_fields_powinv.nim b/tests/math_fields/t_finite_fields_powinv.nim index 58402ace2..fd220cc65 100644 --- a/tests/math_fields/t_finite_fields_powinv.nim +++ b/tests/math_fields/t_finite_fields_powinv.nim @@ -158,10 +158,10 @@ proc main() = computed == expected suite "Modular division by 2": - proc testRandomDiv2(curve: static Curve) = - test "Random modular div2 testing on " & $Curve(curve): + proc testRandomDiv2(name: static Algebra) = + test "Random modular div2 testing on " & $Algebra(name): for _ in 0 ..< Iters: - let a = rng.random_unsafe(Fp[curve]) + let a = rng.random_unsafe(Fp[name]) var a2 = a a2.double() a2.div2() @@ -171,7 +171,7 @@ proc main() = check: bool(a == a2) for _ in 0 ..< Iters: - let a = rng.randomHighHammingWeight(Fp[curve]) + let a = rng.randomHighHammingWeight(Fp[name]) var a2 = a a2.double() a2.div2() @@ -181,7 +181,7 @@ proc main() = check: bool(a == a2) for _ in 0 ..< Iters: - let a = rng.random_long01Seq(Fp[curve]) + let a = rng.random_long01Seq(Fp[name]) var a2 = a a2.double() a2.div2() @@ -272,12 +272,12 @@ proc main() = r2.inv_vartime(x) check: bool(r2 == expected) - proc testRandomInv(curve: static Curve) = - test "Random inversion testing on " & $Curve(curve): - var aInv, r: Fp[curve] + proc testRandomInv(name: static Algebra) = + test "Random inversion testing on " & $Algebra(name): + var aInv, r: Fp[name] for _ in 0 ..< Iters: - let a = rng.random_unsafe(Fp[curve]) + let a = rng.random_unsafe(Fp[name]) aInv.inv(a) r.prod(a, aInv) check: bool r.isOne() or (a.isZero() and r.isZero()) @@ -291,7 +291,7 @@ proc main() = check: bool r.isOne() or (a.isZero() and r.isZero()) for _ in 0 ..< Iters: - let a = rng.randomHighHammingWeight(Fp[curve]) + let a = rng.randomHighHammingWeight(Fp[name]) aInv.inv(a) r.prod(a, aInv) check: bool r.isOne() or (a.isZero() and r.isZero()) @@ -304,7 +304,7 @@ proc main() = r.prod(aInv, a) check: bool r.isOne() or (a.isZero() and r.isZero()) for _ in 0 ..< Iters: - let a = rng.random_long01Seq(Fp[curve]) + let a = rng.random_long01Seq(Fp[name]) aInv.inv(a) r.prod(a, aInv) check: bool r.isOne() or (a.isZero() and r.isZero()) @@ -331,14 +331,14 @@ proc main() = suite "Batch inversion over prime fields" & " [" & $WordBitWidth & "-bit words]": - proc testRandomBatchInv(curve: static Curve) = + proc testRandomBatchInv(name: static Algebra) = const N = 10 - var a: array[N, Fp[curve]] + var a: array[N, Fp[name]] rng.random_unsafe(a) - test "Batch inversion: " & alignLeft("random testing", 22) & $Curve(curve): - var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[curve]] + test "Batch inversion: " & alignLeft("random testing", 22) & $Algebra(name): + var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[name]] r1.batchInv(a) r2.batchInv_vartime(a) for i in 0 ..< N: @@ -346,8 +346,8 @@ proc main() = doAssert bool(r[i] == r1[i]) doAssert bool(r[i] == r2[i]) - test "Batch inversion: " & alignLeft("zero value in middle", 22) & $Curve(curve): - var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[curve]] + test "Batch inversion: " & alignLeft("zero value in middle", 22) & $Algebra(name): + var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[name]] var b = a b[N div 2].setZero() r1.batchInv(b) @@ -357,8 +357,8 @@ proc main() = doAssert bool(r[i] == r1[i]) doAssert bool(r[i] == r2[i]) - test "Batch inversion: " & alignLeft("zero value at start", 22) & $Curve(curve): - var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[curve]] + test "Batch inversion: " & alignLeft("zero value at start", 22) & $Algebra(name): + var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[name]] var b = a b[0].setZero() r1.batchInv(b) @@ -368,8 +368,8 @@ proc main() = doAssert bool(r[i] == r1[i]) doAssert bool(r[i] == r2[i]) - test "Batch inversion: " & alignLeft("zero value at end", 22) & $Curve(curve): - var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[curve]] + test "Batch inversion: " & alignLeft("zero value at end", 22) & $Algebra(name): + var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[name]] var b = a b[N-1].setZero() r1.batchInv(b) @@ -379,8 +379,8 @@ proc main() = doAssert bool(r[i] == r1[i]) doAssert bool(r[i] == r2[i]) - test "Batch inversion: " & alignLeft("multiple zero values", 22) & $Curve(curve): - var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[curve]] + test "Batch inversion: " & alignLeft("multiple zero values", 22) & $Algebra(name): + var r{.noInit.}, r1{.noInit.}, r2{.noInit.}: array[N, Fp[name]] var b = a block: static: doAssert N < sizeof(rng.next()) * 8, "There are only " & $sizeof(rng.next() * 8) & " bits produced." @@ -431,7 +431,7 @@ proc main_anti_regression = a.fromHex"0x184d02ce4f24d5e59b4150a57a31b202fd40a4b41d7518c22b84bee475fbcb7763100448ef6b17a6ea603cf062e5db51" - var pm3div4 = BLS12_381.Mod + var pm3div4 = Fp[BLS12_381].getModulus() discard pm3div4.sub SecretWord(3) pm3div4.shiftRight(2) @@ -454,7 +454,7 @@ proc main_anti_regression = a.fromHex"0x0f16d7854229d8804bcadd889f70411d6a482bde840d238033bf868e89558d39d52f9df60b2d745e02584375f16c34a3" - var pm3div4 = BLS12_381.Mod + var pm3div4 = Fp[BLS12_381].getModulus() discard pm3div4.sub SecretWord(3) pm3div4.shiftRight(2) diff --git a/tests/math_fields/t_finite_fields_sqrt.nim b/tests/math_fields/t_finite_fields_sqrt.nim index 22b8d640a..96d471fdc 100644 --- a/tests/math_fields/t_finite_fields_sqrt.nim +++ b/tests/math_fields/t_finite_fields_sqrt.nim @@ -28,14 +28,14 @@ echo "test_finite_fields_sqrt xoshiro512** seed: ", seed static: doAssert defined(CTT_TEST_CURVES), "This modules requires the -d:CTT_TEST_CURVES compile option" -proc exhaustiveCheck(C: static Curve, modulus: static int) = - test "Exhaustive square root check for " & $Curve(C): +proc exhaustiveCheck(Name: static Algebra, modulus: static int) = + test "Exhaustive square root check for " & $Algebra(C): var squares_to_roots: Table[uint16, set[uint16]] # Create all squares # ------------------------- for i in 0'u16 ..< modulus: - var a{.noInit.}: Fp[C] + var a{.noInit.}: Fp[Name] a.fromUint(i) a.square() @@ -54,7 +54,7 @@ proc exhaustiveCheck(C: static Curve, modulus: static int) = # Check squares # ------------------------- for i in 0'u16 ..< modulus: - var a{.noInit.}: Fp[C] + var a{.noInit.}: Fp[Name] a.fromUint(i) if i in squares_to_roots: @@ -102,18 +102,18 @@ template testSqrtImpl(a: untyped): untyped {.dirty.} = bool(r == s) bool(r == a or r == na) -proc randomSqrtCheck(C: static Curve) = - test "Random square root check for " & $Curve(C): +proc randomSqrtCheck(Name: static Algebra) = + test "Random square root check for " & $Algebra(C): for _ in 0 ..< Iters: - let a = rng.random_unsafe(Fp[C]) + let a = rng.random_unsafe(Fp[Name]) testSqrtImpl(a) for _ in 0 ..< Iters: - let a = rng.randomHighHammingWeight(Fp[C]) + let a = rng.randomHighHammingWeight(Fp[Name]) testSqrtImpl(a) for _ in 0 ..< Iters: - let a = rng.random_long01Seq(Fp[C]) + let a = rng.random_long01Seq(Fp[Name]) testSqrtImpl(a) template testSqrtRatioImpl(u, v: untyped): untyped {.dirty.} = @@ -128,21 +128,21 @@ template testSqrtRatioImpl(u, v: untyped): untyped {.dirty.} = r.square() check: bool(r == u_over_v) -proc randomSqrtRatioCheck(C: static Curve) = - test "Random square root check for " & $Curve(C): +proc randomSqrtRatioCheck(Name: static Algebra) = + test "Random square root check for " & $Algebra(C): for _ in 0 ..< Iters: - let u = rng.random_unsafe(Fp[C]) - let v = rng.random_unsafe(Fp[C]) + let u = rng.random_unsafe(Fp[Name]) + let v = rng.random_unsafe(Fp[Name]) testSqrtRatioImpl(u, v) for _ in 0 ..< Iters: - let u = rng.randomHighHammingWeight(Fp[C]) - let v = rng.randomHighHammingWeight(Fp[C]) + let u = rng.randomHighHammingWeight(Fp[Name]) + let v = rng.randomHighHammingWeight(Fp[Name]) testSqrtRatioImpl(u, v) for _ in 0 ..< Iters: - let u = rng.random_long01Seq(Fp[C]) - let v = rng.random_long01Seq(Fp[C]) + let u = rng.random_long01Seq(Fp[Name]) + let v = rng.random_long01Seq(Fp[Name]) testSqrtRatioImpl(u, v) proc main() = diff --git a/tests/math_fields/t_finite_fields_vs_gmp.nim b/tests/math_fields/t_finite_fields_vs_gmp.nim index 744bd6c84..36704715b 100644 --- a/tests/math_fields/t_finite_fields_vs_gmp.nim +++ b/tests/math_fields/t_finite_fields_vs_gmp.nim @@ -47,24 +47,24 @@ const # https://gmplib.org/manual/Integer-Import-and-Export.html # # Factor common things in proc to avoid generating 100k+ lines of C code -proc binary_prologue[C: static Curve, N: static int]( +proc binary_prologue[Name: static Algebra, N: static int]( rng: var RngState, a, b, p: var mpz_t, - aTest, bTest: var Fp[C], + aTest, bTest: var Fp[Name], aBuf, bBuf: var array[N, byte]) = # Build the field elements - aTest = rng.random_unsafe(Fp[C]) - bTest = rng.random_unsafe(Fp[C]) + aTest = rng.random_unsafe(Fp[Name]) + bTest = rng.random_unsafe(Fp[Name]) # Set modulus to curve modulus - let err = mpz_set_str(p, Curve(C).Mod.toHex(), 0) - doAssert err == 0, "Error on prime for curve " & $Curve(C) + let err = mpz_set_str(p, Algebra(C).Mod.toHex(), 0) + doAssert err == 0, "Error on prime for curve " & $Algebra(C) ######################################################### # Conversion to GMP - const aLen = C.getCurveBitwidth().ceilDiv_vartime(8) - const bLen = C.getCurveBitwidth().ceilDiv_vartime(8) + const aLen = Name.getCurveBitwidth().ceilDiv_vartime(8) + const bLen = Name.getCurveBitwidth().ceilDiv_vartime(8) var aBuf: array[aLen, byte] var bBuf: array[bLen, byte] @@ -75,9 +75,9 @@ proc binary_prologue[C: static Curve, N: static int]( mpz_import(a, aLen, GMP_MostSignificantWordFirst, 1, GMP_WordNativeEndian, 0, aBuf[0].addr) mpz_import(b, bLen, GMP_MostSignificantWordFirst, 1, GMP_WordNativeEndian, 0, bBuf[0].addr) -proc binary_epilogue[C: static Curve, N: static int]( +proc binary_epilogue[Name: static Algebra, N: static int]( r, a, b: mpz_t, - rTest: Fp[C], + rTest: Fp[Name], aBuf, bBuf: array[N, byte], operation: string ) = @@ -100,7 +100,7 @@ proc binary_epilogue[C: static Curve, N: static int]( # Reexport as bigEndian for debugging discard mpz_export(aBuf[0].unsafeAddr, aW.addr, GMP_MostSignificantWordFirst, 1, GMP_WordNativeEndian, 0, a) discard mpz_export(bBuf[0].unsafeAddr, bW.addr, GMP_MostSignificantWordFirst, 1, GMP_WordNativeEndian, 0, b) - "\nModular " & operation & " on curve " & $C & " with operands\n" & + "\nModular " & operation & " on curve " & $Name & " with operands\n" & " a: " & aBuf.toHex & "\n" & " b: " & bBuf.toHex & "\n" & "failed:" & "\n" & @@ -114,21 +114,21 @@ proc binary_epilogue[C: static Curve, N: static int]( # # ############################################################ -proc addTests(rng: var RngState, a, b, p, r: var mpz_t, C: static Curve) = - # echo "Testing: random modular addition on ", $C +proc addTests(rng: var RngState, a, b, p, r: var mpz_t, Name: static Algebra) = + # echo "Testing: random modular addition on ", $Name const - bits = C.getCurveBitwidth() + bits = Name.getCurveBitwidth() bufLen = bits.ceilDiv_vartime(8) var - aTest, bTest{.noInit.}: Fp[C] + aTest, bTest{.noInit.}: Fp[Name] aBuf, bBuf: array[bufLen, byte] binary_prologue(rng, a, b, p, aTest, bTest, aBuf, bBuf) mpz_add(r, a, b) mpz_mod(r, r, p) - var rTest {.noInit.}: Fp[C] + var rTest {.noInit.}: Fp[Name] rTest.sum(aTest, bTest) var r2Test = aTest @@ -137,21 +137,21 @@ proc addTests(rng: var RngState, a, b, p, r: var mpz_t, C: static Curve) = binary_epilogue(r, a, b, rTest, aBuf, bBuf, "Addition (with result)") binary_epilogue(r, a, b, r2Test, aBuf, bBuf, "Addition (in-place)") -proc subTests(rng: var RngState, a, b, p, r: var mpz_t, C: static Curve) = - # echo "Testing: random modular substraction on ", $C +proc subTests(rng: var RngState, a, b, p, r: var mpz_t, Name: static Algebra) = + # echo "Testing: random modular substraction on ", $Name const - bits = C.getCurveBitwidth() + bits = Name.getCurveBitwidth() bufLen = bits.ceilDiv_vartime(8) var - aTest, bTest{.noInit.}: Fp[C] + aTest, bTest{.noInit.}: Fp[Name] aBuf, bBuf: array[bufLen, byte] binary_prologue(rng, a, b, p, aTest, bTest, aBuf, bBuf) mpz_sub(r, a, b) mpz_mod(r, r, p) - var rTest {.noInit.}: Fp[C] + var rTest {.noInit.}: Fp[Name] rTest.diff(aTest, bTest) var r2Test = aTest @@ -165,21 +165,21 @@ proc subTests(rng: var RngState, a, b, p, r: var mpz_t, C: static Curve) = binary_epilogue(r, a, b, r2Test, aBuf, bBuf, "Substraction (in-place)") binary_epilogue(r, a, b, r3Test, aBuf, bBuf, "Substraction (result aliasing)") -proc mulTests(rng: var RngState, a, b, p, r: var mpz_t, C: static Curve) = - # echo "Testing: random modular multiplication on ", $C +proc mulTests(rng: var RngState, a, b, p, r: var mpz_t, Name: static Algebra) = + # echo "Testing: random modular multiplication on ", $Name const - bits = C.getCurveBitwidth() + bits = Name.getCurveBitwidth() bufLen = bits.ceilDiv_vartime(8) var - aTest, bTest{.noInit.}: Fp[C] + aTest, bTest{.noInit.}: Fp[Name] aBuf, bBuf: array[bufLen, byte] binary_prologue(rng, a, b, p, aTest, bTest, aBuf, bBuf) mpz_mul(r, a, b) mpz_mod(r, r, p) - var rTest {.noInit.}: Fp[C] + var rTest {.noInit.}: Fp[Name] rTest.prod(aTest, bTest) var r2Test = aTest @@ -188,22 +188,22 @@ proc mulTests(rng: var RngState, a, b, p, r: var mpz_t, C: static Curve) = binary_epilogue(r, a, b, rTest, aBuf, bBuf, "Multiplication (with result)") binary_epilogue(r, a, b, r2Test, aBuf, bBuf, "Multiplication (in-place)") -proc invTests(rng: var RngState, a, b, p, r: var mpz_t, C: static Curve) = +proc invTests(rng: var RngState, a, b, p, r: var mpz_t, Name: static Algebra) = # We use the binary prologue epilogue but the "b" parameter is actual unused - # echo "Testing: random modular inversion on ", $C + # echo "Testing: random modular inversion on ", $Name const - bits = C.getCurveBitwidth() + bits = Name.getCurveBitwidth() bufLen = bits.ceilDiv_vartime(8) var - aTest, bTest{.noInit.}: Fp[C] + aTest, bTest{.noInit.}: Fp[Name] aBuf, bBuf: array[bufLen, byte] binary_prologue(rng, a, b, p, aTest, bTest, aBuf, bBuf) let exist = mpz_invert(r, a, p) doAssert exist != 0 - var rTest {.noInit.}: Fp[C] + var rTest {.noInit.}: Fp[Name] rTest.inv(aTest) binary_epilogue(r, a, b, rTest, aBuf, bBuf, "Inversion (b is unused)") @@ -224,7 +224,7 @@ macro randomTests(numTests: static int, curveSym, body: untyped): untyped = result.add quote do: block: - const `curveSym` = Curve(`curve`) + const `curveSym` = Algebra(`curve`) block: `body` diff --git a/tests/math_fields/t_fp_cubic_root.nim b/tests/math_fields/t_fp_cubic_root.nim index 311ce8fd5..9d09a6d07 100644 --- a/tests/math_fields/t_fp_cubic_root.nim +++ b/tests/math_fields/t_fp_cubic_root.nim @@ -14,7 +14,7 @@ import std/unittest, echo "\n------------------------------------------------------\n" -proc checkCubeRootOfUnity(curve: static Curve) = +proc checkCubeRootOfUnity(name: static Algebra) = test $curve & " cube root of unity (mod p)": var cru = curve.getCubicRootOfUnity_mod_p() cru.square() diff --git a/tests/math_fields/t_fr.nim b/tests/math_fields/t_fr.nim index 201a704f9..dcd2ef279 100644 --- a/tests/math_fields/t_fr.nim +++ b/tests/math_fields/t_fr.nim @@ -25,16 +25,16 @@ rng.seed(seed) echo "\n------------------------------------------------------\n" echo "test_fr xoshiro512** seed: ", seed -proc sanity(C: static Curve) = - test "Fr: Squaring 0,1,2 with "& $Fr[C] & " [FastSquaring = " & $(Fr[C].getSpareBits() >= 2) & "]": +proc sanity(Name: static Algebra) = + test "Fr: Squaring 0,1,2 with "& $Fr[Name] & " [FastSquaring = " & $(Fr[Name].getSpareBits() >= 2) & "]": block: # 0² mod - var n: Fr[C] + var n: Fr[Name] n.fromUint(0'u32) let expected = n # Out-of-place - var r: Fr[C] + var r: Fr[Name] r.square(n) # In-place n.square() @@ -44,13 +44,13 @@ proc sanity(C: static Curve) = bool(n == expected) block: # 1² mod - var n: Fr[C] + var n: Fr[Name] n.fromUint(1'u32) let expected = n # Out-of-place - var r: Fr[C] + var r: Fr[Name] r.square(n) # In-place n.square() @@ -60,13 +60,13 @@ proc sanity(C: static Curve) = bool(n == expected) block: # 2² mod - var n, expected: Fr[C] + var n, expected: Fr[Name] n.fromUint(2'u32) expected.fromUint(4'u32) # Out-of-place - var r: Fr[C] + var r: Fr[Name] r.square(n) # In-place n.square() @@ -82,30 +82,30 @@ proc mainSanity() = mainSanity() -proc randomCurve(C: static Curve) = - let a = rng.random_unsafe(Fr[C]) +proc randomCurve(Name: static Algebra) = + let a = rng.random_unsafe(Fr[Name]) - var r_mul, r_sqr: Fr[C] + var r_mul, r_sqr: Fr[Name] r_mul.prod(a, a) r_sqr.square(a) doAssert bool(r_mul == r_sqr) -proc randomHighHammingWeight(C: static Curve) = - let a = rng.random_highHammingWeight(Fr[C]) +proc randomHighHammingWeight(Name: static Algebra) = + let a = rng.random_highHammingWeight(Fr[Name]) - var r_mul, r_sqr: Fr[C] + var r_mul, r_sqr: Fr[Name] r_mul.prod(a, a) r_sqr.square(a) doAssert bool(r_mul == r_sqr) -proc random_long01Seq(C: static Curve) = - let a = rng.random_long01Seq(Fr[C]) +proc random_long01Seq(Name: static Algebra) = + let a = rng.random_long01Seq(Fr[Name]) - var r_mul, r_sqr: Fr[C] + var r_mul, r_sqr: Fr[Name] r_mul.prod(a, a) r_sqr.square(a) diff --git a/tests/math_pairings/t_pairing_bls12_377_line_functions.nim b/tests/math_pairings/t_pairing_bls12_377_line_functions.nim index 0e692a34d..c916c5f8a 100644 --- a/tests/math_pairings/t_pairing_bls12_377_line_functions.nim +++ b/tests/math_pairings/t_pairing_bls12_377_line_functions.nim @@ -67,12 +67,12 @@ func random_point*(rng: var RngState, EC: typedesc, randZ: bool, gen: RandomGen) suite "Pairing - Line Functions on BLS12-377" & " [" & $WordBitWidth & "-bit words]": test "Line double - lt,t(P)": - proc test_line_double(C: static Curve, randZ: bool, gen: RandomGen) = + proc test_line_double(Name: static Algebra, randZ: bool, gen: RandomGen) = for _ in 0 ..< Iters: - let P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1], gen) - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2], randZ, gen) - let Q = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2], randZ, gen) - var l: Line[Fp2[C]] + let P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1], gen) + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2], randZ, gen) + let Q = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2], randZ, gen) + var l: Line[Fp2[Name]] var T2: typeof(Q) T2.double(T) @@ -89,17 +89,17 @@ suite "Pairing - Line Functions on BLS12-377" & " [" & $WordBitWidth & "-bit wor test_line_double(curve, randZ = true, gen = Long01Sequence) test "Line add - lt,q(P)": - proc test_line_add(C: static Curve, randZ: bool, gen: RandomGen) = + proc test_line_add(Name: static Algebra, randZ: bool, gen: RandomGen) = for _ in 0 ..< Iters: - let P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1], gen) - let Q = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2], randZ, gen) - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2], randZ, gen) - var l: Line[Fp2[C]] + let P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1], gen) + let Q = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2], randZ, gen) + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2], randZ, gen) + var l: Line[Fp2[Name]] var TQ{.noInit.}: typeof(T) TQ.sum(T, Q) - var Qaff{.noInit.}: ECP_ShortW_Aff[Fp2[C], G2] + var Qaff{.noInit.}: EC_ShortW_Aff[Fp2[Name], G2] Qaff.affine(Q) l.line_add(T, Qaff, P) diff --git a/tests/math_pairings/t_pairing_bls12_377_multi.nim b/tests/math_pairings/t_pairing_bls12_377_multi.nim index fde27df8e..b7924598d 100644 --- a/tests/math_pairings/t_pairing_bls12_377_multi.nim +++ b/tests/math_pairings/t_pairing_bls12_377_multi.nim @@ -29,8 +29,8 @@ echo "test_pairing_bls12_377_multi xoshiro512** seed: ", timeseed proc testMultiPairing(rng: var RngState, N: static int) = var - Ps {.noInit.}: array[N, ECP_ShortW_Aff[Fp[BLS12_381], G1]] - Qs {.noInit.}: array[N, ECP_ShortW_Aff[Fp2[BLS12_381], G2]] + Ps {.noInit.}: array[N, EC_ShortW_Aff[Fp[BLS12_381], G1]] + Qs {.noInit.}: array[N, EC_ShortW_Aff[Fp2[BLS12_381], G2]] GTs {.noInit.}: array[N, Fp12[BLS12_381]] diff --git a/tests/math_pairings/t_pairing_bls12_377_optate.nim b/tests/math_pairings/t_pairing_bls12_377_optate.nim index 5a8a3ac4e..d6cbe09ee 100644 --- a/tests/math_pairings/t_pairing_bls12_377_optate.nim +++ b/tests/math_pairings/t_pairing_bls12_377_optate.nim @@ -13,7 +13,7 @@ import runPairingTests( 4, BLS12_377, - G1 = ECP_ShortW_Prj[Fp[BLS12_377], G1], - G2 = ECP_ShortW_Prj[Fp2[BLS12_377], G2], + G1 = EC_ShortW_Prj[Fp[BLS12_377], G1], + G2 = EC_ShortW_Prj[Fp2[BLS12_377], G2], GT = Fp12[BLS12_377], pairing_bls12) diff --git a/tests/math_pairings/t_pairing_bls12_381_line_functions.nim b/tests/math_pairings/t_pairing_bls12_381_line_functions.nim index ecf8dbce8..ae9074efe 100644 --- a/tests/math_pairings/t_pairing_bls12_381_line_functions.nim +++ b/tests/math_pairings/t_pairing_bls12_381_line_functions.nim @@ -66,12 +66,12 @@ func random_point*(rng: var RngState, EC: typedesc, randZ: bool, gen: RandomGen) suite "Pairing - Line Functions on BLS12-381" & " [" & $WordBitWidth & "-bit words]": test "Line double - lt,t(P)": - proc test_line_double(C: static Curve, randZ: bool, gen: RandomGen) = + proc test_line_double(Name: static Algebra, randZ: bool, gen: RandomGen) = for _ in 0 ..< Iters: - let P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1], gen) - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2], randZ, gen) - let Q = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2], randZ, gen) - var l: Line[Fp2[C]] + let P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1], gen) + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2], randZ, gen) + let Q = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2], randZ, gen) + var l: Line[Fp2[Name]] var T2: typeof(Q) T2.double(T) @@ -88,17 +88,17 @@ suite "Pairing - Line Functions on BLS12-381" & " [" & $WordBitWidth & "-bit wor test_line_double(curve, randZ = true, gen = Long01Sequence) test "Line add - lt,q(P)": - proc test_line_add(C: static Curve, randZ: bool, gen: RandomGen) = + proc test_line_add(Name: static Algebra, randZ: bool, gen: RandomGen) = for _ in 0 ..< Iters: - let P = rng.random_point(ECP_ShortW_Aff[Fp[C], G1], gen) - let Q = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2], randZ, gen) - var T = rng.random_point(ECP_ShortW_Prj[Fp2[C], G2], randZ, gen) - var l: Line[Fp2[C]] + let P = rng.random_point(EC_ShortW_Aff[Fp[Name], G1], gen) + let Q = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2], randZ, gen) + var T = rng.random_point(EC_ShortW_Prj[Fp2[Name], G2], randZ, gen) + var l: Line[Fp2[Name]] var TQ{.noInit.}: typeof(T) TQ.sum(T, Q) - var Qaff{.noInit.}: ECP_ShortW_Aff[Fp2[C], G2] + var Qaff{.noInit.}: EC_ShortW_Aff[Fp2[Name], G2] Qaff.affine(Q) l.line_add(T, Qaff, P) diff --git a/tests/math_pairings/t_pairing_bls12_381_multi.nim b/tests/math_pairings/t_pairing_bls12_381_multi.nim index 14008d9ed..5be83c9ce 100644 --- a/tests/math_pairings/t_pairing_bls12_381_multi.nim +++ b/tests/math_pairings/t_pairing_bls12_381_multi.nim @@ -29,8 +29,8 @@ echo "test_pairing_bls12_381_multi xoshiro512** seed: ", timeseed proc testMultiPairing(rng: var RngState, N: static int) = var - Ps {.noInit.}: array[N, ECP_ShortW_Aff[Fp[BLS12_381], G1]] - Qs {.noInit.}: array[N, ECP_ShortW_Aff[Fp2[BLS12_381], G2]] + Ps {.noInit.}: array[N, EC_ShortW_Aff[Fp[BLS12_381], G1]] + Qs {.noInit.}: array[N, EC_ShortW_Aff[Fp2[BLS12_381], G2]] GTs {.noInit.}: array[N, Fp12[BLS12_381]] diff --git a/tests/math_pairings/t_pairing_bls12_381_optate.nim b/tests/math_pairings/t_pairing_bls12_381_optate.nim index aebe5196c..eda18b2e9 100644 --- a/tests/math_pairings/t_pairing_bls12_381_optate.nim +++ b/tests/math_pairings/t_pairing_bls12_381_optate.nim @@ -13,7 +13,7 @@ import runPairingTests( 4, BLS12_381, - G1 = ECP_ShortW_Prj[Fp[BLS12_381], G1], - G2 = ECP_ShortW_Prj[Fp2[BLS12_381], G2], + G1 = EC_ShortW_Prj[Fp[BLS12_381], G1], + G2 = EC_ShortW_Prj[Fp2[BLS12_381], G2], GT = Fp12[BLS12_381], pairing_bls12) diff --git a/tests/math_pairings/t_pairing_bn254_nogami_multi.nim b/tests/math_pairings/t_pairing_bn254_nogami_multi.nim index 70ed9c18d..dbf3e26ea 100644 --- a/tests/math_pairings/t_pairing_bn254_nogami_multi.nim +++ b/tests/math_pairings/t_pairing_bn254_nogami_multi.nim @@ -29,8 +29,8 @@ echo "test_pairing_bn254_nogami_multi xoshiro512** seed: ", timeseed proc testMultiPairing(rng: var RngState, N: static int) = var - Ps {.noInit.}: array[N, ECP_ShortW_Aff[Fp[BN254_Nogami], G1]] - Qs {.noInit.}: array[N, ECP_ShortW_Aff[Fp2[BN254_Nogami], G2]] + Ps {.noInit.}: array[N, EC_ShortW_Aff[Fp[BN254_Nogami], G1]] + Qs {.noInit.}: array[N, EC_ShortW_Aff[Fp2[BN254_Nogami], G2]] GTs {.noInit.}: array[N, Fp12[BN254_Nogami]] diff --git a/tests/math_pairings/t_pairing_bn254_nogami_optate.nim b/tests/math_pairings/t_pairing_bn254_nogami_optate.nim index f9b97375c..6c72eea58 100644 --- a/tests/math_pairings/t_pairing_bn254_nogami_optate.nim +++ b/tests/math_pairings/t_pairing_bn254_nogami_optate.nim @@ -13,7 +13,7 @@ import runPairingTests( 4, BN254_Nogami, - G1 = ECP_ShortW_Prj[Fp[BN254_Nogami], G1], - G2 = ECP_ShortW_Prj[Fp2[BN254_Nogami], G2], + G1 = EC_ShortW_Prj[Fp[BN254_Nogami], G1], + G2 = EC_ShortW_Prj[Fp2[BN254_Nogami], G2], GT = Fp12[BN254_Nogami], pairing_bn) diff --git a/tests/math_pairings/t_pairing_bn254_snarks_multi.nim b/tests/math_pairings/t_pairing_bn254_snarks_multi.nim index e6e87005a..33c65c050 100644 --- a/tests/math_pairings/t_pairing_bn254_snarks_multi.nim +++ b/tests/math_pairings/t_pairing_bn254_snarks_multi.nim @@ -29,8 +29,8 @@ echo "test_pairing_bn254_snarks_multi xoshiro512** seed: ", timeseed proc testMultiPairing(rng: var RngState, N: static int) = var - Ps {.noInit.}: array[N, ECP_ShortW_Aff[Fp[BN254_Snarks], G1]] - Qs {.noInit.}: array[N, ECP_ShortW_Aff[Fp2[BN254_Snarks], G2]] + Ps {.noInit.}: array[N, EC_ShortW_Aff[Fp[BN254_Snarks], G1]] + Qs {.noInit.}: array[N, EC_ShortW_Aff[Fp2[BN254_Snarks], G2]] GTs {.noInit.}: array[N, Fp12[BN254_Snarks]] diff --git a/tests/math_pairings/t_pairing_bn254_snarks_optate.nim b/tests/math_pairings/t_pairing_bn254_snarks_optate.nim index 742e33bba..59635f766 100644 --- a/tests/math_pairings/t_pairing_bn254_snarks_optate.nim +++ b/tests/math_pairings/t_pairing_bn254_snarks_optate.nim @@ -13,7 +13,7 @@ import runPairingTests( 4, BN254_Snarks, - G1 = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], - G2 = ECP_ShortW_Prj[Fp2[BN254_Snarks], G2], + G1 = EC_ShortW_Prj[Fp[BN254_Snarks], G1], + G2 = EC_ShortW_Prj[Fp2[BN254_Snarks], G2], GT = Fp12[BN254_Snarks], pairing_bn) diff --git a/tests/math_pairings/t_pairing_bw6_761_optate.nim b/tests/math_pairings/t_pairing_bw6_761_optate.nim index b3bf39118..34870bed3 100644 --- a/tests/math_pairings/t_pairing_bw6_761_optate.nim +++ b/tests/math_pairings/t_pairing_bw6_761_optate.nim @@ -13,7 +13,7 @@ import runPairingTests( 4, BW6_761, - G1 = ECP_ShortW_Prj[Fp[BW6_761], G1], - G2 = ECP_ShortW_Prj[Fp[BW6_761], G2], + G1 = EC_ShortW_Prj[Fp[BW6_761], G1], + G2 = EC_ShortW_Prj[Fp[BW6_761], G2], GT = Fp6[BW6_761], pairing_bw6_761_reference) diff --git a/tests/math_pairings/t_pairing_cyclotomic_subgroup.nim b/tests/math_pairings/t_pairing_cyclotomic_subgroup.nim index 2315257bd..2abcc25b3 100644 --- a/tests/math_pairings/t_pairing_cyclotomic_subgroup.nim +++ b/tests/math_pairings/t_pairing_cyclotomic_subgroup.nim @@ -51,9 +51,9 @@ func random_elem(rng: var RngState, F: typedesc, gen: RandomGen): F {.inline, no suite "Pairing - Cyclotomic subgroup - GΦ₁₂(p) = {α ∈ Fp¹² : α^Φ₁₂(p) ≡ 1 (mod p¹²)}" & " [" & $WordBitWidth & "-bit words]": test "Easy part of the final exponentiation maps to the cyclotomic subgroup": - proc test_final_exp_easy_cycl(C: static Curve, gen: static RandomGen) = + proc test_final_exp_easy_cycl(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) f.finalExpEasy() @@ -73,9 +73,9 @@ suite "Pairing - Cyclotomic subgroup - GΦ₁₂(p) = {α ∈ Fp¹² : α^Φ₁ test_final_exp_easy_cycl(curve, gen = Long01Sequence) test "Cyclotomic inverse": - proc test_cycl_inverse(C: static Curve, gen: static RandomGen) = + proc test_cycl_inverse(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) f.finalExpEasy() var g = f @@ -91,9 +91,9 @@ suite "Pairing - Cyclotomic subgroup - GΦ₁₂(p) = {α ∈ Fp¹² : α^Φ₁ test_cycl_inverse(curve, gen = Long01Sequence) test "Cyclotomic squaring": - proc test_cycl_squaring_in_place(C: static Curve, gen: static RandomGen) = + proc test_cycl_squaring_in_place(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) f.finalExpEasy() var g = f @@ -108,9 +108,9 @@ suite "Pairing - Cyclotomic subgroup - GΦ₁₂(p) = {α ∈ Fp¹² : α^Φ₁ test_cycl_squaring_in_place(curve, gen = HighHammingWeight) test_cycl_squaring_in_place(curve, gen = Long01Sequence) - proc test_cycl_squaring_out_place(C: static Curve, gen: static RandomGen) = + proc test_cycl_squaring_out_place(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) f.finalExpEasy() var g = f @@ -127,9 +127,9 @@ suite "Pairing - Cyclotomic subgroup - GΦ₁₂(p) = {α ∈ Fp¹² : α^Φ₁ test_cycl_squaring_out_place(curve, gen = Long01Sequence) test "Compressed cyclotomic squarings": - proc test_compressed_cycl_squarings(C: static Curve, gen: static RandomGen) = + proc test_compressed_cycl_squarings(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) f.finalExpEasy() var g = f @@ -145,9 +145,9 @@ suite "Pairing - Cyclotomic subgroup - GΦ₁₂(p) = {α ∈ Fp¹² : α^Φ₁ test_compressed_cycl_squarings(curve, gen = Long01Sequence) test "Compressed cyclotomic exponentiation": - proc test_compressed_cycl_exp(C: static Curve, gen: static RandomGen) = + proc test_compressed_cycl_exp(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) f.finalExpEasy() var g = f diff --git a/tests/math_pairings/t_pairing_mul_fp12_by_lines.nim b/tests/math_pairings/t_pairing_mul_fp12_by_lines.nim index 56fcc02a4..3344f5fba 100644 --- a/tests/math_pairings/t_pairing_mul_fp12_by_lines.nim +++ b/tests/math_pairings/t_pairing_mul_fp12_by_lines.nim @@ -50,13 +50,13 @@ func random_elem(rng: var RngState, F: typedesc, gen: RandomGen): F {.inline, no suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent with dense 𝔽p12 mul": test "Dense 𝔽p4 by Sparse 0y": - proc test_fp4_0y(C: static Curve, gen: static RandomGen) = + proc test_fp4_0y(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - let a = rng.random_elem(Fp4[C], gen) - let y = rng.random_elem(Fp2[C], gen) - let b = Fp4[C](coords: [Fp2[C](), y]) + let a = rng.random_elem(Fp4[Name], gen) + let y = rng.random_elem(Fp2[Name], gen) + let b = Fp4[Name](coords: [Fp2[Name](), y]) - var r, r2: Fp4[C] + var r, r2: Fp4[Name] r.prod(a, b) r2.mul_sparse_by_0y(a, y) @@ -69,13 +69,13 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp4_0y(curve, gen = Long01Sequence) test "Dense 𝔽p6 by Sparse 0y0": - proc test_fp6_0y0(C: static Curve, gen: static RandomGen) = + proc test_fp6_0y0(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - let a = rng.random_elem(Fp6[C], gen) - let y = rng.random_elem(Fp2[C], gen) - let b = Fp6[C](coords: [Fp2[C](), y, Fp2[C]()]) + let a = rng.random_elem(Fp6[Name], gen) + let y = rng.random_elem(Fp2[Name], gen) + let b = Fp6[Name](coords: [Fp2[Name](), y, Fp2[Name]()]) - var r, r2: Fp6[C] + var r, r2: Fp6[Name] r.prod(a, b) r2.mul_sparse_by_0y0(a, y) @@ -88,14 +88,14 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp6_0y0(curve, gen = Long01Sequence) test "Dense 𝔽p6 by Sparse xy0": - proc test_fp6_xy0(C: static Curve, gen: static RandomGen) = + proc test_fp6_xy0(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - let a = rng.random_elem(Fp6[C], gen) - let x = rng.random_elem(Fp2[C], gen) - let y = rng.random_elem(Fp2[C], gen) - let b = Fp6[C](coords: [x, y, Fp2[C]()]) + let a = rng.random_elem(Fp6[Name], gen) + let x = rng.random_elem(Fp2[Name], gen) + let y = rng.random_elem(Fp2[Name], gen) + let b = Fp6[Name](coords: [x, y, Fp2[Name]()]) - var r, r2: Fp6[C] + var r, r2: Fp6[Name] r.prod(a, b) r2.mul_sparse_by_xy0(a, x, y) @@ -108,14 +108,14 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp6_xy0(curve, gen = Long01Sequence) test "Dense 𝔽p6 by Sparse 0yz": - proc test_fp6_0yz(C: static Curve, gen: static RandomGen) = + proc test_fp6_0yz(Name: static Algebra, gen: static RandomGen) = for _ in 0 ..< Iters: - let a = rng.random_elem(Fp6[C], gen) - let y = rng.random_elem(Fp2[C], gen) - let z = rng.random_elem(Fp2[C], gen) - let b = Fp6[C](coords: [Fp2[C](), y, z]) + let a = rng.random_elem(Fp6[Name], gen) + let y = rng.random_elem(Fp2[Name], gen) + let z = rng.random_elem(Fp2[Name], gen) + let b = Fp6[Name](coords: [Fp2[Name](), y, z]) - var r, r2: Fp6[C] + var r, r2: Fp6[Name] r.prod(a, b) r2.mul_sparse_by_0yz(a, y, z) @@ -131,20 +131,20 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi # =========== Towering 𝔽p12/𝔽p6 ====================================== test "Sparse 𝔽p12/𝔽p6 resulting from a00bc0 line function": - proc test_fp12_a00bc0(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == D_Twist: + proc test_fp12_a00bc0(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == D_Twist: for _ in 0 ..< Iters: - var a = rng.random_elem(Fp12[C], gen) + var a = rng.random_elem(Fp12[Name], gen) var a2 = a - var x = rng.random_elem(Fp2[C], gen) - var y = rng.random_elem(Fp2[C], gen) - var z = rng.random_elem(Fp2[C], gen) + var x = rng.random_elem(Fp2[Name], gen) + var y = rng.random_elem(Fp2[Name], gen) + var z = rng.random_elem(Fp2[Name], gen) - let line = Line[Fp2[C]](a: x, b: y, c: z) - let b = Fp12[C]( coords: [ - Fp6[C](coords: [ x, Fp2[C](), Fp2[C]()]), - Fp6[C](coords: [ y, z, Fp2[C]()]) + let line = Line[Fp2[Name]](a: x, b: y, c: z) + let b = Fp12[Name]( coords: [ + Fp6[Name](coords: [ x, Fp2[Name](), Fp2[Name]()]), + Fp6[Name](coords: [ y, z, Fp2[Name]()]) ]) a *= b @@ -158,20 +158,20 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_a00bc0(curve, gen = Long01Sequence) test "Sparse 𝔽p12/𝔽p6 resulting from cb00a0 line function": - proc test_fp12_cb00a0(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == M_Twist: + proc test_fp12_cb00a0(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == M_Twist: for _ in 0 ..< Iters: - var a = rng.random_elem(Fp12[C], gen) + var a = rng.random_elem(Fp12[Name], gen) var a2 = a - var x = rng.random_elem(Fp2[C], gen) - var y = rng.random_elem(Fp2[C], gen) - var z = rng.random_elem(Fp2[C], gen) + var x = rng.random_elem(Fp2[Name], gen) + var y = rng.random_elem(Fp2[Name], gen) + var z = rng.random_elem(Fp2[Name], gen) - let line = Line[Fp2[C]](a: x, b: y, c: z) - let b = Fp12[C](coords: [ - Fp6[C](coords: [ z, y, Fp2[C]()]), - Fp6[C](coords: [Fp2[C](), x, Fp2[C]()]) + let line = Line[Fp2[Name]](a: x, b: y, c: z) + let b = Fp12[Name](coords: [ + Fp6[Name](coords: [ z, y, Fp2[Name]()]), + Fp6[Name](coords: [Fp2[Name](), x, Fp2[Name]()]) ]) a *= b @@ -185,34 +185,34 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_cb00a0(curve, gen = Long01Sequence) test "Somewhat-sparse 𝔽p12/𝔽p6 resulting from a00bc0*a00bc0 line functions (D-twist only)": - proc test_fp12_a00bc0_a00bc0(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == D_Twist: + proc test_fp12_a00bc0_a00bc0(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == D_Twist: for _ in 0 ..< Iters: - var x0 = rng.random_elem(Fp2[C], gen) - var y0 = rng.random_elem(Fp2[C], gen) - var z0 = rng.random_elem(Fp2[C], gen) - - let line0 = Line[Fp2[C]](a: x0, b: y0, c: z0) - let f0 = Fp12[C]( coords: [ - Fp6[C](coords: [ x0, Fp2[C](), Fp2[C]()]), - Fp6[C](coords: [ y0, z0, Fp2[C]()]) + var x0 = rng.random_elem(Fp2[Name], gen) + var y0 = rng.random_elem(Fp2[Name], gen) + var z0 = rng.random_elem(Fp2[Name], gen) + + let line0 = Line[Fp2[Name]](a: x0, b: y0, c: z0) + let f0 = Fp12[Name]( coords: [ + Fp6[Name](coords: [ x0, Fp2[Name](), Fp2[Name]()]), + Fp6[Name](coords: [ y0, z0, Fp2[Name]()]) ]) - var x1 = rng.random_elem(Fp2[C], gen) - var y1 = rng.random_elem(Fp2[C], gen) - var z1 = rng.random_elem(Fp2[C], gen) + var x1 = rng.random_elem(Fp2[Name], gen) + var y1 = rng.random_elem(Fp2[Name], gen) + var z1 = rng.random_elem(Fp2[Name], gen) - let line1 = Line[Fp2[C]](a: x1, b: y1, c: z1) - let f1 = Fp12[C]( coords: [ - Fp6[C](coords: [ x1, Fp2[C](), Fp2[C]()]), - Fp6[C](coords: [ y1, z1, Fp2[C]()]) + let line1 = Line[Fp2[Name]](a: x1, b: y1, c: z1) + let f1 = Fp12[Name]( coords: [ + Fp6[Name](coords: [ x1, Fp2[Name](), Fp2[Name]()]), + Fp6[Name](coords: [ y1, z1, Fp2[Name]()]) ]) - var r: Fp12[C] + var r: Fp12[Name] r.prod(f0, f1) - var rl: Fp12[C] + var rl: Fp12[Name] rl.prod_x00yz0_x00yz0_into_abcdefghij00(line0, line1) check: bool(r == rl) @@ -223,33 +223,33 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_a00bc0_a00bc0(curve, gen = Long01Sequence) test "Somewhat-sparse 𝔽p12/𝔽p6 resulting from cb00a0*cb00a0 line functions (M-twist only)": - proc test_fp12_cb00a0_cb00a0(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == M_Twist: + proc test_fp12_cb00a0_cb00a0(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == M_Twist: for _ in 0 ..< Iters: - var x0 = rng.random_elem(Fp2[C], gen) - var y0 = rng.random_elem(Fp2[C], gen) - var z0 = rng.random_elem(Fp2[C], gen) - - let line0 = Line[Fp2[C]](a: x0, b: y0, c: z0) - let f0 = Fp12[C](coords: [ - Fp6[C](coords: [ z0, y0, Fp2[C]()]), - Fp6[C](coords: [Fp2[C](), x0, Fp2[C]()]) + var x0 = rng.random_elem(Fp2[Name], gen) + var y0 = rng.random_elem(Fp2[Name], gen) + var z0 = rng.random_elem(Fp2[Name], gen) + + let line0 = Line[Fp2[Name]](a: x0, b: y0, c: z0) + let f0 = Fp12[Name](coords: [ + Fp6[Name](coords: [ z0, y0, Fp2[Name]()]), + Fp6[Name](coords: [Fp2[Name](), x0, Fp2[Name]()]) ]) - var x1 = rng.random_elem(Fp2[C], gen) - var y1 = rng.random_elem(Fp2[C], gen) - var z1 = rng.random_elem(Fp2[C], gen) + var x1 = rng.random_elem(Fp2[Name], gen) + var y1 = rng.random_elem(Fp2[Name], gen) + var z1 = rng.random_elem(Fp2[Name], gen) - let line1 = Line[Fp2[C]](a: x1, b: y1, c: z1) - let f1 = Fp12[C](coords: [ - Fp6[C](coords: [ z1, y1, Fp2[C]()]), - Fp6[C](coords: [Fp2[C](), x1, Fp2[C]()]) + let line1 = Line[Fp2[Name]](a: x1, b: y1, c: z1) + let f1 = Fp12[Name](coords: [ + Fp6[Name](coords: [ z1, y1, Fp2[Name]()]), + Fp6[Name](coords: [Fp2[Name](), x1, Fp2[Name]()]) ]) - var r: Fp12[C] + var r: Fp12[Name] r.prod(f0, f1) - var rl: Fp12[C] + var rl: Fp12[Name] rl.prod_zy00x0_zy00x0_into_abcdef00ghij(line0, line1) check: bool(r == rl) @@ -260,38 +260,38 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_cb00a0_cb00a0(curve, gen = Long01Sequence) test "Somewhat-sparse 𝔽p12/𝔽p6 mul by the product a00bc0*a00bc0 of line functions (D-twist only)": - proc test_fp12_abcdefghij00(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == D_Twist: + proc test_fp12_abcdefghij00(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == D_Twist: for _ in 0 ..< Iters: - var x0 = rng.random_elem(Fp2[C], gen) - var y0 = rng.random_elem(Fp2[C], gen) - var z0 = rng.random_elem(Fp2[C], gen) - - let line0 = Line[Fp2[C]](a: x0, b: y0, c: z0) - let f0 = Fp12[C]( coords: [ - Fp6[C](coords: [ x0, Fp2[C](), Fp2[C]()]), - Fp6[C](coords: [ y0, z0, Fp2[C]()]) + var x0 = rng.random_elem(Fp2[Name], gen) + var y0 = rng.random_elem(Fp2[Name], gen) + var z0 = rng.random_elem(Fp2[Name], gen) + + let line0 = Line[Fp2[Name]](a: x0, b: y0, c: z0) + let f0 = Fp12[Name]( coords: [ + Fp6[Name](coords: [ x0, Fp2[Name](), Fp2[Name]()]), + Fp6[Name](coords: [ y0, z0, Fp2[Name]()]) ]) - var x1 = rng.random_elem(Fp2[C], gen) - var y1 = rng.random_elem(Fp2[C], gen) - var z1 = rng.random_elem(Fp2[C], gen) + var x1 = rng.random_elem(Fp2[Name], gen) + var y1 = rng.random_elem(Fp2[Name], gen) + var z1 = rng.random_elem(Fp2[Name], gen) - let line1 = Line[Fp2[C]](a: x1, b: y1, c: z1) - let f1 = Fp12[C]( coords: [ - Fp6[C](coords: [ x1, Fp2[C](), Fp2[C]()]), - Fp6[C](coords: [ y1, z1, Fp2[C]()]) + let line1 = Line[Fp2[Name]](a: x1, b: y1, c: z1) + let f1 = Fp12[Name]( coords: [ + Fp6[Name](coords: [ x1, Fp2[Name](), Fp2[Name]()]), + Fp6[Name](coords: [ y1, z1, Fp2[Name]()]) ]) - var r: Fp12[C] + var r: Fp12[Name] r.prod(f0, f1) - var rl: Fp12[C] + var rl: Fp12[Name] rl.prod_x00yz0_x00yz0_into_abcdefghij00(line0, line1) - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) var f2 = f f *= rl @@ -305,36 +305,36 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_abcdefghij00(curve, gen = Long01Sequence) test "Somewhat-sparse 𝔽p12/𝔽p6 mul by the product (cb00a0*cb00a0) of line functions (M-twist only)": - proc test_fp12_abcdef00ghij(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == M_Twist: + proc test_fp12_abcdef00ghij(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == M_Twist: for _ in 0 ..< Iters: - var x0 = rng.random_elem(Fp2[C], gen) - var y0 = rng.random_elem(Fp2[C], gen) - var z0 = rng.random_elem(Fp2[C], gen) - - let line0 = Line[Fp2[C]](a: x0, b: y0, c: z0) - let f0 = Fp12[C](coords: [ - Fp6[C](coords: [ z0, y0, Fp2[C]()]), - Fp6[C](coords: [Fp2[C](), x0, Fp2[C]()]) + var x0 = rng.random_elem(Fp2[Name], gen) + var y0 = rng.random_elem(Fp2[Name], gen) + var z0 = rng.random_elem(Fp2[Name], gen) + + let line0 = Line[Fp2[Name]](a: x0, b: y0, c: z0) + let f0 = Fp12[Name](coords: [ + Fp6[Name](coords: [ z0, y0, Fp2[Name]()]), + Fp6[Name](coords: [Fp2[Name](), x0, Fp2[Name]()]) ]) - var x1 = rng.random_elem(Fp2[C], gen) - var y1 = rng.random_elem(Fp2[C], gen) - var z1 = rng.random_elem(Fp2[C], gen) + var x1 = rng.random_elem(Fp2[Name], gen) + var y1 = rng.random_elem(Fp2[Name], gen) + var z1 = rng.random_elem(Fp2[Name], gen) - let line1 = Line[Fp2[C]](a: x1, b: y1, c: z1) - let f1 = Fp12[C](coords: [ - Fp6[C](coords: [ z1, y1, Fp2[C]()]), - Fp6[C](coords: [Fp2[C](), x1, Fp2[C]()]) + let line1 = Line[Fp2[Name]](a: x1, b: y1, c: z1) + let f1 = Fp12[Name](coords: [ + Fp6[Name](coords: [ z1, y1, Fp2[Name]()]), + Fp6[Name](coords: [Fp2[Name](), x1, Fp2[Name]()]) ]) - var r: Fp12[C] + var r: Fp12[Name] r.prod(f0, f1) - var rl: Fp12[C] + var rl: Fp12[Name] rl.prod_zy00x0_zy00x0_into_abcdef00ghij(line0, line1) - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) var f2 = f f *= rl @@ -351,22 +351,22 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi static: doAssert Fp12[BN254_Snarks]().c0.typeof is Fp4 test "Sparse 𝔽p12/𝔽p4 resulting from ca00b0 line function (M-twist only)": - proc test_fp12_ca00b0(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == M_Twist: + proc test_fp12_ca00b0(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == M_Twist: for _ in 0 ..< Iters: - var a = rng.random_elem(Fp12[C], gen) + var a = rng.random_elem(Fp12[Name], gen) var a2 = a - var x = rng.random_elem(Fp2[C], gen) - var y = rng.random_elem(Fp2[C], gen) - var z = rng.random_elem(Fp2[C], gen) + var x = rng.random_elem(Fp2[Name], gen) + var y = rng.random_elem(Fp2[Name], gen) + var z = rng.random_elem(Fp2[Name], gen) - let line = Line[Fp2[C]](a: x, b: y, c: z) - let b = Fp12[C]( + let line = Line[Fp2[Name]](a: x, b: y, c: z) + let b = Fp12[Name]( coords: [ - Fp4[C](coords: [z, x]), - Fp4[C](), - Fp4[C](coords: [y, Fp2[C]()]) + Fp4[Name](coords: [z, x]), + Fp4[Name](), + Fp4[Name](coords: [y, Fp2[Name]()]) ] ) @@ -381,22 +381,22 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_ca00b0(curve, gen = Long01Sequence) test "Sparse 𝔽p12/𝔽p4 resulting from xyz000 line function (D-twist only)": - proc test_fp12_acb000(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == D_Twist: + proc test_fp12_acb000(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == D_Twist: for _ in 0 ..< Iters: - var a = rng.random_elem(Fp12[C], gen) + var a = rng.random_elem(Fp12[Name], gen) var a2 = a - var x = rng.random_elem(Fp2[C], gen) - var y = rng.random_elem(Fp2[C], gen) - var z = rng.random_elem(Fp2[C], gen) + var x = rng.random_elem(Fp2[Name], gen) + var y = rng.random_elem(Fp2[Name], gen) + var z = rng.random_elem(Fp2[Name], gen) - let line = Line[Fp2[C]](a: x, b: y, c: z) - let b = Fp12[C]( + let line = Line[Fp2[Name]](a: x, b: y, c: z) + let b = Fp12[Name]( coords: [ - Fp4[C](coords: [x, z]), - Fp4[C](coords: [y, Fp2[C]()]), - Fp4[C]() + Fp4[Name](coords: [x, z]), + Fp4[Name](coords: [y, Fp2[Name]()]), + Fp4[Name]() ] ) @@ -411,39 +411,39 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_acb000(curve, gen = Long01Sequence) test "Somewhat-sparse 𝔽p12/𝔽p4 resulting from ca00b0*ca00b0 line functions (M-twist only)": - proc test_fp12_ca00b0_ca00b0(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == M_Twist: + proc test_fp12_ca00b0_ca00b0(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == M_Twist: for _ in 0 ..< Iters: - var x0 = rng.random_elem(Fp2[C], gen) - var y0 = rng.random_elem(Fp2[C], gen) - var z0 = rng.random_elem(Fp2[C], gen) + var x0 = rng.random_elem(Fp2[Name], gen) + var y0 = rng.random_elem(Fp2[Name], gen) + var z0 = rng.random_elem(Fp2[Name], gen) - let line0 = Line[Fp2[C]](a: x0, b: y0, c: z0) - let f0 = Fp12[C]( + let line0 = Line[Fp2[Name]](a: x0, b: y0, c: z0) + let f0 = Fp12[Name]( coords: [ - Fp4[C](coords: [z0, x0]), - Fp4[C](), - Fp4[C](coords: [y0, Fp2[C]()]) + Fp4[Name](coords: [z0, x0]), + Fp4[Name](), + Fp4[Name](coords: [y0, Fp2[Name]()]) ] ) - var x1 = rng.random_elem(Fp2[C], gen) - var y1 = rng.random_elem(Fp2[C], gen) - var z1 = rng.random_elem(Fp2[C], gen) + var x1 = rng.random_elem(Fp2[Name], gen) + var y1 = rng.random_elem(Fp2[Name], gen) + var z1 = rng.random_elem(Fp2[Name], gen) - let line1 = Line[Fp2[C]](a: x1, b: y1, c: z1) - let f1 = Fp12[C]( + let line1 = Line[Fp2[Name]](a: x1, b: y1, c: z1) + let f1 = Fp12[Name]( coords: [ - Fp4[C](coords: [z1, x1]), - Fp4[C](), - Fp4[C](coords: [y1, Fp2[C]()]) + Fp4[Name](coords: [z1, x1]), + Fp4[Name](), + Fp4[Name](coords: [y1, Fp2[Name]()]) ] ) - var r: Fp12[C] + var r: Fp12[Name] r.prod(f0, f1) - var rl: Fp12[C] + var rl: Fp12[Name] rl.prod_zx00y0_zx00y0_into_abcd00efghij(line0, line1) check: bool(r == rl) @@ -454,39 +454,39 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_ca00b0_ca00b0(curve, gen = Long01Sequence) test "Somewhat-sparse 𝔽p12/𝔽p4 resulting from acb000*acb000 line functions (D-twist only)": - proc test_fp12_acb000_acb000(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == D_Twist: + proc test_fp12_acb000_acb000(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == D_Twist: for _ in 0 ..< Iters: - var x0 = rng.random_elem(Fp2[C], gen) - var y0 = rng.random_elem(Fp2[C], gen) - var z0 = rng.random_elem(Fp2[C], gen) + var x0 = rng.random_elem(Fp2[Name], gen) + var y0 = rng.random_elem(Fp2[Name], gen) + var z0 = rng.random_elem(Fp2[Name], gen) - let line0 = Line[Fp2[C]](a: x0, b: y0, c: z0) - let f0 = Fp12[C]( + let line0 = Line[Fp2[Name]](a: x0, b: y0, c: z0) + let f0 = Fp12[Name]( coords: [ - Fp4[C](coords: [x0, z0]), - Fp4[C](coords: [y0, Fp2[C]()]), - Fp4[C]() + Fp4[Name](coords: [x0, z0]), + Fp4[Name](coords: [y0, Fp2[Name]()]), + Fp4[Name]() ] ) - var x1 = rng.random_elem(Fp2[C], gen) - var y1 = rng.random_elem(Fp2[C], gen) - var z1 = rng.random_elem(Fp2[C], gen) + var x1 = rng.random_elem(Fp2[Name], gen) + var y1 = rng.random_elem(Fp2[Name], gen) + var z1 = rng.random_elem(Fp2[Name], gen) - let line1 = Line[Fp2[C]](a: x1, b: y1, c: z1) - let f1 = Fp12[C]( + let line1 = Line[Fp2[Name]](a: x1, b: y1, c: z1) + let f1 = Fp12[Name]( coords: [ - Fp4[C](coords: [x1, z1]), - Fp4[C](coords: [y1, Fp2[C]()]), - Fp4[C]() + Fp4[Name](coords: [x1, z1]), + Fp4[Name](coords: [y1, Fp2[Name]()]), + Fp4[Name]() ] ) - var r: Fp12[C] + var r: Fp12[Name] r.prod(f0, f1) - var rl: Fp12[C] + var rl: Fp12[Name] rl.prod_xzy000_xzy000_into_abcdefghij00(line0, line1) check: bool(r == rl) @@ -497,42 +497,42 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_acb000_acb000(curve, gen = Long01Sequence) test "Somewhat-sparse 𝔽p12/𝔽p4 mul by the product (acb000*acb000) of line functions (D-twist only)": - proc test_fp12_abcdefghij00(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == D_Twist: + proc test_fp12_abcdefghij00(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == D_Twist: for _ in 0 ..< Iters: - var x0 = rng.random_elem(Fp2[C], gen) - var y0 = rng.random_elem(Fp2[C], gen) - var z0 = rng.random_elem(Fp2[C], gen) + var x0 = rng.random_elem(Fp2[Name], gen) + var y0 = rng.random_elem(Fp2[Name], gen) + var z0 = rng.random_elem(Fp2[Name], gen) - let line0 = Line[Fp2[C]](a: x0, b: y0, c: z0) - let f0 = Fp12[C]( + let line0 = Line[Fp2[Name]](a: x0, b: y0, c: z0) + let f0 = Fp12[Name]( coords: [ - Fp4[C](coords: [x0, z0]), - Fp4[C](coords: [y0, Fp2[C]()]), - Fp4[C]() + Fp4[Name](coords: [x0, z0]), + Fp4[Name](coords: [y0, Fp2[Name]()]), + Fp4[Name]() ] ) - var x1 = rng.random_elem(Fp2[C], gen) - var y1 = rng.random_elem(Fp2[C], gen) - var z1 = rng.random_elem(Fp2[C], gen) + var x1 = rng.random_elem(Fp2[Name], gen) + var y1 = rng.random_elem(Fp2[Name], gen) + var z1 = rng.random_elem(Fp2[Name], gen) - let line1 = Line[Fp2[C]](a: x1, b: y1, c: z1) - let f1 = Fp12[C]( + let line1 = Line[Fp2[Name]](a: x1, b: y1, c: z1) + let f1 = Fp12[Name]( coords: [ - Fp4[C](coords: [x1, z1]), - Fp4[C](coords: [y1, Fp2[C]()]), - Fp4[C]() + Fp4[Name](coords: [x1, z1]), + Fp4[Name](coords: [y1, Fp2[Name]()]), + Fp4[Name]() ] ) - var r: Fp12[C] + var r: Fp12[Name] r.prod(f0, f1) - var rl: Fp12[C] + var rl: Fp12[Name] rl.prod_xzy000_xzy000_into_abcdefghij00(line0, line1) - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) var f2 = f f *= rl @@ -546,42 +546,42 @@ suite "Pairing - Sparse 𝔽p12 multiplication by line function is consistent wi test_fp12_abcdefghij00(curve, gen = Long01Sequence) test "Somewhat-sparse 𝔽p12/𝔽p4 mul by the product (ca00b0*ca00b0) of line functions (M-twist only)": - proc test_fp12_abcdef00ghij(C: static Curve, gen: static RandomGen) = - when C.getSexticTwist() == M_Twist: + proc test_fp12_abcdef00ghij(Name: static Algebra, gen: static RandomGen) = + when Name.getSexticTwist() == M_Twist: for _ in 0 ..< Iters: - var x0 = rng.random_elem(Fp2[C], gen) - var y0 = rng.random_elem(Fp2[C], gen) - var z0 = rng.random_elem(Fp2[C], gen) + var x0 = rng.random_elem(Fp2[Name], gen) + var y0 = rng.random_elem(Fp2[Name], gen) + var z0 = rng.random_elem(Fp2[Name], gen) - let line0 = Line[Fp2[C]](a: x0, b: y0, c: z0) - let f0 = Fp12[C]( + let line0 = Line[Fp2[Name]](a: x0, b: y0, c: z0) + let f0 = Fp12[Name]( coords: [ - Fp4[C](coords: [z0, x0]), - Fp4[C](), - Fp4[C](coords: [y0, Fp2[C]()]) + Fp4[Name](coords: [z0, x0]), + Fp4[Name](), + Fp4[Name](coords: [y0, Fp2[Name]()]) ] ) - var x1 = rng.random_elem(Fp2[C], gen) - var y1 = rng.random_elem(Fp2[C], gen) - var z1 = rng.random_elem(Fp2[C], gen) + var x1 = rng.random_elem(Fp2[Name], gen) + var y1 = rng.random_elem(Fp2[Name], gen) + var z1 = rng.random_elem(Fp2[Name], gen) - let line1 = Line[Fp2[C]](a: x1, b: y1, c: z1) - let f1 = Fp12[C]( + let line1 = Line[Fp2[Name]](a: x1, b: y1, c: z1) + let f1 = Fp12[Name]( coords: [ - Fp4[C](coords: [z1, x1]), - Fp4[C](), - Fp4[C](coords: [y1, Fp2[C]()]) + Fp4[Name](coords: [z1, x1]), + Fp4[Name](), + Fp4[Name](coords: [y1, Fp2[Name]()]) ] ) - var r: Fp12[C] + var r: Fp12[Name] r.prod(f0, f1) - var rl: Fp12[C] + var rl: Fp12[Name] rl.prod_zx00y0_zx00y0_into_abcd00efghij(line0, line1) - var f = rng.random_elem(Fp12[C], gen) + var f = rng.random_elem(Fp12[Name], gen) var f2 = f f *= rl diff --git a/tests/math_pairings/t_pairing_template.nim b/tests/math_pairings/t_pairing_template.nim index 30218c6d8..c7378d1f0 100644 --- a/tests/math_pairings/t_pairing_template.nim +++ b/tests/math_pairings/t_pairing_template.nim @@ -37,13 +37,13 @@ type Long01Sequence template affineType[F; G: static Subgroup]( - ec: ECP_ShortW_Prj[F, G]): type = - ECP_ShortW_Aff[F, G] + ec: EC_ShortW_Prj[F, G]): type = + EC_ShortW_Aff[F, G] func clearCofactor[F; G: static Subgroup]( - ec: var ECP_ShortW_Aff[F, G]) = + ec: var EC_ShortW_Aff[F, G]) = # For now we don't have any affine operation defined - var t {.noInit.}: ECP_ShortW_Prj[F, G] + var t {.noInit.}: EC_ShortW_Prj[F, G] t.fromAffine(ec) t.clearCofactor() ec.affine(t) @@ -59,14 +59,14 @@ func random_point*(rng: var RngState, EC: typedesc, randZ: bool, gen: RandomGen) result = rng.random_long01Seq(EC) result.clearCofactor() -template runPairingTests*(Iters: static int, C: static Curve, G1, G2, GT: typedesc, pairing_fn: untyped): untyped {.dirty.}= +template runPairingTests*(Iters: static int, Name: static Algebra, G1, G2, GT: typedesc, pairing_fn: untyped): untyped {.dirty.}= bind affineType var rng: RngState let timeseed = uint32(toUnix(getTime()) and (1'i64 shl 32 - 1)) # unixTime mod 2^32 seed(rng, timeseed) echo "\n------------------------------------------------------\n" - echo "test_pairing_",$C,"_optate xoshiro512** seed: ", timeseed + echo "test_pairing_",$Name,"_optate xoshiro512** seed: ", timeseed proc test_bilinearity_double_impl(randZ: bool, gen: RandomGen) = for _ in 0 ..< Iters: @@ -99,7 +99,7 @@ template runPairingTests*(Iters: static int, C: static Curve, G1, G2, GT: typede doAssert bool(r == r3) doAssert bool(r2 == r3) - suite "Pairing - Optimal Ate on " & $C & " [" & $WordBitWidth & "-bit words]": + suite "Pairing - Optimal Ate on " & $Name & " [" & $WordBitWidth & "-bit words]": test "Bilinearity e([2]P, Q) = e(P, [2]Q) = e(P, Q)^2": test_bilinearity_double_impl(randZ = false, gen = Uniform) test_bilinearity_double_impl(randZ = false, gen = HighHammingWeight) @@ -120,7 +120,7 @@ template runGTsubgroupTests*(Iters: static int, GT: typedesc, finalExpHard_fn: u let timeseed = uint32(toUnix(getTime()) and (1'i64 shl 32 - 1)) # unixTime mod 2^32 seed(rng, timeseed) echo "\n------------------------------------------------------\n" - echo "test_pairing_",$GT.C,"_gt xoshiro512** seed: ", timeseed + echo "test_pairing_",$GT.Name,"_gt xoshiro512** seed: ", timeseed proc test_gt_impl(gen: RandomGen) = stdout.write " " @@ -139,7 +139,7 @@ template runGTsubgroupTests*(Iters: static int, GT: typedesc, finalExpHard_fn: u stdout.write '\n' - suite "Pairing - GT subgroup " & $GT.C & " [" & $WordBitWidth & "-bit words]": + suite "Pairing - GT subgroup " & $GT.Name & " [" & $WordBitWidth & "-bit words]": test "Final Exponentiation and GT-subgroup membership": test_gt_impl(gen = Uniform) test_gt_impl(gen = HighHammingWeight) diff --git a/tests/parallel/t_ec_shortw_jac_g1_batch_add_parallel.nim b/tests/parallel/t_ec_shortw_jac_g1_batch_add_parallel.nim index 6c1d94cc2..5297f3213 100644 --- a/tests/parallel/t_ec_shortw_jac_g1_batch_add_parallel.nim +++ b/tests/parallel/t_ec_shortw_jac_g1_batch_add_parallel.nim @@ -17,13 +17,13 @@ import const numPoints = [1, 2, 8, 16, 128, 1024, 2048, 16384, 32768] # 262144, 1048576] run_EC_batch_add_parallel_impl( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_batch_add_parallel_" & $BN254_Snarks ) run_EC_batch_add_parallel_impl( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_batch_add_parallel_" & $BLS12_381 ) diff --git a/tests/parallel/t_ec_shortw_jac_g1_msm_parallel.nim b/tests/parallel/t_ec_shortw_jac_g1_msm_parallel.nim index 2c6e9a16b..9dc1e6993 100644 --- a/tests/parallel/t_ec_shortw_jac_g1_msm_parallel.nim +++ b/tests/parallel/t_ec_shortw_jac_g1_msm_parallel.nim @@ -17,13 +17,13 @@ import const numPoints = [1, 2, 8, 16, 32, 64, 128, 1024, 2048, 16384] # 32768, 262144, 1048576] run_EC_multi_scalar_mul_parallel_impl( - ec = ECP_ShortW_Jac[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Jac[Fp[BN254_Snarks], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_msm_parallel_" & $BN254_Snarks ) run_EC_multi_scalar_mul_parallel_impl( - ec = ECP_ShortW_Jac[Fp[BLS12_381], G1], + ec = EC_ShortW_Jac[Fp[BLS12_381], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_jacobian_msm_parallel_" & $BLS12_381 ) diff --git a/tests/parallel/t_ec_shortw_prj_g1_batch_add_parallel.nim b/tests/parallel/t_ec_shortw_prj_g1_batch_add_parallel.nim index 827d91ad6..3f50b2310 100644 --- a/tests/parallel/t_ec_shortw_prj_g1_batch_add_parallel.nim +++ b/tests/parallel/t_ec_shortw_prj_g1_batch_add_parallel.nim @@ -17,13 +17,13 @@ import const numPoints = [1, 2, 8, 16, 128, 1024, 2048, 16384, 32768] # 262144, 1048576] run_EC_batch_add_parallel_impl( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_projective_batch_add_parallel_" & $BN254_Snarks ) run_EC_batch_add_parallel_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_projective_batch_add_parallel_" & $BLS12_381 ) diff --git a/tests/parallel/t_ec_shortw_prj_g1_msm_parallel.nim b/tests/parallel/t_ec_shortw_prj_g1_msm_parallel.nim index ebac995d1..7fa2a09ab 100644 --- a/tests/parallel/t_ec_shortw_prj_g1_msm_parallel.nim +++ b/tests/parallel/t_ec_shortw_prj_g1_msm_parallel.nim @@ -17,13 +17,13 @@ import const numPoints = [1, 2, 8, 16, 128, 1024, 2048, 16384] # 32768, 262144, 1048576] run_EC_multi_scalar_mul_parallel_impl( - ec = ECP_ShortW_Prj[Fp[BN254_Snarks], G1], + ec = EC_ShortW_Prj[Fp[BN254_Snarks], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_projective_msm_parallel_" & $BN254_Snarks ) run_EC_multi_scalar_mul_parallel_impl( - ec = ECP_ShortW_Prj[Fp[BLS12_381], G1], + ec = EC_ShortW_Prj[Fp[BLS12_381], G1], numPoints = numPoints, moduleName = "test_ec_shortweierstrass_projective_msm_parallel_" & $BLS12_381 ) diff --git a/tests/parallel/t_ec_template_parallel.nim b/tests/parallel/t_ec_template_parallel.nim index 34e31153f..06102c546 100644 --- a/tests/parallel/t_ec_template_parallel.nim +++ b/tests/parallel/t_ec_template_parallel.nim @@ -42,7 +42,7 @@ type Long01Sequence func random_point*(rng: var RngState, EC: typedesc, randZ: bool, gen: RandomGen): EC {.noInit.} = - when EC is (ECP_ShortW_Aff or ECP_TwEdwards_Aff): + when EC is (EC_ShortW_Aff or EC_TwEdw_Aff): if gen == Uniform: result = rng.random_unsafe(EC) elif gen == HighHammingWeight: @@ -88,10 +88,10 @@ proc run_EC_batch_add_parallel_impl*[N: static int]( let tp = Threadpool.new() defer: tp.shutdown() - var points = newSeq[ECP_ShortW_Aff[EC.F, EC.G]](n) + var points = newSeq[EC_ShortW_Aff[EC.F, EC.G]](n) for i in 0 ..< n: - points[i] = rng.random_point(ECP_ShortW_Aff[EC.F, EC.G], randZ = false, gen) + points[i] = rng.random_point(EC_ShortW_Aff[EC.F, EC.G], randZ = false, gen) var r_batch{.noinit.}, r_ref{.noInit.}: EC @@ -113,19 +113,19 @@ proc run_EC_batch_add_parallel_impl*[N: static int]( let tp = Threadpool.new() defer: tp.shutdown() - var points = newSeq[ECP_ShortW_Aff[EC.F, EC.G]](n) + var points = newSeq[EC_ShortW_Aff[EC.F, EC.G]](n) let halfN = n div 2 for i in 0 ..< halfN: - points[i] = rng.random_point(ECP_ShortW_Aff[EC.F, EC.G], randZ = false, gen) + points[i] = rng.random_point(EC_ShortW_Aff[EC.F, EC.G], randZ = false, gen) for i in halfN ..< n: # The special cases test relies on internal knowledge that we sum(points[i], points[i+n/2] # It should be changed if scheduling change, for example if we sum(points[2*i], points[2*i+1]) let c = rng.random_unsafe(3) if c == 0: - points[i] = rng.random_point(ECP_ShortW_Aff[EC.F, EC.G], randZ = false, gen) + points[i] = rng.random_point(EC_ShortW_Aff[EC.F, EC.G], randZ = false, gen) elif c == 1: points[i] = points[i-halfN] else: @@ -161,19 +161,19 @@ proc run_EC_multi_scalar_mul_parallel_impl*[N: static int]( suite testSuiteDesc & " - " & $ec & " - [" & $WordBitWidth & "-bit mode]": for n in numPoints: - let bucketBits = bestBucketBitSize(n, ec.F.C.getCurveOrderBitwidth(), useSignedBuckets = false, useManualTuning = false) + let bucketBits = bestBucketBitSize(n, ec.getScalarField().bits(), useSignedBuckets = false, useManualTuning = false) test $ec & " Parallel Multi-scalar-mul (N=" & $n & ", bucket bits (default): " & $bucketBits & ")": proc test(EC: typedesc, gen: RandomGen) = let tp = Threadpool.new() defer: tp.shutdown() var points = newSeq[affine(EC)](n) - var coefs = newSeq[BigInt[EC.F.C.getCurveOrderBitwidth()]](n) + var coefs = newSeq[BigInt[EC.getScalarField().bits()]](n) for i in 0 ..< n: var tmp = rng.random_unsafe(EC) tmp.clearCofactor() points[i].affine(tmp) - coefs[i] = rng.random_unsafe(BigInt[EC.F.C.getCurveOrderBitwidth()]) + coefs[i] = rng.random_unsafe(BigInt[EC.getScalarField().bits()]) var naive, naive_tmp: EC naive.setNeutral() diff --git a/tests/parallel/t_ec_twedwards_prj_msm_parallel.nim b/tests/parallel/t_ec_twedwards_prj_msm_parallel.nim index b8601be66..5e898de74 100644 --- a/tests/parallel/t_ec_twedwards_prj_msm_parallel.nim +++ b/tests/parallel/t_ec_twedwards_prj_msm_parallel.nim @@ -17,7 +17,7 @@ import const numPoints = [1, 2, 8, 16, 32, 64, 128, 1024, 2048, 16384] # 32768, 262144, 1048576] run_EC_multi_scalar_mul_parallel_impl( - ec = ECP_TwEdwards_Prj[Fp[Bandersnatch]], + ec = EC_TwEdw_Prj[Fp[Bandersnatch]], numPoints = numPoints, moduleName = "test_ec_twistededwards_prj_msm_parallel_" & $Bandersnatch ) diff --git a/tests/primitives/t_io_unsaturated.nim b/tests/primitives/t_io_unsaturated.nim index de9c4604f..571b09ba7 100644 --- a/tests/primitives/t_io_unsaturated.nim +++ b/tests/primitives/t_io_unsaturated.nim @@ -27,21 +27,21 @@ type HighHammingWeight Long01Sequence -func random_bigint*(rng: var RngState, curve: static Curve, gen: static RandomGen): auto = +func random_bigint*(rng: var RngState, name: static Algebra, gen: static RandomGen): auto = when gen == Uniform: - rng.random_unsafe(matchingBigInt(curve)) + rng.random_unsafe(Fp[name].getBigInt()) elif gen == HighHammingWeight: - rng.random_highHammingWeight(matchingBigInt(curve)) + rng.random_highHammingWeight(Fp[name].getBigInt()) else: - rng.random_long01Seq(matchingBigInt(curve)) + rng.random_long01Seq(Fp[name].getBigInt()) -proc testRoundtrip(curve: static Curve, gen: static RandomGen) = - const bits = curve.getCurveBitwidth() +proc testRoundtrip(name: static Algebra, gen: static RandomGen) = + const bits = Fp[name].bits() const Excess = 2 const UnsatBitwidth = WordBitWidth - Excess const N = bits.ceilDiv_vartime(UnsatBitwidth) - let a = rng.random_bigint(curve, gen) + let a = rng.random_bigint(name, gen) var u: LimbsUnsaturated[N, Excess] var b: typeof(a) diff --git a/tests/t_ethereum_eip2333_bls12381_key_derivation.nim b/tests/t_ethereum_eip2333_bls12381_key_derivation.nim index 957c110fd..efa293644 100644 --- a/tests/t_ethereum_eip2333_bls12381_key_derivation.nim +++ b/tests/t_ethereum_eip2333_bls12381_key_derivation.nim @@ -16,7 +16,7 @@ import constantine/platforms/abstractions, constantine/serialization/codecs -type SecretKey = matchingOrderBigInt(BLS12_381) +type SecretKey = Fr[BLS12_381].getBigInt() proc toBytes(hex: string): seq[byte] = doAssert (hex.len and 1) == 0, "Input hex must have an even number of characters" diff --git a/tests/t_ethereum_verkle_ipa_primitives.nim b/tests/t_ethereum_verkle_ipa_primitives.nim index d6dfdad71..b8c258aa9 100644 --- a/tests/t_ethereum_verkle_ipa_primitives.nim +++ b/tests/t_ethereum_verkle_ipa_primitives.nim @@ -65,7 +65,7 @@ suite "Barycentric Form Tests": poly.interpolate(points,2) - var genfp: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var genfp: EC_TwEdw_Prj[Fp[Banderwagon]] genfp.setGenerator() var genfr: Fr[Banderwagon] genfr.mapToScalarField(genfp) @@ -175,7 +175,7 @@ suite "Barycentric Form Tests": # var ipaConfig {.noInit.}: IPASettings # ipaConfig.genIPAConfig() -# var basisPoints {.noInit.}: array[256, ECP_TwEdwards_Aff[Fp[Banderwagon]]] +# var basisPoints {.noInit.}: array[256, EC_TwEdw_Aff[Fp[Banderwagon]]] # basisPoints.generate_random_points() # var p0 {.noInit.}, p255 {.noInit.}: array[32, byte] @@ -203,14 +203,14 @@ suite "Barycentric Form Tests": # var ipaConfig: IPASettings # ipaConfig.genIPAConfig() -# var basisPoints: PolynomialEval[256, ECP_TwEdwards_Aff[Fp[Banderwagon]]] +# var basisPoints: PolynomialEval[256, EC_TwEdw_Aff[Fp[Banderwagon]]] # basisPoints.evals.generate_random_points() # var test_scalars {.noInit.}: PolynomialEval[256, Fr[Banderwagon]] # for i in 0 ..< 256: # test_scalars.evals[i].fromHex(testScalarsHex[i]) -# var commitment {.noInit.}: ECP_TwEdwards_Prj[Fp[Banderwagon]] +# var commitment {.noInit.}: EC_TwEdw_Prj[Fp[Banderwagon]] # basisPoints.pedersen_commit(commitment, test_scalars) # var arr22 {.noInit.}: Bytes @@ -231,7 +231,7 @@ suite "Deserialize a proof which contains an invalid final scalar by @Ignacio": test "Deserialize a proof which contains a final scalar bigger than the field size (MUST fail)": proc testBiggerThanFieldSizeDeserialize() = - var test_big {.noInit.}: matchingOrderBigInt(Banderwagon) + var test_big {.noInit.}: Fr[Banderwagon].getBigInt() var proof1_bytes = newSeq[byte](serializedProof1.len) proof1_bytes.fromHex(serializedProof1) @@ -259,7 +259,7 @@ suite "Deserialize a proof which wrong lengths by @Ignacio": proc testInvalidFieldSizeDeserialize() = - var test_big {.noInit.}: array[3, matchingOrderBigInt(Banderwagon)] + var test_big {.noInit.}: array[3, Fr[Banderwagon].getBigInt()] var i: int = 0 @@ -377,7 +377,7 @@ suite "Transcript Tests": tr.domainSeparator("separate me again") tr.absorb("now 1", one) - var challenge {.noInit.}: matchingOrderBigInt(Banderwagon) + var challenge {.noInit.}: Fr[Banderwagon].getBigInt() tr.squeezeChallenge("simple_challenge", challenge) var bytes {.noInit.}: array[32, byte] @@ -421,7 +421,7 @@ suite "IPA proof tests": # var commitmentBytes {.noInit.} : array[32, byte] # commitmentBytes.fromHex(IPAPedersenCommitment) - # var commitment: ECP_TwEdwards_Aff[Fp[Banderwagon]] + # var commitment: EC_TwEdw_Aff[Fp[Banderwagon]] # discard commitment.deserialize(commitmentBytes) # var evalPoint: Fr[Banderwagon] @@ -432,11 +432,11 @@ suite "IPA proof tests": # var proof_bytes: EthVerkleIpaProofBytes # proof_bytes.fromHex(IPASerializedProofVec) - # var proof {.noInit.}: IpaProof[8, ECP_TwEdwards_Aff[Fp[Banderwagon]], Fr[Banderwagon]] + # var proof {.noInit.}: IpaProof[8, EC_TwEdw_Aff[Fp[Banderwagon]], Fr[Banderwagon]] # let status = proof.deserialize(proof_bytes) # doAssert status == cttEthVerkleIpa_Success - # var CRS: PolynomialEval[EthVerkleDomain, ECP_TwEdwards_Aff[Fp[Banderwagon]]] + # var CRS: PolynomialEval[EthVerkleDomain, EC_TwEdw_Aff[Fp[Banderwagon]]] # CRS.evals.generate_random_points() # var domain: PolyEvalLinearDomain[EthVerkleDomain, Fr[Banderwagon]] @@ -462,7 +462,7 @@ suite "IPA proof tests": var opening_challenge: Fr[Banderwagon] opening_challenge.fromInt(2101) - var CRS: PolynomialEval[EthVerkleDomain, ECP_TwEdwards_Aff[Fp[Banderwagon]]] + var CRS: PolynomialEval[EthVerkleDomain, EC_TwEdw_Aff[Fp[Banderwagon]]] CRS.evals.generate_random_points() var domain: PolyEvalLinearDomain[EthVerkleDomain, Fr[Banderwagon]] @@ -482,9 +482,9 @@ suite "IPA proof tests": var poly: PolynomialEval[256, Fr[Banderwagon]] poly.evals.testPoly256(testVals) - var comm: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var comm: EC_TwEdw_Prj[Fp[Banderwagon]] CRS.pedersen_commit(comm, poly) - var commitment: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var commitment: EC_TwEdw_Aff[Fp[Banderwagon]] commitment.affine(comm) var C {.noInit.}: array[32, byte] @@ -495,7 +495,7 @@ suite "IPA proof tests": var prover_transcript {.noInit.}: sha256 prover_transcript.initTranscript("test") - var proof {.noInit.}: IpaProof[8, ECP_TwEdwards_Aff[Fp[Banderwagon]], Fr[Banderwagon]] + var proof {.noInit.}: IpaProof[8, EC_TwEdw_Aff[Fp[Banderwagon]], Fr[Banderwagon]] var eval_at_challenge {.noInit.}: Fr[Banderwagon] CRS.ipa_prove( domain, prover_transcript, @@ -513,7 +513,7 @@ suite "IPA proof tests": # var opening_challenge: Fr[Banderwagon] # opening_challenge.fromInt(2101) - # var CRS: PolynomialEval[EthVerkleDomain, ECP_TwEdwards_Aff[Fp[Banderwagon]]] + # var CRS: PolynomialEval[EthVerkleDomain, EC_TwEdw_Aff[Fp[Banderwagon]]] # CRS.evals.generate_random_points() # var domain: PolyEvalLinearDomain[EthVerkleDomain, Fr[Banderwagon]] @@ -524,16 +524,16 @@ suite "IPA proof tests": # var poly: PolynomialEval[256, Fr[Banderwagon]] # poly.evals.testPoly256(testVals) - # var comm: ECP_TwEdwards_Prj[Fp[Banderwagon]] + # var comm: EC_TwEdw_Prj[Fp[Banderwagon]] # CRS.pedersen_commit(comm, poly) - # var commitment: ECP_TwEdwards_Aff[Fp[Banderwagon]] + # var commitment: EC_TwEdw_Aff[Fp[Banderwagon]] # commitment.affine(comm) # # Prover's side # var prover_transcript {.noInit.}: sha256 # prover_transcript.initTranscript("ipa") - # var proof {.noInit.}: IpaProof[8, ECP_TwEdwards_Aff[Fp[Banderwagon]], Fr[Banderwagon]] + # var proof {.noInit.}: IpaProof[8, EC_TwEdw_Aff[Fp[Banderwagon]], Fr[Banderwagon]] # var eval_at_challenge {.noInit.}: Fr[Banderwagon] # CRS.ipa_prove( # domain, prover_transcript, @@ -634,7 +634,7 @@ suite "Multiproof Tests": # test "Multiproof Creation and Verification (new)": # proc testMultiproofCreationAndVerification()= - # var CRS: PolynomialEval[EthVerkleDomain, ECP_TwEdwards_Aff[Fp[Banderwagon]]] + # var CRS: PolynomialEval[EthVerkleDomain, EC_TwEdw_Aff[Fp[Banderwagon]]] # CRS.evals.generate_random_points() # var domain: PolyEvalLinearDomain[EthVerkleDomain, Fr[Banderwagon]] @@ -644,19 +644,19 @@ suite "Multiproof Tests": # var poly: PolynomialEval[256, Fr[Banderwagon]] # poly.evals.testPoly256(testVals) - # var prover_comm: ECP_TwEdwards_Prj[Fp[Banderwagon]] + # var prover_comm: EC_TwEdw_Prj[Fp[Banderwagon]] # CRS.pedersen_commit(prover_comm, poly) - # var C: ECP_TwEdwards_Aff[Fp[Banderwagon]] + # var C: EC_TwEdw_Aff[Fp[Banderwagon]] # C.affine(prover_comm) # # Prover's view # var prover_transcript {.noInit.}: sha256 # prover_transcript.initTranscript("multiproof") - # var multiproof {.noInit.}: IpaMultiProof[8, ECP_TwEdwards_Aff[Fp[Banderwagon]], Fr[Banderwagon]] + # var multiproof {.noInit.}: IpaMultiProof[8, EC_TwEdw_Aff[Fp[Banderwagon]], Fr[Banderwagon]] # CRS.ipa_multi_prove( # domain, prover_transcript, - # multiproof, [poly], [C], [0'u32] + # multiproof, [poly], [Name], [0'u32] # ) # var hexproof: EthVerkleIpaMultiProofBytes @@ -667,7 +667,7 @@ suite "Multiproof Tests": # var verifier_transcript: sha256 # verifier_transcript.initTranscript("multiproof") - # let ok = CRS.ipa_multi_verify(domain, verifier_transcript, [C], [0'u32], [Fr[Banderwagon].fromUint(1'u32)], multiproof) + # let ok = CRS.ipa_multi_verify(domain, verifier_transcript, [Name], [0'u32], [Fr[Banderwagon].fromUint(1'u32)], multiproof) # doAssert ok, "Multiproof verification error!" @@ -726,7 +726,7 @@ suite "Multiproof Tests": validMultiproof_bytes.fromHex(validMultiproof) ## Deserialize it into the Multiproof type - var multiproof {.noInit.}: IpaMultiProof[8, ECP_TwEdwards_Aff[Fp[Banderwagon]], Fr[Banderwagon]] + var multiproof {.noInit.}: IpaMultiProof[8, EC_TwEdw_Aff[Fp[Banderwagon]], Fr[Banderwagon]] let s1 = multiproof.deserialize(validMultiproof_bytes) doAssert s1 == cttEthVerkleIpa_Success, "Failed to deserialize Multiproof" diff --git a/tests/t_ethereum_verkle_ipa_test_helper.nim b/tests/t_ethereum_verkle_ipa_test_helper.nim index ed800e360..f345953a8 100644 --- a/tests/t_ethereum_verkle_ipa_test_helper.nim +++ b/tests/t_ethereum_verkle_ipa_test_helper.nim @@ -173,13 +173,13 @@ func testPoly256* [Fr] (res: var openArray[Fr], polynomialUint: openArray[int])= for i in polynomialUint.len ..< pad: res[i].setZero() -func isPointEqHex*(point: ECP_TwEdwards_Prj[Fp[Banderwagon]], expected: string): bool {.discardable.} = +func isPointEqHex*(point: EC_TwEdw_Prj[Fp[Banderwagon]], expected: string): bool {.discardable.} = var point_bytes {.noInit.}: array[32, byte] if point_bytes.serialize(point) == cttCodecEcc_Success: doAssert (point_bytes.toHex() == expected).bool() == true, "Point does not equal to the expected hex value!" -func isScalarEqHex*(scalar: matchingOrderBigInt(Banderwagon), expected: string) : bool {.discardable.} = +func isScalarEqHex*(scalar: Fr[Banderwagon].getBigInt(), expected: string) : bool {.discardable.} = var scalar_bytes {.noInit.}: array[32, byte] if scalar_bytes.serialize_scalar(scalar) == cttCodecScalar_Success: diff --git a/tests/t_ethereum_verkle_primitives.nim b/tests/t_ethereum_verkle_primitives.nim index 4003f90b7..b08f620e2 100644 --- a/tests/t_ethereum_verkle_primitives.nim +++ b/tests/t_ethereum_verkle_primitives.nim @@ -100,7 +100,7 @@ proc testDeserialize(hexString: string, status: CttCodecEccStatus) : bool = if check: # deserialization from bits - var point{.noInit.}: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var point{.noInit.}: EC_TwEdw_Aff[Fp[Banderwagon]] let stat = point.deserialize_vartime(arr) return stat == status @@ -120,8 +120,8 @@ suite "Banderwagon Serialization Tests": # proc testSerialize(len: int) = # # First the point is set to generator P # # then with each iteration 2P, 4P, . . . doubling - # var points: seq[ECP_TwEdwards_Aff[Fp[Banderwagon]]] - # var point {.noInit.}: ECP_TwEdwards_Aff[Fp[Banderwagon]] + # var points: seq[EC_TwEdw_Aff[Fp[Banderwagon]]] + # var point {.noInit.}: EC_TwEdw_Aff[Fp[Banderwagon]] # point.setGenerator() # for i in 0 ..< len: @@ -149,7 +149,7 @@ suite "Banderwagon Serialization Tests": # discard arr.parseHex(bit_string) # # deserialization from expected bits - # var point{.noInit.}: ECP_TwEdwards_Aff[Fp[Banderwagon]] + # var point{.noInit.}: EC_TwEdw_Aff[Fp[Banderwagon]] # let stat = point.deserialize(arr) # # Assertion check for the Deserialization Success & correctness @@ -170,7 +170,7 @@ suite "Banderwagon Serialization Tests": # discard arr.parseHex(bit_string) # # deserialization from expected bits - # var point{.noInit.}: ECP_TwEdwards_Prj[Fp[Banderwagon]] + # var point{.noInit.}: EC_TwEdw_Prj[Fp[Banderwagon]] # let stat = point.deserialize_vartime(arr) # # Assertion check for the Deserialization Success & correctness @@ -198,7 +198,7 @@ suite "Banderwagon Serialization Tests": test "Serialize a valid point with Y lexicographically highest": proc testSerializeWithYLargest() = const expected_serialized_point = "0x0e7e3748db7c5c999a7bcd93d71d671f1f40090423792266f94cb27ca43fce5c" - var point {.noInit.}: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var point {.noInit.}: EC_TwEdw_Prj[Fp[Banderwagon]] point.x.fromHex("0x0e7e3748db7c5c999a7bcd93d71d671f1f40090423792266f94cb27ca43fce5c") point.y.fromHex("0x563a625521456130dc66f9fd6bda67330c7bb183b7f2223216c1c9536e1c622f") @@ -261,7 +261,7 @@ suite "Banderwagon Serialization Tests": ## Tests for Uncompressed point serialization test "Uncompressed Point Serialization": proc testUncompressedSerialization() = - var point, point_regen {.noInit.}: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var point, point_regen {.noInit.}: EC_TwEdw_Aff[Fp[Banderwagon]] point.setGenerator() var arr: array[64, byte] @@ -288,7 +288,7 @@ suite "Banderwagon Points Tests": ## and correctness of the subtraction test "Test for Addition, Subtraction, Doubling": proc testAddSubDouble() = - var a, b, gen_point, identity {.noInit.} : ECP_TwEdwards_Prj[Fp[Banderwagon]] + var a, b, gen_point, identity {.noInit.} : EC_TwEdw_Prj[Fp[Banderwagon]] gen_point.setGenerator() # Setting the identity Element @@ -311,18 +311,18 @@ suite "Banderwagon Points Tests": ## are equal, where the two torsion point is not the point at infinity test "Test Two Torsion Equality": proc testTwoTorsion() = - var two_torsion: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var two_torsion: EC_TwEdw_Prj[Fp[Banderwagon]] # Setting the two torsion point two_torsion.x.setZero() two_torsion.y.setMinusOne() two_torsion.z.setOne() - var point{.noInit.}: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var point{.noInit.}: EC_TwEdw_Prj[Fp[Banderwagon]] point.setGenerator() for i in 0 ..< 1000: - var point_plus_torsion: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var point_plus_torsion: EC_TwEdw_Prj[Fp[Banderwagon]] point_plus_torsion.sum(point, two_torsion) # adding generator with two torsion point doAssert (point == point_plus_torsion).bool(), "points that differ by an order-2 point should be equal" @@ -351,7 +351,7 @@ suite "Banderwagon Elements Mapping": ## is working as expected or not test "Testing Map To Base Field": proc testMultiMapToBaseField() = - var A, B, genPoint {.noInit.}: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var A, B, genPoint {.noInit.}: EC_TwEdw_Prj[Fp[Banderwagon]] genPoint.setGenerator() A.sum(genPoint, genPoint) # A = g+g = 2g @@ -377,7 +377,7 @@ suite "Banderwagon Elements Mapping": proc testMapToField() = const expected_field_element = "0x038ae85a1376b72642f6694eb4238e3f1348253498e2bf4daec9e77024ae8b07" - var point {.noInit.} : ECP_TwEdwards_Aff[Fp[Banderwagon]] + var point {.noInit.} : EC_TwEdw_Aff[Fp[Banderwagon]] var element: Fr[Banderwagon] var arr: array[32, byte] discard arr.parseHex("0x524996a95838712c4580220bb3de453d76cffd7f732f89914d4417bc8e99b513") @@ -403,14 +403,14 @@ suite "Batch Operations on Banderwagon": ## we try to achive this test "BatchAffine and fromAffine Consistency": proc testbatch(n: static int) = - var g, temp {.noInit.}: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var g, temp {.noInit.}: EC_TwEdw_Prj[Fp[Banderwagon]] g.setGenerator() # setting the generator point - var aff{.noInit.}: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var aff{.noInit.}: EC_TwEdw_Aff[Fp[Banderwagon]] aff.setGenerator() - var points_prj: array[n, ECP_TwEdwards_Prj[Fp[Banderwagon]]] - var points_aff: array[n, ECP_TwEdwards_Aff[Fp[Banderwagon]]] + var points_prj: array[n, EC_TwEdw_Prj[Fp[Banderwagon]]] + var points_aff: array[n, EC_TwEdw_Aff[Fp[Banderwagon]]] for i in 0 ..< n: points_prj[i] = g @@ -434,7 +434,7 @@ suite "Batch Operations on Banderwagon": ## we try to achive this test "Testing Batch Map to Base Field": proc testBatchMapToBaseField() = - var A, B, g: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var A, B, g: EC_TwEdw_Prj[Fp[Banderwagon]] g.setGenerator() A.sum(g, g) @@ -447,7 +447,7 @@ suite "Batch Operations on Banderwagon": var ARes, BRes: Fr[Banderwagon] var scalars: array[2, Fr[Banderwagon]] = [ARes, BRes] - var fps: array[2, ECP_TwEdwards_Prj[Fp[Banderwagon]]] = [A, B] + var fps: array[2, EC_TwEdw_Prj[Fp[Banderwagon]]] = [A, B] doAssert scalars.batchMapToScalarField(fps), "Batch Map to Scalar Failed" doAssert (expected_a == scalars[0]).bool(), "expected scalar for point `A` is incorrect" @@ -460,8 +460,8 @@ suite "Batch Operations on Banderwagon": proc testBatchSerialize(len: static int) = # First the point is set to generator P # then with each iteration 2P, 4P, . . . doubling - var points: array[len, ECP_TwEdwards_Prj[Fp[Banderwagon]]] - var point {.noInit.}: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var points: array[len, EC_TwEdw_Prj[Fp[Banderwagon]]] + var point {.noInit.}: EC_TwEdw_Prj[Fp[Banderwagon]] point.setGenerator() for i in 0 ..< len: @@ -482,8 +482,8 @@ suite "Batch Operations on Banderwagon": ## Check batch Uncompressed encoding test "Batch Uncompressed Point Serialization": proc testBatchUncompressedSerialization() = - var points: array[10, ECP_TwEdwards_Prj[Fp[Banderwagon]]] - var point, point_regen {.noInit.}: ECP_TwEdwards_Prj[Fp[Banderwagon]] + var points: array[10, EC_TwEdw_Prj[Fp[Banderwagon]]] + var point, point_regen {.noInit.}: EC_TwEdw_Prj[Fp[Banderwagon]] point.setGenerator() for i in 0 ..< 10: @@ -495,7 +495,7 @@ suite "Batch Operations on Banderwagon": doAssert status == cttCodecEcc_Success, "Uncompressed Serialization Failed" for i in 0 ..< 10: - var p_regen: ECP_TwEdwards_Aff[Fp[Banderwagon]] + var p_regen: EC_TwEdw_Aff[Fp[Banderwagon]] let status2 = p_regen.deserializeUncompressed(arr[i]) point_regen.fromAffine(p_regen) doAssert status2 == cttCodecEcc_Success, "Uncompressed Deserialization Failed" diff --git a/tests/t_hash_to_curve.nim b/tests/t_hash_to_curve.nim index afbecce04..edf6b917e 100644 --- a/tests/t_hash_to_curve.nim +++ b/tests/t_hash_to_curve.nim @@ -31,7 +31,7 @@ type MapDesc = object name: string - HashToCurveTest[EC: ECP_ShortW_Aff] = object + HashToCurveTest[EC: EC_ShortW_Aff] = object L: string Z: string ciphersuite: string @@ -45,7 +45,7 @@ type randomOracle: bool vectors: seq[TestVector[EC]] - TestVector*[EC: ECP_ShortW_Aff] = object + TestVector*[EC: EC_ShortW_Aff] = object P: EC Q0, Q1: EC msg: string @@ -65,21 +65,21 @@ const TestVectorsDir* = currentSourcePath.rsplit(DirSep, 1)[0] / "protocol_hash_to_curve" -proc parseHook*(src: string, pos: var int, value: var ECP_ShortW_Aff) = +proc parseHook*(src: string, pos: var int, value: var EC_ShortW_Aff) = # Note when nim-serialization was used: - # When ECP_ShortW_Aff[Fp[Foo], G1] - # and ECP_ShortW_Aff[Fp[Foo], G2] + # When EC_ShortW_Aff[Fp[Foo], G1] + # and EC_ShortW_Aff[Fp[Foo], G2] # are generated in the same file (i.e. twists and base curve are both on Fp) # this creates bad codegen, in the C code, the `value`parameter gets the wrong type # TODO: upstream - when ECP_ShortW_Aff.F is Fp: + when EC_ShortW_Aff.F is Fp: var P: EC_G1_hex parseHook(src, pos, P) let ok = value.fromHex(P.x, P.y) doAssert ok, "\nDeserialization error on G1 for\n" & " P.x: " & P.x & "\n" & " P.y: " & P.x & "\n" - elif ECP_ShortW_Aff.F is Fp2: + elif EC_ShortW_Aff.F is Fp2: var P: EC_G2_hex parseHook(src, pos, P) let Px = P.x.split(',') @@ -111,9 +111,9 @@ proc run_hash_to_curve_test( const G1_or_G2 = "G1" else: const G1_or_G2 = "G2" - let vec = loadVectors(HashToCurveTest[ECP_ShortW_Aff[EC.F, EC.G]], filename) + let vec = loadVectors(HashToCurveTest[EC_ShortW_Aff[EC.F, EC.G]], filename) - let testSuiteDesc = "Hash to Curve " & $EC.F.C & " " & G1_or_G2 & " - official specs " & spec_version & " test vectors" + let testSuiteDesc = "Hash to Curve " & $EC.F.Name & " " & G1_or_G2 & " - official specs " & spec_version & " test vectors" suite testSuiteDesc & " [" & $WordBitWidth & "-bit words]": @@ -146,9 +146,9 @@ proc run_hash_to_curve_svdw_test( const G1_or_G2 = "G1" else: const G1_or_G2 = "G2" - let vec = loadVectors(HashToCurveTest[ECP_ShortW_Aff[EC.F, EC.G]], filename) + let vec = loadVectors(HashToCurveTest[EC_ShortW_Aff[EC.F, EC.G]], filename) - let testSuiteDesc = "Hash to Curve " & $EC.F.C & " " & G1_or_G2 & " - official specs " & spec_version & " test vectors" + let testSuiteDesc = "Hash to Curve " & $EC.F.Name & " " & G1_or_G2 & " - official specs " & spec_version & " test vectors" suite testSuiteDesc & " [" & $WordBitWidth & "-bit words]": @@ -177,13 +177,13 @@ echo "Hash-to-curve" & '\n' # Hash-to-curve v8 to latest # https://github.com/cfrg/draft-irtf-cfrg-hash-to-curve/blob/draft-irtf-cfrg-hash-to-curve-10/poc/vectors/BLS12381G2_XMD:SHA-256_SSWU_RO_.json run_hash_to_curve_test( - ECP_ShortW_Prj[Fp[BLS12_381], G1], + EC_ShortW_Prj[Fp[BLS12_381], G1], "v8", "tv_h2c_v8_BLS12_381_hash_to_G1_SHA256_SSWU_RO.json" ) run_hash_to_curve_test( - ECP_ShortW_Prj[Fp2[BLS12_381], G2], + EC_ShortW_Prj[Fp2[BLS12_381], G2], "v8", "tv_h2c_v8_BLS12_381_hash_to_G2_SHA256_SSWU_RO.json" ) @@ -191,26 +191,26 @@ run_hash_to_curve_test( # Hash-to-curve v7 (different domain separation tag) # https://github.com/cfrg/draft-irtf-cfrg-hash-to-curve/blob/draft-irtf-cfrg-hash-to-curve-07/poc/vectors/BLS12381G2_XMD:SHA-256_SSWU_RO_.json run_hash_to_curve_test( - ECP_ShortW_Prj[Fp[BLS12_381], G1], + EC_ShortW_Prj[Fp[BLS12_381], G1], "v7", "tv_h2c_v7_BLS12_381_hash_to_G1_SHA256_SSWU_RO.json" ) run_hash_to_curve_test( - ECP_ShortW_Prj[Fp2[BLS12_381], G2], + EC_ShortW_Prj[Fp2[BLS12_381], G2], "v7", "tv_h2c_v7_BLS12_381_hash_to_G2_SHA256_SSWU_RO.json" ) # With the slower universal SVDW mapping instead of SSWU run_hash_to_curve_svdw_test( - ECP_ShortW_Jac[Fp[BLS12_381], G1], + EC_ShortW_Jac[Fp[BLS12_381], G1], "v7 (SVDW)", "tv_h2c_v7_BLS12_381_hash_to_G1_SHA256_SVDW_RO.json" ) run_hash_to_curve_svdw_test( - ECP_ShortW_Jac[Fp2[BLS12_381], G2], + EC_ShortW_Jac[Fp2[BLS12_381], G2], "v7 (SVDW)", "tv_h2c_v7_BLS12_381_hash_to_G2_SHA256_SVDW_RO.json" ) diff --git a/tests/t_hash_to_curve_random.nim b/tests/t_hash_to_curve_random.nim index b79d2d244..6a3a1dad7 100644 --- a/tests/t_hash_to_curve_random.nim +++ b/tests/t_hash_to_curve_random.nim @@ -29,7 +29,7 @@ rng.seed(seed) echo "\n------------------------------------------------------\n" echo "Hash-to-curve (randomized) xoshiro512** seed: ", seed -proc testH2C_consistency[EC: ECP_ShortW](curve: typedesc[EC]) = +proc testH2C_consistency[EC: EC_ShortW](curve: typedesc[EC]) = var P{.noInit.}: EC let msg = rng.random_byte_seq(32) sha256.hashToCurve( @@ -46,16 +46,16 @@ proc testH2C_consistency[EC: ECP_ShortW](curve: typedesc[EC]) = suite "Hash-to-curve produces points on curve and in correct subgroup": test "BLS12-381 G1": for i in 0 ..< Iters: - testH2C_consistency(ECP_ShortW_Aff[Fp[BLS12_381], G1]) + testH2C_consistency(EC_ShortW_Aff[Fp[BLS12_381], G1]) test "BLS12-381 G2": for i in 0 ..< Iters: - testH2C_consistency(ECP_ShortW_Aff[Fp2[BLS12_381], G2]) + testH2C_consistency(EC_ShortW_Aff[Fp2[BLS12_381], G2]) test "BN254_Snarks G1": for i in 0 ..< Iters: - testH2C_consistency(ECP_ShortW_Aff[Fp[BN254_Snarks], G1]) + testH2C_consistency(EC_ShortW_Aff[Fp[BN254_Snarks], G1]) test "BN254_Snarks G2": for i in 0 ..< Iters: - testH2C_consistency(ECP_ShortW_Aff[Fp2[BN254_Snarks], G2]) + testH2C_consistency(EC_ShortW_Aff[Fp2[BN254_Snarks], G2]) proc testH2C_guidovranken_fuzz_failure_2() = # From Guido Vranken differential fuzzing @@ -75,10 +75,10 @@ proc testH2C_guidovranken_fuzz_failure_2() = 0xf1, 0xaf, 0xa5, 0x06, 0x78, 0x80, 0xde, 0xf0, 0x0d, 0xdf] - var r{.noInit}: ECP_ShortW_Jac[Fp[BLS12_381], G1] + var r{.noInit}: EC_ShortW_Jac[Fp[BLS12_381], G1] sha256.hashToCurve(128, r, aug, msg, dst) - let expected = ECP_ShortW_Jac[Fp[BLS12_381], G1].fromHex( + let expected = EC_ShortW_Jac[Fp[BLS12_381], G1].fromHex( x = "0x48f2bbee30aa236feaa7fb924d8a3de3090ff160f9972a8afda302bd248248527dcc59ce195cd5f5a1488417cfc64cc", y = "0xe91b0a3cdea4981741791c8e9b4287d2f693c6626d8e4408ecaaa473e6ff2f691f5f23f8b7b46bdf3560e7cca67e5bc" )