Skip to content

refactor: improve c7 circuit computation [skip-line-limit]#1315

Merged
cedoor merged 3 commits into
mainfrom
ref/circuits-comp
Feb 13, 2026
Merged

refactor: improve c7 circuit computation [skip-line-limit]#1315
cedoor merged 3 commits into
mainfrom
ref/circuits-comp

Conversation

@0xjei

@0xjei 0xjei commented Feb 13, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

Release Notes

  • New Features

    • JSON inputs now accept numeric coefficients (not just strings) when values fit in standard integer ranges.
  • Bug Fixes

    • Updated benchmark metrics and system specifications for improved accuracy.
    • Optimized polynomial computation paths for enhanced circuit performance.
  • Refactor

    • Simplified configuration naming conventions for improved clarity.
    • Restructured internal polynomial handling using optimized data structures.
    • Cleaned up benchmark automation to remove intermediate data files.

@0xjei 0xjei added this to the PHASE 2: PROVE & VERIFY milestone Feb 13, 2026
@0xjei 0xjei self-assigned this Feb 13, 2026
@vercel

vercel Bot commented Feb 13, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
crisp Ready Ready Preview, Comment Feb 13, 2026 3:08pm
enclave-docs Ready Ready Preview, Comment Feb 13, 2026 3:08pm

Request Review

@coderabbitai

coderabbitai Bot commented Feb 13, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR refactors circuit configurations by systematically renaming DKG share encryption constants, introducing new modulus parameters, removing ZKP modulus-based reduction operations, refactoring data structures from raw BigInt vectors to polynomial abstractions, and updating benchmark reports with new execution metrics.

Changes

Cohort / File(s) Summary
Benchmark Reports and Scripts
circuits/benchmarks/results_insecure/report.md, circuits/benchmarks/results_secure/report.md, circuits/benchmarks/scripts/run_benchmarks.sh
Updated benchmark report metadata (timestamps, git branch/commit), reformatted timing and size metrics tables across all circuits, updated hardware specs (CPU cores 12→14, RAM 24GB→48GB), and added cleanup of raw JSON folder after report generation.
DKG Configuration Renaming (Insecure & Secure)
circuits/lib/src/configs/insecure/dkg.nr, circuits/lib/src/configs/secure/dkg.nr
Renamed DKG_SHARE_ENCRYPTION_* constants to SHARE_ENCRYPTION_*, introduced PLAINTEXT_MODULUS and Q_MOD_T globals, updated ShareEncryptionConfigs constructor signatures to use new parameter names and ordering.
Threshold Configuration Updates
circuits/lib/src/configs/insecure/threshold.nr, circuits/lib/src/configs/secure/threshold.nr
Replaced USER_DATA_ENCRYPTION_Q_MOD_T_MOD_P with new Q_MOD_T constant, updated UserDataEncryptionConfigs constructor to use simplified modulus parameter.
Core Threshold User Data Encryption
circuits/lib/src/core/threshold/user_data_encryption.nr
Renamed struct field from q_mod_t_mod_p to q_mod_t in Configs struct, updated constructor signature accordingly.
DKG Share Encryption Computation
crates/zk-helpers/src/circuits/dkg/share_encryption/computation.rs, crates/zk-helpers/src/circuits/dkg/share_encryption/codegen.rs
Removed per-modulus CRT reduction calls, eliminated ZKP modulus-based uniform reductions, updated codegen to generate PLAINTEXT_MODULUS and Q_MOD_T instead of T and Q_MOD_T.
DKG PK and Share Computation
crates/zk-helpers/src/circuits/dkg/pk/computation.rs, crates/zk-helpers/src/circuits/dkg/share_computation/computation.rs
Removed runtime reduction steps using ZKP modulus, eliminated get_zkp_modulus imports and reduce_uniform calls, now directly converts polynomials to CRT-centered form.
DKG Share Decryption
crates/zk-helpers/src/circuits/dkg/share_decryption/computation.rs
Updated documentation for JSON input representation to clarify numeric/string coefficient handling; no behavioral changes to serialization logic.
Threshold Decrypted Shares Aggregation
crates/zk-helpers/src/circuits/threshold/decrypted_shares_aggregation/computation.rs, crates/zk-helpers/src/circuits/threshold/decrypted_shares_aggregation/sample.rs
Refactored from Vec<Vec<Vec>> to CrtPolynomial/Polynomial-based structures, added truncation utilities for coefficient limiting, updated JSON serialization to use crt_polynomial_to_toml_json and polynomial_to_toml_json, adjusted test assertions to use .coefficients() accessor.
Threshold PK and Share Handling
crates/zk-helpers/src/circuits/threshold/pk_aggregation/computation.rs, crates/zk-helpers/src/circuits/threshold/pk_generation/computation.rs, crates/zk-helpers/src/circuits/threshold/share_decryption/computation.rs
Removed all uniform reductions using ZKP modulus (reduce_uniform calls and get_zkp_modulus imports), retained standard per-moduli reductions; simplified reduction flow for share decryption per-core computations.
Threshold User Data Encryption
crates/zk-helpers/src/circuits/threshold/user_data_encryption/codegen.rs, crates/zk-helpers/src/circuits/threshold/user_data_encryption/computation.rs, crates/zk-helpers/src/circuits/threshold/user_data_encryption/utils.rs
Updated codegen to generate Q_MOD_T instead of Q_MOD_T_MOD_P, refactored computation to use q_mod_t instead of q_mod_t_mod_p, removed unnecessary CRT reduction steps and get_zkp_modulus usage in utils.
JSON and Utilities
crates/zk-helpers/src/utils.rs, crates/zk-prover/src/circuits/utils.rs
Introduced bigint_to_json_value helper to serialize BigInt coefficients as numbers when fitting in i64, otherwise as strings; updated poly_coefficients_to_toml_json and crt_polynomial_to_toml_json accordingly; modified coefficient parsing to accept both strings and numeric literals.
Circuit Main Files and Examples
circuits/bin/dkg/share_encryption/src/main.nr, examples/CRISP/circuits/src/main.nr, examples/CRISP/crates/zk-inputs-wasm/src/lib.rs, examples/CRISP/crates/zk-inputs/src/ciphertext_addition.rs
Updated imports to use SHARE_ENCRYPTION_* constants instead of DKG_SHARE_ENCRYPTION_*, added Q_MOD_T usage and removed USER_DATA_ENCRYPTION_Q_MOD_T_MOD_P, added js_value_to_bigint_string helper for flexible input handling, removed ZKP modulus reduction in ciphertext addition.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • cedoor

