Skip to content

refactor: general zk-helpers refactoring#1283

Merged
cedoor merged 3 commits into
mainfrom
refactoring/zk-helpers
Feb 10, 2026
Merged

refactor: general zk-helpers refactoring#1283
cedoor merged 3 commits into
mainfrom
refactoring/zk-helpers

Conversation

@cedoor

@cedoor cedoor commented Feb 10, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Chores
    • Increased committee honest-party count from 3 to 5.
  • Bug Fixes / Reliability
    • Sample generation now surfaces and propagates errors instead of panicking, improving error reporting across circuit tooling and CLI flows.
  • New Features
    • Exposed a utility to determine maximum modulus for cryptographic parameter calculations.
  • Style / Naming
    • Renamed a share-encryption circuit identifier for clearer naming.

@vercel

vercel Bot commented Feb 10, 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 10, 2026 3:49pm
enclave-docs Ready Ready Preview, Comment Feb 10, 2026 3:49pm

Request Review

@coderabbitai

coderabbitai Bot commented Feb 10, 2026

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@cedoor has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 41 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📝 Walkthrough

Walkthrough

Multiple crates updated to propagate fallible sample generation: many generate_sample functions now return Result<..., CircuitsErrors> and tests were updated to .unwrap() those results; committee honest-party constant H changed from 3→5; helper API additions and a circuit renaming were also applied.

Changes

Cohort / File(s) Summary
Committee Configuration
circuits/lib/src/configs/committee/small.nr, crates/zk-helpers/src/ciphernodes_committee.rs
Updated Small committee honest-party count H from 3 to 5 (including examples/comments).
Sample generation API changes
crates/zk-helpers/src/circuits/dkg/pk/sample.rs, crates/zk-helpers/src/circuits/dkg/share_computation/sample.rs, crates/zk-helpers/src/circuits/dkg/share_encryption/sample.rs, crates/zk-helpers/src/circuits/threshold/decrypted_shares_aggregation/sample.rs, crates/zk-helpers/src/circuits/threshold/user_data_encryption/sample.rs
Changed multiple generate_sample functions to return Result<..., CircuitsErrors> and replaced panics/unwraps with error mapping/propagation. Tests updated to handle (or .unwrap()) the new Results.
Tests — unwrap / call sites
crates/zk-helpers/src/.../codegen.rs, crates/zk-helpers/src/.../computation.rs, crates/zk-prover/tests/local_e2e_tests.rs, crates/zk-helpers/src/bin/zk_cli.rs
Updated many test and CLI call sites to propagate or explicitly .unwrap() on the new Result-returning generate_sample calls; zk_cli.rs also propagates errors from generate_sample via ? in several paths.
Computation refactors & helpers
crates/zk-helpers/src/circuits/dkg/pk/computation.rs, crates/zk-helpers/src/circuits/dkg/share_encryption/computation.rs, crates/zk-helpers/src/utils.rs
Minor refactors: introduced local l, replaced inline max-modulus logic with new public helper compute_max_modulus(moduli: &[u64]) -> u64, and adjusted usages to call the helper.
Circuit metadata rename
crates/zk-helpers/src/circuits/dkg/share_encryption/circuit.rs
Renamed public circuit constants: NAME "dkg-share-encryption""share-encryption" and PREFIX "DKG_SHARE_ENCRYPTION""SHARE_ENCRYPTION".
Codegen/test updates
crates/zk-helpers/src/circuits/dkg/*/codegen.rs, crates/zk-helpers/src/circuits/threshold/*/codegen.rs
Adjusted tests to reflect new generate_sample return types, adding .unwrap() where needed and minor formatting tweaks around calls.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • 0xjei

Poem

"🐰 Hop, I hopped through code today,
H grew from three to five — hooray!
Samples now may fail or float,
So I bring Results in my tote.
Carrots, tests, and constants sing; code ready for spring!"

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The PR title 'refactor: general zk-helpers refactoring' is vague and generic, using non-descriptive terms that don't convey specific information about the changes. Use a more specific title that highlights the main change, such as 'refactor: update honest parties count and improve error handling in zk-helpers' or 'refactor: increase committee h to 5 and propagate sampling errors'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactoring/zk-helpers

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.

@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.

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (2)
crates/zk-helpers/src/circuits/dkg/share_encryption/sample.rs (1)

68-81: ⚠️ Potential issue | 🟠 Major

Duplicate .map_err() produces nested, garbled error messages.

There are two chained .map_err() calls on the result of generate_smudging_error. The first (lines 70–75) converts the original error to CircuitsErrors::Sample. The second (lines 76–81) then re-wraps that CircuitsErrors inside another CircuitsErrors::Sample, producing a message like "Failed to generate smudging error: Sample(\"Failed to generate smudging error: ...\")".

Remove the duplicate and use ? directly after the first mapping.

🐛 Proposed fix
             let esi_coeffs = trbfv
                 .generate_smudging_error(num_ciphertexts as usize, lambda as usize, &mut rng)
                 .map_err(|e| {
                     CircuitsErrors::Sample(format!(
                         "Failed to generate smudging error: {:?}",
                         e
                     ))
-                })
-                .map_err(|e| {
-                    CircuitsErrors::Sample(format!(
-                        "Failed to generate smudging error: {:?}",
-                        e
-                    ))
                 })?;
crates/zk-helpers/src/circuits/dkg/share_computation/sample.rs (1)

88-114: ⚠️ Potential issue | 🔴 Critical

