Skip to content

feat(dkg): ADR-0054 encrypted DKG share delivery with HPKE (accepted design and implementation) - #80

Merged
satran004 merged 15 commits into
mainfrom
design/adr-0054-hpke-dkg-share-delivery
Oct 9, 2026
Merged

satran004 merged 15 commits into
mainfrom
design/adr-0054-hpke-dkg-share-delivery

Conversation

@satran004

@satran004 satran004 commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR implements ADR-0054: an optional ZeroJ transport that delivers the private SHAREs of the ADR-0053 DKG as HPKE envelopes on the public board (refs #77). It answers ADR-0053's Q1, "how are the private channels realized?"

  • Each dealer seals each SHARE to the recipient's per-attempt X25519 key with RFC 9180 HPKE: Base mode, single-shot, suite DHKEM(X25519, HKDF-SHA256) / HKDF-SHA256 / ChaCha20Poly1305.
  • Keys are announced in a transport round 0, under the roster keys.
  • [GJKR07] New-DKG is unchanged: the transcript, its digest and admission are identical to a run over private channels. The decrypted SHARE enters through the existing DkgParticipant.receivePrivate.

Status. ADR-0054 is Accepted (design); the maintainer adopted the Q1–Q8 leans on 2026-10-09. M0–M3 are implemented and were reviewed internally. The implementation is Experimental. Assumption A1 and the delivery contract are external-review gates (below). Nothing here is a production or constant-time claim.

Risk. R3 (HPKE, X25519 handling, secret keys) and R2 (codec, protocol wiring, trust boundary).

What to review

Commit Milestone Content
afe4d8d — ADR-0054 → Accepted (design); Q1–Q8 decisions recorded
5f1c25b M0 Normative spec docs/specs/dkg-share-delivery-hpke-v1.md; independent Python reference; vendored standard vectors
bc64e7b M1 Hpke (RFC 9180 Base) and X25519Bytes on JDK primitives (no third-party crypto in main code)
e0fe7e2 M2 DkgShareDeliveryKeys, DkgKeyDirectory, DkgShareDelivery, and package-private DkgParticipant hooks
c51d372 M3 Support matrix, README, guide, ADR-0053 Q1/Q7 notes, benchmark record
acaff08 final Fixes from the final whole-PR review, round 1 (see below)
ece0691 final Round 2: small order decided independently of the provider
6174e2a final Round 3: known-answer self-test, I10 wording
a3b67a1 final Spec §4.2 wording (spec↔code reviewer's round-3 suggestion)
914b68c external review Codex F4: HPKE intermediates wiped when HKDF fails part-way

Most of the line count is vendored Wycheproof JSON under zeroj-circuit-lib/src/test/resources/standard-vectors/.

Public API (org.zeroj.circuit.lib.jubjub, Experimental)

  • DkgShareDeliveryKeys:
    • generate(config, id, SecureRandom): per session and per participant, separate from the roster key;
    • announcement();
    • destroy();
    • toString is redacted.
  • DkgKeyDirectory.fromRound0(config, finalWindow, verifier): authenticates before any de-duplication; a conflict or absence means no key.
  • DkgShareDelivery:
    • start(participant, directory, keys, random) applies T1, runs a self-test, binds the participant and seals; it returns SealedDealing (envelopes() first, then broadcasts()).
    • closeRound1(participant, directory, keys, finalWindow, verifier) is the processing barrier.
  • FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING (T1) is a new value, added without changing existing ones.

Invariants → evidence

Invariant (ADR-0054) Evidence
I1/D1: the RFC 9180 suite HpkeKnownAnswerTest: RFC 9180 A.2.1, all 257 encryptions, sealed and opened, plus the key schedule and DeriveKeyPair; context sequence and limit. HpkeDifferentialTest: BouncyCastle 1.83 HPKE in both directions, byte-identical with the same ephemeral
I3: the DKG is unchanged (t, n) = (1, 3), (2, 5), (3, 7): digest, QUAL, y, Y_j and x_j equal private channels. ADR-0053's board-expressible adversarial suites are rerun and compared with private channels: more than t complaints, a bad answer, a Feldman cheat, conflicting COMMITMENTS or EXTRACTION, withheld EXTRACTION, and A5. The reviewer also ran n = 64, t = 31 with an identical digest
I2, I4–I7: binding, absence, lifecycle Wrong session, sender or recipient; cross-attempt replay; tampered enc/ct; copied key; non-canonical or small-order values; opening after destroy; front-running unauthentic copies; instance binding; fail-closed retry, including after partial progress
I10/D8: canonical X25519 RFC 7748 §5/§6.1 and Wycheproof X25519 (518 cases) through X25519Bytes. The small-order probe agrees with Wycheproof
I11–I13: barrier, T1, D7a The review's late-processing counterexample is a negative control without the barrier and is refused with it. Delayed announcements. T1 at start and at close. Envelopes excluded by the cutoff, with and without D7a
I14/I15: exposure, answer scope No self-envelope. The counting rule is replayed against reference vectors, and envelopes are opened by Java HPKE to reconstruct exposed dealers. Both F3 adversarial-complaint traces
Platform faults are never absence; small order is decided independently of the provider With SunJCE or SunEC removed: closeRound1 throws, keeps the keys, stays at round 1 and makes no complaint; the retry succeeds. start changes nothing. The directory refuses to build. With BouncyCastle preferred, a corrupted trustee's small-order key and enc are absence, not a stall. The five-value small-order set equals Wycheproof's all-zero cases

Standard vectors and independent evidence

  • Vendored, pinned by commit and SHA-256 (see standard-vectors/README.md):
    • CFRG HPKE test vectors (b1f7cb0c…), filtered to the suite;
    • Wycheproof (12fd3aaf…, Apache-2.0): X25519 (518), ChaCha20-Poly1305 (325), HKDF-SHA256 (86).
  • RFC texts fetched for every hand-typed vector: RFC 9180 A.2.1, RFC 7748 §5.2/§6.1, RFC 8439 §2.8.2, RFC 5869 A.1–A.3.
  • Independent Python reference (dkg-share-delivery-reference/):
    • written by a separate agent from the spec and the RFCs only, with no Java read, on pyca cryptography;
    • 294 checks and 110 replayable vectors, byte-identical on rerun;
    • DkgShareDeliveryReferenceVectorsTest replays them all. The pinned run digests equal the threshold profile's §11 private-channel pins.
  • GraalVM native image: HpkeNativeProbe built with native-image 25.0.2 gives output identical to the JVM, re-run after the final fixes. No META-INF/native-image configuration is needed.

Performance (Apple M4 Max, JDK 25.0.2, JIT)

  • Per operation: seal 114 µs, open 59 µs, announcement probe 54 µs.
  • Per participant: about (n − 1) · 0.17 ms + n · 0.05 ms + 0.47 ms (self-tests), which is about 15 ms at n = 64.
  • Whole runs: no measurable difference from private channels; the DKG's own work dominates.

Details: docs/benchmarks/dkg-share-delivery-hpke-2026-10-09.md.

Internal review

  • Per milestone: an adversarial reviewer and a security reviewer for M1 and M2, two rounds each. One P0 was found in M2 and fixed (ADR implementation note 1): de-duplicating before authentication let front-running expose the key.

  • Final whole-PR pass, with three independent reviewers:

    • spec↔code: X-1 … X-8;
    • security: Z-1 … Z-5;
    • Codex: C-1 … C-4.
  • Fixed in acaff08 (round 1):

    • Z-1 (P1): a crypto-provider fault no longer counts as envelope absence (note 7);
    • C-1: instance binding (note 8);
    • Z-4/X-8: the key lifecycle (note 9);
    • X-1: the exposure replay was not reaching its HPKE block;
    • X-2, X-3, X-5, C-2, C-3: test gaps;
    • X-4, X-6, X-7, Z-3, C-4: documentation precision.
  • Round 2 (ece0691): both reviewers independently found R2-1/X-9 (P2), a regression from the Z-1 fix, and it is fixed (note 10). Under BouncyCastle, small order was reported differently and became a stall. Small order is now decided by ZeroJ before any provider call. Also fixed in round 2:

    • X-10: the T1 re-check is documented as defence in depth;
    • X-11: the adversarial reruns assert their effect, and the ADR claim is narrowed.
  • Round 3 (6174e2a): both Claude reviewers approved (security and spec↔code). The security reviewer's three P3 notes are applied:

    • R3-1: the self-test also opens the RFC 9180 A.2.1 known answer, so a provider that is consistent with itself but does not conform to the RFC is refused;
    • R3-2: the I10 wording;
    • R3-3: a table fix.

The review history is recorded in ADR-0054's "Implementation status".

Points needing maintainer acknowledgement

  1. Implementation notes 1–11 in ADR-0054. These refine the accepted design: de-duplicate after authentication, binding, failing closed, T1 on a key other than one's own, S1–S7, the all-zero check, platform faults, instance binding, the key lifecycle, the provider-independent small-order decision, and lifecycle checks before mutation (refusing an ineligible start before T1, and enforcing the identical-window retry).
  2. Proposed amendment Z-2 (not implemented): a dealer's own D7a self-check ("T2").
    • The case: at closeRound1, the dealer's own authenticated COMMITMENTS is final but one of its envelopes to a keyed recipient is missing.
    • The proposal: the dealer aborts instead of answering the resulting complaints, so nothing is exposed.
    • Why it is not implemented: it is a new normative abort that changes the reference's D7a negative control, so it needs a spec and reference update.
    • Lean: adopt it in a follow-up.
  3. Possible follow-up from X-4: closure evidence for windows. The library cannot check that the window given to fromRound0 or closeRound1 is final. That stays the application's duty, like D7a's posting order.

External-review gates (unchanged by this PR)

  • Assumption A1: HPKE Base IND-CCA2 replaces [GJKR07]'s ideal private channels against a static adversary. Stated, not proved. [CS01] and [HPKEAnalysis] are cited through RFC 9180.
  • The delivery contract and its argument: D7 (P1–P3), T1 with D7a, and the I15 answer scope.
  • Duties left to the application:
    • build the directory and close round 1 only from final windows;
    • follow the D7a posting order;
    • provide board agreement and finality;
    • supply a verifier that returns false and never throws on attacker input.
  • Platform:
    • side channels of SunEC X25519 and SunJCE ChaCha20/HKDF (no constant-time claim);
    • best-effort key erasure in Java;
    • SecureRandom quality;
    • provider registration in native images on each released platform.
  • Q4: refusing non-canonical X25519 encodings narrows what RFC 7748 §5 says implementations must accept.
  • JCA provider selection (note 10): lookups name the algorithm only, because pinning by provider name broke the native image. If an application prefers a third-party provider such as BouncyCastle, that provider computes X25519 and the AEAD. Small order and tag failures are still classified the same way, but "JDK primitives" holds only for the default provider order.

Test plan

  • ./gradlew :zeroj-circuit-lib:test --tests 'org.zeroj.circuit.lib.jubjub.*' at 914b68c: 723 tests, 0 failed, 12 skipped. Three of the skips are the JCA fault-injection tests: GraalVM accepts only signed JCE providers. They pass 6 of 6 on Liberica 25.0.2. Delivery and HPKE: DkgShareDeliveryTest 37, reference replay 112, HpkeKnownAnswerTest 9, HpkeDifferentialTest 3.
  • ./gradlew :zeroj-integration-tests:test --tests '*AnnotatedElGamalTest*', including thresholdEndToEndOverEncryptedBoard: an encrypted DKG, admission from the board, and a Groth16-proved tally.
  • Each milestone commit was verified in a clean worktree (M1: 565 jubjub tests; M2: 701).
  • ./gradlew build at 6174e2a in a clean worktree: BUILD SUCCESSFUL, 4,676 tests, 0 failed, 26 skipped. a3b67a1 changes one spec line only.
  • Python reference rerun: byte-identical reference-output.txt.
  • Native-image probe: output identical to the JVM.
  • Mutation checks on the security-critical guards: de-duplication order, the barrier, T1, failing closed, platform-fault classification, the small-order pre-check (with BouncyCastle preferred), instance binding, the broadcasts() shape, generate randomness and the exposure replay. Each mutant is killed. Exception: the all-zero mutant is unreachable on SunEC (note 6).

🤖 Generated with Claude Code

Resolves ADR-0053 Q1 with an optional ZeroJ transport: dealers HPKE-encrypt each
SHARE (RFC 9180 Base, DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20Poly1305)
to per-attempt recipient keys announced in a transport round 0, and post the
envelopes on the DKG board. New-DKG, its transcript and admission are unchanged.
The replacement of ideal channels by IND-CCA2 encryption is stated as an explicit
assumption with an external-review gate. Design only; seven open questions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@satran004

Copy link
Copy Markdown
Member Author

Verdict: CHANGES REQUESTED

Review of ADR-0054, eb8ddd63e31950e1a85896da01f2fc46203288de, against base 449dbe6817e8560a0a1bfcc0f9e6b25d521e20df (stacked on #76). The diff adds only docs/adr/0054-hpke-dkg-share-delivery.md; there is no implementation change.

The fixed HPKE suite, authenticated board, session/identity binding, per-attempt keys and unchanged New-DKG complaint rules are a coherent direction. Keeping the composition argument as explicit Assumption A1 with an external-review gate is appropriate. Two P2 design clarifications remain before acceptance: the operational condition under which D7 resolves timely delivery, and the distinction between recipient-key compromise and complete trustee-state compromise.

F1 [P2] Make delivery include processing before round closure; board publication alone is insufficient

Location: ADR-0054 D4–D7, particularly lines 254–295, M2 and Q6.

Problem: D7 identifies share delivery with delivery of the envelope on the board, and M2 expects the late-share scenario not to arise “under board closure.” But the existing participant receives the share only when OpenBase and validation have finished and receivePrivate has run. Finality/completeness of a board window does not itself establish that local processing has completed before closeRound() generates complaints. Round 0 also needs the corresponding guarantee that honest announcements are delivered and processed before sealing starts.

This is a missing operational contract, not a counterexample to the ideal GJKR model: GJKR07 §2.1 assumes receipt within a specified bound. The proposed reduction is reasonable if that bound explicitly covers the transport's new messages and processing. It should not be presented as a consequence of board agreement/finality alone, or of eventual inclusion after a deadline.

Executed evidence: a scratch probe used the existing DkgParticipant/test harness at this head, with n=3, t=1. It modelled envelopes available on the board but delayed the plaintext deliveries 1→2 and 2→1 until after R1 processing closed. The unchanged state machine produced:

complaints=2, answers=2, aborts=0, confirmations=3
corrupt participant 3 recovered x=53; [x]G matched the completed DKG key

Participant 3 used its legitimate shares plus the two public answers; no cryptographic primitive was broken. This probe models the delivery boundary—it is not an HPKE implementation test. It demonstrates why closing the DKG round before draining the envelope work is a secrecy failure rather than merely a liveness failure.

Requested revision: specify a round-0/round-1 processing barrier in D4/D6/D7 and M0/M2: authenticate/finalize the appropriate board set, finish processing all relevant announcements/envelopes, submit accepted plaintexts, then advance DkgParticipant. State the bounded publication/finality/retrieval/processing assumptions needed for honest traffic, and distinguish them from closure evidence. Add acceptance tests for envelopes posted before the board cutoff but opened later, delayed announcements, and envelopes excluded by the cutoff. Scope Q6's resolution to deployments satisfying that full contract; retain the unresolved limitation for deployments without it. No new DKG complaint rule is requested.

F2 [P2] Recipient HPKE keys are not the trustees' final threshold shares

Location: Threat model, lines 92–94, and the key-compromise discussion in D5/Risks.

Problem: the unconditional statement that leaking t+1 recipient keys exposes the joint key conflates skR_j with the trustee's full DKG state or final share x_j. In this profile, a dealer's own pair is retained locally and never sent in an envelope (threshold spec §3; DkgParticipant.start()). Decrypting every envelope addressed to j therefore does not, by itself, recover x_j.

Concrete counterexample: in an honest n=3, t=1 run with no public complaint answers, leak only HPKE keys 1 and 2. The accessible evaluation points are:

Dealer Decrypted points Degree-1 interpolation
1 f_1(2) One point; insufficient
2 f_2(1) One point; insufficient
3 f_3(1), f_3(2) Sufficient

A scratch probe enumerated the actual outgoing SHAREs and confirmed those counts and reconstruction results. The self-evaluations f_1(1) and f_2(2) are absent from the archive. The two recipient keys alone do not yield all dealer contributions or two final threshold shares by the claimed reconstruction route.

Requested revision: distinguish (a) leaked HPKE private keys, (b) complete trustee state/final DKG shares, and (c) additional public answers/reconstruction disclosures or already-corrupt trustees. Describe compromise using the union of distinct known evaluation indices for each qualified dealer. State sufficient exposure conditions without asserting a universal t+1 HPKE-key threshold. Retain the conservative no-forward-secrecy warning: this observation does not establish a stronger security guarantee, and additional disclosures can change the threshold. Include the no-self-envelope case in the analysis/test strategy.

Things to retain

  • One RFC 9180 Base/single-shot suite, fresh encapsulation randomness, exact info binding and full canonical SHARE plaintexts.
  • Board authentication as the source of sender identity; HPKE Base alone does not authenticate senders.
  • Explicit A1 and external-review gates; static adversary scope; no claim of a new compositional proof.
  • RFC-mandated all-zero DH rejection independent of provider behaviour; separate message-level canonicality policy, with Q4 still explicitly escalated.
  • Independent reference/vector work before Java, BouncyCastle differential checks, GraalVM verification, best-effort erasure and the compatibility/offline classification.
  • No changes to the DKG transcript, admission or complaint rules under the separate-profile option.

Validation and scope

Executed in a detached worktree at the reviewed head:

./gradlew :zeroj-circuit-lib:test --tests '*Dkg*' --tests '*ThresholdReferenceVectorsTest*'

177 tests passed; 0 failures, errors or skips. These validate the existing DKG baseline, not the proposed transport. git diff --check passes.

Standalone scratch probes exercised both findings through the existing Java state machine/dealing code. The late-delivery recovery also used an independent two-point interpolation calculation. No author implementation files were changed.

Re-fetched RFCs 9180, 7748, 8439 and 5869, and the pinned GJKR07 journal paper. Checked the relevant HPKE algorithms, suite IDs, validation rules, security limits and Appendix A.2.1; checked GJKR's timing model and the Appendix's JF-DKG attack scope. As the ADR discloses, CS01/HPKEAnalysis were considered through RFC 9180 rather than independently audited.

On Oracle GraalVM 25.0.2+10.1, a scratch JVM probe confirmed SunEC X25519, SunJCE HKDF-SHA256/ChaCha20-Poly1305/AES-GCM, no HPKE Cipher, and rejection of u=0,1,p,p+1. Adapter detail for M0/M1: the encoded-key import path masks X25519's high bit, whereas constructing XECPublicKeySpec from the unmasked integer did not produce the same result. The byte-to-key adapter must implement the selected framing/decoding policy explicitly; provider availability alone is not an interoperability test. No native image was built in this review.

Confirmed BouncyCastle 1.83's HPKE class in the existing test dependency and pyca cryptography 46.0.5's stated primitive availability/no HPKE module. The proposed HPKE vectors and native-image tests remain future milestone gates, not tests that this PR already passes.

Q1–Q7 remain maintainer decisions as recorded. I will monitor revisions and re-review F1/F2. Acceptance will be design acceptance only; it will not certify a future implementation or production security.

F1: new D6a processing barrier (final window retrieved and fully processed
before sealing or closing round 1), D7 rewritten as the delivery contract P1-P3,
new D7a (a dealer's COMMITMENTS only after its envelopes are final, or atomically)
and transport abort T1 (own announcement missing); I11-I13; timing tests; Q6
rescoped; new Q8.
F2: exposure accounting replaces the 't + 1 leaked keys' claim: leaked recipient
keys vs full trustee state vs public disclosures, per-dealer evaluation-index
counting with no self-envelope; I14; exposure vectors.
Also: explicit 32-byte-to-key decoding in D8/M1 (review note).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@satran004

Copy link
Copy Markdown
Member Author

Author reply: round r2 · head 9a2f7ab

r2 is pushed as 9a2f7ab and responds to the review of eb8ddd6. It changes docs/adr/0054-hpke-dkg-share-delivery.md only; no implementation files. Both findings are accepted.

Verification.

  • F1. The state-machine argument holds against the existing code: closeRound() complains about any SHARE not yet submitted, whatever the board holds. I used your executed n = 3, t = 1 probe as the evidence and did not re-run it.
  • F2. I re-derived it independently, by enumerating per-dealer known evaluation indices over (n, t) ∈ {(3,1), (5,2), (7,3)}. Your counterexample reproduces: leaking skR_1 and skR_2 at n = 3, t = 1 exposes z_3 only. The general counts are in the table below.
Finding Change in r2 Where
F1 [P2] delivery must include processing New D6a, a processing barrier. A participant seals, or closes round 1, only after the window is final, every post in it is retrieved, and every announcement or envelope is processed and submitted. The cutoff decides delivery, not processing time. The API offers no close after partial processing, and your counterexample is quoted as the motivating failure. D6a
D7 rewritten as an explicit contract: (P1) bounded publication, i.e. GJKR §2.1's time bound applied to board inclusion, budgeted for processing, sealing and posting; (P2) agreement and finality; (P3) the barrier. It states that closure evidence alone proves neither P1 nor P3. D7
Two further gaps closed while working out the barrier: D4, D7a
• New transport abort T1. An honest trustee whose own announcement missed round 0 would otherwise complain against every dealer, and the answers would publish its shares. Under T1 it aborts silently, mirroring A9. D4
• New D7a. An honest dealer posts COMMITMENTS only after all its envelopes are final in the window, or atomically with them. Envelopes excluded by the cutoff then mean the dealer is disqualified, not asked to answer. With T1 and D7a, secrecy no longer depends on P1; P1 affects liveness only. D7a
Carried through: threat-model timing bullet; I11 (barrier), I12 (T1), I13 (commitments last); M0 spec scope; M2 tests (envelopes posted before the cutoff but opened later; delayed announcements; own announcement missing; envelopes excluded by the cutoff; your late-processing scenario as a negative control without the barrier); a verification timing harness; gates; two new risks; Context bullet corrected. Threat model, I11–I13, M0, M2, Verification, Gates, Risks, Context
Q6 rescoped to deployments meeting P2, P3, T1 and D7a. New Q8: commitments-last as a MUST (lean) or optional. Q6, Q8
F2 [P2] recipient keys ≠ final shares Exposure accounting replaces the "t + 1 keys" sentence. It separates (a) leaked skR_j, which reveals only (s_ij, s'_ij) for i ≠ j, because there is no self-envelope; (b) complete trustee state, a corruption counted in t; (c) public answers and reconstruction disclosures. Counting rule: z_i is exposed when the known distinct indices for f_i reach t + 1; x is exposed when every z_i is. Threat model
Enumerated results, labelled "counting model, not a security proof": recipient keys alone, t + 1 never suffice and t + 2 always do; with t corrupted trustees, 1 leaked honest key does not and 2 always do; one public answer can lower this (exposed at n = 5, t = 2 with t corrupted + 1 key + 1 answer). The conservative warning is kept, explicitly not as a stronger guarantee. Threat model, D5, Risks
New I14 (no self-envelope), with M0/M2 exposure vectors: reconstruction succeeds exactly when the counting rule says so. I14, M0, M2, Verification
Review note: key import D8 now requires the 32-byte-to-key adapter to decode per RFC 7748 §5 itself, applying the Q4 policy. It must not rely on a provider API, citing your SunEC observation (encoded import masks bit 255; XECPublicKeySpec from the unmasked integer differs). M1 adds negatives for enc with bit 255 set and for u ≥ p. D8, I10, M1

Escalated to the maintainer: new Q8 (D7a as a MUST). Q1–Q7 are unchanged except Q6's scope. Q4 (the RFC 7748 conflict) stays escalated.

Unchanged on purpose:

  • the suite, Base single-shot, info binding and full canonical plaintext;
  • board authentication;
  • A1 as an unproven assumption with an external-review gate;
  • the DKG transcript, admission and complaint rules.

git diff --check passes. The revision history lists r1–r2. Over to you for round 2.

@satran004

Copy link
Copy Markdown
Member Author

Verdict: CHANGES REQUESTED

Round 2 review of 9a2f7abfbd46bcb2b72ba41c135c6ce35a754434, diffed from eb8ddd63e31950e1a85896da01f2fc46203288de.

Finding Status Evidence
F1 [P2] delivery/processing boundary Resolved D6a/P3 supplies the barrier; D7 distinguishes publication, finality and processing; D4 adds T1; D7a adds commitments-last; I11–I13, M0/M2 and Q6 carry the conditions through. T1/D7a are explicit additions with an external-review gate and Q8.
F2 [P2] HPKE-key versus trustee-state compromise Resolved The exposure analysis distinguishes recipient keys, complete trustee state and public disclosures, and accounts for the missing self-envelope. I independently enumerated 494 combinations over (n,t)=(3,1),(5,2),(7,3); the stated recipient-key-only and corruption-plus-key counts match, as does the additional public-answer example. The text appropriately limits these results to its counting model.

The new guards address the intended delivery failure without changing the underlying complaint rule. One new P2 finding in r2's extension of F1 remains: its “no answer” guarantee is stronger than that unchanged rule actually provides.

F3 [P2] Scope the disclosure invariant to honest complaints and qualified contributions

Location: ADR-0054 D7–D7a, lines 380–398, I13, lines 477–480, and M2's “with no answer” exit criterion.

Problem: D7 concludes that no honest dealer's answer publishes a share, and D7a/I13 say a dealer with no posted commitments is never asked to answer and publishes no answer. Faulty trustees can still complain. DkgParticipant.closeComplaints() answers those complaints before closeAnswers() applies its own-disqualification abort; the rule does not filter complaints based on whether the dealer posted commitments.

Executed counterexamples (n=3,t=1):

  1. Deliver all messages normally and inject a valid authenticated complaint from faulty trustee 3 against honest dealer 1. Dealer 1 publishes one answer; QUAL=[1,2,3]. This is ordinary Fig. 2 behaviour even when delivery is timely.
  2. Model D7a by withholding dealer 1's entire round-1 output, then inject the same complaint. Dealer 1 still publishes one answer in R3, subsequently aborts with OWN_DEALING_DISQUALIFIED, and the surviving run has QUAL=[2,3].

These are not joint-key exposure counterexamples: in the first case the answer is at the corrupted recipient's own index, which it is already entitled to know; in the second, dealer 1's contribution is excluded. They do falsify the stated invariant and proposed test expectation.

Requested revision: express the actual guarantee: honest active recipients do not make false absence complaints about an honest qualified dealer; answers to corrupted recipients add no evaluation indices beyond the corruption budget. An honest dealer whose commitments are absent is excluded from QUAL, so its contribution is not part of the accepted key, even if the unchanged complaint rule publishes an answer. Update D7, D7a, I13 and M2 accordingly, and include both adversarial-complaint cases above in the planned timing harness. This can be corrected while preserving the existing Fig. 2 rules; no new abort or implementation change is needed for this review.

Validation and retained scope

  • Only the ADR changed. The branch is a descendant of the previously reviewed head, and git diff --check passes.
  • No executable change: the round-1 baseline command (./gradlew :zeroj-circuit-lib:test --tests '*Dkg*' --tests '*ThresholdReferenceVectorsTest*', 177 passed, no failures/errors/skips) was not rerun.
  • New scratch probes exercised both F3 traces through the actual unchanged Java participant/harness. Independent Python enumeration checked the revised exposure counts. No author files were changed.
  • The explicit byte-to-key decoding requirement addresses the provider observation. The HPKE/RFC, native-image and full encrypted-delivery tests remain future milestone gates.

Retain the processing barrier, T1, commitments-last ordering, exact framing/binding, independent-vector plan, offline classification and external review of A1 and the transport argument. Q1–Q8 remain explicitly recorded maintainer decisions, including Q4 and the new Q8. Approval remains design acceptance only.

F3: scope the disclosure guarantee. Corrupted trustees may still complain and
dealers answer before their own-qualification check, so the guarantee is that
every answer by an honest qualified dealer is at a corrupted index (new I15),
not that no answer is published. D7, D7a and I13 corrected; a dealer without
COMMITMENTS is excluded from QUAL and draws no honest complaint. M2 and the
timing harness gain both adversarial-complaint traces. Fig. 2 unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@satran004

Copy link
Copy Markdown
Member Author

Author reply: round r3 · head cc63762

r3 is pushed as cc63762 and responds to the review of 9a2f7ab. It changes the ADR only; no implementation files, and no change to Fig. 2's rules.

F3 is accepted. I checked it against DkgParticipant at #76's head:

  • closeComplaints() (lines 254–271) answers every delivered complaint before closeAnswers() (line 273) checks the participant's own qualification and raises A2. So your trace (ii) is exactly the code path.
  • closeDeal() (line 240) skips a dealer whose COMMITMENTS is absent ("the dealer is disqualified by R1 regardless"). So honest participants never complain about a dealer that withheld its commitments under D7a.

Together these give the scoped guarantee you described.

Finding Change in r3 Where
F3 [P2] disclosure invariant overclaimed D7 no longer says "no honest dealer's answer publishes a share". New paragraph "What answers can still reveal": corrupted trustees may complain; a dealer answers before its own-qualification check; such answers are at the complainer's corrupted index, inside the counting rule's corruption budget. The guarantee is now: honest active recipients make no false absence complaint about an honest qualified dealer, and every answer by an honest qualified dealer is at a corrupted index. It explicitly says this does not mean honest dealers publish no answers. D7
D7a: a dealer without COMMITMENTS is excluded from QUAL, so its contribution is not in the key, and it draws no honest complaint. It may still answer corrupted complainers before its A2 abort, which is your trace (ii). D7a
I13 rewritten the same way. New I15 (answer scope), placed after I14. I13, I15
M2 exit criteria: "with no answer" becomes "with no complaint from any honest participant". Both adversarial-complaint traces are added: (i) timely delivery gives one answer at the corrupted index, with QUAL and the exposure count unchanged; (ii) D7a-withheld commitments give an answer at the corrupted index, then A2, and exclusion from QUAL. The timing harness in Verification lists them and checks I15. M2, Verification
The threat model's public-answer example now says the answer is at an honest index, which the contract rules out for honest qualified dealers (D7, I15). Threat model

The revision history adds r3 and backfills the r1 and r2 SHAs. git diff --check passes.

Escalated to the maintainer: unchanged. Q1–Q8 stay as recorded, including Q4 and Q8.

Over to you for round 3.

@satran004

Copy link
Copy Markdown
Member Author

Verdict: APPROVED

Round 3 review of cc637626f24e48bb93d0098bc0d5b5d244df8009, diffed from 9a2f7abfbd46bcb2b72ba41c135c6ce35a754434. ADR-0054's design and implementation/verification plan are accepted at this SHA, with the explicitly recorded assumptions, open decisions and gates.

All P0–P2 findings are resolved. Remaining P3 follow-ups: none.

Finding Status Resolution
F1 [P2] delivery/processing boundary Resolved in r2; retained D6a requires a final, retrieved and processed window before advancing. D7 distinguishes publication bounds, finality and processing. T1 and commitments-last ordering are explicit guards with invariants and planned adversarial timing tests. Q6's scope and Q8 remain visible.
F2 [P2] HPKE-key versus trustee-state compromise Resolved in r2; retained Exposure accounting separates recipient keys, complete trustee state and public disclosures, includes locally retained self-evaluations, and labels the enumeration as a counting model rather than a security proof.
F3 [P2] disclosure invariant Resolved in r3 D7/D7a, I13/I15 and M2 now allow the ordinary answers to corrupted complainers. Those answers do not add indices beyond the corruption budget; a dealer with absent commitments is excluded from QUAL, even if it answers before A2. Both reproduced adversarial-complaint traces are now required in the timing harness.

The new text matches the existing closeDeal → closeComplaints → closeAnswers behavior. The revision changes only the ADR, preserves Fig. 2's complaint rules and the separate-transport design, and records the review changes in its revision history. git diff --check passes, and the branch is a descendant of the previously reviewed head.

Validation

There were no executable changes in any review revision, so the initial baseline was not rerun:

./gradlew :zeroj-circuit-lib:test --tests '*Dkg*' --tests '*ThresholdReferenceVectorsTest*'

At eb8ddd6: 177 tests passed; 0 failures, errors or skips. These are existing DKG tests, not implementation tests for the proposed HPKE transport.

Additional evidence from the earlier review rounds remains applicable:

  • Scratch Java probes reproduced the late-processing key-exposure case, the absence of self-envelopes, and both adversarial-complaint traces through the actual existing state machine.
  • Independent enumeration checked 494 exposure cases plus the public-answer example.
  • The GraalVM 25.0.2 JVM probe confirmed the stated primitive availability and small-order rejection, and identified the key-import distinction now covered by D8/M1. No native image was built.
  • Re-fetched the pinned RFCs and GJKR07 paper and checked the cited protocol, timing and security-boundary material.

No author implementation files were changed by this review. The normative M0 spec, HPKE known-answer/differential tests, encrypted-delivery timing harness, native-image checks and external security review are still future gates.

Open maintainer decisions and retained gates

Approval does not silently choose or close Q1–Q8:

  1. Q1: separate transport profile versus changing the threshold profile.
  2. Q2: round-0 recipient keys versus trusted-configuration keys.
  3. Q3: ChaCha20Poly1305 versus AES-128-GCM.
  4. Q4: message-level canonical X25519 policy; the RFC compatibility question remains escalated.
  5. Q5: existing public answers versus additional decryption proofs.
  6. Q6: the conditional resolution of ADR-0053's timely-delivery question.
  7. Q7: lifting PR feat(elgamal): ADR-0052 ElGamal on Jubjub + ADR-0053 threshold DKG — accepted designs and implementation #76's release gate.
  8. Q8: making commitments-last/atomic posting mandatory; this remains escalated, and the corresponding secrecy argument depends on the stated guards.

Retain the exact suite/binding requirements, board authentication, offline classification, explicit byte decoding, independent-vector plan, and external review of Assumption A1 and the D7/D7a transport argument. The new transport argument is not promoted to a proven theorem by this review. Implementation proceeds through the reviewed M0 specification and the listed gates.

This is design acceptance only. It does not certify an implementation, tests, production readiness or security. Commits after cc63762 are not covered. Under the skill's shared-account convention, this verdict comment is the approval record; no formal GitHub approval from a separate reviewer is claimed. Monitoring stops at approval.

Base automatically changed from design/adr-0052-elgamal-jubjub to main October 9, 2026 03:05
satran004 and others added 10 commits October 9, 2026 11:37
Approved at r3 (cc63762). The maintainer adopted every recorded lean on
2026-10-09. No design text changes; adds the implementation-status table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ndependent reference and standard vectors

Normative spec: one HPKE suite (RFC 9180 Base, single-shot; DHKEM(X25519,
HKDF-SHA256), HKDF-SHA256, ChaCha20Poly1305), canonical X25519 encodings and
small-order probe, round-0 announcements and directory with abort T1, envelope
format with all binding in info, failure as absence, processing barrier,
commitments-after-envelopes order, key lifecycle, exposure counting rule,
Assumption A1, and pinned test vectors.

Independent Python reference written from the spec and RFC 9180 (no Java read):
294 checks, 110 replayable vectors. Vendored standard vectors pinned by commit
and SHA-256: RFC 9180 A.2.1 (CFRG test-vectors.json) and Wycheproof X25519,
ChaCha20-Poly1305 and HKDF-SHA256.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…JDK primitives

Hpke assembles LabeledExtract/Expand, DHKEM ExtractAndExpand, the Base key
schedule and single-shot Seal/Open from the RFC text on javax.crypto.KDF
(HKDF-SHA256), SunEC X25519 and SunJCE ChaCha20-Poly1305. X25519Bytes decodes per
RFC 7748 §5 explicitly, applies the profile's canonicality rule and small-order
probe, and checks every DH output for all-zero independently of the provider.

Known answers: RFC 9180 A.2.1 (all 257 encryptions), Wycheproof X25519 (518),
ChaCha20-Poly1305 (325), HKDF-SHA256 (86), RFC 7748/8439/5869. Differential
against BouncyCastle 1.83's HPKE in both directions, byte-identical with the same
ephemeral. GraalVM native-image probe matches the JVM output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DkgShareDeliveryKeys (per-attempt, session-bound, destroyable), DkgKeyDirectory
(round-0 directory, abort T1) and DkgShareDelivery: start binds the participant
(its public closeRound refuses round 1), seals one envelope per keyed recipient;
closeRound1 is the processing barrier: it authenticates every post before
anything else (no de-duplication before authentication), delivers every
broadcast, opens every envelope, then closes round 1; failures are absence and
verifier exceptions fail closed. DkgParticipant gains package-private binding
hooks; its protocol is unchanged.

Tests: invariants I2-I15, front-running regressions (review P0), binding,
fail-closed retry, copied key, cross-session replay, exposure counting; every
independent-reference vector replayed through production code; Groth16 end to
end over an encrypted board with admission from the board.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… benchmark record

Experimental rows for dkg-share-delivery-hpke-v1, a gadget-guide section with the
MUST rules (barrier, commitments last, T1, keys), ADR-0053 Q1 answered and Q7
resolved for deployments meeting the delivery contract, an informative pointer in
the threshold spec, the host benchmark record, and ADR-0054's implementation
notes 1-6 and status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ce binding, test gaps

Final whole-PR pass (spec↔code, security, Codex):
- Z-1 (P1): a crypto-provider fault was treated as envelope absence, so an honest
  recipient would complain about every honest dealer. Hpke now separates input
  failures (small order, AEAD tag, length) from platform faults (fail closed);
  start/closeRound1 run a seal-and-open self-test; the small-order probe never
  reports a fault as small order. Provider-removal tests.
- C-1: closeRound1 requires the keys/directory instances given to start.
- Z-4/X-8: keys destroyed on close or abort only; kept for retry otherwise;
  HPKE wipes intermediates in finally.
- C-2/C-3/X-1/X-2/X-3/X-5: partial-progress retry, HPKE sequence, exposure
  replay coverage, broadcasts() shape, generate() randomness, junk round-1 posts.
- M2 exit: ADR-0053 board-expressible adversarial suites rerun over encrypted
  delivery and compared with private channels.
- Docs: Z-3 exposure source, X-4/X-6 window rules, X-7/C-4 precision.
- Z-2 (dealer D7a self-check) recorded as a proposed amendment for the maintainer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…decision

R2-1/X-9 (P2): after the Z-1 fix, small order was recognised by SunEC's
InvalidKeyException. With BouncyCastle preferred, a small-order enc or announced
key raised a different exception, was classified as a platform fault, and let
one corrupted trustee stall every honest participant. Small order is now decided
before the provider is called, by membership in the five canonical small-order
u-coordinates (checked against Wycheproof); the all-zero check stays. A whole DKG
runs with BouncyCastle preferred. Pinning SunEC/SunJCE by name was tried and
broke the native image; lookups stay algorithm-only (native probe identical).

X-10: the T1 re-check in closeRound1 is documented as defence in depth.
X-11: each adversarial rerun asserts its attack took effect; the ADR claim is
narrowed to the suites actually rerun. Spec §3.2: a fault while building the
directory is not a missing key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ng, table fix

R3-1: the platform self-test in start/closeRound1 also opens the RFC 9180 A.2.1
sequence-0 ciphertext, so a provider consistent with itself but not with the
RFC is refused instead of turning every honest envelope into a complaint.
R3-2: I10 records the algorithm-only provider policy (note 10).
R3-3: the M2 status row no longer breaks the markdown table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@satran004 satran004 changed the title docs(adr): ADR-0054 encrypted DKG share delivery with HPKE (proposed) feat(dkg): ADR-0054 encrypted DKG share delivery with HPKE (accepted design and implementation) Oct 9, 2026
@satran004

Copy link
Copy Markdown
Member Author

Author note: implementation · head a3b67a1

ADR-0054 (accepted design, cc63762) is now implemented on this PR: M0 5f1c25b, M1 bc64e7b, M2 e0fe7e2, M3 c51d372, plus final-review fixes in acaff08, ece0691, 6174e2a and a3b67a1. The PR description has the full detail.

Ready for external review. This is not a production or constant-time claim. The component is Experimental.

Evidence

  • RFC 9180 A.2.1: all 257 encryptions match.
  • Wycheproof: X25519 518, ChaCha20-Poly1305 325, HKDF-SHA256 86. The standard vectors are pinned by commit and SHA-256.
  • BouncyCastle 1.83 HPKE differential: both directions.
  • Independent Python reference: 294 checks and 110 vectors, written without reading the Java code; every vector is replayed in Java.
  • Native image: the GraalVM probe's output is identical to the JVM's.
  • ADR-0053 adversarial suites: the board-expressible ones are rerun over encrypted delivery and compared with private channels.
  • Builds: a full ./gradlew build in a clean worktree passes, with 4,676 tests and 0 failures.

Internal review

  • Per milestone: adversarial and security reviewers for M1 and M2. They found one P0, which is fixed (note 1).
  • Final pass: spec↔code, security and Codex reviews over three rounds.
    • P1 Z-1: a provider fault was counted as absence.
    • P2 R2-1/X-9: small order depended on the provider.
    • Both are fixed. Both Claude reviewers approve at round 3, and Codex approved the round-1 head.

Needs maintainer acknowledgement

  1. ADR-0054 implementation notes 1–10.
  2. The proposed amendment Z-2 / T2, a dealer's own D7a self-check. It is not implemented, and my lean is a follow-up.
  3. The X-4 follow-up idea: closure evidence for final windows.

External-review gates

  • Assumption A1.
  • D7 (P1–P3), T1, D7a and I15.
  • What the application must do: use final windows only, follow the D7a posting order, and supply a verifier that never throws.
  • Provider policy (note 10).
  • Platform side channels, key erasure and SecureRandom.
  • Q4: refusing non-canonical X25519 encodings.

Not merging. Over to external reviewers.

@satran004

Copy link
Copy Markdown
Member Author

Verdict: CHANGES REQUESTED

Implementation review of ADR-0054 at a3b67a1c368c92e931f2bea36db9b214cce8b1db, against main at 1132ce9582f66730ca992fcdb2062eaededd939a, using the requested adr-pr-reviewer workflow. Implementation is explicitly in scope. The previous design findings F1–F3 remain resolved; this review does not reopen the approved design.

The fixed suite, canonical transport framing, authenticated delivery, processing barrier, T1, instance binding and separation of input failures from platform faults agree with the accepted design. The independent-vector, differential, adversarial-DKG, integration and native-image evidence reproduced successfully. One P2 secret-lifecycle finding remains: the key-schedule helpers bypass cleanup when HKDF throws, contrary to implementation note 9. I found no new protocol-validity or encoding counterexample in this pass.

F4 [P2] Clear intermediate HPKE secrets when key derivation fails

Location: Hpke.java, lines 240–256, keySchedule and extractAndExpand; ADR-0054 implementation note 9.

Problem: eaePrk and secret are wiped only after the following HKDF operations return successfully. If expansion throws, those fills are skipped. If base_nonce expansion throws after key was allocated, the AEAD key is also left unwiped because no Context was returned for the caller to destroy. The outer finally blocks clear dh and sharedSecret, but cannot reach these helper-local arrays. Both sealing and opening use these helpers.

Evidence: A temporary KDFSpi probe delegates successful derivations to the actual SunJCE KDF, keeps references to the arrays returned to ZeroJ, and injects a ProviderException at a selected derivation. It disables JCA's fallback to a second KDF provider so the injected fault actually reaches ZeroJ. No production files are changed, and only synthetic test keys are used.

Failure point ZeroJ-owned secret arrays still nonzero after the exception
shared_secret expansion, derivation 2 eaePrk
key expansion, derivation 6 secret
base_nonce expansion, derivation 7 secret, key
Successful control run All captured secret arrays are wiped

This concerns avoidable retention of arrays owned by ZeroJ after a platform failure, including failures during the documented retry flow. It is not a demonstrated remote key-recovery attack or a claim that Java can guarantee erasure. The documented limitations of provider-internal copies do not explain skipping cleanup of these accessible arrays.

Requested revision: put eaePrk and secret cleanup in finally; wipe any derived key whose ownership was not successfully transferred to a returned Context. Add fault-injection coverage after extraction and after key derivation, preserving the existing fail-closed behavior and successful RFC/differential outputs. Keep the best-effort qualification. This completes the accepted lifecycle requirement; no protocol change is requested.

Things to retain and remaining gates

  • Authentication before de-duplication, the barrier and instance binding, provider-independent small-order classification, canonical message encodings and public-answer scope.
  • Separate input rejection from platform failure. The fault-injection cleanup fix must not convert a platform exception into an absent share.
  • The Experimental/offline classification, Assumption A1, deployment finality/posting-order duties, provider policy, platform side-channel and erasure gates.
  • T2/Z-2 and closure evidence remain explicitly recorded maintainer decisions/follow-ups. I am not treating their absence as a new implementation finding: the accepted profile assigns those duties to the application.

Validation and scope

Executed in an isolated worktree at the reviewed SHA, on Java 25.0.2:

./gradlew :zeroj-circuit-lib:test --tests 'org.zeroj.circuit.lib.jubjub.*'
./gradlew :zeroj-integration-tests:test --tests '*AnnotatedElGamalTest*'
./gradlew :zeroj-circuit-lib:elgamalBenchmark --tests '*ElGamalBenchmark.dkgShareDelivery'
python3 zeroj-circuit-lib/src/test/resources/dkg-share-delivery-reference/dkg_share_delivery_hpke_v1_reference.py
git diff --check 1132ce9582f66730ca992fcdb2062eaededd939a..a3b67a1c368c92e931f2bea36db9b214cce8b1db
  • Jubjub suite: 717 tests, 708 passed, 9 skipped, 0 failures/errors. This includes the RFC 9180 encryptions, Wycheproof vectors, BouncyCastle differential, encrypted-delivery negatives, and reference replay.
  • Integration: 5 passed, 0 failures/errors/skips, including encrypted-board DKG → admission → Groth16-proved tally.
  • Python reference: 294 checks, 110 vectors, 0 failures; regenerated output is byte-identical to the committed file.
  • Re-fetched the CFRG HPKE vector at b1f7cb0cdeab6906c61b3d6574e8bdfdbe1cd3fb and the three Wycheproof files at 12fd3aaf33eb5fa1f52e026912ee00c054f9d984. SHA-256 values match; the filtered HPKE object is identical and Wycheproof files are byte-identical.
  • Re-fetched RFC 9180, RFC 7748, RFC 8439 and RFC 5869 for the HPKE composition, decoding and primitive checks. The underlying GJKR07 design approval is retained; this pass does not claim a new proof of A1.
  • GraalVM 25.0.2: built HpkeNativeProbe with native-image --no-fallback; its entire output matches the JVM output. Build took 19.5 s, peak build RSS 2.26 GB. No added native-image configuration.
  • Benchmark: 139 µs seal, 72 µs open, 66 µs announcement probe. Whole-run plain/encrypted times in ms: (1,3) 51/55, (2,5) 143/143, (3,7) 295/304, (5,11) 820/855, (10,21) 4151/3897. These are indicative single-host runs with other validation work active, not a statistical regression bound or a portable guarantee. No material end-to-end regression was demonstrated.
  • Maximum supported roster probe (t,n)=(31,64): both runs finish without aborts, all 64 contexts and secret shares match, and all 4,032 envelopes are produced. Transcript digest agrees: 79194616513c0e8b40d5954c8ddd1ad79032f39ba7da6d882a42a629bc1c84c1. Plain/encrypted times were 138.4/110.4 s in one sequential JVM run (warm-up/order effects apply); combined process peak RSS was 1,649,688,576 bytes, with -Xmx2g. This verifies equivalence at the roster limit, not a transport speedup.
  • GitHub CI at the reviewed SHA reports successful build, both platform test jobs and assurance jobs. The full local build was not repeated; the focused tests above were run directly.

No author implementation files were changed. The scratch worktree remains clean. Prior ADR acceptance remains design acceptance only; neither that approval nor these test results certify production safety, constant-time behavior, or security.

Reproducible F4 fault-injection probe (scratch source, not a proposed production change)

Save as FailureWipeProbe.java outside the checkout, after the Gradle build above. It reports erasure state only; it prints no key bytes.

javac -cp zeroj-circuit-lib/build/classes/java/main -d /tmp/pr80-probe /tmp/FailureWipeProbe.java
java -cp /tmp/pr80-probe:zeroj-circuit-lib/build/classes/java/main org.zeroj.circuit.lib.jubjub.FailureWipeProbe
package org.zeroj.circuit.lib.jubjub;

import javax.crypto.KDF;
import javax.crypto.KDFParameters;
import javax.crypto.KDFSpi;
import javax.crypto.SecretKey;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.spec.AlgorithmParameterSpec;
import java.util.ArrayList;
import java.util.List;

public final class FailureWipeProbe {
    private static final Provider REAL = Security.getProvider("SunJCE");
    public static final class ProbeProvider extends Provider {
        public ProbeProvider() {
            super("ReviewKdf", "1", "Delegating fault-injection provider");
            put("KDF.HKDF-SHA256", ProbeKdf.class.getName());
        }
    }
    public static final class NonKdfProvider extends Provider {
        public NonKdfProvider() {
            super("SunJCE", "1", "Original services except KDF, for a no-fallback fault probe");
            REAL.forEach((k, v) -> {
                if (!k.toString().startsWith("KDF.") && !k.toString().startsWith("Alg.Alias.KDF.")) put(k, v);
            });
        }
    }
    public static final class ProbeKdf extends KDFSpi {
        static final List<byte[]> returned = new ArrayList<>();
        static int calls;
        static int failAt;
        public ProbeKdf(KDFParameters parameters) throws InvalidAlgorithmParameterException {
            super(parameters);
        }
        protected KDFParameters engineGetParameters() { return null; }
        protected SecretKey engineDeriveKey(String algorithm, AlgorithmParameterSpec spec)
                throws InvalidAlgorithmParameterException, NoSuchAlgorithmException {
            throw new NoSuchAlgorithmException("unused");
        }
        protected byte[] engineDeriveData(AlgorithmParameterSpec spec)
                throws InvalidAlgorithmParameterException {
            if (++calls == failAt) throw new java.security.ProviderException("review-injected failure");
            try {
                byte[] bytes = KDF.getInstance("HKDF-SHA256", REAL).deriveData(spec);
                returned.add(bytes);
                return bytes;
            } catch (NoSuchAlgorithmException e) {
                throw new IllegalStateException(e);
            }
        }
    }
    public static void main(String[] args) throws Exception {
        byte[] skR = new byte[32]; skR[0] = 7;
        byte[] skE = new byte[32]; skE[0] = 11;
        byte[] pkR = X25519Bytes.publicFromPrivate(skR);
        Security.insertProviderAt(new ProbeProvider(), 1);
        Provider sunJce = Security.getProvider("SunJCE");
        try {
            for (int failure : new int[]{2, 6, 7, 0}) {
                Security.removeProvider("SunJCE");
                Security.addProvider(failure != 0 ? new NonKdfProvider() : sunJce);
                ProbeKdf.calls = 0; ProbeKdf.failAt = failure; ProbeKdf.returned.clear();
                try {
                    Hpke.sealBaseWithEphemeral(skE, pkR, new byte[]{1}, new byte[0], new byte[100]);
                    if (failure != 0) throw new AssertionError("missing fault; calls=" + ProbeKdf.calls + "; explicit=" + KDF.getInstance("HKDF-SHA256", "ReviewKdf").getProviderName());
                } catch (IllegalStateException expected) {
                    if (failure == 0) throw expected;
                    if (ProbeKdf.calls != failure) throw new AssertionError("unexpected fault before injected call " + failure, expected);
                }
                System.out.print("failAt=" + failure + " ");
                String[] labels = {"eaePrk", "sharedSecret", "pskIdHash(public)", "infoHash(public)", "secret", "key", "baseNonce"};
                for (int j = 0; j < ProbeKdf.returned.size(); j++) {
                    System.out.print(labels[j] + "=" + (X25519Bytes.isAllZero(ProbeKdf.returned.get(j)) ? "wiped" : "RETAINED") + " ");
                }
                System.out.println();
            }
        } finally { Security.removeProvider("ReviewKdf"); }
    }
}

The key schedule and ExtractAndExpand wiped eae_prk and secret only after the
following derivations returned; a failure part-way left them (and a derived key
not yet handed to a Context) unwiped. They are now wiped on every path; key and
base_nonce are wiped unless ownership passes to the returned Context.

HpkeFailureWipeTest injects HKDF failures through a package-private Hpke.Hkdf
seam (any JDK) and through a delegating JCA provider (runs on OpenJDK builds;
Oracle JDK/GraalVM accept only signed JCE providers and skip it). Failures stay
platform faults, never input failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@satran004

Copy link
Copy Markdown
Member Author

Author reply: round r1 (implementation) · head 914b68c

Thanks. F4 is accepted and fixed. I reproduced your probe before changing anything, and the change is limited to the secret lifecycle; the protocol is untouched.

Finding Change Where
F4 [P2] intermediate HPKE secrets kept when HKDF fails extractAndExpand wipes eae_prk in finally. keySchedule wipes secret on every path, and wipes key/base_nonce unless ownership passes to the returned Context; the caller's destroy() then covers them, as before. The deriveKeyPair test seam wipes dkp_prk the same way. Hpke.java (keySchedule, extractAndExpand, deriveKeyPair); ADR-0054 implementation note 9 and the review history

Fault-injection coverage (HpkeFailureWipeTest)

  • Seam tests, run on every JDK: a package-private Hpke.Hkdf interface takes the two HKDF calls. Production code always uses Hpke.JDK_HKDF, which is the same javax.crypto.KDF lookup by algorithm name as before, so it is not mutable state. The tests fail chosen derivations and check:
    • a failure expanding shared_secret leaves eae_prk wiped;
    • a failure at key leaves secret wiped; a failure at base_nonce leaves secret and key wiped;
    • in the control run, secret is wiped and key/base_nonce live in the context until destroy() wipes them. The seam produces the same key as the JDK HKDF.
  • JCA tests, end to end: this is your delegating-provider probe as a test, with SunJCE's KDF hidden. It checks that seal fails at derivations 2, 6 and 7, open fails at 7, and the control passes. A failure still surfaces as IllegalStateException, a platform fault, so it is never treated as an absent share.
    • Caveat: Oracle JDK and GraalVM refuse unsigned JCE providers ("JCE cannot authenticate the provider"), so these tests skip themselves there, which includes our CI (distribution: graalvm). That is why the seam tests exist.
    • I ran the full class on Liberica 25.0.2 (BellSoft OpenJDK): 6 of 6 passed, none skipped.
  • Mutation check: with the finally wipes removed, the seam tests fail.

Verification at 914b68c

  • :zeroj-circuit-lib:test --tests 'org.zeroj.circuit.lib.jubjub.*' on GraalVM 25.0.2: 723 tests, 0 failed, 12 skipped. These are the 9 skipped before, plus the 3 JCA tests skipped on GraalVM.
  • The GraalVM native-image HpkeNativeProbe was rebuilt; its output is identical to the JVM's and unchanged from before.
  • RFC 9180 A.2.1, Wycheproof and BouncyCastle differential results are unchanged; those tests are part of the suite above.

Kept as you asked: input rejection and platform failure stay separate. The wiping remains best effort; copies held inside the provider are still outside ZeroJ's control, as note 9 says. T2/Z-2 and closure evidence remain maintainer follow-ups.

@satran004

Copy link
Copy Markdown
Member Author

Verdict: APPROVED

Implementation re-review of 914b68cdcf92c9ab7ecaeee621c517db688f1a04, diffed from a3b67a1c368c92e931f2bea36db9b214cce8b1db, responding to the author's implementation reply.

The implementation is accepted against ADR-0054 for its stated Experimental/offline scope at this SHA. There are no open P0–P2 findings from this review and no new findings in the revision. The earlier design acceptance remains unchanged.

Finding Status Independently checked resolution
F4 [P2] intermediate HPKE secrets retained when HKDF fails Resolved extractAndExpand and deriveKeyPair now clear their PRKs in finally. keySchedule clears secret on every path and clears key/baseNonce unless ownership transfers to the returned Context. The immutable production JDK_HKDF still uses the same algorithm-only JCA lookup; the new package-private test seam does not replace the production provider policy. ADR implementation note 9 and the review history record the fix.
F1–F3, prior design review Resolved; retained This revision changes neither the processing/posting contract nor the exposure and answer-scope rules.

I reran the original external fault-injection probe, unchanged, against the new classes. Its real SunJCE derivations now show eaePrk, secret, and the untransferred AEAD key wiped at all three failure points. The successful control still works and clears the secrets. The failure remains a platform exception, preserving fail-closed behavior.

Validation at 914b68c

./gradlew :zeroj-circuit-lib:test --tests 'org.zeroj.circuit.lib.jubjub.*'
./gradlew :zeroj-integration-tests:test --tests '*AnnotatedElGamalTest.thresholdEndToEndOverEncryptedBoard' :zeroj-circuit-lib:elgamalBenchmark --tests '*ElGamalBenchmark.dkgShareDelivery'
git merge-base --is-ancestor a3b67a1 914b68c
git diff --check a3b67a1..914b68c
  • 723 Jubjub tests: 714 passed, 9 skipped, 0 failures/errors. All six HpkeFailureWipeTest cases passed without skips on this OpenJDK 25.0.2 run, including the JCA-provider tests. The documented Oracle/GraalVM unsigned-provider limitation is covered by the additional seam tests; it did not suppress the JCA tests here.
  • The encrypted-board DKG → admission → Groth16-proved tally integration test passed.
  • The HPKE benchmark passed: 140 µs seal, 72 µs open, 66 µs announcement probe, effectively unchanged from the first review's 139/72/66 µs. Whole-run plain/encrypted times were 58/55, 185/173, 401/381, 1215/1115 and 6515/5551 ms for (t,n)=(1,3),(2,5),(3,7),(5,11),(10,21). Shared-host and run-order noise apply; these numbers are not a speedup claim or a statistical performance guarantee.
  • Rebuilt HpkeNativeProbe with GraalVM 25.0.2, --no-fallback. Its entire output matches both the new JVM output and the prior-head JVM output. The added HKDF seam introduced no native-image reachability/configuration issue in this probe.
  • The original review's byte-identical Python reference rerun, upstream-vector provenance checks, and (31,64) transcript/context/share equivalence probe remain baseline evidence; those unchanged artifacts and the maximum-roster probe were not rerun for this cleanup-only revision. RFC, differential and Java reference-replay tests were rerun as part of the 723-test suite.
  • The new head is a descendant of the reviewed head, the three-file diff is bounded to cleanup/tests/ADR notes, git diff --check passes, and the review worktree is clean. No author implementation files were changed by this review.

Retained scope and follow-ups

No P3 findings remain from this review. T2/Z-2 and closure evidence remain the explicitly recorded maintainer design follow-ups; application finality, complete windows and D7a posting order remain mandatory under the accepted profile. Assumption A1, the transport argument, platform/provider side channels and erasure, and native-image coverage for released platforms retain their external-review gates. The refreshed full CI jobs were still running when checked; local validation above does not represent their completion.

This approval does not certify production readiness, constant-time execution, guaranteed erasure or cryptographic security, and it upgrades no maturity claim. Commits after 914b68c are not covered. Under the skill's shared-account convention, this verdict comment is the approval record. Monitoring stops at this approval; the PR is not merged by this review.

@satran004

Copy link
Copy Markdown
Member Author

Follow-up on the two P3 findings, checked against 914b68cdcf92c9ab7ecaeee621c517db688f1a04. I agree they are worth addressing. Neither changes my no-blocking-findings assessment under the accepted ADR and its documented application obligations; my technical approval remains limited to the Experimental/offline scope.

  1. Reject invalid start() calls before destructive checks.

    In DkgShareDelivery.start(), directory.requireOwn(keys) runs before the participant's lifecycle validation. Calling it on an already-started participant with a missing/conflicting own-key announcement therefore aborts the participant and destroys the supplied keys.

    Validate that the participant is eligible to start before T1 processing or mutation, preserving existing aborted-participant semantics. An already-started participant should receive IllegalStateException without changes to participant state or keys.

    Add regression tests covering an already-started participant with missing/conflicting own-key announcements. Preserve the intended T1 abort and key destruction for a legitimate first start.

  2. Enforce identical windows across closeRound1() retries.

    An interrupted attempt may already have delivered messages. The identical-window retry requirement currently exists only in Javadoc.

    Bind the participant's round-1 delivery attempt to the complete window before its first delivery, using a digest or equivalent immutable snapshot. Reject a different retry window before further processing or mutation. If hashing, use unambiguous framing covering every message and authenticator, with explicitly defined ordering and duplicate handling.

    Test an injected failure after partial delivery: an identical retry succeeds; changed, added, or removed entries are rejected while preserving participant state and keys. Include changes to message bytes and authenticator bytes.

These are lifecycle correctness and contract-enforcement fixes. Window binding does not establish board finality, completeness, or agreement across participants. Keep those application obligations and the Experimental/offline classification explicit. Security, correctness, and performance remain mandatory.

Please update relevant documentation, run affected tests with the Gradle wrapper, and report results plus any ADR implications. Keep the proposed T2/Z-2 amendment outside this patch.

…re mutation

1. DkgShareDelivery.start refuses an ineligible participant before T1.
   An already-started participant gets IllegalStateException, and an
   aborted one rethrows its abort. Neither aborts the participant nor
   destroys the keys. A legitimate first start still applies T1.

2. closeRound1 enforces the identical-window retry. The first call that
   reaches delivery binds the participant to a SHA-256 digest of the
   window: every message and authenticator, length-prefixed, in order,
   repeats counted. A retry with any other window gets
   IllegalArgumentException before T1 or any delivery. This does not
   establish finality, completeness or agreement (P1, P2 stay the
   application's).

Tests: startAgainRefusedBeforeT1, retryNeedsIdenticalWindow (changed
message/authenticator bytes, added/removed/reordered posts after a
partial delivery; the identical retry succeeds) and windowDigestFraming.
Each fix's mutant is killed. ADR-0054 implementation note 11, spec §4.2
and the gadget guide are updated. T2/Z-2 is not touched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@satran004

Copy link
Copy Markdown
Member Author

Author reply: round r5 · head 52e9bf5

This responds to the follow-up on 914b68c (comment). I agree with both points, and both are fixed in 52e9bf5. T2/Z-2 is not touched.

Item Change Where
1. Reject an invalid start() before destructive checks start calls a new DkgParticipant.requireStartable() right after the session and identifier checks, before T1. An already-started participant gets IllegalStateException; an aborted one rethrows its own abort, as before. Neither path aborts the participant or destroys the keys. A legitimate first start still aborts on T1 and destroys the keys. DkgParticipant.start() uses the same check. DkgShareDelivery.start, DkgParticipant.requireStartable
2. Enforce identical windows across closeRound1() retries The first call that reaches delivery (after the self-test, before the first post) binds the participant to windowDigest(window). A later call with a different digest gets IllegalArgumentException before the T1 re-check, the self-test or any delivery, so nothing changes. One immutable snapshot of the list feeds both the digest and the deliveries. DkgShareDelivery.closeRound1, windowDigest; DkgParticipant.round1WindowMatches, bindRound1Window

Digest framing. SHA-256 over "zeroj.dkg-share-delivery-hpke.v1.round1-window" ‖ u32(count), then for each post in the given order u32(|message|) ‖ message ‖ u32(|authenticator|) ‖ authenticator. Lengths are big-endian. Every field is length-prefixed, so the framing is unambiguous.

  • Ordering is significant and repeats count: a reordered window, or one with a duplicated post, is a different window.
  • The digest is local and never posted. Comparison uses MessageDigest.isEqual.

Scope, stated in the Javadoc, spec §4.2, ADR note 11 and the gadget guide. Binding checks only that a retry repeats the first window. It does not establish board finality or completeness, or agreement across participants. Those remain application obligations (P1, P2), and the Experimental/offline classification is unchanged.

Tests (DkgShareDeliveryTest.Lifecycle):

  • startAgainRefusedBeforeT1
    • A started participant passed a directory with a missing own key, then one with a conflicting own key, gets IllegalStateException. Its keys are kept, it stays at round 1 and still bound to its keys and directory, and it closes round 1 normally afterwards.
    • A fresh participant with a missing key still gets T1, with its keys destroyed.
    • A second start on that aborted participant rethrows the same abort (assertSame) and leaves new keys untouched.
  • retryNeedsIdenticalWindow
    • The verifier throws after a partial delivery.
    • Each of these is then refused with no change to the participant's received shares, round or keys: changed message bytes, changed authenticator bytes, an added post, a removed post and a reordered window.
    • An identical window rebuilt from fresh copies then succeeds with no complaints and exactly one share per dealer.
  • windowDigestFraming: moving a byte between message and authenticator, or between posts, changes the digest; equal contents give equal digests.
  • Mutation checks. Each of these mutants makes one test fail:
    • removing the requireStartable call in start;
    • disabling the window comparison;
    • dropping the authenticator from the digest.

Results (Gradle wrapper, Java 25.0.2-graal, at 52e9bf5):

  • ./gradlew :zeroj-circuit-lib:test: 1,021 tests, 0 failed, 21 skipped. The jubjub package is 726 tests, 0 failed, 12 skipped; it was 723 before.
  • ./gradlew :zeroj-integration-tests:test --tests '*AnnotatedElGamalTest*': 5 of 5 pass.
  • The Javadoc builds with no warnings on the touched classes.
  • CI has not finished yet.

ADR implications. No design decision changes; this is recorded as implementation note 11. Spec §4.2 already allowed a retry only over "the same final window". It now says so explicitly, and adds that repeating the window is no evidence of finality, completeness or agreement. The Python reference does not model retries, so no vectors change.

Performance. The digest adds one SHA-256 pass over the round-1 window on each closeRound1 call. I have not measured it. My estimate is well under a millisecond at the sizes in the benchmark doc, against about 59 µs per HPKE open.

@satran004

Copy link
Copy Markdown
Member Author

Verdict: APPROVED

Implementation re-review of 52e9bf5bafe2cadf6760bef174c5a74313d45b4c, diffed from 914b68cdcf92c9ab7ecaeee621c517db688f1a04, responding to author reply r5 and the two P3 follow-ups.

Both follow-ups are resolved. No new blocking findings. The implementation is accepted against ADR-0054 for its stated Experimental/offline scope at this SHA. The earlier design acceptance and its external-review gates remain unchanged.

Item Status Independently checked resolution
Follow-up 1 [P3]: invalid start() can abort an existing run Resolved requireStartable() runs before T1 and any mutation. Started participants are refused without destroying keys or changing their binding; aborted participants rethrow their original abort. A legitimate first start still applies T1. The shared check preserves DkgParticipant.start() semantics.
Follow-up 2 [P3]: identical-window retries only documented Resolved One immutable list snapshot supplies both hashing and delivery. The first call reaching delivery binds the participant before the first post. Different retries are refused before T1, self-test, authentication or delivery. The SHA-256 framing includes a domain tag, post count, and length-prefixed message/authenticator bytes, preserving order and duplicate multiplicity. AuthenticatedDkgMessage defensively copies its arrays.
F1–F4 from prior reviews Resolved; retained Processing/posting and exposure rules are unchanged. All six F4 secret-wipe regression tests passed again.

ADR implementation note 11, spec §4.2, the API documentation and the gadget guide agree on the new behavior. The digest is local retry enforcement, not a wire-format or DKG transcript change. It establishes neither finality/completeness nor agreement between participants; those obligations remain explicit. T2/Z-2 remains the separate recorded design follow-up.

Validation at this SHA — isolated worktree, OpenJDK 25.0.2:

./gradlew :zeroj-circuit-lib:test --tests 'org.zeroj.circuit.lib.jubjub.*' :zeroj-integration-tests:test --tests '*AnnotatedElGamalTest*' :zeroj-circuit-lib:elgamalBenchmark --tests '*ElGamalBenchmark.dkgShareDelivery'
./gradlew :zeroj-circuit-lib:elgamalBenchmark --tests '*ElGamalBenchmark.dkgShareDelivery'
git merge-base --is-ancestor 914b68c 52e9bf5
git diff --check 914b68c..52e9bf5
  • 726 Jubjub tests: 717 passed, 9 skipped, 0 failures/errors. All three new regression tests and all six HPKE secret-wipe tests passed without skips.
  • All 5 AnnotatedElGamalTest integration tests passed, including encrypted-board DKG → admission → Groth16-proved tally. The benchmark test passed.
  • A temporary standalone probe independently checked the original private-channel reuse scenario with missing/conflicting announcements, first-start conflict T1, caller-list mutation during authentication, actual partial share delivery, changed-window rejection before invoking the verifier, and successful identical retry with one share per remote dealer.
  • 101 digest cases matched an independent Python hashlib/struct implementation of the documented framing, including the empty window and varied field lengths.
  • Built that probe using GraalVM 25.0.2 native-image --no-fallback. The lifecycle/snapshot/retry checks passed natively, and all 101 native digests matched both the JVM and Python. No additional native-image configuration was supplied.
  • Ancestry and whitespace checks passed; the review worktree was clean. No author implementation files were changed.

Performance: the second benchmark ran after native-image compilation finished; the first run's overlapping compilation distorted its timings, so it is not used for comparison. The rerun measured 139 µs seal / 71 µs open / 65 µs announcement probe, consistent with the previous review's 140/72/66 µs. Whole-run plain/encrypted times were 56/56, 180/171, 392/379, 1225/1094 and 6452/5487 ms for (t,n)=(1,3),(2,5),(3,7),(5,11),(10,21). Run-order and shared-host noise apply; the negative differences are not a speedup claim.

The added digest itself was also measured on synthetic windows containing all n(n-1) 223-byte envelopes plus n commitment messages and 64-byte authenticators. Median per-call times over seven batches after warm-up:

Participants Posts Message + authenticator bytes JVM Native image
21 441 130,032 0.061 ms 0.516 ms
64 4,096 1,229,120 0.485 ms 4.903 ms

The digest adds a linear pass over the supplied bytes and retains only a 32-byte binding in the participant. These measurements support a small added cost for the tested windows; they are not a portable performance guarantee or a bound for arbitrarily large application-supplied windows.

Scope: unchanged upstream-vector provenance, Python profile-reference reruns and the earlier complete 64-participant equivalence run remain baseline evidence and were not repeated for this bounded revision. Java RFC/differential/reference-replay tests were rerun. The full remote CI build/Linux/macOS jobs were still running at the final check; the WASM, snarkjs, gnark and documentation-build checks had succeeded.

No P3 follow-ups remain from these two items. Assumption A1, the delivery contract, provider side channels/erasure and released-platform coverage retain their external-review gates. This approval does not certify production readiness, constant-time execution, guaranteed erasure or cryptographic security, and it upgrades no maturity claim. Commits after 52e9bf5 are not covered. Under the skill's shared-account convention this comment records the technical approval; GitHub branch protection still requires an independent formal review. Monitoring stops at approval; this review does not merge the PR.

@satran004
satran004 merged commit 45732dc into main Oct 9, 2026
@satran004
satran004 deleted the design/adr-0054-hpke-dkg-share-delivery branch October 9, 2026 12:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant