From f38652153ec155d9342083ad1fce0399c2ddb678 Mon Sep 17 00:00:00 2001 From: Zara Date: Thu, 19 Nov 2026 21:45:07 +0000 Subject: [PATCH 01/16] refactor(circuits)!: prove C4 one CRT limb at a time with unchanged commitments At 28 honest parties C4 is a 2^24 circuit, over a node's 13 GiB per-job budget. Its openings and sums are independent per limb, and the aggregate commitment C6 reads is one SAFE sponge over the normalized limbs in order, so prove each limb separately and carry that sponge between them. The last limb squeezes the unchunked C4 commitment; C6 is unchanged. - aggregate_limb holds C4's per-limb statement (checked openings, sum, reverse and center); the unchunked execute and the limb circuits share it. - share_decryption_limb_0/1/2 each start the aggregate sponge at their limb's fixed position, so every absorb position is static. The final share_decryption circuit verifies the three limbs, links them from the fresh sponge and returns the aggregate commitment, then the limb key tree. - c4ab_fold and the VK tree anchor the key tree; peers check it when verifying a C4. The C4 output layout names the trailing key tree. - The limb circuits are published in the default variant only, as the C2 chunk circuits are. - The circuit identity lock gains rows for the limb circuit names, appended after the existing variants. --- circuits/README.md | 11 +- circuits/benchmarks/config.json | 3 + circuits/bin/dkg/Nargo.toml | 3 + circuits/bin/dkg/share_decryption/Nargo.toml | 1 + circuits/bin/dkg/share_decryption/README.md | 15 +- circuits/bin/dkg/share_decryption/src/main.nr | 43 +++- .../dkg/share_decryption_limb_0/Nargo.toml | 7 + .../dkg/share_decryption_limb_0/src/main.nr | 31 +++ .../dkg/share_decryption_limb_1/Nargo.toml | 7 + .../dkg/share_decryption_limb_1/src/main.nr | 31 +++ .../dkg/share_decryption_limb_2/Nargo.toml | 7 + .../dkg/share_decryption_limb_2/src/main.nr | 31 +++ .../c4ab_fold/src/main.nr | 20 +- circuits/lib/src/README.md | 1 + circuits/lib/src/core/dkg/mod.nr | 1 + circuits/lib/src/core/dkg/share_decryption.nr | 138 +++++++----- .../src/core/dkg/share_decryption_chain.nr | 197 ++++++++++++++++++ circuits/lib/src/math/commitments.nr | 7 + .../src/circuit_benchmark/inputs.rs | 51 ++++- .../benchmarks/src/circuit_benchmark/leaf.rs | 26 ++- .../src/circuit_benchmark/selection.rs | 12 +- .../benchmarks/src/circuit_benchmark/tests.rs | 8 +- crates/zk/build/src/artifacts.rs | 24 ++- crates/zk/build/src/tests.rs | 8 +- crates/zk/build/src/vk_tree.rs | 9 +- crates/zk/config/src/circuit.rs | 19 +- crates/zk/config/src/output_layout.rs | 5 +- crates/zk/config/tests/circuit_identity.rs | 27 ++- crates/zk/prover/required-artifacts.json | 9 + .../src/circuits/aggregation/c2_chain.rs | 4 +- .../src/circuits/aggregation/c4_chain.rs | 128 ++++++++++++ .../src/circuits/aggregation/chain_keys.rs | 13 +- .../zk/prover/src/circuits/aggregation/mod.rs | 1 + .../src/circuits/dkg/share_decryption.rs | 59 +++++- .../prover/src/commitment_links/c4a_to_c6.rs | 8 +- .../prover/src/commitment_links/c4b_to_c6.rs | 7 +- crates/zk/prover/src/lib.rs | 1 + crates/zk/prover/src/request_execution.rs | 40 +++- crates/zk/prover/tests/common/helpers.rs | 8 +- crates/zk/prover/tests/local_e2e_tests.rs | 2 +- .../tests/node_fold_correlated_e2e_tests.rs | 2 +- crates/zk/witness/src/commitments.rs | 10 +- crates/zk/witness/src/dkg/mod.rs | 1 + .../witness/src/dkg/share_decryption_chain.rs | 144 +++++++++++++ crates/zk/witness/tests/dkg_samples.rs | 71 +++++++ docs/architecture/proof-statements.md | 21 +- docs/pages/build/noir-circuits.mdx | 25 ++- .../internals/commitment-consistency.mdx | 6 +- 48 files changed, 1144 insertions(+), 159 deletions(-) create mode 100644 circuits/bin/dkg/share_decryption_limb_0/Nargo.toml create mode 100644 circuits/bin/dkg/share_decryption_limb_0/src/main.nr create mode 100644 circuits/bin/dkg/share_decryption_limb_1/Nargo.toml create mode 100644 circuits/bin/dkg/share_decryption_limb_1/src/main.nr create mode 100644 circuits/bin/dkg/share_decryption_limb_2/Nargo.toml create mode 100644 circuits/bin/dkg/share_decryption_limb_2/src/main.nr create mode 100644 circuits/lib/src/core/dkg/share_decryption_chain.nr create mode 100644 crates/zk/prover/src/circuits/aggregation/c4_chain.rs create mode 100644 crates/zk/witness/src/dkg/share_decryption_chain.rs diff --git a/circuits/README.md b/circuits/README.md index 0478260baf..12b4f24a4f 100644 --- a/circuits/README.md +++ b/circuits/README.md @@ -51,6 +51,12 @@ chunks, so its proof is the one peers and `c2ab_fold` consume, and its share com unchunked C2's. Gossip and threshold signing use that final proof. `c2ab_fold` verifies the final C2a and C2b proofs and hashes each one's chunk key tree into its key hash. +**C4** is proven the same way, one CRT limb per proof: `share_decryption` (**C4a**, **C4b**) is the +final circuit over `share_decryption_limb_0`, `_1` and `_2`, which each run C4's statement for one +limb and carry the aggregate commitment sponge between them. Its commitments equal the unchunked +C4's, so C6 is unchanged. `c4ab_fold` verifies the final C4a and C4b proofs and hashes each one's +limb key tree into its key hash. + ### DKG (`bin/dkg/`) | Path | ID | `CircuitName` | Role | @@ -63,7 +69,10 @@ C2a and C2b proofs and hashes each one's chunk key tree into its key hash. | `e_sm_share_computation_chain` | C2b chunk | `ESmShareComputationChain` | A chunk of C2b other than the last; non-ZK | | `e_sm_share_computation_chain_last` | C2b chunk | `ESmShareComputationChainLast` | The last chunk of C2b | | `share_encryption` | C3 | `ShareEncryption` | BFV encryption of shares under recipient keys | -| `share_decryption` | C4 | `DkgShareDecryption` | Decrypt shares; aggregate; commitments for P4 | +| `share_decryption` | C4 | `DkgShareDecryption` | Decrypt shares; aggregate; commitments for P4; verifies the limbs | +| `share_decryption_limb_0` | C4 limb | `DkgShareDecryptionLimb0` | CRT limb 0 of C4; non-ZK | +| `share_decryption_limb_1` | C4 limb | `DkgShareDecryptionLimb1` | CRT limb 1 of C4; non-ZK | +| `share_decryption_limb_2` | C4 limb | `DkgShareDecryptionLimb2` | CRT limb 2 of C4; non-ZK | ### Threshold (`bin/threshold/`) diff --git a/circuits/benchmarks/config.json b/circuits/benchmarks/config.json index 2b3b2e4fe7..a1c6d75b1a 100644 --- a/circuits/benchmarks/config.json +++ b/circuits/benchmarks/config.json @@ -10,6 +10,9 @@ "dkg/e_sm_share_computation_chain_last", "dkg/share_encryption", "dkg/share_decryption", + "dkg/share_decryption_limb_0", + "dkg/share_decryption_limb_1", + "dkg/share_decryption_limb_2", "threshold/user_data_encryption", "threshold/pk_generation", "threshold/pk_aggregation", diff --git a/circuits/bin/dkg/Nargo.toml b/circuits/bin/dkg/Nargo.toml index 075d9663cc..a8710f0bc1 100644 --- a/circuits/bin/dkg/Nargo.toml +++ b/circuits/bin/dkg/Nargo.toml @@ -9,5 +9,8 @@ members = [ "sk_share_computation_chain_last", "e_sm_share_computation_chain", "e_sm_share_computation_chain_last", + "share_decryption_limb_0", + "share_decryption_limb_1", + "share_decryption_limb_2", ] diff --git a/circuits/bin/dkg/share_decryption/Nargo.toml b/circuits/bin/dkg/share_decryption/Nargo.toml index 4f11840222..4ed5da3440 100644 --- a/circuits/bin/dkg/share_decryption/Nargo.toml +++ b/circuits/bin/dkg/share_decryption/Nargo.toml @@ -5,3 +5,4 @@ authors = ["Gnosis Guild / Interfold"] [dependencies] lib = { path = "../../../lib" } +bb_proof_verification = { git = "https://github.com/AztecProtocol/aztec-packages/", tag = "v6.0.0", directory = "barretenberg/noir/bb_proof_verification" } diff --git a/circuits/bin/dkg/share_decryption/README.md b/circuits/bin/dkg/share_decryption/README.md index a492ac2629..843011e7df 100644 --- a/circuits/bin/dkg/share_decryption/README.md +++ b/circuits/bin/dkg/share_decryption/README.md @@ -1,10 +1,13 @@ # `share_decryption` — C4a / C4b Decrypts incoming shares and aggregates them; outputs commitments consumed by **C6** (threshold -decryption). +decryption). It is the final circuit of a limb chain: it verifies the `share_decryption_limb_0`, +`_1` and `_2` proofs, which run C4's statement for one CRT limb each and carry the aggregate +commitment sponge between them. It links the limbs from a fresh sponge and returns the aggregate +commitment, followed by the hash of the limb keys. -| | | -| --------- | --------------------------------------------------------------------------------------- | -| **Core** | [`lib/src/core/dkg/share_decryption.nr`](../../../lib/src/core/dkg/share_decryption.nr) | -| **Index** | [Circuit package index](../../../README.md#circuit-package-index) | -| **Docs** | [Noir Circuits](../../../../docs/pages/build/noir-circuits.mdx) | +| | | +| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Core** | [`lib/src/core/dkg/share_decryption_chain.nr`](../../../lib/src/core/dkg/share_decryption_chain.nr), [`lib/src/core/dkg/share_decryption.nr`](../../../lib/src/core/dkg/share_decryption.nr) | +| **Index** | [Circuit package index](../../../README.md#circuit-package-index) | +| **Docs** | [Noir Circuits](../../../../docs/pages/build/noir-circuits.mdx) | diff --git a/circuits/bin/dkg/share_decryption/src/main.nr b/circuits/bin/dkg/share_decryption/src/main.nr index 76b85484fb..e921b98235 100644 --- a/circuits/bin/dkg/share_decryption/src/main.nr +++ b/circuits/bin/dkg/share_decryption/src/main.nr @@ -4,19 +4,40 @@ // without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. -use lib::configs::default::dkg::{ - L_THRESHOLD, N, QIS_THRESHOLD, SHARE_DECRYPTION_BIT_AGG, SHARE_DECRYPTION_BIT_MSG, -}; +//! C4 over its verified limb chain. Verifies the three limb proofs (each with its own key), links +//! them from the fresh aggregate sponge and returns the aggregate commitment the unchunked C4 +//! returned. See `lib::core::dkg::share_decryption_chain`. +//! +//! Public: `[expected_commitments[H][L], agg_commitment, key_tree]`, where `key_tree` hashes the +//! three limb keys. The first `H * L + 1` fields are the unchunked C4's public inputs. + +use bb_proof_verification::{UltraHonkProof, UltraHonkVerificationKey, verify_honk_proof_non_zk}; +use lib::configs::default::dkg::{L_THRESHOLD, N, SHARE_DECRYPTION_BIT_AGG}; use lib::configs::default::H; -use lib::core::dkg::share_decryption::ShareDecryption; -use lib::math::polynomial::Polynomial; +use lib::core::dkg::share_decryption_chain::check_limb_chain; +use lib::math::commitments::compute_vk_hash; fn main( expected_commitments: pub [[Field; L_THRESHOLD]; H], - decrypted_shares: [[Polynomial; L_THRESHOLD]; H], -) -> pub Field { - let share_decryption: ShareDecryption = - ShareDecryption::new(expected_commitments, decrypted_shares); - - share_decryption.execute(QIS_THRESHOLD) + limb_vks: [UltraHonkVerificationKey; L_THRESHOLD], + limb_key_hashes: [Field; L_THRESHOLD], + limb_proofs: [UltraHonkProof; L_THRESHOLD], + limb_links: [[Field; 2]; L_THRESHOLD], +) -> pub (Field, Field) { + // One circuit per limb: each limb starts the aggregate sponge at its own position. + std::static_assert( + L_THRESHOLD == 3, + "C4 has one limb circuit for each of three limbs", + ); + for l in 0..L_THRESHOLD { + let mut public = [0; H + 2]; + for party_idx in 0..H { + public[party_idx] = expected_commitments[party_idx][l]; + } + public[H] = limb_links[l][0]; + public[H + 1] = limb_links[l][1]; + verify_honk_proof_non_zk(limb_vks[l], limb_proofs[l], public, limb_key_hashes[l]); + } + let agg_commitment = check_limb_chain::(limb_links); + (agg_commitment, compute_vk_hash(limb_key_hashes.as_vector())) } diff --git a/circuits/bin/dkg/share_decryption_limb_0/Nargo.toml b/circuits/bin/dkg/share_decryption_limb_0/Nargo.toml new file mode 100644 index 0000000000..f2f1772285 --- /dev/null +++ b/circuits/bin/dkg/share_decryption_limb_0/Nargo.toml @@ -0,0 +1,7 @@ +[package] +name = "share_decryption_limb_0" +type = "bin" +authors = ["Gnosis Guild / Interfold"] + +[dependencies] +lib = { path = "../../../lib" } diff --git a/circuits/bin/dkg/share_decryption_limb_0/src/main.nr b/circuits/bin/dkg/share_decryption_limb_0/src/main.nr new file mode 100644 index 0000000000..72f98263d1 --- /dev/null +++ b/circuits/bin/dkg/share_decryption_limb_0/src/main.nr @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// +// This file is provided WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. + +//! Limb 0 of chunked C4: C4's statement for CRT limb 0, continuing the aggregate commitment's +//! sponge from `h_in`. See `lib::core::dkg::share_decryption_chain`. + +use lib::configs::default::dkg::{ + L_THRESHOLD, N, QIS_THRESHOLD, SHARE_DECRYPTION_BIT_AGG, SHARE_DECRYPTION_BIT_MSG, +}; +use lib::configs::default::H; +use lib::core::dkg::share_decryption_chain::share_decryption_limb; +use lib::math::polynomial::Polynomial; +use lib::math::safe::STATE_SIZE; + +fn main( + expected_commitments: pub [Field; H], + h_in: pub Field, + decrypted_shares: [Polynomial; H], + state_in: [Field; STATE_SIZE], +) -> pub Field { + share_decryption_limb::<0, N, L_THRESHOLD, H, SHARE_DECRYPTION_BIT_MSG, SHARE_DECRYPTION_BIT_AGG>( + QIS_THRESHOLD, + expected_commitments, + decrypted_shares, + h_in, + state_in, + ) +} diff --git a/circuits/bin/dkg/share_decryption_limb_1/Nargo.toml b/circuits/bin/dkg/share_decryption_limb_1/Nargo.toml new file mode 100644 index 0000000000..95f1fb2d23 --- /dev/null +++ b/circuits/bin/dkg/share_decryption_limb_1/Nargo.toml @@ -0,0 +1,7 @@ +[package] +name = "share_decryption_limb_1" +type = "bin" +authors = ["Gnosis Guild / Interfold"] + +[dependencies] +lib = { path = "../../../lib" } diff --git a/circuits/bin/dkg/share_decryption_limb_1/src/main.nr b/circuits/bin/dkg/share_decryption_limb_1/src/main.nr new file mode 100644 index 0000000000..fa8d8b2e96 --- /dev/null +++ b/circuits/bin/dkg/share_decryption_limb_1/src/main.nr @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// +// This file is provided WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. + +//! Limb 1 of chunked C4: C4's statement for CRT limb 1, continuing the aggregate commitment's +//! sponge from `h_in`. See `lib::core::dkg::share_decryption_chain`. + +use lib::configs::default::dkg::{ + L_THRESHOLD, N, QIS_THRESHOLD, SHARE_DECRYPTION_BIT_AGG, SHARE_DECRYPTION_BIT_MSG, +}; +use lib::configs::default::H; +use lib::core::dkg::share_decryption_chain::share_decryption_limb; +use lib::math::polynomial::Polynomial; +use lib::math::safe::STATE_SIZE; + +fn main( + expected_commitments: pub [Field; H], + h_in: pub Field, + decrypted_shares: [Polynomial; H], + state_in: [Field; STATE_SIZE], +) -> pub Field { + share_decryption_limb::<1, N, L_THRESHOLD, H, SHARE_DECRYPTION_BIT_MSG, SHARE_DECRYPTION_BIT_AGG>( + QIS_THRESHOLD, + expected_commitments, + decrypted_shares, + h_in, + state_in, + ) +} diff --git a/circuits/bin/dkg/share_decryption_limb_2/Nargo.toml b/circuits/bin/dkg/share_decryption_limb_2/Nargo.toml new file mode 100644 index 0000000000..c107d1434b --- /dev/null +++ b/circuits/bin/dkg/share_decryption_limb_2/Nargo.toml @@ -0,0 +1,7 @@ +[package] +name = "share_decryption_limb_2" +type = "bin" +authors = ["Gnosis Guild / Interfold"] + +[dependencies] +lib = { path = "../../../lib" } diff --git a/circuits/bin/dkg/share_decryption_limb_2/src/main.nr b/circuits/bin/dkg/share_decryption_limb_2/src/main.nr new file mode 100644 index 0000000000..24b326128a --- /dev/null +++ b/circuits/bin/dkg/share_decryption_limb_2/src/main.nr @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// +// This file is provided WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. + +//! Limb 2 of chunked C4: C4's statement for CRT limb 2, continuing the aggregate commitment's +//! sponge from `h_in`. See `lib::core::dkg::share_decryption_chain`. + +use lib::configs::default::dkg::{ + L_THRESHOLD, N, QIS_THRESHOLD, SHARE_DECRYPTION_BIT_AGG, SHARE_DECRYPTION_BIT_MSG, +}; +use lib::configs::default::H; +use lib::core::dkg::share_decryption_chain::share_decryption_limb; +use lib::math::polynomial::Polynomial; +use lib::math::safe::STATE_SIZE; + +fn main( + expected_commitments: pub [Field; H], + h_in: pub Field, + decrypted_shares: [Polynomial; H], + state_in: [Field; STATE_SIZE], +) -> pub Field { + share_decryption_limb::<2, N, L_THRESHOLD, H, SHARE_DECRYPTION_BIT_MSG, SHARE_DECRYPTION_BIT_AGG>( + QIS_THRESHOLD, + expected_commitments, + decrypted_shares, + h_in, + state_in, + ) +} diff --git a/circuits/bin/recursive_aggregation/c4ab_fold/src/main.nr b/circuits/bin/recursive_aggregation/c4ab_fold/src/main.nr index 3a2edcfe76..52e6010260 100644 --- a/circuits/bin/recursive_aggregation/c4ab_fold/src/main.nr +++ b/circuits/bin/recursive_aggregation/c4ab_fold/src/main.nr @@ -5,17 +5,19 @@ // or FITNESS FOR A PARTICULAR PURPOSE. //! Combines C4a + C4b (two ZK Honk proofs using the same C4 binary). +//! +//! Each C4 is the final circuit of a limb chain and exposes the hash of its limb keys last. That +//! hash enters this fold's key hash next to the C4 key, so the VK tree covers every limb circuit. +//! The outputs keep the unchunked C4 layout `node_fold` reads. use bb_proof_verification::{UltraHonkVerificationKey, UltraHonkZKProof, verify_honk_proof}; use lib::configs::default::dkg::L_THRESHOLD; use lib::configs::default::H; use lib::math::commitments::compute_vk_hash; -/// C4 public IO: `expected_commitments` (flattened) + `agg_commit`. -pub global C4_PUBLIC_LEN: u32 = (H * L_THRESHOLD) + 1; - -/// Two key-hash params + combined key hash + two C4-sized public vectors (a and b). -pub global C4AB_FOLD_PUBLIC_LEN: u32 = 3 + (2 * C4_PUBLIC_LEN); +/// C4 public IO: `expected_commitments` (flattened) + `agg_commit` + the limb chain's key tree. +pub global C4_PUBLIC_LEN: u32 = (H * L_THRESHOLD) + 2; +pub global C4_KEY_TREE_IDX: u32 = C4_PUBLIC_LEN - 1; fn main( c4a_vk: UltraHonkVerificationKey, @@ -30,7 +32,13 @@ fn main( verify_honk_proof(c4a_vk, c4a_proof, c4a_public, c4a_key_hash); verify_honk_proof(c4b_vk, c4b_proof, c4b_public, c4b_key_hash); - let vk_hashes = [c4a_key_hash, c4b_key_hash].as_vector(); + let vk_hashes = [ + c4a_key_hash, + c4a_public[C4_KEY_TREE_IDX], + c4b_key_hash, + c4b_public[C4_KEY_TREE_IDX], + ] + .as_vector(); let key_hash = compute_vk_hash(vk_hashes); let mut c4a_expected: [[Field; L_THRESHOLD]; H] = [[0; L_THRESHOLD]; H]; diff --git a/circuits/lib/src/README.md b/circuits/lib/src/README.md index c193a4917d..74f0bc7775 100644 --- a/circuits/lib/src/README.md +++ b/circuits/lib/src/README.md @@ -44,6 +44,7 @@ flowchart LR | `dkg/share_computation_chain.nr` | C2a / C2b | Chunk chain over C2's coefficient ranges: chunk statements, SAFE sponge links, and the final circuit's checks | | `dkg/share_encryption` | C3 | Encrypt share under recipient pk | | `dkg/share_decryption` | C4 | Decrypt and aggregate | +| `dkg/share_decryption_chain.nr` | C4 | Limb chain over C4's CRT limbs: the limb statement, SAFE sponge links, and the final circuit's checks | | `threshold/pk_generation` | C1 | TrBFV contribution | | `threshold/pk_aggregation` | C5 | Aggregate pk shares | | `threshold/user_data_encryption_ct0` / `ct1` | P3 | User encryption legs; `bin/threshold/user_data_encryption` runs both | diff --git a/circuits/lib/src/core/dkg/mod.nr b/circuits/lib/src/core/dkg/mod.nr index 657756d340..93a8fdf9db 100644 --- a/circuits/lib/src/core/dkg/mod.nr +++ b/circuits/lib/src/core/dkg/mod.nr @@ -9,3 +9,4 @@ pub mod share_computation; pub mod share_computation_chain; pub mod share_encryption; pub mod share_decryption; +pub mod share_decryption_chain; diff --git a/circuits/lib/src/core/dkg/share_decryption.nr b/circuits/lib/src/core/dkg/share_decryption.nr index 3d0227954b..ea187aee73 100644 --- a/circuits/lib/src/core/dkg/share_decryption.nr +++ b/circuits/lib/src/core/dkg/share_decryption.nr @@ -53,38 +53,6 @@ impl Sha ShareDecryption { expected_commitments, decrypted_shares } } - /// Verifies that each decrypted share matches its expected commitment from C2a/C2b. - /// - /// For each honest party and each CRT modulus, hashes the decrypted share polynomial - /// and confirms it equals the commitment produced in C2 via commit_to_party_shares. - /// - /// Opens with the checked packing helper: asserting each digit fits its slot makes the opening - /// unique, so the witness must be the share C2 committed and already bounded to `[0, q_j)`. That - /// transferred bound is what `normalize_aggregated` relies on to cap its carry at `H`; the - /// aggregate itself needs no bound of its own. - /// Since commitments are binding, any substitution or tampering, claiming a different - /// decrypted value or using the wrong secret key, will cause this assertion to fail. - fn verify_commitments(self) { - for party_idx in 0..H { - for mod_idx in 0..L { - // Reverse the share polynomial to match the commitment format used by C2's - // commit_to_party_shares, which stores coefficients highest-degree-first. - let share = self.decrypted_shares[party_idx][mod_idx]; - let mut reversed_coeffs: [Field; N] = [0; N]; - for i in 0..N { - reversed_coeffs[N - 1 - i] = share.coefficients[i]; - } - assert( - compute_share_encryption_commitment_from_message_checked::( - Polynomial::new(reversed_coeffs), - ) - == self.expected_commitments[party_idx][mod_idx], - "Commitment mismatch", - ); - } - } - } - /// Executes the share decryption and aggregation circuit. /// /// Returns a commitment to the aggregated shares: @@ -97,28 +65,72 @@ impl Sha /// Rust witness (which operates on sk coefficients already reduced to `[0, q_l)` /// and then applies `.reverse()` and `.center(&qi)` before hashing). pub fn execute(self, moduli: [Field; L]) -> Field { - // Step 1: Verify decrypted shares match expected C2 commitments, opened injectively. - self.verify_commitments(); + let mut normalized: [Polynomial; L] = [Polynomial::new([0; N]); L]; + for mod_idx in 0..L { + let mut commitments = [0; H]; + let mut shares = [Polynomial::new([0; N]); H]; + for party_idx in 0..H { + commitments[party_idx] = self.expected_commitments[party_idx][mod_idx]; + shares[party_idx] = self.decrypted_shares[party_idx][mod_idx]; + } + normalized[mod_idx] = + aggregate_limb::(commitments, shares, moduli[mod_idx]); + } - // Step 2: Sum shares coefficient-wise per CRT limb. - aggregate_canonical_shares::(self.decrypted_shares, moduli) + // Publish commitment to the aggregate (C6 input). + compute_aggregated_shares_commitment::(normalized) } } -/// The caller must first bind and canonically bound every native-order share to `[0, q_l)`. -pub fn aggregate_canonical_shares( - shares: [[Polynomial; L]; H], - moduli: [Field; L], -) -> Field { - let mut aggregated = [Polynomial::new([0; N]); L]; - for limb in 0..L { - let mut coefficients = [0; N]; - for coefficient in 0..N { - for row in 0..H { - coefficients[coefficient] += shares[row][limb].coefficients[coefficient]; - } +/// C4's statement for one CRT limb with modulus `q`: every honest party's decrypted share opens its +/// C2 commitment, and the shares' sum, reversed and centered as C6 hashes it, is returned. +/// +/// Each share is reversed to C2's highest-degree-first order and opened with the checked packing +/// helper. Asserting each digit fits its slot makes the opening unique, so the witness must be the +/// share C2 committed and already bounded to `[0, q)`. That transferred bound is what +/// `normalize_aggregated` relies on to cap its carry at `H`; the aggregate itself needs no bound +/// of its own. Since commitments are binding, any substitution or tampering, claiming a different +/// decrypted value or using the wrong secret key, fails the commitment check. +pub fn aggregate_limb( + expected_commitments: [Field; H], + decrypted_shares: [Polynomial; H], + q: Field, +) -> Polynomial { + for party_idx in 0..H { + // Reverse the share polynomial to match the commitment format used by C2's + // commit_to_party_shares, which stores coefficients highest-degree-first. + let share = decrypted_shares[party_idx]; + let mut reversed_coeffs: [Field; N] = [0; N]; + for i in 0..N { + reversed_coeffs[N - 1 - i] = share.coefficients[i]; + } + assert( + compute_share_encryption_commitment_from_message_checked::(Polynomial::new( + reversed_coeffs, + )) + == expected_commitments[party_idx], + "Commitment mismatch", + ); + } + + aggregate_canonical_limb::(decrypted_shares, q) +} + +/// The caller must first bind and canonically bound every native-order share to `[0, q)`. +/// +/// Sums the shares coefficient-wise, then reverses and centers the sum as C6 hashes it. No +/// reduction is applied while summing: each coefficient is bounded to `[0, q)`, so the sum stays +/// under `H * q` and fits the field. This is the threshold key construction, `sk = sum(sk_i)` over +/// the honest parties. +pub fn aggregate_canonical_limb( + shares: [Polynomial; H], + q: Field, +) -> Polynomial { + let mut sum = [0 as Field; N]; + for coefficient in 0..N { + for row in 0..H { + sum[coefficient] += shares[row].coefficients[coefficient]; } - aggregated[limb] = Polynomial::new(coefficients); } // The carry `normalize_aggregated` divides out is at most H; see AGGREGATION_BIT_CARRY. @@ -126,15 +138,27 @@ pub fn aggregate_canonical_shares(); - } + (q - 1).assert_max_bit_size::(); + + // Normalize to match C6's representation: reverse and centre-reduce mod q. + normalize_aggregated::([Polynomial::new(sum)], [q])[0] +} - // Step 3: Normalize to match C6's representation: reverse and centre-reduce mod q. - let normalized = - normalize_aggregated::(aggregated, moduli); +/// The caller must first bind and canonically bound every native-order share to `[0, q_l)`. +pub fn aggregate_canonical_shares( + shares: [[Polynomial; L]; H], + moduli: [Field; L], +) -> Field { + let mut normalized: [Polynomial; L] = [Polynomial::new([0; N]); L]; + for limb in 0..L { + let mut limb_shares = [Polynomial::new([0; N]); H]; + for row in 0..H { + limb_shares[row] = shares[row][limb]; + } + normalized[limb] = aggregate_canonical_limb::(limb_shares, moduli[limb]); + } - // Step 4: Publish commitment to the aggregate (C6 input). + // Publish commitment to the aggregate (C6 input). compute_aggregated_shares_commitment::(normalized) } @@ -151,7 +175,7 @@ pub fn aggregate_canonical_shares( diff --git a/circuits/lib/src/core/dkg/share_decryption_chain.nr b/circuits/lib/src/core/dkg/share_decryption_chain.nr new file mode 100644 index 0000000000..ba0aff84c5 --- /dev/null +++ b/circuits/lib/src/core/dkg/share_decryption_chain.nr @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// +// This file is provided WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. + +//! Share decryption (C4) split by CRT limb, with C4's commitments unchanged. +//! +//! C4 opens `H * L` share commitments, which at 28 honest parties is a 2^24 circuit. The openings +//! and sums are independent per limb, and the aggregate commitment C6 reads is one SAFE sponge over +//! the normalized limbs in order (limb 0, then 1, then 2). So limb `l`'s proof runs C4's statement +//! for that limb ([`aggregate_limb`]) and continues the aggregate sponge from the state limb +//! `l - 1` left; the last limb squeezes the commitment the unchunked C4 returns. +//! +//! Each limb packs into its own carriers, so a limb can start mid-block. The start position follows +//! from the limb index alone, so each limb has its own circuit and every absorb position is known +//! when it is compiled. +//! +//! **Links.** Limb `l` proves `out` from `h_in`, a hash of the carried sponge state; `out` is the +//! next limb's `h_in`, or the aggregate commitment for the last limb. The final C4 circuit verifies +//! every limb, links them and starts the chain from the fresh sponge. + +use crate::core::dkg::share_decryption::aggregate_limb; +use crate::math::commitments::{ + compute_commitment, DS_AGGREGATED_SHARES, DS_SHARE_DECRYPTION_CHAIN_STATE, +}; +use crate::math::helpers::{pack, packing_layout}; +use crate::math::polynomial::Polynomial; +use crate::math::safe::{absorb_from, initial_state, squeeze_one_after_absorb, STATE_SIZE}; + +/// SAFE IO pattern of the aggregate commitment (`compute_aggregated_shares_commitment`). +pub fn aggregated_io_pattern() -> [u32; 2] { + let (_, group) = packing_layout::(); + [0x80000000 | (L * ((N + group - 1) / group)), 1] +} + +/// The aggregate sponge's absorb position when limb `LIMB` starts: the earlier limbs absorbed +/// `LIMB` limbs' carriers. +fn limb_start_pos() -> u32 { + let (_, group) = packing_layout::(); + let absorbed = LIMB * ((N + group - 1) / group); + if absorbed == 0 { + 0 + } else { + (absorbed - 1) % 3 + 1 + } +} + +/// Hash of the carried aggregate sponge state. +pub fn limb_state_hash(state: [Field; STATE_SIZE]) -> Field { + compute_commitment(state.as_vector(), DS_SHARE_DECRYPTION_CHAIN_STATE) +} + +/// The chain's start: the aggregate sponge fresh. +pub fn limb_chain_start_hash() -> Field { + limb_state_hash( + initial_state( + aggregated_io_pattern::(), + DS_AGGREGATED_SHARES, + ), + ) +} + +/// Limb `LIMB` of `L`: C4's statement for that limb, continuing the aggregate sponge from `state_in`. +/// Returns the next limb's input hash, or for the last limb the aggregate commitment. +pub fn share_decryption_limb( + qis: [Field; L], + expected_commitments: [Field; H], + decrypted_shares: [Polynomial; H], + h_in: Field, + state_in: [Field; STATE_SIZE], +) -> Field { + std::static_assert(LIMB < L, "limb index out of range"); + assert(limb_state_hash(state_in) == h_in, "Chain state mismatch"); + let normalized = + aggregate_limb::(expected_commitments, decrypted_shares, qis[LIMB]); + let (state, pos) = absorb_from( + state_in, + limb_start_pos::(), + pack::(normalized.coefficients), + ); + if LIMB == L - 1 { + squeeze_one_after_absorb(aggregated_io_pattern::(), state, pos) + } else { + limb_state_hash(state) + } +} + +/// Checks the limbs' `(h_in, out)` links cover the chain in order from the fresh sponge, and returns +/// the last limb's output, the aggregate commitment. +pub fn check_limb_chain(links: [[Field; 2]; L]) -> Field { + assert(links[0][0] == limb_chain_start_hash::(), "Chain must start fresh"); + for l in 0..L - 1 { + assert(links[l][1] == links[l + 1][0], "Limb link mismatch"); + } + links[L - 1][1] +} + +// ------------------------------------------------------------------------------------------------ +// Tests: 4 coefficients, 3 parties, 3 limbs. +// ------------------------------------------------------------------------------------------------ + +global TQ: [Field; 3] = [97, 89, 83]; + +/// Shares `[party][limb]` in `[0, q)`, their commitments, and the C4 aggregate commitment. +fn test_limbs() -> ([[Polynomial<4>; 3]; 3], [[Field; 3]; 3], Field) { + let mut shares = [[Polynomial::new([0; 4]); 3]; 3]; + let mut commitments = [[0; 3]; 3]; + for party in 0..3 { + for limb in 0..3 { + let q: u64 = if limb == 0 { + 97 + } else if limb == 1 { + 89 + } else { + 83 + }; + let mut coeffs = [0; 4]; + for i in 0..4 { + coeffs[i] = (((party * 31 + limb * 7 + i * 13 + 5) as u64) % q) as Field; + } + shares[party][limb] = Polynomial::new(coeffs); + let mut reversed = [0; 4]; + for i in 0..4 { + reversed[3 - i] = coeffs[i]; + } + commitments[party][limb] = crate::math::commitments::compute_share_encryption_commitment_from_message::<4, 60>( + Polynomial::new(reversed), + ); + } + } + let expected = crate::core::dkg::share_decryption::ShareDecryption::<4, 3, 3, 60, 60>::new( + commitments, + shares, + ) + .execute(TQ); + (shares, commitments, expected) +} + +fn limb_inputs( + shares: [[Polynomial<4>; 3]; 3], + commitments: [[Field; 3]; 3], + limb: u32, +) -> ([Field; 3], [Polynomial<4>; 3]) { + let mut c = [0; 3]; + let mut s = [Polynomial::new([0; 4]); 3]; + for party in 0..3 { + c[party] = commitments[party][limb]; + s[party] = shares[party][limb]; + } + (c, s) +} + +/// The limb chain reproduces the unchunked C4 aggregate commitment. +#[test] +fn limb_chain_equals_the_unchunked_c4_commitment() { + let (shares, commitments, expected) = test_limbs(); + let fresh = initial_state(aggregated_io_pattern::<4, 3, 60>(), DS_AGGREGATED_SHARES); + let h0 = limb_state_hash(fresh); + + // Replay the sponge to hand each limb its carried state. + let (c0, s0) = limb_inputs(shares, commitments, 0); + let h1 = share_decryption_limb::<0, 4, 3, 3, 60, 60>(TQ, c0, s0, h0, fresh); + let n0 = aggregate_limb::<4, 3, 60>(c0, s0, TQ[0]); + let (st1, _) = absorb_from(fresh, 0, pack::<4, 60>(n0.coefficients)); + assert(limb_state_hash(st1) == h1); + + let (c1, s1) = limb_inputs(shares, commitments, 1); + let h2 = share_decryption_limb::<1, 4, 3, 3, 60, 60>(TQ, c1, s1, h1, st1); + let n1 = aggregate_limb::<4, 3, 60>(c1, s1, TQ[1]); + let (st2, _) = absorb_from( + st1, + limb_start_pos::<4, 60, 1>(), + pack::<4, 60>(n1.coefficients), + ); + assert(limb_state_hash(st2) == h2); + + let (c2, s2) = limb_inputs(shares, commitments, 2); + let agg = share_decryption_limb::<2, 4, 3, 3, 60, 60>(TQ, c2, s2, h2, st2); + assert(agg == expected); + assert(check_limb_chain::<4, 3, 60>([[h0, h1], [h1, h2], [h2, agg]]) == expected); +} + +#[test(should_fail_with = "Commitment mismatch")] +fn a_limb_rejects_a_share_that_does_not_open_its_commitment() { + let (mut shares, commitments, _) = test_limbs(); + shares[1][0].coefficients[2] = shares[1][0].coefficients[2] + 1; + let fresh = initial_state(aggregated_io_pattern::<4, 3, 60>(), DS_AGGREGATED_SHARES); + let (c0, s0) = limb_inputs(shares, commitments, 0); + let _ = share_decryption_limb::<0, 4, 3, 3, 60, 60>(TQ, c0, s0, limb_state_hash(fresh), fresh); +} + +#[test(should_fail_with = "Limb link mismatch")] +fn the_limb_chain_rejects_unlinked_limbs() { + let start = limb_chain_start_hash::<4, 3, 60>(); + let _ = check_limb_chain::<4, 3, 60>([[start, 1], [2, 3], [3, 4]]); +} diff --git a/circuits/lib/src/math/commitments.nr b/circuits/lib/src/math/commitments.nr index 7ffc9aa39a..899185a596 100644 --- a/circuits/lib/src/math/commitments.nr +++ b/circuits/lib/src/math/commitments.nr @@ -58,6 +58,13 @@ pub global DS_SHARE_COMPUTATION_CHAIN_OUTPUT: [u8; 64] = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; +// Domain separator - "SHARE_DECRYPTION_CHAIN_STATE" +pub global DS_SHARE_DECRYPTION_CHAIN_STATE: [u8; 64] = [ + 0x53, 0x48, 0x41, 0x52, 0x45, 0x5f, 0x44, 0x45, 0x43, 0x52, 0x59, 0x50, 0x54, 0x49, 0x4f, 0x4e, + 0x5f, 0x43, 0x48, 0x41, 0x49, 0x4e, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +]; // Domain separator - "PK_AGGREGATION" pub global DS_PK_AGGREGATION: [u8; 64] = [ 0x50, 0x4b, 0x5f, 0x41, 0x47, 0x47, 0x52, 0x45, 0x47, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x00, 0x00, diff --git a/crates/zk/benchmarks/src/circuit_benchmark/inputs.rs b/crates/zk/benchmarks/src/circuit_benchmark/inputs.rs index 7de6d1cd5e..4a949cf542 100644 --- a/crates/zk/benchmarks/src/circuit_benchmark/inputs.rs +++ b/crates/zk/benchmarks/src/circuit_benchmark/inputs.rs @@ -191,7 +191,14 @@ pub(crate) fn prepare( )?; prepared(e3_zk_prover::ShareEncryptionCircuit, config, sample, record) } - Case::Named(CircuitName::DkgShareDecryption) => { + Case::Named( + name @ (CircuitName::DkgShareDecryption + | CircuitName::DkgShareDecryptionLimb0 + | CircuitName::DkgShareDecryptionLimb1 + | CircuitName::DkgShareDecryptionLimb2), + ) => { + // C4 is proven as a limb chain: the final circuit's inputs are the limb proofs, and + // each limb circuit is measured on its own limb of the same sample. let config = dkg::share_decryption::Configs::new(&m.threshold, &m.dkg)?; let sample = e3_zk_samples::dkg::share_decryption::generate( &config, @@ -199,12 +206,42 @@ pub(crate) fn prepare( m.committee.values(), DkgInputType::SecretKey, )?; - prepared( - e3_zk_prover::DkgShareDecryptionCircuit, - config, - sample, - record, - ) + // The limb circuits are artifacts: they load before the timer starts. + let limbs = if name == CircuitName::DkgShareDecryption { + record.preparation.metric = "limb_chain_proving_and_input_projection_wall".into(); + Some(e3_zk_prover::LimbCircuits::load(prover, pair)?) + } else { + None + }; + let start = Instant::now(); + let result = (|| -> Result { + if let Some(limbs) = &limbs { + let json = e3_zk_prover::final_share_decryption_inputs( + prover, + &config, + &sample, + limbs, + "benchmark-c4", + pair, + )?; + return Ok(e3_zk_prover::inputs_json_to_input_map(&json)?); + } + let inputs = + e3_zk_witness::dkg::share_decryption::Inputs::compute(&config, &sample)?; + let chain = e3_zk_witness::dkg::share_decryption_chain::LimbChain::compute( + &config, &inputs, + )?; + let limb = match name { + CircuitName::DkgShareDecryptionLimb0 => 0, + CircuitName::DkgShareDecryptionLimb1 => 1, + _ => 2, + }; + Ok(e3_zk_prover::inputs_json_to_input_map( + &chain.limbs[limb].to_json(), + )?) + })(); + record.preparation.finish(start.elapsed(), &result); + result } Case::Named(CircuitName::PkGeneration) => { let config = diff --git a/crates/zk/benchmarks/src/circuit_benchmark/leaf.rs b/crates/zk/benchmarks/src/circuit_benchmark/leaf.rs index 2ffe0dc596..9c583e1651 100644 --- a/crates/zk/benchmarks/src/circuit_benchmark/leaf.rs +++ b/crates/zk/benchmarks/src/circuit_benchmark/leaf.rs @@ -9,7 +9,10 @@ use super::{ Options, }; use anyhow::{bail, Result}; -use e3_zk_prover::{Provable, ShareComputationCircuit, WitnessGenerator, ZkProver}; +use e3_zk_config::CircuitName; +use e3_zk_prover::{ + DkgShareDecryptionCircuit, Provable, ShareComputationCircuit, WitnessGenerator, ZkProver, +}; use std::{fs, path::Path, process::Command, time::Instant}; #[allow(clippy::too_many_arguments)] @@ -128,18 +131,27 @@ pub(crate) fn benchmark( let proof = proof?; record.proof_bytes(&proof.data, &proof.public_signals); let start = Instant::now(); - // A final C2 proof is valid only over the chunk key tree of the selected pair. - let verified = if e3_zk_prover::chunk_circuits(name).is_some() { - ShareComputationCircuit.verify_with_variant( + // A final C2 or C4 proof is valid only over the chunk key tree of the selected pair. + let verified = match name { + CircuitName::SkShareComputation | CircuitName::ESmShareComputation => { + ShareComputationCircuit.verify_with_variant( + prover, + &proof, + "benchmark", + 1, + variant, + pair, + ) + } + CircuitName::DkgShareDecryption => DkgShareDecryptionCircuit.verify_with_variant( prover, &proof, "benchmark", 1, variant, pair, - ) - } else { - prover.verify_proof_with_variant(&proof, "benchmark", 1, variant, pair) + ), + _ => prover.verify_proof_with_variant(&proof, "benchmark", 1, variant, pair), }; let result = verified.map_err(anyhow::Error::from).and_then(|valid| { if valid { diff --git a/crates/zk/benchmarks/src/circuit_benchmark/selection.rs b/crates/zk/benchmarks/src/circuit_benchmark/selection.rs index f75ad533b7..7ad3ef47ab 100644 --- a/crates/zk/benchmarks/src/circuit_benchmark/selection.rs +++ b/crates/zk/benchmarks/src/circuit_benchmark/selection.rs @@ -27,6 +27,9 @@ impl Case { CircuitName::ESmShareComputationChainLast, CircuitName::ShareEncryption, CircuitName::DkgShareDecryption, + CircuitName::DkgShareDecryptionLimb0, + CircuitName::DkgShareDecryptionLimb1, + CircuitName::DkgShareDecryptionLimb2, CircuitName::PkGeneration, CircuitName::PkAggregation, CircuitName::ThresholdShareDecryption, @@ -48,15 +51,18 @@ impl Case { pub fn name(self) -> String { self.path().rsplit('/').next().unwrap().to_string() } - /// The variant this case runs in. The C2 chunk circuits are only built, proven and verified - /// non-ZK (`default`), whichever variant the run requests. + /// The variant this case runs in. The C2 chunk and C4 limb circuits are only built, proven and + /// verified non-ZK (`default`), whichever variant the run requests. pub fn variant(self, requested: CircuitVariant) -> CircuitVariant { match self { Self::Named( CircuitName::SkShareComputationChain | CircuitName::SkShareComputationChainLast | CircuitName::ESmShareComputationChain - | CircuitName::ESmShareComputationChainLast, + | CircuitName::ESmShareComputationChainLast + | CircuitName::DkgShareDecryptionLimb0 + | CircuitName::DkgShareDecryptionLimb1 + | CircuitName::DkgShareDecryptionLimb2, ) => CircuitVariant::Default, _ => requested, } diff --git a/crates/zk/benchmarks/src/circuit_benchmark/tests.rs b/crates/zk/benchmarks/src/circuit_benchmark/tests.rs index 09da3f0da7..81b8bed036 100644 --- a/crates/zk/benchmarks/src/circuit_benchmark/tests.rs +++ b/crates/zk/benchmarks/src/circuit_benchmark/tests.rs @@ -30,13 +30,16 @@ fn configured_leaf_selection_rejects_unknown_or_restricted_cases() { } #[test] -fn c2_chunk_cases_always_run_in_the_default_variant() { +fn chunk_and_limb_cases_always_run_in_the_default_variant() { use e3_zk_config::{CircuitName, CircuitVariant}; for chunk in [ CircuitName::SkShareComputationChain, CircuitName::SkShareComputationChainLast, CircuitName::ESmShareComputationChain, CircuitName::ESmShareComputationChainLast, + CircuitName::DkgShareDecryptionLimb0, + CircuitName::DkgShareDecryptionLimb1, + CircuitName::DkgShareDecryptionLimb2, ] { for requested in [ CircuitVariant::Recursive, @@ -49,10 +52,11 @@ fn c2_chunk_cases_always_run_in_the_default_variant() { assert_eq!(record.variant, "default"); } } - // Every other case, the final C2 circuits included, runs in the requested variant. + // Every other case, the final C2 and C4 circuits included, runs in the requested variant. for case in [ Case::Named(CircuitName::SkShareComputation), Case::Named(CircuitName::ESmShareComputation), + Case::Named(CircuitName::DkgShareDecryption), Case::Named(CircuitName::PkBfv), Case::Ude, ] { diff --git a/crates/zk/build/src/artifacts.rs b/crates/zk/build/src/artifacts.rs index 539ee87f56..2668d84829 100644 --- a/crates/zk/build/src/artifacts.rs +++ b/crates/zk/build/src/artifacts.rs @@ -547,9 +547,12 @@ pub fn variants(circuit: &Circuit) -> Vec<(&'static str, &'static str, &'static values.push(("evm", "evm", "vk")); } values - } else if circuit.group == "dkg" && circuit.name.contains("_share_computation_chain") { - // The C2 chunk circuits are only proven non-ZK and verified inside the final C2 circuit, - // so their `default` key is the only one anything reads. + } else if circuit.group == "dkg" + && (circuit.name.contains("_share_computation_chain") + || circuit.name.starts_with("share_decryption_limb_")) + { + // The C2 chunk and C4 limb circuits are only proven non-ZK and verified inside their final + // circuit, so their `default` key is the only one anything reads. vec![("default", "noir-recursive-no-zk", "vk_recursive")] } else { vec![ @@ -937,7 +940,7 @@ mod tests { use e3_fhe_params::BfvPreset; #[test] - fn c2_chunk_circuits_build_only_their_default_key() { + fn chunk_and_limb_circuits_build_only_their_default_key() { let circuit = |group: &str, name: &str| Circuit { name: name.to_string(), group: group.to_string(), @@ -955,10 +958,17 @@ mod tests { "sk_share_computation_chain_last", "e_sm_share_computation_chain", "e_sm_share_computation_chain_last", + "share_decryption_limb_0", + "share_decryption_limb_1", + "share_decryption_limb_2", ] { assert_eq!(names(&circuit("dkg", chunk)), ["default"], "{chunk}"); } - for final_circuit in ["sk_share_computation", "e_sm_share_computation"] { + for final_circuit in [ + "sk_share_computation", + "e_sm_share_computation", + "share_decryption", + ] { assert_eq!( names(&circuit("dkg", final_circuit)), ["evm", "default", "recursive"], @@ -1461,9 +1471,9 @@ mod tests { let manifest: serde_json::Value = serde_json::from_slice(&fs::read(root.join("dist/circuits/checksums.json")).unwrap()) .unwrap(); - // The json, vk and vk_hash of pk and pk_generation in three variants (18), plus the 27 + // The json, vk and vk_hash of pk and pk_generation in three variants (18), plus the 30 // seeded anchor keys the build does not write. - assert_eq!(manifest["files"].as_object().unwrap().len(), 45); + assert_eq!(manifest["files"].as_object().unwrap().len(), 48); let hash = identity::source_hash(root, &request(), Some("insecure-64"), Some("minimum")).unwrap(); let built_stamp = read_stamp(&pair.join(".build-stamp.json")) diff --git a/crates/zk/build/src/tests.rs b/crates/zk/build/src/tests.rs index 1f82c57d66..692cc8c9cf 100644 --- a/crates/zk/build/src/tests.rs +++ b/crates/zk/build/src/tests.rs @@ -1495,6 +1495,9 @@ const VK_PATHS: &[(&str, &str, &str)] = &[ ("default", "chonk", "c6_chonk_app"), ("default", "chonk", "c6_chonk_init_kernel"), ("default", "chonk", "c6_chonk_tail_kernel"), + ("default", "dkg", "share_decryption_limb_0"), + ("default", "dkg", "share_decryption_limb_1"), + ("default", "dkg", "share_decryption_limb_2"), ]; pub(crate) fn seed_anchor_keys(pair: &Path) { for i in 0..VK_PATHS.len() { @@ -1537,7 +1540,10 @@ fn anchors_bind_all_descendants_in_circuit_order_and_reject_noncanonical_keys() keys[9], compute_vk_hash(vec![c3_chain, c3_chain]), keys[10], - compute_vk_hash(vec![keys[5], keys[5]]), + { + let limbs = compute_vk_hash(vec![keys[25], keys[26], keys[27]]); + compute_vk_hash(vec![keys[5], limbs, keys[5], limbs]) + }, ]); let expected = [ ( diff --git a/crates/zk/build/src/vk_tree.rs b/crates/zk/build/src/vk_tree.rs index 55b821d843..0a9a9edeb2 100644 --- a/crates/zk/build/src/vk_tree.rs +++ b/crates/zk/build/src/vk_tree.rs @@ -61,8 +61,15 @@ pub fn hashes(root: &Path) -> Result<[(&'static str, [u8; 32]); 2]> { chonk("c3_chonk_tail_kernel")?, ]); let c3 = compute_vk_hash(vec![c3_chain, c3_chain]); + // Each final C4 exposes the hash of its three limb keys; `c4ab_fold` hashes it next to the C4 + // key, for C4a and C4b alike. let c4_key = load(root, "recursive", "dkg", "share_decryption")?; - let c4 = compute_vk_hash(vec![c4_key, c4_key]); + let c4_chain = compute_vk_hash(vec![ + load(root, "default", "dkg", "share_decryption_limb_0")?, + load(root, "default", "dkg", "share_decryption_limb_1")?, + load(root, "default", "dkg", "share_decryption_limb_2")?, + ]); + let c4 = compute_vk_hash(vec![c4_key, c4_chain, c4_key, c4_chain]); let node = compute_vk_hash(vec![ load(root, "recursive", "dkg", "pk")?, load(root, "recursive", "threshold", "pk_generation")?, diff --git a/crates/zk/config/src/circuit.rs b/crates/zk/config/src/circuit.rs index 1327e45143..26ad606439 100644 --- a/crates/zk/config/src/circuit.rs +++ b/crates/zk/config/src/circuit.rs @@ -131,6 +131,12 @@ pub enum CircuitName { C6ChonkTube, /// Closes the C6 tube's IPA claim; the decryption aggregator verifies it. C6ChonkRoot, + /// Chunked C4: CRT limb 0 (non-ZK, verified by the final C4 circuit). + DkgShareDecryptionLimb0, + /// Chunked C4: CRT limb 1. + DkgShareDecryptionLimb1, + /// Chunked C4: CRT limb 2. + DkgShareDecryptionLimb2, } impl CircuitName { @@ -275,6 +281,9 @@ impl CircuitName { CircuitName::C6ChonkHidingKernel => "c6_chonk_hiding_kernel", CircuitName::C6ChonkTube => "c6_chonk_tube", CircuitName::C6ChonkRoot => "c6_chonk_root", + CircuitName::DkgShareDecryptionLimb0 => "share_decryption_limb_0", + CircuitName::DkgShareDecryptionLimb1 => "share_decryption_limb_1", + CircuitName::DkgShareDecryptionLimb2 => "share_decryption_limb_2", } } @@ -288,7 +297,10 @@ impl CircuitName { | CircuitName::ESmShareComputationChain | CircuitName::ESmShareComputationChainLast => "dkg", CircuitName::ShareEncryption => "dkg", - CircuitName::DkgShareDecryption => "dkg", + CircuitName::DkgShareDecryption + | CircuitName::DkgShareDecryptionLimb0 + | CircuitName::DkgShareDecryptionLimb1 + | CircuitName::DkgShareDecryptionLimb2 => "dkg", CircuitName::PkGeneration => "threshold", CircuitName::ThresholdShareDecryption => "threshold", CircuitName::PkAggregation => "threshold", @@ -376,7 +388,10 @@ impl CircuitName { | CircuitName::C6ChonkTailKernel | CircuitName::C6ChonkHidingKernel | CircuitName::C6ChonkTube - | CircuitName::C6ChonkRoot => CircuitOutputLayout::None, + | CircuitName::C6ChonkRoot + | CircuitName::DkgShareDecryptionLimb0 + | CircuitName::DkgShareDecryptionLimb1 + | CircuitName::DkgShareDecryptionLimb2 => CircuitOutputLayout::None, } } diff --git a/crates/zk/config/src/output_layout.rs b/crates/zk/config/src/output_layout.rs index cb3697f679..cab4cf035f 100644 --- a/crates/zk/config/src/output_layout.rs +++ b/crates/zk/config/src/output_layout.rs @@ -151,8 +151,9 @@ pub const PK_BFV_OUTPUTS: &[OutputField] = &[f("pk_commitment")]; pub const PK_GENERATION_OUTPUTS: &[OutputField] = &[f("sk_commitment"), f("pk_commitment"), f("e_sm_commitment")]; -/// C4 — DKG share decryption. -pub const DKG_SHARE_DECRYPTION_OUTPUTS: &[OutputField] = &[f("commitment")]; +/// C4 — DKG share decryption. The final circuit of the limb chain also returns the hash of its limb +/// keys after the aggregate commitment. +pub const DKG_SHARE_DECRYPTION_OUTPUTS: &[OutputField] = &[f("commitment"), f("key_tree")]; /// C5 — Public key aggregation. pub const PK_AGGREGATION_OUTPUTS: &[OutputField] = &[f("commitment")]; diff --git a/crates/zk/config/tests/circuit_identity.rs b/crates/zk/config/tests/circuit_identity.rs index 46feac75dc..32c7396e8b 100644 --- a/crates/zk/config/tests/circuit_identity.rs +++ b/crates/zk/config/tests/circuit_identity.rs @@ -33,16 +33,17 @@ fn secure_minimum_is_decryption_only_and_does_not_fall_back_to_ss() { #[test] fn baseline_enum_bytes_names_paths_and_layout_selection_are_unchanged() { - // Frozen from the e3-events definitions at 26023af50, including the shared C4/C6 basename. - // The four share-computation chunk circuits, then the C3 and C6 Chonk circuits, are new rows - // appended after the existing variants. + // Frozen from the e3-events definitions at 26023af50, including the shared C4/C6 basename. The + // chunked C4 also outputs its key tree. The four share-computation chunk circuits, then the C3 + // and C6 Chonk circuits, then the C4 limb circuits are new rows appended after the existing + // variants. for (index, (name, path, inputs, outputs)) in [ ("PkBfv", "dkg/pk", 0, Some(1)), ("PkGeneration", "threshold/pk_generation", 0, Some(3)), ("SkShareComputation", "dkg/sk_share_computation", 0, None), ("ESmShareComputation", "dkg/e_sm_share_computation", 0, None), ("ShareEncryption", "dkg/share_encryption", 2, Some(1)), - ("DkgShareDecryption", "dkg/share_decryption", 0, Some(1)), + ("DkgShareDecryption", "dkg/share_decryption", 0, Some(2)), ("PkAggregation", "threshold/pk_aggregation", 0, Some(1)), ( "ThresholdShareDecryption", @@ -179,6 +180,24 @@ fn baseline_enum_bytes_names_paths_and_layout_selection_are_unchanged() { 0, Some(0), ), + ( + "DkgShareDecryptionLimb0", + "dkg/share_decryption_limb_0", + 0, + Some(0), + ), + ( + "DkgShareDecryptionLimb1", + "dkg/share_decryption_limb_1", + 0, + Some(0), + ), + ( + "DkgShareDecryptionLimb2", + "dkg/share_decryption_limb_2", + 0, + Some(0), + ), ] .into_iter() .enumerate() diff --git a/crates/zk/prover/required-artifacts.json b/crates/zk/prover/required-artifacts.json index 506dcf3c53..fdc78711fe 100644 --- a/crates/zk/prover/required-artifacts.json +++ b/crates/zk/prover/required-artifacts.json @@ -14,6 +14,15 @@ "default/dkg/share_decryption/share_decryption.json", "default/dkg/share_decryption/share_decryption.vk", "default/dkg/share_decryption/share_decryption.vk_hash", + "default/dkg/share_decryption_limb_0/share_decryption_limb_0.json", + "default/dkg/share_decryption_limb_0/share_decryption_limb_0.vk", + "default/dkg/share_decryption_limb_0/share_decryption_limb_0.vk_hash", + "default/dkg/share_decryption_limb_1/share_decryption_limb_1.json", + "default/dkg/share_decryption_limb_1/share_decryption_limb_1.vk", + "default/dkg/share_decryption_limb_1/share_decryption_limb_1.vk_hash", + "default/dkg/share_decryption_limb_2/share_decryption_limb_2.json", + "default/dkg/share_decryption_limb_2/share_decryption_limb_2.vk", + "default/dkg/share_decryption_limb_2/share_decryption_limb_2.vk_hash", "default/dkg/share_encryption/share_encryption.json", "default/dkg/share_encryption/share_encryption.vk", "default/dkg/share_encryption/share_encryption.vk_hash", diff --git a/crates/zk/prover/src/circuits/aggregation/c2_chain.rs b/crates/zk/prover/src/circuits/aggregation/c2_chain.rs index af052c4198..911b368dbf 100644 --- a/crates/zk/prover/src/circuits/aggregation/c2_chain.rs +++ b/crates/zk/prover/src/circuits/aggregation/c2_chain.rs @@ -29,7 +29,7 @@ pub fn final_circuit(input_type: DkgInputType) -> CircuitName { } } -fn load_compiled( +pub(super) fn load_compiled( prover: &ZkProver, circuit: CircuitName, variant: CircuitVariant, @@ -42,7 +42,7 @@ fn load_compiled( CompiledCircuit::from_file(&path) } -fn prove_circuit( +pub(super) fn prove_circuit( prover: &ZkProver, circuit: CircuitName, compiled: &CompiledCircuit, diff --git a/crates/zk/prover/src/circuits/aggregation/c4_chain.rs b/crates/zk/prover/src/circuits/aggregation/c4_chain.rs new file mode 100644 index 0000000000..7b714339e1 --- /dev/null +++ b/crates/zk/prover/src/circuits/aggregation/c4_chain.rs @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// +// This file is provided WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. + +//! Chunked C4: proves the limb chain of `lib::core::dkg::share_decryption_chain`, then the final +//! `share_decryption` proof that verifies every limb and that peers and `c4ab_fold` consume. The +//! limb proofs never leave this node, so they are non-ZK; the final proof is a ZK proof of the same +//! circuit name as the unchunked C4. + +use super::c2_chain::{load_compiled, prove_circuit}; +use crate::circuits::utils::bytes_to_field_strings; +use crate::circuits::vk; +use crate::error::ZkError; +use crate::prover::ZkProver; +use crate::witness::CompiledCircuit; +use e3_events::{CircuitName, CircuitVariant, Proof}; +use e3_zk_config::dkg::share_decryption::Configs; +use e3_zk_witness::dkg::share_decryption::{Inputs, ShareDecryptionCircuitData}; +use e3_zk_witness::dkg::share_decryption_chain::LimbChain; +use serde_json::{json, Value}; + +/// The limb circuits of the final C4 circuit, loaded for proving: each limb's compiled program and +/// its `default` key, in limb order. +pub struct LimbCircuits(Vec<(CircuitName, CompiledCircuit, vk::VkArtifacts)>); + +impl LimbCircuits { + /// Loads the limb circuits of the final C4 circuit. + pub fn load(prover: &ZkProver, artifacts_dir: &str) -> Result { + let default_dir = prover.circuits_dir(CircuitVariant::Default, artifacts_dir); + super::chain_keys::chunk_circuits(CircuitName::DkgShareDecryption) + .expect("the final C4 circuit is chunked") + .iter() + .map(|&circuit| { + Ok(( + circuit, + load_compiled(prover, circuit, CircuitVariant::Default, artifacts_dir)?, + vk::load_vk_artifacts(&default_dir, circuit)?, + )) + }) + .collect::>() + .map(Self) + } +} + +/// Proves the limb chain of C4 for `input` with `limbs` and returns the final circuit's inputs: the +/// expected commitments, plus the limb keys, proofs and links. +pub fn final_share_decryption_inputs( + prover: &ZkProver, + config: &Configs, + input: &ShareDecryptionCircuitData, + limbs: &LimbCircuits, + e3_id: &str, + artifacts_dir: &str, +) -> Result { + let inputs = Inputs::compute(config, input) + .map_err(|e| ZkError::InputsGenerationFailed(e.to_string()))?; + let chain = LimbChain::compute(config, &inputs) + .map_err(|e| ZkError::InputsGenerationFailed(e.to_string()))?; + if limbs.0.len() != chain.limbs.len() { + return Err(ZkError::InvalidInput(format!( + "C4 has {} limb circuits for {} limbs", + limbs.0.len(), + chain.limbs.len() + ))); + } + + let mut limb_vks = Vec::with_capacity(limbs.0.len()); + let mut limb_key_hashes = Vec::with_capacity(limbs.0.len()); + let mut limb_proofs = Vec::with_capacity(limbs.0.len()); + let mut limb_links = Vec::with_capacity(limbs.0.len()); + for (l, (limb, (circuit, compiled, key))) in chain.limbs.iter().zip(&limbs.0).enumerate() { + let job_id = format!("{e3_id}-c4-limb-{l}"); + let proof = prove_circuit( + prover, + *circuit, + compiled, + CircuitVariant::Default, + &limb.to_json(), + &job_id, + artifacts_dir, + )?; + let _ = prover.cleanup(&job_id); + // Public: the limb's H commitments, then `h_in` and its output. + let publics = bytes_to_field_strings(&proof.public_signals)?; + limb_vks.push(&key.verification_key); + limb_key_hashes.push(&key.key_hash); + limb_proofs.push(bytes_to_field_strings(&proof.data)?); + limb_links.push(publics[publics.len() - 2..].to_vec()); + } + + let mut final_inputs = inputs.to_json(); + let fields = final_inputs + .as_object_mut() + .expect("C4 inputs serialize as an object"); + fields.remove("decrypted_shares"); + fields.insert("limb_vks".into(), json!(limb_vks)); + fields.insert("limb_key_hashes".into(), json!(limb_key_hashes)); + fields.insert("limb_proofs".into(), json!(limb_proofs)); + fields.insert("limb_links".into(), json!(limb_links)); + Ok(final_inputs) +} + +/// Proves C4 for `input` as a limb chain and returns the final proof. +pub fn prove_share_decryption_chain( + prover: &ZkProver, + config: &Configs, + input: &ShareDecryptionCircuitData, + e3_id: &str, + variant: CircuitVariant, + artifacts_dir: &str, +) -> Result { + let limbs = LimbCircuits::load(prover, artifacts_dir)?; + let final_inputs = + final_share_decryption_inputs(prover, config, input, &limbs, e3_id, artifacts_dir)?; + let circuit = CircuitName::DkgShareDecryption; + let compiled = load_compiled(prover, circuit, variant, artifacts_dir)?; + prove_circuit( + prover, + circuit, + &compiled, + variant, + &final_inputs, + e3_id, + artifacts_dir, + ) +} diff --git a/crates/zk/prover/src/circuits/aggregation/chain_keys.rs b/crates/zk/prover/src/circuits/aggregation/chain_keys.rs index b44993b7a9..b237a67cdf 100644 --- a/crates/zk/prover/src/circuits/aggregation/chain_keys.rs +++ b/crates/zk/prover/src/circuits/aggregation/chain_keys.rs @@ -4,10 +4,10 @@ // without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. -//! Key trees of the chunked circuits. A final C2 proof verifies its chunk proofs against keys the -//! prover passes and exposes their hash as its last public field, so the proof alone does not pin -//! them. `c2ab_fold` anchors the hash in the VK tree for the on-chain path; a peer verifying a C2 -//! directly compares it here. +//! Key trees of the chunked circuits. A final C2 or C4 proof verifies its chunk proofs against +//! keys the prover passes and exposes their hash as its last public field, so the proof alone does +//! not pin them. `c2ab_fold` and `c4ab_fold` anchor the hash in the VK tree for the on-chain path; +//! a peer verifying a C2 or C4 directly compares it here. use crate::circuits::utils::bytes_to_field_strings; use crate::circuits::vk; @@ -28,6 +28,11 @@ pub fn chunk_circuits(final_circuit: CircuitName) -> Option<&'static [CircuitNam CircuitName::ESmShareComputationChain, CircuitName::ESmShareComputationChainLast, ]), + CircuitName::DkgShareDecryption => Some(&[ + CircuitName::DkgShareDecryptionLimb0, + CircuitName::DkgShareDecryptionLimb1, + CircuitName::DkgShareDecryptionLimb2, + ]), _ => None, } } diff --git a/crates/zk/prover/src/circuits/aggregation/mod.rs b/crates/zk/prover/src/circuits/aggregation/mod.rs index bd5573b7c2..6391accf91 100644 --- a/crates/zk/prover/src/circuits/aggregation/mod.rs +++ b/crates/zk/prover/src/circuits/aggregation/mod.rs @@ -8,6 +8,7 @@ pub mod c2_chain; pub mod c3_chonk; +pub mod c4_chain; pub mod c6_chonk; pub mod chain_keys; pub mod chonk_stack; diff --git a/crates/zk/prover/src/circuits/dkg/share_decryption.rs b/crates/zk/prover/src/circuits/dkg/share_decryption.rs index 172c0cf951..14d34128b8 100644 --- a/crates/zk/prover/src/circuits/dkg/share_decryption.rs +++ b/crates/zk/prover/src/circuits/dkg/share_decryption.rs @@ -6,7 +6,7 @@ use crate::traits::Provable; use e3_zk_config::CircuitName; -use e3_zk_witness::dkg::share_decryption::{Inputs, ShareDecryptionCircuitData}; +use e3_zk_witness::dkg::share_decryption::ShareDecryptionCircuitData; use crate::ZkError; @@ -19,9 +19,60 @@ impl Provable for ShareDecryptionCircuit { config: &Self::Config, input: &Self::Input, ) -> Result { - let inputs = Inputs::compute(config, input) - .map_err(|e| ZkError::InputsGenerationFailed(e.to_string()))?; - crate::circuits::utils::inputs_json_to_input_map(&inputs.to_json()) + let _ = (config, input); + Err(ZkError::InputsGenerationFailed( + "C4 is proven as a limb chain; its final inputs need the limb proofs".into(), + )) + } + + /// Proves the limb chain and the final C4 proof (see + /// [`crate::circuits::aggregation::c4_chain`]). + fn prove_with_variant( + &self, + prover: &crate::ZkProver, + config: &Self::Config, + input: &Self::Input, + e3_id: &str, + variant: e3_events::CircuitVariant, + artifacts_dir: &str, + ) -> Result { + crate::circuits::aggregation::c4_chain::prove_share_decryption_chain( + prover, + config, + input, + e3_id, + variant, + artifacts_dir, + ) + } + + /// Verifies the final C4 proof and its limb key tree. The final circuit verifies its limb + /// proofs against keys it only exposes as a hash, so a valid outer proof alone does not show + /// the limbs ran this node's limb circuits. + fn verify_with_variant( + &self, + prover: &crate::ZkProver, + proof: &e3_events::Proof, + e3_id: &str, + party_id: u64, + variant: e3_events::CircuitVariant, + artifacts_dir: &str, + ) -> Result { + if !self.valid_circuits().contains(&proof.circuit) { + return Err(ZkError::VerifyFailed(format!( + "circuit mismatch: expected one of {:?}, got {}", + self.valid_circuits(), + proof.circuit + ))); + } + Ok( + prover.verify_proof_with_variant(proof, e3_id, party_id, variant, artifacts_dir)? + && crate::circuits::aggregation::chain_keys::check_key_tree( + prover, + proof, + artifacts_dir, + )?, + ) } type Config = e3_zk_config::dkg::share_decryption::Configs; diff --git a/crates/zk/prover/src/commitment_links/c4a_to_c6.rs b/crates/zk/prover/src/commitment_links/c4a_to_c6.rs index a48cf2e3d3..d290ca544c 100644 --- a/crates/zk/prover/src/commitment_links/c4a_to_c6.rs +++ b/crates/zk/prover/src/commitment_links/c4a_to_c6.rs @@ -6,7 +6,8 @@ //! C4a (SK share decryption) → C6 (ThresholdShareDecryption) sk_commitment link. //! -//! C4a outputs a single `commitment` field (the sk_commitment). +//! C4a returns its `commitment` (the sk_commitment), then its limb-key tree, after its public +//! `expected_commitments`. //! C6 takes `expected_sk_commitment` as a public input. use super::{CommitmentLink, FieldValue, LinkScope}; @@ -67,8 +68,9 @@ mod tests { #[test] fn extract_commitment_from_c4a() { let link = C4aToC6SkCommitmentLink; - // C4 has no public inputs, just one output: commitment - let signals = make_field(42); + // C4's public inputs (the expected share commitments) come first; its outputs are the + // commitment, then its limb-key tree. + let signals = [make_field(7), make_field(42), make_field(1)].concat(); let values = link.extract_source_values(&signals); assert_eq!(values.len(), 1); assert_eq!(values[0], make_field(42)); diff --git a/crates/zk/prover/src/commitment_links/c4b_to_c6.rs b/crates/zk/prover/src/commitment_links/c4b_to_c6.rs index dd5cee0376..251a60f5db 100644 --- a/crates/zk/prover/src/commitment_links/c4b_to_c6.rs +++ b/crates/zk/prover/src/commitment_links/c4b_to_c6.rs @@ -6,7 +6,8 @@ //! C4b (ESM share decryption) → C6 (ThresholdShareDecryption) e_sm_commitment link. //! -//! C4b outputs a single `commitment` field (the e_sm_commitment). +//! C4b returns its `commitment` (the e_sm_commitment), then its limb-key tree, after its public +//! `expected_commitments`. //! C6 takes `expected_e_sm_commitment` as a public input. use super::{CommitmentLink, FieldValue, LinkScope}; @@ -67,7 +68,9 @@ mod tests { #[test] fn extract_commitment_from_c4b() { let link = C4bToC6ESmCommitmentLink; - let signals = make_field(77); + // C4's public inputs (the expected share commitments) come first; its outputs are the + // commitment, then its limb-key tree. + let signals = [make_field(7), make_field(77), make_field(1)].concat(); let values = link.extract_source_values(&signals); assert_eq!(values.len(), 1); assert_eq!(values[0], make_field(77)); diff --git a/crates/zk/prover/src/lib.rs b/crates/zk/prover/src/lib.rs index fcbb16d734..57345a9e3b 100644 --- a/crates/zk/prover/src/lib.rs +++ b/crates/zk/prover/src/lib.rs @@ -32,6 +32,7 @@ pub use domain::commitment_links::default_links; pub use backend::{BBPath, SetupStatus, ZkBackend}; pub use circuits::aggregation::c2_chain::{final_circuit_inputs, ChunkCircuits}; pub use circuits::aggregation::c3_chonk::generate_c3_chonk_chain; +pub use circuits::aggregation::c4_chain::{final_share_decryption_inputs, LimbCircuits}; pub use circuits::aggregation::c6_chonk::generate_c6_chonk_root; pub use circuits::aggregation::chain_keys::chunk_circuits; pub use circuits::aggregation::node_dkg_fold::{ diff --git a/crates/zk/prover/src/request_execution.rs b/crates/zk/prover/src/request_execution.rs index e8f525a75a..828a09af75 100644 --- a/crates/zk/prover/src/request_execution.rs +++ b/crates/zk/prover/src/request_execution.rs @@ -1203,8 +1203,8 @@ fn prove_synchronized_leaf Result { - if profile.protocol() == e3_fhe_params::BfvDecryptionProtocol::SecretShared - && ShareComputationCircuit + if profile.protocol() == e3_fhe_params::BfvDecryptionProtocol::SecretShared { + if ShareComputationCircuit .valid_circuits() .contains(&proof.circuit) - { - return ShareComputationCircuit.verify(prover, proof, e3_id_str, party_id, artifacts_dir); + { + return ShareComputationCircuit.verify( + prover, + proof, + e3_id_str, + party_id, + artifacts_dir, + ); + } + if ShareDecryptionCircuit + .valid_circuits() + .contains(&proof.circuit) + { + return ShareDecryptionCircuit.verify( + prover, + proof, + e3_id_str, + party_id, + artifacts_dir, + ); + } } prover.verify_proof(proof, e3_id_str, party_id, artifacts_dir) } @@ -1354,7 +1373,14 @@ fn handle_verify_share_decryption_proofs( } let proof = &signed_proof.payload.proof; - match prover.verify_proof(proof, &e3_id_str, sender, &artifacts_dir) { + match zk_verify_share_proof_bundle( + prover, + req.params_profile, + proof, + &e3_id_str, + sender, + &artifacts_dir, + ) { Ok(true) => {} Ok(false) => { info!( diff --git a/crates/zk/prover/tests/common/helpers.rs b/crates/zk/prover/tests/common/helpers.rs index f173eb46e3..0508cf5c6a 100644 --- a/crates/zk/prover/tests/common/helpers.rs +++ b/crates/zk/prover/tests/common/helpers.rs @@ -146,13 +146,14 @@ pub async fn setup_compiled_circuit_for_committee( } } -/// Sets up both final C2 circuits in every variant and the four chunk circuits they are proven -/// through in the `default` variant only, as `pnpm build:circuits` publishes them. +/// Sets up the final C2 and C4 circuits in every variant and the chunk and limb circuits they are +/// proven through in the `default` variant only, as `pnpm build:circuits` publishes them. #[allow(dead_code)] pub async fn setup_chunked_dkg_circuits(backend: &ZkBackend) { for circuit in [ CircuitName::SkShareComputation, CircuitName::ESmShareComputation, + CircuitName::DkgShareDecryption, ] { setup_compiled_circuit(backend, circuit.group(), circuit.as_str()).await; } @@ -163,6 +164,9 @@ pub async fn setup_chunked_dkg_circuits(backend: &ZkBackend) { CircuitName::SkShareComputationChainLast, CircuitName::ESmShareComputationChain, CircuitName::ESmShareComputationChainLast, + CircuitName::DkgShareDecryptionLimb0, + CircuitName::DkgShareDecryptionLimb1, + CircuitName::DkgShareDecryptionLimb2, ], ) .await; diff --git a/crates/zk/prover/tests/local_e2e_tests.rs b/crates/zk/prover/tests/local_e2e_tests.rs index d06d050bbe..01e1060be4 100644 --- a/crates/zk/prover/tests/local_e2e_tests.rs +++ b/crates/zk/prover/tests/local_e2e_tests.rs @@ -342,7 +342,7 @@ async fn setup_c4_c6_e2e_test() -> Option<( require_minimum_circuits()?; let (backend, temp) = setup_test_prover(&bb).await; - setup_compiled_circuit(&backend, "dkg", "share_decryption").await; + setup_chunked_dkg_circuits(&backend).await; setup_compiled_circuit(&backend, "threshold", "share_decryption").await; let config = e3_zk_config::dkg::share_decryption::Configs::for_preset(preset).ok()?; diff --git a/crates/zk/prover/tests/node_fold_correlated_e2e_tests.rs b/crates/zk/prover/tests/node_fold_correlated_e2e_tests.rs index 780c4fa231..8a8a68f27e 100644 --- a/crates/zk/prover/tests/node_fold_correlated_e2e_tests.rs +++ b/crates/zk/prover/tests/node_fold_correlated_e2e_tests.rs @@ -353,7 +353,7 @@ async fn node_fold_correlated_sparse_self_slot_proves_and_verifies() { let artifacts_dir = preset.artifacts_dir_for_committee(CiphernodesCommitteeSize::Minimum.as_str()); - for name in ["pk", "share_encryption", "share_decryption"] { + for name in ["pk", "share_encryption"] { setup_compiled_circuit(&backend, "dkg", name).await; } setup_chunked_dkg_circuits(&backend).await; diff --git a/crates/zk/witness/src/commitments.rs b/crates/zk/witness/src/commitments.rs index 8dd05bea9e..a0eb676e02 100644 --- a/crates/zk/witness/src/commitments.rs +++ b/crates/zk/witness/src/commitments.rs @@ -82,6 +82,14 @@ pub(crate) const DS_SHARE_COMPUTATION_CHAIN_OUTPUT: [u8; 64] = [ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; +/// String: "SHARE_DECRYPTION_CHAIN_STATE" +pub(crate) const DS_SHARE_DECRYPTION_CHAIN_STATE: [u8; 64] = [ + 0x53, 0x48, 0x41, 0x52, 0x45, 0x5f, 0x44, 0x45, 0x43, 0x52, 0x59, 0x50, 0x54, 0x49, 0x4f, 0x4e, + 0x5f, 0x43, 0x48, 0x41, 0x49, 0x4e, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +]; + /// String: "PK_AGGREGATION" const DS_PK_AGGREGATION: [u8; 64] = [ 0x50, 0x4b, 0x5f, 0x41, 0x47, 0x47, 0x52, 0x45, 0x47, 0x41, 0x54, 0x49, 0x4f, 0x4e, 0x00, 0x00, @@ -100,7 +108,7 @@ const DS_CIPHERTEXT: [u8; 64] = [ ]; /// String: "AGGREGATED_SHARES" -const DS_AGGREGATED_SHARES: [u8; 64] = [ +pub(crate) const DS_AGGREGATED_SHARES: [u8; 64] = [ 0x41, 0x47, 0x47, 0x52, 0x45, 0x47, 0x41, 0x54, 0x45, 0x44, 0x5f, 0x53, 0x48, 0x41, 0x52, 0x45, 0x53, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, diff --git a/crates/zk/witness/src/dkg/mod.rs b/crates/zk/witness/src/dkg/mod.rs index ffcf80619f..7367ff1d5b 100644 --- a/crates/zk/witness/src/dkg/mod.rs +++ b/crates/zk/witness/src/dkg/mod.rs @@ -8,4 +8,5 @@ pub mod pk; pub mod share_computation; pub mod share_computation_chain; pub mod share_decryption; +pub mod share_decryption_chain; pub mod share_encryption; diff --git a/crates/zk/witness/src/dkg/share_decryption_chain.rs b/crates/zk/witness/src/dkg/share_decryption_chain.rs new file mode 100644 index 0000000000..1c77e8ce96 --- /dev/null +++ b/crates/zk/witness/src/dkg/share_decryption_chain.rs @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: LGPL-3.0-only +// +// This file is provided WITHOUT ANY WARRANTY; +// without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR PURPOSE. + +//! Witnesses for chunked share decryption (C4): the limb chain of +//! `circuits/lib/src/core/dkg/share_decryption_chain.nr`. +//! +//! Limb `l` opens every honest party's limb-`l` share commitment and continues the aggregate +//! commitment's sponge. Replaying the sponge natively gives each limb's carried state and input +//! hash, and the aggregate commitment the last limb returns. + +use super::share_computation_chain::field_to_string; +use super::share_decryption::Inputs; +use crate::commitments::{ + compute_commitments, packer, DS_AGGREGATED_SHARES, DS_SHARE_DECRYPTION_CHAIN_STATE, +}; +use crate::encoding::poly_coefficients_to_toml_json; +use crate::WitnessError; +use ark_bn254::Fr as Field; +use e3_polynomial::Polynomial; +use e3_safe::{absorb_from, initial_state, squeeze_one_after_absorb, ABSORB_FLAG, STATE_SIZE}; +use e3_zk_config::dkg::share_decryption::Configs; +use num_bigint::BigInt; +use num_traits::Signed; + +/// One limb's witness. +#[derive(Debug, Clone)] +pub struct LimbChunk { + /// `expected_commitments[party][limb]` for this limb. + pub expected_commitments: Vec, + /// `decrypted_shares[party][limb]` for this limb. + pub decrypted_shares: Vec>, + pub h_in: Field, + pub state_in: [Field; STATE_SIZE], +} + +impl LimbChunk { + pub fn to_json(&self) -> serde_json::Value { + serde_json::json!({ + "expected_commitments": self + .expected_commitments + .iter() + .map(|c| c.to_string()) + .collect::>(), + "h_in": field_to_string(&self.h_in), + "decrypted_shares": self + .decrypted_shares + .iter() + .map(|share| poly_coefficients_to_toml_json(share)) + .collect::>(), + "state_in": self.state_in.iter().map(field_to_string).collect::>(), + }) + } +} + +/// The limb chain and the aggregate commitment it ends on. +#[derive(Debug, Clone)] +pub struct LimbChain { + pub limbs: Vec, + /// Hash of the fresh aggregate sponge: limb 0's `h_in`. + pub start_hash: Field, + /// The commitment the last limb returns (the unchunked C4 output). + pub aggregate: Field, +} + +impl LimbChain { + pub fn compute(config: &Configs, inputs: &Inputs) -> Result { + let moduli = config.threshold_params.moduli(); + let num_moduli = moduli.len(); + let degree = config.threshold_params.degree(); + let agg_bit = config.bits.agg_bit; + let nibble_bits = agg_bit.div_ceil(4) * 4; + let group = (254 / (nibble_bits + 4)) as usize; + let io_pattern = [ + ABSORB_FLAG | (num_moduli * degree.div_ceil(group)) as u32, + 1, + ]; + + let mut state = initial_state(io_pattern, DS_AGGREGATED_SHARES); + let mut pos = 0; + let start_hash = limb_state_hash(&state); + let mut limbs = Vec::with_capacity(num_moduli); + for (limb, &q) in moduli.iter().enumerate() { + let shares: Vec> = inputs + .decrypted_shares + .iter() + .map(|party| party[limb].clone()) + .collect(); + if shares.iter().any(|share| share.len() != degree) { + return Err(WitnessError::Other(format!( + "C4 limb {limb} expects {degree} coefficients per share" + ))); + } + limbs.push(LimbChunk { + expected_commitments: inputs + .expected_commitments + .iter() + .map(|party| party[limb].clone()) + .collect(), + decrypted_shares: shares.clone(), + h_in: limb_state_hash(&state), + state_in: state, + }); + + // C4's normalization: sum the shares, center mod q, highest degree first. + let q = BigInt::from(q); + let half = (&q - 1) / 2; + let mut normalized: Vec = (0..degree) + .map(|i| { + let sum: BigInt = shares.iter().map(|share| &share[i]).sum(); + let mut r = sum % &q; + if r.is_negative() { + r += &q; + } + if r > half { + r - &q + } else { + r + } + }) + .collect(); + normalized.reverse(); + let carriers = packer(&Polynomial::new(normalized), agg_bit); + (state, pos) = absorb_from(state, pos, &carriers); + } + + Ok(LimbChain { + limbs, + start_hash, + aggregate: squeeze_one_after_absorb(io_pattern, state, pos), + }) + } +} + +/// Matches Noir `limb_state_hash`. +pub fn limb_state_hash(state: &[Field; STATE_SIZE]) -> Field { + compute_commitments( + state.to_vec(), + DS_SHARE_DECRYPTION_CHAIN_STATE, + [ABSORB_FLAG | STATE_SIZE as u32, 1], + )[0] +} diff --git a/crates/zk/witness/tests/dkg_samples.rs b/crates/zk/witness/tests/dkg_samples.rs index ac92899d81..41e8ce9954 100644 --- a/crates/zk/witness/tests/dkg_samples.rs +++ b/crates/zk/witness/tests/dkg_samples.rs @@ -428,3 +428,74 @@ mod share_computation_chain { assert!(error.to_string().contains("per share row"), "{error}"); } } + +mod share_decryption_chain { + use ark_ff::{BigInteger, PrimeField}; + use e3_committee::CiphernodesCommitteeSize; + use e3_fhe_params::BfvPreset; + use e3_polynomial::{CrtPolynomial, Polynomial}; + use e3_zk_config::dkg::share_decryption::Configs; + use e3_zk_config::DkgInputType; + use e3_zk_witness::commitments::compute_aggregated_shares_commitment; + use e3_zk_witness::dkg::share_decryption::Inputs; + use e3_zk_witness::dkg::share_decryption_chain::LimbChain; + use num_bigint::{BigInt, BigUint}; + use num_traits::Signed; + + /// The limb chain ends on the aggregate commitment of the normalized limbs, as one absorb. + #[test] + fn limb_chain_aggregate_equals_the_unchunked_commitment() { + let preset = BfvPreset::InsecureThreshold64; + let committee = CiphernodesCommitteeSize::Micro.values(); + let config = Configs::for_preset(preset).unwrap(); + for input_type in [DkgInputType::SecretKey, DkgInputType::SmudgingNoise] { + let sample = e3_zk_samples::dkg::share_decryption::generate( + &config, + preset, + committee.clone(), + input_type, + ) + .unwrap(); + let inputs = Inputs::compute(&config, &sample).unwrap(); + let chain = LimbChain::compute(&config, &inputs).unwrap(); + assert_eq!(chain.limbs.len(), config.threshold_params.moduli().len()); + assert_eq!(chain.limbs[0].h_in, chain.start_hash); + + let degree = config.threshold_params.degree(); + let limbs: Vec = config + .threshold_params + .moduli() + .iter() + .enumerate() + .map(|(limb, &q)| { + let q = BigInt::from(q); + let mut coeffs: Vec = (0..degree) + .map(|i| { + let sum: BigInt = + inputs.decrypted_shares.iter().map(|p| &p[limb][i]).sum(); + let mut r = sum % &q; + if r.is_negative() { + r += &q; + } + if r > (&q - 1) / 2 { + r - &q + } else { + r + } + }) + .collect(); + coeffs.reverse(); + Polynomial::new(coeffs) + }) + .collect(); + let expected = compute_aggregated_shares_commitment( + &CrtPolynomial::new(limbs), + config.bits.agg_bit, + ); + let got = BigInt::from(BigUint::from_bytes_le( + &chain.aggregate.into_bigint().to_bytes_le(), + )); + assert_eq!(got, expected, "{input_type:?}"); + } + } +} diff --git a/docs/architecture/proof-statements.md b/docs/architecture/proof-statements.md index 808740d281..0eeed4a1d6 100644 --- a/docs/architecture/proof-statements.md +++ b/docs/architecture/proof-statements.md @@ -16,7 +16,7 @@ audit remediation is not completeness evidence. | C1 | Threshold public share derives from SK; integer smudging bound is enforced; output commits to SK, PK, and ESM residues. | | C2a/C2b | Correct Shamir splitting of SK/ESM, linked to C1 secrets. Proven as a chunk chain whose final proof keeps C2's commitments. | | C3a/C3b | Correct recipient encryption of those shares under the C0 key, linked to C2 messages. | -| C4a/C4b | The H selected received shares open their C2 commitments and form the normalized summed SK/ESM anchors. | +| C4a/C4b | The H selected received shares open their C2 commitments and form the normalized summed SK/ESM anchors. Proven one CRT limb per proof under a final proof that keeps C4's commitment. | | C5 | Aggregate PK derives from exactly the H canonical dealer shares. | | C6 | The decryption share derives from the anchored SK/ESM and ciphertext, in one canonical E3 domain. Full `d` enters Fiat-Shamir; the C7-facing commitment binds the configured native tail. | | C7 | Exactly T+1 distinct ordered shares reconstruct every claimed message coefficient, including zeros. | @@ -529,7 +529,8 @@ C2b chain = hash(e_sm_share_computation_chain, e_sm_share_computation_chain_las C2 tree = hash(C2a, C2a chain, C2b, C2b chain) C3 chain = hash(c3_chonk_accumulate, c3_chonk_tube, hiding kernel, C3, app, init, tail) C3 tree = hash(C3a chain, C3b chain) -C4 tree = hash(C4a, C4b) +C4 chain = hash(share_decryption_limb_0, share_decryption_limb_1, share_decryption_limb_2) +C4 tree = hash(C4a, C4 chain, C4b, C4 chain) node tree = hash(C0, C1, c2ab_fold, C2 tree, c3ab_fold, C3 tree, c4ab_fold, C4 tree) nodes tree = hash(nodes_fold, nodes_fold_kernel, node_fold, node tree) C6 chain = hash(c6_chonk_tube, c6_chonk_tube, hiding kernel, C6, app, init, tail) @@ -584,6 +585,22 @@ keys (`zk_verify_share_proof_bundle`); the proof alone does not pin them. The chunk circuits are proven non-ZK and only verified inside the final circuit, so the build publishes them in the `default` variant alone; the final circuits keep every variant. +## Chunked C4 + +C4's openings and sums are independent per CRT limb, and the aggregate commitment C6 reads is one +SAFE sponge over the normalized limbs in order. So limb `l`'s proof runs C4's statement for that +limb (`aggregate_limb`: open every honest party's limb-`l` share commitment with checked packing, +sum, reverse and center) and continues the aggregate sponge from the state limb `l - 1` left; the +last limb squeezes the unchunked C4 commitment. Each limb packs into its own carriers and can start +mid-block, and its start position follows from the limb index, so each limb has its own circuit. + +The final `share_decryption` circuit verifies the three limb proofs, each with its own key, links +them from the fresh aggregate sponge (`DS_SHARE_DECRYPTION_CHAIN_STATE`), and returns the aggregate +commitment then the hash of the limb keys. `c4ab_fold` folds that hash into the VK tree; a peer +verifying a C4 directly compares it with its own limb keys (`zk_verify_share_proof_bundle`). The +limb circuits are proven non-ZK and only verified inside the final circuit, so the build publishes +them in the `default` variant alone. + ## Evidence and change review - [Noir helpers](../../circuits/lib/src/math/) and diff --git a/docs/pages/build/noir-circuits.mdx b/docs/pages/build/noir-circuits.mdx index 8c2bdb59bb..4d602cfbfa 100644 --- a/docs/pages/build/noir-circuits.mdx +++ b/docs/pages/build/noir-circuits.mdx @@ -57,6 +57,9 @@ All binary packages depend on one shared library. The Nargo package name of the + + + @@ -96,17 +99,17 @@ All binary packages depend on one shared library. The Nargo package name of the -| Directory | Contents | -| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `lib/src/math` | Polynomials, the SAFE sponge (Poseidon2 and Keccak256), modular arithmetic, and the commitment functions with their domain separators. | -| `lib/src/core` | The circuit logic that the binary packages call. `core/dkg` holds C0 and C2 to C4. `core/threshold` holds C1, C5, the two user-encryption legs, C6, and C7. | -| `lib/src/configs` | The BFV presets (`insecure`, `secure`) and the committee sizes. `default/mod.nr` and `committee/active.nr` select the active pair. The build script writes both files. | -| `bin/dkg` | Nargo workspace: `pk` (C0), `sk_share_computation` (C2a), `e_sm_share_computation` (C2b), `share_encryption` (C3), `share_decryption` (C4), and the C2 chunk circuits those two verify. | -| `bin/threshold` | Nargo workspace: `pk_generation` (C1), `pk_aggregation` (C5), `user_data_encryption` (P3), `share_decryption` (C6), `decrypted_shares_aggregation` (C7). | -| `bin/chonk` | Nargo workspace: the app and three kernels of the C3 and C6 Chonk stacks. | -| `bin/recursive_aggregation` | Twelve packages that fold proofs together. The two final circuits are `dkg_aggregator` and `decryption_aggregator`. | -| `bin/config` | Package `validate_secure_configs`. It checks the secure preset constants (CRT moduli and bounds). | -| `benchmarks` | Timing scripts and reports. | +| Directory | Contents | +| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `lib/src/math` | Polynomials, the SAFE sponge (Poseidon2 and Keccak256), modular arithmetic, and the commitment functions with their domain separators. | +| `lib/src/core` | The circuit logic that the binary packages call. `core/dkg` holds C0 and C2 to C4. `core/threshold` holds C1, C5, the two user-encryption legs, C6, and C7. | +| `lib/src/configs` | The BFV presets (`insecure`, `secure`) and the committee sizes. `default/mod.nr` and `committee/active.nr` select the active pair. The build script writes both files. | +| `bin/dkg` | Nargo workspace: `pk` (C0), `sk_share_computation` (C2a), `e_sm_share_computation` (C2b), `share_encryption` (C3), `share_decryption` (C4), and the C2 chunk and C4 limb circuits those verify. | +| `bin/threshold` | Nargo workspace: `pk_generation` (C1), `pk_aggregation` (C5), `user_data_encryption` (P3), `share_decryption` (C6), `decrypted_shares_aggregation` (C7). | +| `bin/chonk` | Nargo workspace: the app and three kernels of the C3 and C6 Chonk stacks. | +| `bin/recursive_aggregation` | Twelve packages that fold proofs together. The two final circuits are `dkg_aggregator` and `decryption_aggregator`. | +| `bin/config` | Package `validate_secure_configs`. It checks the secure preset constants (CRT moduli and bounds). | +| `benchmarks` | Timing scripts and reports. | The package directory names match the `CircuitName` enum in `crates/zk/config/src/circuit.rs`. For example, `CircuitName::PkBfv` is `pk`, and `CircuitName::DkgAggregator` is `dkg_aggregator`. The diff --git a/docs/pages/internals/commitment-consistency.mdx b/docs/pages/internals/commitment-consistency.mdx index 361a3218ac..050168c1b2 100644 --- a/docs/pages/internals/commitment-consistency.mdx +++ b/docs/pages/internals/commitment-consistency.mdx @@ -202,14 +202,16 @@ keys. [key_tree] <- skipped by extract_share_commitments ``` -C4 (`share_decryption`) has $H \cdot L + 1$ fields. The rows follow the accepted roster order, not -the full committee order: +C4 (`share_decryption`) has $H \cdot L + 2$ fields: the expected commitments, the aggregate +commitment and the hash of the limb keys. The rows follow the accepted roster order, not the full +committee order: ```text [expected_commitments[0][0]] ... [expected_commitments[0][L-1]] ... [expected_commitments[H-1][0]] ... [expected_commitments[H-1][L-1]] [commitment] <- aggregate, not compared +[key_tree] <- not compared ``` ### Check logic From 2dceaa2dbc415bd0ef87c85254192e64e4352f36 Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:45:07 +0000 Subject: [PATCH 02/16] docs(blueprint): follow the C4 limb chain --- scripts/blueprint/curated.mjs | 2 +- scripts/blueprint/facts/05-zk.json | 2 +- scripts/blueprint/facts/11-circuits.json | 20 ++++++++++---------- scripts/blueprint/refs/D-circuits.json | 4 ++-- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/scripts/blueprint/curated.mjs b/scripts/blueprint/curated.mjs index ea18db3e0d..5c55f3aaa2 100644 --- a/scripts/blueprint/curated.mjs +++ b/scripts/blueprint/curated.mjs @@ -607,7 +607,7 @@ function circuits() { title: 'c4ab_fold', lines: ['C4a + C4b'], mono: true, - ref: `${CIR}/recursive_aggregation/c4ab_fold/src/main.nr@30@verify_honk_proof(c4a_vk, c4a_proof`, + ref: `${CIR}/recursive_aggregation/c4ab_fold/src/main.nr@32@verify_honk_proof(c4a_vk, c4a_proof`, }, { id: 'node', diff --git a/scripts/blueprint/facts/05-zk.json b/scripts/blueprint/facts/05-zk.json index 9bcd8d3a9f..d149a2b70c 100644 --- a/scripts/blueprint/facts/05-zk.json +++ b/scripts/blueprint/facts/05-zk.json @@ -386,7 +386,7 @@ { "pattern": "enum-match", "note": "CircuitName maps static identities to artifact names without runtime dependencies.", - "ref": "crates/zk/config/src/circuit.rs@241@CircuitName::PkBfv => \"pk\"," + "ref": "crates/zk/config/src/circuit.rs@247@CircuitName::PkBfv => \"pk\"," } ], "depends_on": ["e3-committee", "e3-fhe-params", "e3-polynomial", "e3-polynomial-fhe"], diff --git a/scripts/blueprint/facts/11-circuits.json b/scripts/blueprint/facts/11-circuits.json index dc149d1255..a42a6aa2f8 100644 --- a/scripts/blueprint/facts/11-circuits.json +++ b/scripts/blueprint/facts/11-circuits.json @@ -48,7 +48,7 @@ }, { "why": "the commitment: hashes pk0 then pk1 under the DS_PK domain separator", - "ref": "circuits/lib/src/math/commitments.nr@211@pub fn compute_dkg_pk_commitment" + "ref": "circuits/lib/src/math/commitments.nr@218@pub fn compute_dkg_pk_commitment" } ], "rust_patterns": [], @@ -393,12 +393,12 @@ { "name": "public: expected_commitments", "by": "ShareDecryption::execute", - "ref": "circuits/bin/dkg/share_decryption/src/main.nr@15@expected_commitments: pub [[Field; L_THRESHOLD]; H]" + "ref": "circuits/bin/dkg/share_decryption/src/main.nr@21@expected_commitments: pub [[Field; L_THRESHOLD]; H]" }, { - "name": "private: decrypted_shares", + "name": "private: limb_proofs", "by": "ShareDecryption::execute", - "ref": "circuits/bin/dkg/share_decryption/src/main.nr@16@decrypted_shares: [[Polynomial; L_THRESHOLD]; H]" + "ref": "circuits/bin/dkg/share_decryption/src/main.nr@24@limb_proofs: [UltraHonkProof; L_THRESHOLD]" } ], "emits": [], @@ -412,20 +412,20 @@ ], "read_first": [ { - "why": "entry point: main takes the C2 commitments and the H decrypted shares and returns the aggregate commitment", - "ref": "circuits/bin/dkg/share_decryption/src/main.nr@14@fn main(" + "why": "entry point: main takes the C2 commitments and the three limb proofs, links them and returns the aggregate commitment and the limb key hash", + "ref": "circuits/bin/dkg/share_decryption/src/main.nr@20@fn main(" }, { "why": "execute: check each share, sum, normalize, then commit", - "ref": "circuits/lib/src/core/dkg/share_decryption.nr@130@pub fn execute(self, moduli: [Field; L]) -> Field" + "ref": "circuits/lib/src/core/dkg/share_decryption.nr@67@pub fn execute(self, moduli: [Field; L]) -> Field" }, { "why": "the per-share check against its C2 commitment", - "ref": "circuits/lib/src/core/dkg/share_decryption.nr@78@compute_share_encryption_commitment_from_message_checked::(" + "ref": "circuits/lib/src/core/dkg/share_decryption.nr@108@compute_share_encryption_commitment_from_message_checked::(" }, { "why": "the output commitment that C6 later opens", - "ref": "circuits/lib/src/core/dkg/share_decryption.nr@151@compute_aggregated_shares_commitment::(normalized)" + "ref": "circuits/lib/src/core/dkg/share_decryption.nr@81@compute_aggregated_shares_commitment::(normalized)" } ], "rust_patterns": [], @@ -1024,7 +1024,7 @@ }, { "why": "the commitment wrapper that every commitment goes through", - "ref": "circuits/lib/src/math/commitments.nr@143@pub fn compute_commitment(" + "ref": "circuits/lib/src/math/commitments.nr@150@pub fn compute_commitment(" }, { "why": "the negacyclic evaluation kernel used by the BFV identity checks", diff --git a/scripts/blueprint/refs/D-circuits.json b/scripts/blueprint/refs/D-circuits.json index eb6d6af316..2a65129399 100644 --- a/scripts/blueprint/refs/D-circuits.json +++ b/scripts/blueprint/refs/D-circuits.json @@ -37,8 +37,8 @@ "id": "D3", "supported": true, "refs": [ - "circuits/bin/recursive_aggregation/c4ab_fold/src/main.nr@30@verify_honk_proof(c4a_vk, c4a_proof", - "circuits/bin/recursive_aggregation/c4ab_fold/src/main.nr@31@verify_honk_proof(c4b_vk, c4b_proof" + "circuits/bin/recursive_aggregation/c4ab_fold/src/main.nr@32@verify_honk_proof(c4a_vk, c4a_proof", + "circuits/bin/recursive_aggregation/c4ab_fold/src/main.nr@33@verify_honk_proof(c4b_vk, c4b_proof" ], "line_text": [ "verify_honk_proof(c4a_vk, c4a_proof, c4a_public, c4a_key_hash);", From dba08a4fd080e684f9a3fdc10c847d6fa6e34142 Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:50:11 +0000 Subject: [PATCH 03/16] refactor(circuits): name the folded C4 length apart from C4's public length C4 now also outputs its key tree, so c4ab_fold's C4_PUBLIC_LEN is one field more than what the fold passes on. The node and nodes folds call their length C4_FOLDED_LEN, as they already do for C2. --- .../bin/recursive_aggregation/node_fold/src/main.nr | 10 ++++++---- .../bin/recursive_aggregation/nodes_fold/src/main.nr | 6 ++++-- .../nodes_fold_kernel/src/main.nr | 6 ++++-- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/circuits/bin/recursive_aggregation/node_fold/src/main.nr b/circuits/bin/recursive_aggregation/node_fold/src/main.nr index 19eedfb08a..20322138da 100644 --- a/circuits/bin/recursive_aggregation/node_fold/src/main.nr +++ b/circuits/bin/recursive_aggregation/node_fold/src/main.nr @@ -23,12 +23,14 @@ pub global C3_SLOTS: u32 = N_PARTIES * L_THRESHOLD; pub global C3AB_FOLD_PUBLIC_LEN: u32 = 2 + 1 + (6 * C3_SLOTS); /// Prefix (two inner key hashes + combined hash) before six `C3_SLOTS` columns in `c3ab_fold` public IO. pub global C3AB_PREFIX_LEN: u32 = C3AB_FOLD_PUBLIC_LEN - (6 * C3_SLOTS); -pub global C4_PUBLIC_LEN: u32 = (H * L_THRESHOLD) + 1; -pub global C4AB_FOLD_PUBLIC_LEN: u32 = 3 + (2 * C4_PUBLIC_LEN); +/// C4's public inputs as `c4ab_fold` passes them on, likewise without the key tree +/// (`c4ab_fold::C4_PUBLIC_LEN` is one field more). +pub global C4_FOLDED_LEN: u32 = (H * L_THRESHOLD) + 1; +pub global C4AB_FOLD_PUBLIC_LEN: u32 = 3 + (2 * C4_FOLDED_LEN); /// Key-hash prefix length in `c2ab_fold` / `c4ab_fold` flattened public IO. pub global C2AB_PREFIX_LEN: u32 = C2AB_FOLD_PUBLIC_LEN - (2 * C2_FOLDED_LEN); -pub global C4AB_PREFIX_LEN: u32 = C4AB_FOLD_PUBLIC_LEN - (2 * C4_PUBLIC_LEN); +pub global C4AB_PREFIX_LEN: u32 = C4AB_FOLD_PUBLIC_LEN - (2 * C4_FOLDED_LEN); /// Inner C2 / C4 column offsets inside `c2ab_public` / `c4ab_public` /// (parallel to `NF_*` in `dkg_aggregator`; keep in sync). @@ -38,7 +40,7 @@ pub global C2A_SHARES_START: u32 = C2A_INNER_START + 1; pub global C2B_SHARES_START: u32 = C2B_INNER_START + 1; pub global C4A_INNER_START: u32 = C4AB_PREFIX_LEN; -pub global C4B_INNER_START: u32 = C4AB_PREFIX_LEN + C4_PUBLIC_LEN; +pub global C4B_INNER_START: u32 = C4AB_PREFIX_LEN + C4_FOLDED_LEN; pub global SK_AGG_INDEX: u32 = C4A_INNER_START + (H * L_THRESHOLD); pub global ESM_AGG_INDEX: u32 = C4B_INNER_START + (H * L_THRESHOLD); diff --git a/circuits/bin/recursive_aggregation/nodes_fold/src/main.nr b/circuits/bin/recursive_aggregation/nodes_fold/src/main.nr index a6c19ad9a2..bda745fc79 100644 --- a/circuits/bin/recursive_aggregation/nodes_fold/src/main.nr +++ b/circuits/bin/recursive_aggregation/nodes_fold/src/main.nr @@ -22,8 +22,10 @@ pub global C2AB_FOLD_PUBLIC_LEN: u32 = 3 + (2 * C2_FOLDED_LEN); /// Must match `c3ab_fold::C3AB_FOLD_PUBLIC_LEN` (one C3 slot per party and CRT limb). pub global C3_SLOTS: u32 = N_PARTIES * L_THRESHOLD; pub global C3AB_FOLD_PUBLIC_LEN: u32 = 2 + 1 + (6 * C3_SLOTS); -pub global C4_PUBLIC_LEN: u32 = (H * L_THRESHOLD) + 1; -pub global C4AB_FOLD_PUBLIC_LEN: u32 = 3 + (2 * C4_PUBLIC_LEN); +/// C4's public inputs as `c4ab_fold` passes them on, likewise without the key tree +/// (`c4ab_fold::C4_PUBLIC_LEN` is one field more). +pub global C4_FOLDED_LEN: u32 = (H * L_THRESHOLD) + 1; +pub global C4AB_FOLD_PUBLIC_LEN: u32 = 3 + (2 * C4_FOLDED_LEN); /// Must match `node_fold::NODE_FOLD_PUBLIC_LEN`. pub global NODE_FOLD_PUBLIC_LEN: u32 = 11 + N_PARTIES + (2 * (N_PARTIES + H) * L_THRESHOLD); diff --git a/circuits/bin/recursive_aggregation/nodes_fold_kernel/src/main.nr b/circuits/bin/recursive_aggregation/nodes_fold_kernel/src/main.nr index e7ba84634c..c4d6e54a40 100644 --- a/circuits/bin/recursive_aggregation/nodes_fold_kernel/src/main.nr +++ b/circuits/bin/recursive_aggregation/nodes_fold_kernel/src/main.nr @@ -20,8 +20,10 @@ pub global C2AB_FOLD_PUBLIC_LEN: u32 = 3 + (2 * C2_FOLDED_LEN); /// Must match `c3ab_fold::C3AB_FOLD_PUBLIC_LEN` (one C3 slot per party and CRT limb). pub global C3_SLOTS: u32 = N_PARTIES * L_THRESHOLD; pub global C3AB_FOLD_PUBLIC_LEN: u32 = 2 + 1 + (6 * C3_SLOTS); -pub global C4_PUBLIC_LEN: u32 = (H * L_THRESHOLD) + 1; -pub global C4AB_FOLD_PUBLIC_LEN: u32 = 3 + (2 * C4_PUBLIC_LEN); +/// C4's public inputs as `c4ab_fold` passes them on, likewise without the key tree +/// (`c4ab_fold::C4_PUBLIC_LEN` is one field more). +pub global C4_FOLDED_LEN: u32 = (H * L_THRESHOLD) + 1; +pub global C4AB_FOLD_PUBLIC_LEN: u32 = 3 + (2 * C4_FOLDED_LEN); /// Must match `node_fold::NODE_FOLD_PUBLIC_LEN`. pub global NODE_FOLD_PUBLIC_LEN: u32 = 11 + N_PARTIES + (2 * (N_PARTIES + H) * L_THRESHOLD); From 7c5fe45a84f12dee9b9d20277d41f3e1a0de4bcd Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:15:07 +0000 Subject: [PATCH 04/16] test(zk-build): hash the C4 limb keys, not the C6 Chonk keys, in the anchor test The limb keys are VK_PATHS 29..=31; 25..=28 are the C6 Chonk keys, so the expected node tree used the wrong keys and the mutation loop counted the limb keys as C6 descendants. --- crates/zk/build/src/tests.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/zk/build/src/tests.rs b/crates/zk/build/src/tests.rs index 692cc8c9cf..251084d179 100644 --- a/crates/zk/build/src/tests.rs +++ b/crates/zk/build/src/tests.rs @@ -1541,7 +1541,7 @@ fn anchors_bind_all_descendants_in_circuit_order_and_reject_noncanonical_keys() compute_vk_hash(vec![c3_chain, c3_chain]), keys[10], { - let limbs = compute_vk_hash(vec![keys[25], keys[26], keys[27]]); + let limbs = compute_vk_hash(vec![keys[29], keys[30], keys[31]]); compute_vk_hash(vec![keys[5], limbs, keys[5], limbs]) }, ]); @@ -1562,8 +1562,8 @@ fn anchors_bind_all_descendants_in_circuit_order_and_reject_noncanonical_keys() ]; assert_eq!(vk_tree::hashes(root).unwrap(), expected); for (i, key) in keys.iter().enumerate() { - // Keys 14..=16 and 25.. are the C6 chain; every other key is under the node fold. - let c6 = usize::from((14..=16).contains(&i) || i >= 25); + // Keys 14..=16 and 25..=28 are the C6 chain; every other key is under the node fold. + let c6 = usize::from((14..=16).contains(&i) || (25..=28).contains(&i)); write(root, &key_path(i), field_bytes(Fr::from(99_u64))); let changed = vk_tree::hashes(root).unwrap(); assert_ne!(changed[c6].1, expected[c6].1, "{}", key_path(i)); From 62005398e6a7278f031c1d3cf330457a72f37d1b Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:16:16 +0000 Subject: [PATCH 05/16] test(zk-prover): pin the C4 limb key tree through both verifiers The peer C4 handler now checks the final C4's limb key tree. Run the key-tree test over C4 as well as C2, so a regression to the bare outer-proof check fails. --- .../zk/prover/src/request_execution_tests.rs | 118 ++++++++++-------- 1 file changed, 65 insertions(+), 53 deletions(-) diff --git a/crates/zk/prover/src/request_execution_tests.rs b/crates/zk/prover/src/request_execution_tests.rs index 6c76e42ae1..d0900089a3 100644 --- a/crates/zk/prover/src/request_execution_tests.rs +++ b/crates/zk/prover/src/request_execution_tests.rs @@ -728,10 +728,11 @@ async fn execution_rejects_a_native_request_without_touching_its_secret() { ); } -/// A secret-shared C2 proof passes only when its trailing key tree hashes this node's chunk keys, -/// through the public C2 verifier and the peer handler alike. A synchronized C2 has no key tree. +/// A secret-shared C2 or C4 proof passes only when its trailing key tree hashes this node's chunk +/// keys, through the public verifier and the peer handler alike. A synchronized C2 or C4 has no key +/// tree. #[test] -fn both_c2_verifiers_reject_a_key_tree_other_than_this_nodes() { +fn both_chunked_verifiers_reject_a_key_tree_other_than_this_nodes() { use ark_ff::{BigInteger, PrimeField}; use e3_fhe_params::BfvProfile; use e3_zk_config::CircuitName; @@ -760,65 +761,76 @@ fn both_c2_verifiers_reject_a_key_tree_other_than_this_nodes() { ); let prover = ZkProver::new(&backend); let artifacts_dir = "insecure-64/minimum"; - let circuit = CircuitName::SkShareComputation; - let outer = prover - .circuits_dir(CircuitVariant::Recursive, artifacts_dir) - .join(circuit.dir_path()); - fs::create_dir_all(&outer).unwrap(); - fs::write(outer.join(format!("{}.vk", circuit.as_str())), [0u8; 32]).unwrap(); - let chunks = crate::circuits::aggregation::chain_keys::chunk_circuits(circuit).unwrap(); - for (i, chunk) in chunks.iter().enumerate() { - let dir = prover - .circuits_dir(CircuitVariant::Default, artifacts_dir) - .join(chunk.dir_path()); - fs::create_dir_all(&dir).unwrap(); - fs::write(dir.join(format!("{}.vk", chunk.as_str())), [0u8; 32]).unwrap(); - fs::write( - dir.join(format!("{}.vk_hash", chunk.as_str())), - field_bytes(ark_bn254::Fr::from(i as u64 + 1)), - ) - .unwrap(); - } - let tree = e3_zk_witness::compute_vk_hash(vec![1u64.into(), 2u64.into()]); - let proof = |key_tree: ark_bn254::Fr| { - let mut signals = field_bytes(7u64.into()); - signals.extend(field_bytes(key_tree)); - Proof::new( - circuit, - ArcBytes::from_bytes(&[0u8; 8]), - ArcBytes::from_bytes(&signals), - ) - }; - let other = tree + ark_bn254::Fr::from(1u64); + for circuit in [ + CircuitName::SkShareComputation, + CircuitName::DkgShareDecryption, + ] { + let outer = prover + .circuits_dir(CircuitVariant::Recursive, artifacts_dir) + .join(circuit.dir_path()); + fs::create_dir_all(&outer).unwrap(); + fs::write(outer.join(format!("{}.vk", circuit.as_str())), [0u8; 32]).unwrap(); + let chunks = crate::circuits::aggregation::chain_keys::chunk_circuits(circuit).unwrap(); + let mut hashes = Vec::with_capacity(chunks.len()); + for (i, chunk) in chunks.iter().enumerate() { + let dir = prover + .circuits_dir(CircuitVariant::Default, artifacts_dir) + .join(chunk.dir_path()); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join(format!("{}.vk", chunk.as_str())), [0u8; 32]).unwrap(); + let hash = ark_bn254::Fr::from(i as u64 + 1); + fs::write( + dir.join(format!("{}.vk_hash", chunk.as_str())), + field_bytes(hash), + ) + .unwrap(); + hashes.push(hash); + } + let tree = e3_zk_witness::compute_vk_hash(hashes); + let proof = |key_tree: ark_bn254::Fr| { + let mut signals = field_bytes(7u64.into()); + signals.extend(field_bytes(key_tree)); + Proof::new( + circuit, + ArcBytes::from_bytes(&[0u8; 8]), + ArcBytes::from_bytes(&signals), + ) + }; + let other = tree + ark_bn254::Fr::from(1u64); - for (key_tree, accepted) in [(tree, true), (other, false)] { - let proof = proof(key_tree); - assert_eq!( - ShareComputationCircuit - .verify(&prover, &proof, "e3-1", 1, artifacts_dir) + for (key_tree, accepted) in [(tree, true), (other, false)] { + let proof = proof(key_tree); + let public = if circuit == CircuitName::DkgShareDecryption { + ShareDecryptionCircuit.verify(&prover, &proof, "e3-1", 1, artifacts_dir) + } else { + ShareComputationCircuit.verify(&prover, &proof, "e3-1", 1, artifacts_dir) + }; + assert_eq!(public.unwrap(), accepted, "{circuit}"); + assert_eq!( + zk_verify_share_proof_bundle( + &prover, + BfvProfile::SsInsecure64, + &proof, + "e3-1", + 1, + artifacts_dir + ) .unwrap(), - accepted - ); - assert_eq!( + accepted, + "{circuit}" + ); + } + assert!( zk_verify_share_proof_bundle( &prover, - BfvProfile::SsInsecure64, - &proof, + BfvProfile::SyncDecInsecure64, + &proof(other), "e3-1", 1, artifacts_dir ) .unwrap(), - accepted + "{circuit}" ); } - assert!(zk_verify_share_proof_bundle( - &prover, - BfvProfile::SyncDecInsecure64, - &proof(other), - "e3-1", - 1, - artifacts_dir - ) - .unwrap()); } From 36e616816866d0c311520a396cc8ee52c546e064 Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:18:02 +0000 Subject: [PATCH 06/16] refactor(circuits): drop the unchunked C4 struct the limb chain replaced No circuit calls ShareDecryption::execute since C4 is proven per limb; only the chain test used it as its oracle. Keep C4's role as module docs, take the one-shot commitment from aggregate_canonical_shares in the test, and point the blueprint at the limb statement and the chain check. --- circuits/lib/src/core/dkg/share_decryption.nr | 87 +++++-------------- .../src/core/dkg/share_decryption_chain.nr | 7 +- scripts/blueprint/facts/11-circuits.json | 22 ++--- 3 files changed, 34 insertions(+), 82 deletions(-) diff --git a/circuits/lib/src/core/dkg/share_decryption.nr b/circuits/lib/src/core/dkg/share_decryption.nr index ea187aee73..404e24e704 100644 --- a/circuits/lib/src/core/dkg/share_decryption.nr +++ b/circuits/lib/src/core/dkg/share_decryption.nr @@ -4,6 +4,22 @@ // without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. +//! DKG share decryption and aggregation (C4a / C4b), one CRT limb at a time. +//! +//! **Role:** Verify decrypted shares against C2 commitments and publish a commitment to the sum +//! over honest parties (run twice: sk path and e_sm path). +//! +//! **Consumes:** Per-party share commitments from C2 (sk or e_sm branch). +//! +//! **Produces:** +//! - C4a: `commit(agg_sk)` -> C6 (threshold share decryption). +//! - C4b: `commit(agg_e_sm)` -> C6 (threshold share decryption). +//! +//! [`aggregate_limb`] is C4's statement for one limb; `share_decryption_chain` proves it per limb +//! and carries the aggregate commitment's sponge between the limbs. `BIT_MSG` hashes per-share +//! plaintexts (aligned with C2). `BIT_AGG` hashes the CRT aggregate +//! (`compute_aggregated_shares_commitment`) and must match threshold C6 `BIT_SK` / `BIT_E_SM`. + use crate::math::commitments::{ compute_aggregated_shares_commitment, compute_share_encryption_commitment_from_message_checked, }; @@ -13,75 +29,12 @@ use crate::math::polynomial::Polynomial; /// Bits allowed for the carry that [`normalize_aggregated`] divides out. /// /// The aggregate is a sum of `H` coefficients, each in `[0, q)`, so the carry is at most `H`. Eight -/// bits cover every committee up to 255 members, and `execute` asserts that. It is deliberately -/// loose: the carry bound exists to keep the reduction an integer identity, not to select the -/// representative — the centered window does that — so slack costs a fraction of a gate per -/// coefficient and buys independence from the committee config. +/// bits cover every committee up to 255 members, and `aggregate_canonical_limb` asserts that. It is +/// deliberately loose: the carry bound exists to keep the reduction an integer identity, not to +/// select the representative — the centered window does that — so slack costs a fraction of a gate +/// per coefficient and buys independence from the committee config. pub global AGGREGATION_BIT_CARRY: u32 = 8; -/// DKG share decryption and aggregation (C4a / C4b). -/// -/// **Role:** Verify decrypted shares against C2 commitments and publish a commitment to the sum -/// over honest parties (run twice: sk path and e_sm path). -/// -/// **Consumes:** Per-party share commitments from C2 (sk or e_sm branch). -/// -/// **Produces:** -/// - C4a: `commit(agg_sk)` -> C6 (threshold share decryption). -/// - C4b: `commit(agg_e_sm)` -> C6 (threshold share decryption). -/// -/// `BIT_MSG` hashes per-share plaintexts (aligned with C2). `BIT_AGG` hashes the CRT aggregate -/// (`compute_aggregated_shares_commitment`) and must match threshold C6 `BIT_SK` / `BIT_E_SM`. -pub struct ShareDecryption { - /// Expected commitments to the share polynomials, produced in C2a (for C4a) or C2b (for C4b) - /// via commit_to_party_shares. Organised as [party_idx][mod_idx], covering all H honest - /// parties and L CRT moduli. - /// (public witnesses) - expected_commitments: [[Field; L]; H], - - /// Decrypted share polynomials from H honest parties. - /// Organised as [party_idx][mod_idx]. - /// (secret witnesses) - decrypted_shares: [[Polynomial; L]; H], -} - -impl ShareDecryption { - pub fn new( - expected_commitments: [[Field; L]; H], - decrypted_shares: [[Polynomial; L]; H], - ) -> Self { - ShareDecryption { expected_commitments, decrypted_shares } - } - - /// Executes the share decryption and aggregation circuit. - /// - /// Returns a commitment to the aggregated shares: - /// - C4a: commit(agg_sk), consumed by C6 in P4 - /// - C4b: commit(agg_e_sm), consumed by C6 in P4 - /// - /// `moduli` must be the threshold CRT moduli `[q_0, ..., q_{L-1}]`. - /// They are used to reverse and center the aggregated polynomials so that - /// `compute_aggregated_shares_commitment` produces the same hash as C6's - /// Rust witness (which operates on sk coefficients already reduced to `[0, q_l)` - /// and then applies `.reverse()` and `.center(&qi)` before hashing). - pub fn execute(self, moduli: [Field; L]) -> Field { - let mut normalized: [Polynomial; L] = [Polynomial::new([0; N]); L]; - for mod_idx in 0..L { - let mut commitments = [0; H]; - let mut shares = [Polynomial::new([0; N]); H]; - for party_idx in 0..H { - commitments[party_idx] = self.expected_commitments[party_idx][mod_idx]; - shares[party_idx] = self.decrypted_shares[party_idx][mod_idx]; - } - normalized[mod_idx] = - aggregate_limb::(commitments, shares, moduli[mod_idx]); - } - - // Publish commitment to the aggregate (C6 input). - compute_aggregated_shares_commitment::(normalized) - } -} - /// C4's statement for one CRT limb with modulus `q`: every honest party's decrypted share opens its /// C2 commitment, and the shares' sum, reversed and centered as C6 hashes it, is returned. /// diff --git a/circuits/lib/src/core/dkg/share_decryption_chain.nr b/circuits/lib/src/core/dkg/share_decryption_chain.nr index ba0aff84c5..6ab526371b 100644 --- a/circuits/lib/src/core/dkg/share_decryption_chain.nr +++ b/circuits/lib/src/core/dkg/share_decryption_chain.nr @@ -129,11 +129,10 @@ fn test_limbs() -> ([[Polynomial<4>; 3]; 3], [[Field; 3]; 3], Field) { ); } } - let expected = crate::core::dkg::share_decryption::ShareDecryption::<4, 3, 3, 60, 60>::new( - commitments, + let expected = crate::core::dkg::share_decryption::aggregate_canonical_shares::<4, 3, 3, 60, 60>( shares, - ) - .execute(TQ); + TQ, + ); (shares, commitments, expected) } diff --git a/scripts/blueprint/facts/11-circuits.json b/scripts/blueprint/facts/11-circuits.json index a42a6aa2f8..12100de8ae 100644 --- a/scripts/blueprint/facts/11-circuits.json +++ b/scripts/blueprint/facts/11-circuits.json @@ -392,12 +392,12 @@ "consumes": [ { "name": "public: expected_commitments", - "by": "ShareDecryption::execute", + "by": "share_decryption_limb", "ref": "circuits/bin/dkg/share_decryption/src/main.nr@21@expected_commitments: pub [[Field; L_THRESHOLD]; H]" }, { "name": "private: limb_proofs", - "by": "ShareDecryption::execute", + "by": "check_limb_chain", "ref": "circuits/bin/dkg/share_decryption/src/main.nr@24@limb_proofs: [UltraHonkProof; L_THRESHOLD]" } ], @@ -405,9 +405,9 @@ "state": [], "key_types": [ { - "name": "ShareDecryption", - "what": "H decrypted shares and their C2 commitments, aggregated per CRT limb", - "ref": "circuits/lib/src/core/dkg/share_decryption.nr@35@pub struct ShareDecryption<" + "name": "share_decryption_limb", + "what": "C4's statement for one CRT limb: open the H shares, sum, normalize and continue the aggregate commitment's sponge", + "ref": "circuits/lib/src/core/dkg/share_decryption_chain.nr@66@pub fn share_decryption_limb<" } ], "read_first": [ @@ -416,21 +416,21 @@ "ref": "circuits/bin/dkg/share_decryption/src/main.nr@20@fn main(" }, { - "why": "execute: check each share, sum, normalize, then commit", - "ref": "circuits/lib/src/core/dkg/share_decryption.nr@67@pub fn execute(self, moduli: [Field; L]) -> Field" + "why": "the chain check: the limb links start from the fresh aggregate sponge and the last limb's output is the commitment", + "ref": "circuits/lib/src/core/dkg/share_decryption_chain.nr@92@assert(links[0][0] == limb_chain_start_hash::(), \"Chain must start fresh\");" }, { "why": "the per-share check against its C2 commitment", - "ref": "circuits/lib/src/core/dkg/share_decryption.nr@108@compute_share_encryption_commitment_from_message_checked::(" + "ref": "circuits/lib/src/core/dkg/share_decryption.nr@61@compute_share_encryption_commitment_from_message_checked::(" }, { - "why": "the output commitment that C6 later opens", - "ref": "circuits/lib/src/core/dkg/share_decryption.nr@81@compute_aggregated_shares_commitment::(normalized)" + "why": "the output commitment that C6 later opens, squeezed by the last limb", + "ref": "circuits/lib/src/core/dkg/share_decryption_chain.nr@83@squeeze_one_after_absorb(aggregated_io_pattern::(), state, pos)" } ], "rust_patterns": [], "depends_on": [], - "tests": "lib/src/core/dkg/share_decryption.nr has 2 #[test] functions; run nargo test in circuits/lib. This package has none.", + "tests": "lib/src/core/dkg/share_decryption_chain.nr has 3 #[test] functions and core/dkg/share_decryption.nr has 2; run nargo test in circuits/lib. This package has none.", "unverified": [ "Generator role (each selected member proves its own aggregate) comes from docs/architecture/dkg.md, not from the circuit code." ] From 65228868d16dfb8059f42b8e525fe8ca09731bda Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:18:02 +0000 Subject: [PATCH 07/16] docs(dkg): say c4ab_fold binds each C4's limb key tree --- docs/pages/internals/dkg.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/pages/internals/dkg.mdx b/docs/pages/internals/dkg.mdx index 5e8d4f817f..f475ae049d 100644 --- a/docs/pages/internals/dkg.mdx +++ b/docs/pages/internals/dkg.mdx @@ -114,7 +114,7 @@ proofs. | `c2ab_fold` | `C2abFold` | Folds C2a and C2b and binds each C2's chunk key tree into its key hash. | | `c3_chonk_*` | `C3Chonk*` | Verifies one branch's C3 proofs in Chonk stacks of 24, then tubes and accumulates them. | | `c3ab_fold` | `C3abFold` | Closes the secret key and smudging noise C3 chains. | -| `c4ab_fold` | `C4abFold` | Folds C4a and C4b. | +| `c4ab_fold` | `C4abFold` | Folds C4a and C4b and binds each C4's limb key tree into its key hash. | | `node_fold` | `NodeFold` | Folds C0, C1, `c2ab_fold`, `c3ab_fold`, and `c4ab_fold` for one node. | | `nodes_fold`, `nodes_fold_kernel` | `NodesFold`, `NodesFoldKernel` | Folds the H `node_fold` proofs in sequence. | | `dkg_aggregator` | `DkgAggregator` | Verifies `nodes_fold` and C5. Its EVM proof goes to `publishCommittee`. | From ee5c5df151fb33d8422423281cc0890084643253 Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:19:25 +0000 Subject: [PATCH 08/16] docs(zk-prover): show the C4 limb key tree in the C2-to-C4 link layout The final C4 returns its limb key tree after the aggregate commitment. Say so in the link's layout and row comment, and end the C4 test signals with a key tree as a real final C4 does. --- crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs | 5 +++-- crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs b/crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs index 4c053d957a..36dec30fad 100644 --- a/crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs +++ b/crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs @@ -44,7 +44,8 @@ //! [expected_commitments[0][0] (32 B)] ... [expected_commitments[0][L-1]] //! [expected_commitments[1][0]] ... //! [expected_commitments[H-1][L-1]] -//! [commitment (32 B, TAIL aggregated output)] +//! [commitment (32 B, aggregated output)] +//! [key_tree (32 B, hash of the limb keys, last)] //! ``` //! //! ## Precise check @@ -216,7 +217,7 @@ fn check_exact_l_commitments( let c2_block = &source_values[c2_start..c2_end]; // C4 row for src_idx (the C2 sender): bytes [X*L*32 .. (X+1)*L*32]. - // C4 must also have the aggregated output as the last field. + // C4's outputs (the aggregate commitment, then the limb key tree) follow the rows. let c4_row_start = src_idx * l * FIELD_BYTE_LEN; let c4_row_end = c4_row_start + l * FIELD_BYTE_LEN; if target_public_signals.len() < c4_row_end + FIELD_BYTE_LEN { diff --git a/crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs b/crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs index b18f4c6295..9e601ced5e 100644 --- a/crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs +++ b/crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs @@ -27,7 +27,8 @@ fn c2_signals(share_commits: &[[u8; 32]]) -> Vec { v } -/// C4 signals: [expected_commitments row-major (party, mod)..., aggregated_commitment]. +/// Final C4 signals: [expected_commitments row-major (party, mod)..., aggregated_commitment] + +/// [key_tree]. fn c4_signals(rows: &[Vec<[u8; 32]>], aggregated: [u8; 32]) -> Vec { let mut v = Vec::new(); for row in rows { @@ -36,6 +37,7 @@ fn c4_signals(rows: &[Vec<[u8; 32]>], aggregated: [u8; 32]) -> Vec { } } v.extend_from_slice(&aggregated); + v.extend_from_slice(&make_field(KEY_TREE)); v } @@ -72,7 +74,7 @@ fn extract_skips_secret_commitment() { /// 3 parties (N=3), 2 moduli (L=2), 2 honest parties (H=2). /// C2 from party X=1, C4 for recipient R=1. /// C2_X: [p0m0,p0m1, p1m0,p1m1, p2m0,p2m1] -/// C4_R=1: rows for party 0 and party 1 = [[p0m0,p0m1],[p1m0,p1m1]] + agg +/// C4_R=1: rows for party 0 and party 1 = [[p0m0,p0m1],[p1m0,p1m1]] + agg + key tree /// check_consistency(src=1, tgt=1): C2 slot R=1 = [p1m0,p1m1] must equal C4 row X=1 = [p1m0,p1m1] #[test] fn consistency_passes_precise_l_way_check() { From a4e88daa8347540e7be22b5e43cb479b1a52892d Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:50:41 +0000 Subject: [PATCH 09/16] docs(blueprint): follow the C4_FOLDED_LEN lines in the node folds Naming C4_FOLDED_LEN added two lines to node_fold, nodes_fold and nodes_fold_kernel, which left ten blueprint references two lines short. --- scripts/blueprint/curated.mjs | 4 ++-- scripts/blueprint/facts/11-circuits.json | 2 +- scripts/blueprint/refs/D-circuits.json | 16 ++++++++-------- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/scripts/blueprint/curated.mjs b/scripts/blueprint/curated.mjs index 5c55f3aaa2..5bfbcded5c 100644 --- a/scripts/blueprint/curated.mjs +++ b/scripts/blueprint/curated.mjs @@ -618,7 +618,7 @@ function circuits() { title: 'node_fold', lines: ['one proof per member:', 'C0 · C1 · c2ab', 'c3ab · c4ab'], mono: true, - ref: `${CIR}/recursive_aggregation/node_fold/src/main.nr@109@verify_honk_proof(c0_vk, c0_proof`, + ref: `${CIR}/recursive_aggregation/node_fold/src/main.nr@111@verify_honk_proof(c0_vk, c0_proof`, }, { id: 'c5', @@ -640,7 +640,7 @@ function circuits() { title: 'nodes_fold', lines: ["all H members' node proofs"], mono: true, - ref: `${CIR}/recursive_aggregation/nodes_fold/src/main.nr@66@verify_honk_proof_non_zk(acc_vk, acc_proof`, + ref: `${CIR}/recursive_aggregation/nodes_fold/src/main.nr@68@verify_honk_proof_non_zk(acc_vk, acc_proof`, }, { id: 'dkgagg', diff --git a/scripts/blueprint/facts/11-circuits.json b/scripts/blueprint/facts/11-circuits.json index 12100de8ae..9bc510250f 100644 --- a/scripts/blueprint/facts/11-circuits.json +++ b/scripts/blueprint/facts/11-circuits.json @@ -946,7 +946,7 @@ }, { "why": "node_fold entry point: one member's C0 to C4 proofs and their same-party links", - "ref": "circuits/bin/recursive_aggregation/node_fold/src/main.nr@85@fn main(" + "ref": "circuits/bin/recursive_aggregation/node_fold/src/main.nr@87@fn main(" } ], "rust_patterns": [], diff --git a/scripts/blueprint/refs/D-circuits.json b/scripts/blueprint/refs/D-circuits.json index 2a65129399..17380d46e5 100644 --- a/scripts/blueprint/refs/D-circuits.json +++ b/scripts/blueprint/refs/D-circuits.json @@ -67,11 +67,11 @@ "id": "D5", "supported": true, "refs": [ - "circuits/bin/recursive_aggregation/node_fold/src/main.nr@109@verify_honk_proof(c0_vk, c0_proof", - "circuits/bin/recursive_aggregation/node_fold/src/main.nr@110@verify_honk_proof(c1_vk, c1_proof", - "circuits/bin/recursive_aggregation/node_fold/src/main.nr@111@verify_honk_proof_non_zk(c2ab_vk, c2ab_proof", - "circuits/bin/recursive_aggregation/node_fold/src/main.nr@112@verify_honk_proof_non_zk(c3ab_vk, c3ab_proof", - "circuits/bin/recursive_aggregation/node_fold/src/main.nr@113@verify_honk_proof_non_zk(c4ab_vk, c4ab_proof" + "circuits/bin/recursive_aggregation/node_fold/src/main.nr@111@verify_honk_proof(c0_vk, c0_proof", + "circuits/bin/recursive_aggregation/node_fold/src/main.nr@112@verify_honk_proof(c1_vk, c1_proof", + "circuits/bin/recursive_aggregation/node_fold/src/main.nr@113@verify_honk_proof_non_zk(c2ab_vk, c2ab_proof", + "circuits/bin/recursive_aggregation/node_fold/src/main.nr@114@verify_honk_proof_non_zk(c3ab_vk, c3ab_proof", + "circuits/bin/recursive_aggregation/node_fold/src/main.nr@115@verify_honk_proof_non_zk(c4ab_vk, c4ab_proof" ], "line_text": [ "verify_honk_proof(c0_vk, c0_proof, c0_public, c0_key_hash);", @@ -86,9 +86,9 @@ "id": "D6", "supported": true, "refs": [ - "circuits/bin/recursive_aggregation/nodes_fold/src/main.nr@53@inner_proofs[k],", - "circuits/bin/recursive_aggregation/nodes_fold/src/main.nr@66@verify_honk_proof_non_zk(acc_vk, acc_proof", - "circuits/bin/recursive_aggregation/nodes_fold_kernel/src/main.nr@49@inner_proofs[k]," + "circuits/bin/recursive_aggregation/nodes_fold/src/main.nr@55@inner_proofs[k],", + "circuits/bin/recursive_aggregation/nodes_fold/src/main.nr@68@verify_honk_proof_non_zk(acc_vk, acc_proof", + "circuits/bin/recursive_aggregation/nodes_fold_kernel/src/main.nr@51@inner_proofs[k]," ], "line_text": ["inner_proofs[k],", "verify_honk_proof_non_zk(acc_vk, acc_proof, acc_public_inputs, acc_key_hash);", "inner_proofs[k],"], "note": "nodes_fold verifies three node_fold proofs per step plus the previous accumulator over the H rows, and nodes_fold_kernel verifies only its three node_fold proofs." From 7a4e4ecd7065eba198ebdd36ef67cdf10e1475cc Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:50:41 +0000 Subject: [PATCH 10/16] docs(zk-benchmarks): say the artifact check covers C4 limb circuits chunk_circuits returns the C4 limb circuits too, so the comment that named only C2 chunks was stale. --- crates/zk/benchmarks/src/circuit_benchmark/artifacts.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/zk/benchmarks/src/circuit_benchmark/artifacts.rs b/crates/zk/benchmarks/src/circuit_benchmark/artifacts.rs index 187cb49c73..e46abbf0e3 100644 --- a/crates/zk/benchmarks/src/circuit_benchmark/artifacts.rs +++ b/crates/zk/benchmarks/src/circuit_benchmark/artifacts.rs @@ -273,8 +273,8 @@ pub(crate) fn load( verify_manifest_file(prover, variant, &vk_path, &fs::read(&vk_path)?)?; } if let Case::Named(name) = case { - // A final C2 proof is built from its chunk circuits, which the prover loads by itself: - // they must come from the same manifest and compiler as the circuit measured. + // A final C2 or C4 proof is built from its chunk or limb circuits, which the prover loads + // by itself: they must come from the same manifest and compiler as the circuit measured. for chunk in e3_zk_prover::chunk_circuits(name).unwrap_or_default() { let directory = prover .circuits_dir(e3_zk_config::CircuitVariant::Default, pair) From 4af17cd01ba850c509d638d25f12cfd9dfafcbe9 Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:16:15 +0000 Subject: [PATCH 11/16] docs(circuits): say c4ab_fold binds each C4's limb key tree --- circuits/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circuits/README.md b/circuits/README.md index 12b4f24a4f..ff54be4a8a 100644 --- a/circuits/README.md +++ b/circuits/README.md @@ -91,7 +91,7 @@ limb key tree into its key hash. | `c2ab_fold` | `C2abFold` | Folds C2a and C2b and binds each C2's chunk key tree into its key hash. | | `c3_fold`, `c3_fold_kernel` | `C3Fold`, `C3FoldKernel` | Folds the C3 proofs of one branch in sequence. The kernel makes the first accumulator. | | `c3ab_fold` | `C3abFold` | Folds the final secret key and smudging noise C3 folds. | -| `c4ab_fold` | `C4abFold` | Folds C4a and C4b. | +| `c4ab_fold` | `C4abFold` | Folds C4a and C4b and binds each C4's limb key tree into its key hash. | | `node_fold` | `NodeFold` | Folds C0, C1, `c2ab_fold`, `c3ab_fold`, and `c4ab_fold` for one node. | | `nodes_fold`, `nodes_fold_kernel` | `NodesFold`, `NodesFoldKernel` | Folds the H `node_fold` proofs in sequence. | | `dkg_aggregator` | `DkgAggregator` | Verifies `nodes_fold` and C5. Its EVM proof goes to `publishCommittee`. | From a89bb2fe7fe30f6c8d5b6289cafa7ea4cff4df9a Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:18:53 +0000 Subject: [PATCH 12/16] fix(zk-prover): require both C4 outputs after a C2-to-C4 row The final C4 proof now ends on two outputs (the aggregate commitment, then the limb key tree), but the C2-to-C4 row bound still asked for one field after the row. With one modulus the row one past the roster passed the bound and compared C2's commitments with C4's aggregate. Unreachable today (three moduli, roster-mapped rows); the bound is exact again. --- crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs | 2 +- crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs b/crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs index 36dec30fad..efe844e79c 100644 --- a/crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs +++ b/crates/zk/prover/src/commitment_links/c2_to_c4/mod.rs @@ -220,7 +220,7 @@ fn check_exact_l_commitments( // C4's outputs (the aggregate commitment, then the limb key tree) follow the rows. let c4_row_start = src_idx * l * FIELD_BYTE_LEN; let c4_row_end = c4_row_start + l * FIELD_BYTE_LEN; - if target_public_signals.len() < c4_row_end + FIELD_BYTE_LEN { + if target_public_signals.len() < c4_row_end + 2 * FIELD_BYTE_LEN { return false; } diff --git a/crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs b/crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs index 9e601ced5e..6ea4d51d42 100644 --- a/crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs +++ b/crates/zk/prover/src/commitment_links/c2_to_c4/tests.rs @@ -166,6 +166,8 @@ fn consistency_does_not_match_aggregated_output() { let c4 = c4_signals(&[vec![make_field(5)]], make_field(99)); assert!(!link.check_consistency(&source_values, &c4, 0, 0)); + // The row one past the roster is the aggregated output: both outputs must follow a row. + assert!(!link.check_consistency(&source_values, &c4, 1, 0)); } #[test] From a7448afe24fcc619af95f259c4f81da920ac3a15 Mon Sep 17 00:00:00 2001 From: ctrlc03 <93448202+ctrlc03@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:48:44 +0000 Subject: [PATCH 13/16] test(zk-benchmarks): count the three C4 limb cases in the configured selection The benchmark configuration lists share_decryption_limb_0/1/2 for both modes, so the default selection has 18 secure and 17 insecure cases. --- crates/zk/benchmarks/src/circuit_benchmark/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/zk/benchmarks/src/circuit_benchmark/tests.rs b/crates/zk/benchmarks/src/circuit_benchmark/tests.rs index 81b8bed036..3e4e0c8023 100644 --- a/crates/zk/benchmarks/src/circuit_benchmark/tests.rs +++ b/crates/zk/benchmarks/src/circuit_benchmark/tests.rs @@ -11,8 +11,8 @@ fn configured_leaf_selection_rejects_unknown_or_restricted_cases() { "../../../../../circuits/benchmarks/config.json" )) .unwrap(); - assert_eq!(config.select("secure", &[]).unwrap().len(), 15); - assert_eq!(config.select("insecure", &[]).unwrap().len(), 14); + assert_eq!(config.select("secure", &[]).unwrap().len(), 18); + assert_eq!(config.select("insecure", &[]).unwrap().len(), 17); assert!(config.select("insecure", &["config".into()]).is_err()); assert!(config .select("secure", &["threshold/missing".into()]) From 597fac15bd166da29c715759b8c2244dedd590b5 Mon Sep 17 00:00:00 2001 From: ctrlc03 Date: Fri, 20 Nov 2026 17:09:56 +0000 Subject: [PATCH 14/16] fix(zk-prover): build the final C4 witness without the decrypted-share grid The final C4 circuit reads the expected commitments and the limb proofs only. Serializing every decrypted share and then removing them materialized H x L x N coefficients per proof (835,584 for secure Large) for nothing; the shares stay in the limb witnesses. --- .../src/circuits/aggregation/c4_chain.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/zk/prover/src/circuits/aggregation/c4_chain.rs b/crates/zk/prover/src/circuits/aggregation/c4_chain.rs index 7b714339e1..4377bc8409 100644 --- a/crates/zk/prover/src/circuits/aggregation/c4_chain.rs +++ b/crates/zk/prover/src/circuits/aggregation/c4_chain.rs @@ -19,6 +19,7 @@ use e3_events::{CircuitName, CircuitVariant, Proof}; use e3_zk_config::dkg::share_decryption::Configs; use e3_zk_witness::dkg::share_decryption::{Inputs, ShareDecryptionCircuitData}; use e3_zk_witness::dkg::share_decryption_chain::LimbChain; +use e3_zk_witness::encoding::bigint_2d_to_json_values; use serde_json::{json, Value}; /// The limb circuits of the final C4 circuit, loaded for proving: each limb's compiled program and @@ -90,16 +91,15 @@ pub fn final_share_decryption_inputs( limb_links.push(publics[publics.len() - 2..].to_vec()); } - let mut final_inputs = inputs.to_json(); - let fields = final_inputs - .as_object_mut() - .expect("C4 inputs serialize as an object"); - fields.remove("decrypted_shares"); - fields.insert("limb_vks".into(), json!(limb_vks)); - fields.insert("limb_key_hashes".into(), json!(limb_key_hashes)); - fields.insert("limb_proofs".into(), json!(limb_proofs)); - fields.insert("limb_links".into(), json!(limb_links)); - Ok(final_inputs) + // The final circuit reads only the commitments and the limb proofs; the decrypted shares stay in + // the limb witnesses. + Ok(json!({ + "expected_commitments": bigint_2d_to_json_values(&inputs.expected_commitments), + "limb_vks": limb_vks, + "limb_key_hashes": limb_key_hashes, + "limb_proofs": limb_proofs, + "limb_links": limb_links, + })) } /// Proves C4 for `input` as a limb chain and returns the final proof. From 7975f307a0be3e7b09dcce604e23366370a7279f Mon Sep 17 00:00:00 2001 From: ctrlc03 Date: Sat, 21 Nov 2026 14:21:51 +0000 Subject: [PATCH 15/16] fix(zk): pin the C4 chain bindings and drop the stale C4 JSON Two negative Noir tests cover the asserts that stop a prover substituting the carried sponge state or starting the chain from a state of its choice. LimbChain::compute returns an error for a party row with the wrong limb count instead of panicking, and the unused Inputs::to_json with its obsolete ABI comment is gone. The cutover doc records chunked C4, and the blueprint names the verifier as the consumer of limb_proofs. --- .../src/core/dkg/share_decryption_chain.nr | 21 +++++++++++++++++ crates/zk/witness/src/dkg/share_decryption.rs | 23 ------------------- .../witness/src/dkg/share_decryption_chain.rs | 13 +++++++++++ docs/architecture/upgrades.md | 6 +++++ scripts/blueprint/facts/11-circuits.json | 4 ++-- 5 files changed, 42 insertions(+), 25 deletions(-) diff --git a/circuits/lib/src/core/dkg/share_decryption_chain.nr b/circuits/lib/src/core/dkg/share_decryption_chain.nr index 6ab526371b..d379e0c63d 100644 --- a/circuits/lib/src/core/dkg/share_decryption_chain.nr +++ b/circuits/lib/src/core/dkg/share_decryption_chain.nr @@ -194,3 +194,24 @@ fn the_limb_chain_rejects_unlinked_limbs() { let start = limb_chain_start_hash::<4, 3, 60>(); let _ = check_limb_chain::<4, 3, 60>([[start, 1], [2, 3], [3, 4]]); } + +#[test(should_fail_with = "Chain state mismatch")] +fn a_limb_rejects_a_carried_state_other_than_its_input_hash() { + let (shares, commitments, _) = test_limbs(); + let fresh = initial_state(aggregated_io_pattern::<4, 3, 60>(), DS_AGGREGATED_SHARES); + let mut substituted = fresh; + substituted[0] = substituted[0] + 1; + let (c0, s0) = limb_inputs(shares, commitments, 0); + let _ = share_decryption_limb::<0, 4, 3, 3, 60, 60>( + TQ, + c0, + s0, + limb_state_hash(fresh), + substituted, + ); +} + +#[test(should_fail_with = "Chain must start fresh")] +fn the_limb_chain_rejects_a_chain_that_starts_from_another_state() { + let _ = check_limb_chain::<4, 3, 60>([[1, 2], [2, 3], [3, 4]]); +} diff --git a/crates/zk/witness/src/dkg/share_decryption.rs b/crates/zk/witness/src/dkg/share_decryption.rs index e02431e991..eb63e88291 100644 --- a/crates/zk/witness/src/dkg/share_decryption.rs +++ b/crates/zk/witness/src/dkg/share_decryption.rs @@ -7,8 +7,6 @@ //! Circuit input data, witness preparation, and canonical Noir encoding. use crate::commitments::compute_share_encryption_commitment_from_message; -use crate::encoding::bigint_2d_to_json_values; -use crate::encoding::poly_coefficients_to_toml_json; use crate::WitnessError; use e3_polynomial::Polynomial; use e3_zk_config::dkg::share_decryption::Configs; @@ -144,25 +142,4 @@ impl Inputs { decrypted_shares, }) } - - // Used as input for Nargo execution. - /// Serializes input so that `decrypted_shares` matches Noir's `[[Polynomial; L]; H]`: - /// each polynomial is `{ "coefficients": [number|string, ...] }` (numbers when fit in i64). - pub fn to_json(&self) -> serde_json::Value { - let decrypted_shares: Vec> = self - .decrypted_shares - .iter() - .map(|party_shares| { - party_shares - .iter() - .map(|share| poly_coefficients_to_toml_json(share)) - .collect::>() - }) - .collect::>(); - - serde_json::json!({ - "expected_commitments": bigint_2d_to_json_values(&self.expected_commitments), - "decrypted_shares": decrypted_shares, - }) - } } diff --git a/crates/zk/witness/src/dkg/share_decryption_chain.rs b/crates/zk/witness/src/dkg/share_decryption_chain.rs index 1c77e8ce96..15a39f138c 100644 --- a/crates/zk/witness/src/dkg/share_decryption_chain.rs +++ b/crates/zk/witness/src/dkg/share_decryption_chain.rs @@ -70,6 +70,19 @@ impl LimbChain { let moduli = config.threshold_params.moduli(); let num_moduli = moduli.len(); let degree = config.threshold_params.degree(); + if inputs + .decrypted_shares + .iter() + .any(|party| party.len() != num_moduli) + || inputs + .expected_commitments + .iter() + .any(|party| party.len() != num_moduli) + { + return Err(WitnessError::Other(format!( + "C4 inputs need {num_moduli} limbs per party" + ))); + } let agg_bit = config.bits.agg_bit; let nibble_bits = agg_bit.div_ceil(4) * 4; let group = (254 / (nibble_bits + 4)) as usize; diff --git a/docs/architecture/upgrades.md b/docs/architecture/upgrades.md index 17b26a4b81..5bc1eebbfb 100644 --- a/docs/architecture/upgrades.md +++ b/docs/architecture/upgrades.md @@ -231,6 +231,12 @@ schema-9/protocol-9/generation-2 cutover**: this change raises no counter, and t or supported replay between intermediate builds. Rollback uses the prior backup or a controlled reset/resync, never an older binary on a journal that holds the new encoding. +The cutover also carries chunked C4: the final C4 verifies one limb circuit per CRT limb. The C4 and +`c4ab_fold` keys, the C4 branch of the VK tree, the nodes-tree anchor and the DKG verifier change, +final C4 proofs gain a trailing key-tree public field, and each pair gains nine required limb +artifacts. Stored C4 proofs from in-flight E3s can be neither folded, link-checked nor verified by +peers, so drain them first. + ## BFV profile cutover New contract requests require protocol/DKG/committee-bound profile identities, including SS; the diff --git a/scripts/blueprint/facts/11-circuits.json b/scripts/blueprint/facts/11-circuits.json index 9bc510250f..7667b5f083 100644 --- a/scripts/blueprint/facts/11-circuits.json +++ b/scripts/blueprint/facts/11-circuits.json @@ -397,7 +397,7 @@ }, { "name": "private: limb_proofs", - "by": "check_limb_chain", + "by": "verify_honk_proof_non_zk", "ref": "circuits/bin/dkg/share_decryption/src/main.nr@24@limb_proofs: [UltraHonkProof; L_THRESHOLD]" } ], @@ -430,7 +430,7 @@ ], "rust_patterns": [], "depends_on": [], - "tests": "lib/src/core/dkg/share_decryption_chain.nr has 3 #[test] functions and core/dkg/share_decryption.nr has 2; run nargo test in circuits/lib. This package has none.", + "tests": "lib/src/core/dkg/share_decryption_chain.nr has 5 #[test] functions and core/dkg/share_decryption.nr has 2; run nargo test in circuits/lib. This package has none.", "unverified": [ "Generator role (each selected member proves its own aggregate) comes from docs/architecture/dkg.md, not from the circuit code." ] From f7a9fc385f9772d52a4056aa2f61b81bd81e0f69 Mon Sep 17 00:00:00 2001 From: ctrlc03 Date: Sat, 21 Nov 2026 14:25:48 +0000 Subject: [PATCH 16/16] fix(zk-witness): reject C4 inputs whose share and commitment rows differ in count --- crates/zk/witness/src/dkg/share_decryption_chain.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/zk/witness/src/dkg/share_decryption_chain.rs b/crates/zk/witness/src/dkg/share_decryption_chain.rs index 15a39f138c..8ba87a2e83 100644 --- a/crates/zk/witness/src/dkg/share_decryption_chain.rs +++ b/crates/zk/witness/src/dkg/share_decryption_chain.rs @@ -70,17 +70,18 @@ impl LimbChain { let moduli = config.threshold_params.moduli(); let num_moduli = moduli.len(); let degree = config.threshold_params.degree(); - if inputs - .decrypted_shares - .iter() - .any(|party| party.len() != num_moduli) + if inputs.decrypted_shares.len() != inputs.expected_commitments.len() + || inputs + .decrypted_shares + .iter() + .any(|party| party.len() != num_moduli) || inputs .expected_commitments .iter() .any(|party| party.len() != num_moduli) { return Err(WitnessError::Other(format!( - "C4 inputs need {num_moduli} limbs per party" + "C4 inputs need one commitment row per share row and {num_moduli} limbs per party" ))); } let agg_bit = config.bits.agg_bit;