Poem

🐰 Constants renamed with flair so bright,
ZKP reductions dimmed their light,
BigInt vectors turned to Polynomial grace,
Benchmarks refreshed at a rapid pace—
This refactor hops to a better place! 🌿

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main refactoring effort: improving circuit computation by removing redundant modulus reduction operations and simplifying constant naming conventions across the codebase.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into main

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ref/circuits-comp

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cedoor cedoor left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utACK

@cedoor cedoor enabled auto-merge (squash) February 13, 2026 15:13

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
crates/zk-helpers/src/circuits/dkg/share_computation/computation.rs (1)

83-98: ⚠️ Potential issue | 🟡 Minor

Stale doc comments reference ZKP modulus reduction that was removed.

Lines 84–86 state coefficients are "reduced to the ZKP field modulus for serialization," and lines 90/92 reference [0, zkp_modulus). The ZKP modulus reduction has been removed in this refactor, so these comments are now inaccurate. Similarly, the module-level doc (lines 10–11) mentions normalization "to the ZKP field modulus."

Consider updating the doc comments to reflect that values are now in [0, q_j) per modulus without further ZKP reduction.

crates/zk-helpers/src/circuits/dkg/share_encryption/computation.rs (1)

529-546: ⚠️ Potential issue | 🟠 Major

e0_mod_q is not reduced by ZKP modulus, unlike in user_data_encryption.

In user_data_encryption/computation.rs (lines 544-546), e0_mod_q.reduce(&zkp_modulus) is explicitly called before storing e0 in the output, with a comment explaining the reduction is necessary so coefficients fit in the proof system field. Here, e0_mod_q is stored directly (line 540) with centered coefficients that can be as large as ±Q/2 (~2^100+ for insecure, ~2^200+ for secure). Add the missing reduce() call to match user_data_encryption or clarify why share_encryption intentionally omits it.

crates/zk-prover/src/circuits/utils.rs (1)

49-64: ⚠️ Potential issue | 🔴 Critical

Negative coefficients serialized as JSON numbers will fail to parse.

FieldElement::try_from_str in Noir v1.0.0-beta.15 does not support negative decimal strings. When bigint_to_json_value emits a negative coefficient as a JSON number (e.g., -5 for values fitting in i64), the parsing code converts it to the string "-5" and passes it to try_from_str, which returns None since it only recognizes hex strings (0x...) or unsigned decimals. This causes any negative coefficient in the range [-i64::MAX, -1] to fail with a SerializationError.

Fix: Either parse the magnitude and negate in field arithmetic (strip the -, parse, then negate), or emit negative coefficients as strings from bigint_to_json_value to bypass the as_i64() path entirely.

🧹 Nitpick comments (6)
examples/CRISP/crates/zk-inputs/src/ciphertext_addition.rs (1)