SmudgingNoise branch still panics via .unwrap() instead of propagating errors.

The entire purpose of this refactor is to make generate_sample return Result, yet the SmudgingNoise branch uses .unwrap() on four fallible operations (lines 97, 98, 104, 112). This means the function will panic instead of returning Err if any of these fail — completely defeating the error-propagation goal. The SecretKey branch (lines 52–86) correctly uses map_err(...)? throughout.

🐛 Proposed fix — propagate errors consistently
             DkgInputType::SmudgingNoise => {
                 let esi_coeffs = trbfv
                     .generate_smudging_error(committee.n as usize, sd.lambda as usize, &mut rng)
                     .map_err(|e| {
                         CircuitsErrors::Sample(format!(
                             "Failed to generate smudging error: {:?}",
                             e
                         ))
-                    })
-                    .unwrap();
-                let esi_poly = share_manager.bigints_to_poly(&esi_coeffs).unwrap();
+                    })?;
+                let esi_poly = share_manager.bigints_to_poly(&esi_coeffs).map_err(|e| {
+                    CircuitsErrors::Sample(format!("Failed to convert error to poly: {:?}", e))
+                })?;
                 let esi_sss_u64 = share_manager
                     .generate_secret_shares_from_poly(esi_poly.clone(), rng)
                     .map_err(|e| {
                         CircuitsErrors::Sample(format!("Failed to generate error shares: {:?}", e))
-                    })
-                    .unwrap();
+                    })?;
                 let secret_sss: SecretShares = esi_sss_u64
                     .into_iter()
                     .map(|arr| arr.mapv(BigInt::from))
                     .collect();
 
                 let mut secret_crt =
                     CrtPolynomial::from_mod_q_polynomial(&esi_coeffs, threshold_params.moduli());
-                secret_crt.center(threshold_params.moduli()).unwrap();
+                secret_crt.center(threshold_params.moduli()).map_err(|e| {
+                    CircuitsErrors::Sample(format!("Failed to center secret CRT: {:?}", e))
+                })?;
 
                 (secret_crt, secret_sss)
             }
🤖 Fix all issues with AI agents
In `@crates/zk-helpers/src/circuits/dkg/share_encryption/sample.rs`:
- Around line 85-92: The call to
share_manager.generate_secret_shares_from_poly(esi_poly.clone(), &mut
rng.clone()) is mapped twice with .map_err(), which re-wraps an
already-converted error; remove the duplicate mapping so the error is converted
to CircuitsErrors::Sample only once. Locate the expression assigning esi_sss_u64
and keep a single .map_err(|e| CircuitsErrors::Sample(format!("Failed to
generate error shares: {:?}", e))) (or adjust to propagate the original error
type if intended), ensuring generate_secret_shares_from_poly is only followed by
one map_err transformation.
🧹 Nitpick comments (3)
crates/zk-helpers/src/utils.rs (1)

176-178: unwrap() will panic on an empty moduli slice.

Since compute_max_modulus is now a pub API, callers outside compute_modulus_bit could pass an empty slice. Consider returning an Option<u64> or documenting the panic precondition explicitly (e.g., # Panics).

Option A: Add a `# Panics` doc section
 /// Computes the maximum modulus from a vector of moduli.
 ///
 /// # Arguments
 /// * `moduli` - Vector of moduli
 ///
 /// # Returns
 /// The maximum modulus
+///
+/// # Panics
+/// Panics if `moduli` is empty.
 pub fn compute_max_modulus(moduli: &[u64]) -> u64 {
     moduli.iter().copied().max().unwrap()
 }
crates/zk-helpers/src/circuits/threshold/decrypted_shares_aggregation/sample.rs (1)

148-155: Redundant double map_err — inner already maps to CircuitsErrors.

The inner map_err (Line 148) already converts the ShapeError into CircuitsErrors::Sample. The outer map_err (Line 153) then wraps the CircuitsErrors Debug output into another CircuitsErrors::Sample, producing nested messages like "Failed to collect sk_sss_collected: Sample(\"sk_sss_collected shape: ...\")". The outer map_err can be removed since collect::<Result<Vec<_>, _>>()? will propagate the inner error directly.

Suggested simplification
                 .collect::<Result<Vec<_>, _>>()
-                .map_err(|e| {
-                    CircuitsErrors::Sample(format!("Failed to collect sk_sss_collected: {:?}", e))
-                })?;
+                ?;

Same applies to the es_sss_collected block at Lines 167–174.

crates/zk-helpers/src/bin/zk_cli.rs (1)

328-332: Inconsistent use of committee variable.

Line 262 already defines let committee = CiphernodesCommitteeSize::Small.values();, but this branch re-creates the same value inline. All other branches use the committee local. Consider using it here too for consistency.

♻️ Suggested fix
             name if name == <DecryptedSharesAggregationCircuit as Circuit>::NAME => {
                 let sample = DecryptedSharesAggregationCircuitInput::generate_sample(
                     preset,
-                    CiphernodesCommitteeSize::Small.values(),
+                    committee,
                 )?;

Comment thread crates/zk-helpers/src/circuits/dkg/share_encryption/sample.rs
cedoor and others added 3 commits February 10, 2026 16:47
- Remove redundant .map_err() on generate_secret_shares_from_poly result
- Error now converted to CircuitsErrors::Sample only once

Co-authored-by: Cursor <cursoragent@cursor.com>

@0xjei 0xjei 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

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