74-83: Remove now-unnecessary mut qualifiers.

With the ZKP modulus reduction block gone, prev_ct0, prev_ct1, sum_ct0, sum_ct1, r0, and r1 are never mutated. The compiler will emit unused_mut warnings.

♻️ Suggested diff
-        let [mut prev_ct0, mut prev_ct1, mut ct0, mut ct1, mut sum_ct0, mut sum_ct1] =
+        let [prev_ct0, prev_ct1, ct0, ct1, sum_ct0, sum_ct1] =
             crt_polynomials;

         ...
-        let mut r0 = Self::compute_quotient(&sum_ct0, &ct0, &prev_ct0, &moduli)
+        let r0 = Self::compute_quotient(&sum_ct0, &ct0, &prev_ct0, &moduli)
             .with_context(|| "Failed to compute r0 quotient")?;
-        let mut r1 = Self::compute_quotient(&sum_ct1, &ct1, &prev_ct1, &moduli)
+        let r1 = Self::compute_quotient(&sum_ct1, &ct1, &prev_ct1, &moduli)
             .with_context(|| "Failed to compute r1 quotient")?;
examples/CRISP/crates/zk-inputs-wasm/src/lib.rs (1)

160-196: Consider extracting the repeated parsing into a helper.

The ct0is and ct1is parsing blocks (lines 160-177 and 179-196) are nearly identical. A small helper like fn parse_crt_arrays(input: &JsValue, name: &str) -> Result<Vec<Vec<BigInt>>, JsValue> would reduce duplication and ensure both paths stay in sync.

♻️ Sketch of extracted helper
fn parse_crt_arrays(input: &JsValue, name: &str) -> Result<Vec<Vec<BigInt>>, JsValue> {
    let outer = js_sys::Array::from(input);
    let mut result: Vec<Vec<BigInt>> = Vec::new();
    for i in 0..outer.length() {
        let inner = outer
            .get(i)
            .dyn_into::<js_sys::Array>()
            .map_err(|_| JsValue::from_str(&format!("Expected array of arrays for {}", name)))?;
        let mut coefficients: Vec<BigInt> = Vec::new();
        for j in 0..inner.length() {
            let s = js_value_to_bigint_string(inner.get(j))
                .ok_or_else(|| JsValue::from_str("Expected string, number, or BigInt in inner array"))?;
            let bigint = s
                .parse::<BigInt>()
                .map_err(|e| JsValue::from_str(&format!("Failed to parse BigInt: {}", e)))?;
            coefficients.push(bigint);
        }
        result.push(coefficients);
    }
    Ok(result)
}
circuits/benchmarks/scripts/run_benchmarks.sh (1)

216-222: Raw JSON deletion is unconditional — consider gating it behind --clean.

The raw benchmark data is removed after every run regardless of flags. If someone needs to debug or re-process raw results, they'd have to re-run the full benchmark. Since the script already has a --clean flag for artifact cleanup, it would be more consistent to gate this removal behind the same flag (or a separate --keep-raw opt-out).

That said, if the intent is that raw data is strictly ephemeral and only the Markdown report matters, this is fine as-is.

crates/zk-helpers/src/circuits/threshold/user_data_encryption/computation.rs (2)

137-163: Minor inconsistency: q_mod_t is not reduced by ZKP modulus here, but is in share_encryption.

In this file (line 147), q_mod_t is stored as center(q_mod_t_uint, t) without the ZKP modulus reduction. In crates/zk-helpers/src/circuits/dkg/share_encryption/computation.rs (lines 159–169), the equivalent field still applies reduce(&q_mod_t, &p) before storing. Both produce the same value in practice since |q_mod_t| ≤ t/2 which is tiny relative to the ZKP modulus, but it's worth aligning the two for consistency.


634-646: Test doesn't assert q_mod_t roundtrip.

The JSON roundtrip test checks n, l, moduli, bits, and bounds but omits the new q_mod_t field. Consider adding an assertion for completeness.

Suggested addition
         assert_eq!(decoded.n, constants.n);
         assert_eq!(decoded.l, constants.l);
         assert_eq!(decoded.moduli, constants.moduli);
+        assert_eq!(decoded.q_mod_t, constants.q_mod_t);
         assert_eq!(decoded.bits, constants.bits);
         assert_eq!(decoded.bounds, constants.bounds);
circuits/benchmarks/results_secure/report.md (1)

69-70: Minor: Quoted numeric values in detail tables but not in summary tables.

Values like "2949141" and "11539441" have surrounding quotes in the Circuit Details section, while the summary tables use unquoted numbers. This is likely a benchmark script formatting artifact — consider normalizing the output in the script for consistency.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants