diff --git a/docs/adr/0053-threshold-elgamal-jubjub-dkg.md b/docs/adr/0053-threshold-elgamal-jubjub-dkg.md index 1b3691c2..72100c00 100644 --- a/docs/adr/0053-threshold-elgamal-jubjub-dkg.md +++ b/docs/adr/0053-threshold-elgamal-jubjub-dkg.md @@ -11,6 +11,10 @@ Accepted (design) — 2026-10-05. - Q2–Q6 were decided by the maintainer on 2026-10-05: each recorded lean is adopted. Q1 (the private channels) stays escalated and does not block the library, whose transport is pluggable (#77). +- **2026-10-09:** Q1 is answered by ADR-0054 (Accepted), which provides an optional ZeroJ + transport for the private shares: HPKE-encrypted envelopes on the board. Q7 is resolved for + deployments that use that transport and meet its delivery contract (ADR-0054 Q6). Neither + changes this ADR's protocol, encodings or admission. This ADR builds on ADR-0052 (Accepted). It changes no maturity claim. ADR-0039's assurance classes apply: every secret-bearing operation here is **compatibility/offline** class. @@ -510,6 +514,11 @@ ADR-0052's host API, ADR-0052's own M0 and M1 come first (see the PR description would need its own pinned references and review. - Lean: (a). **Escalated**, and still open; tracked in #77. The library takes no position: the transport is the application's. + - **Answered 2026-10-09 by ADR-0054 (Accepted).** It adds an optional transport, + `dkg-share-delivery-hpke-v1`: each `SHARE` is HPKE-encrypted (RFC 9180) to a per-attempt + recipient key and posted on the board. It is a pinned standard used as specified, not new + cryptography, and replacing ideal channels by encryption is stated there as Assumption A1, + for external review. Option (a) stays available. 2. **Q2 (D2): thresholds above a majority**, such as 4-of-5. - Lean: unsupported. Theorem 1 covers only `t < n/2`. - **Decided 2026-10-05 (maintainer): lean adopted.** @@ -543,6 +552,17 @@ ADR-0052's host API, ADR-0052's own M0 and M1 come first (see the PR description disqualification. This changes `QUAL` semantics and needs analysis; - (c) use a construction from the asynchronous-DKG literature (out of scope, D8). - Lean: (a), with the transport review gate covering deadlines. **Escalated.** + - **Resolved 2026-10-09, scoped (ADR-0054 Q6).** For deployments that use + `dkg-share-delivery-hpke-v1` and meet its contract, a share is delivered when its envelope + is in the final round-1 window. Three rules then apply: + - the processing barrier (ADR-0054 D6a); + - abort T1 for a missing own key (D4); + - a dealer's `COMMITMENTS` only after its envelopes are final (D7a). + + Together they make an honest recipient's false absence complaint impossible, and keep every + answer by an honest qualified dealer at a corrupted index. Secrecy then no longer depends on + publication timing. The precondition, and this question, stay as stated above for + application-provided channels. ## Related findings (out of scope) diff --git a/docs/adr/0054-hpke-dkg-share-delivery.md b/docs/adr/0054-hpke-dkg-share-delivery.md new file mode 100644 index 00000000..cddb4fd4 --- /dev/null +++ b/docs/adr/0054-hpke-dkg-share-delivery.md @@ -0,0 +1,834 @@ +# ADR-0054: Encrypted DKG share delivery with HPKE (`dkg-share-delivery-hpke-v1`) + +## Status +Accepted (design) — 2026-10-09. +- The reviewer approved r3 at `cc63762` with no outstanding findings, and the maintainer + accepted the design. +- Acceptance is design acceptance only. It certifies no implementation, test or security + property. +- Q1–Q8 were decided by the maintainer on 2026-10-09: each recorded lean is adopted (see "Open + questions"). +- It answers ADR-0053's Q1 ("how are the private channels realized?") with an **optional** + ZeroJ-provided transport. Application-provided channels (ADR-0053 D3) stay supported. +- It bears on ADR-0053's Q7 (late shares under partial synchrony); see D7 and Q6. +- Tracked as #77. M0–M3 are implemented on PR #80 and reviewed internally (per milestone and in + a final whole-PR pass); the PR awaits external review. The "Implementation status" section at + the end records the state. The implementation is Experimental and makes no production claim. + +This ADR changes no maturity claim. ADR-0039's assurance classes apply: every secret-bearing +host operation here is **compatibility/offline** class. + +## Date +2026-10-05 (proposed); 2026-10-09 (accepted) + +## Revision history +- **r1** (`eb8ddd6`, 2026-10-05): initial proposal. +- **r2** (`9a2f7ab`, 2026-10-05; responds to the review of `eb8ddd6`): + - F1 → new D6a (a processing barrier: a window is final, retrieved and fully processed before + a participant seals or closes round 1); D7 rewritten as an explicit contract P1–P3; new D7a + (a dealer's `COMMITMENTS` only after its envelopes are final, or atomically); new transport + abort T1 in D4 (own announcement missing); a timing bullet in the threat model; new I11–I13; + M0/M2 tests for late-processed envelopes, delayed announcements and envelopes excluded by the + cutoff; Q6 rescoped; new Q8. + - F2 → the threat model's key-compromise bullet is replaced by exposure accounting that + separates leaked recipient keys, full trustee state and public disclosures, with per-dealer + evaluation-index counting (no dealer sends itself an envelope). New I14; M0/M2 exposure tests; + D5 and Risks updated. + - Review note on key import → D8 and M1: the 32-byte-to-key adapter decodes explicitly and does + not rely on provider masking. +- **r3** (2026-10-05; responds to the review of `9a2f7ab`): F3 → the disclosure guarantee is + scoped. D7 now says what answers can still reveal: corrupted trustees may complain, and dealers + answer before their own-qualification check, at corrupted indices only. D7a and I13 no longer + claim "no answer"; a dealer without `COMMITMENTS` is excluded from `QUAL` and draws no honest + complaint. New I15 (answer scope). M2 and the timing harness include both adversarial-complaint + traces. The threat model's public-answer example is scoped to honest indices. No change to + Fig. 2's rules. +- **Accepted** (2026-10-09): approved at r3 (`cc63762`); status flipped without changing the + design text. +- **Decisions recorded** (2026-10-09): the maintainer adopted the leans of Q1–Q8. No design text + changes. + +## Risk classification +- **R3:** D1 (the ciphersuite and mode), D2 (the composition that replaces [GJKR07]'s ideal + private channels) and D5 (recipient key lifecycle). These decide whether a share stays secret. +- **R2:** D3 (the envelope and its binding), D4 (key announcement and abort T1), D6 (failure + handling and the interface to `DkgParticipant`), D6a (the processing barrier), D7 and D7a + (the delivery contract and the dealer's posting order) and D8 (encodings and canonicality). + +## Context + +[GJKR07] §2.1 assumes that the trustees "are connected by a complete network of private (i.e., +untappable and authenticated) point-to-point channels", in addition to "a dedicated broadcast +channel". ADR-0053 implements New-DKG over Jubjub and leaves both to the application (D3), with Q1 +escalated. PR #76's `DkgParticipant` takes private deliveries through +`receivePrivate(authenticatedSender, message)`, so the transport is pluggable. + +Leaving the private channels to every application has costs: +- Each application must build and review its own confidential, authenticated channel. That is + exactly the kind of security-critical code ZeroJ exists to provide once, reviewed. +- Point-to-point channels such as TLS between trustees need trustees to be online together and + reachable, and leave no evidence of delivery. +- ADR-0053's implementation review found that **timely private delivery is a secrecy + precondition** (spec §5.2, Q7). A `SHARE` that misses its round draws a complaint. The + dealer's answer then publishes the pair, and with the `t` shares the faulty participants hold, + that determines the dealer's polynomial. If that happens for every honest dealer, the joint key + is exposed with no abort. + +Cardano gives a natural alternative. The trustees already need a broadcast board with agreement +and round closure (ADR-0053 D3, D4a), for example transactions. If each dealer **encrypts each +share to its recipient's key and posts the ciphertext on that board**, then: +- delivery is provable: everyone sees whether, and when, an encrypted share was posted; +- trustees need not be online together or reach each other; +- the board decides which shares were delivered. With a processing barrier, a commitments-last + posting order and an abort for a missing own announcement (D6a, D7, D7a, D4), secrecy no longer + depends on private-delivery timing. + +The scheme must be a pinned standard used exactly as specified. HPKE (RFC 9180) is the standard +construction for encrypting one message to a public key, and Java 25 provides every building +block (D1). + +The [GJKR07] Appendix, "Committing Encryption on a Broadcast Channel", shows that encrypting +shares on the broadcast channel **does not fix the bias attack on JF-DKG** (Fig. 1). The attack +works because a JF-DKG dealer's contribution is still undecided when complaints are filed. It +does not say that encryption is unsafe for New-DKG. New-DKG's two-phase structure, with Pedersen +commitments fixed before `QUAL` is decided and extraction only afterwards, is what prevents bias, +and this ADR leaves New-DKG unchanged. + +## Threat model and trust assumptions + +This extends ADR-0053's threat model, which still applies in full. + +- **Adversary:** static and rushing, corrupting up to `t < n/2` trustees ([GJKR07] §2.1), as in + ADR-0053. Adaptive corruption stays out of scope (ADR-0053 D8). +- **The board is public and permanent.** Every ciphertext posted on it can be stored forever by + anyone ("harvest now, decrypt later"). +- **Broadcast with agreement and round closure** is still provided by the application + (ADR-0053 D3). Board posts are authenticated under the roster keys (ADR-0053 D4a). +- **Untrusted:** every announced encryption key, every envelope, and the plaintext inside it, + until it passes ADR-0053's `SHARE` checks. +- **Secret:** + - each trustee's HPKE private key `skR` for the attempt; + - every share pair `(s_ij, s'_ij)` before the dealer publishes it in an answer; + - each dealer's encapsulation randomness. +- **HPKE's guarantees and limits (RFC 9180):** + - §9.1 and §9.1.2: Base mode targets message secrecy against chosen-ciphertext attacks. + [CS01] shows that a hybrid scheme of essentially this form is IND-CCA2 secure when its KEM + and AEAD are. The RFC notes that the extra KDF calls in HPKE need their own analysis + ([HPKEAnalysis]). + - §9.1 and §9.7.4: **no forward secrecy with respect to recipient compromise.** "In the Base + and Auth modes, the secrecy properties are only expected to hold if the recipient private + key skR is not compromised at any point in time." + - §9.7.5: with bad encapsulation randomness, Base mode can lose confidentiality completely. + - §9.1.3: the analyses are classical; X25519 is not post-quantum. +- **Timing and processing (r2, F1).** Secrecy also needs bounded publication, finality, + retrieval and local processing of the round-0 and round-1 board posts before each participant + advances: the contract P1–P3 of D7, with the barrier of D6a. Closure evidence (ADR-0053 D4a) + proves which posts a window contains. It does not prove that a participant processed them before + it closed its round. +- **Exposure accounting (r2, F2).** Three kinds of compromise must be kept apart: + - **(a) a leaked HPKE private key `skR_j`.** It reveals what was sent to `j` in envelopes: the + pairs `(s_ij, s'_ij)` for dealers `i ≠ j`. A dealer keeps its own evaluation `f_j(j)` and + never sends itself an envelope (threshold spec §3; `DkgParticipant.start()`), so `skR_j` + alone does not reveal `j`'s final share `x_j`; + - **(b) a trustee's complete state:** its polynomials, received shares and `x_j`. That is a + corruption, counted in `t`; + - **(c) public disclosures:** complaint answers (round 3), and the pairs published to + reconstruct marked dealers (rounds 5–6). + + **Counting rule.** Dealer `i`'s contribution `z_i` is exposed when the distinct evaluation + indices known for `f_i` reach `t + 1`. The known indices are: + - the leaked recipient keys other than `i`; + - the corrupted trustees; + - the public answers for `i`; + - all of them, if `i` itself is corrupted. + + The joint key `x = Σ z_i` is exposed when every `z_i`, `i ∈ QUAL`, is exposed. For example + (`n = 3`, `t = 1`, no corruption), leaking `skR_1` and `skR_2` exposes `z_3` but not `z_1` or + `z_2`, since only `f_1(2)` and `f_2(1)` are in envelopes. + + An enumeration over `(n, t) ∈ {(3, 1), (5, 2), (7, 3)}` (2026-10-05) gives, **in this counting + model** (not a security proof): + - **Recipient keys alone:** `t + 1` leaked keys never expose `x`, because each leaked trustee's + own dealing has only `t` known points. `t + 2` always do. + - **With the static adversary's `t` corrupted trustees:** one leaked honest key does not expose + `x`; two always do. + - **Public answers add points and lower these numbers:** `t` corrupted trustees, one leaked key + and one answer at an honest index against that trustee's dealing exposed `x` at `n = 5`, + `t = 2`. Under the delivery contract, an honest qualified dealer never answers at an honest + index (D7, I15). + + This is **not** a stronger guarantee. Deployments must assume that a few leaked recipient keys, + together with corruptions and disclosures, can expose the key and every ballot encrypted to it. + D5 limits the window to one attempt. +- **Post-quantum.** A quantum adversary could decrypt the envelopes. It could equally compute + discrete logarithms on Jubjub and decrypt the `elgamal-jubjub-v1` ballots directly, so X25519 + adds no weaker link than the one the election already has. A post-quantum design is out of + scope (see Related findings). + +## Pinned normative references + +- **[RFC9180]** R. Barnes, K. Bhargavan, B. Lipp, C. Wood, *Hybrid Public Key Encryption*, + RFC 9180, February 2022. The text was fetched from rfc-editor.org on 2026-10-05. + - §4.1: DHKEM. + - §5.1.1: `SetupBaseS`/`SetupBaseR`. + - §5.2: encryption and decryption. + - §6.1: single-shot `SealBase`/`OpenBase`. + - §7.1: KEM `0x0020` DHKEM(X25519, HKDF-SHA256). §7.2: KDF `0x0001` HKDF-SHA256. + §7.3: AEAD `0x0003` ChaCha20Poly1305 (and `0x0001` AES-128-GCM, the Q3 alternative). + - §7.1.4: "recipients MUST check whether the Diffie-Hellman shared secret is the all-zero value + and abort if so." + - §8.1: applications that use only the single-shot APIs "should use the Setup info parameter". + - §9.1, §9.1.1, §9.1.2, §9.1.3, §9.2.3 (encapsulation randomness "MUST NOT be reused"), + §9.7.3 (no replay protection), §9.7.4, §9.7.5. + - Appendix A.2: test vectors for DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20Poly1305. + A.2.1 covers Base mode. +- **[RFC7748]** Langley, Hamburg, Turner, *Elliptic Curves for Security*, RFC 7748, January 2016. + Fetched 2026-10-05. + - §5: X25519 implementations "MUST mask the most significant bit in the final byte" and "MUST + accept non-canonical values and process them as if they had been reduced modulo the field + prime". + - §6.1: the optional all-zero check. +- **[RFC8439]** ChaCha20 and Poly1305 for IETF protocols, §2.8 (AEAD). Fetched 2026-10-05. +- **[RFC5869]** HKDF. Fetched 2026-10-05. +- **[GJKR07]** as pinned by ADR-0053: §2.1 (the channel and adversary model) and the Appendix + ("Committing Encryption on a Broadcast Channel", an attack on JF-DKG's bias). +- **[CS01], [HPKEAnalysis]**: cited through RFC 9180 §9.1.2; not fetched (**unverified** + directly). +- **ZeroJ:** + - ADR-0053 (D3, D4a, D6, D8; Q1, Q7); + - `docs/specs/elgamal-jubjub-threshold-v1.md` (§4 messages, §5 delivery windows, §5.2, §8); + - ADR-0039 (assurance classes). + +## Notation + +- `n`, `t`, trustee identifiers `1 … n`, `session`: as in `elgamal-jubjub-threshold-v1`. +- `SHARE_ij`: the canonical 100-byte `SHARE` message of spec §4 from dealer `i` to recipient `j` + (header and `I2OSP32(s_ij) ‖ I2OSP32(s'_ij)`). +- `(skR_j, pkR_j)`: trustee `j`'s X25519 key pair for one attempt. +- `SealBase`/`OpenBase`: RFC 9180 §6.1. + +## Decision + +### D1 — Ciphersuite and mode (R3) + +ZeroJ uses **HPKE Base mode, single-shot** (RFC 9180 §5.1.1, §6.1) with one fixed ciphersuite: +- KEM `0x0020`, DHKEM(X25519, HKDF-SHA256); +- KDF `0x0001`, HKDF-SHA256; +- AEAD `0x0003`, ChaCha20Poly1305 (lean; Q3). + +No other mode, suite or negotiation is accepted. A fixed suite leaves nothing to downgrade +(RFC 9180 §9.7.2). + +**Base, not Auth.** Sender authentication comes from the board: every post is authenticated under +the dealer's roster key (ADR-0053 D4a). HPKE's Auth mode would add a second sender key, and its +DHKEM variant is subject to key-compromise impersonation (§9.1.1). + +**The implementation is assembled from the RFC on JDK primitives.** Java 25 has no HPKE `Cipher`. +A probe on GraalVM JDK 25.0.2 (2026-10-05) found: +- `KeyAgreement` X25519 from SunEC; +- `javax.crypto.KDF` HKDF-SHA256 from SunJCE; +- `Cipher` ChaCha20-Poly1305 and AES/GCM from SunJCE. + +SunEC refuses small-order inputs with `InvalidKeyException: Point has small order`. That +includes `u = 0`, `u = 1` and their non-canonical forms `p` and `p + 1`, which covers §7.1.4's +all-zero check. The ZeroJ code also checks the shared secret explicitly, so the rule does not +depend on the provider. ZeroJ's main code uses no third-party cryptography library. + +### D2 — Replacing ideal channels by encryption (R3; security argument stated, not proven) + +The [GJKR07] proof assumes ideal private channels. Here, each private channel is replaced by HPKE +encryption of `SHARE_ij` to `pkR_j`, posted on the board. The assumption this rests on is stated +explicitly: + +> **Assumption A1 (to be reviewed externally).** Against a static adversary, New-DKG with ideal +> private channels can be replaced by New-DKG whose private messages are encrypted under an +> IND-CCA2-secure public-key encryption scheme to per-attempt honest recipient keys. Secrecy then +> holds computationally, under the security of that scheme plus [GJKR07]'s discrete-log +> assumption. + +The intuition, which is **not** a proof: +- A simulator for the ideal-channel proof knows every share between an honest and a corrupted + party, and can replace each honest-to-honest ciphertext by an encryption of a fixed dummy + plaintext. +- IND-CCA2 covers the adversary's ability to post envelopes to honest recipients and watch + whether they complain, which amounts to a one-bit decryption oracle (D6). +- Non-committing encryption would be needed only against adaptive corruption, which is out of + scope. + +ZeroJ does not supply a proof of A1. It is an explicit **external-review gate**, and the spec +must state it. + +Robustness and the complaint flow are unchanged. A dealer still answers a complaint by publishing +the pair in the clear ([GJKR07] Fig. 2, Step 1(c)), so no party ever needs to prove what a +ciphertext decrypts to (Q5). + +### D3 — The envelope and its binding (R2) + +Dealer `i` sends `SHARE_ij` by posting an **envelope** on the board in round 1: + +``` +envelope = header ‖ enc (32 bytes) ‖ ct (116 bytes) +header = PROFILE_TAG ‖ session (32 bytes) ‖ u8(sender i) ‖ u8(recipient j) +info = INFO_TAG ‖ session ‖ u8(i) ‖ u8(j) +(enc, ct) = SealBase(pkR_j, info, aad = empty, pt = SHARE_ij) +``` + +The illustration is not normative; the spec (M0) fixes the tags, lengths and order. Its +properties are fixed here: +- **Everything is bound in `info`**, as RFC 9180 §8.1 recommends for single-shot use: the + profile, the session, the sender and the recipient. HPKE also binds `enc` and `pkR_j` through + its key schedule. `aad` is empty. +- **The plaintext is the full canonical `SHARE_ij`**, header included. After decryption, + ADR-0053's existing `SHARE` checks apply unchanged: the session, round, sender, subject and + scalar ranges. +- **Fixed length.** 100-byte plaintext and 116-byte ciphertext, so length reveals nothing + (RFC 9180 §9.7.6). +- **Not a DKG message.** The header starts with a tag that is not a session prefix, so + `DkgMessage.decode` refuses envelopes and `DkgTranscript.deliveredRound` drops them as junk. + The DKG transcript, digest and admission (ADR-0053 D4a) are unchanged. +- **Replay** is refused by the binding: an envelope opens only for its own session, sender and + recipient. RFC 9180 provides no replay protection itself (§9.7.3). Byte-identical repeats count + once. Two different envelopes from one dealer to one recipient deliver two `SHARE`s, which + ADR-0053's conflict rules already handle. + +### D4 — Key announcement (R2) + +Before round 1, a transport round 0 publishes the attempt's encryption keys: +- Each trustee `j` posts `ANNOUNCE_j = header ‖ pkR_j`, authenticated under its roster key, like + every board post. +- Trustee `j`'s key is the **unique** well-formed, authenticated announcement from `j` delivered + in round 0, under the per-window delivery rule of spec §5. +- Two different announcements from `j` are a conflict, and `j` then has **no key**. So does a + trustee that posts no announcement. +- A dealer posts no envelope to a recipient without a key. +- **Transport abort T1 (r2).** A trustee whose own announcement is absent from the final round-0 + set, or conflicts there, aborts the attempt before round 1. It stays silent: it neither deals + nor complains. + + Without T1, an honest trustee whose announcement missed the cutoff would complain against + every dealer. The answers would then publish its shares, which is the §5.2 exposure in another + form. T1 mirrors A9, under which a participant's own broadcasts are delivered to itself. + + A recipient without a key that does complain is therefore faulty. The answers give it only the + shares a corrupted trustee holds in [GJKR07]'s model anyway. +- Round 1's window opens on schedule after round 0's. A dealer seals only after processing the + final round-0 set (D6a). The DKG's round numbering and rules (spec §5) are unchanged. + +No proof of possession is required for these keys. Copying another trustee's public key only +makes the copier's own shares unreadable to itself. HPKE binds `pkR` in its key schedule, so the +victim cannot be made to accept the copier's shares as its own. The copier's complaints then +publish only its own shares. Rogue-key attacks matter for key aggregation, which this +construction does not use. + +Alternative (Q2): put the encryption keys in the trusted configuration instead. + +### D5 — Recipient key lifecycle (R3) + +- **Per attempt.** Each trustee generates a fresh X25519 key pair for every `(session, j)`, from + a `SecureRandom`. The API binds a key pair to the session it was generated for, and refuses to + seal or open under another session. +- **Separation.** The encryption key is never the roster authentication key, nor derived from + it. +- **Deletion.** The private key is needed only until round 1 closes and the envelopes are opened. + The API provides a best-effort destroy, after which opening is refused. Java cannot guarantee + erasure of key material, so this is an offline-class property, not a guarantee. +- **Encapsulation randomness** is fresh per envelope from a `SecureRandom` and never reused + (RFC 9180 §9.2.3, §9.7.5). +- **Harvest now, decrypt later.** Per-attempt keys deleted after round 1 bound the exposure to + the DKG window. Long-lived encryption keys would expose every past attempt to one later + compromise. How many leaked keys suffice depends on corruptions and disclosures; the threat + model's exposure accounting gives the count. + +### D6 — Failure handling and the `DkgParticipant` interface (R2) + +Every failure to obtain a valid `SHARE_ij` is treated **as absence**, and leads to the same +public consequence as today: a Fig. 2 complaint in round 2. The failures are: +- no envelope; +- a malformed envelope or header; +- a non-canonical or invalid `enc`; +- an all-zero shared secret; +- AEAD failure; +- a plaintext that fails ADR-0053's `SHARE` checks. + +The recipient publishes no other signal, and the library exposes no error detail to other +parties. Locally, the reason may be logged for diagnosis. + +The interface is a thin layer over the existing participant: +- **Open:** the recipient decrypts and calls `DkgParticipant.receivePrivate(i, SHARE_ij)`. +- **Seal:** the dealer takes the `SHARE` messages from `DkgParticipant.start()` and seals each + one into an envelope. + +`DkgParticipant`, `DkgRules`, `DkgTranscript` and `ThresholdKeyContext.admit` are unchanged. + +### D6a — Processing barrier (R2; r2, responds to F1) + +A participant advances past round 0 or round 1 only when all three hold: +1. **The window is final.** Its cutoff has passed, and the set of posts up to the cutoff is final + and complete, on the same closure evidence admission uses (ADR-0053 D4a). +2. **Every post is retrieved.** It has every post in that window. +3. **Every post is processed.** + - Round 0: the announcements are applied to the key directory (D4, including T1). + - Round 1: every envelope is opened and validated, and each accepted plaintext is submitted + through `receivePrivate` (D6). + +Only then does it seal its envelopes (after round 0) or call `DkgParticipant.closeRound()` (for +round 1). + +- **The cutoff decides delivery, not processing time.** Slow processing delays the participant, + a liveness cost. It never turns a delivered share into an absent one. +- **Never close round 1 on a timer while envelopes in the final window are unprocessed.** That is + the failure the review demonstrated with the unchanged state machine (`n = 3`, `t = 1`). + Envelopes `1→2` and `2→1` were processed after round 1 closed. That drew two complaints and two + public answers, and corrupted participant 3 recovered `x` from its own shares plus the answers. +- **The API enforces the order.** The delivery layer takes a final window's posts and returns + only after every accepted plaintext has been submitted. It offers no close after partial + processing. + +### D7 — Relation to ADR-0053's delivery precondition (R2; Q6; rewritten in r2 for F1) + +With this transport, a `SHARE` is delivered when the final round-1 set contains its envelope and +the recipient has processed it. The §5.2 argument needs an explicit **delivery contract**: +- **(P1) Bounded publication.** An honest trustee's round-0 announcement and round-1 posts are + included on the board before their window's cutoff. This is [GJKR07] §2.1's "received by their + recipients within some specified time bound", applied to board inclusion. Its budget must + include processing the previous window, sealing and posting. +- **(P2) Agreement and finality.** Every honest participant obtains the same final set of posts + for each window (ADR-0053 D3, D4a). +- **(P3) The processing barrier** of D6a. + +Under P1–P3, an honest recipient holds its key, so T1 never fires for it. It receives every honest +dealer's envelope in the final round-1 set, and processes it before closing round 1. It never +complains about a dealer whose `COMMITMENTS` is absent: `closeDeal` skips such a dealer, which +R1 disqualifies regardless. So an honest active recipient never makes a false absence complaint +about an honest qualified dealer. + +**What answers can still reveal (r3, F3).** Fig. 2 is unchanged, so corrupted trustees may still +complain about any dealer. A dealer answers every delivered complaint in round 3 (`closeComplaints`) +before it checks its own qualification (`closeAnswers`). Such an answer publishes the pair at the +**complainer's** index. That is a corrupted index, already inside the corruption budget of the +threat model's counting rule, so it adds no new evaluation index. + +The guarantee is therefore scoped: +- for every honest dealer in `QUAL`, every answer it publishes is addressed to a corrupted + complainer (I15); +- so the known indices of its polynomial stay within the corrupted set. + +It is **not** that honest dealers publish no answers. The §5.2 precondition, in this scoped form, +then **reduces to P1–P3**. + +Closure evidence alone is not enough. It proves what a window contains (part of P2). It proves +neither that honest posts made the cutoff (P1) nor that they were processed in time (P3). + +#### D7a — A dealer's `COMMITMENTS` only after its envelopes (R2; r2; Q8) + +An honest dealer posts its round-1 `COMMITMENTS` **only after all its envelopes are final on the +board within the round-1 window**. Posting them all atomically in one post, for example one +transaction, satisfies the same rule. Recipients need no new check: this constrains honest +dealers only. A dealer whose `COMMITMENTS` arrives without a recipient's envelope is faulty, and +the recipient's complaint makes it publish a point on its own polynomial. + +With T1 and D7a, **secrecy no longer depends on P1**: +- An honest dealer whose envelopes miss the cutoff never posts `COMMITMENTS`. R1 disqualifies it, + so its contribution is not part of the joint key. Honest participants do not complain about it, + because `closeDeal` skips a dealer without `COMMITMENTS`. Corrupted trustees still may: under the + unchanged Fig. 2 rule it answers them in round 3, and only then aborts with A2 (`closeAnswers`). + Those answers concern a polynomial excluded from `QUAL`, at corrupted indices. +- An honest trustee whose announcement misses round 0 aborts (T1) and never complains. + +P1 then matters only for liveness, through ADR-0053's A1 bound on `|QUAL|`. Without D7a, an +envelope that misses the cutoff while its `COMMITMENTS` makes it reproduces the §5.2 exposure for +that dealer. Hence Q8. + +This is an argument, not a theorem, and it is flagged for review. It does not cover an honest +recipient that loses its key during the run, which is a local fault like losing its share. +ADR-0053's Q7 note stays in force for application-provided channels, and for deployments that do +not meet P2, P3, T1 and D7a. + +### D8 — Encodings and canonicality (R2; Q4) + +- Announcements and envelopes have exact lengths. +- Every X25519 public value on the board (`pkR_j`, `enc`) must be the **canonical** 32-byte + little-endian encoding: bit 255 clear and `u < 2^255 − 19`. A non-canonical value makes the + announcement or envelope malformed, so the key or share is absent. +- The X25519 function itself stays RFC 7748 conformant. This is a message-format rule, applied + before any X25519 call. It keeps one accepted encoding per message, as AGENTS.md requires. + Because RFC 7748 §5 says implementations "MUST accept non-canonical values", Q4 asks the + maintainer to confirm that a protocol message format may refuse them. +- **Explicit decoding (r2, from the review).** The adapter from 32 bytes to a provider key + implements RFC 7748 §5's decoding itself: little-endian, then the Q4 policy (refuse, under the + lean) for bit 255 and for `u ≥ 2^255 − 19`. It does not rely on a provider API to decide. The + review observed that SunEC's encoded-key import masks bit 255, while building an + `XECPublicKeySpec` from the unmasked integer did not give the same result. + +### D9 — Out of scope + +- Post-quantum or hybrid KEMs. +- Adaptive security and non-committing encryption. +- Publicly verifiable secret sharing, which proves share validity in zero knowledge and would + remove the complaint round. +- HPKE PSK, Auth and AuthPSK modes; the export interface. +- Key storage between attempts. +- Delivery for anything other than DKG `SHARE`s. + +### Alternatives considered + +| Alternative | Why not chosen | +|---|---| +| Application-provided channels only (ADR-0053 status quo) | Kept as an option, but every application must build and review its own. Point-to-point channels give no evidence of delivery, and they leave the §5.2 precondition on the application. | +| TLS or Noise between trustees | Needs simultaneous online presence and reachability. Delivery is not provable on the board, and it is application infrastructure rather than a library primitive. | +| ECIES or ElGamal-based encryption on Jubjub | No standardized ciphersuite exists; ZeroJ would be defining new cryptography. | +| HPKE Auth mode | Redundant with board authentication, and DHKEM Auth is subject to key-compromise impersonation (RFC 9180 §9.1.1). | +| Committing encryption with recipient proofs of decryption | Not needed: Fig. 2's public answers resolve disputes. The [GJKR07] Appendix shows it does not help JF-DKG, and proofs about decryption would be new constructions. | +| PVSS with zero-knowledge share proofs | Would remove complaints and answers, but is a research-level protocol change with new proofs and circuits. Possible future work. | +| Amending `elgamal-jubjub-threshold-v1` to carry envelopes as DKG messages | Changes a format under review in PR #76 and puts transport into the DKG transcript. Kept as Q1's alternative. | + +## Security invariants + +- **I1 (D1, D2, D5) Confidentiality.** `SHARE_ij` is recoverable only with `skR_j` of that + attempt, under HPKE Base IND-CCA2 and Assumption A1. Tested only for functional behaviour + (wrong-key failure); the security claim is an assumption. +- **I2 (D3) Binding.** An envelope opens only under the profile, session, sender `i` and recipient + `j` it was sealed for. Changing any of them, `enc`, `ct` or the recipient key makes it fail. +- **I3 (D3, D6) DKG unchanged.** A decrypted plaintext enters only through + `receivePrivate(i, ·)` and must pass every ADR-0053 `SHARE` check. No transport message is ever + accepted by `DkgMessage.decode`. The transcript digest and admission are identical to an + application-channel run with the same shares. +- **I4 (D6) Uniform failure.** Every envelope failure is equivalent to absence: no exception, + return value or public message distinguishes the failure kinds. +- **I5 (D4) Announcement rule.** A trustee's key is its unique authenticated round-0 + announcement. A conflict or absence gives no key, and dealers send no envelope to it. +- **I6 (D8) Canonical encodings.** Exact lengths, and canonical X25519 values, are enforced + before cryptographic use. All-zero shared secrets are refused independently of the provider. +- **I7 (D5) Key lifecycle.** Keys are fresh per session, refused for any other session, never the + roster key, and destroyable. Opening after destroy is refused. +- **I8 (D5) Randomness.** Encapsulation uses fresh `SecureRandom` output per envelope. Determinism + exists only in a test seam for RFC known-answer tests. +- **I9 (D1) Single suite.** Only `(0x0020, 0x0001, 0x0003)` in Base mode is produced or accepted. +- **I10 (D1, D8) Provider.** Main code uses JDK primitives only, with identical results on the JVM + and in a GraalVM native image. The byte-to-key adapter decodes explicitly (D8). *(Refined + during implementation, note 10: lookups name the algorithm only, so the JDK providers compute + under the default provider order. Under a preferred third-party provider, that provider + computes; absence is still decided by ZeroJ.)* +- **I11 (D6a) Processing barrier.** A participant seals only after the final round-0 window is + processed, and closes round 1 only after every envelope in the final round-1 window is processed + and submitted. An envelope inside the cutoff but opened late draws no complaint. +- **I12 (D4) Abort T1.** A trustee whose own announcement is absent or conflicting in the final + round-0 set aborts before round 1 and never deals or complains. +- **I13 (D7a) Commitments last.** An honest dealer's `COMMITMENTS` is released for posting only + after all its envelopes are final in the round-1 window, or together with them atomically. + Envelopes excluded by the cutoff therefore leave the dealer disqualified, with its contribution + outside the joint key and no complaint from any honest participant. It may still answer + complaints from corrupted trustees before its A2 abort (r3, F3). +- **I14 (threat model, F2) No self-envelope.** A dealer never seals an envelope to itself, so a + leaked recipient key reveals only the pairs `(s_ij, s'_ij)`, `i ≠ j`. Exposure follows the + counting rule of the threat model. +- **I15 (D7; r3, F3) Answer scope.** Under P1–P3, T1 and D7a, every answer that an honest dealer + in `QUAL` publishes is addressed to a corrupted complainer. Answers therefore add no evaluation + index beyond the corruption budget. Honest active recipients make no false absence complaint + about an honest qualified dealer. Fig. 2's complaint and answer rules are unchanged. + +## Consequences + +- Applications get confidential share delivery without building channels, and delivery becomes + evidence on the board. +- The DKG gains a transport round 0 and per-attempt key generation; round 1 waits for round 0 to + close. +- Each trustee posts one announcement and `n − 1` envelopes of about 182 bytes plus the profile + tag each (34-byte header, 32-byte `enc`, 116-byte `ct` in D3's illustrative layout; the spec + fixes the length). That is `n(n − 1)` envelopes per attempt, + 4,032 at `n = 64`. Board cost scales quadratically, as the `SHARE` count already does. +- Round 1 includes one finality wait: envelopes first, then `COMMITMENTS` (D7a), unless both are + posted atomically. +- Secrecy now rests computationally on HPKE and Assumption A1, not on ideal channels, and + operationally on the contract of D7. +- Recipient key compromise during the window exposes that recipient's shares (no forward secrecy, + RFC 9180 §9.7.4). + +## Compatibility + +- **No change** to `elgamal-jubjub-v1`, `elgamal-jubjub-threshold-v1`, their encodings, + transcripts or admission, under the Q1 lean. Under that lean, PR #76's release gate ("don't + ship the threshold profile until ADR-0054 settles its wire format") can be lifted; Q7 asks the + maintainer to confirm. +- A new profile, `dkg-share-delivery-hpke-v1`, and a new public API in + `org.zeroj.circuit.lib.jubjub`. +- Application-provided channels remain valid. + +## Implementation milestones + +| ID | Scope | Entry gate | Exit criteria | +|---|---|---|---| +| M0 | Normative spec `docs/specs/dkg-share-delivery-hpke-v1.md`: tags, announcement and envelope formats, `info`, the suite, canonicality and explicit decoding, absence rules, abort T1, the processing barrier, the delivery contract P1–P3 and the posting order of D7a, key lifecycle, exposure accounting, Assumption A1, test vectors. An independent Python reference written from the spec and RFC 9180 on pyca `cryptography` primitives (X25519, HKDF, ChaCha20Poly1305) with no Java read. It reproduces RFC 9180 A.2.1, models the barrier and the exposure counting rule, and emits replayable vectors | ADR accepted | Spec reviewed. The reference passes A.2.1 and its own vectors. | +| M1 | Package-private HPKE (Base, single-shot, the D1 suite) on JDK primitives, with a deterministic-ephemeral test seam and the explicit byte-to-key adapter (D8) | M0 | Every RFC 9180 A.2.1 Base encryption matches. Differential against BouncyCastle 1.83's HPKE on random inputs. Negatives: small-order and all-zero inputs; non-canonical `enc`, both bit 255 set and `u ≥ p`; tampered `enc`/`ct`; wrong `info`/key. A GraalVM native-image probe produces identical results (I10). | +| M2 | Delivery layer: key generation per session, round-0 announcement and T1, the processing barrier, seal/open with the D7a posting order, wiring to `DkgParticipant` | M1, and ADR-0053 M2 (merged with PR #76) | ADR-0053's honest and adversarial DKG suites rerun with encrypted delivery and identical transcripts (I3). Negatives for I2, I4–I7: wrong session, sender or recipient; cross-attempt replay; conflicting or missing announcements; copied keys; opening after destroy. **Timing (I11–I13):** envelopes posted before the cutoff but opened later draw no complaint; delayed announcements are processed before sealing; an own announcement missing triggers T1 with no complaint; envelopes excluded by the cutoff leave the dealer's `COMMITMENTS` unposted and the dealer disqualified, with no complaint from any honest participant. The review's late-processing scenario (`n = 3`, `t = 1`) is reproduced as a negative control without the barrier and refused with it. **Adversarial complaints (I15):** (i) with timely delivery, a corrupted trustee's complaint against an honest dealer draws one answer at the corrupted index, `QUAL` is unchanged, and the exposure count is unchanged; (ii) under D7a, a corrupted trustee's complaint against an honest dealer whose `COMMITMENTS` was withheld draws an answer at the corrupted index, after which the dealer aborts with A2 and is excluded from `QUAL`. **Exposure (I14):** no envelope is addressed to its sender; leaked-key exposure matches the counting rule. The Python reference replays. | +| M3 | Docs: support matrix and guide; ADR-0053 Q1/Q7 notes pointing here | M2 | Docs reviewed. | + +## Verification and test-vector strategy + +- **Published vectors:** RFC 9180 Appendix A.2.1 (Base mode), all encryptions. +- **Independent implementations:** + - BouncyCastle 1.83's `org.bouncycastle.crypto.hpke.HPKE`, already a test dependency; + - a Python reference from the RFC text on pyca `cryptography` 46, which has X25519, HKDF and + ChaCha20Poly1305 but no HPKE, so it is written independently. Its reproduction of A.2.1 is + checked before Java exists. +- **Adversarial and negative cases:** every invariant's failure mode, run through the real + `DkgParticipant` state machine. +- **Timing harness:** a board model with window cutoffs, finality and delayed processing. It + drives the barrier (I11), T1 (I12), the posting order (I13) and the answer scope (I15). It + includes: + - the review's late-processing counterexample, as a negative control; + - both adversarial-complaint traces of review round 2. Every answer by an honest qualified + dealer must be at a corrupted index. +- **Exposure accounting:** vectors that leak chosen recipient keys, with and without corruptions + and public answers. Reconstruction must succeed exactly when the counting rule says it does. +- **Expected values never come from the code under test.** + +## Production / audit gates + +- External review of Assumption A1, D7 and D7a (the contract P1–P3, T1 and the posting order), + together with ADR-0053's DKG review. +- External review of key storage, deletion and `SecureRandom` use on the deployment platform. +- Native-image verification on each released platform. +- Not production-ready until those gates pass; experimental, like ADR-0053. + +## Risks + +- **The composition argument is wrong or incomplete.** Mitigation: it is stated as an + assumption, with an external-review gate. +- **Recipient key compromise** while a key exists exposes that trustee's received shares; with + corruptions and public answers, a few leaked keys can expose the joint key (threat model). + Mitigation: per-attempt keys and deletion (D5). +- **An application closes rounds on a timer**, before processing finishes. Mitigation: the API's + order (D6a), documentation, and the negative control in M2. +- **Board finality is slow** relative to the window, so honest dealers miss the cutoff under D7a. + This costs liveness (A1 aborts), not secrecy. Mitigation: size the windows for finality. +- **Assembly errors in HPKE.** Mitigation: RFC known-answer tests, a BouncyCastle differential + and an independent Python reference. +- **Provider differences** between the JVM and native image. Mitigation: I10, tested in M1. +- **Metadata:** the board reveals who sent envelopes to whom and when (RFC 9180 §9.9). This + matches the public DKG structure and reveals no share. + +## Open questions (points needing a maintainer decision) + +**Decided 2026-10-09 (maintainer): the lean of every question below is adopted.** The +questions stay as written for the record. + +1. **Q1 (D3, Compatibility): layering.** + - Options: + - (a) a separate transport profile; envelopes and announcements are board posts outside the + DKG transcript, and `elgamal-jubjub-threshold-v1` is unchanged; + - (b) amend the threshold profile with envelope and announcement message kinds in its + transcript. + - Lean: (a). The DKG stays untouched and #76's release gate can lift. Admission does not need + envelopes, because outputs do not depend on them. +2. **Q2 (D4): where encryption keys come from.** + - Options: + - (a) per-attempt keys announced in a round 0 under the roster keys; + - (b) keys in the trusted configuration, such as an election manifest. + - Lean: (a). Fresh keys per attempt bound harvest-now-decrypt-later exposure. (b) saves a + round, but tends toward long-lived keys. +3. **Q3 (D1): the AEAD.** + - Options: (a) ChaCha20Poly1305 (`0x0003`); (b) AES-128-GCM (`0x0001`). + - Lean: (a). Its software implementation uses no table-based S-box, so it does not depend on + AES hardware support for timing behaviour. Both have RFC 9180 test vectors (A.2 and A.1). + This is not a constant-time claim. +4. **Q4 (D8): canonical X25519 encodings versus RFC 7748 §5.** + - Options: + - (a) refuse non-canonical values at the message layer, before X25519; + - (b) accept them, as the X25519 function must, and canonicalize. + - Lean: (a). The RFC's MUST governs the X25519 function, and ZeroJ's message formats require + one accepted encoding. Escalated because it narrows inputs that RFC 7748 says + implementations accept. +5. **Q5 (D2): complaint evidence.** + - Options: + - (a) keep [GJKR07] Fig. 2's public answers only; + - (b) add recipient proofs of what an envelope decrypts to. + - Lean: (a). It is sufficient for disputes, and (b) would be new cryptography. +6. **Q6 (D7): ADR-0053's Q7.** Should ADR-0053 record Q7 as resolved once ADR-0054 is accepted? + Lean: yes, but **only for deployments that use this transport and meet P2, P3, T1 and D7a**. + ADR-0053 keeps the precondition, and the documented limitation, for application-provided + channels and for deployments without that contract. +7. **Q7 (Compatibility): PR #76's release gate.** If Q1's lean is adopted, lift it. Lean: yes. +8. **Q8 (D7a): must a dealer's `COMMITMENTS` follow its final envelopes?** + - Options: + - (a) a MUST of the profile, either commitments after the envelopes are final, or one atomic + post; + - (b) optional, with the §5.2 exposure documented for dealers whose envelopes miss the + cutoff. + - Lean: (a). It removes secrecy's dependence on publication timing, at the cost of one + finality wait in round 1. Recipients need no new check. + +## Related findings (out of scope) + +- A post-quantum or hybrid KEM (outside RFC 9180's registry) would matter only alongside a + post-quantum replacement for Jubjub ElGamal itself. +- PVSS-style DKGs with zero-knowledge share proofs could remove complaint rounds. That would be a + separate ADR. + +## Implementation notes (refinements recorded during implementation) + +These refine the accepted design and are recorded for maintainer acknowledgement, as AGENTS.md +requires. Each is stated normatively in `docs/specs/dkg-share-delivery-hpke-v1.md`. They came +from the independent reference (findings S1–S7) and the M1/M2 reviews. + +1. **De-duplicate only after authentication** (spec §4.2; reviews M-1 and S-1, P0). The first + implementation dropped byte-identical posts before authenticating them. A corrupted + participant could then front-run unauthentic copies of honest envelopes, or of a + `COMMITMENTS`. The genuine posts were skipped, honest participants complained about each + other, and the answers exposed the joint key; both reviewers demonstrated this end to end. + Fixed: every post is authenticated first, and the participant counts identical copies once. + Front-running vectors and a mutant-killing regression test are included. +2. **"Process before closing" is enforced by binding the participant** (D6a; review S-2). + `DkgShareDelivery.start` replaces `DkgParticipant.start()` for this transport. It applies T1 + and binds the participant, whose public `closeRound()` then refuses round 1, so round 1 + closes only through `closeRound1`. `DkgParticipant` gains package-private hooks for this; its + protocol is unchanged. + - **What binding does not enforce** (final review X-4): that the window passed to + `closeRound1` is complete, that is, taken after the cutoff and finality. + - A snapshot taken before finality reproduces the late-processing failure, so this part of + the barrier stays the application's, like D7a's posting order. + - Closure evidence checked through the verifier could enforce it. That needs a spec + addition for rounds 0 and 1, and is a possible follow-up. +3. **Fail closed on verifier exceptions** (review M-4). An exception from the application's + authenticator leaves the participant at round 1 with its keys, so `closeRound1` can be + retried. It is not treated as "unauthentic", which would turn a transient failure into + false complaints. +4. **T1 also on a key other than one's own** (spec §3.3). If the directory holds a key for `j` + other than the public key of the private key `j` holds, someone authenticated as `j` + announced it, so `j` is faulty; it aborts. +5. **Spec clarifications from the reference** (S1–S7): + - round 1's window opens when round 0's closes; + - the counting rule counts only envelopes actually sent, plus the round 5–6 disclosures; + - the `GenerateKeyPair` citation is fixed; + - atomic posting is a board property; + - the test-key tag scheme is pinned; + - byte-identical plaintexts count once; + - a T1 participant answers nothing. +6. **The all-zero DH check is unreachable on SunEC** (review M-6). SunEC refuses small-order + inputs before returning a shared secret, so the explicit check is defence in depth. Its + mutant cannot be killed without a stub provider. It is kept for providers that return + `0^32`. +7. **A platform fault is never absence** (spec §4.2; final security review Z-1, P1). Before the + fix, any exception from the JDK primitives counted as a failed open. A missing or failing + HKDF/AEAD provider at an honest recipient made it complain about every honest dealer, and + the answers then exposed their contributions. Now only input-caused failures are absence: + - small order (decided as note 10 says); + - AEAD tag failure; + - wrong length. + + Everything else is an `IllegalStateException` that fails closed, like verifier exceptions + (note 3). Note 10 refines how small order is decided. `start` and `closeRound1` also run a seal-and-open self-test with the participant's + own keys before judging any input. The small-order probe no longer reports a fault as small + order. Tests remove the SunJCE or SunEC provider at each entry point. +8. **The keys and directory are bound by instance** (final Codex review C-1). `closeRound1` + refuses any keys or directory other than the instances given to `start`, so substituting + either cannot turn genuine shares into absences. +9. **Key lifecycle on failure paths** (Z-4). Keys are destroyed when round 1 closes or the + participant aborts. Any other failure keeps them, for the documented retry. An application + that abandons the attempt calls `destroy()`. HPKE wipes its intermediate secrets in `finally`. + - **Also on failure (external Codex review, F4):** the key schedule wipes `eae_prk` and + `secret` on every path. It also wipes `key` and `base_nonce` unless they passed to the + returned context. + - **Tests:** `HpkeFailureWipeTest` injects HKDF failures through a package-private + `Hpke.Hkdf` seam, which runs on any JDK. It also injects them through a delegating JCA + provider; that variant runs on OpenJDK builds, while Oracle JDK and GraalVM accept only + signed JCE providers and skip it. +10. **Small order is decided without the provider** (security round 2, R2-1, and spec↔code + round 2, X-9; P2). + - **The bug:** after note 7, small order was recognised by SunEC's `InvalidKeyException`. + With BouncyCastle preferred, which is common in Java stacks, a small-order `enc` or + announced key raised a different exception. It was classified as a platform fault, so one + corrupted trustee could stall every honest participant. + - **The fix:** small order is now decided before the provider is called, by membership in + the five canonical small-order u-coordinates (spec §2.2, informative note). The set is + checked against Wycheproof, and the all-zero check is kept. + - A test runs a whole DKG with BouncyCastle as the preferred provider. + - **Provider selection stays algorithm-only.** Pinning `SunEC`/`SunJCE` by name was tried + and broke the GraalVM native image, which registers a provider only when an + algorithm-only lookup reaches it. With BouncyCastle preferred, BouncyCastle computes + X25519 and the AEAD. The outcome does not change: small order is decided by ZeroJ, and BC + reports tag failures as `AEADBadTagException`. I10's "JDK primitives" therefore holds for + the default provider order. Provider policy is listed as a review gate. + - The self-test in `start` and `closeRound1` also opens the RFC 9180 A.2.1 sequence-0 + ciphertext (security round 3, R3-1). A provider that is consistent with itself but does not + conform to the RFC is therefore refused, rather than turning every honest envelope into a + complaint. + +11. **Lifecycle checks before anything changes** (external review of `914b68c`, two P3s). + - **`start` on an ineligible participant.** T1 used to run before the lifecycle check. So a + second `start` on a running participant, with a missing or conflicting own-key + announcement, aborted it and destroyed its keys. `start` now refuses an ineligible + participant first, changing nothing: + - one already started gets an `IllegalStateException`; + - an aborted one throws its own abort again. + + A legitimate first `start` still applies T1. + - **The identical-window retry is enforced** (spec §4.2, "A local fault is not a failed + step"). The first `closeRound1` that reaches delivery binds the participant to the + window's SHA-256 digest. The digest covers every post's message and authenticator, each + length-prefixed, in the given order, with repeats counted. A retry with any other window + is refused with `IllegalArgumentException`, before T1 or any delivery. + - **What this does not establish:** binding checks only that a retry repeats the first + window. It is no evidence that the window is final or complete, or that participants + agree on it. Those stay the application's (P1, P2; note 2). + - **Tests:** + - `startAgainRefusedBeforeT1` covers a missing and a conflicting own key. + - `retryNeedsIdenticalWindow` refuses, after a partial delivery: changed message bytes, + changed authenticator bytes, an added post, a removed post and a reordered window. Each + refusal leaves the participant's shares, round and keys as they were. An identical + retry then succeeds. + - `windowDigestFraming` checks the framing. + + Each fix's mutant is killed. No design decision changes. + +### Proposed amendment awaiting a maintainer decision (not implemented) + +- **T2: a dealer's own D7a self-check** (final security review Z-2, P2). Suppose `closeRound1` + finds the dealer's own authenticated `COMMITMENTS` in the final window, but an envelope from it + to some keyed recipient missing; the application broke D7a. Honest recipients will then + complain, and the dealer's answers make those shares public. + - **Proposal:** the dealer aborts with a new reason before closing round 1. An aborted dealer + answers nothing and is disqualified, so nothing is exposed. + - **Why it is not implemented:** it is a new normative abort. It changes the expected outcome + of the reference's D7a negative control and contradicts spec §5.2's "Recipients perform no + check of this rule" only in spirit, since it is the dealer's own check. It therefore needs a + spec amendment and an update to the independent reference, which is ADR scope, not + implementation scope. + - **Lean:** adopt it in a follow-up. + +## Implementation status + +| Milestone | State | Notes | +|---|---|---| +| M0 | Done, reviewed | Spec `docs/specs/dkg-share-delivery-hpke-v1.md`. An independent Python reference (`zeroj-circuit-lib/src/test/resources/dkg-share-delivery-reference/`, 294 checks, 110 replayable vectors), written from the spec and RFC 9180 with no Java read. It reproduces RFC 9180 A.2.1 (all 257 encryptions), Wycheproof X25519, ChaCha20-Poly1305 and HKDF-SHA256, and RFC 7748, RFC 8439 and RFC 5869. Its two revisions raised S1–S7 and R2-1/R2-2, all resolved in the spec. Standard vectors are vendored, pinned by commit and SHA-256, in `src/test/resources/standard-vectors/`. | +| M1 | Done, reviewed (adversarial and security, 2 rounds) | `Hpke` (Base, single-shot, the D1 suite) and `X25519Bytes` (explicit RFC 7748 decoding, canonicality, small-order probe, all-zero check) on JDK primitives. Tests: `HpkeKnownAnswerTest` (A.2.1, Wycheproof, RFC 7748/8439/5869) and `HpkeDifferentialTest` (BouncyCastle 1.83 both ways, byte-identical with the same ephemeral). The GraalVM native-image probe (`HpkeNativeProbe`) gives output identical to the JVM. Seal 114 µs, open 59 µs. | +| M2 | Done, reviewed (adversarial and security, 2 rounds; one P0 found and fixed, implementation note 1) | `DkgShareDeliveryKeys`, `DkgKeyDirectory` (T1), `DkgShareDelivery` (`start` binds the participant; `closeRound1` is the barrier, authenticates before anything else, and fails closed). Tests: `DkgShareDeliveryTest` (I2–I15, front-running, binding, fail-closed retry, copied key, cross-session, platform faults). It reruns several of ADR-0053's adversarial suites over encrypted delivery and compares each with private channels, asserting that each attack took effect: more than `t` complaints; a bad answer; the Feldman cheat; conflicting `COMMITMENTS` or `EXTRACTION`; withheld `EXTRACTION`; and A5. Other board-expressible suites are not rerun: a single unanswered complaint, A3, the rushing order and A7's lying confirmations. They act only on broadcasts, which the transport does not touch. Suites that need per-recipient views (A6, A9) cannot be posted on an agreed board. `DkgShareDeliveryReferenceVectorsTest` replays every reference vector. Honest participants and HPKE run through production code. The reference's negative controls (no barrier, D7a ignored) and corrupted participants run through test code, and the §6 counting rule is re-implemented in the test from the spec. Integration test `AnnotatedElGamalTest.thresholdEndToEndOverEncryptedBoard`: encrypted DKG, admission from the board, Groth16-proved tally. | +| M3 | Done, reviewed in the final pass | Support matrix and `zeroj-circuit-lib` README rows, a gadget-guide section with the MUST rules, the annotation guide, ADR-0053's Q1/Q7 notes, a threshold spec §5.2 pointer, and `docs/benchmarks/dkg-share-delivery-hpke-2026-10-09.md`. | + +**Final whole-PR review (2026-10-09).** Three independent reviews ran: spec↔code (Claude), +security (Claude) and Codex. +- **Codex:** approved, with C-1 to C-4. +- **The two Claude reviews:** requested changes. + +All findings are addressed except Z-2: +- **C-1:** instance binding (note 8). +- **C-2:** a retry after partial progress. +- **C-3:** HPKE sequence tests. +- **C-4, Z-5, X-7:** documentation precision. +- **Z-1 (P1):** a platform fault is never absence (note 7). +- **Z-3:** the encapsulation-randomness exposure source (spec §6). +- **Z-4, X-8:** the key lifecycle on failure paths (note 9). +- **X-1:** the exposure replay now reaches its HPKE reconstruction, guarded by a coverage check. +- **X-2:** the shape of `broadcasts()`. +- **X-3:** `generate` uses its generator. +- **X-4, X-6:** what binding does not enforce, and the round-1 window rule. +- **X-5:** authenticated junk in the round-1 window. +- **Z-2** (a dealer's own D7a self-check) awaits a maintainer decision; see "Proposed amendment" + above. +- **External Codex review of `a3b67a1`:** F4 (P2), wiping intermediate HPKE secrets when HKDF + fails part-way (note 9), is fixed. +- **Round 2:** both reviews found the same regression from the Z-1 fix (R2-1/X-9, note 10). It + is fixed. Also in round 2: + - X-10: the T1 re-check in `closeRound1` is documented as defence in depth; + - X-11: each adversarial rerun asserts that its attack took effect; + - spec §3.2: a fault while building the directory is not a missing key. diff --git a/docs/adr/circuit-annotation/cardano-gadget-support-matrix.md b/docs/adr/circuit-annotation/cardano-gadget-support-matrix.md index c990fdb0..27cbe907 100644 --- a/docs/adr/circuit-annotation/cardano-gadget-support-matrix.md +++ b/docs/adr/circuit-annotation/cardano-gadget-support-matrix.md @@ -125,7 +125,8 @@ Relevant source: | `ZkPedersenCommitment`, `ZkPedersen.assertBalanced` | Typed in-circuit commitments with origin tracking; no-wraparound balance helper (ADR-0051 D3/D3a) | Requires BLS12-381 scalar field | Direct | Experimental, pending review and external review | Unopened external commitments enter only through `witnessInSubgroup` (in-circuit subgroup proof, 5,547 rows) or `fromVerifierCheckedPublic` (public coordinates; the verifier runs `PedersenCommitment.decode`). `assertBalanced` refuses, at definition time, any side whose maximum `Σ coefficient·(2^width − 1)` reaches `l`, then asserts the integer relation on committed values. | | `ZkPedersenVector`, `InCircuitPedersenVector`, `PedersenVectorCommitment` | `pedersen-jubjub-vector-v1`: commitment to up to 16 values (ADR-0051 D5) | Requires BLS12-381 scalar field | Direct | Experimental, pending spec review and external review | Bases from Zcash `FindGroupHash` (`ZeroJ_PV`), pinned and checked against Zcash known answers. The point binds neither length nor schema: every proof binds a public schema digest (`bindSchema`) checked against `PedersenSchemaRegistry`, and received commitments need an authenticated issuance record. 2,411 / 3,581 / 8,261 rows at n = 1 / 4 / 16 (64-bit values). | | `InCircuitElGamal`, `ZkElGamal` | `elgamal-jubjub-v1` encryption relation and DLEQ trustee relation (ADR-0052 D3) | Requires BLS12-381 scalar field | Direct | Experimental, pending review and external review | Message width 1–64; 252-bit private randomness consumed by one decomposition; keys via `fromVerifierFixedPublic` (verifier checks subgroup) or `witnessInSubgroup`, identity refused; DLEQ needs all six coordinates public and `X ∈ 𝔾` as a verifier precondition. 6,558 / 6,938 rows (width 1 / 64); DLEQ 6,546. Spec: `docs/specs/elgamal-jubjub-v1.md`. | -| `ElGamal` host API; `DkgParticipant`, `ThresholdKeyContext` | Admission, bounds, verified shares; t-of-n key generation and decryption (ADR-0052, ADR-0053) | Jubjub over BLS12-381 scalar field | Not a circuit gadget | Experimental; **offline/isolated secret operations only** | Secret multiplications use the blinded best-effort schedule (no constant-time claim). The DKG's transport (broadcast with agreement, private channels, deadlines) and the admission verifier's authenticity/closure checks are the application's. Spec: `docs/specs/elgamal-jubjub-threshold-v1.md`. | +| `ElGamal` host API; `DkgParticipant`, `ThresholdKeyContext` | Admission, bounds, verified shares; t-of-n key generation and decryption (ADR-0052, ADR-0053) | Jubjub over BLS12-381 scalar field | Not a circuit gadget | Experimental; **offline/isolated secret operations only** | Secret multiplications use the blinded best-effort schedule (no constant-time claim). The DKG's transport (broadcast with agreement, private channels, deadlines) and the admission verifier's authenticity/closure checks are the application's; the private channels can instead be the encrypted board delivery of ADR-0054 (next row). Spec: `docs/specs/elgamal-jubjub-threshold-v1.md`. | +| `DkgShareDelivery`, `DkgShareDeliveryKeys`, `DkgKeyDirectory` | Encrypted delivery of DKG `SHARE`s over the public board: HPKE (RFC 9180 Base; X25519, HKDF-SHA256, ChaCha20Poly1305) to per-attempt keys announced in round 0 (ADR-0054) | X25519, JDK providers | Not a circuit gadget | Experimental; **Assumption A1 and the delivery contract (P1–P3) await external review** | The key generation, transcript and admission are unchanged. `closeRound1` is the processing barrier: binding the participant enforces processing before closing, and the application must pass the window after its cutoff and finality. A dealer posts `COMMITMENTS` only after its envelopes are final. A participant whose directory holds no key, or not its own key, for it aborts (T1). Checked against RFC 9180 A.2.1 (all 257 encryptions), Wycheproof X25519, ChaCha20-Poly1305 and HKDF, and BouncyCastle 1.83's HPKE; identical results in a GraalVM native image. Spec: `docs/specs/dkg-share-delivery-hpke-v1.md`. | | `PedersenCommitment.commit` (off-circuit) | Host-side commitment generation | Jubjub over BLS12-381 scalar field | Not a circuit gadget | **Offline/isolated generation only (ADR-0038)** | Both secret scalars use a fresh multiple-of-`l` blinding and fixed 316-add/316-double schedule. The former loop-bound/operation-count channel is removed and the raw trailing-zero signal is blinded, but Java branches and `BigInteger` remain variable-time. The commitment's hiding and binding are unaffected; the restriction is on secret-bearing execution. | | `InCircuitEdDSAJubjub` / `ZkEdDSAJubjub` | EdDSA-Jubjub verification | Requires BLS12-381 scalar field | Direct | Yes for verification, pending external review; signing is not constant-time | Use `verifyStrict` when `pk` is prover-supplied, `verifyWithRegisteredKey` when it is a public input or constant. No unqualified `verify`. Spec: `docs/specs/jubjub-eddsa-v1.md`. | | `zeroj-bls12381` | BLS12-381 field, G1/G2, pairing, hash-to-curve | BLS12-381 | Not a circuit gadget | Supports off-chain proof verification and conversion paths; Cardano has BLS builtins | Use for proof systems and BBS, not directly inside symbolic circuits unless a circuit gadget is built. | diff --git a/docs/benchmarks/dkg-share-delivery-hpke-2026-10-09.md b/docs/benchmarks/dkg-share-delivery-hpke-2026-10-09.md new file mode 100644 index 00000000..055163e7 --- /dev/null +++ b/docs/benchmarks/dkg-share-delivery-hpke-2026-10-09.md @@ -0,0 +1,70 @@ +# Encrypted DKG share delivery (`dkg-share-delivery-hpke-v1`): host measurements (ADR-0054) + +**Date:** 2026-10-09 +**Harness:** `ElGamalBenchmark.dkgShareDelivery`, run in its own JVM with +`./gradlew :zeroj-circuit-lib:elgamalBenchmark --tests '*ElGamalBenchmark.dkgShareDelivery'`. +**Machine:** Apple M4 Max (arm64), macOS, Oracle GraalVM JDK 25.0.2 (JIT, not native image). + +These numbers are evidence for this JVM and CPU only. They record throughput and make no +timing-side-channel claim. X25519, HKDF and ChaCha20-Poly1305 are the JDK providers (SunEC, +SunJCE); secret operations are compatibility/offline class (ADR-0039). + +## Per envelope + +| Operation (100-byte `SHARE`) | µs/op | +|---|---:| +| `SealBase`: ephemeral key, DH, key schedule, AEAD | 114 | +| `OpenBase`: DH, key schedule, AEAD, recipient's public key supplied | 59 | +| Announcement small-order probe (one X25519) | 54 | + +Sealing needs two X25519 operations: the ephemeral public key and the DH. Opening needs one, +because `closeRound1` passes the recipient's known public key. An earlier version that +recomputed it cost 111 µs per open. The harness calls the `byte[]` overload, which also rebuilds +the provider private key on every open. `closeRound1` builds it once per round, so the row is an +upper bound for production. + +## Per participant and per run + +Each participant: +- seals `n − 1` envelopes and opens `n − 1`; +- runs the probe on up to `n` announcements; +- runs two platform self-tests, in `start` and `closeRound1` (ADR-0054 implementation notes 7 + and 10). Each one opens the RFC 9180 A.2.1 known answer, then seals and opens once. + +The delivery work per participant is therefore about +`(n − 1) · 0.17 ms + n · 0.05 ms + 0.47 ms`: + +| `n` | Delivery work per participant (computed from the table above) | +|---:|---:| +| 3 | ≈ 1.0 ms | +| 7 | ≈ 1.9 ms | +| 21 | ≈ 5.1 ms | +| 64 | ≈ 15 ms | + +Whole encrypted runs, with all `n` participants in one JVM, measured against plain runs on the same +dealings. These were measured before the self-tests were added; they add about 0.5 ms per +participant, well inside the run-to-run noise: + +| DKG (t, n) | Plain run | Encrypted run | +|---|---:|---:| +| (1, 3) | 45 ms | 48 ms | +| (2, 5) | 144 ms | 129 ms | +| (3, 7) | 298 ms | 279 ms | +| (5, 11) | 766 ms | 764 ms | +| (10, 21) | 3,819 ms | 3,540 ms | + +The difference is within run-to-run noise. The threshold key generation's own work (blinded +dealing, VSS checks, recomputation) dominates, and the two harnesses differ slightly in overhead. +The board cost is `n(n − 1)` envelopes of 223 bytes per attempt plus `n` announcements of 106 +bytes: about 0.9 MB of envelopes at `n = 64`. + +## GraalVM native image + +`HpkeNativeProbe` (in `zeroj-circuit-lib` test sources) compiled with `native-image` 25.0.2 +(`--no-fallback`; about 19 s build) prints exactly the JVM's output: +- the RFC 9180 A.2.1 values; +- all 257 sequence ciphertexts (by digest); +- the RFC 7748 §6.1 public key; +- the small-order refusals. + +No `META-INF/native-image` configuration was needed. diff --git a/docs/circuit-annotation-user-guide.md b/docs/circuit-annotation-user-guide.md index 23e59b51..3e4fee63 100644 --- a/docs/circuit-annotation-user-guide.md +++ b/docs/circuit-annotation-user-guide.md @@ -271,7 +271,9 @@ ElGamal encryption (`elgamal-jubjub-v1`, experimental) has typed adapters too: See `AnnotatedElGamalBallot` and `AnnotatedElGamalDleq`, proved and verified in `AnnotatedElGamalTest`. The test also runs the full flow: verified admission of ballots, -possession proofs, threshold key generation, and verified decryption shares. +possession proofs, threshold key generation, and verified decryption shares. It runs the threshold key +generation twice: once over private channels, and once with the private shares HPKE-encrypted on the +board (`dkg-share-delivery-hpke-v1`, ADR-0054). Jubjub adapters use BLS12-381. Bind every prover-supplied point with `ZkJubjubPoint.witnessAffine(zk, u, v)`. It asserts the diff --git a/docs/specs/dkg-share-delivery-hpke-v1.md b/docs/specs/dkg-share-delivery-hpke-v1.md new file mode 100644 index 00000000..0857f75b --- /dev/null +++ b/docs/specs/dkg-share-delivery-hpke-v1.md @@ -0,0 +1,417 @@ +# ZeroJ DKG Share Delivery with HPKE v1 — Normative Specification + +**Profile identifier:** `dkg-share-delivery-hpke-v1` +**Status:** Normative. Required by ADR-0054 (milestone M0). +**Date:** 2026-10-09 + +This document pins every value, message, rule and encoding that a second implementation needs to +deliver the private `SHARE` messages of [`elgamal-jubjub-threshold-v1`](elgamal-jubjub-threshold-v1.md) +over the same public board as the rest of the key generation. Each `SHARE` is encrypted with +HPKE [RFC 9180] to a per-attempt recipient key announced in a transport round 0 (ADR-0054 D1–D8). +Anything not written here is not part of the profile. Any change needs a new identifier (`-v2`). + +This is a **transport profile**. It changes nothing in `elgamal-jubjub-threshold-v1`: not its +messages, rules, transcript, digest, admission or outputs (ADR-0054 Q1). A run that uses this +transport produces exactly the transcript a run with ideal private channels would produce, given +the same shares. + +Conventions: +- `u8` is one unsigned byte. `‖` is concatenation. +- `I2OSP(x, k)` writes `x` as `k` big-endian bytes, as in RFC 9180 §3. +- `p = 2^255 − 19`. X25519 values are 32-byte strings, little-endian, as in [RFC 7748] §5. +- `session`, `n`, `t`, the identifiers `1 … n`, the roster keys `key_j`, `SHARE`, + `COMMITMENTS` and the rounds are those of `elgamal-jubjub-threshold-v1` (§1–§5). +- `ASCII(s)` is the byte string of the ASCII characters of `s`, without a terminator. + +--- + +## 1. Suite and mode + +| Item | Value | Reference | +|---|---|---| +| Mode | `mode_base = 0x00`, single-shot | RFC 9180 §5.1.1, §6.1 | +| KEM | `0x0020` DHKEM(X25519, HKDF-SHA256): `Nsecret = 32`, `Nenc = 32`, `Npk = 32`, `Nsk = 32` | §4.1, §7.1 | +| KDF | `0x0001` HKDF-SHA256: `Nh = 32` | §7.2, [RFC 5869] | +| AEAD | `0x0003` ChaCha20Poly1305: `Nk = 32`, `Nn = 12`, `Nt = 16` | §7.3, [RFC 8439] §2.8 | + +This one suite and this one mode are the only ones produced or accepted. There is no +negotiation. `SealBase` and `OpenBase` are RFC 9180 §6.1 exactly, with the key schedule of §5.1, +`psk = ""` and `psk_id = ""`. A single-shot context uses sequence number 0 only. The export +interface (§5.3) is not used. + +**Validation (RFC 9180 §7.1.4).** Every Diffie–Hellman output is checked. If `DH(sk, pk)` is the +all-zero string, the operation fails. This is required of both the sender (`Encap`) and the +recipient (`Decap`), whatever the underlying X25519 implementation does. + +--- + +## 2. X25519 encodings + +### 2.1 Canonical public values + +A 32-byte string `b` is a **canonical X25519 public value** if: +1. bit 255 of `b` (the most significant bit of `b[31]`) is 0; and +2. the little-endian integer `u` that `b` encodes satisfies `u < p`. + +Every X25519 public value carried in a message of this profile, the announced key `pkR` (§3) and +the encapsulation `enc` (§4), must be canonical. A non-canonical value makes its message +**malformed**. This is checked on the bytes before any X25519 computation (ADR-0054 D8, Q4). + +The X25519 function itself is unchanged. [RFC 7748] §5 requires implementations of the function +to "accept non-canonical values". This profile only refuses such values earlier, at the message +format, so that each message has one accepted encoding. + +### 2.2 Small-order announced keys + +An announced key `pkR` must also have **non-zero DH output** with a fixed probe scalar: + +``` +PROBE = 0x09 ‖ 0^31 (a 32-byte X25519 private scalar, clamped as in RFC 7748 §5) +X25519(PROBE, pkR) ≠ 0^32 +``` + +Clamping makes every X25519 scalar `k` a multiple of 8, with `k = 8k'` and +`2^251 ≤ k' < 2^252`. So `k'` is never a multiple of either large prime factor: +- the curve's subgroup order `q = 2^252 + 27742317777372353535851937790883648493`; +- the twist's `q' = 2^253 − 55484635554744707071703875581767296995`. + +Hence `X25519(k, u) = 0^32` exactly when the point with u-coordinate `u` has order dividing 8 +(curve, cofactor 8) or 4 (twist, cofactor 4), whatever the scalar. That is, `u` is of small +order. One fixed scalar decides it for all. A small-order key would make every dealer's `Encap` fail (§1). Refusing it in the +announcement gives every participant the same directory (§3.2). + +*Informative.* Reduced mod `p`, there are exactly five such u-coordinates: `0`, `1`, `p − 1`, +and the two order-8 values +`325606250916557431795983626356110631294008115727848805560023387167927233504` and +`39382357235489614581723060781553021112529911719440698176882885853963445705823`. They are the +public values of every all-zero case in Wycheproof `x25519_test.json` (§9.2). An implementation +may decide "small order" by membership in this set, for the probe and for `enc` (§4.2 step 5), +instead of by how its X25519 provider reports it. The outcome is identical, and it does not +depend on the provider (§4.2, "A local fault is not a failed step"). + +### 2.3 Private keys + +A recipient private key `skR` is 32 bytes from a cryptographically secure generator: RFC 9180 +§4's `GenerateKeyPair`, which for X25519 is 32 random bytes used as the scalar. It is clamped by +X25519 itself. `DeriveKeyPair` (§7.1.3) is used only to reproduce the RFC's test vectors. +`pkR = X25519(skR, 9)`, which is `SerializePublicKey`. The same applies to the ephemeral key `skE`: fresh for every envelope, and +never reused (RFC 9180 §9.2.3). + +--- + +## 3. Round 0 — key announcements + +### 3.1 Message + +Before round 1 of the key generation, each participant `j` posts one announcement for the +attempt: + +``` +ANNOUNCE_j = TAG_A ‖ session (32) ‖ u8(j) ‖ pkR_j (32) +TAG_A = ASCII("zeroj.dkg-share-delivery-hpke.v1.announce") (41 bytes) +``` + +Its length is exactly 106 bytes. `pkR_j` is a fresh key for this session (§7). + +An announcement is **well-formed** for a configuration only if all of the following hold: +- its length is exactly 106 bytes and it starts with `TAG_A`; +- `session` equals the configuration's session; +- `1 ≤ j ≤ n`; +- `pkR_j` is canonical (§2.1) and passes the small-order probe (§2.2). + +It is **delivered** only if it is also authenticated as sent by participant `j` under `key_j`, +by the application's authenticator (`elgamal-jubjub-threshold-v1` §8), and it is in the final +round-0 window (§5). + +### 3.2 The key directory + +For each `j`, consider the delivered announcements from `j`. Byte-identical copies count once. +- Exactly one distinct announcement: `j`'s key is its `pkR_j`. +- None, or two or more distinct ones (a **conflict**): `j` has **no key**. + +The directory is a deterministic function of the final round-0 window, so every honest +participant computes the same one. A local fault while building it (§4.2, "A local fault is not +a failed step") is not a missing key: the participant does not build a directory and may retry +on the same window. + +### 3.3 Abort T1 — own key missing + +A participant `j` whose directory gives **no key for `j` itself**, or a key other than its own +(the public key of the private key `j` holds), aborts the attempt before round 1 (ADR-0054 D4). It does not deal, complain, +answer, confirm or post anything further for the attempt. +- This covers an announcement that is missing, malformed, unauthenticated or in conflict. +- A different key can be there only if someone authenticated as `j` posted it. That cannot + happen to an honest participant. + +T1 ensures that an honest participant never complains about missing shares because its own key +went missing. Such complaints would make every dealer publish that participant's shares. + +--- + +## 4. Round 1 — envelopes + +### 4.1 Sealing + +For each recipient `j ≠ i` that has a key in the directory, dealer `i` seals its `SHARE_ij`, the +canonical 100-byte `SHARE` message of `elgamal-jubjub-threshold-v1` §4 (header included): + +``` +info = TAG_I ‖ session (32) ‖ u8(i) ‖ u8(j) +TAG_I = ASCII("zeroj.dkg-share-delivery-hpke.v1.info") (37 bytes) +(enc, ct) = SealBase(pkR_j, info, aad = "", pt = SHARE_ij) (RFC 9180 §6.1) +ENVELOPE_ij = TAG_E ‖ session (32) ‖ u8(i) ‖ u8(j) ‖ enc (32) ‖ ct (116) +TAG_E = ASCII("zeroj.dkg-share-delivery-hpke.v1.envelope") (41 bytes) +``` + +- `ENVELOPE_ij` is exactly 223 bytes, and `ct` is exactly `100 + 16 = 116` bytes. +- `info` is 71 bytes. All binding is in `info`, as RFC 9180 §8.1 recommends for single-shot + use, and `aad` is the empty string. +- A dealer seals **no envelope to itself**: it keeps `(s_ii, s'_ii)`. +- It seals none to a recipient without a key. + +None of the three tags is a prefix of any other, or of any `elgamal-jubjub-threshold-v1` +message. Those all begin with a 32-byte session, which a fixed ASCII tag matches only with +negligible probability, so the threshold profile's decoding refuses every message of this +profile. + +### 4.2 Opening + +Recipient `j` processes every envelope in the final round-1 window (§5) whose header names `j` +as recipient. An envelope is **accepted** only if every step succeeds: +1. its length is exactly 223 bytes and it starts with `TAG_E`; +2. `session` equals the configuration's session, `1 ≤ i ≤ n`, the header recipient is `j`, and + `i ≠ j`; +3. it is authenticated as sent by participant `i` under `key_i`; +4. `enc` is canonical (§2.1); +5. `pt = OpenBase(enc, skR_j, info_ij, aad = "", ct)` succeeds, including the all-zero DH check + (§1) and AEAD verification; +6. `pt` is a well-formed `SHARE` of this session, with sender `i` and subject `j` + (`elgamal-jubjub-threshold-v1` §4). The recipient then submits it as a private delivery from + `i`. + +Byte-identical envelopes count once. Envelopes are de-duplicated only **after** authentication +(step 3), so an unauthenticated copy can never shadow the genuine post. +- Two accepted envelopes from `i` to `j` whose plaintexts are byte-identical deliver one `SHARE`. +- Two whose plaintexts differ deliver two different `SHARE`s, which the threshold profile treats + as a conflict (§5, R2: a complaint). + +**Failure is absence.** If any step fails, that envelope delivers nothing. The participant +publishes nothing about the failure and no other message. The only public consequence of a +missing or invalid share is the threshold profile's usual round-2 `COMPLAINT` (ADR-0054 D6, I4). + +**A local fault is not a failed step.** A step fails only because of the envelope: +- a malformed header (steps 1, 2, 4); +- an authentication result of "not authentic" (step 3); +- a small-order `enc` (decided as in §2.2), or the all-zero value (step 5); +- an AEAD verification failure (step 5); +- a plaintext that is not the expected `SHARE` (step 6). + +If the recipient's own platform fails instead (a primitive is unavailable or errs, or the +authenticator cannot answer), the recipient must not treat the envelope as absent. It stops +processing, keeps its key and does not close round 1; it may then process the same final window +again, and only that window: the earlier pass may already have delivered from it. A retry that +repeats the window is still no evidence that the window is final, complete or agreed (P1, P2). +Treating such a fault as absence would turn every honest dealer's share into a complaint, +and so into a public answer. + +--- + +## 5. Windows, the processing barrier and posting order + +A **window** is the board's set of posts for one round of this profile or of the threshold +profile, delivered under the per-window rule of `elgamal-jubjub-threshold-v1` §5. That set +contains the posts made while the round was open, before its cutoff, and final. An early or late +post belongs to no window. + +With this profile, **round 0 precedes round 1**: +- Round 1's window opens when round 0's window closes. This refines the threshold profile's + "for round 1, once the session started". +- A threshold-profile message posted during round 0 is early and belongs to no window. +- Rounds 2–7 are unchanged. + +**Atomic posting** (§5.2) is a property of the board: all of a set of posts are included in one +window, or none are. For example, they share one ledger transaction. This profile defines no +wire format for it. Each contained message is authenticated and processed exactly as if posted +alone. + +### 5.1 Processing barrier (ADR-0054 D6a) + +A participant advances only after the window is final, retrieved and fully processed: +- **After round 0:** it builds the directory (§3.2), applies T1 (§3.3) and only then seals + (§4.1). +- **After round 1:** it delivers its round-1 broadcasts to the threshold participant, opens and + processes **every** envelope addressed to it (§4.2), and only then closes round 1 of the + threshold profile. + +A participant must never close round 1 while an envelope in the final window is unprocessed. The +window's cutoff decides what was delivered; how long processing takes does not. + +### 5.2 Posting order (ADR-0054 D7a) + +Dealer `i` posts its round-1 `COMMITMENTS` **only after all its envelopes are final on the board +within the round-1 window**. Alternatively, it posts the envelopes and `COMMITMENTS` atomically, +in one post that the board includes entirely or not at all. + +If its envelopes cannot be made final before the cutoff, the dealer posts no `COMMITMENTS`. R1 +then disqualifies it, and it is never asked to answer an honest complaint. Recipients perform no +check of this rule. + +### 5.3 Delivery contract (ADR-0054 D7) + +The secrecy argument of ADR-0054 assumes: +- **(P1) bounded publication:** an honest participant's posts are included before their window's + cutoff; +- **(P2) agreement and finality:** every honest participant obtains the same final window; +- **(P3) the barrier of §5.1.** + +With T1 (§3.3) and the posting order (§5.2), secrecy does not depend on P1. P1 then affects only +liveness. + +--- + +## 6. What the board reveals + +This section is informative: it records consequences, not rules. + +- The board reveals who sent envelopes to whom and when, but no share (RFC 9180 §9.9). +- **No self-envelope.** A leaked `skR_j` reveals only the pairs `(s_ij, s'_ij)` with `i ≠ j`, + never `j`'s own evaluation or final share. +- **Exposure counting rule (ADR-0054 threat model).** Dealer `i`'s contribution is exposed when + the distinct evaluation indices known for `f_i` reach `t + 1`. The known indices are: + - leaked recipient keys `j ≠ i` for which an authentic envelope from `i` is on the board. This + includes one posted outside its window: it delivered nothing, but it is public and permanent; + - corrupted participants; + - public answers for `i`; + - the pairs published in rounds 5–6 for `i` (extraction complaints and reconstruction); a + dealer reconstructed in round 6 is entirely public; + - every recipient of an envelope from `i`, if the ephemeral randomness `i` used for sealing is + predictable or leaked (§7): with it, anyone can derive each envelope's key. That is at least + `n − 1 ≥ t + 1` indices, so `i`'s contribution is exposed; + - all of them, if `i` is corrupted. + + The joint key is exposed when every qualified dealer's contribution is exposed. +- **Answers.** Corrupted participants may still complain about any dealer. A dealer that has not + aborted answers every delivered complaint; a participant that aborted with T1 answers nothing + (§3.3). Under §5, every answer by an honest qualified dealer goes to a corrupted complainer's + index (ADR-0054 I15). + +--- + +## 7. Key lifecycle + +- **Per attempt.** A recipient key pair is generated for exactly one `(session, j)` and is used + only for that session. +- **Separation.** It is never the roster key `key_j` and is not derived from it. +- **Destroy.** The private key is needed only until round 1 is processed (§5.1), and should then + be destroyed, as it should when the attempt aborts or is abandoned. Implementations can only + make this best-effort; it is offline class (ADR-0039). +- **Fresh randomness.** Every envelope uses a fresh ephemeral key from a cryptographically + secure generator. + +--- + +## 8. Assumption A1 + +The [GJKR07] proof assumes ideal private channels. This profile relies on the following +assumption, which ADR-0054 states and does not prove (an external-review gate): + +> Against a static adversary, New-DKG with ideal private channels can be replaced by New-DKG +> whose private messages are encrypted under an IND-CCA2-secure public-key encryption scheme +> to per-attempt honest recipient keys. Secrecy then holds computationally, under the security +> of that scheme plus [GJKR07]'s discrete-log assumption. + +RFC 9180 §9.1 and §9.1.2 describe HPKE Base mode's chosen-ciphertext security goal, and its +analysis. + +--- + +## 9. Test vectors + +### 9.1 Test keys + +Test keys are deterministic. Test X25519 private keys are + +``` +sk(tag) = SHA-256( ASCII("zeroj.dkg-share-delivery-hpke.v1.test.") ‖ ASCII(tag) ) +``` + +used as 32-byte scalars, clamped by X25519. Production keys must come from a secure generator. + +Tag scheme of the profile vectors (§9.3): +- `.recipient.` is participant `j`'s recipient key; +- `.ephemeral..` is the ephemeral key of envelope `i → j`; +- `envelope.ephemeral.` is the ephemeral key of a single envelope case. + +The prefix is the fixture name (`honest-2of3`, `honest-3of5`, `honest-4of7`), `timing.`, +`directory…`, `envelope…` or `announce`. The reference's README lists every tag. No tag is used +twice. + +### 9.2 Required external vectors + +- RFC 9180 Appendix A.2.1: every Base-mode encryption, sequence numbers 0–256 as listed in the + CFRG `test-vectors.json` at commit `b1f7cb0cdeab6906c61b3d6574e8bdfdbe1cd3fb`. +- [RFC 7748] §5.2 and §6.1, and Wycheproof `x25519_test.json`. +- [RFC 8439] §2.8.2, and Wycheproof `chacha20_poly1305_test.json`. +- [RFC 5869] A.1–A.3, and Wycheproof `hkdf_sha256_test.json`. + +The Wycheproof files are taken at commit `12fd3aaf33eb5fa1f52e026912ee00c054f9d984` of +`C2SP/wycheproof`. + +### 9.3 Profile vectors + +They are produced by the independent reference in +`zeroj-circuit-lib/src/test/resources/dkg-share-delivery-reference/`. Pinned values: + +Configuration `honest-2of3`: `t = 1`, `n = 3`, `ctx = "zeroj.test.honest"`, attempt 1, the +standard roster. Recipient 2's key is `sk("envelope.recipient.2")`. Dealer 1's share to +participant 2 is sealed with `skE = sk("envelope.ephemeral.good")`. + +| Item | Value | +|---|---| +| `pkR` (recipient 2) | `504988081ce259944f19570f5e350690a094ec9d519d9c41e20c355c4939d96a` | +| `info` (1 → 2) | `7a65726f6a2e646b672d73686172652d64656c69766572792d68706b652e76312e696e666f` ‖ session ‖ `01` ‖ `02` (71 bytes) | +| `enc` | `b9886d82301676564de05a8ace89f381e6421f55d634db0194093db4bc733d12` | +| `shared_secret` | `0af8f73bda0aa3472c9dfc33df93d80647bdd1612bfd2316d83c3c46022bd8e7` | +| `key` | `a50c772753344ab621250e97d7be47778df5114d1703a701e0ab16c1703e3e6f` | +| `base_nonce` | `a13c0a5653e198c69e43a28b` | +| `ct` (116 bytes) | `d898640e561c28fa2f1256ff43dbb3f03b61fe44f15577bcf715434119db5be2faf267425d83e29475d62b7a3f82fdd98994c385fb537b1d595b67021e048fa21bb4e467e4432ed55d8282edbe3c735ae7e28b54322539f3df54d7d31ce761da2028a60045b07987e39b92e44acd84f34431cbf7` | + +Full encrypted runs, with recipient keys `.recipient.` and ephemerals +`.ephemeral..`, give exactly the threshold profile's §11 outputs. Encrypted delivery +leaves the key generation unchanged: + +| Run | Transcript digest | `y` | +|---|---|---| +| `honest-2of3` | `2af7f7eae154833d51861bae276448b396eae5479a074a833a31a9fb9aa46023` | `14acdc488055720e853cbb6b613d2c7f52aee2fa8e7f37b410b1fa9093082658` | +| `honest-3of5` | `edd7aa9f589992e9801d76987611d293ff921e046da81c3790121d767ffdcf71` | `89eeef65017eb8f1a18e38a5b9fc0efb971386181e0db4649c60941cd5a6c425` | +| `honest-4of7` | `9b6a52fe5b0fb06feb875b82cb37871e64bc235b01de384ba54a06f96c24431b` | `ba8011aef2b5f23231919caf1c3c901626e7c970436e98386d46b01713616a63` | + +The reference's `reference-output.txt` holds every vector: 110 replayable cases (announce, +envelope, directory, timing, run and exposure), each documented in its README. + +--- + +## 10. References + +- **[RFC 9180]** R. Barnes, K. Bhargavan, B. Lipp, C. Wood, *Hybrid Public Key Encryption*, + February 2022: + - §3: notation; + - §4: labeled HKDF; + - §4.1: DHKEM; + - §5.1: key schedule; + - §5.1.1: Base mode; + - §5.2: encryption and sequence numbers; + - §6.1: single-shot; + - §7.1–§7.3: identifiers; + - §7.1.3: DeriveKeyPair; + - §7.1.4: validation; + - §8.1: `info`; + - §9: security considerations; + - Appendix A.2: test vectors. +- **[RFC 7748]** *Elliptic Curves for Security*, January 2016: §5 (X25519, decoding), §5.2 and + §6.1 (test vectors). +- **[RFC 8439]** *ChaCha20 and Poly1305 for IETF Protocols*, June 2018: §2.8 (AEAD). +- **[RFC 5869]** *HMAC-based Extract-and-Expand Key Derivation Function (HKDF)*, May 2010, + including Appendix A. +- **[GJKR07]** Gennaro, Jarecki, Krawczyk, Rabin, J. Cryptology 20:51–83 (2007), §2.1 and Fig. 2. +- **ZeroJ:** ADR-0053, ADR-0054, [`elgamal-jubjub-threshold-v1`](elgamal-jubjub-threshold-v1.md). diff --git a/docs/specs/elgamal-jubjub-threshold-v1.md b/docs/specs/elgamal-jubjub-threshold-v1.md index d4e9a402..2f4cbe6e 100644 --- a/docs/specs/elgamal-jubjub-threshold-v1.md +++ b/docs/specs/elgamal-jubjub-threshold-v1.md @@ -144,7 +144,10 @@ authenticated, well-formed message **of round `r`** that arrived while round `r` round `r − 1` closed (for round 1, once the session started) and before round `r` closed. A message that is late, early or malformed counts as **absent**. An early message, sent while an earlier round was open, is dropped and not carried forward into its own round; honest -participants send round `r`'s messages only while round `r` is open. Every rule below is a deterministic function of the delivered broadcast sets, so all +participants send round `r`'s messages only while round `r` is open. (*Informative:* with the +transport profile [`dkg-share-delivery-hpke-v1`](dkg-share-delivery-hpke-v1.md), round 1 opens +when that profile's round 0 closes, its §5; a message of this profile posted during round 0 is +early.) Every rule below is a deterministic function of the delivered broadcast sets, so all honest participants, and anyone recomputing a transcript, take the same decisions. **R1.** Dealer `i` is **disqualified** if its `COMMITMENTS` is absent or in conflict. @@ -270,6 +273,11 @@ deadline, with deadlines chosen accordingly. How an honest dealer should respond it believes is caused by late delivery is an open maintainer question (ADR-0053 Q7). This profile does not change Fig. 2's rule. +*Informative.* The transport profile [`dkg-share-delivery-hpke-v1`](dkg-share-delivery-hpke-v1.md) +(ADR-0054) delivers the `SHARE`s as HPKE envelopes on the board. Its processing barrier, +commitments-last posting order and abort T1 remove this precondition's dependence on timing, for +deployments that meet its delivery contract. It changes nothing in this profile. + A4 cannot be triggered without knowing `log_G H`. Pairs that pass (4) but disagree with the polynomial require that discrete logarithm. So A4 is a defensive check, and the independent reference exercises it only with a test-only trapdoor base. diff --git a/www/src/content/docs/guides/circuits/gadgets.md b/www/src/content/docs/guides/circuits/gadgets.md index b8296b6d..0398bb4f 100644 --- a/www/src/content/docs/guides/circuits/gadgets.md +++ b/www/src/content/docs/guides/circuits/gadgets.md @@ -305,12 +305,64 @@ can decrypt, and up to `t` can be lost or malicious. The trustees run a distribu generation, New-DKG of Gennaro et al., with `DkgParticipant`. No single party ever holds the key, provided the transport delivers the private shares on time. A late share can make an honest dealer publish it, so timely delivery is a secrecy requirement, not only a liveness one. -- Your application supplies the transport: a broadcast board with agreement, private channels - for shares, and round deadlines. +- Your application supplies the transport: a broadcast board with agreement and round + deadlines. For the private shares it can supply its own channels, or use ZeroJ's encrypted + delivery over the same board (below). - A third party accepts the result with `ThresholdKeyContext.admit`, which requires authenticated messages, closed rounds, and confirmations from at least `t + 1` trustees. - Ballots and sums are unchanged. Decryption takes any `t + 1` verified shares. +**Encrypted share delivery over the board.** `dkg-share-delivery-hpke-v1` (ADR-0054, +experimental) removes the private channels. It encrypts each share with HPKE (RFC 9180 Base +mode; X25519, HKDF-SHA256, ChaCha20-Poly1305) to the recipient's key for this attempt, and the +dealer posts the envelope on the board. Delivery becomes visible, and trustees need not be +online together. The key generation, its transcript and admission are unchanged. + +```java +// Round 0: a fresh key per attempt, announced under the roster key. +DkgShareDeliveryKeys keys = DkgShareDeliveryKeys.generate(config, myId, random); +post(keys.announcement()); +DkgKeyDirectory directory = DkgKeyDirectory.fromRound0(config, finalRound0Window, verifier); + +// Round 1: start (instead of participant.start()); post the envelopes, and the COMMITMENTS only +// once the envelopes are final. +DkgShareDelivery.SealedDealing dealing = DkgShareDelivery.start(participant, directory, keys, random); +postAndAwaitFinality(dealing.envelopes()); +post(dealing.broadcasts()); + +// Close round 1 behind the barrier, with the complete final window. This also destroys the keys. +List complaints = DkgShareDelivery.closeRound1(participant, directory, keys, finalRound1Window, verifier); +// Rounds 2–7 continue with participant.receiveBroadcast / closeRound as before. +``` + +These rules are what keep the shares secret. They are not optional: +- **Barrier.** Close round 1 only through `closeRound1`, with the window *after* its cutoff and + finality. The library can't check that: a snapshot taken before finality can miss envelopes, + and processing late is exactly the failure the barrier prevents. Round 1's window opens when + round 0's closes, so a threshold message posted during round 0 is early and doesn't count. A participant started with `DkgShareDelivery.start` refuses the plain `closeRound()` + at round 1, so it cannot complain about a share it never processed. If `closeRound1` throws + anything other than an abort (your verifier, or a crypto-provider fault), the participant + stays at round 1 with its keys; retry with the same window, or call `keys.destroy()` if you + give up the attempt. The retry must pass exactly the same posts in the same order: any other + window is refused with `IllegalArgumentException`. This check proves only that the retry + repeats the first call. It does not prove the window is final or complete. Your verifier must return `false`, not throw, for posts it does not + accept. If `start` throws after the participant started, post nothing for it in round 1. +- **Commitments last.** Post `COMMITMENTS` only after every envelope is final within the round-1 + window, or post them all atomically. If the envelopes cannot make the cutoff, post nothing: + the dealer is then disqualified and its contribution is excluded from the key. Honest + trustees don't complain about it; a corrupted trustee still can, and receives only its own + share in the public answer. +- **T1.** If your own announcement is missing from the final round-0 window, or the directory holds + a different key for you, `start` throws `OWN_KEY_ANNOUNCEMENT_MISSING` and aborts the participant. + Post nothing more for this attempt. +- **Keys.** Generate fresh keys per attempt; they are separate from the roster key. Ciphertexts on + a public board are kept forever, and a leaked key opens what was sent to it. A few leaked keys, + together with corrupted trustees, can expose the joint key. + +The construction rests on a stated assumption: that encryption can replace the private channels +of the GJKR07 proof. That assumption, and the delivery argument, await external review. See the +spec `docs/specs/dkg-share-delivery-hpke-v1.md`. + :::caution[Offline trustee and encryption operations] Key generation, encryption, decryption shares and the DKG handle secrets with variable-time Java `BigInteger` arithmetic, through the blinded best-effort schedule used for Pedersen. @@ -364,6 +416,7 @@ authorization or replay rules. | EdDSA-Jubjub | BLS12-381 only | Verification ready pending external review; legacy signing offline only | | ElGamal encryption and trustee proofs (in-circuit) | BLS12-381 only | Experimental | | ElGamal host API, threshold key generation | Jubjub | Experimental; secret operations offline or isolated only | +| Encrypted DKG share delivery (`dkg-share-delivery-hpke-v1`) | X25519 HPKE | Experimental; Assumption A1 and the delivery contract await external review | | BLAKE2b, CIP-1852 derivation | Field-agnostic | Ready on BLS12-381 Groth16 | | SHA-512, HMAC-SHA512, BIP32-Ed25519 | Field-agnostic | Ready as building blocks | | Poseidon MPF/JMT authenticated state | BLS12-381 Poseidon profile | Experimental (separate modules) | diff --git a/zeroj-circuit-lib/README.md b/zeroj-circuit-lib/README.md index c35a0f75..8832837e 100644 --- a/zeroj-circuit-lib/README.md +++ b/zeroj-circuit-lib/README.md @@ -51,7 +51,8 @@ final proof, verification key data, and public inputs. | Pedersen homomorphic API | `InCircuitJubjub.negate`/`subtract`/`assertInPrimeOrderSubgroup` | `ZkPedersenCommitment`, `ZkPedersen.assertBalanced`, `ZkJubjubPoint.negate`/`subtract`/`assertInPrimeOrderSubgroup` | BLS12-381 scalar field only | Experimental, pending review and external review | The public subgroup assertion validates the point (curve, `T·Z = U·V`, `Z ≠ 0`) before `[l]·P = O`. Unopened external commitments enter only through `witnessInSubgroup` or `fromVerifierCheckedPublic`. Commitment sums hold mod `l`; `assertBalanced` refuses layouts that could wrap (ADR-0051 D3a). `PedersenCommitment.decode` adds the subgroup check to canonical decoding. | | Pedersen vector commitment | `InCircuitPedersenVector`, `PedersenVectorBases`, `PedersenVectorSchema`, `PedersenVectorCommitment`, `PedersenSchemaRegistry` | `ZkPedersenVector`, `ZkPedersenVectorCommitment` | BLS12-381 scalar field only | Experimental, pending spec and external review | Spec: [`pedersen-jubjub-vector-v1`](../docs/specs/pedersen-jubjub-vector-v1.md). Up to 16 values; bases from Zcash `FindGroupHash("ZeroJ_PV", …)`. The point binds neither length nor schema, so proofs bind a public schema digest and verifiers check it against a registry; received commitments need an authenticated issuance record (fail closed). | | ElGamal encryption (in-circuit) | `InCircuitElGamal` | `ZkElGamal`, `ZkElGamalPublicKey`, `ZkElGamalCiphertext` | BLS12-381 scalar field only | Experimental, pending review and external review | Spec: [`elgamal-jubjub-v1`](../docs/specs/elgamal-jubjub-v1.md) (ADR-0052). Message width 1–64 (wider refused at definition); randomness exactly 252 bits, never public, one decomposition for `[k]·G` and `[k]·PK`; keys enter as verifier-fixed public coordinates or witnessed in the subgroup, never the identity. DLEQ requires all six coordinates public. Rows: 6,558 (width 1) / 6,650 (16) / 6,938 (64); witnessed key 12,105; DLEQ 6,546. | -| ElGamal host API and threshold DKG | `ElGamal`, `ElGamalCiphertext`, `NOfNKeyContext`, `VerifiedKeyShare`, `VerifiedDecryptionShare`, `JubjubDiscreteLog`; `DkgParticipant`, `DkgTranscript`, `ThresholdKeyContext` | — | Jubjub over BLS12-381 | Experimental; secret operations **offline/isolated only** (ADR-0039 compatibility class) | Safe layer: admitted ciphertexts carry a key context and an established bound; shares and keys are verified by type. Threshold profile [`elgamal-jubjub-threshold-v1`](../docs/specs/elgamal-jubjub-threshold-v1.md) (ADR-0053): GJKR07 New-DKG, `t < n/2`, library-computed admission; transport is the application's. | +| ElGamal host API and threshold DKG | `ElGamal`, `ElGamalCiphertext`, `NOfNKeyContext`, `VerifiedKeyShare`, `VerifiedDecryptionShare`, `JubjubDiscreteLog`; `DkgParticipant`, `DkgTranscript`, `ThresholdKeyContext` | — | Jubjub over BLS12-381 | Experimental; secret operations **offline/isolated only** (ADR-0039 compatibility class) | Safe layer: admitted ciphertexts carry a key context and an established bound; shares and keys are verified by type. Threshold profile [`elgamal-jubjub-threshold-v1`](../docs/specs/elgamal-jubjub-threshold-v1.md) (ADR-0053): GJKR07 New-DKG, `t < n/2`, library-computed admission; transport is the application's, or the encrypted board delivery below for the private shares. | +| Encrypted DKG share delivery | `DkgShareDelivery`, `DkgShareDeliveryKeys`, `DkgKeyDirectory` | — | X25519 (JDK providers) | Experimental; Assumption A1 and the delivery contract await external review | Profile [`dkg-share-delivery-hpke-v1`](../docs/specs/dkg-share-delivery-hpke-v1.md) (ADR-0054): HPKE (RFC 9180 Base; X25519, HKDF-SHA256, ChaCha20Poly1305) envelopes on the DKG board, per-attempt keys announced in round 0. Rules: close round 1 only through `closeRound1` (the barrier), with the window after its cutoff and finality; post `COMMITMENTS` only after the envelopes are final; abort if the directory holds no key, or not your own key, for you (T1). Checked against RFC 9180 A.2.1, Wycheproof and BouncyCastle's HPKE. | | Pedersen commitment (off-circuit generation) | `PedersenCommitment.commit`; internal fixed-limb review candidate | — | Jubjub over BLS12-381 | Legacy is **offline/isolated only**; fixed-limb path is an unapproved ADR-0039 M9 candidate | The candidate is package-private, uses mutable explicit-width openings and fixed-limb schedules, and has separate timing/external/platform gates. Hiding and binding of the commitment itself are unaffected. | | EdDSA-Jubjub | `InCircuitEdDSAJubjub`, `EdDSAJubjub`, `JubjubSigner` | `ZkEdDSAJubjub` | BLS12-381 scalar field only | Verification ready pending external review; legacy signing offline-only; fixed-limb hedged profile remains an unapproved candidate | Two in-circuit entry points are named for their key-trust model. `JubjubSigners.validatedDedicatedHostJavaRequired` deliberately fails closed until ADR-0039 M4–M8 pass. Specs: [`jubjub-eddsa-v1`](../docs/specs/jubjub-eddsa-v1.md), [hedged candidate](../docs/specs/jubjub-eddsa-hedged-v1-candidate.md). | | Poseidon parameters and off-circuit hashing | `PoseidonParams*`, `PoseidonHash`, `PoseidonGrainLFSR`, `PoseidonParameterFingerprint` | Used by `ZkPoseidon*`, `ZkMerkle`, and the separate MPF/JMT modules | BN254 T3, BLS12-381 T3, BLS12-381 T5 presets exist | Ready when matched to the circuit field and gadget shape | `PoseidonHash` is host-side hashing for expected roots/test vectors, not a circuit constraint by itself. `FastPoseidonBls12381T3` is the equivalence-tested optimized **host-side** path used for off-circuit roots and witnesses; circuit constraints still use the Poseidon gadget. | diff --git a/zeroj-circuit-lib/build.gradle b/zeroj-circuit-lib/build.gradle index 23e47a97..7dd45857 100644 --- a/zeroj-circuit-lib/build.gradle +++ b/zeroj-circuit-lib/build.gradle @@ -143,6 +143,9 @@ dependencies { testImplementation "com.bloxbean.cardano:cardano-client-crypto:${rootProject.ext.cclVersion}" // Authoritative RFC 8032 Ed25519 oracle for the Ed25519 gadget tests. testImplementation 'org.bouncycastle:bcprov-jdk18on:1.83' + // Reads the vendored standard test vectors (RFC 9180 / CFRG HPKE, Wycheproof) in + // src/test/resources/standard-vectors. Test-only. + testImplementation 'com.fasterxml.jackson.core:jackson-databind:2.18.2' } /** diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgAdmissionVerifier.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgAdmissionVerifier.java index 30087f48..48f717a1 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgAdmissionVerifier.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgAdmissionVerifier.java @@ -23,7 +23,15 @@ */ public interface DkgAdmissionVerifier { - /** {@code true} iff {@code message} was sent by the participant holding {@code rosterKey}. */ + /** + * {@code true} iff {@code message} was sent by the participant holding {@code rosterKey}. + * + *

Return {@code false}, never throw, for input that is malformed or not authentic: the + * authenticator bytes come from the board and may be chosen by an attacker. Throw only on a + * transient fault of the checking itself. {@link DkgShareDelivery#closeRound1} then stops + * without closing round 1 (fail closed) and can be retried; a verifier that throws on attacker + * input would block that participant's round 1 for good. + */ boolean authenticate(int sender, byte[] rosterKey, byte[] message, byte[] authenticator); /** diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgKeyDirectory.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgKeyDirectory.java new file mode 100644 index 00000000..4807cc65 --- /dev/null +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgKeyDirectory.java @@ -0,0 +1,110 @@ +package org.zeroj.circuit.lib.jubjub; + +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +/** + * The round-0 key directory of {@code dkg-share-delivery-hpke-v1} (spec §3.2; ADR-0054 D4, I5): for + * each participant, its unique delivered announcement's key, or none. + * + *

It is a deterministic function of the final round-0 window, so every honest participant + * builds the same directory. Byte-identical announcements count once. Two distinct well-formed, + * authenticated announcements from one participant are a conflict, and that participant has no + * key. + */ +public final class DkgKeyDirectory { + + private final DkgConfig config; + private final byte[][] keys; // index j − 1; null: no key + + private DkgKeyDirectory(DkgConfig config, byte[][] keys) { + this.config = config; + this.keys = keys; + } + + /** + * Builds the directory from the final round-0 window: the board's posts of round 0, after + * the window's cutoff and finality (spec §5). Malformed posts, posts for another session and + * posts that fail {@code verifier}'s authentication under the announcing participant's roster + * key are ignored. + * + *

The library cannot check finality. A directory built from a snapshot taken before the + * window is final can differ from other participants' directories, which breaks the agreement + * the profile relies on (spec §5.3, P2). + * + * @throws IllegalStateException if the platform's X25519 fails (a fault, never reported as a + * missing key) + */ + public static DkgKeyDirectory fromRound0(DkgConfig config, List finalWindow, + DkgAdmissionVerifier verifier) { + Objects.requireNonNull(config, "config"); + Objects.requireNonNull(finalWindow, "finalWindow"); + Objects.requireNonNull(verifier, "verifier"); + List> distinct = new ArrayList<>(); + for (int j = 0; j < config.n(); j++) distinct.add(new HashSet<>()); + byte[][] keys = new byte[config.n()][]; + for (AuthenticatedDkgMessage post : List.copyOf(finalWindow)) { + byte[] bytes = post.message(); + int j = DkgShareDeliveryCodec.announcedParticipant(config, bytes); + if (j < 1 || distinct.get(j - 1).size() > 1) continue; // malformed header, or already in conflict + if (!verifier.authenticate(j, config.rosterKey(j), bytes.clone(), post.authenticator())) continue; + DkgShareDeliveryCodec.Announcement a = DkgShareDeliveryCodec.decodeAnnouncement(config, bytes); + if (a == null) continue; // non-canonical or small-order key + if (distinct.get(j - 1).add(ByteBuffer.wrap(bytes))) keys[j - 1] = a.publicKey(); + } + for (int j = 1; j <= config.n(); j++) { + if (distinct.get(j - 1).size() != 1) keys[j - 1] = null; // none, or a conflict + } + return new DkgKeyDirectory(config, keys); + } + + /** The configuration this directory belongs to. */ + public DkgConfig config() { + return config; + } + + /** Participant {@code j}'s key, or empty if it has none. */ + public Optional key(int j) { + config.requireParticipant(j); + byte[] k = keys[j - 1]; + return k == null ? Optional.empty() : Optional.of(k.clone()); + } + + /** {@code true} iff participant {@code j} has a key. */ + public boolean hasKey(int j) { + config.requireParticipant(j); + return keys[j - 1] != null; + } + + /** + * Abort T1 (spec §3.3): throws if participant {@code id} has no key of its own. A participant + * that hits T1 must not deal, complain or post anything further for the attempt. + * + * @throws FaultAssumptionViolatedException with reason {@code OWN_KEY_ANNOUNCEMENT_MISSING} + */ + public void requireOwn(int id) { + if (!hasKey(id)) { + throw new FaultAssumptionViolatedException(FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING, + "participant " + id + "'s own key announcement is missing or in conflict in the final round-0 window"); + } + } + + /** + * Abort T1 for this participant's own keys: throws unless the directory holds exactly + * {@code keys}' public key for {@code keys.id()}. + */ + public void requireOwn(DkgShareDeliveryKeys keys) { + Objects.requireNonNull(keys, "keys"); + requireOwn(keys.id()); + if (!Arrays.equals(this.keys[keys.id() - 1], keys.publicKey())) { + throw new FaultAssumptionViolatedException(FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING, + "participant " + keys.id() + "'s directory key is not its own announced key"); + } + } +} diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgParticipant.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgParticipant.java index 6918c906..73d6ac21 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgParticipant.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgParticipant.java @@ -2,6 +2,7 @@ import java.math.BigInteger; import java.nio.ByteBuffer; +import java.security.MessageDigest; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; @@ -78,6 +79,13 @@ public final class DkgParticipant { private byte[] digest; private ThresholdKeyShare result; private FaultAssumptionViolatedException abort; + /** Set by {@link DkgShareDelivery#start}: round 1 then closes only through {@link DkgShareDelivery#closeRound1}. */ + private boolean encryptedDelivery; + /** The exact keys and directory {@link DkgShareDelivery#start} bound; round 1 closes only with these. */ + private Object boundKeys; + private Object boundDirectory; + /** The digest of the round-1 window {@link DkgShareDelivery#closeRound1} first delivered from; a retry must match it. */ + private byte[] round1Window; private DkgParticipant(DkgConfig config, int id, ThresholdVss.Dealing dealing) { this.config = config; @@ -116,9 +124,7 @@ public int openRound() { * {@code SHARE} per other participant. */ public List start() { - if (open != 0) { - throw new IllegalStateException("already started"); - } + requireStartable(); open = 1; List out = new ArrayList<>(config.n()); out.add(DkgMessage.points(config, DkgMessage.Kind.COMMITMENTS, id, dealing.commitments())); @@ -184,6 +190,17 @@ private DkgMessage accept(int authenticatedSender, byte[] message) { return m; } + /** + * Refuses a participant that cannot start, changing nothing: an aborted one throws its abort + * again, and one already started throws {@link IllegalStateException}. + */ + void requireStartable() { + requireNotAborted(); + if (open != 0) { + throw new IllegalStateException("already started"); + } + } + private void requireNotAborted() { if (abort != null) { throw abort; @@ -198,6 +215,73 @@ private void requireNotAborted() { */ public List closeRound() { requireNotAborted(); + if (encryptedDelivery && open == 1) { + // The processing barrier of dkg-share-delivery-hpke-v1 §5.1 (ADR-0054 D6a): a bound + // participant never closes round 1 except after every envelope has been processed. + throw new IllegalStateException("round 1 of a run using encrypted share delivery closes only through" + + " DkgShareDelivery.closeRound1"); + } + return closeOpenRound(); + } + + /** {@link #closeRound()} without the delivery guard; {@link DkgShareDelivery#closeRound1} only. */ + List closeRoundOneAfterDelivery() { + if (!encryptedDelivery || open != 1) { + throw new IllegalStateException("not a bound participant at round 1"); + } + requireNotAborted(); + return closeOpenRound(); + } + + /** Binds this participant to encrypted share delivery with these exact keys and directory; only before {@link #start()}. */ + void bindEncryptedDelivery(Object keys, Object directory) { + if (open != 0) { + throw new IllegalStateException("encrypted delivery must be bound before start"); + } + encryptedDelivery = true; + boundKeys = keys; + boundDirectory = directory; + } + + boolean boundToEncryptedDelivery() { + return encryptedDelivery; + } + + /** {@code true} iff {@code keys} and {@code directory} are the very objects bound at start. */ + boolean boundTo(Object keys, Object directory) { + return encryptedDelivery && boundKeys == keys && boundDirectory == directory; + } + + /** {@code true} iff no round-1 window is bound yet, or {@code windowDigest} is the bound one. */ + boolean round1WindowMatches(byte[] windowDigest) { + return round1Window == null || MessageDigest.isEqual(round1Window, windowDigest); + } + + /** Binds the round-1 window before its first delivery; later calls keep the first binding. */ + void bindRound1Window(byte[] windowDigest) { + if (round1Window == null) { + round1Window = windowDigest.clone(); + } + } + + /** Aborts this participant (sticky), for transport aborts such as T1. */ + void abortWith(FaultAssumptionViolatedException e) { + if (abort == null) { + abort = e; + forgetSecrets(); + } + } + + DkgConfig config() { + return config; + } + + /** The distinct {@code SHARE}s received from {@code dealer} so far (tests and vectors only). */ + List receivedShares(int dealer) { + return List.copyOf(sharesReceived.getOrDefault(dealer, List.of())); + } + + private List closeOpenRound() { try { return switch (open) { case 1 -> closeDeal(); diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgShareDelivery.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgShareDelivery.java new file mode 100644 index 00000000..9ea4541f --- /dev/null +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgShareDelivery.java @@ -0,0 +1,434 @@ +package org.zeroj.circuit.lib.jubjub; + +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.function.IntFunction; + +/** + * Encrypted delivery of a threshold key generation's private {@code SHARE}s over the public board: + * {@code dkg-share-delivery-hpke-v1} (ADR-0054). Each {@code SHARE} is encrypted with HPKE + * (RFC 9180 Base mode; DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20Poly1305) to the + * recipient's per-attempt key from round 0, and posted as an envelope. + * + *

The key generation itself is unchanged: {@link DkgParticipant} receives each decrypted + * {@code SHARE} through {@link DkgParticipant#receivePrivate}, and the transcript, digest and + * admission are exactly those of a run with private channels. + * + *

The rules (spec §3.3, §5; ADR-0054 D4, D6a, D7a). The library enforces those it can: + *

    + *
  1. Round 0. Post {@link DkgShareDeliveryKeys#announcement()}. When the round-0 window + * is final, build the {@link DkgKeyDirectory}.
  2. + *
  3. Start. Call {@link #start} instead of {@link DkgParticipant#start()}. It applies + * abort T1 and binds the participant: from then on its round 1 closes only through + * {@link #closeRound1}, and the public {@link DkgParticipant#closeRound()} refuses round 1.
  4. + *
  5. Posting order. Post {@link SealedDealing#envelopes()} first. Post + * {@link SealedDealing#broadcasts()} (the {@code COMMITMENTS}) only after every envelope + * is final on the board within the round-1 window, or post them all atomically. If the + * envelopes cannot be made final before the cutoff, do not post the broadcasts. This one + * rule is the application's to follow: the library cannot see the board.
  6. + *
  7. Barrier. {@link #closeRound1} takes the complete final round-1 window, delivers every + * broadcast and opens every envelope, and only then closes round 1. Binding enforces + * "process before closing"; that the window is complete is the application's to ensure. + * Pass the window only after its cutoff and finality: a snapshot taken earlier can + * miss envelopes that become final later. That is the late-processing failure the barrier + * exists to prevent (ADR-0054 D6a). Round 1's window opens when round 0's window closes, so + * a threshold-profile message posted during round 0 is early and belongs to no window + * (spec §5).
  8. + *
  9. Rounds 2–7 continue with {@link DkgParticipant#receiveBroadcast} and + * {@link DkgParticipant#closeRound()} as before.
  10. + *
+ * + *

Fail closed. If {@link #closeRound1} throws (a refused argument, T1, an exception + * from the application's verifier, or a fault of the platform's cryptographic providers) the + * participant is left at round 1, or aborted on T1, and + * cannot close round 1 any other way, so it never complains about a share it did not process. + * That costs liveness, never secrecy. A verifier must return {@code false}, not throw, for a + * post it does not accept; a verifier exception is not treated as "unauthentic", because a + * transient failure would then turn into false complaints. + * + *

The delivery contract (P1 bounded publication, P2 agreement and finality) and Assumption A1 + * are the application's and the reviewers', as stated in ADR-0054. Secret operations are + * compatibility/offline class (ADR-0039 §3.1). + */ +public final class DkgShareDelivery { + + private DkgShareDelivery() { + } + + /** A dealer's round-1 output, split by posting order (spec §5.2). */ + public static final class SealedDealing { + private final List envelopes; + private final List broadcasts; + + SealedDealing(List envelopes, List broadcasts) { + this.envelopes = envelopes; + this.broadcasts = broadcasts; + } + + /** The envelopes, to post first. */ + public List envelopes() { + List out = new ArrayList<>(envelopes.size()); + for (byte[] e : envelopes) out.add(e.clone()); + return out; + } + + /** + * The round-1 broadcasts (the {@code COMMITMENTS}), to post only after every envelope is + * final on the board within the round-1 window, or atomically with them. + */ + public List broadcasts() { + return broadcasts; + } + } + + /** + * Starts {@code participant} for encrypted delivery (spec §3.3, §4.1). It checks that the + * participant, the directory and the keys share one session and one identifier, and that the + * participant can start, before anything changes. It then applies abort T1, runs a + * seal-and-open self-test of the platform's primitives, binds the participant (see the class + * documentation), opens round 1, and seals one envelope per other participant that has a + * key. It never seals to the dealer itself. + * + *

If the self-test fails, nothing has changed and {@code start} can be retried. If sealing + * fails after round 1 opened (a platform fault, never caused by a directory key), no dealing is + * returned: the application posts nothing for this participant in round 1, so R1 disqualifies + * its dealing and no honest participant complains about it (spec §5.2). + * + * @throws FaultAssumptionViolatedException with reason {@code OWN_KEY_ANNOUNCEMENT_MISSING} + * (T1); the participant is then aborted and the keys destroyed. A participant that had + * already aborted throws its own abort again, and nothing changes + * @throws IllegalArgumentException if the participant, directory and keys disagree + * @throws IllegalStateException if the participant has already started (nothing changes: + * T1 is not applied and the keys are kept), or the platform's HPKE primitives fail + * (see above) + */ + public static SealedDealing start(DkgParticipant participant, DkgKeyDirectory directory, DkgShareDeliveryKeys keys, + SecureRandom random) { + Objects.requireNonNull(random, "random"); + return start(participant, directory, keys, recipient -> { + byte[] skE = new byte[Hpke.N_SK]; + random.nextBytes(skE); + return skE; + }); + } + + /** + * Test seam: {@link #start} with the ephemeral private key for each recipient supplied by + * {@code ephemeral} (spec §9.1 test keys). Production code uses fresh randomness only. + */ + static SealedDealing start(DkgParticipant participant, DkgKeyDirectory directory, DkgShareDeliveryKeys keys, + IntFunction ephemeral) { + Objects.requireNonNull(participant, "participant"); + Objects.requireNonNull(directory, "directory"); + Objects.requireNonNull(keys, "keys"); + Objects.requireNonNull(ephemeral, "ephemeral"); + DkgConfig config = participant.config(); + requireSameRun(participant, directory, keys); + // Refuse an ineligible participant before T1, which aborts it and destroys the keys: a + // second start must not undo a run in progress (external review of 914b68c, item 1). + participant.requireStartable(); + try { + directory.requireOwn(keys); + } catch (FaultAssumptionViolatedException t1) { + participant.abortWith(t1); + keys.destroy(); + throw t1; + } + byte[] ownSecret = keys.secretFor(config); + try { + selfTest(X25519Bytes.privateKey(ownSecret), keys.publicKey()); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("X25519 is unavailable", e); + } finally { + Arrays.fill(ownSecret, (byte) 0); + } + participant.bindEncryptedDelivery(keys, directory); + List startOutput = participant.start(); + List envelopes = new ArrayList<>(); + List broadcasts = new ArrayList<>(); + for (DkgMessage m : startOutput) { + if (m.kind() != DkgMessage.Kind.SHARE) { + broadcasts.add(m); + continue; + } + int i = m.sender(); + int j = m.subject(); + if (i == j) continue; // never sealed to oneself (spec §4.1) + byte[] pkR = directory.key(j).orElse(null); + if (pkR == null) continue; // no key: no envelope (spec §4.1) + envelopes.add(sealOne(config, i, j, pkR, m, ephemeral.apply(j))); + } + return new SealedDealing(List.copyOf(envelopes), List.copyOf(broadcasts)); + } + + private static final byte[] SELF_TEST_INFO = Hpke.ascii("zeroj.dkg-share-delivery-hpke.v1.self-test"); + + // RFC 9180 Appendix A.2.1 (DHKEM(X25519, HKDF-SHA256), HKDF-SHA256, ChaCha20Poly1305, Base), + // encryption at sequence 0. Public test values, copied from the vendored CFRG vectors + // (src/test/resources/standard-vectors/); HpkeKnownAnswerTest checks the same values. + private static final String A21_SK_R = "8057991eef8f1f1af18f4a9491d16a1ce333f695d4db8e38da75975c4478e0fb"; + private static final String A21_PK_R = "4310ee97d88cc1f088a5576c77ab0cf5c3ac797f3d95139c6c84b5429c59662a"; + private static final String A21_ENC = "1afa08d3dec047a643885163f1180476fa7ddb54c6a8029ea33f95796bf2ac4a"; + private static final String A21_INFO = "4f6465206f6e2061204772656369616e2055726e"; + private static final String A21_AAD_0 = "436f756e742d30"; + private static final String A21_PT_0 = "4265617574792069732074727574682c20747275746820626561757479"; + private static final String A21_CT_0 = "1c5250d8034ec2b784ba2cfd69dbdb8af406cfe3ff938e131f0def8c8b60b4db21993c62ce81883d2dd1b51a28"; + + /** + * A local check of the platform's X25519, HKDF and ChaCha20-Poly1305, run before any input is + * judged (reviews Z-1, R3-1). Nothing of it is posted. It opens the RFC 9180 Appendix A.2.1 + * sequence-0 ciphertext, a known answer that a provider consistent with itself but not with + * the RFC fails. It then seals a fixed plaintext to {@code pkR} under a fresh ephemeral key and + * opens it with {@code recipient}. + * + * @throws IllegalStateException if any step fails or a plaintext differs + */ + private static void selfTest(PrivateKey recipient, byte[] pkR) { + byte[] pt = new byte[DkgShareDeliveryCodec.SHARE_LENGTH]; + try { + HexFormat hex = HexFormat.of(); + byte[] known = Hpke.openBase(hex.parseHex(A21_ENC), hex.parseHex(A21_SK_R), hex.parseHex(A21_PK_R), + hex.parseHex(A21_INFO), hex.parseHex(A21_AAD_0), hex.parseHex(A21_CT_0)); + if (!Arrays.equals(hex.parseHex(A21_PT_0), known)) { + throw new IllegalStateException("HPKE known-answer self-test returned a different plaintext"); + } + Hpke.Sealed sealed = Hpke.sealBase(pkR, SELF_TEST_INFO, new byte[0], pt, new SecureRandom()); + if (!Arrays.equals(pt, Hpke.openBase(sealed.enc(), recipient, pkR, SELF_TEST_INFO, new byte[0], sealed.ct()))) { + throw new IllegalStateException("HPKE self-test returned a different plaintext"); + } + } catch (Hpke.HpkeException e) { + throw new IllegalStateException("HPKE self-test failed", e); + } + } + + /** Test seam: seals one given {@code SHARE} message (for envelopes built by negative tests). */ + static byte[] sealOne(DkgConfig config, int i, int j, byte[] pkR, DkgMessage share, byte[] skE) { + byte[] pt = share.encode(); + try { + Hpke.Sealed sealed = Hpke.sealBaseWithEphemeral(skE, pkR, DkgShareDeliveryCodec.info(config, i, j), new byte[0], pt); + return DkgShareDeliveryCodec.envelope(config, i, j, sealed.enc(), sealed.ct()); + } catch (Hpke.HpkeException e) { + // The directory holds only canonical, non-small-order keys, so sealing cannot fail on + // the recipient key. Anything else is an environment fault, not a protocol event. + throw new IllegalStateException("HPKE sealing failed", e); + } finally { + Arrays.fill(skE, (byte) 0); + Arrays.fill(pt, (byte) 0); + } + } + + /** + * Closes round 1 behind the processing barrier (spec §5.1; ADR-0054 D6a, I11). For a + * participant started with {@link #start}, it: + *

    + *
  1. checks the session and identifier of the participant, directory and keys, and + * requires the very keys and directory instances given to {@link #start} (with these, + * T1 cannot newly apply; it is re-checked only as defence in depth);
  2. + *
  3. authenticates every post of the window under its sender's roster key, and drops those + * that fail. Nothing is de-duplicated before authentication, so a copy posted under + * another author cannot shadow the genuine post;
  4. + *
  5. delivers every threshold-profile broadcast to the participant;
  6. + *
  7. opens every envelope addressed to it, submitting each accepted {@code SHARE} + * through {@link DkgParticipant#receivePrivate}. Byte-identical copies are counted once + * by the participant;
  8. + *
  9. only then closes round 1, returning the round-2 complaints.
  10. + *
+ * Before the first post it runs a seal-and-open self-test of the platform's primitives with + * the participant's own keys. + * + *

The delivery keys are destroyed once round 1 is closed, or when the participant aborts + * (T1, or an abort while closing round 1) (spec §7). If anything else throws (the + * application's verifier, the self-test, a platform fault while opening, or an unexpected + * failure closing the round), the keys are kept and the call can be retried; while the + * participant is still at round 1 it stays there. A retry must pass the identical final + * window: deliveries from the interrupted pass stay with the participant, which counts + * byte-identical repeats once. This is enforced. The first call that reaches delivery binds + * the participant to the window's digest ({@link #windowDigest}: every post's message and + * authenticator bytes, in the given order, repeats included). A later call with any other + * window is refused before anything changes. Binding checks only that a retry repeats the + * first window. It is no evidence that the window is final or complete, or that other + * participants saw the same one: those stay the application's (P1, P2). An application that + * abandons the attempt instead calls {@link DkgShareDeliveryKeys#destroy()}. The participant + * can close round 1 in no other way. + * + *

An envelope that fails because of its content (spec §4.2 steps 1–6) is silently absence + * (ADR-0054 I4). A failure of the platform's primitives is never absence: it fails closed as + * above, since treating it as absence would turn honest dealers' shares into complaints, and + * so into public answers (review Z-1). + * + * @param finalRound1Window every board post of the round-1 window, after the cutoff and + * finality: threshold-profile messages, envelopes and anything else + * @throws IllegalStateException if {@code participant} was not started with + * {@link #start} or is not at round 1, the keys were + * destroyed, or the platform's primitives failed + * @throws IllegalArgumentException if the participant, directory and keys disagree, or + * are not the instances given to {@link #start}, or a + * retry's window differs from the bound one + * @throws FaultAssumptionViolatedException if the participant aborts while closing round 1 + */ + public static List closeRound1(DkgParticipant participant, DkgKeyDirectory directory, + DkgShareDeliveryKeys keys, + List finalRound1Window, + DkgAdmissionVerifier verifier) { + Objects.requireNonNull(participant, "participant"); + Objects.requireNonNull(directory, "directory"); + Objects.requireNonNull(keys, "keys"); + Objects.requireNonNull(finalRound1Window, "finalRound1Window"); + Objects.requireNonNull(verifier, "verifier"); + if (!participant.boundToEncryptedDelivery()) { + throw new IllegalStateException("start the participant with DkgShareDelivery.start"); + } + if (participant.openRound() != 1) { + throw new IllegalStateException("closeRound1 needs a participant at round 1, got round " + participant.openRound()); + } + requireSameRun(participant, directory, keys); + if (!participant.boundTo(keys, directory)) { + // The directory decides which envelopes exist for this participant, and the keys which + // open. Substituting either after start would turn genuine shares into absences, and so + // into complaints (review C-1). + throw new IllegalArgumentException("closeRound1 needs the same keys and directory instances given to start"); + } + // One snapshot for the digest and the deliveries, so a list changed meanwhile cannot split them. + List window = List.copyOf(finalRound1Window); + byte[] windowDigest = windowDigest(window); + if (!participant.round1WindowMatches(windowDigest)) { + // An interrupted pass may already have delivered from the bound window. Another + // window would mix two views of round 1 (external review of 914b68c, item 2). + throw new IllegalArgumentException("a retry of closeRound1 needs the identical round-1 window"); + } + try { + directory.requireOwn(keys); + } catch (FaultAssumptionViolatedException t1) { + participant.abortWith(t1); + keys.destroy(); + throw t1; + } + DkgConfig config = participant.config(); + byte[] skR = keys.secretFor(config); + byte[] pkR = keys.publicKey(); + try { + PrivateKey recipient = X25519Bytes.privateKey(skR); + selfTest(recipient, pkR); + participant.bindRound1Window(windowDigest); + for (AuthenticatedDkgMessage post : window) { + deliver(config, post.message(), post.authenticator(), recipient, pkR, participant, verifier); + } + } catch (GeneralSecurityException e) { + throw new IllegalStateException("X25519 is unavailable", e); + } finally { + Arrays.fill(skR, (byte) 0); + } + // Every envelope is processed. An exception above (from the application's verifier or a + // platform fault) leaves the keys, and the participant at round 1, so closeRound1 can be + // retried with the same window. The keys go once the round is closed or the participant + // aborts (spec §7); any other failure keeps them for a retry (review Z-4). + List complaints; + try { + complaints = participant.closeRoundOneAfterDelivery(); + } catch (FaultAssumptionViolatedException abort) { + keys.destroy(); + throw abort; + } + keys.destroy(); + return complaints; + } + + private static final byte[] WINDOW_TAG = Hpke.ascii("zeroj.dkg-share-delivery-hpke.v1.round1-window"); + + /** + * SHA-256 over a round-1 window, which binds {@link #closeRound1} retries; local only, never + * posted. The input is {@code WINDOW_TAG ‖ u32(count)} followed, for every post in the given + * order, by {@code u32(|message|) ‖ message ‖ u32(|authenticator|) ‖ authenticator}, with + * big-endian lengths. Each field is length-prefixed, so the framing is unambiguous. Order is + * significant and repeats count, so reordering, adding, removing or repeating a post changes + * the digest. + */ + static byte[] windowDigest(List window) { + MessageDigest sha256; + try { + sha256 = MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is unavailable", e); + } + sha256.update(WINDOW_TAG); + ByteBuffer length = ByteBuffer.allocate(Integer.BYTES); + sha256.update(length.putInt(0, window.size()).array()); + for (AuthenticatedDkgMessage post : window) { + byte[] message = post.message(); + byte[] authenticator = post.authenticator(); + sha256.update(length.putInt(0, message.length).array()); + sha256.update(message); + sha256.update(length.putInt(0, authenticator.length).array()); + sha256.update(authenticator); + } + return sha256.digest(); + } + + private static void requireSameRun(DkgParticipant participant, DkgKeyDirectory directory, DkgShareDeliveryKeys keys) { + DkgConfig config = participant.config(); + if (!config.equals(directory.config()) || !config.equals(keys.config())) { + throw new IllegalArgumentException("the participant, directory and keys belong to different sessions"); + } + if (participant.id() != keys.id()) { + throw new IllegalArgumentException("the delivery keys belong to participant " + keys.id() + + ", not " + participant.id()); + } + } + + /** One round-1 post: authenticated first, then routed as an envelope or a broadcast. */ + private static void deliver(DkgConfig config, byte[] bytes, byte[] authenticator, PrivateKey recipient, byte[] pkR, + DkgParticipant participant, DkgAdmissionVerifier verifier) { + DkgShareDeliveryCodec.Envelope envelope = DkgShareDeliveryCodec.decodeEnvelope(config, bytes); + if (envelope != null) { + if (envelope.recipient() != participant.id()) return; + int i = envelope.sender(); + if (!verifier.authenticate(i, config.rosterKey(i), bytes.clone(), authenticator)) return; // step 3 + open(config, envelope, recipient, pkR, participant); + return; + } + DkgMessage m; + try { + m = DkgMessage.decode(config, bytes); + } catch (IllegalArgumentException malformed) { + return; // not a message of either profile + } + if (!verifier.authenticate(m.sender(), config.rosterKey(m.sender()), bytes.clone(), authenticator)) return; + try { + participant.receiveBroadcast(m.sender(), bytes); + } catch (IllegalArgumentException refused) { + // another round, a SHARE on the board, or otherwise refused: absent + } + } + + /** + * Spec §4.2 steps 5 and 6; a failure caused by the envelope is absence. A platform fault + * ({@link IllegalStateException} from {@link Hpke}) propagates and fails closed. + */ + private static void open(DkgConfig config, DkgShareDeliveryCodec.Envelope envelope, PrivateKey recipient, byte[] pkR, + DkgParticipant participant) { + int i = envelope.sender(); + byte[] pt; + try { + pt = Hpke.openBase(envelope.enc(), recipient, pkR, DkgShareDeliveryCodec.info(config, i, envelope.recipient()), + new byte[0], envelope.ct()); + } catch (Hpke.HpkeException absent) { + return; + } + try { + participant.receivePrivate(i, pt); // checks: SHARE of this session, sender i, subject j + } catch (IllegalArgumentException absent) { + // not a valid SHARE from i to this participant: absent + } finally { + Arrays.fill(pt, (byte) 0); + } + } +} diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryCodec.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryCodec.java new file mode 100644 index 00000000..fd015bff --- /dev/null +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryCodec.java @@ -0,0 +1,88 @@ +package org.zeroj.circuit.lib.jubjub; + +import java.util.Arrays; + +/** + * The byte formats of {@code dkg-share-delivery-hpke-v1} (spec §3.1, §4.1): announcements, + * envelopes and the HPKE {@code info}. Decoding returns {@code null} for anything that is not + * well-formed; the profile treats every such message as absent. + */ +final class DkgShareDeliveryCodec { + + static final byte[] TAG_A = Hpke.ascii("zeroj.dkg-share-delivery-hpke.v1.announce"); + static final byte[] TAG_E = Hpke.ascii("zeroj.dkg-share-delivery-hpke.v1.envelope"); + static final byte[] TAG_I = Hpke.ascii("zeroj.dkg-share-delivery-hpke.v1.info"); + + static final int ANNOUNCE_LENGTH = TAG_A.length + 32 + 1 + 32; // 106 + static final int SHARE_LENGTH = 100; // threshold spec §4 + static final int CT_LENGTH = SHARE_LENGTH + Hpke.N_T; // 116 + static final int ENVELOPE_LENGTH = TAG_E.length + 32 + 2 + Hpke.N_ENC + CT_LENGTH; // 223 + + private DkgShareDeliveryCodec() { + } + + /** A decoded announcement: participant {@code j} and its key {@code pkR}. */ + record Announcement(int participant, byte[] publicKey) { + } + + /** A decoded envelope header and body. */ + record Envelope(int sender, int recipient, byte[] enc, byte[] ct) { + } + + static byte[] announcement(DkgConfig config, int j, byte[] publicKey) { + return Hpke.concat(TAG_A, config.sessionRef(), new byte[]{(byte) j}, publicKey); + } + + /** + * The participant an announcement names if its length, tag, session and identifier are + * well-formed (spec §3.1, without the key checks), or {@code 0}. Cheap: no X25519. + */ + static int announcedParticipant(DkgConfig config, byte[] bytes) { + if (bytes == null || bytes.length != ANNOUNCE_LENGTH || !startsWith(bytes, TAG_A)) return 0; + int at = TAG_A.length; + if (!Arrays.equals(bytes, at, at + 32, config.sessionRef(), 0, 32)) return 0; + int j = bytes[at + 32] & 0xFF; + return j >= 1 && j <= config.n() ? j : 0; + } + + /** Spec §3.1: well-formed for this session, or {@code null}. Authentication is the caller's. */ + static Announcement decodeAnnouncement(DkgConfig config, byte[] bytes) { + if (bytes == null || bytes.length != ANNOUNCE_LENGTH || !startsWith(bytes, TAG_A)) return null; + int at = TAG_A.length; + if (!Arrays.equals(bytes, at, at + 32, config.sessionRef(), 0, 32)) return null; + int j = bytes[at + 32] & 0xFF; + if (j < 1 || j > config.n()) return null; + byte[] pk = Arrays.copyOfRange(bytes, at + 33, at + 65); + if (!X25519Bytes.isCanonical(pk) || !X25519Bytes.passesSmallOrderProbe(pk)) return null; + return new Announcement(j, pk); + } + + static byte[] info(DkgConfig config, int sender, int recipient) { + return Hpke.concat(TAG_I, config.sessionRef(), new byte[]{(byte) sender, (byte) recipient}); + } + + static byte[] envelope(DkgConfig config, int sender, int recipient, byte[] enc, byte[] ct) { + return Hpke.concat(TAG_E, config.sessionRef(), new byte[]{(byte) sender, (byte) recipient}, enc, ct); + } + + /** + * Spec §4.2 steps 1, 2 and 4: length, tag, session, identifiers and a canonical {@code enc}; + * or {@code null}. Authentication (step 3) and opening (steps 5–6) are the caller's. + */ + static Envelope decodeEnvelope(DkgConfig config, byte[] bytes) { + if (bytes == null || bytes.length != ENVELOPE_LENGTH || !startsWith(bytes, TAG_E)) return null; + int at = TAG_E.length; + if (!Arrays.equals(bytes, at, at + 32, config.sessionRef(), 0, 32)) return null; + int i = bytes[at + 32] & 0xFF; + int j = bytes[at + 33] & 0xFF; + if (i < 1 || i > config.n() || j < 1 || j > config.n() || i == j) return null; + byte[] enc = Arrays.copyOfRange(bytes, at + 34, at + 34 + Hpke.N_ENC); + if (!X25519Bytes.isCanonical(enc)) return null; + byte[] ct = Arrays.copyOfRange(bytes, at + 34 + Hpke.N_ENC, bytes.length); + return new Envelope(i, j, enc, ct); + } + + private static boolean startsWith(byte[] bytes, byte[] prefix) { + return Arrays.equals(bytes, 0, prefix.length, prefix, 0, prefix.length); + } +} diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryKeys.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryKeys.java new file mode 100644 index 00000000..1035cd3e --- /dev/null +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryKeys.java @@ -0,0 +1,114 @@ +package org.zeroj.circuit.lib.jubjub; + +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Objects; + +/** + * One participant's encryption key pair for one key-generation attempt + * ({@code dkg-share-delivery-hpke-v1} §2.3, §7; ADR-0054 D5). + * + *

    + *
  • Per attempt. The pair is bound to the session it was generated for. It refuses + * to open envelopes of any other session.
  • + *
  • Separate. It is never the roster authentication key and is not derived from + * it.
  • + *
  • Destroyable. {@link #destroy()} wipes the private key, and opening is refused + * afterwards. {@link DkgShareDelivery#closeRound1} destroys it once round 1 is processed. + * Java cannot guarantee erasure, so this is best effort: compatibility/offline class + * (ADR-0039 §3.1). Copies outside this class's control include the provider's + * {@code XECPrivateKey} built for each {@code closeRound1}, the HKDF and AEAD + * {@code SecretKeySpec}s, and the JDK {@code KDF} and {@code Cipher} internals; on JDK 25 + * their {@code destroy()} is not supported.
  • + *
+ */ +public final class DkgShareDeliveryKeys { + + private final DkgConfig config; + private final int id; + private final byte[] secret; + private final byte[] publicKey; + private boolean destroyed; + + private DkgShareDeliveryKeys(DkgConfig config, int id, byte[] secret, byte[] publicKey) { + this.config = config; + this.id = id; + this.secret = secret; + this.publicKey = publicKey; + } + + /** A fresh key pair for participant {@code id} of this configuration's session. */ + public static DkgShareDeliveryKeys generate(DkgConfig config, int id, SecureRandom random) { + Objects.requireNonNull(random, "random"); + byte[] secret = new byte[Hpke.N_SK]; + random.nextBytes(secret); + try { + return fromSecret(config, id, secret); + } finally { + Arrays.fill(secret, (byte) 0); // fromSecret keeps its own copy + } + } + + /** Test seam: a key pair from a given private key (spec §9.1 test keys). */ + static DkgShareDeliveryKeys fromSecret(DkgConfig config, int id, byte[] secret) { + Objects.requireNonNull(config, "config"); + config.requireParticipant(id); + if (secret == null || secret.length != Hpke.N_SK) { + throw new IllegalArgumentException("an X25519 private key is 32 bytes"); + } + try { + return new DkgShareDeliveryKeys(config, id, secret.clone(), X25519Bytes.publicFromPrivate(secret)); + } catch (GeneralSecurityException e) { + throw new IllegalStateException("X25519 is unavailable", e); + } + } + + /** The participant this pair belongs to. */ + public int id() { + return id; + } + + /** The configuration, and so the session, this pair is bound to. */ + public DkgConfig config() { + return config; + } + + /** {@code pkR}, 32 bytes. */ + public byte[] publicKey() { + return publicKey.clone(); + } + + /** The round-0 announcement to post, authenticated under the roster key (spec §3.1). */ + public byte[] announcement() { + return DkgShareDeliveryCodec.announcement(config, id, publicKey); + } + + /** Wipes the private key; opening is refused afterwards. Idempotent. */ + public synchronized void destroy() { + Arrays.fill(secret, (byte) 0); + destroyed = true; + } + + /** {@code true} once {@link #destroy()} has run. */ + public synchronized boolean isDestroyed() { + return destroyed; + } + + /** The private key for opening under {@code session}, or an exception if refused. */ + synchronized byte[] secretFor(DkgConfig session) { + if (destroyed) { + throw new IllegalStateException("the delivery keys have been destroyed"); + } + if (!config.equals(session)) { + throw new IllegalArgumentException("the delivery keys belong to another session"); + } + return secret.clone(); + } + + @Override + public String toString() { + return "DkgShareDeliveryKeys{id=" + id + ", session=" + config + ", secret=" + + (destroyed ? ", destroyed" : "") + "}"; + } +} diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/FaultAssumptionViolatedException.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/FaultAssumptionViolatedException.java index 62155599..4a1b864c 100644 --- a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/FaultAssumptionViolatedException.java +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/FaultAssumptionViolatedException.java @@ -29,7 +29,13 @@ public enum Reason { /** A8: this participant's own dealing was marked for reconstruction. */ OWN_DEALING_MARKED, /** A9: this participant's own complaint is missing from its delivered round-2 set. */ - OWN_COMPLAINT_MISSING + OWN_COMPLAINT_MISSING, + /** + * T1 ({@code dkg-share-delivery-hpke-v1} §3.3, ADR-0054 D4): the directory holds no key + * for this participant (its announcement is missing, malformed, unauthenticated or in + * conflict) or a key other than its own, so it aborts before round 1. + */ + OWN_KEY_ANNOUNCEMENT_MISSING } private final Reason reason; diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/Hpke.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/Hpke.java new file mode 100644 index 00000000..559368bc --- /dev/null +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/Hpke.java @@ -0,0 +1,447 @@ +package org.zeroj.circuit.lib.jubjub; + +import javax.crypto.AEADBadTagException; +import javax.crypto.Cipher; +import javax.crypto.KDF; +import javax.crypto.spec.HKDFParameterSpec; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Objects; + +/** + * HPKE [RFC 9180] in Base mode for the single suite of {@code dkg-share-delivery-hpke-v1} + * (ADR-0054 D1): DHKEM(X25519, HKDF-SHA256) {@code 0x0020}, HKDF-SHA256 {@code 0x0001}, + * ChaCha20Poly1305 {@code 0x0003}. Assembled from the RFC text on JDK primitives + * ({@code javax.crypto.KDF}, SunEC X25519, SunJCE ChaCha20-Poly1305) through algorithm-only + * lookups (see {@link X25519Bytes} on providers). + * + *

Production code uses only single-shot SealBase and OpenBase (§6.1), at sequence number 0: + * {@link #sealBaseWithEphemeral} with an ephemeral key the caller drew from a {@code SecureRandom} + * (or {@link #sealBase}, which draws it), and {@link #openBase}. {@link Context#setSequence} exists + * so that the RFC 9180 Appendix A.2.1 known-answer tests can exercise every listed sequence + * number, and {@link #deriveKeyPair} and {@link #setupBaseSWithEphemeral} are test seams. The + * export interface is not provided. + * + *

Failures. A failure caused by the input is an {@link HpkeException}: a small-order + * {@code enc} or {@code pkR} (RFC 9180 §7.1.4, RFC 7748 §6.1), a wrong length, an AEAD + * authentication failure, or the message limit. Any other failure of the underlying primitives + * (a missing or failing provider) is an {@link IllegalStateException}: it says nothing about the + * input, and callers must not treat it as one (review Z-1). + * + *

Secret. Private keys, shared secrets and AEAD keys are compatibility/offline class + * (ADR-0039 §3.1). Intermediate arrays are wiped on a best-effort basis. + */ +final class Hpke { + + static final int KEM_ID = 0x0020; + static final int KDF_ID = 0x0001; + static final int AEAD_ID = 0x0003; + static final int N_SECRET = 32; + static final int N_ENC = 32; + static final int N_PK = 32; + static final int N_SK = 32; + static final int N_K = 32; + static final int N_N = 12; + static final int N_T = 16; + static final int N_H = 32; + private static final byte MODE_BASE = 0x00; + + private static final byte[] HPKE_V1 = ascii("HPKE-v1"); + /** {@code "KEM" ‖ I2OSP(kem_id, 2)} (§4.1). */ + private static final byte[] KEM_SUITE_ID = concat(ascii("KEM"), i2osp(KEM_ID, 2)); + /** {@code "HPKE" ‖ I2OSP(kem_id, 2) ‖ I2OSP(kdf_id, 2) ‖ I2OSP(aead_id, 2)} (§5.1). */ + private static final byte[] HPKE_SUITE_ID = concat(ascii("HPKE"), i2osp(KEM_ID, 2), i2osp(KDF_ID, 2), i2osp(AEAD_ID, 2)); + private static final byte[] EMPTY = new byte[0]; + + private Hpke() { + } + + /** + * An HPKE failure caused by the input (see the class documentation). The message is generic on + * purpose; callers treat it as absence. + */ + static final class HpkeException extends Exception { + HpkeException(Throwable cause) { + super("HPKE operation failed", cause); + } + } + + /** + * Classifies a failure of the primitives: an {@link HpkeException} if the input caused it, + * otherwise an {@link IllegalStateException} thrown from here. + */ + private static HpkeException inputFailure(Exception e) { + if (e instanceof X25519Bytes.SmallOrderException || e instanceof AEADBadTagException) { + return new HpkeException(e); + } + throw new IllegalStateException("HPKE primitive failure (a platform fault, not a property of the input)", e); + } + + private static void wipe(byte[] b) { + if (b != null) Arrays.fill(b, (byte) 0); + } + + /** The output of {@link #sealBase}: the encapsulation and the ciphertext. */ + record Sealed(byte[] enc, byte[] ct) { + } + + // ---------------------------------------------------------------- single-shot (§6.1) + + /** {@code SealBase(pkR, info, aad, pt)} with a fresh ephemeral key from {@code random}. */ + static Sealed sealBase(byte[] pkR, byte[] info, byte[] aad, byte[] pt, SecureRandom random) throws HpkeException { + Objects.requireNonNull(random, "random"); + byte[] skE = new byte[N_SK]; + random.nextBytes(skE); + try { + return sealBaseWithEphemeral(skE, pkR, info, aad, pt); + } finally { + Arrays.fill(skE, (byte) 0); + } + } + + /** Test seam: {@link #sealBase} with a given ephemeral private key. */ + static Sealed sealBaseWithEphemeral(byte[] skE, byte[] pkR, byte[] info, byte[] aad, byte[] pt) throws HpkeException { + Objects.requireNonNull(pkR, "pkR"); + Objects.requireNonNull(info, "info"); + Objects.requireNonNull(aad, "aad"); + Objects.requireNonNull(pt, "pt"); + if (pkR.length != N_PK) { + throw new HpkeException(new IllegalArgumentException("pkR must be " + N_PK + " bytes")); + } + byte[] dh = null; + byte[] sharedSecret = null; + try { + byte[] enc = X25519Bytes.publicFromPrivate(skE); + dh = X25519Bytes.dh(X25519Bytes.privateKey(skE), pkR); + sharedSecret = extractAndExpand(dh, concat(enc, pkR)); + Context context = keySchedule(sharedSecret, info); + try { + return new Sealed(enc, context.seal(aad, pt)); + } finally { + context.destroy(); + } + } catch (GeneralSecurityException | RuntimeException e) { + throw inputFailure(e); + } finally { + wipe(dh); + wipe(sharedSecret); + } + } + + /** {@code OpenBase(enc, skR, info, aad, ct)}. */ + static byte[] openBase(byte[] enc, byte[] skR, byte[] info, byte[] aad, byte[] ct) throws HpkeException { + return openBase(enc, skR, null, info, aad, ct); + } + + /** + * {@code OpenBase} with the recipient's serialized public key {@code pkRm} supplied, saving one + * X25519 operation. {@code pkR} must be {@code skR}'s public key; {@code null} recomputes it. + */ + static byte[] openBase(byte[] enc, byte[] skR, byte[] pkR, byte[] info, byte[] aad, byte[] ct) throws HpkeException { + Context context = setupBaseR(enc, skR, pkR, info); + try { + return context.open(aad, ct); + } finally { + context.destroy(); + } + } + + /** + * {@code OpenBase} with a provider private key built once by the caller and the recipient's + * serialized public key {@code pkRm}; used to open many envelopes to one recipient. + */ + static byte[] openBase(byte[] enc, PrivateKey skR, byte[] pkR, byte[] info, byte[] aad, byte[] ct) throws HpkeException { + Objects.requireNonNull(skR, "skR"); + Objects.requireNonNull(pkR, "pkR"); + Context context = setupBaseR(enc, skR, pkR, info); + try { + return context.open(aad, ct); + } finally { + context.destroy(); + } + } + + // ---------------------------------------------------------------- setup (§5.1.1) + + /** {@code SetupBaseR(enc, skR, info)}. */ + static Context setupBaseR(byte[] enc, byte[] skR, byte[] info) throws HpkeException { + return setupBaseR(enc, skR, null, info); + } + + private static Context setupBaseR(byte[] enc, byte[] skR, byte[] knownPkR, byte[] info) throws HpkeException { + Objects.requireNonNull(skR, "skR"); + byte[] pkR; + PrivateKey recipient; + try { + pkR = knownPkR != null ? knownPkR : X25519Bytes.publicFromPrivate(skR); + recipient = X25519Bytes.privateKey(skR); + } catch (GeneralSecurityException | RuntimeException e) { + throw inputFailure(e); + } + return setupBaseR(enc, recipient, pkR, info); + } + + private static Context setupBaseR(byte[] enc, PrivateKey recipient, byte[] pkR, byte[] info) throws HpkeException { + Objects.requireNonNull(enc, "enc"); + Objects.requireNonNull(info, "info"); + if (enc.length != N_ENC) { + throw new HpkeException(new IllegalArgumentException("enc must be " + N_ENC + " bytes")); + } + byte[] dh = null; + byte[] sharedSecret = null; + try { + dh = X25519Bytes.dh(recipient, enc); + sharedSecret = extractAndExpand(dh, concat(enc, pkR)); + return keySchedule(sharedSecret, info); + } catch (GeneralSecurityException | RuntimeException e) { + throw inputFailure(e); + } finally { + wipe(dh); + wipe(sharedSecret); + } + } + + /** {@code SetupBaseS(pkR, info)} with a given ephemeral key; returns {@code enc} too. Test seam. */ + static Context setupBaseSWithEphemeral(byte[] skE, byte[] pkR, byte[] info, byte[][] encOut) throws HpkeException { + byte[] dh = null; + byte[] sharedSecret = null; + try { + byte[] enc = X25519Bytes.publicFromPrivate(skE); + dh = X25519Bytes.dh(X25519Bytes.privateKey(skE), pkR); + sharedSecret = extractAndExpand(dh, concat(enc, pkR)); + encOut[0] = enc; + return keySchedule(sharedSecret, info); + } catch (GeneralSecurityException | RuntimeException e) { + throw inputFailure(e); + } finally { + wipe(dh); + wipe(sharedSecret); + } + } + + /** {@code DeriveKeyPair(ikm)} for X25519 (§7.1.3); returns {@code skR}. Test seam. */ + static byte[] deriveKeyPair(byte[] ikm) throws HpkeException { + byte[] dkpPrk = null; + try { + dkpPrk = labeledExtract(KEM_SUITE_ID, EMPTY, ascii("dkp_prk"), ikm); + return labeledExpand(KEM_SUITE_ID, dkpPrk, ascii("sk"), EMPTY, N_SK); + } catch (GeneralSecurityException e) { + throw new HpkeException(e); + } finally { + wipe(dkpPrk); + } + } + + // ---------------------------------------------------------------- key schedule (§5.1) + + /** + * The key schedule. Intermediate secrets are wiped on every path; {@code key} and + * {@code base_nonce} are wiped too unless they pass to the returned {@link Context}, whose + * {@code destroy()} is then the caller's (review F4). + */ + private static Context keySchedule(byte[] sharedSecret, byte[] info) throws GeneralSecurityException { + return keySchedule(JDK_HKDF, sharedSecret, info); + } + + /** {@link #keySchedule(byte[], byte[])} over a given HKDF; tests inject failures through it. */ + static Context keySchedule(Hkdf hkdf, byte[] sharedSecret, byte[] info) throws GeneralSecurityException { + byte[] pskIdHash = labeledExtract(hkdf, HPKE_SUITE_ID, EMPTY, ascii("psk_id_hash"), EMPTY); + byte[] infoHash = labeledExtract(hkdf, HPKE_SUITE_ID, EMPTY, ascii("info_hash"), info); + byte[] keyScheduleContext = concat(new byte[]{MODE_BASE}, pskIdHash, infoHash); + byte[] secret = null; + byte[] key = null; + byte[] baseNonce = null; + boolean transferred = false; + try { + secret = labeledExtract(hkdf, HPKE_SUITE_ID, sharedSecret, ascii("secret"), EMPTY); + key = labeledExpand(hkdf, HPKE_SUITE_ID, secret, ascii("key"), keyScheduleContext, N_K); + baseNonce = labeledExpand(hkdf, HPKE_SUITE_ID, secret, ascii("base_nonce"), keyScheduleContext, N_N); + Context context = new Context(key, baseNonce); + transferred = true; + return context; + } finally { + wipe(secret); + if (!transferred) { + wipe(key); + wipe(baseNonce); + } + } + } + + /** {@code ExtractAndExpand(dh, kem_context)} of DHKEM (§4.1). */ + private static byte[] extractAndExpand(byte[] dh, byte[] kemContext) throws GeneralSecurityException { + return extractAndExpand(JDK_HKDF, dh, kemContext); + } + + /** {@link #extractAndExpand(byte[], byte[])} over a given HKDF; tests inject failures through it. */ + static byte[] extractAndExpand(Hkdf hkdf, byte[] dh, byte[] kemContext) throws GeneralSecurityException { + byte[] eaePrk = null; + try { + eaePrk = labeledExtract(hkdf, KEM_SUITE_ID, EMPTY, ascii("eae_prk"), dh); + return labeledExpand(hkdf, KEM_SUITE_ID, eaePrk, ascii("shared_secret"), kemContext, N_SECRET); + } finally { + wipe(eaePrk); // on every path (review F4) + } + } + + // ---------------------------------------------------------------- labeled HKDF (§4) + + /** + * HKDF-SHA256 Extract and Expand (RFC 5869 §2.2, §2.3). Production uses {@link #JDK_HKDF} only; + * the interface lets tests fail a chosen derivation on any JDK (review F4). + */ + interface Hkdf { + byte[] extract(byte[] salt, byte[] ikm) throws GeneralSecurityException; + + byte[] expand(byte[] prk, byte[] info, int length) throws GeneralSecurityException; + } + + /** HKDF-SHA256 through {@code javax.crypto.KDF}, looked up by algorithm only (see {@link X25519Bytes}). */ + static final Hkdf JDK_HKDF = new Hkdf() { + @Override + public byte[] extract(byte[] salt, byte[] ikm) throws GeneralSecurityException { + HKDFParameterSpec.Builder builder = HKDFParameterSpec.ofExtract().addIKM(ikm); + if (salt.length > 0) { + builder.addSalt(salt); // an absent salt is HashLen zero bytes, as RFC 5869 §2.2 requires + } + return KDF.getInstance("HKDF-SHA256").deriveData(builder.extractOnly()); + } + + @Override + public byte[] expand(byte[] prk, byte[] info, int length) throws GeneralSecurityException { + return KDF.getInstance("HKDF-SHA256") + .deriveData(HKDFParameterSpec.expandOnly(new SecretKeySpec(prk, "HKDF-PRK"), info, length)); + } + }; + + /** {@code LabeledExtract(salt, label, ikm) = Extract(salt, "HPKE-v1" ‖ suite_id ‖ label ‖ ikm)}. */ + static byte[] labeledExtract(byte[] suiteId, byte[] salt, byte[] label, byte[] ikm) throws GeneralSecurityException { + return labeledExtract(JDK_HKDF, suiteId, salt, label, ikm); + } + + private static byte[] labeledExtract(Hkdf hkdf, byte[] suiteId, byte[] salt, byte[] label, byte[] ikm) + throws GeneralSecurityException { + byte[] labeledIkm = concat(HPKE_V1, suiteId, label, ikm); + try { + return hkdf.extract(salt, labeledIkm); + } finally { + Arrays.fill(labeledIkm, (byte) 0); + } + } + + /** {@code LabeledExpand(prk, label, info, L) = Expand(prk, I2OSP(L, 2) ‖ "HPKE-v1" ‖ suite_id ‖ label ‖ info, L)}. */ + static byte[] labeledExpand(byte[] suiteId, byte[] prk, byte[] label, byte[] info, int length) throws GeneralSecurityException { + return labeledExpand(JDK_HKDF, suiteId, prk, label, info, length); + } + + private static byte[] labeledExpand(Hkdf hkdf, byte[] suiteId, byte[] prk, byte[] label, byte[] info, int length) + throws GeneralSecurityException { + return hkdf.expand(prk, concat(i2osp(length, 2), HPKE_V1, suiteId, label, info), length); + } + + static byte[] kemSuiteId() { + return KEM_SUITE_ID.clone(); + } + + static byte[] hpkeSuiteId() { + return HPKE_SUITE_ID.clone(); + } + + // ---------------------------------------------------------------- context (§5.2) + + /** + * An encryption context: {@code key}, {@code base_nonce} and a sequence number. Single-shot use + * calls one operation at sequence 0. Not thread-safe. + */ + static final class Context { + private final byte[] key; + private final byte[] baseNonce; + private long seq; + + private Context(byte[] key, byte[] baseNonce) { + this.key = key; + this.baseNonce = baseNonce; + } + + byte[] key() { + return key.clone(); + } + + byte[] baseNonce() { + return baseNonce.clone(); + } + + /** Test seam: jump to a sequence number (§5.2's nonce is {@code base_nonce XOR I2OSP(seq, Nn)}). */ + void setSequence(long sequence) { + if (sequence < 0) throw new IllegalArgumentException("sequence must be non-negative"); + this.seq = sequence; + } + + byte[] seal(byte[] aad, byte[] pt) throws GeneralSecurityException { + byte[] out = aead(Cipher.ENCRYPT_MODE, aad, pt); + seq++; + return out; + } + + byte[] open(byte[] aad, byte[] ct) throws HpkeException { + Objects.requireNonNull(aad, "aad"); + Objects.requireNonNull(ct, "ct"); + if (seq == Long.MAX_VALUE) { + throw new HpkeException(new GeneralSecurityException("message limit reached")); + } + try { + byte[] out = aead(Cipher.DECRYPT_MODE, aad, ct); + seq++; + return out; + } catch (GeneralSecurityException | RuntimeException e) { + throw inputFailure(e); + } + } + + private byte[] aead(int mode, byte[] aad, byte[] input) throws GeneralSecurityException { + Objects.requireNonNull(aad, "aad"); + Objects.requireNonNull(input, "input"); + if (seq == Long.MAX_VALUE) { + throw new GeneralSecurityException("message limit reached"); // far below 2^(8·Nn) − 1 + } + byte[] nonce = baseNonce.clone(); + byte[] seqBytes = i2osp(seq, N_N); + for (int i = 0; i < N_N; i++) nonce[i] ^= seqBytes[i]; + Cipher cipher = Cipher.getInstance("ChaCha20-Poly1305"); + cipher.init(mode, new SecretKeySpec(key, "ChaCha20"), new IvParameterSpec(nonce)); + if (aad.length > 0) cipher.updateAAD(aad); + return cipher.doFinal(input); + } + + void destroy() { + Arrays.fill(key, (byte) 0); + Arrays.fill(baseNonce, (byte) 0); + } + } + + // ---------------------------------------------------------------- encoding helpers + + static byte[] i2osp(long value, int length) { + byte[] out = new byte[length]; + for (int i = length - 1, shift = 0; i >= 0 && shift < 64; i--, shift += 8) { + out[i] = (byte) (value >>> shift); + } + return out; + } + + static byte[] ascii(String s) { + return s.getBytes(StandardCharsets.US_ASCII); + } + + static byte[] concat(byte[]... parts) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (byte[] part : parts) out.writeBytes(part); + return out.toByteArray(); + } +} diff --git a/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/X25519Bytes.java b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/X25519Bytes.java new file mode 100644 index 00000000..6b2004fb --- /dev/null +++ b/zeroj-circuit-lib/src/main/java/org/zeroj/circuit/lib/jubjub/X25519Bytes.java @@ -0,0 +1,187 @@ +package org.zeroj.circuit.lib.jubjub; + +import javax.crypto.KeyAgreement; +import java.math.BigInteger; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.spec.NamedParameterSpec; +import java.security.spec.XECPrivateKeySpec; +import java.security.spec.XECPublicKeySpec; +import java.util.Objects; +import java.util.Set; + +/** + * X25519 on 32-byte strings, with the decoding done here rather than by a provider + * ([RFC 7748] §5; ADR-0054 D8, I10). + * + *

Two decodings exist on purpose: + *

    + *
  • {@link #decodeUCoordinate} is RFC 7748's function decoding: mask bit 255, then reduce + * mod {@code p}. HPKE (RFC 9180) uses it, so any 32-byte value is accepted as the function + * requires.
  • + *
  • {@link #isCanonical} is the {@code dkg-share-delivery-hpke-v1} message rule (spec §2.1): + * bit 255 clear and {@code u < p}. Profile messages refuse anything else before X25519 is + * called.
  • + *
+ * Every shared secret is checked against the all-zero value here, independently of the + * provider (RFC 9180 §7.1.4). + * + *

Input refusals versus faults. A small-order input is the only way the input can make + * {@link #dh} fail. It is decided here, before the provider is called, against the five canonical + * small-order u-coordinates, and reported as {@link SmallOrderException}; the all-zero check + * stays as defence in depth. Every exception from the provider is then a fault of the platform, + * and callers must not treat it as a property of the input. The decision therefore does not + * depend on how a provider reports small order (reviews Z-1, R2-1). + * + *

Providers. Lookups name the algorithm only, so the highest-priority provider serves + * them: {@code SunEC} on a standard JDK. Naming the provider would break native images, which + * register a provider only when an algorithm-only lookup reaches it. An application that prefers + * a third-party provider (for example BouncyCastle) gets that provider's X25519; small order is + * still decided here, so the outcome does not change (review R2-1). + * + *

Secret. Private scalars are compatibility/offline class (ADR-0039 §3.1). The DH + * itself is the JDK provider's (SunEC); no constant-time claim is made for this class. + */ +final class X25519Bytes { + + /** {@code p = 2^255 − 19}. */ + static final BigInteger P = BigInteger.ONE.shiftLeft(255).subtract(BigInteger.valueOf(19)); + + /** The RFC 7748 base point, {@code u = 9}. */ + static final byte[] BASE_POINT = littleEndian(BigInteger.valueOf(9)); + + /** The small-order probe scalar of spec §2.2: {@code 0x09 ‖ 0^31}. */ + static final byte[] PROBE = BASE_POINT.clone(); + + /** + * The u-coordinates, reduced mod {@code p}, of the points of order dividing 8 on Curve25519 + * and its twist: {@code 0}, {@code 1}, {@code p − 1} and the two order-8 points. A clamped + * scalar is {@code 8k'} with {@code 2^251 ≤ k' < 2^252}, below both large prime orders, so + * {@code X25519(k, u) = 0^32} exactly for these {@code u} (spec §2.2). The set equals the + * public values of every all-zero case in Wycheproof {@code x25519_test.json} + * ({@code HpkeKnownAnswerTest.smallOrderSetMatchesWycheproof}). + */ + private static final Set SMALL_ORDER = Set.of( + BigInteger.ZERO, + BigInteger.ONE, + P.subtract(BigInteger.ONE), + new BigInteger("325606250916557431795983626356110631294008115727848805560023387167927233504"), + new BigInteger("39382357235489614581723060781553021112529911719440698176882885853963445705823")); + + private X25519Bytes() { + } + + /** {@code X25519(k, u)} refused because {@code u} has small order: a property of the input. */ + static final class SmallOrderException extends GeneralSecurityException { + SmallOrderException(String message, Throwable cause) { + super(message, cause); + } + } + + /** Spec §2.1: exactly 32 bytes, bit 255 clear and {@code u < p}. */ + static boolean isCanonical(byte[] b) { + if (b == null || b.length != 32 || (b[31] & 0x80) != 0) { + return false; + } + return littleEndianToInteger(b).compareTo(P) < 0; + } + + /** RFC 7748 §5 {@code decodeUCoordinate}: masks bit 255, then reduces mod {@code p}. */ + static BigInteger decodeUCoordinate(byte[] b) { + if (b == null || b.length != 32) { + throw new IllegalArgumentException("an X25519 value is 32 bytes"); + } + byte[] masked = b.clone(); + masked[31] &= 0x7F; + return littleEndianToInteger(masked).mod(P); + } + + /** The provider public key for a 32-byte u-coordinate, decoded per RFC 7748 §5. */ + static PublicKey publicKey(byte[] b) throws GeneralSecurityException { + return keyFactory() + .generatePublic(new XECPublicKeySpec(NamedParameterSpec.X25519, decodeUCoordinate(b))); + } + + /** The provider private key for a 32-byte scalar (clamped by X25519 itself). */ + static PrivateKey privateKey(byte[] scalar) throws GeneralSecurityException { + if (scalar == null || scalar.length != 32) { + throw new IllegalArgumentException("an X25519 private key is 32 bytes"); + } + return keyFactory().generatePrivate(new XECPrivateKeySpec(NamedParameterSpec.X25519, scalar)); + } + + /** + * {@code X25519(scalar, u)}, refusing an all-zero result (RFC 9180 §7.1.4, RFC 7748 §6.1). + * + * @throws SmallOrderException if {@code u} has small order (decided before the provider + * is called), or the provider returned the all-zero value + * @throws GeneralSecurityException any other failure, which is a fault of the platform + */ + static byte[] dh(PrivateKey scalar, byte[] u) throws GeneralSecurityException { + Objects.requireNonNull(scalar, "scalar"); + if (isSmallOrder(u)) { + throw new SmallOrderException("small-order X25519 input", null); + } + PublicKey point = publicKey(u); + KeyAgreement agreement = KeyAgreement.getInstance("X25519"); + agreement.init(scalar); + agreement.doPhase(point, true); + byte[] shared = agreement.generateSecret(); + if (isAllZero(shared)) { + throw new SmallOrderException("all-zero X25519 output", null); + } + return shared; + } + + /** {@code X25519(scalar, 9)}: the public key of a private scalar. */ + static byte[] publicFromPrivate(byte[] scalar) throws GeneralSecurityException { + return dh(privateKey(scalar), BASE_POINT); + } + + /** + * Spec §2.2: {@code X25519(PROBE, u) ≠ 0^32}, i.e. {@code u} is not of small order. + * + * @throws IllegalStateException if X25519 fails for any other reason (a platform fault, never + * reported as a property of {@code u}) + */ + static boolean passesSmallOrderProbe(byte[] u) { + try { + dh(privateKey(PROBE), u); + return true; + } catch (SmallOrderException smallOrder) { + return false; + } catch (GeneralSecurityException fault) { + throw new IllegalStateException("X25519 is unavailable", fault); + } + } + + private static KeyFactory keyFactory() throws GeneralSecurityException { + return KeyFactory.getInstance("XDH"); + } + + /** {@code true} iff {@code u}, decoded per RFC 7748 §5, is a small-order u-coordinate. */ + static boolean isSmallOrder(byte[] u) { + return SMALL_ORDER.contains(decodeUCoordinate(u)); + } + + static boolean isAllZero(byte[] b) { + int acc = 0; + for (byte x : b) acc |= x; + return acc == 0; + } + + private static BigInteger littleEndianToInteger(byte[] b) { + byte[] be = new byte[b.length]; + for (int i = 0; i < b.length; i++) be[i] = b[b.length - 1 - i]; + return new BigInteger(1, be); + } + + static byte[] littleEndian(BigInteger u) { + byte[] out = new byte[32]; + byte[] be = u.toByteArray(); + for (int i = 0; i < be.length && i < 32; i++) out[i] = be[be.length - 1 - i]; + return out; + } +} diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/DkgEncryptedHarness.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/DkgEncryptedHarness.java new file mode 100644 index 00000000..95924654 --- /dev/null +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/DkgEncryptedHarness.java @@ -0,0 +1,363 @@ +package org.zeroj.circuit.lib.jubjub; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.Security; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A board with windows for {@code dkg-share-delivery-hpke-v1} tests (ADR-0054 M2). Round 0 + * carries announcements, round 1 carries envelopes and {@code COMMITMENTS}, and rounds 2–7 are + * the threshold profile's. Every post carries an authenticator, a keyed hash under its author's + * roster key, which {@link #AUTH} checks under the claimed sender's roster key. Each participant + * reads the same final window per round (P2) and is started and closed through + * {@link DkgShareDelivery} (T1 and the barrier, P3), except participants that a test drives + * without the barrier as a negative control. + * + *

{@link Hooks} let a test script corrupt participants, front-running copies, and late or + * excluded posts. + */ +final class DkgEncryptedHarness { + + /** One board post, authenticated as {@code author}. */ + record Post(int author, byte[] bytes) { + } + + /** Test hooks. Every default is honest. */ + interface Hooks { + /** Round-0 posts for participant {@code j}'s announcement (drop, duplicate, replace). */ + default List announcement(int j, byte[] announcement) { + return List.of(announcement); + } + + /** Envelope posts for one sealed envelope (drop, duplicate, replace). */ + default List envelope(int i, int j, byte[] envelope) { + return List.of(envelope); + } + + /** {@code true} if this envelope misses the round-1 cutoff (it is posted, but too late). */ + default boolean missesCutoff(int i, int j) { + return false; + } + + /** Dealers that ignore D7a and post {@code COMMITMENTS} even when envelopes missed the cutoff. */ + default Set ignoreCommitmentsLast() { + return Set.of(); + } + + /** Rewrites a broadcast of rounds 1–7 into the posts that actually happen. */ + default List broadcast(DkgMessage m) { + return List.of(m.encode()); + } + + /** Posts placed at the front of a round's window, before every honest post (front-running). */ + default List before(int round, DkgEncryptedHarness h) { + return List.of(); + } + + /** Extra posts appended to a round's window. */ + default List extra(int round) { + return List.of(); + } + + /** + * {@code true} if recipient {@code j} opens dealer {@code i}'s envelope only after closing + * round 1. Such a recipient does not use the library's barrier: the negative control of + * review F1. + */ + default boolean processedLate(int i, int j) { + return false; + } + } + + static final Hooks HONEST = new Hooks() { + }; + + /** Authenticity: the authenticator is {@code SHA-256(rosterKey ‖ message)} under the claimed sender's key. */ + static final DkgAdmissionVerifier AUTH = new DkgAdmissionVerifier() { + @Override + public boolean authenticate(int sender, byte[] rosterKey, byte[] message, byte[] authenticator) { + return Arrays.equals(tag(rosterKey, message), authenticator); + } + + @Override + public boolean roundClosed(DkgConfig config, int round, List canonicalMessages, byte[] evidence) { + return true; + } + }; + + static byte[] tag(byte[] rosterKey, byte[] message) { + try { + MessageDigest sha = MessageDigest.getInstance("SHA-256"); + sha.update(rosterKey); + sha.update(message); + return sha.digest(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + final DkgConfig config; + final List dealings; + final List participants = new ArrayList<>(); + final Map keys = new HashMap<>(); + final Map secrets = new HashMap<>(); + final Map aborted = new HashMap<>(); + /** Every post per round, 0–7, in board order. */ + final List> board = new ArrayList<>(); + /** Every envelope sealed, before hooks: {@code [i, j, bytes]}. */ + final List sealed = new ArrayList<>(); + DkgKeyDirectory directory; + private final Hooks hooks; + + private final String tagPrefix; + + DkgEncryptedHarness(DkgConfig config, List dealings, Hooks hooks) { + this(config, dealings, hooks, ""); + } + + /** {@code tagPrefix}: spec §9.1 test keys are {@code tagPrefix + "recipient." + j} and {@code tagPrefix + "ephemeral." + i + "." + j}. */ + DkgEncryptedHarness(DkgConfig config, List dealings, Hooks hooks, String tagPrefix) { + this.config = config; + this.dealings = dealings; + this.hooks = hooks; + this.tagPrefix = tagPrefix; + for (int r = 0; r <= 7; r++) board.add(new ArrayList<>()); + for (int i = 1; i <= config.n(); i++) { + participants.add(DkgParticipant.withDealing(config, i, dealings.get(i - 1))); + byte[] sk = testKey(tagPrefix + "recipient." + i); + secrets.put(i, sk); + keys.put(i, DkgShareDeliveryKeys.fromSecret(config, i, sk)); + } + } + + static DkgEncryptedHarness fixed(DkgConfig config, List dealings, Hooks hooks) { + return new DkgEncryptedHarness(config, dealings, hooks); + } + + /** Spec §9.1 test keys: SHA-256 of the tag under the profile's test prefix. */ + /** + * Runs {@code body} with the JDK provider {@code name} removed, then reinstalls it at its + * position: a platform fault for fail-closed tests. Tests in this module run sequentially. + */ + static void withoutProvider(String name, Runnable body) { + Provider[] all = Security.getProviders(); + int position = -1; + for (int k = 0; k < all.length; k++) { + if (all[k].getName().equals(name)) position = k; + } + if (position < 0) throw new IllegalStateException("no provider " + name); + Provider removed = all[position]; + Security.removeProvider(name); + try { + body.run(); + } finally { + Security.insertProviderAt(removed, position + 1); + } + } + + /** Runs {@code body} with {@code provider} preferred over every other provider, then removes it. */ + static void withPreferredProvider(Provider provider, Runnable body) { + if (Security.getProvider(provider.getName()) != null) throw new IllegalStateException(provider.getName() + " already installed"); + Security.insertProviderAt(provider, 1); + try { + body.run(); + } finally { + Security.removeProvider(provider.getName()); + } + } + + static byte[] testKey(String tag) { + try { + return MessageDigest.getInstance("SHA-256") + .digest(("zeroj.dkg-share-delivery-hpke.v1.test." + tag).getBytes(StandardCharsets.US_ASCII)); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + DkgParticipant participant(int id) { + return participants.get(id - 1); + } + + List window(List posts) { + List out = new ArrayList<>(); + for (Post p : posts) out.add(new AuthenticatedDkgMessage(p.bytes(), tag(config.rosterKey(p.author()), p.bytes()))); + return out; + } + + private boolean withoutBarrier(int j) { + for (int i = 1; i <= config.n(); i++) if (hooks.processedLate(i, j)) return true; + return false; + } + + DkgEncryptedHarness run() { + // Round 0: announcements, then the directory from the final window. + for (int j = 1; j <= config.n(); j++) { + for (byte[] a : hooks.announcement(j, keys.get(j).announcement())) board.get(0).add(new Post(j, a)); + } + board.get(0).addAll(hooks.extra(0)); + directory = DkgKeyDirectory.fromRound0(config, window(board.get(0)), AUTH); + + // Round 1: start (T1, seal), envelopes first, COMMITMENTS only after all envelopes made the window. + List round1 = new ArrayList<>(); + for (DkgParticipant p : participants) { + int i = p.id(); + DkgShareDelivery.SealedDealing dealing; + try { + dealing = withoutBarrier(i) ? startWithoutBinding(p) + : DkgShareDelivery.start(p, directory, keys.get(i), j -> testKey(tagPrefix + "ephemeral." + i + "." + j)); + } catch (FaultAssumptionViolatedException t1) { + aborted.put(i, t1); + continue; + } + // The plaintext SHAREs never leave through the broadcasts (final review X-2). + if (dealing.broadcasts().size() != 1 || dealing.broadcasts().get(0).kind() != DkgMessage.Kind.COMMITMENTS) { + throw new AssertionError("dealer " + i + " broadcasts " + dealing.broadcasts()); + } + boolean allInWindow = true; + for (byte[] e : dealing.envelopes()) { + DkgShareDeliveryCodec.Envelope env = DkgShareDeliveryCodec.decodeEnvelope(config, e); + sealed.add(new Object[]{env.sender(), env.recipient(), e}); + if (hooks.missesCutoff(env.sender(), env.recipient())) { + allInWindow = false; + continue; // posted after the cutoff: in no window + } + for (byte[] posted : hooks.envelope(env.sender(), env.recipient(), e)) round1.add(new Post(i, posted)); + } + if (allInWindow || hooks.ignoreCommitmentsLast().contains(i)) { + for (DkgMessage m : dealing.broadcasts()) { + for (byte[] posted : hooks.broadcast(m)) round1.add(new Post(i, posted)); + } + } + } + board.get(1).addAll(hooks.before(1, this)); // front-running copies, computed from the sealed envelopes + board.get(1).addAll(round1); + board.get(1).addAll(hooks.extra(1)); + List window1 = window(board.get(1)); + Map> outgoing = new HashMap<>(); + for (DkgParticipant p : participants) { + if (aborted.containsKey(p.id())) continue; + try { + outgoing.put(p.id(), withoutBarrier(p.id()) ? closeWithoutBarrier(p, window1) + : DkgShareDelivery.closeRound1(p, directory, keys.get(p.id()), window1, AUTH)); + } catch (FaultAssumptionViolatedException e) { + aborted.put(p.id(), e); + } + } + + // Rounds 2–7: the threshold profile's broadcasts, unchanged. + for (int round = 2; round <= 7; round++) { + for (DkgParticipant p : participants) { + for (DkgMessage m : outgoing.getOrDefault(p.id(), List.of())) { + for (byte[] posted : hooks.broadcast(m)) board.get(round).add(new Post(p.id(), posted)); + } + } + board.get(round).addAll(hooks.extra(round)); + outgoing.clear(); + for (DkgParticipant p : participants) { + if (aborted.containsKey(p.id())) continue; + for (Post post : board.get(round)) { + try { + p.receiveBroadcast(post.author(), post.bytes()); + } catch (IllegalArgumentException refused) { + // absent + } + } + try { + outgoing.put(p.id(), p.closeRound()); + } catch (FaultAssumptionViolatedException e) { + aborted.put(p.id(), e); + } + } + } + return this; + } + + /** A participant outside the library's barrier: started unbound, sealed with the test seam. */ + private DkgShareDelivery.SealedDealing startWithoutBinding(DkgParticipant p) { + directory.requireOwn(keys.get(p.id())); + List envelopes = new ArrayList<>(); + List broadcasts = new ArrayList<>(); + for (DkgMessage m : p.start()) { + if (m.kind() != DkgMessage.Kind.SHARE) { + broadcasts.add(m); + } else { + envelopes.add(DkgShareDelivery.sealOne(config, m.sender(), m.subject(), directory.key(m.subject()).orElseThrow(), m, + testKey(tagPrefix + "ephemeral." + m.sender() + "." + m.subject()))); + } + } + return new DkgShareDelivery.SealedDealing(envelopes, broadcasts); + } + + /** + * The negative control of the review's F1: broadcasts and timely envelopes are delivered, + * round 1 is closed, and only then are the late envelopes opened, when the participant no + * longer accepts them. + */ + private List closeWithoutBarrier(DkgParticipant p, List window1) { + for (AuthenticatedDkgMessage post : window1) { + byte[] bytes = post.message(); + DkgShareDeliveryCodec.Envelope env = DkgShareDeliveryCodec.decodeEnvelope(config, bytes); + if (env != null) { + if (env.recipient() == p.id() && !hooks.processedLate(env.sender(), p.id())) openInto(p, env); + continue; + } + try { + DkgMessage m = DkgMessage.decode(config, bytes); + if (AUTH.authenticate(m.sender(), config.rosterKey(m.sender()), bytes, post.authenticator())) { + p.receiveBroadcast(m.sender(), bytes); + } + } catch (IllegalArgumentException refused) { + // absent + } + } + List out = p.closeRound(); + for (AuthenticatedDkgMessage post : window1) { + DkgShareDeliveryCodec.Envelope env = DkgShareDeliveryCodec.decodeEnvelope(config, post.message()); + if (env != null && env.recipient() == p.id() && hooks.processedLate(env.sender(), p.id())) openInto(p, env); + } + keys.get(p.id()).destroy(); + return out; + } + + private void openInto(DkgParticipant p, DkgShareDeliveryCodec.Envelope env) { + try { + byte[] pt = Hpke.openBase(env.enc(), secrets.get(p.id()), DkgShareDeliveryCodec.info(config, env.sender(), env.recipient()), + new byte[0], env.ct()); + p.receivePrivate(env.sender(), pt); // refused once round 1 is closed + } catch (Hpke.HpkeException | IllegalArgumentException | IllegalStateException late) { + // absent + } + } + + /** The threshold profile's broadcasts of rounds 1–6, authenticated, as the board holds them. */ + List transcriptMessages() { + List out = new ArrayList<>(); + for (int r = 1; r <= 6; r++) out.addAll(DkgTranscript.deliveredRound(config, r, window(board.get(r)), AUTH)); + return out; + } + + /** Authenticated messages of a kind posted in a round, byte-identical copies once. */ + List posted(int round, DkgMessage.Kind kind) { + List out = new ArrayList<>(); + Set seen = new HashSet<>(); + for (Post p : board.get(round)) { + try { + DkgMessage m = DkgMessage.decode(config, p.bytes()); + if (m.sender() == p.author() && m.kind() == kind && seen.add(Arrays.toString(p.bytes()))) out.add(m); + } catch (IllegalArgumentException junk) { + // envelopes and junk + } + } + return out; + } +} diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryReferenceVectorsTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryReferenceVectorsTest.java new file mode 100644 index 00000000..7f043a03 --- /dev/null +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryReferenceVectorsTest.java @@ -0,0 +1,578 @@ +package org.zeroj.circuit.lib.jubjub; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * ADR-0054 M0/M2: the library against the independent {@code dkg-share-delivery-hpke-v1} + * reference ({@code src/test/resources/dkg-share-delivery-reference/}), written from the spec and + * RFC 9180 with no ZeroJ Java read. Every replayable {@code case.*} vector is replayed through the + * production code: the codec, {@link DkgShareDelivery#start} and {@link DkgShareDelivery#closeRound1} + * with a real {@link DkgParticipant}, and the key directory. Regenerate with + * {@code python3 dkg_share_delivery_hpke_v1_reference.py} in that directory. + */ +class DkgShareDeliveryReferenceVectorsTest { + + private static final String RESOURCE = "/dkg-share-delivery-reference/reference-output.txt"; + private static final String THRESHOLD = "/elgamal-threshold-reference/reference-output.txt"; + private static final HexFormat HEX = HexFormat.of(); + private static final BigInteger L = JubjubCurve.SUBGROUP_ORDER; + private static Map ref; + private static Map threshold; + + @BeforeAll + static void load() throws IOException { + ref = read(RESOURCE); + threshold = read(THRESHOLD); + } + + private static Map read(String resource) throws IOException { + Map out = new LinkedHashMap<>(); + try (InputStream in = Objects.requireNonNull(DkgShareDeliveryReferenceVectorsTest.class.getResourceAsStream(resource), resource); + BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + if (line.isBlank() || line.startsWith("#")) continue; + int eq = line.indexOf('='); + out.put(line.substring(0, eq), line.substring(eq + 1)); + } + } + return out; + } + + /** The keys of one case, with the {@code case...} prefix removed. */ + private record Case(String name, Map keys) { + String get(String k) { + return Objects.requireNonNull(keys.get(k), () -> name + ": missing " + k); + } + + boolean has(String k) { + return keys.containsKey(k); + } + } + + /** Cases of a family; a case is the longest key prefix that owns a {@code config} key. */ + private static Map cases(String family, int unused) { + String prefix = "case." + family + "."; + Set names = new TreeSet<>(); + for (String k : ref.keySet()) { + if (k.startsWith(prefix) && k.endsWith(".config")) names.add(k.substring(prefix.length(), k.length() - ".config".length())); + } + Map> grouped = new TreeMap<>(); + for (var e : ref.entrySet()) { + if (!e.getKey().startsWith(prefix)) continue; + String rest = e.getKey().substring(prefix.length()); + String owner = null; + for (String n : names) if (rest.startsWith(n + ".") && (owner == null || n.length() > owner.length())) owner = n; + if (owner == null) continue; + grouped.computeIfAbsent(owner, x -> new LinkedHashMap<>()).put(rest.substring(owner.length() + 1), e.getValue()); + } + Map out = new TreeMap<>(); + grouped.forEach((n, k) -> out.put(n, new Case(family + "." + n, k))); + return out; + } + + private static DkgConfig config(String spec) { + String[] f = spec.split(",", -1); + int t = Integer.parseInt(f[0]); + int n = Integer.parseInt(f[1]); + List roster = new ArrayList<>(); + for (int j = 1; j <= n; j++) { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) j); + roster.add(key); + } + return DkgConfig.create(t, n, roster, HEX.parseHex(f[2]), Long.parseLong(f[3])); + } + + /** The threshold reference's fixture dealings, {@code a_ik} and {@code b_ik}. */ + private static List fixtureDealings(String fixture, int t, int n) { + List out = new ArrayList<>(); + for (int i = 1; i <= n; i++) { + BigInteger[] a = new BigInteger[t + 1]; + BigInteger[] b = new BigInteger[t + 1]; + for (int k = 0; k <= t; k++) { + a[k] = num(threshold.get(fixture + ".a." + i + "." + k)); + b[k] = num(threshold.get(fixture + ".b." + i + "." + k)); + } + out.add(ThresholdVss.dealWithCoefficients(a, b)); + } + return out; + } + + private static BigInteger num(String s) { + Objects.requireNonNull(s, "threshold fixture value"); + return s.startsWith("0x") ? new BigInteger(s.substring(2), 16) : new BigInteger(s); + } + + private static String fixtureFor(DkgConfig config) { + return "honest-" + (config.t() + 1) + "of" + config.n(); + } + + private static AuthenticatedDkgMessage post(DkgConfig config, String auth, byte[] bytes) { + if ("none".equals(auth)) return new AuthenticatedDkgMessage(bytes, new byte[32]); + int author = Integer.parseInt(auth); + return new AuthenticatedDkgMessage(bytes, DkgEncryptedHarness.tag(config.rosterKey(author), bytes)); + } + + private static Set ids(String csv) { + Set out = new TreeSet<>(); + if (!csv.isEmpty()) for (String p : csv.split(",")) out.add(Integer.parseInt(p.trim())); + return out; + } + + private static Set pairs(String csv) { + Set out = new TreeSet<>(); + if (!csv.isEmpty()) out.addAll(Arrays.asList(csv.split(","))); + return out; + } + + // ---------------------------------------------------------------- self-check + + @Test + @DisplayName("The reference run passed its own checks, including RFC 9180 A.2.1 and Wycheproof") + void referencePassed() { + assertEquals("pass", ref.get("result")); + int checks = 0; + for (var e : ref.entrySet()) { + if (e.getKey().startsWith("check.")) { + assertEquals("true", e.getValue(), e.getKey()); + checks++; + } + } + assertTrue(checks > 200, "checks: " + checks); + int cases = 0; + for (String family : List.of("announce", "envelope", "directory", "timing", "run", "exposure")) cases += cases(family, 1).size(); + assertEquals(Integer.parseInt(ref.get("info.case_count")), cases, "every case vector is replayed"); + } + + // ---------------------------------------------------------------- announce + + @TestFactory + @DisplayName("case.announce.*: §3.1 well-formedness through the codec") + Stream announce() { + return cases("announce", 1).values().stream().map(c -> DynamicTest.dynamicTest(c.name(), () -> { + DkgConfig config = config(c.get("config")); + boolean accepted = DkgShareDeliveryCodec.decodeAnnouncement(config, HEX.parseHex(c.get("bytes"))) != null; + assertEquals("accept".equals(c.get("expect")), accepted, c.name()); + })); + } + + // ---------------------------------------------------------------- envelope + + @TestFactory + @DisplayName("case.envelope.*: §4.2 acceptance through closeRound1 and a bound participant") + Stream envelope() { + return cases("envelope", 1).values().stream().map(c -> DynamicTest.dynamicTest(c.name(), () -> { + DkgConfig config = config(c.get("config")); + int j = Integer.parseInt(c.get("recipient")); + DkgShareDeliveryKeys keys = DkgShareDeliveryKeys.fromSecret(config, j, DkgEncryptedHarness.testKey(c.get("recipient_key_tag"))); + DkgKeyDirectory dir = DkgKeyDirectory.fromRound0(config, List.of(post(config, Integer.toString(j), keys.announcement())), + DkgEncryptedHarness.AUTH); + DkgParticipant p = DkgParticipant.withDealing(config, j, fixtureDealings(fixtureFor(config), config.t(), config.n()).get(j - 1)); + DkgShareDelivery.start(p, dir, keys, new SecureRandom()); + List window = new ArrayList<>(); + if (c.has("bytes")) window.add(post(config, c.get("auth"), HEX.parseHex(c.get("bytes")))); + for (int k = 1; c.has("bytes." + k); k++) window.add(post(config, c.get("auth." + k), HEX.parseHex(c.get("bytes." + k)))); + DkgShareDelivery.closeRound1(p, dir, keys, window, DkgEncryptedHarness.AUTH); + List got = new ArrayList<>(); + for (int i = 1; i <= config.n(); i++) for (DkgMessage m : p.receivedShares(i)) got.add(HEX.formatHex(m.encode())); + String expect = c.get("expect"); + if (expect.equals("absent")) { + assertEquals(List.of(), got, c.name()); + } else if (expect.startsWith("share:")) { + assertEquals(List.of(expect.substring(6)), got, c.name()); + } else { + assertEquals(new TreeSet<>(Arrays.asList(expect.substring(7).split(","))), new TreeSet<>(got), c.name()); + } + if (c.has("ephemeral_tag")) { // the good case, byte for byte + byte[] pk = keys.publicKey(); + DkgMessage share = DkgMessage.decode(config, HEX.parseHex(c.get("plaintext"))); + assertArrayEquals(HEX.parseHex(c.get("bytes")), DkgShareDelivery.sealOne(config, share.sender(), share.subject(), pk, share, + DkgEncryptedHarness.testKey(c.get("ephemeral_tag"))), c.name() + " envelope bytes"); + assertArrayEquals(HEX.parseHex(c.get("info")), DkgShareDeliveryCodec.info(config, share.sender(), share.subject())); + } + })); + } + + // ---------------------------------------------------------------- run + + @TestFactory + @DisplayName("case.run.*: full encrypted runs reproduce every announcement, envelope and output byte for byte") + Stream run() { + return cases("run", 1).values().stream().map(c -> DynamicTest.dynamicTest(c.name(), () -> { + DkgConfig config = config(c.get("config")); + String fixture = c.name().substring("run.".length()); + String prefix = c.get("recipient_key_tag.1").replace("recipient.1", ""); + DkgEncryptedHarness h = new DkgEncryptedHarness(config, fixtureDealings(fixture, config.t(), config.n()), + DkgEncryptedHarness.HONEST, prefix).run(); + for (int j = 1; j <= config.n(); j++) { + assertArrayEquals(HEX.parseHex(c.get("announce." + j)), h.keys.get(j).announcement(), "announce " + j); + } + int envelopes = 0; + for (Object[] e : h.sealed) { + assertArrayEquals(HEX.parseHex(c.get("envelope." + e[0] + "." + e[1])), (byte[]) e[2], "envelope " + e[0] + "." + e[1]); + envelopes++; + } + assertEquals(config.n() * (config.n() - 1), envelopes); + assertTrue(h.aborted.isEmpty(), "aborts " + h.aborted); + DkgTranscript transcript = DkgTranscript.of(config, h.transcriptMessages()); + assertArrayEquals(HEX.parseHex(c.get("expect.digest")), transcript.digest(), "digest"); + DkgTranscript.DkgPublicOutcome out = transcript.recompute(); + assertEquals(ids(c.get("expect.qual")), out.qual()); + assertArrayEquals(HEX.parseHex(c.get("expect.y")), out.jointKey().toBytes()); + for (int j = 1; j <= config.n(); j++) { + assertArrayEquals(HEX.parseHex(c.get("expect.Y." + j)), out.verificationKeys().get(j - 1).toBytes(), "Y." + j); + } + })); + } + + // ---------------------------------------------------------------- directory and timing (board replay) + + @TestFactory + @DisplayName("case.directory.* and case.timing.*: board replay with windows, lags, the barrier and T1") + Stream board() { + List all = new ArrayList<>(cases("directory", 1).values()); + all.addAll(cases("timing", 1).values()); + return all.stream().map(c -> DynamicTest.dynamicTest(c.name(), () -> new BoardReplay(c).run())); + } + + /** One board vector replayed through the library (honest participants) or the documented negative control. */ + private static final class BoardReplay { + private final Case c; + private final DkgConfig config; + private final int cut0; + private final int cut1; + private final boolean barrier; + private final boolean t1Rule; + private final Set corrupted; + private final Set withholdExtraction; + private final Set ignoreT1; + private final boolean dedupBeforeAuth; + private final List posts = new ArrayList<>(); // time, author, label, hex + private final Map participants = new HashMap<>(); + private final Map keys = new HashMap<>(); + private final Map outcome = new TreeMap<>(); + + BoardReplay(Case c) { + this.c = c; + this.config = config(c.get("config")); + this.cut0 = Integer.parseInt(c.get("cut0")); + this.cut1 = Integer.parseInt(c.get("cut1")); + this.barrier = Boolean.parseBoolean(c.keys().getOrDefault("barrier", "true")); + this.t1Rule = Boolean.parseBoolean(c.keys().getOrDefault("t1_rule", "true")); + this.corrupted = ids(c.keys().getOrDefault("corrupted", "")); + this.withholdExtraction = ids(c.keys().getOrDefault("withhold_extraction", "")); + this.ignoreT1 = ids(c.keys().getOrDefault("t1_ignored_by", "")); + this.dedupBeforeAuth = Boolean.parseBoolean(c.keys().getOrDefault("dedup_before_auth", "false")); + for (int k = 1; c.has("post." + k); k++) posts.add(c.get("post." + k).split(",", 4)); + List d = fixtureDealings(fixtureFor(config), config.t(), config.n()); + for (int j = 1; j <= config.n(); j++) { + participants.put(j, DkgParticipant.withDealing(config, j, d.get(j - 1))); + keys.put(j, DkgShareDeliveryKeys.fromSecret(config, j, DkgEncryptedHarness.testKey(c.get("recipient_key_tag." + j)))); + outcome.put(j, "none"); + } + } + + private int lag(int j, String label) { + return Integer.parseInt(c.keys().getOrDefault("lag." + j + "." + label, "0")); + } + + /** The posts of a window as participant {@code j} has them when it acts. */ + private List window(int from, int to, int j) { + List out = new ArrayList<>(); + for (String[] p : posts) { + int time = Integer.parseInt(p[0]); + if (time < from || time >= to) continue; + if (!barrier && time + lag(j, p[2]) >= to) continue; // not processed before the cutoff + out.add(post(config, p[1], HEX.parseHex(p[3]))); + } + return out; + } + + void run() { + // Round 0: every participant's directory (identical under the barrier). + Map dirs = new HashMap<>(); + for (int j = 1; j <= config.n(); j++) dirs.put(j, DkgKeyDirectory.fromRound0(config, window(0, cut0, j), DkgEncryptedHarness.AUTH)); + DkgKeyDirectory reference = DkgKeyDirectory.fromRound0(config, window(0, cut0, 0), DkgEncryptedHarness.AUTH); + for (int j = 1; j <= config.n(); j++) { + String expect = c.get("expect.directory." + j); + assertEquals(expect, reference.key(j).map(HEX::formatHex).orElse("none"), c.name() + " directory " + j); + } + + // Round 1: honest participants through the library; corrupted ones and negative controls unbound. + Set t1 = new TreeSet<>(); + Map> outgoing = new HashMap<>(); + for (int j = 1; j <= config.n(); j++) { + DkgParticipant p = participants.get(j); + boolean library = barrier && t1Rule && !dedupBeforeAuth && !corrupted.contains(j) && !ignoreT1.contains(j); + try { + if (library) { + DkgShareDelivery.start(p, dirs.get(j), keys.get(j), new SecureRandom()); + outgoing.put(j, DkgShareDelivery.closeRound1(p, dirs.get(j), keys.get(j), window(cut0, cut1, j), DkgEncryptedHarness.AUTH)); + } else { + if (!dirs.get(j).hasKey(j) && t1Rule && !ignoreT1.contains(j)) { + throw new FaultAssumptionViolatedException(FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING, "T1"); + } + p.start(); + outgoing.put(j, closeUnbound(p, window(cut0, cut1, j))); + } + } catch (FaultAssumptionViolatedException e) { + if (e.reason() == FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING) t1.add(j); + outcome.put(j, code(e.reason())); + } + } + assertEquals(ids(c.get("expect.t1")), t1, c.name() + " T1"); + + // Rounds 2–7, with the corrupted participants' extra complaints in round 2. + List> rounds = new ArrayList<>(); + for (int r = 0; r <= 7; r++) rounds.add(new ArrayList<>()); + for (String[] p : posts) { + int time = Integer.parseInt(p[0]); + if (time >= cut0 && time < cut1) rounds.get(1).add(HEX.parseHex(p[3])); + } + Map> boardRounds = new HashMap<>(); + List r1 = new ArrayList<>(); + for (String[] p : posts) { + int time = Integer.parseInt(p[0]); + if (time >= cut0 && time < cut1) r1.add(post(config, p[1], HEX.parseHex(p[3]))); + } + boardRounds.put(1, r1); + for (int round = 2; round <= 7; round++) { + List window = new ArrayList<>(); + for (int j = 1; j <= config.n(); j++) { + for (DkgMessage m : outgoing.getOrDefault(j, List.of())) { + if (m.kind() == DkgMessage.Kind.EXTRACTION && withholdExtraction.contains(j)) continue; // withheld + window.add(post(config, Integer.toString(j), m.encode())); + } + } + if (round == 2) { + for (int k = 1; c.has("extra_complaint." + k); k++) { + String[] cd = c.get("extra_complaint." + k).split("->"); + int from = Integer.parseInt(cd[0]); + window.add(post(config, cd[0], DkgMessage.complaint(config, from, Integer.parseInt(cd[1])).encode())); + } + } + boardRounds.put(round, window); + outgoing.clear(); + for (int j = 1; j <= config.n(); j++) { + if (!"none".equals(outcome.get(j))) continue; + DkgParticipant p = participants.get(j); + for (AuthenticatedDkgMessage post : window) { + try { + DkgMessage m = DkgMessage.decode(config, post.message()); + if (DkgEncryptedHarness.AUTH.authenticate(m.sender(), config.rosterKey(m.sender()), post.message(), post.authenticator())) { + p.receiveBroadcast(m.sender(), post.message()); + } + } catch (IllegalArgumentException refused) { + // absent + } + } + try { + outgoing.put(j, p.closeRound()); + } catch (FaultAssumptionViolatedException e) { + outcome.put(j, code(e.reason())); + } + } + } + + assertEquals(pairs(c.get("expect.complaints")), arrows(boardRounds.get(2), DkgMessage.Kind.COMPLAINT), c.name() + " complaints"); + assertEquals(pairs(c.get("expect.answers")), arrows(boardRounds.get(3), DkgMessage.Kind.ANSWER), c.name() + " answers"); + Map expectedAborts = new TreeMap<>(); + for (String jo : c.get("expect.aborts").split(",")) { + String[] kv = jo.split(":"); + expectedAborts.put(Integer.parseInt(kv[0]), kv[1]); + } + for (int j : expectedAborts.keySet()) { + if (corrupted.contains(j)) continue; // the reference's corrupted behaviour is not honest code's + assertEquals(expectedAborts.get(j), outcome.get(j), c.name() + " outcome of " + j); + } + List transcript = new ArrayList<>(); + for (int r = 1; r <= 6; r++) { + List posts = boardRounds.get(r); + if (r == 1 && dedupBeforeAuth) posts = dedupFirst(posts); // the defective view the negative control records + transcript.addAll(DkgTranscript.deliveredRound(config, r, posts, DkgEncryptedHarness.AUTH)); + } + String expectDigest = c.get("expect.digest"); + DkgTranscript t = DkgTranscript.of(config, transcript); + if (!"none".equals(expectDigest)) assertArrayEquals(HEX.parseHex(expectDigest), t.digest(), c.name() + " digest"); + String publicAbort = c.keys().getOrDefault("expect.public_abort", "none"); + if (!"none".equals(publicAbort)) { + FaultAssumptionViolatedException e = assertThrows(FaultAssumptionViolatedException.class, t::recompute); + assertEquals(publicAbort, code(e.reason()), c.name() + " public abort"); + } else { + DkgTranscript.DkgPublicOutcome out = t.recompute(); + assertEquals(ids(c.get("expect.qual")), out.qual(), c.name() + " QUAL"); + if (c.has("expect.marked")) assertEquals(ids(c.get("expect.marked")), out.marked(), c.name() + " marked"); + assertArrayEquals(HEX.parseHex(c.get("expect.y")), out.jointKey().toBytes(), c.name() + " y"); + } + } + + /** Keeps the first copy of every byte string, before any authentication (the modelled defect). */ + private static List dedupFirst(List posts) { + Set seen = new TreeSet<>(); + List out = new ArrayList<>(); + for (AuthenticatedDkgMessage p : posts) if (seen.add(HEX.formatHex(p.message()))) out.add(p); + return out; + } + + /** A participant outside the library's barrier: opens what it processed, then closes. */ + private List closeUnbound(DkgParticipant p, List window) { + byte[] sk = DkgEncryptedHarness.testKey(c.get("recipient_key_tag." + p.id())); + Set seen = new TreeSet<>(); + for (AuthenticatedDkgMessage post : window) { + byte[] bytes = post.message(); + if (dedupBeforeAuth && !seen.add(HEX.formatHex(bytes))) continue; // the defect the negative control models + DkgShareDeliveryCodec.Envelope env = DkgShareDeliveryCodec.decodeEnvelope(config, bytes); + try { + if (env != null) { + if (env.recipient() != p.id()) continue; + if (!DkgEncryptedHarness.AUTH.authenticate(env.sender(), config.rosterKey(env.sender()), bytes, post.authenticator())) continue; + byte[] pt = Hpke.openBase(env.enc(), sk, DkgShareDeliveryCodec.info(config, env.sender(), env.recipient()), new byte[0], env.ct()); + p.receivePrivate(env.sender(), pt); + } else { + DkgMessage m = DkgMessage.decode(config, bytes); + if (DkgEncryptedHarness.AUTH.authenticate(m.sender(), config.rosterKey(m.sender()), bytes, post.authenticator())) { + p.receiveBroadcast(m.sender(), bytes); + } + } + } catch (Hpke.HpkeException | IllegalArgumentException absent) { + // absent + } + } + return p.closeRound(); + } + + private Set arrows(List window, DkgMessage.Kind kind) { + Set out = new TreeSet<>(); + for (byte[] m : DkgTranscript.deliveredRound(config, kind == DkgMessage.Kind.COMPLAINT ? 2 : 3, window, DkgEncryptedHarness.AUTH)) { + DkgMessage msg = DkgMessage.decode(config, m); + if (msg.kind() == kind) out.add(kind == DkgMessage.Kind.COMPLAINT ? msg.sender() + "->" + msg.subject() : msg.sender() + "->" + msg.subject()); + } + return out; + } + } + + private static String code(FaultAssumptionViolatedException.Reason r) { + return switch (r) { + case TOO_FEW_QUALIFIED -> "A1"; + case OWN_DEALING_DISQUALIFIED -> "A2"; + case TOO_FEW_RECONSTRUCTION_PAIRS -> "A3"; + case INCONSISTENT_RECONSTRUCTION -> "A4"; + case IDENTITY_JOINT_KEY -> "A5"; + case SHARE_MISMATCH -> "A6"; + case CONFLICTING_CONFIRMATION -> "A7"; + case OWN_DEALING_MARKED -> "A8"; + case OWN_COMPLAINT_MISSING -> "A9"; + case OWN_KEY_ANNOUNCEMENT_MISSING -> "T1"; + }; + } + + // ---------------------------------------------------------------- exposure + + @TestFactory + @DisplayName("case.exposure.*: the §6 counting rule, and reconstruction from envelopes opened by Java HPKE where a run backs the case") + Stream exposure() { + AtomicInteger runBacked = new AtomicInteger(); + AtomicInteger reconstructions = new AtomicInteger(); + Stream perCase = cases("exposure", 1).values().stream().map(c -> DynamicTest.dynamicTest(c.name(), () -> { + DkgConfig config = config(c.get("config")); + int n = config.n(); + Set leaked = ids(c.get("leaked")); + Set corruptedSet = ids(c.get("corrupted")); + Set sent = c.has("sent") ? pairs(c.get("sent")) : allPairs(n); + Set answers = pairs(c.keys().getOrDefault("answers", "")); + Set published = pairs(c.keys().getOrDefault("published", "")); + Set reconstructed = ids(c.keys().getOrDefault("reconstructed", "")); + Set qual = ids(c.get("qual")); + boolean allExposed = true; + for (int dealer = 1; dealer <= n; dealer++) { + // The counting rule of spec §6, written here from the spec. + Set known = new TreeSet<>(); + if (corruptedSet.contains(dealer) || reconstructed.contains(dealer)) { + for (int x = 1; x <= n; x++) known.add(x); + } else { + for (int j = 1; j <= n; j++) { + if (j != dealer && (leaked.contains(j) || corruptedSet.contains(j)) && sent.contains(dealer + "->" + j)) known.add(j); + } + for (String a : answers) if (a.startsWith(dealer + "->")) known.add(Integer.parseInt(a.split("->")[1])); + for (String a : published) if (a.startsWith(dealer + "->")) known.add(Integer.parseInt(a.split("->")[1])); + } + if (c.has("known." + dealer)) assertEquals(ids(c.get("known." + dealer)), known, c.name() + " known indices of dealer " + dealer); + boolean exposed = known.size() >= config.t() + 1; + if (c.has("expect.dealer." + dealer)) { + assertEquals(c.get("expect.dealer." + dealer), exposed ? "exposed" : "unexposed", c.name() + " dealer " + dealer); + } + if (qual.contains(dealer)) allExposed &= exposed; + } + assertEquals(c.get("expect.x"), allExposed ? "exposed" : "unexposed", c.name() + " x"); + + // Where a run backs the case: open the actual envelopes with Java HPKE and reconstruct. + if (!c.has("source") || !c.get("source").startsWith("case.run.")) return; + runBacked.incrementAndGet(); + String run = c.get("source").substring("case.run.".length()); + Case runCase = cases("run", 1).get(run); + List d = fixtureDealings(run, config.t(), n); + for (int dealer = 1; dealer <= n; dealer++) { + if (corruptedSet.contains(dealer) || !qual.contains(dealer)) continue; + TreeMap points = new TreeMap<>(); + for (int j = 1; j <= n; j++) { + if (j == dealer || !(leaked.contains(j) || corruptedSet.contains(j)) || !runCase.has("envelope." + dealer + "." + j)) continue; + DkgShareDeliveryCodec.Envelope env = DkgShareDeliveryCodec.decodeEnvelope(config, HEX.parseHex(runCase.get("envelope." + dealer + "." + j))); + byte[] pt = Hpke.openBase(env.enc(), DkgEncryptedHarness.testKey(runCase.get("recipient_key_tag." + j)), + DkgShareDeliveryCodec.info(config, dealer, j), new byte[0], env.ct()); + points.put(j, DkgMessage.decode(config, pt).s()); + } + for (String a : answers) { + String[] ij = a.split("->"); + if (Integer.parseInt(ij[0]) == dealer) points.put(Integer.parseInt(ij[1]), d.get(dealer - 1).share(Integer.parseInt(ij[1]))); + } + if (points.size() >= config.t() + 1) { + assertEquals(d.get(dealer - 1).share(0), DkgShareDeliveryTest.interpolateAtZero(points), c.name() + " z_" + dealer); + reconstructions.incrementAndGet(); + } + } + })); + // Guards the replay itself (final review X-1): the run-backed block must actually run. + DynamicTest coverage = DynamicTest.dynamicTest("run-backed exposure cases reach the HPKE reconstruction", () -> { + assertTrue(runBacked.get() >= 20, "run-backed cases: " + runBacked.get()); + assertTrue(reconstructions.get() >= 1, "dealer reconstructions: " + reconstructions.get()); + }); + return Stream.concat(perCase, Stream.of(coverage)); + } + + private static Set allPairs(int n) { + Set out = new TreeSet<>(); + for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (i != j) out.add(i + "->" + j); + return out; + } +} diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryTest.java new file mode 100644 index 00000000..8bbfb825 --- /dev/null +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/DkgShareDeliveryTest.java @@ -0,0 +1,1253 @@ +package org.zeroj.circuit.lib.jubjub; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.math.BigInteger; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.function.IntFunction; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * ADR-0054 M2: {@code dkg-share-delivery-hpke-v1} through the real {@link DkgParticipant} state + * machine, one nested class per invariant group. The board model is {@link DkgEncryptedHarness}. + */ +class DkgShareDeliveryTest { + + private static final BigInteger L = JubjubCurve.SUBGROUP_ORDER; + + private static DkgConfig config(int t, int n, long attempt) { + return DkgHarness.config(t, n, "dkg-share-delivery-test", attempt); + } + + private static List dealings(int t, int n) { + return DkgHarness.dealings(t, n, 54_000 + 10L * t + n); + } + + private static ThresholdKeyContext context(DkgParticipant p) { + return p.result().context(); + } + + // ------------------------------------------------------------------ I3 + + @Nested + @DisplayName("I3: the key generation is unchanged") + class Unchanged { + + @Test + @DisplayName("Encrypted delivery gives the same transcript digest, QUAL, y, Y_j and x_j as private channels") + void sameAsPrivateChannels() { + for (int[] tn : new int[][]{{1, 3}, {2, 5}, {3, 7}}) { + DkgConfig config = config(tn[0], tn[1], 1); + List d = dealings(tn[0], tn[1]); + DkgEncryptedHarness enc = DkgEncryptedHarness.fixed(config, d, DkgEncryptedHarness.HONEST).run(); + DkgHarness plain = DkgHarness.fixed(config, d, DkgHarness.HONEST).run(); + assertTrue(enc.aborted.isEmpty(), "aborts: " + enc.aborted); + assertArrayEquals(DkgTranscript.of(config, plain.transcriptMessages()).digest(), + DkgTranscript.of(config, enc.transcriptMessages()).digest(), "digest " + Arrays.toString(tn)); + for (int j = 1; j <= config.n(); j++) { + assertEquals(context(plain.participant(j)), context(enc.participant(j))); + assertEquals(plain.participant(j).result().secretScalar(), enc.participant(j).result().secretScalar()); + } + assertEquals(config.n() * (config.n() - 1), enc.sealed.size(), "n(n − 1) envelopes"); + } + } + + @Test + @DisplayName("A bad SHARE sealed by dealer 1 draws the same complaint, answer and outcome as over private channels") + void badShareSameAsPrivateChannels() { + DkgConfig config = config(2, 5, 1); + List d = dealings(2, 5); + DkgMessage honest12 = DkgMessage.pair(config, DkgMessage.Kind.SHARE, 1, 2, d.get(0).share(2), d.get(0).sharePrime(2)); + byte[] bad = DkgShareDelivery.sealOne(config, 1, 2, publicKeyOf(2), bump(config, honest12), + DkgEncryptedHarness.testKey("ephemeral.1.2")); + DkgEncryptedHarness enc = DkgEncryptedHarness.fixed(config, d, new DkgEncryptedHarness.Hooks() { + @Override + public List envelope(int i, int j, byte[] envelope) { + return i == 1 && j == 2 ? List.of(bad) : List.of(envelope); + } + }).run(); + DkgHarness plain = DkgHarness.fixed(config, d, (m, honest) -> + m.kind() == DkgMessage.Kind.SHARE && m.sender() == 1 && m.subject() == 2 + ? List.of(new DkgHarness.Delivery(1, 2, bump(config, m).encode())) : honest).run(); + assertArrayEquals(DkgTranscript.of(config, plain.transcriptMessages()).digest(), + DkgTranscript.of(config, enc.transcriptMessages()).digest()); + assertEquals(1, enc.posted(2, DkgMessage.Kind.COMPLAINT).size()); + assertEquals(1, enc.posted(3, DkgMessage.Kind.ANSWER).size()); + assertEquals(Set.of(1, 2, 3, 4, 5), context(enc.participant(3)).qual()); + } + } + + // ------------------------------------------------------------------ I3 under attack (review X-7) + + /** + * ADR-0053's adversarial suites that can be expressed on an agreed board, rerun over encrypted + * delivery and compared with the same attack over private channels (ADR-0054 M2 exit + * criterion). Suites that need different views per recipient (A6, A7, A9) cannot be posted on + * an agreed board and are not transport-dependent. + */ + @Nested + @DisplayName("I3 under attack: board-expressible ADR-0053 adversarial suites give the same outcome as private channels") + class AdversarialSuites { + + /** The same attack on the board: a tampered SHARE is sealed in its envelope; broadcasts are posted once each. */ + private DkgEncryptedHarness.Hooks onBoard(DkgConfig config, List d, DkgHarness.Adversary adversary) { + DkgHarness bridge = DkgHarness.fixed(config, d, DkgHarness.HONEST); + return new DkgEncryptedHarness.Hooks() { + @Override + public List envelope(int i, int j, byte[] envelope) { + DkgMessage share = DkgMessage.pair(config, DkgMessage.Kind.SHARE, i, j, d.get(i - 1).share(j), d.get(i - 1).sharePrime(j)); + List out = new ArrayList<>(); + for (DkgHarness.Delivery x : adversary.deliver(share, bridge.honestDeliveries(share))) { + out.add(Arrays.equals(x.bytes(), share.encode()) ? envelope + : DkgShareDelivery.sealOne(config, i, j, publicKeyOf(j), DkgMessage.decode(config, x.bytes()), + DkgEncryptedHarness.testKey("ephemeral." + i + "." + j))); + } + return out; + } + + @Override + public List broadcast(DkgMessage m) { + List out = new ArrayList<>(); + for (DkgHarness.Delivery x : adversary.deliver(m, bridge.honestDeliveries(m))) { + if (out.stream().noneMatch(b -> Arrays.equals(b, x.bytes()))) out.add(x.bytes()); + } + return out; + } + }; + } + + private DkgEncryptedHarness sameOutcome(DkgConfig config, List d, DkgHarness.Adversary adversary) { + DkgHarness plain = DkgHarness.fixed(config, d, adversary).run(); + DkgEncryptedHarness enc = DkgEncryptedHarness.fixed(config, d, onBoard(config, d, adversary)).run(); + assertArrayEquals(DkgTranscript.of(config, plain.transcriptMessages()).digest(), + DkgTranscript.of(config, enc.transcriptMessages()).digest(), "transcript digest"); + assertEquals(plain.aborted.keySet(), enc.aborted.keySet(), "aborted participants"); + for (int id : plain.aborted.keySet()) { + assertEquals(plain.aborted.get(id).reason(), enc.aborted.get(id).reason(), "abort reason of " + id); + } + for (int j = 1; j <= config.n(); j++) { + if (plain.aborted.containsKey(j)) continue; + assertEquals(context(plain.participant(j)), context(enc.participant(j)), "context of " + j); + assertEquals(plain.participant(j).result().secretScalar(), enc.participant(j).result().secretScalar(), "x_" + j); + } + return enc; + } + + @Test + @DisplayName("More than t complaints disqualify the dealer (A2 for it)") + void tooManyComplaints() { + DkgConfig config = config(2, 5, 1); + List d = dealings(2, 5); + DkgEncryptedHarness enc = sameOutcome(config, d, (m, honest) -> m.kind() == DkgMessage.Kind.SHARE && m.sender() == 1 && m.subject() >= 3 + ? List.of(new DkgHarness.Delivery(1, m.subject(), bump(config, m).encode())) : honest); + assertEquals(FaultAssumptionViolatedException.Reason.OWN_DEALING_DISQUALIFIED, enc.aborted.get(1).reason(), "the attack took effect"); + assertEquals(Set.of(2, 3, 4, 5), context(enc.participant(2)).qual()); + } + + @Test + @DisplayName("A complaint answered with a failing pair disqualifies the dealer") + void badAnswer() { + DkgConfig config = config(1, 3, 1); + List d = dealings(1, 3); + DkgEncryptedHarness enc = sameOutcome(config, d, (m, honest) -> { + if (m.kind() == DkgMessage.Kind.SHARE && m.sender() == 1 && m.subject() == 2) { + return List.of(new DkgHarness.Delivery(1, 2, bump(config, m).encode())); + } + if (m.kind() == DkgMessage.Kind.ANSWER && m.sender() == 1) { + byte[] bad = DkgMessage.pair(config, DkgMessage.Kind.ANSWER, 1, m.subject(), m.s().add(BigInteger.ONE).mod(L), m.sPrime()).encode(); + List out = new ArrayList<>(); + for (DkgHarness.Delivery x : honest) out.add(new DkgHarness.Delivery(1, x.recipient(), bad)); + return out; + } + return honest; + }); + assertEquals(Set.of(2, 3), context(enc.participant(2)).qual(), "the attack took effect"); + } + + @Test + @DisplayName("Phase-2 Feldman cheat: the dealer is marked and reconstructed (A8 for it); the key is unchanged") + void feldmanCheat() { + DkgConfig config = config(1, 3, 1); + List d = dealings(1, 3); + DkgEncryptedHarness enc = sameOutcome(config, d, (m, honest) -> { + if (m.kind() == DkgMessage.Kind.EXTRACTION && m.sender() == 3) { + List forged = new ArrayList<>(m.points()); + forged.set(1, forged.get(1).add(JubjubPoint.SUBGROUP_GENERATOR).normalized()); + byte[] bytes = DkgMessage.points(config, DkgMessage.Kind.EXTRACTION, 3, forged).encode(); + List out = new ArrayList<>(); + for (DkgHarness.Delivery x : honest) out.add(new DkgHarness.Delivery(3, x.recipient(), bytes)); + return out; + } + return honest; + }); + assertEquals(FaultAssumptionViolatedException.Reason.OWN_DEALING_MARKED, enc.aborted.get(3).reason(), "the attack took effect"); + } + + @Test + @DisplayName("Conflicting COMMITMENTS disqualify; conflicting or withheld EXTRACTION is reconstructed") + void conflictsAndWithholding() { + DkgConfig config = config(1, 3, 1); + List d = dealings(1, 3); + List alt = DkgHarness.dealings(1, 3, 54_999); + for (DkgMessage.Kind kind : List.of(DkgMessage.Kind.COMMITMENTS, DkgMessage.Kind.EXTRACTION)) { + DkgEncryptedHarness enc = sameOutcome(config, d, (m, honest) -> { + if (m.kind() == kind && m.sender() == 3) { + List second = kind == DkgMessage.Kind.COMMITMENTS ? alt.get(2).commitments() : alt.get(2).extraction(); + byte[] bytes = DkgMessage.points(config, kind, 3, second).encode(); + List out = new ArrayList<>(honest); + for (DkgHarness.Delivery x : honest) out.add(new DkgHarness.Delivery(3, x.recipient(), bytes)); + return out; + } + return honest; + }); + if (kind == DkgMessage.Kind.COMMITMENTS) { + assertEquals(Set.of(1, 2), context(enc.participant(1)).qual(), "conflicting COMMITMENTS disqualify"); + } else { + assertEquals(Set.of(3), DkgTranscript.of(config, enc.transcriptMessages()).recompute().marked(), "conflicting EXTRACTION is marked"); + } + } + DkgEncryptedHarness withheld = sameOutcome(config, d, + (m, honest) -> m.kind() == DkgMessage.Kind.EXTRACTION && m.sender() == 2 ? List.of() : honest); + assertEquals(Set.of(2), DkgTranscript.of(config, withheld.transcriptMessages()).recompute().marked(), "withheld EXTRACTION is marked"); + } + + @Test + @DisplayName("A5: constant terms summing to 0 abort everyone") + void identityKey() { + DkgConfig config = config(1, 3, 1); + List d = List.of( + ThresholdVss.dealWithCoefficients(new BigInteger[]{BigInteger.ONE, BigInteger.TWO}, new BigInteger[]{BigInteger.ONE, BigInteger.ONE}), + ThresholdVss.dealWithCoefficients(new BigInteger[]{BigInteger.TWO, BigInteger.ONE}, new BigInteger[]{BigInteger.TWO, BigInteger.ONE}), + ThresholdVss.dealWithCoefficients(new BigInteger[]{L.subtract(BigInteger.valueOf(3)), BigInteger.TEN}, new BigInteger[]{BigInteger.TEN, BigInteger.ONE})); + sameOutcome(config, d, DkgHarness.HONEST); + assertEquals(FaultAssumptionViolatedException.Reason.IDENTITY_JOINT_KEY, + DkgEncryptedHarness.fixed(config, d, DkgEncryptedHarness.HONEST).run().aborted.get(1).reason()); + } + } + + static byte[] publicKeyOf(int j) { + try { + return X25519Bytes.publicFromPrivate(DkgEncryptedHarness.testKey("recipient." + j)); + } catch (GeneralSecurityException e) { + throw new AssertionError(e); + } + } + + static DkgMessage bump(DkgConfig config, DkgMessage share) { + return DkgMessage.pair(config, DkgMessage.Kind.SHARE, share.sender(), share.subject(), share.s().add(BigInteger.ONE).mod(L), share.sPrime()); + } + + // ------------------------------------------------------------------ I2, I4, I6 + + @Nested + @DisplayName("I2, I4, I6: binding, uniform failure and canonical encodings") + class Binding { + + /** Runs n = 3, t = 1 with dealer 1's envelope to 2 replaced by {@code forged}; returns 2's complaints. */ + private List complaintsOf2(byte[] forged) { + DkgConfig config = config(1, 3, 1); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, dealings(1, 3), new DkgEncryptedHarness.Hooks() { + @Override + public List envelope(int i, int j, byte[] envelope) { + return i == 1 && j == 2 ? (forged == null ? List.of() : List.of(forged)) : List.of(envelope); + } + }).run(); + List out = new ArrayList<>(); + for (DkgMessage m : h.posted(2, DkgMessage.Kind.COMPLAINT)) if (m.sender() == 2) out.add(m); + return out; + } + + private byte[] honestEnvelope(DkgConfig config, int i, int j) { + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, dealings(config.t(), config.n()), DkgEncryptedHarness.HONEST); + h.run(); + for (Object[] e : h.sealed) if ((int) e[0] == i && (int) e[1] == j) return ((byte[]) e[2]).clone(); + throw new AssertionError("no envelope " + i + "→" + j); + } + + @Test + @DisplayName("Every failure kind is equivalent to absence: exactly one complaint by 2 against 1, nothing else") + void uniformFailure() { + DkgConfig config = config(1, 3, 1); + byte[] good = honestEnvelope(config, 1, 2); + int encAt = DkgShareDeliveryCodec.TAG_E.length + 34; + int ctAt = encAt + 32; + List forgeries = new ArrayList<>(); + forgeries.add(null); // missing + forgeries.add(flip(good, ctAt + 5)); // tampered ct + forgeries.add(flip(good, ctAt + 115)); // tampered tag + forgeries.add(flip(good, encAt + 3)); // tampered enc + byte[] nonCanonical = good.clone(); + nonCanonical[encAt + 31] ^= (byte) 0x80; // same u mod p, non-canonical + forgeries.add(nonCanonical); + byte[] smallOrder = good.clone(); + Arrays.fill(smallOrder, encAt, encAt + 32, (byte) 0); // small-order enc + forgeries.add(smallOrder); + forgeries.add(Arrays.copyOf(good, good.length - 1)); // truncated + forgeries.add(Arrays.copyOf(good, good.length + 1)); // extended + byte[] otherSession = honestEnvelope(config(1, 3, 2), 1, 2); // replay from another attempt + forgeries.add(otherSession); + byte[] toThree = good.clone(); + toThree[DkgShareDeliveryCodec.TAG_E.length + 33] = 3; // header recipient changed + forgeries.add(toThree); + forgeries.add(sealedTo(config, 2, 3, 1, 2)); // SHARE 1→3 sealed to 2 + forgeries.add(sealedTo(config, 3, 2, 1, 2)); // SHARE 1→2 sealed to 3's key + for (int k = 0; k < forgeries.size(); k++) { + List complaints = complaintsOf2(forgeries.get(k)); + assertEquals(1, complaints.size(), "forgery " + k); + assertEquals(1, complaints.get(0).subject(), "forgery " + k); + } + assertEquals(List.of(), complaintsOf2(good), "the genuine envelope draws no complaint"); + } + + /** An envelope from 1 addressed (header) to {@code headerTo}, sealed to {@code keyOf}'s key, carrying SHARE 1→{@code shareTo}. */ + private byte[] sealedTo(DkgConfig config, int shareTo, int keyOf, int sender, int headerTo) { + ThresholdVss.Dealing d = dealings(config.t(), config.n()).get(sender - 1); + DkgMessage share = DkgMessage.pair(config, DkgMessage.Kind.SHARE, sender, shareTo, d.share(shareTo), d.sharePrime(shareTo)); + try { + byte[] pk = X25519Bytes.publicFromPrivate(DkgEncryptedHarness.testKey("recipient." + keyOf)); + Hpke.Sealed s = Hpke.sealBase(pk, DkgShareDeliveryCodec.info(config, sender, headerTo), new byte[0], share.encode(), new SecureRandom()); + return DkgShareDeliveryCodec.envelope(config, sender, headerTo, s.enc(), s.ct()); + } catch (Exception e) { + throw new AssertionError(e); + } + } + + @Test + @DisplayName("An envelope posted under another author fails authentication and is absent") + void impersonation() { + DkgConfig config = config(1, 3, 1); + byte[] good = honestEnvelope(config, 1, 2); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, dealings(1, 3), new DkgEncryptedHarness.Hooks() { + @Override + public List envelope(int i, int j, byte[] envelope) { + return i == 1 && j == 2 ? List.of() : List.of(envelope); + } + + @Override + public List extra(int round) { + return round == 1 ? List.of(new DkgEncryptedHarness.Post(3, good)) : List.of(); + } + }).run(); + assertEquals(1, h.posted(2, DkgMessage.Kind.COMPLAINT).stream().filter(m -> m.sender() == 2).count()); + } + + @Test + @DisplayName("Codec: exact lengths, tags, session, identifiers and canonical values; profile messages never decode as DKG messages") + void codec() { + DkgConfig config = config(1, 3, 1); + byte[] good = honestEnvelope(config, 1, 2); + assertEquals(223, good.length); + assertThrows(IllegalArgumentException.class, () -> DkgMessage.decode(config, good)); + DkgShareDeliveryKeys k = DkgShareDeliveryKeys.fromSecret(config, 2, DkgEncryptedHarness.testKey("recipient.2")); + byte[] a = k.announcement(); + assertEquals(106, a.length); + assertThrows(IllegalArgumentException.class, () -> DkgMessage.decode(config, a)); + assertEquals(2, DkgShareDeliveryCodec.decodeAnnouncement(config, a).participant()); + assertEquals(null, DkgShareDeliveryCodec.decodeAnnouncement(config(1, 3, 2), a), "other session"); + byte[] zeroKey = a.clone(); + Arrays.fill(zeroKey, a.length - 32, a.length, (byte) 0); + assertEquals(null, DkgShareDeliveryCodec.decodeAnnouncement(config, zeroKey), "small-order key"); + byte[] highBit = a.clone(); + highBit[a.length - 1] |= (byte) 0x80; + assertEquals(null, DkgShareDeliveryCodec.decodeAnnouncement(config, highBit), "non-canonical key"); + byte[] badId = a.clone(); + badId[DkgShareDeliveryCodec.TAG_A.length + 32] = 4; + assertEquals(null, DkgShareDeliveryCodec.decodeAnnouncement(config, badId), "j = n + 1"); + byte[] self = good.clone(); + self[DkgShareDeliveryCodec.TAG_E.length + 33] = 1; + assertEquals(null, DkgShareDeliveryCodec.decodeEnvelope(config, self), "i = j"); + assertEquals(71, DkgShareDeliveryCodec.info(config, 1, 2).length); + } + } + + static byte[] flip(byte[] b, int at) { + byte[] out = b.clone(); + out[at] ^= 1; + return out; + } + + // ------------------------------------------------------------------ I5, I12 + + @Nested + @DisplayName("I5, I12: the directory and abort T1") + class Directory { + + @Test + @DisplayName("T1: a participant whose announcement is missing aborts before round 1, receives no envelope and never complains") + void t1Missing() { + DkgConfig config = config(2, 5, 1); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, dealings(2, 5), new DkgEncryptedHarness.Hooks() { + @Override + public List announcement(int j, byte[] announcement) { + return j == 2 ? List.of() : List.of(announcement); + } + }).run(); + assertEquals(FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING, h.aborted.get(2).reason()); + assertTrue(h.sealed.stream().noneMatch(e -> (int) e[1] == 2), "no envelope to 2"); + for (int r = 1; r <= 7; r++) { + assertTrue(h.board.get(r).stream().noneMatch(p -> p.author() == 2), "2 posts nothing in round " + r); + } + assertTrue(h.posted(2, DkgMessage.Kind.COMPLAINT).isEmpty(), "no complaints at all"); + assertEquals(Set.of(1, 3, 4, 5), context(h.participant(1)).qual()); + } + + @Test + @DisplayName("Directory: conflicts give no key (T1), byte-identical duplicates count once, unauthenticated and malformed posts are ignored") + void directoryRules() { + DkgConfig config = config(1, 3, 1); + DkgShareDeliveryKeys k1 = DkgShareDeliveryKeys.fromSecret(config, 1, DkgEncryptedHarness.testKey("recipient.1")); + DkgShareDeliveryKeys k1b = DkgShareDeliveryKeys.fromSecret(config, 1, DkgEncryptedHarness.testKey("other.1")); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.fromSecret(config, 2, DkgEncryptedHarness.testKey("recipient.2")); + DkgShareDeliveryKeys k3 = DkgShareDeliveryKeys.fromSecret(config, 3, DkgEncryptedHarness.testKey("recipient.3")); + List window = List.of( + post(config, 1, k1.announcement()), post(config, 1, k1b.announcement()), // conflict for 1 + post(config, 2, k2.announcement()), post(config, 2, k2.announcement()), // duplicate for 2 + post(config, 1, k3.announcement()), // 3's announcement under 1's authenticator + post(config, 3, Arrays.copyOf(k3.announcement(), 105))); // malformed + DkgKeyDirectory dir = DkgKeyDirectory.fromRound0(config, window, DkgEncryptedHarness.AUTH); + assertFalse(dir.hasKey(1)); + assertArrayEquals(k2.publicKey(), dir.key(2).orElseThrow()); + assertFalse(dir.hasKey(3)); + assertEquals(FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING, + assertThrows(FaultAssumptionViolatedException.class, () -> dir.requireOwn(k1)).reason()); + dir.requireOwn(k2); + // A participant whose delivered key is not its own keys' public key is T1 too. + DkgShareDeliveryKeys k2b = DkgShareDeliveryKeys.fromSecret(config, 2, DkgEncryptedHarness.testKey("other.2")); + assertThrows(FaultAssumptionViolatedException.class, () -> dir.requireOwn(k2b)); + DkgParticipant p1 = DkgParticipant.create(config, 1, new SecureRandom()); + assertThrows(FaultAssumptionViolatedException.class, () -> DkgShareDelivery.start(p1, dir, k1, new SecureRandom())); + assertThrows(FaultAssumptionViolatedException.class, p1::closeRound, "T1 is sticky"); + assertTrue(k1.isDestroyed(), "T1 destroys the keys"); + } + } + + static AuthenticatedDkgMessage post(DkgConfig config, int author, byte[] bytes) { + return new AuthenticatedDkgMessage(bytes, DkgEncryptedHarness.tag(config.rosterKey(author), bytes)); + } + + // ------------------------------------------------------------------ I7 + + @Nested + @DisplayName("I7: key lifecycle and fail-closed use of the API") + class Lifecycle { + + private DkgKeyDirectory directoryOf(DkgConfig config, DkgShareDeliveryKeys... ks) { + List window = new ArrayList<>(); + for (DkgShareDeliveryKeys k : ks) window.add(post(config, k.id(), k.announcement())); + return DkgKeyDirectory.fromRound0(config, window, DkgEncryptedHarness.AUTH); + } + + @Test + @DisplayName("Keys are bound to one session and participant, destroyed after round 1, and redacted") + void keys() { + DkgConfig config = config(1, 3, 1); + DkgConfig other = config(1, 3, 2); + DkgShareDeliveryKeys keys = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + assertThrows(IllegalArgumentException.class, () -> keys.secretFor(other)); + assertFalse(keys.toString().contains(HexFormat.of().formatHex(keys.secretFor(config)))); + assertTrue(keys.toString().contains("redacted")); + DkgKeyDirectory dir = directoryOf(config, keys); + DkgParticipant p2 = DkgParticipant.create(config, 2, new SecureRandom()); + DkgShareDelivery.start(p2, dir, keys, new SecureRandom()); + DkgShareDelivery.closeRound1(p2, dir, keys, List.of(), DkgEncryptedHarness.AUTH); + assertTrue(keys.isDestroyed(), "closeRound1 destroys the keys"); + assertThrows(IllegalStateException.class, () -> keys.secretFor(config)); + assertEquals(2, p2.openRound()); + assertThrows(IllegalStateException.class, () -> DkgShareDelivery.closeRound1(p2, dir, keys, List.of(), DkgEncryptedHarness.AUTH), + "only at round 1"); + } + + @Test + @DisplayName("start returns exactly one COMMITMENTS to broadcast and one envelope per keyed other participant; no SHARE leaves in the clear (review X-2)") + void sealedDealingShape() { + DkgConfig config = config(2, 5, 1); + List ks = new ArrayList<>(); + for (int j = 1; j <= 4; j++) ks.add(DkgShareDeliveryKeys.generate(config, j, new SecureRandom())); // 5 has no key + DkgKeyDirectory dir = directoryOf(config, ks.toArray(new DkgShareDeliveryKeys[0])); + DkgParticipant p1 = DkgParticipant.create(config, 1, new SecureRandom()); + DkgShareDelivery.SealedDealing dealing = DkgShareDelivery.start(p1, dir, ks.get(0), new SecureRandom()); + assertEquals(1, dealing.broadcasts().size()); + assertEquals(DkgMessage.Kind.COMMITMENTS, dealing.broadcasts().get(0).kind()); + assertEquals(1, dealing.broadcasts().get(0).sender()); + Set recipients = new TreeSet<>(); + for (byte[] e : dealing.envelopes()) { + assertEquals(DkgShareDeliveryCodec.ENVELOPE_LENGTH, e.length); + assertThrows(IllegalArgumentException.class, () -> DkgMessage.decode(config, e), "an envelope is no threshold message"); + recipients.add(DkgShareDeliveryCodec.decodeEnvelope(config, e).recipient()); + } + assertEquals(Set.of(2, 3, 4), recipients); + } + + @Test + @DisplayName("generate draws the private key from the given generator: fresh keys differ, and a fixed generator gives X25519(k, 9) (review X-3)") + void generateUsesRandom() throws Exception { + DkgConfig config = config(1, 3, 1); + DkgShareDeliveryKeys a = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + DkgShareDeliveryKeys b = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + assertFalse(Arrays.equals(a.publicKey(), b.publicKey())); + assertFalse(Arrays.equals(a.secretFor(config), b.secretFor(config))); + byte[] k = DkgEncryptedHarness.testKey("generate.fixed"); + SecureRandom fixed = new SecureRandom() { + @Override + public void nextBytes(byte[] bytes) { + System.arraycopy(k, 0, bytes, 0, bytes.length); + } + }; + DkgShareDeliveryKeys c = DkgShareDeliveryKeys.generate(config, 2, fixed); + assertArrayEquals(k, c.secretFor(config)); + assertArrayEquals(X25519Bytes.publicFromPrivate(k), c.publicKey()); + // RFC 7748 §6.1 (Alice), independent of ZeroJ code. + byte[] alice = HexFormat.of().parseHex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + SecureRandom rfc = new SecureRandom() { + @Override + public void nextBytes(byte[] bytes) { + System.arraycopy(alice, 0, bytes, 0, bytes.length); + } + }; + assertArrayEquals(HexFormat.of().parseHex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"), + DkgShareDeliveryKeys.generate(config, 2, rfc).publicKey()); + } + + @Test + @DisplayName("Session and identifier must agree: participant, directory and keys of different runs are refused") + void sameRun() { + DkgConfig config = config(1, 3, 1); + DkgConfig other = config(1, 3, 2); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + DkgShareDeliveryKeys otherK2 = DkgShareDeliveryKeys.generate(other, 2, new SecureRandom()); + DkgKeyDirectory dir = directoryOf(config, k2); + DkgKeyDirectory otherDir = directoryOf(other, otherK2); + assertThrows(IllegalArgumentException.class, + () -> DkgShareDelivery.start(DkgParticipant.create(config, 2, new SecureRandom()), otherDir, k2, new SecureRandom())); + assertThrows(IllegalArgumentException.class, + () -> DkgShareDelivery.start(DkgParticipant.create(other, 2, new SecureRandom()), dir, k2, new SecureRandom())); + assertThrows(IllegalArgumentException.class, + () -> DkgShareDelivery.start(DkgParticipant.create(config, 3, new SecureRandom()), dir, k2, new SecureRandom())); + DkgParticipant p2 = DkgParticipant.create(config, 2, new SecureRandom()); + DkgShareDelivery.start(p2, dir, k2, new SecureRandom()); + assertThrows(IllegalArgumentException.class, + () -> DkgShareDelivery.closeRound1(p2, dir, otherK2, List.of(), DkgEncryptedHarness.AUTH), "keys of another session"); + assertFalse(k2.isDestroyed(), "a refused argument leaves the keys"); + assertEquals(1, p2.openRound()); + } + + @Test + @DisplayName("Binding: a started participant cannot close round 1 by itself; an unbound one cannot use closeRound1") + void binding() { + DkgConfig config = config(1, 3, 1); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + DkgKeyDirectory dir = directoryOf(config, k2); + DkgParticipant bound = DkgParticipant.create(config, 2, new SecureRandom()); + DkgShareDelivery.start(bound, dir, k2, new SecureRandom()); + assertThrows(IllegalStateException.class, bound::closeRound, "the public close refuses round 1"); + DkgParticipant unbound = DkgParticipant.create(config, 2, new SecureRandom()); + unbound.start(); + assertThrows(IllegalStateException.class, + () -> DkgShareDelivery.closeRound1(unbound, dir, k2, List.of(), DkgEncryptedHarness.AUTH)); + DkgParticipant already = DkgParticipant.create(config, 2, new SecureRandom()); + already.start(); + assertThrows(IllegalStateException.class, () -> DkgShareDelivery.start(already, dir, k2, new SecureRandom())); + } + + @Test + @DisplayName("closeRound1 needs the keys and directory instances given to start; a substitute is refused and changes nothing (review C-1)") + void substitutedAtClose() { + DkgConfig config = config(1, 3, 1); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + DkgShareDeliveryKeys otherK2 = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + DkgKeyDirectory withKey = directoryOf(config, k2); + DkgKeyDirectory sameContent = directoryOf(config, k2); + DkgKeyDirectory withOther = directoryOf(config, otherK2); + DkgKeyDirectory without = DkgKeyDirectory.fromRound0(config, List.of(), DkgEncryptedHarness.AUTH); + DkgParticipant p2 = DkgParticipant.create(config, 2, new SecureRandom()); + DkgShareDelivery.start(p2, withKey, k2, new SecureRandom()); + assertThrows(IllegalArgumentException.class, + () -> DkgShareDelivery.closeRound1(p2, without, k2, List.of(), DkgEncryptedHarness.AUTH), "directory without the key"); + assertThrows(IllegalArgumentException.class, + () -> DkgShareDelivery.closeRound1(p2, sameContent, k2, List.of(), DkgEncryptedHarness.AUTH), "an equal but different directory"); + assertThrows(IllegalArgumentException.class, + () -> DkgShareDelivery.closeRound1(p2, withOther, otherK2, List.of(), DkgEncryptedHarness.AUTH), "other keys and their directory"); + assertThrows(IllegalArgumentException.class, + () -> DkgShareDelivery.closeRound1(p2, withKey, otherK2, List.of(), DkgEncryptedHarness.AUTH), "other keys"); + assertFalse(k2.isDestroyed()); + assertFalse(otherK2.isDestroyed()); + assertEquals(1, p2.openRound()); + DkgShareDelivery.closeRound1(p2, withKey, k2, List.of(), DkgEncryptedHarness.AUTH); + assertEquals(2, p2.openRound(), "the bound pair still closes the round"); + assertTrue(k2.isDestroyed()); + } + + @Test + @DisplayName("start() after a T1 abort throws the sticky abort and changes nothing (review S-7)") + void startAfterAbort() { + DkgConfig config = config(1, 3, 1); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + DkgKeyDirectory without = DkgKeyDirectory.fromRound0(config, List.of(), DkgEncryptedHarness.AUTH); + DkgParticipant p2 = DkgParticipant.create(config, 2, new SecureRandom()); + assertThrows(FaultAssumptionViolatedException.class, () -> DkgShareDelivery.start(p2, without, k2, new SecureRandom())); + assertThrows(FaultAssumptionViolatedException.class, p2::start); + assertEquals(0, p2.openRound()); + } + + @Test + @DisplayName("A verifier that throws leaves the keys and round 1 open: no complaint, and a retry completes the round") + void verifierThrowsFailsClosed() { + DkgConfig config = config(1, 3, 1); + List d = dealings(1, 3); + DkgEncryptedHarness honest = DkgEncryptedHarness.fixed(config, d, DkgEncryptedHarness.HONEST); + honest.run(); + DkgParticipant p2 = DkgParticipant.withDealing(config, 2, d.get(1)); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.fromSecret(config, 2, DkgEncryptedHarness.testKey("recipient.2")); + DkgShareDelivery.start(p2, honest.directory, k2, new SecureRandom()); + List window = honest.window(honest.board.get(1)); + DkgAdmissionVerifier flaky = new DkgAdmissionVerifier() { + @Override + public boolean authenticate(int sender, byte[] rosterKey, byte[] message, byte[] authenticator) { + throw new IllegalStateException("signature service unavailable"); + } + + @Override + public boolean roundClosed(DkgConfig c, int round, List m, byte[] e) { + return true; + } + }; + assertThrows(IllegalStateException.class, () -> DkgShareDelivery.closeRound1(p2, honest.directory, k2, window, flaky)); + assertFalse(k2.isDestroyed()); + assertEquals(1, p2.openRound()); + assertThrows(IllegalStateException.class, p2::closeRound, "still no way to close round 1 but the barrier"); + assertEquals(List.of(), DkgShareDelivery.closeRound1(p2, honest.directory, k2, window, DkgEncryptedHarness.AUTH), + "the retry processes every envelope: no complaint"); + assertTrue(k2.isDestroyed()); + } + + @Test + @DisplayName("A verifier that throws after accepting some envelopes: the retry adds no second copy and no complaint (review C-2)") + void verifierThrowsAfterPartialProgress() { + DkgConfig config = config(2, 5, 1); + List d = dealings(2, 5); + DkgEncryptedHarness honest = DkgEncryptedHarness.fixed(config, d, DkgEncryptedHarness.HONEST); + honest.run(); + DkgParticipant p2 = DkgParticipant.withDealing(config, 2, d.get(1)); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.fromSecret(config, 2, DkgEncryptedHarness.testKey("recipient.2")); + DkgShareDelivery.start(p2, honest.directory, k2, new SecureRandom()); + List window = honest.window(honest.board.get(1)); + int[] calls = {0}; + DkgAdmissionVerifier flaky = new DkgAdmissionVerifier() { + @Override + public boolean authenticate(int sender, byte[] rosterKey, byte[] message, byte[] authenticator) { + if (++calls[0] > 3) throw new IllegalStateException("signature service unavailable"); + return DkgEncryptedHarness.AUTH.authenticate(sender, rosterKey, message, authenticator); + } + + @Override + public boolean roundClosed(DkgConfig c, int round, List m, byte[] e) { + return true; + } + }; + assertThrows(IllegalStateException.class, () -> DkgShareDelivery.closeRound1(p2, honest.directory, k2, window, flaky)); + int partial = 0; + for (int dealer = 1; dealer <= config.n(); dealer++) { + if (dealer != 2) partial += p2.receivedShares(dealer).size(); + } + assertTrue(partial >= 1, "the failed attempt accepted at least one share before throwing"); + assertFalse(k2.isDestroyed()); + assertEquals(1, p2.openRound()); + assertEquals(List.of(), DkgShareDelivery.closeRound1(p2, honest.directory, k2, window, DkgEncryptedHarness.AUTH), + "the identical retry: no complaint"); + for (int dealer = 1; dealer <= config.n(); dealer++) { + if (dealer != 2) assertEquals(1, p2.receivedShares(dealer).size(), "one share from dealer " + dealer); + } + assertTrue(k2.isDestroyed()); + } + + @Test + @DisplayName("start on a started participant is refused before T1: a missing or conflicting own key neither aborts it nor destroys its keys") + void startAgainRefusedBeforeT1() { + DkgConfig config = config(1, 3, 1); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + DkgShareDeliveryKeys otherK2 = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + DkgKeyDirectory dir = directoryOf(config, k2); + DkgKeyDirectory missing = DkgKeyDirectory.fromRound0(config, List.of(), DkgEncryptedHarness.AUTH); + DkgKeyDirectory conflicting = directoryOf(config, k2, otherK2); + assertThrows(FaultAssumptionViolatedException.class, () -> conflicting.requireOwn(k2), "the directory alone gives T1"); + DkgParticipant p2 = DkgParticipant.create(config, 2, new SecureRandom()); + DkgShareDelivery.start(p2, dir, k2, new SecureRandom()); + for (DkgKeyDirectory bad : List.of(missing, conflicting)) { + assertThrows(IllegalStateException.class, () -> DkgShareDelivery.start(p2, bad, k2, new SecureRandom())); + assertFalse(k2.isDestroyed(), "the bound keys are kept"); + assertEquals(1, p2.openRound()); + assertTrue(p2.boundTo(k2, dir), "still bound to the first start's keys and directory"); + } + assertEquals(List.of(), DkgShareDelivery.closeRound1(p2, dir, k2, List.of(), DkgEncryptedHarness.AUTH), + "the run continues: no abort was recorded"); + assertEquals(2, p2.openRound()); + + // A legitimate first start still applies T1: abort, keys destroyed. + DkgShareDeliveryKeys k3 = DkgShareDeliveryKeys.generate(config, 3, new SecureRandom()); + DkgParticipant p3 = DkgParticipant.create(config, 3, new SecureRandom()); + FaultAssumptionViolatedException t1 = assertThrows(FaultAssumptionViolatedException.class, + () -> DkgShareDelivery.start(p3, missing, k3, new SecureRandom())); + assertEquals(FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING, t1.reason()); + assertTrue(k3.isDestroyed()); + // An aborted participant throws its own abort again and changes nothing more. + DkgShareDeliveryKeys fresh = DkgShareDeliveryKeys.generate(config, 3, new SecureRandom()); + assertSame(t1, assertThrows(FaultAssumptionViolatedException.class, + () -> DkgShareDelivery.start(p3, missing, fresh, new SecureRandom()))); + assertFalse(fresh.isDestroyed(), "keys given to an aborted participant are not touched"); + assertEquals(0, p3.openRound()); + } + + @Test + @DisplayName("A retry after partial delivery needs the identical window: changed message or authenticator bytes, added, removed or reordered posts are refused and change nothing") + void retryNeedsIdenticalWindow() { + DkgConfig config = config(2, 5, 1); + List d = dealings(2, 5); + DkgEncryptedHarness honest = DkgEncryptedHarness.fixed(config, d, DkgEncryptedHarness.HONEST); + honest.run(); + DkgParticipant p2 = DkgParticipant.withDealing(config, 2, d.get(1)); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.fromSecret(config, 2, DkgEncryptedHarness.testKey("recipient.2")); + DkgShareDelivery.start(p2, honest.directory, k2, new SecureRandom()); + List window = honest.window(honest.board.get(1)); + int[] calls = {0}; + DkgAdmissionVerifier flaky = new DkgAdmissionVerifier() { + @Override + public boolean authenticate(int sender, byte[] rosterKey, byte[] message, byte[] authenticator) { + if (++calls[0] > 3) throw new IllegalStateException("signature service unavailable"); + return DkgEncryptedHarness.AUTH.authenticate(sender, rosterKey, message, authenticator); + } + + @Override + public boolean roundClosed(DkgConfig c, int round, List m, byte[] e) { + return true; + } + }; + assertThrows(IllegalStateException.class, () -> DkgShareDelivery.closeRound1(p2, honest.directory, k2, window, flaky)); + TreeMap> partial = new TreeMap<>(); + for (int dealer = 1; dealer <= config.n(); dealer++) partial.put(dealer, p2.receivedShares(dealer)); + assertTrue(partial.values().stream().mapToInt(List::size).sum() >= 1, "the failed attempt delivered something"); + + int envelope = -1; + for (int k = 0; k < window.size(); k++) { + if (DkgShareDeliveryCodec.decodeEnvelope(config, window.get(k).message()) != null) { + envelope = k; + break; + } + } + assertTrue(envelope >= 0); + AuthenticatedDkgMessage e = window.get(envelope); + byte[] message = e.message(); + message[message.length - 1] ^= 1; + byte[] authenticator = e.authenticator(); + authenticator[0] ^= 1; + List messageChanged = new ArrayList<>(window); + messageChanged.set(envelope, new AuthenticatedDkgMessage(message, e.authenticator())); + List authenticatorChanged = new ArrayList<>(window); + authenticatorChanged.set(envelope, new AuthenticatedDkgMessage(e.message(), authenticator)); + List added = new ArrayList<>(window); + added.add(e); + List removed = new ArrayList<>(window); + removed.remove(envelope); + List reordered = new ArrayList<>(window); + reordered.add(reordered.remove(0)); + for (List other : List.of(messageChanged, authenticatorChanged, added, removed, reordered)) { + assertNotEquals(HexFormat.of().formatHex(DkgShareDelivery.windowDigest(window)), + HexFormat.of().formatHex(DkgShareDelivery.windowDigest(other))); + assertThrows(IllegalArgumentException.class, + () -> DkgShareDelivery.closeRound1(p2, honest.directory, k2, other, DkgEncryptedHarness.AUTH)); + assertFalse(k2.isDestroyed(), "keys kept"); + assertEquals(1, p2.openRound(), "still at round 1"); + for (int dealer = 1; dealer <= config.n(); dealer++) { + assertEquals(partial.get(dealer), p2.receivedShares(dealer), "nothing more delivered from dealer " + dealer); + } + } + + // The identical window, rebuilt from fresh copies, completes the round. + List identical = new ArrayList<>(); + for (AuthenticatedDkgMessage post : window) identical.add(new AuthenticatedDkgMessage(post.message(), post.authenticator())); + assertEquals(List.of(), DkgShareDelivery.closeRound1(p2, honest.directory, k2, identical, DkgEncryptedHarness.AUTH), + "the identical retry: no complaint"); + for (int dealer = 1; dealer <= config.n(); dealer++) { + if (dealer != 2) assertEquals(1, p2.receivedShares(dealer).size(), "one share from dealer " + dealer); + } + assertTrue(k2.isDestroyed()); + } + + @Test + @DisplayName("The window digest frames every field: moving a byte between message and authenticator, or between posts, changes it") + void windowDigestFraming() { + byte[] ab = {1, 2}; + AuthenticatedDkgMessage split1 = new AuthenticatedDkgMessage(new byte[]{1}, new byte[]{2}); + AuthenticatedDkgMessage split2 = new AuthenticatedDkgMessage(ab, new byte[0]); + AuthenticatedDkgMessage split3 = new AuthenticatedDkgMessage(new byte[0], ab); + Set digests = new HashSet<>(); + for (List w : List.of(List.of(split1), List.of(split2), List.of(split3), + List.of(new AuthenticatedDkgMessage(new byte[]{1}, new byte[0]), new AuthenticatedDkgMessage(new byte[]{2}, new byte[0])), + List.of())) { + assertTrue(digests.add(HexFormat.of().formatHex(DkgShareDelivery.windowDigest(w))), "distinct digest"); + } + assertArrayEquals(DkgShareDelivery.windowDigest(List.of(split1, split2)), + DkgShareDelivery.windowDigest(List.of(new AuthenticatedDkgMessage(new byte[]{1}, new byte[]{2}), split2)), + "equal contents, equal digest"); + } + } + + // ------------------------------------------------------------------ I11, I13, I15 + + @Nested + @DisplayName("I11, I13, I15: the barrier, commitments last and answer scope") + class Timing { + + @Test + @DisplayName("Review F1 negative control: without the barrier the corrupted participant recovers x; with it there are no complaints") + void barrier() { + DkgConfig config = config(1, 3, 1); + List d = dealings(1, 3); + DkgEncryptedHarness late = DkgEncryptedHarness.fixed(config, d, new DkgEncryptedHarness.Hooks() { + @Override + public boolean processedLate(int i, int j) { + return i == 1 && j == 2 || i == 2 && j == 1; + } + }).run(); + assertEquals(2, late.posted(2, DkgMessage.Kind.COMPLAINT).size(), "1 and 2 complain about each other"); + List answers = late.posted(3, DkgMessage.Kind.ANSWER); + assertEquals(2, answers.size(), "both answers are public"); + // Corrupted participant 3: its own shares plus the two public answers (t + 1 = 2 points per dealer). + BigInteger x = BigInteger.ZERO; + for (int dealer = 1; dealer <= 3; dealer++) { + if (dealer == 3) { + x = x.add(d.get(2).share(0)).mod(L); + continue; + } + TreeMap points = new TreeMap<>(); + points.put(3, d.get(dealer - 1).share(3)); + for (DkgMessage a : answers) if (a.sender() == dealer) points.put(a.subject(), a.s()); + x = x.add(interpolateAtZero(points)).mod(L); + } + assertTrue(JubjubPoint.SUBGROUP_GENERATOR.scalarMul(x).projectiveEquals(context(late.participant(3)).jointKey().point()), + "the key is exposed without the barrier"); + + DkgEncryptedHarness withBarrier = DkgEncryptedHarness.fixed(config, d, DkgEncryptedHarness.HONEST).run(); + assertTrue(withBarrier.posted(2, DkgMessage.Kind.COMPLAINT).isEmpty()); + assertTrue(withBarrier.posted(3, DkgMessage.Kind.ANSWER).isEmpty()); + } + + @Test + @DisplayName("D7a: envelopes that miss the cutoff leave the dealer without COMMITMENTS, disqualified, with no honest complaint") + void commitmentsLast() { + DkgConfig config = config(2, 5, 1); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, dealings(2, 5), new DkgEncryptedHarness.Hooks() { + @Override + public boolean missesCutoff(int i, int j) { + return i == 1 && j == 4; + } + }).run(); + assertTrue(h.posted(1, DkgMessage.Kind.COMMITMENTS).stream().noneMatch(m -> m.sender() == 1)); + assertTrue(h.posted(2, DkgMessage.Kind.COMPLAINT).isEmpty(), "no complaint by any honest participant"); + assertEquals(FaultAssumptionViolatedException.Reason.OWN_DEALING_DISQUALIFIED, h.aborted.get(1).reason()); + assertEquals(Set.of(2, 3, 4, 5), context(h.participant(2)).qual()); + // Negative control: a dealer that ignores D7a draws a complaint, and its answer publishes 4's share. + DkgEncryptedHarness ignored = DkgEncryptedHarness.fixed(config, dealings(2, 5), new DkgEncryptedHarness.Hooks() { + @Override + public boolean missesCutoff(int i, int j) { + return i == 1 && j == 4; + } + + @Override + public Set ignoreCommitmentsLast() { + return Set.of(1); + } + }).run(); + assertEquals(1, ignored.posted(2, DkgMessage.Kind.COMPLAINT).size()); + assertEquals(4, ignored.posted(3, DkgMessage.Kind.ANSWER).get(0).subject(), "an honest index is published"); + } + + @Test + @DisplayName("Authenticated junk in the round-1 window (a plaintext SHARE, an early COMPLAINT, garbage) is absent: no throw, no complaint, same transcript (review X-5)") + void junkBroadcastsInRoundOne() { + DkgConfig config = config(1, 3, 1); + List d = dealings(1, 3); + DkgMessage share31 = DkgMessage.pair(config, DkgMessage.Kind.SHARE, 3, 1, d.get(2).share(1), d.get(2).sharePrime(1)); + DkgEncryptedHarness junk = DkgEncryptedHarness.fixed(config, d, new DkgEncryptedHarness.Hooks() { + @Override + public List extra(int round) { + if (round != 1) return List.of(); + return List.of(new DkgEncryptedHarness.Post(3, share31.encode()), + new DkgEncryptedHarness.Post(3, DkgMessage.complaint(config, 3, 1).encode()), + new DkgEncryptedHarness.Post(3, new byte[]{1, 2, 3})); + } + }).run(); + DkgEncryptedHarness honest = DkgEncryptedHarness.fixed(config, d, DkgEncryptedHarness.HONEST).run(); + assertTrue(junk.aborted.isEmpty(), "aborts: " + junk.aborted); + assertTrue(junk.posted(2, DkgMessage.Kind.COMPLAINT).isEmpty()); + assertArrayEquals(DkgTranscript.of(config, honest.transcriptMessages()).digest(), + DkgTranscript.of(config, junk.transcriptMessages()).digest()); + } + + @Test + @DisplayName("I15 (review F3): a corrupted complaint draws an answer at the corrupted index only, timely or with withheld commitments") + void answerScope() { + DkgConfig config = config(1, 3, 1); + // (i) Timely delivery: corrupted 3 complains about honest qualified dealer 1. + DkgEncryptedHarness timely = DkgEncryptedHarness.fixed(config, dealings(1, 3), new DkgEncryptedHarness.Hooks() { + @Override + public List extra(int round) { + return round == 2 ? List.of(new DkgEncryptedHarness.Post(3, DkgMessage.complaint(config, 3, 1).encode())) : List.of(); + } + }).run(); + List answers = timely.posted(3, DkgMessage.Kind.ANSWER); + assertEquals(1, answers.size()); + assertEquals(1, answers.get(0).sender()); + assertEquals(3, answers.get(0).subject(), "at the corrupted index"); + assertEquals(Set.of(1, 2, 3), context(timely.participant(1)).qual()); + // (ii) Dealer 1's envelope to 2 missed the cutoff, so it withheld COMMITMENTS; corrupted 3 complains anyway. + DkgEncryptedHarness withheld = DkgEncryptedHarness.fixed(config, dealings(1, 3), new DkgEncryptedHarness.Hooks() { + @Override + public boolean missesCutoff(int i, int j) { + return i == 1 && j == 2; + } + + @Override + public List extra(int round) { + return round == 2 ? List.of(new DkgEncryptedHarness.Post(3, DkgMessage.complaint(config, 3, 1).encode())) : List.of(); + } + }).run(); + List w = withheld.posted(3, DkgMessage.Kind.ANSWER); + assertEquals(1, w.size()); + assertEquals(3, w.get(0).subject(), "answers the corrupted complainer before A2"); + assertEquals(FaultAssumptionViolatedException.Reason.OWN_DEALING_DISQUALIFIED, withheld.aborted.get(1).reason()); + assertEquals(Set.of(2, 3), context(withheld.participant(2)).qual()); + assertTrue(withheld.posted(2, DkgMessage.Kind.COMPLAINT).stream().noneMatch(m -> m.sender() == 2), "honest 2 never complains"); + } + } + + static BigInteger interpolateAtZero(TreeMap points) { + int[] xs = points.keySet().stream().mapToInt(Integer::intValue).toArray(); + BigInteger[] lambda = ThresholdMath.lagrangeAt(xs, 0); + BigInteger acc = BigInteger.ZERO; + int k = 0; + for (BigInteger y : points.values()) acc = acc.add(lambda[k++].multiply(y)).mod(L); + return acc; + } + + // ------------------------------------------------------------------ review M-1 / S-1 and further negatives + + @Nested + @DisplayName("Front-running and further binding negatives (reviews M-1, S-1, S-4, M-6)") + class Hardening { + + @Test + @DisplayName("Unauthentic byte-identical copies posted first shadow neither an envelope nor COMMITMENTS") + void frontRunning() { + DkgConfig config = config(1, 3, 1); + List d = dealings(1, 3); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, d, new DkgEncryptedHarness.Hooks() { + @Override + public List before(int round, DkgEncryptedHarness harness) { + if (round != 1) return List.of(); + List copies = new ArrayList<>(); + for (Object[] e : harness.sealed) { + int i = (int) e[0], j = (int) e[1]; + if (i == 1 && j == 2 || i == 2 && j == 1) copies.add(new DkgEncryptedHarness.Post(3, (byte[]) e[2])); + } + ThresholdVss.Dealing d1 = d.get(0); + copies.add(new DkgEncryptedHarness.Post(3, + DkgMessage.points(config, DkgMessage.Kind.COMMITMENTS, 1, d1.commitments()).encode())); + return copies; + } + }).run(); + assertTrue(h.aborted.isEmpty(), "aborts: " + h.aborted); + assertTrue(h.posted(2, DkgMessage.Kind.COMPLAINT).isEmpty(), "no complaints"); + assertEquals(Set.of(1, 2, 3), context(h.participant(1)).qual()); + DkgHarness plain = DkgHarness.fixed(config, d, DkgHarness.HONEST).run(); + assertArrayEquals(DkgTranscript.of(config, plain.transcriptMessages()).digest(), + DkgTranscript.of(config, h.transcriptMessages()).digest()); + } + + @Test + @DisplayName("A forged, distinct COMMITMENTS for an honest dealer under another author is ignored (review M-9)") + void forgedCommitmentsIgnored() { + DkgConfig config = config(1, 3, 1); + List d = dealings(1, 3); + ThresholdVss.Dealing other = DkgHarness.dealings(1, 3, 999).get(0); + byte[] forged = DkgMessage.points(config, DkgMessage.Kind.COMMITMENTS, 1, other.commitments()).encode(); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, d, new DkgEncryptedHarness.Hooks() { + @Override + public List before(int round, DkgEncryptedHarness harness) { + return round == 1 ? List.of(new DkgEncryptedHarness.Post(3, forged)) : List.of(); + } + }).run(); + assertTrue(h.aborted.isEmpty(), "aborts: " + h.aborted); + assertTrue(h.posted(2, DkgMessage.Kind.COMPLAINT).isEmpty()); + assertEquals(Set.of(1, 2, 3), context(h.participant(1)).qual()); + } + + @Test + @DisplayName("A copied announcement key: the copier gets T1 (it is not its own), and nobody else is affected") + void copiedKey() { + DkgConfig config = config(1, 3, 1); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, dealings(1, 3), new DkgEncryptedHarness.Hooks() { + @Override + public List announcement(int j, byte[] announcement) { + if (j != 3) return List.of(announcement); + return List.of(DkgShareDeliveryCodec.announcement(config, 3, publicKeyOf(2))); + } + }).run(); + assertEquals(FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING, h.aborted.get(3).reason()); + assertTrue(h.posted(2, DkgMessage.Kind.COMPLAINT).isEmpty()); + assertEquals(Set.of(1, 2), context(h.participant(1)).qual()); + } + + @Test + @DisplayName("Cross-session replay with the header rewritten fails on info, even with the same recipient key") + void crossSessionRewritten() { + DkgConfig attempt1 = config(1, 3, 1); + DkgConfig attempt2 = config(1, 3, 2); + DkgEncryptedHarness other = DkgEncryptedHarness.fixed(attempt2, dealings(1, 3), DkgEncryptedHarness.HONEST).run(); + byte[] replay = null; + for (Object[] e : other.sealed) if ((int) e[0] == 1 && (int) e[1] == 2) replay = ((byte[]) e[2]).clone(); + int at = DkgShareDeliveryCodec.TAG_E.length; + System.arraycopy(attempt1.session(), 0, replay, at, 32); // header now names attempt 1 + assertTrue(DkgShareDeliveryCodec.decodeEnvelope(attempt1, replay) != null, "well-formed for attempt 1"); + byte[] forged = replay; + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(attempt1, dealings(1, 3), new DkgEncryptedHarness.Hooks() { + @Override + public List envelope(int i, int j, byte[] envelope) { + return i == 1 && j == 2 ? List.of(forged) : List.of(envelope); + } + }).run(); + assertEquals(1, h.posted(2, DkgMessage.Kind.COMPLAINT).size(), "the replayed share is absent"); + } + + @Test + @DisplayName("info is exactly TAG_I ‖ session ‖ i ‖ j, and a non-canonical enc is refused by the codec") + void infoAndCanonicalEnc() { + DkgConfig config = config(1, 3, 1); + byte[] info = DkgShareDeliveryCodec.info(config, 1, 2); + assertArrayEquals(Hpke.concat(Hpke.ascii("zeroj.dkg-share-delivery-hpke.v1.info"), config.session(), new byte[]{1, 2}), info); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, dealings(1, 3), DkgEncryptedHarness.HONEST).run(); + byte[] good = (byte[]) h.sealed.get(0)[2]; + byte[] high = good.clone(); + high[DkgShareDeliveryCodec.TAG_E.length + 34 + 31] |= (byte) 0x80; + assertEquals(null, DkgShareDeliveryCodec.decodeEnvelope(config, high), "bit 255 set"); + byte[] bigU = good.clone(); + Arrays.fill(bigU, DkgShareDeliveryCodec.TAG_E.length + 34, DkgShareDeliveryCodec.TAG_E.length + 66, (byte) 0xFF); + bigU[DkgShareDeliveryCodec.TAG_E.length + 65] = 0x7F; // u = 2^255 − 1 ≥ p + assertEquals(null, DkgShareDeliveryCodec.decodeEnvelope(config, bigU), "u ≥ p"); + } + + @Test + @DisplayName("The public start draws a fresh ephemeral for every envelope and every call") + void freshEphemerals() { + DkgConfig config = config(2, 5, 1); + List ks = new ArrayList<>(); + List window = new ArrayList<>(); + for (int j = 1; j <= 5; j++) { + ks.add(DkgShareDeliveryKeys.generate(config, j, new SecureRandom())); + window.add(post(config, j, ks.get(j - 1).announcement())); + } + DkgKeyDirectory dir = DkgKeyDirectory.fromRound0(config, window, DkgEncryptedHarness.AUTH); + Set encs = new HashSet<>(); + for (int run = 0; run < 2; run++) { + DkgParticipant p1 = DkgParticipant.withDealing(config, 1, dealings(2, 5).get(0)); + for (byte[] e : DkgShareDelivery.start(p1, dir, ks.get(0), new SecureRandom()).envelopes()) { + assertTrue(encs.add(HexFormat.of().formatHex(DkgShareDeliveryCodec.decodeEnvelope(config, e).enc())), "enc reused"); + } + } + assertEquals(8, encs.size()); + } + } + + // ------------------------------------------------------------------ review Z-1, Z-4 + + @Nested + @DisplayName("Platform faults fail closed: never absence, never a complaint (review Z-1)") + class PlatformFaults { + + @Test + @DisplayName("HPKE: tag failure and small-order enc are input failures; a missing provider is not") + void hpkeClassification() throws Exception { + byte[] skR = DkgEncryptedHarness.testKey("recipient.2"); + byte[] pkR = X25519Bytes.publicFromPrivate(skR); + byte[] info = Hpke.ascii("classification"); + Hpke.Sealed sealed = Hpke.sealBase(pkR, info, new byte[0], new byte[100], new SecureRandom()); + byte[] tampered = sealed.ct().clone(); + tampered[5] ^= 1; + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(sealed.enc(), skR, info, new byte[0], tampered)); + byte[] smallOrder = new byte[32]; + smallOrder[0] = 1; + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(smallOrder, skR, info, new byte[0], sealed.ct())); + assertThrows(Hpke.HpkeException.class, () -> Hpke.sealBase(smallOrder, info, new byte[0], new byte[100], new SecureRandom())); + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(new byte[31], skR, info, new byte[0], sealed.ct())); + DkgEncryptedHarness.withoutProvider("SunJCE", () -> { + assertThrows(IllegalStateException.class, () -> Hpke.openBase(sealed.enc(), skR, pkR, info, new byte[0], sealed.ct())); + assertThrows(IllegalStateException.class, () -> Hpke.sealBase(pkR, info, new byte[0], new byte[100], new SecureRandom())); + }); + DkgEncryptedHarness.withoutProvider("SunEC", () -> { + assertThrows(IllegalStateException.class, () -> Hpke.openBase(sealed.enc(), skR, pkR, info, new byte[0], sealed.ct())); + assertThrows(IllegalStateException.class, () -> X25519Bytes.passesSmallOrderProbe(pkR), + "the probe never reports a fault as small order"); + }); + assertArrayEquals(new byte[100], Hpke.openBase(sealed.enc(), skR, info, new byte[0], sealed.ct()), "restored"); + } + + @Test + @DisplayName("With BouncyCastle preferred: small-order enc and keys are still absence, not a stall; honest envelopes still open (review R2-1)") + void preferredThirdPartyProvider() { + DkgConfig config = config(1, 3, 1); + List d = dealings(1, 3); + byte[] zeroEnc = new byte[32]; + DkgEncryptedHarness.withPreferredProvider(new BouncyCastleProvider(), () -> { + // Round 0: corrupted 3 announces u = 0; round 1: it sends u = 0 as enc to everyone. + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, d, new DkgEncryptedHarness.Hooks() { + @Override + public List announcement(int j, byte[] announcement) { + return j == 3 ? List.of(DkgShareDeliveryCodec.announcement(config, 3, zeroEnc)) : List.of(announcement); + } + + @Override + public List extra(int round) { + if (round != 1) return List.of(); + return List.of( + new DkgEncryptedHarness.Post(3, DkgShareDeliveryCodec.envelope(config, 3, 1, zeroEnc, new byte[DkgShareDeliveryCodec.CT_LENGTH])), + new DkgEncryptedHarness.Post(3, DkgShareDeliveryCodec.envelope(config, 3, 2, zeroEnc, new byte[DkgShareDeliveryCodec.CT_LENGTH]))); + } + }).run(); + assertFalse(h.directory.hasKey(3), "a small-order key is no key"); + assertEquals(FaultAssumptionViolatedException.Reason.OWN_KEY_ANNOUNCEMENT_MISSING, h.aborted.get(3).reason()); + assertEquals(Set.of(3), h.aborted.keySet(), "only 3 aborts; 1 and 2 closed round 1 past the small-order envelopes"); + assertTrue(h.posted(2, DkgMessage.Kind.COMPLAINT).isEmpty(), "3 dealt nothing, so nobody complains"); + assertEquals(Set.of(1, 2), context(h.participant(1)).qual()); + byte[] skR = DkgEncryptedHarness.testKey("recipient.2"); + assertThrows(Hpke.HpkeException.class, + () -> Hpke.openBase(zeroEnc, skR, new byte[1], new byte[0], new byte[DkgShareDeliveryCodec.CT_LENGTH])); + assertFalse(X25519Bytes.passesSmallOrderProbe(zeroEnc)); + }); + } + + @Test + @DisplayName("closeRound1 with a failing AEAD/HKDF provider: no complaint, keys kept, round 1 open; the retry succeeds") + void closeRound1() { + DkgConfig config = config(2, 5, 1); + List d = dealings(2, 5); + DkgEncryptedHarness honest = DkgEncryptedHarness.fixed(config, d, DkgEncryptedHarness.HONEST); + honest.run(); + DkgParticipant p2 = DkgParticipant.withDealing(config, 2, d.get(1)); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.fromSecret(config, 2, DkgEncryptedHarness.testKey("recipient.2")); + DkgShareDelivery.start(p2, honest.directory, k2, new SecureRandom()); + List window = honest.window(honest.board.get(1)); + for (String provider : List.of("SunJCE", "SunEC")) { + DkgEncryptedHarness.withoutProvider(provider, () -> assertThrows(IllegalStateException.class, + () -> DkgShareDelivery.closeRound1(p2, honest.directory, k2, window, DkgEncryptedHarness.AUTH), provider)); + assertFalse(k2.isDestroyed(), provider); + assertEquals(1, p2.openRound(), provider); + } + assertEquals(List.of(), DkgShareDelivery.closeRound1(p2, honest.directory, k2, window, DkgEncryptedHarness.AUTH)); + assertTrue(k2.isDestroyed()); + } + + @Test + @DisplayName("start with a failing provider changes nothing; the directory refuses to build rather than drop keys") + void startAndDirectory() { + DkgConfig config = config(1, 3, 1); + DkgShareDeliveryKeys k2 = DkgShareDeliveryKeys.generate(config, 2, new SecureRandom()); + List round0 = List.of(post(config, 2, k2.announcement())); + DkgEncryptedHarness.withoutProvider("SunEC", () -> assertThrows(IllegalStateException.class, + () -> DkgKeyDirectory.fromRound0(config, round0, DkgEncryptedHarness.AUTH))); + DkgKeyDirectory dir = DkgKeyDirectory.fromRound0(config, round0, DkgEncryptedHarness.AUTH); + DkgParticipant p2 = DkgParticipant.create(config, 2, new SecureRandom()); + DkgEncryptedHarness.withoutProvider("SunJCE", () -> assertThrows(IllegalStateException.class, + () -> DkgShareDelivery.start(p2, dir, k2, new SecureRandom()))); + assertEquals(0, p2.openRound()); + assertFalse(p2.boundToEncryptedDelivery()); + assertFalse(k2.isDestroyed()); + DkgShareDelivery.start(p2, dir, k2, new SecureRandom()); + assertEquals(1, p2.openRound(), "the retry starts the participant"); + } + } + + // ------------------------------------------------------------------ I14 + + @Nested + @DisplayName("I14: no self-envelope and exposure counting") + class Exposure { + + @Test + @DisplayName("No envelope is addressed to its sender; leaked recipient keys expose exactly the dealers the counting rule says") + void countingRule() throws Exception { + int t = 2, n = 5; + DkgConfig config = config(t, n, 1); + List d = dealings(t, n); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(config, d, DkgEncryptedHarness.HONEST).run(); + assertTrue(h.sealed.stream().noneMatch(e -> (int) e[0] == (int) e[1])); + for (Set leaked : List.of(Set.of(1, 2, 3), Set.of(1, 2, 3, 4), Set.of(4, 5), Set.of(1, 2, 3, 4, 5))) { + for (int dealer = 1; dealer <= n; dealer++) { + TreeMap points = new TreeMap<>(); + for (Object[] e : h.sealed) { + int i = (int) e[0], j = (int) e[1]; + if (i != dealer || !leaked.contains(j)) continue; + DkgShareDeliveryCodec.Envelope env = DkgShareDeliveryCodec.decodeEnvelope(config, (byte[]) e[2]); + byte[] pt = Hpke.openBase(env.enc(), h.secrets.get(j), DkgShareDeliveryCodec.info(config, i, j), new byte[0], env.ct()); + points.put(j, DkgMessage.decode(config, pt).s()); + } + Set rule = new TreeSet<>(leaked); + rule.remove(dealer); + assertEquals(rule, points.keySet(), "known indices for dealer " + dealer); + if (points.size() >= t + 1) { + assertEquals(d.get(dealer - 1).share(0), interpolateAtZero(points), "z_" + dealer + " reconstructed"); + } + } + } + } + } + + // ------------------------------------------------------------------ API surface + + @Test + @DisplayName("Public delivery types are final with no public constructor; HPKE, X25519 and the codec stay package-private") + void apiSurface() { + for (Class c : List.of(DkgShareDelivery.class, DkgShareDeliveryKeys.class, DkgKeyDirectory.class, + DkgShareDelivery.SealedDealing.class)) { + assertTrue(Modifier.isFinal(c.getModifiers()), c + " final"); + assertFalse(c.isRecord(), c + " not a record"); + for (Constructor k : c.getDeclaredConstructors()) { + assertFalse(Modifier.isPublic(k.getModifiers()) || Modifier.isProtected(k.getModifiers()), c + " constructor"); + } + } + for (Class c : List.of(Hpke.class, X25519Bytes.class, DkgShareDeliveryCodec.class)) { + assertFalse(Modifier.isPublic(c.getModifiers()), c + " package-private"); + } + // Deterministic seams stay package-private: production uses fresh randomness only. + for (Method m : DkgShareDelivery.class.getDeclaredMethods()) { + boolean seam = Arrays.asList(m.getParameterTypes()).contains(IntFunction.class) + || m.getName().equals("sealOne"); + if (seam) assertFalse(Modifier.isPublic(m.getModifiers()), m + " must not be public"); + } + for (Method m : DkgShareDeliveryKeys.class.getDeclaredMethods()) { + if (m.getName().equals("fromSecret") || m.getName().equals("secretFor")) { + assertFalse(Modifier.isPublic(m.getModifiers()), m + " must not be public"); + } + } + } +} diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/ElGamalBenchmark.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/ElGamalBenchmark.java index 6617f809..45eaecbe 100644 --- a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/ElGamalBenchmark.java +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/ElGamalBenchmark.java @@ -97,4 +97,58 @@ void dkg() { System.out.printf("| (%d, %d) | %.0f ms | %.0f ms |%n", tn[0], tn[1], ms, ms / tn[1]); } } + + @Test + void dkgShareDelivery() throws Exception { + // ADR-0054: HPKE seal/open per envelope, then whole encrypted runs against plain runs. + DkgConfig config = DkgHarness.config(2, 5, "bench-delivery", 1); + byte[] skR = new byte[32]; + RNG.nextBytes(skR); + byte[] pkR = X25519Bytes.publicFromPrivate(skR); + byte[] info = DkgShareDeliveryCodec.info(config, 1, 2); + byte[] share = new byte[DkgShareDeliveryCodec.SHARE_LENGTH]; + for (int i = 0; i < 3_000; i++) { // warm-up + Hpke.Sealed w = Hpke.sealBase(pkR, info, new byte[0], share, RNG); + Hpke.openBase(w.enc(), skR, info, new byte[0], w.ct()); + } + Hpke.Sealed sealed = Hpke.sealBase(pkR, info, new byte[0], share, RNG); + double seal = microsPerOp(5_000, () -> { + try { + Hpke.sealBase(pkR, info, new byte[0], share, RNG); + } catch (Hpke.HpkeException e) { + throw new IllegalStateException(e); + } + }); + double open = microsPerOp(5_000, () -> { + try { + Hpke.openBase(sealed.enc(), skR, pkR, info, new byte[0], sealed.ct()); + } catch (Hpke.HpkeException e) { + throw new IllegalStateException(e); + } + }); + double probe = microsPerOp(5_000, () -> X25519Bytes.passesSmallOrderProbe(pkR)); + System.out.println(); + System.out.println("| HPKE (DHKEM X25519, HKDF-SHA256, ChaCha20Poly1305), 100-byte SHARE | µs/op |"); + System.out.println("|---|---:|"); + System.out.printf("| SealBase (one envelope) | %.0f |%n", seal); + System.out.printf("| OpenBase (one envelope) | %.0f |%n", open); + System.out.printf("| Announcement small-order probe | %.0f |%n", probe); + System.out.println(); + System.out.println("| DKG (t, n) | Plain run | Encrypted run | Added per participant |"); + System.out.println("|---|---:|---:|---:|"); + for (int[] tn : new int[][]{{1, 3}, {2, 5}, {3, 7}, {5, 11}, {10, 21}}) { + DkgConfig c = DkgHarness.config(tn[0], tn[1], "bench-delivery", tn[1]); + List d = DkgHarness.dealings(tn[0], tn[1], tn[1]); + DkgHarness.fixed(c, d, DkgHarness.HONEST).run(); + DkgEncryptedHarness.fixed(c, d, DkgEncryptedHarness.HONEST).run(); // warm-up + long a = System.nanoTime(); + DkgHarness.fixed(c, d, DkgHarness.HONEST).run(); + double plainMs = (System.nanoTime() - a) / 1e6; + long b = System.nanoTime(); + DkgEncryptedHarness h = DkgEncryptedHarness.fixed(c, d, DkgEncryptedHarness.HONEST).run(); + double encMs = (System.nanoTime() - b) / 1e6; + if (!h.aborted.isEmpty()) throw new AssertionError("aborted: " + h.aborted); + System.out.printf("| (%d, %d) | %.0f ms | %.0f ms | %.1f ms |%n", tn[0], tn[1], plainMs, encMs, (encMs - plainMs) / tn[1]); + } + } } diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeDifferentialTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeDifferentialTest.java new file mode 100644 index 00000000..c879fd7c --- /dev/null +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeDifferentialTest.java @@ -0,0 +1,125 @@ +package org.zeroj.circuit.lib.jubjub; + +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.crypto.hpke.HPKE; +import org.bouncycastle.crypto.hpke.HPKEContextWithEncapsulation; +import org.bouncycastle.crypto.params.X25519PrivateKeyParameters; +import org.bouncycastle.crypto.params.X25519PublicKeyParameters; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * ADR-0054 M1: ZeroJ's {@link Hpke} against BouncyCastle 1.83's independent + * {@code org.bouncycastle.crypto.hpke.HPKE} for the same suite, in both directions, and the + * negative cases of the milestone. + */ +class HpkeDifferentialTest { + + private static final HPKE BC = new HPKE(HPKE.mode_base, HPKE.kem_X25519_SHA256, HPKE.kdf_HKDF_SHA256, + HPKE.aead_CHACHA20_POLY1305); + + private static AsymmetricCipherKeyPair bcPair(byte[] sk) { + X25519PrivateKeyParameters priv = new X25519PrivateKeyParameters(sk, 0); + return new AsymmetricCipherKeyPair(priv.generatePublicKey(), priv); + } + + @Test + @DisplayName("ZeroJ seal → BouncyCastle open, and BouncyCastle seal → ZeroJ open, on random keys, info, aad and plaintexts") + void bothDirections() throws Exception { + SecureRandom rng = new SecureRandom(); + Random sizes = new Random(9180); + for (int i = 0; i < 200; i++) { + byte[] skR = new byte[32]; + rng.nextBytes(skR); + byte[] pkR = X25519Bytes.publicFromPrivate(skR); + assertArrayEquals(((X25519PublicKeyParameters) bcPair(skR).getPublic()).getEncoded(), pkR, "public key"); + byte[] info = random(rng, sizes.nextInt(80)); + byte[] aad = random(rng, sizes.nextInt(3) == 0 ? 0 : sizes.nextInt(40)); + byte[] pt = random(rng, sizes.nextInt(300)); + + Hpke.Sealed ours = Hpke.sealBase(pkR, info, aad, pt, rng); + assertArrayEquals(pt, BC.open(ours.enc(), bcPair(skR), info, aad, ours.ct(), null, null, null), "BC opens ZeroJ"); + + byte[][] theirs = BC.seal(new X25519PublicKeyParameters(pkR, 0), info, aad, pt, null, null, null); + byte[] ct = theirs[0].length == pt.length + Hpke.N_T ? theirs[0] : theirs[1]; + byte[] enc = ct == theirs[0] ? theirs[1] : theirs[0]; + assertEquals(Hpke.N_ENC, enc.length); + assertArrayEquals(pt, Hpke.openBase(enc, skR, info, aad, ct), "ZeroJ opens BC"); + + // Same ephemeral on both sides: identical bytes. + byte[] skE = new byte[32]; + rng.nextBytes(skE); + Hpke.Sealed fixed = Hpke.sealBaseWithEphemeral(skE, pkR, info, aad, pt); + // BouncyCastle's SetupBaseS with an explicit ephemeral pair (its seal(..., kpS) argument is the + // Auth-mode sender key, not the ephemeral). + HPKEContextWithEncapsulation bcContext = BC.setupBaseS(new X25519PublicKeyParameters(pkR, 0), info, bcPair(skE)); + assertArrayEquals(bcContext.getEncapsulation(), fixed.enc()); + assertArrayEquals(bcContext.seal(aad, pt), fixed.ct()); + } + } + + @Test + @DisplayName("Negatives: tampered enc or ct, wrong info, aad or key, small-order and wrong-length enc all fail") + void negatives() throws Exception { + SecureRandom rng = new SecureRandom(); + byte[] skR = random(rng, 32); + byte[] pkR = X25519Bytes.publicFromPrivate(skR); + byte[] info = "info".getBytes(); + byte[] pt = random(rng, 100); + Hpke.Sealed s = Hpke.sealBase(pkR, info, new byte[0], pt, rng); + assertArrayEquals(pt, Hpke.openBase(s.enc(), skR, info, new byte[0], s.ct())); + + for (int i = 0; i < s.ct().length; i++) { + byte[] ct = s.ct().clone(); + ct[i] ^= 1; + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(s.enc(), skR, info, new byte[0], ct), "ct byte " + i); + } + for (int i = 0; i < 31; i++) { // byte 31 bit 0 flip keeps a different but valid u; covered below + byte[] enc = s.enc().clone(); + enc[i] ^= 1; + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(enc, skR, info, new byte[0], s.ct()), "enc byte " + i); + } + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(s.enc(), skR, "infx".getBytes(), new byte[0], s.ct())); + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(s.enc(), skR, info, new byte[]{0}, s.ct())); + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(s.enc(), random(rng, 32), info, new byte[0], s.ct())); + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(Arrays.copyOf(s.enc(), 31), skR, info, new byte[0], s.ct())); + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(s.enc(), skR, info, new byte[0], Arrays.copyOf(s.ct(), 115))); + // Small-order enc: the DH output is all-zero, refused (RFC 9180 §7.1.4). + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(new byte[32], skR, info, new byte[0], s.ct())); + byte[] one = new byte[32]; + one[0] = 1; + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(one, skR, info, new byte[0], s.ct())); + // Sealing to a small-order recipient key fails for the sender too. + assertThrows(Hpke.HpkeException.class, () -> Hpke.sealBase(new byte[32], info, new byte[0], pt, rng)); + // Non-canonical enc with the same reduced value is a different encapsulation (kem_context binds the bytes). + byte[] highBit = s.enc().clone(); + highBit[31] ^= (byte) 0x80; + assertThrows(Hpke.HpkeException.class, () -> Hpke.openBase(highBit, skR, info, new byte[0], s.ct())); + } + + @Test + @DisplayName("Fresh ephemeral per seal: two seals of the same message never share enc or ct") + void freshEphemeral() throws Exception { + SecureRandom rng = new SecureRandom(); + byte[] pkR = X25519Bytes.publicFromPrivate(random(rng, 32)); + byte[] pt = random(rng, 100); + Hpke.Sealed a = Hpke.sealBase(pkR, new byte[0], new byte[0], pt, rng); + Hpke.Sealed b = Hpke.sealBase(pkR, new byte[0], new byte[0], pt, rng); + assertEquals(false, Arrays.equals(a.enc(), b.enc())); + assertEquals(false, Arrays.equals(a.ct(), b.ct())); + } + + private static byte[] random(SecureRandom rng, int n) { + byte[] b = new byte[n]; + rng.nextBytes(b); + return b; + } +} diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeFailureWipeTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeFailureWipeTest.java new file mode 100644 index 00000000..3c1eda59 --- /dev/null +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeFailureWipeTest.java @@ -0,0 +1,278 @@ +package org.zeroj.circuit.lib.jubjub; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import javax.crypto.KDF; +import javax.crypto.KDFParameters; +import javax.crypto.KDFSpi; +import javax.crypto.SecretKey; +import java.security.GeneralSecurityException; +import java.security.InvalidAlgorithmParameterException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.ProviderException; +import java.security.Security; +import java.security.spec.AlgorithmParameterSpec; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * Review F4: when HKDF fails part-way through the HPKE key schedule, every secret array ZeroJ + * owns is still wiped. + *

    + *
  • {@link Seam} fails a chosen derivation through {@link Hpke.Hkdf}, on any JDK.
  • + *
  • The JCA tests fail it inside a real provider, end to end through SealBase/OpenBase, and + * also check that the failure stays a platform fault ({@link IllegalStateException}), never + * an input failure. JDKs that accept only signed JCE providers (Oracle JDK and GraalVM) + * skip them; OpenJDK builds run them.
  • + *
+ * Tests in this module run sequentially, and the providers are restored afterwards. + */ +public class HpkeFailureWipeTest { // public: JCA instantiates the nested provider classes reflectively + + /** + * The HKDF derivations of one SealBase, in order (RFC 9180 §4.1, §5.1): 1 eae_prk, 2 + * shared_secret, 3 psk_id_hash, 4 info_hash, 5 secret, 6 key, 7 base_nonce. 3 and 4 are public. + */ + private static final String[] LABELS = {"eae_prk", "shared_secret", "psk_id_hash", "info_hash", "secret", "key", "base_nonce"}; + private static final boolean[] SECRET = {true, true, false, false, true, true, true}; + + private static Provider real; + + /** Serves HKDF-SHA256 by delegating to SunJCE, failing at derivation {@link #failAt}. */ + public static final class FaultyKdfProvider extends Provider { + public FaultyKdfProvider() { + super("ZeroJFaultyKdf", "1", "HKDF fault injection for HpkeFailureWipeTest"); + put("KDF.HKDF-SHA256", FaultyKdf.class.getName()); + } + } + + /** SunJCE without its KDF services, so a failing HKDF is not retried with SunJCE. */ + public static final class SunJceWithoutKdf extends Provider { + public SunJceWithoutKdf() { + super("SunJCE", "1", "SunJCE services except KDF"); + real.forEach((k, v) -> { + String key = k.toString(); + if (!key.startsWith("KDF.") && !key.startsWith("Alg.Alias.KDF.")) put(k, v); + }); + } + } + + public static final class FaultyKdf extends KDFSpi { + static final List returned = new ArrayList<>(); + static int calls; + static int failAt; + + public FaultyKdf(KDFParameters parameters) throws InvalidAlgorithmParameterException { + super(parameters); + } + + @Override + protected KDFParameters engineGetParameters() { + return null; + } + + @Override + protected SecretKey engineDeriveKey(String algorithm, AlgorithmParameterSpec spec) throws NoSuchAlgorithmException { + throw new NoSuchAlgorithmException("not used by Hpke"); + } + + @Override + protected byte[] engineDeriveData(AlgorithmParameterSpec spec) throws InvalidAlgorithmParameterException { + if (++calls == failAt) throw new ProviderException("injected HKDF failure at derivation " + calls); + try { + byte[] out = KDF.getInstance("HKDF-SHA256", real).deriveData(spec); + returned.add(out); + return out; + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + } + + private interface Body { + void run() throws Exception; + } + + /** + * Runs {@code body} with the faulty KDF first. When a failure is injected, SunJCE's KDF is + * hidden so JCA cannot retry with it; with none (the control), the real SunJCE stays for the + * AEAD. The providers are restored afterwards. + */ + private static void withFaultyKdf(int failAt, Body body) throws Exception { + Provider[] all = Security.getProviders(); + int position = -1; + for (int k = 0; k < all.length; k++) if (all[k].getName().equals("SunJCE")) position = k + 1; + real = Security.getProvider("SunJCE"); + FaultyKdf.calls = 0; + FaultyKdf.failAt = failAt; + FaultyKdf.returned.clear(); + if (failAt != 0) { + Security.removeProvider("SunJCE"); + Security.insertProviderAt(new SunJceWithoutKdf(), position); + } + Security.insertProviderAt(new FaultyKdfProvider(), 1); + try { + body.run(); + } finally { + Security.removeProvider("ZeroJFaultyKdf"); + if (failAt != 0) { + Security.removeProvider("SunJCE"); + Security.insertProviderAt(real, position); + } + } + assertEquals(real, Security.getProvider("SunJCE"), "SunJCE restored"); + } + + private static void assertSecretsWiped(String when) { + for (int j = 0; j < FaultyKdf.returned.size(); j++) { + if (SECRET[j]) { + assertTrue(X25519Bytes.isAllZero(FaultyKdf.returned.get(j)), LABELS[j] + " retained " + when); + } + } + } + + /** An HKDF over the JDK one that fails at derivation {@code failAt} and records what it returns. */ + private static final class FailingHkdf implements Hpke.Hkdf { + final List returned = new ArrayList<>(); + final int failAt; + int calls; + + FailingHkdf(int failAt) { + this.failAt = failAt; + } + + private byte[] record(byte[] out) { + returned.add(out); + return out; + } + + @Override + public byte[] extract(byte[] salt, byte[] ikm) throws GeneralSecurityException { + if (++calls == failAt) throw new GeneralSecurityException("injected failure at derivation " + calls); + return record(Hpke.JDK_HKDF.extract(salt, ikm)); + } + + @Override + public byte[] expand(byte[] prk, byte[] info, int length) throws GeneralSecurityException { + if (++calls == failAt) throw new GeneralSecurityException("injected failure at derivation " + calls); + return record(Hpke.JDK_HKDF.expand(prk, info, length)); + } + } + + @Nested + @DisplayName("Through the Hkdf seam (any JDK)") + class Seam { + + private final byte[] dh = DkgEncryptedHarness.testKey("wipe.dh"); + private final byte[] sharedSecret = DkgEncryptedHarness.testKey("wipe.shared"); + + @Test + @DisplayName("ExtractAndExpand: a failure expanding shared_secret still wipes eae_prk") + void extractAndExpand() { + FailingHkdf hkdf = new FailingHkdf(2); + assertThrows(GeneralSecurityException.class, () -> Hpke.extractAndExpand(hkdf, dh, new byte[64])); + assertEquals(1, hkdf.returned.size()); + assertTrue(X25519Bytes.isAllZero(hkdf.returned.get(0)), "eae_prk"); + } + + @Test + @DisplayName("KeySchedule: a failure at key wipes secret; at base_nonce wipes secret and key") + void keySchedule() { + // Derivations: 1 psk_id_hash, 2 info_hash (both public), 3 secret, 4 key, 5 base_nonce. + FailingHkdf atKey = new FailingHkdf(4); + assertThrows(GeneralSecurityException.class, () -> Hpke.keySchedule(atKey, sharedSecret, new byte[]{1})); + assertTrue(X25519Bytes.isAllZero(atKey.returned.get(2)), "secret"); + FailingHkdf atNonce = new FailingHkdf(5); + assertThrows(GeneralSecurityException.class, () -> Hpke.keySchedule(atNonce, sharedSecret, new byte[]{1})); + assertTrue(X25519Bytes.isAllZero(atNonce.returned.get(2)), "secret"); + assertTrue(X25519Bytes.isAllZero(atNonce.returned.get(3)), "key"); + } + + @Test + @DisplayName("KeySchedule control: secret is wiped; key and base_nonce pass to the Context and are wiped by destroy()") + void control() throws Exception { + FailingHkdf none = new FailingHkdf(0); + Hpke.Context context = Hpke.keySchedule(none, sharedSecret, new byte[]{1}); + assertEquals(5, none.returned.size()); + assertTrue(X25519Bytes.isAllZero(none.returned.get(2)), "secret"); + assertFalse(X25519Bytes.isAllZero(none.returned.get(3)), "key belongs to the live context"); + assertArrayEquals(Hpke.keySchedule(Hpke.JDK_HKDF, sharedSecret, new byte[]{1}).key(), context.key(), + "the seam computes what the JDK HKDF computes"); + context.destroy(); + assertTrue(X25519Bytes.isAllZero(none.returned.get(3)), "key after destroy"); + assertTrue(X25519Bytes.isAllZero(none.returned.get(4)), "base_nonce after destroy"); + } + } + + /** Skips the JCA tests on JDKs that refuse unsigned JCE providers. */ + private static void assumeUnsignedProvidersAccepted() { + boolean accepted; + try { + real = Security.getProvider("SunJCE"); + KDF.getInstance("HKDF-SHA256", new FaultyKdfProvider()); + accepted = true; + } catch (SecurityException | NoSuchAlgorithmException refused) { + accepted = false; + } + assumeTrue(accepted, "this JDK accepts only signed JCE providers"); + } + + @Test + @DisplayName("SealBase: an HKDF failure after extraction, after key, or at base_nonce leaves no ZeroJ-owned secret unwiped, and stays a platform fault") + void sealFailures() throws Exception { + assumeUnsignedProvidersAccepted(); + byte[] skR = DkgEncryptedHarness.testKey("wipe.recipient"); + byte[] skE = DkgEncryptedHarness.testKey("wipe.ephemeral"); + byte[] pkR = X25519Bytes.publicFromPrivate(skR); + for (int failAt : new int[]{2, 6, 7}) { + withFaultyKdf(failAt, () -> { + assertThrows(IllegalStateException.class, + () -> Hpke.sealBaseWithEphemeral(skE, pkR, new byte[]{1}, new byte[0], new byte[100]), + "a platform fault, never an input failure"); + assertEquals(failAt, FaultyKdf.calls, "the injected derivation was reached"); + assertEquals(failAt - 1, FaultyKdf.returned.size()); + assertSecretsWiped("after a failure at " + LABELS[failAt - 1]); + }); + } + } + + @Test + @DisplayName("OpenBase: an HKDF failure at base_nonce leaves no ZeroJ-owned secret unwiped, and stays a platform fault") + void openFailure() throws Exception { + assumeUnsignedProvidersAccepted(); + byte[] skR = DkgEncryptedHarness.testKey("wipe.recipient"); + byte[] pkR = X25519Bytes.publicFromPrivate(skR); + Hpke.Sealed sealed = Hpke.sealBaseWithEphemeral(DkgEncryptedHarness.testKey("wipe.ephemeral"), pkR, + new byte[]{1}, new byte[0], new byte[100]); + withFaultyKdf(7, () -> { + assertThrows(IllegalStateException.class, + () -> Hpke.openBase(sealed.enc(), skR, pkR, new byte[]{1}, new byte[0], sealed.ct())); + assertSecretsWiped("after a failed open"); + }); + } + + @Test + @DisplayName("Control: with no failure, the round trip works through the delegating KDF and every secret is wiped afterwards") + void jcaControl() throws Exception { + assumeUnsignedProvidersAccepted(); + byte[] skR = DkgEncryptedHarness.testKey("wipe.recipient"); + byte[] pkR = X25519Bytes.publicFromPrivate(skR); + withFaultyKdf(0, () -> { + Hpke.Sealed sealed = Hpke.sealBaseWithEphemeral(DkgEncryptedHarness.testKey("wipe.ephemeral"), pkR, + new byte[]{1}, new byte[0], new byte[100]); + assertEquals(7, FaultyKdf.returned.size(), "the faulty KDF served every derivation"); + assertSecretsWiped("after a successful seal"); + assertArrayEquals(new byte[100], Hpke.openBase(sealed.enc(), skR, pkR, new byte[]{1}, new byte[0], sealed.ct())); + }); + } +} diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeKnownAnswerTest.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeKnownAnswerTest.java new file mode 100644 index 00000000..b574e11b --- /dev/null +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeKnownAnswerTest.java @@ -0,0 +1,379 @@ +package org.zeroj.circuit.lib.jubjub; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import javax.crypto.Cipher; +import javax.crypto.KDF; +import javax.crypto.spec.HKDFParameterSpec; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.TreeSet; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * ADR-0054 M1: the HPKE building blocks against published vectors only (see + * {@code src/test/resources/standard-vectors/README.md}). No expected value comes from ZeroJ code. + */ +class HpkeKnownAnswerTest { + + private static final HexFormat HEX = HexFormat.of(); + private static final ObjectMapper JSON = new ObjectMapper(); + + private static JsonNode load(String name) throws IOException { + try (InputStream in = Objects.requireNonNull( + HpkeKnownAnswerTest.class.getResourceAsStream("/standard-vectors/" + name), name)) { + return JSON.readTree(in); + } + } + + private static byte[] hex(JsonNode node, String field) { + return HEX.parseHex(node.get(field).asText()); + } + + // ---------------------------------------------------------------- RFC 9180 A.2.1 + + @Test + @DisplayName("RFC 9180 A.2.1 (Base): key derivation, key schedule and all 257 encryptions, sealed and opened") + void rfc9180A21() throws Exception { + JsonNode suite = load("hpke-x25519-sha256-chacha20poly1305-base.json"); + assertEquals(1, suite.size()); + JsonNode v = suite.get(0); + assertEquals(0, v.get("mode").asInt()); + assertEquals(Hpke.KEM_ID, v.get("kem_id").asInt()); + assertEquals(Hpke.KDF_ID, v.get("kdf_id").asInt()); + assertEquals(Hpke.AEAD_ID, v.get("aead_id").asInt()); + + // DeriveKeyPair (§7.1.3) and SerializePublicKey. + byte[] skE = Hpke.deriveKeyPair(hex(v, "ikmE")); + byte[] skR = Hpke.deriveKeyPair(hex(v, "ikmR")); + assertArrayEquals(hex(v, "skEm"), skE); + assertArrayEquals(hex(v, "skRm"), skR); + assertArrayEquals(hex(v, "pkEm"), X25519Bytes.publicFromPrivate(skE)); + assertArrayEquals(hex(v, "pkRm"), X25519Bytes.publicFromPrivate(skR)); + + // SetupBaseS with the vector's ephemeral key; the key schedule outputs. + byte[] info = hex(v, "info"); + byte[][] enc = new byte[1][]; + Hpke.Context sender = Hpke.setupBaseSWithEphemeral(skE, hex(v, "pkRm"), info, enc); + assertArrayEquals(hex(v, "enc"), enc[0]); + assertArrayEquals(hex(v, "key"), sender.key()); + assertArrayEquals(hex(v, "base_nonce"), sender.baseNonce()); + Hpke.Context recipient = Hpke.setupBaseR(enc[0], skR, info); + assertArrayEquals(hex(v, "key"), recipient.key()); + assertArrayEquals(hex(v, "base_nonce"), recipient.baseNonce()); + + // Every listed encryption, at its own sequence number (§5.2). + JsonNode encryptions = v.get("encryptions"); + assertEquals(257, encryptions.size()); + for (int seq = 0; seq < encryptions.size(); seq++) { + JsonNode e = encryptions.get(seq); + assertArrayEquals(hex(e, "nonce"), xorNonce(sender.baseNonce(), seq), "nonce " + seq); + sender.setSequence(seq); + assertArrayEquals(hex(e, "ct"), sender.seal(hex(e, "aad"), hex(e, "pt")), "seal " + seq); + recipient.setSequence(seq); + assertArrayEquals(hex(e, "pt"), recipient.open(hex(e, "aad"), hex(e, "ct")), "open " + seq); + } + + // Single-shot is sequence 0. + Hpke.Sealed single = Hpke.sealBaseWithEphemeral(skE, hex(v, "pkRm"), info, + hex(encryptions.get(0), "aad"), hex(encryptions.get(0), "pt")); + assertArrayEquals(hex(v, "enc"), single.enc()); + assertArrayEquals(hex(encryptions.get(0), "ct"), single.ct()); + assertArrayEquals(hex(encryptions.get(0), "pt"), + Hpke.openBase(single.enc(), skR, info, hex(encryptions.get(0), "aad"), single.ct())); + } + + @Test + @DisplayName("Context sequence (§5.2): seal and open advance it, a failed open does not, and the limit is refused (review C-3)") + void contextSequence() throws Exception { + JsonNode v = load("hpke-x25519-sha256-chacha20poly1305-base.json").get(0); + byte[] skE = hex(v, "skEm"); + byte[] skR = hex(v, "skRm"); + byte[] info = hex(v, "info"); + byte[][] enc = new byte[1][]; + Hpke.Context sender = Hpke.setupBaseSWithEphemeral(skE, hex(v, "pkRm"), info, enc); + Hpke.Context recipient = Hpke.setupBaseR(enc[0], skR, info); + + // No setSequence: the k-th call uses sequence k, so the vector's encryptions come out in order. + JsonNode encryptions = v.get("encryptions"); + for (int seq = 0; seq < encryptions.size(); seq++) { + JsonNode e = encryptions.get(seq); + byte[] ct = hex(e, "ct"); + assertArrayEquals(ct, sender.seal(hex(e, "aad"), hex(e, "pt")), "seal " + seq); + byte[] tampered = ct.clone(); + tampered[0] ^= 1; + assertThrows(Hpke.HpkeException.class, () -> recipient.open(hex(e, "aad"), tampered), "tampered " + seq); + assertArrayEquals(hex(e, "pt"), recipient.open(hex(e, "aad"), ct), "a failed open leaves sequence " + seq); + } + + // One below the limit still works and advances to it; the next call is refused, both ways. + JsonNode first = encryptions.get(0); + sender.setSequence(Long.MAX_VALUE - 1); + recipient.setSequence(Long.MAX_VALUE - 1); + byte[] last = sender.seal(hex(first, "aad"), hex(first, "pt")); + assertArrayEquals(hex(first, "pt"), recipient.open(hex(first, "aad"), last)); + assertThrows(GeneralSecurityException.class, () -> sender.seal(hex(first, "aad"), hex(first, "pt"))); + assertThrows(Hpke.HpkeException.class, () -> recipient.open(hex(first, "aad"), last)); + assertThrows(IllegalArgumentException.class, () -> sender.setSequence(-1)); + } + + private static byte[] xorNonce(byte[] baseNonce, long seq) { + byte[] out = baseNonce.clone(); + byte[] s = Hpke.i2osp(seq, Hpke.N_N); + for (int i = 0; i < out.length; i++) out[i] ^= s[i]; + return out; + } + + // ---------------------------------------------------------------- X25519 + + @Test + @DisplayName("RFC 7748 §5.2 and §6.1 X25519 vectors") + void rfc7748() throws Exception { + // §5.2, first vector (scalar, u-coordinate, output). + assertArrayEquals(HEX.parseHex("c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552"), + X25519Bytes.dh(X25519Bytes.privateKey(HEX.parseHex("a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4")), + HEX.parseHex("e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c"))); + // §5.2, second vector: the u-coordinate has bit 255 set, which X25519 must mask. + assertArrayEquals(HEX.parseHex("95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957"), + X25519Bytes.dh(X25519Bytes.privateKey(HEX.parseHex("4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d")), + HEX.parseHex("e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493"))); + // §6.1 Diffie–Hellman. + byte[] a = HEX.parseHex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + byte[] b = HEX.parseHex("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"); + assertArrayEquals(HEX.parseHex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"), X25519Bytes.publicFromPrivate(a)); + assertArrayEquals(HEX.parseHex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"), X25519Bytes.publicFromPrivate(b)); + byte[] k = HEX.parseHex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"); + assertArrayEquals(k, X25519Bytes.dh(X25519Bytes.privateKey(a), X25519Bytes.publicFromPrivate(b))); + assertArrayEquals(k, X25519Bytes.dh(X25519Bytes.privateKey(b), X25519Bytes.publicFromPrivate(a))); + } + + /** + * Every Wycheproof X25519 test through {@link X25519Bytes#dh}. "valid" must match. "invalid" + * must fail. "acceptable" cases (small-order and twist inputs, non-canonical values) may match + * or fail, but this implementation's behaviour is pinned: an all-zero result fails (RFC 9180 + * §7.1.4); any other result must equal the shared value. + */ + @Test + @DisplayName("Wycheproof x25519_test.json: 518 tests, all-zero results refused") + void wycheproofX25519() throws Exception { + JsonNode root = load("wycheproof-x25519_test.json"); + int total = 0, zeroRefused = 0, nonCanonical = 0; + for (JsonNode group : root.get("testGroups")) { + for (JsonNode t : group.get("tests")) { + total++; + byte[] priv = hex(t, "private"); + byte[] pub = hex(t, "public"); + byte[] shared = hex(t, "shared"); + String result = t.get("result").asText(); + boolean expectZero = X25519Bytes.isAllZero(shared); + if (!X25519Bytes.isCanonical(pub)) nonCanonical++; + String id = "tcId " + t.get("tcId").asInt() + " " + t.get("comment").asText(); + if ("invalid".equals(result)) { + assertThrows(GeneralSecurityException.class, () -> X25519Bytes.dh(X25519Bytes.privateKey(priv), pub), id); + } else if (expectZero) { + assertThrows(GeneralSecurityException.class, () -> X25519Bytes.dh(X25519Bytes.privateKey(priv), pub), id); + zeroRefused++; + } else { + assertArrayEquals(shared, X25519Bytes.dh(X25519Bytes.privateKey(priv), pub), id); + } + } + } + assertEquals(518, total); + assertTrue(zeroRefused > 0, "Wycheproof contains all-zero cases"); + assertTrue(nonCanonical > 0, "Wycheproof contains non-canonical public values"); + } + + @Test + @DisplayName("The provider-independent small-order set equals Wycheproof's all-zero public values (review R2-1)") + void smallOrderSetMatchesWycheproof() { + JsonNode root; + try { + root = load("wycheproof-x25519_test.json"); + } catch (IOException e) { + throw new AssertionError(e); + } + Set zero = new TreeSet<>(); + int nonZero = 0; + for (JsonNode group : root.get("testGroups")) { + for (JsonNode t : group.get("tests")) { + byte[] pub = hex(t, "public"); + String id = "tcId " + t.get("tcId").asInt(); + if (X25519Bytes.isAllZero(hex(t, "shared"))) { + assertTrue(X25519Bytes.isSmallOrder(pub), id); + zero.add(X25519Bytes.decodeUCoordinate(pub)); + } else if (!"invalid".equals(t.get("result").asText())) { + assertFalse(X25519Bytes.isSmallOrder(pub), id); + nonZero++; + } + } + } + assertEquals(5, zero.size(), "0, 1, p − 1 and the two order-8 u-coordinates: " + zero); + assertTrue(nonZero > 400); + } + + @Test + @DisplayName("Canonicality (spec §2.1) and the small-order probe (§2.2) agree with Wycheproof's small-order cases") + void canonicalAndProbe() { + byte[] p = X25519Bytes.littleEndian(X25519Bytes.P); + assertFalse(X25519Bytes.isCanonical(p), "u = p"); + assertFalse(X25519Bytes.isCanonical(X25519Bytes.littleEndian(X25519Bytes.P.add(BigInteger.ONE))), "u = p + 1"); + byte[] high = X25519Bytes.BASE_POINT.clone(); + high[31] |= (byte) 0x80; + assertFalse(X25519Bytes.isCanonical(high), "bit 255 set"); + assertTrue(X25519Bytes.isCanonical(X25519Bytes.BASE_POINT)); + assertTrue(X25519Bytes.isCanonical(X25519Bytes.littleEndian(X25519Bytes.P.subtract(BigInteger.ONE)))); + assertFalse(X25519Bytes.isCanonical(new byte[31])); + assertTrue(X25519Bytes.passesSmallOrderProbe(X25519Bytes.BASE_POINT)); + assertFalse(X25519Bytes.passesSmallOrderProbe(new byte[32]), "u = 0"); + byte[] one = new byte[32]; + one[0] = 1; + assertFalse(X25519Bytes.passesSmallOrderProbe(one), "u = 1"); + } + + @Test + @DisplayName("Small-order probe: refuses exactly the canonical public values Wycheproof lists with all-zero shared secrets") + void probeMatchesWycheproof() throws Exception { + JsonNode root = load("wycheproof-x25519_test.json"); + List checked = new ArrayList<>(); + for (JsonNode group : root.get("testGroups")) { + for (JsonNode t : group.get("tests")) { + byte[] pub = hex(t, "public"); + if (!X25519Bytes.isCanonical(pub)) continue; + boolean zero = X25519Bytes.isAllZero(hex(t, "shared")); + // Clamping makes "all-zero for one scalar" equivalent to "all-zero for every scalar". + assertEquals(!zero, X25519Bytes.passesSmallOrderProbe(pub), "tcId " + t.get("tcId").asInt()); + if (zero) checked.add(t.get("public").asText()); + } + } + assertTrue(checked.size() >= 3, "small-order canonical cases seen: " + checked.size()); + } + + // ---------------------------------------------------------------- ChaCha20-Poly1305 + + @Test + @DisplayName("RFC 8439 §2.8.2 and Wycheproof chacha20_poly1305_test.json through the JDK cipher Hpke uses") + void chacha20Poly1305() throws Exception { + // RFC 8439 §2.8.2. + byte[] key = HEX.parseHex("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"); + byte[] nonce = HEX.parseHex("070000004041424344454647"); + byte[] aad = HEX.parseHex("50515253c0c1c2c3c4c5c6c7"); + byte[] pt = ("Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, " + + "sunscreen would be it.").getBytes(StandardCharsets.US_ASCII); + byte[] expected = HEX.parseHex("d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b" + + "1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116" + + "1ae10b594f09e26a7e902ecbd0600691"); + assertArrayEquals(expected, chacha(Cipher.ENCRYPT_MODE, key, nonce, aad, pt)); + assertArrayEquals(pt, chacha(Cipher.DECRYPT_MODE, key, nonce, aad, expected)); + + JsonNode root = load("wycheproof-chacha20_poly1305_test.json"); + int total = 0, run = 0; + for (JsonNode group : root.get("testGroups")) { + for (JsonNode t : group.get("tests")) { + total++; + byte[] k = hex(t, "key"), iv = hex(t, "iv"), a = hex(t, "aad"), msg = hex(t, "msg"); + byte[] ctTag = concat(hex(t, "ct"), hex(t, "tag")); + String result = t.get("result").asText(); + String id = "tcId " + t.get("tcId").asInt(); + if (iv.length != Hpke.N_N || k.length != Hpke.N_K) { + // HPKE only ever uses 32-byte keys and 12-byte nonces; other sizes must be refused. + assertEquals("invalid", result, id); + assertThrows(GeneralSecurityException.class, () -> chacha(Cipher.DECRYPT_MODE, k, iv, a, ctTag), id); + continue; + } + run++; + if ("valid".equals(result)) { + assertArrayEquals(ctTag, chacha(Cipher.ENCRYPT_MODE, k, iv, a, msg), id); + assertArrayEquals(msg, chacha(Cipher.DECRYPT_MODE, k, iv, a, ctTag), id); + } else { + assertThrows(GeneralSecurityException.class, () -> chacha(Cipher.DECRYPT_MODE, k, iv, a, ctTag), id); + } + } + } + assertEquals(325, total); + assertTrue(run > 250, "12-byte-nonce cases: " + run); + } + + private static byte[] chacha(int mode, byte[] key, byte[] nonce, byte[] aad, byte[] input) throws GeneralSecurityException { + Cipher cipher = Cipher.getInstance("ChaCha20-Poly1305"); + cipher.init(mode, new SecretKeySpec(key, "ChaCha20"), new IvParameterSpec(nonce)); + if (aad.length > 0) cipher.updateAAD(aad); + return cipher.doFinal(input); + } + + // ---------------------------------------------------------------- HKDF-SHA256 + + @Test + @DisplayName("RFC 5869 A.1–A.3 and Wycheproof hkdf_sha256_test.json through the JDK KDF Hpke uses") + void hkdf() throws Exception { + String[][] rfc = { + // ikm, salt, info, L, prk, okm (RFC 5869 A.1, A.2, A.3) + {"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "000102030405060708090a0b0c", "f0f1f2f3f4f5f6f7f8f9", "42", + "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5", + "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"}, + {"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f", + "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf", + "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", + "82", "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244", + "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87"}, + {"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "", "", "42", + "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04", + "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"}}; + KDF kdf = KDF.getInstance("HKDF-SHA256"); + for (String[] r : rfc) { + HKDFParameterSpec.Builder b = HKDFParameterSpec.ofExtract().addIKM(HEX.parseHex(r[0])); + if (!r[1].isEmpty()) b.addSalt(HEX.parseHex(r[1])); + byte[] prk = kdf.deriveData(b.extractOnly()); + assertArrayEquals(HEX.parseHex(r[4]), prk, "prk"); + assertArrayEquals(HEX.parseHex(r[5]), kdf.deriveData(HKDFParameterSpec.expandOnly( + new SecretKeySpec(prk, "HKDF-PRK"), HEX.parseHex(r[2]), Integer.parseInt(r[3]))), "okm"); + } + + JsonNode root = load("wycheproof-hkdf_sha256_test.json"); + int total = 0; + for (JsonNode group : root.get("testGroups")) { + for (JsonNode t : group.get("tests")) { + total++; + byte[] ikm = hex(t, "ikm"), salt = hex(t, "salt"), info = hex(t, "info"); + int size = t.get("size").asInt(); + String id = "tcId " + t.get("tcId").asInt(); + try { + HKDFParameterSpec.Builder b = HKDFParameterSpec.ofExtract().addIKM(ikm); + if (salt.length > 0) b.addSalt(salt); + byte[] prk = kdf.deriveData(b.extractOnly()); + byte[] okm = kdf.deriveData(HKDFParameterSpec.expandOnly(new SecretKeySpec(prk, "HKDF-PRK"), info, size)); + if ("invalid".equals(t.get("result").asText())) fail(id + ": expected a refusal"); + assertArrayEquals(hex(t, "okm"), okm, id); + } catch (GeneralSecurityException | IllegalArgumentException refused) { + assertEquals("invalid", t.get("result").asText(), id + ": " + refused); + } + } + } + assertEquals(86, total); + } + + private static byte[] concat(byte[] a, byte[] b) { + byte[] out = new byte[a.length + b.length]; + System.arraycopy(a, 0, out, 0, a.length); + System.arraycopy(b, 0, out, a.length, b.length); + return out; + } +} diff --git a/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeNativeProbe.java b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeNativeProbe.java new file mode 100644 index 00000000..4bb2b9d4 --- /dev/null +++ b/zeroj-circuit-lib/src/test/java/org/zeroj/circuit/lib/jubjub/HpkeNativeProbe.java @@ -0,0 +1,62 @@ +package org.zeroj.circuit.lib.jubjub; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.SecureRandom; +import java.util.HexFormat; + +/** + * ADR-0054 M1 GraalVM native-image probe (not a JUnit test). Prints HPKE results that must be + * identical on the JVM and in a native image. Reproduce, from the repository root: + *
+ * ./gradlew :zeroj-circuit-lib:testClasses
+ * CP=zeroj-circuit-lib/build/classes/java/main:zeroj-circuit-lib/build/classes/java/test
+ * java -cp $CP org.zeroj.circuit.lib.jubjub.HpkeNativeProbe > jvm.txt
+ * native-image --no-fallback -cp $CP -o hpke-probe org.zeroj.circuit.lib.jubjub.HpkeNativeProbe
+ * ./hpke-probe > native.txt && diff jvm.txt native.txt   # all but the last (random) line
+ * 
+ * The first lines reproduce RFC 9180 A.2.1 ({@code skEm}, {@code skRm}, {@code pkRm}, {@code enc}, + * {@code key}, {@code base_nonce}, the sequence-0 ciphertext). + */ +public final class HpkeNativeProbe { + public static void main(String[] args) throws Exception { + HexFormat h = HexFormat.of(); + // RFC 9180 A.2.1 inputs. + byte[] skE = Hpke.deriveKeyPair(h.parseHex("909a9b35d3dc4713a5e72a4da274b55d3d3821a37e5d099e74a647db583a904b")); + byte[] skR = Hpke.deriveKeyPair(h.parseHex("1ac01f181fdf9f352797655161c58b75c656a6cc2716dcb66372da835542e1df")); + byte[] pkR = X25519Bytes.publicFromPrivate(skR); + byte[] info = h.parseHex("4f6465206f6e2061204772656369616e2055726e"); + System.out.println("skEm " + h.formatHex(skE)); + System.out.println("skRm " + h.formatHex(skR)); + System.out.println("pkRm " + h.formatHex(pkR)); + byte[][] enc = new byte[1][]; + Hpke.Context ctx = Hpke.setupBaseSWithEphemeral(skE, pkR, info, enc); + System.out.println("enc " + h.formatHex(enc[0])); + System.out.println("key " + h.formatHex(ctx.key())); + System.out.println("base_nonce " + h.formatHex(ctx.baseNonce())); + MessageDigest d = MessageDigest.getInstance("SHA-256"); + byte[] pt = h.parseHex("4265617574792069732074727574682c20747275746820626561757479"); + for (int seq = 0; seq <= 256; seq++) { + ctx.setSequence(seq); + d.update(ctx.seal(("Count-" + seq).getBytes(StandardCharsets.US_ASCII), pt)); + } + System.out.println("ct_digest " + h.formatHex(d.digest())); + Hpke.Sealed s = Hpke.sealBaseWithEphemeral(skE, pkR, info, "Count-0".getBytes(StandardCharsets.US_ASCII), pt); + System.out.println("single_ct " + h.formatHex(s.ct())); + System.out.println("open " + h.formatHex(Hpke.openBase(s.enc(), skR, info, "Count-0".getBytes(StandardCharsets.US_ASCII), s.ct()))); + // RFC 7748 §6.1 and the small-order probe. + System.out.println("x25519_alice_pk " + h.formatHex(X25519Bytes.publicFromPrivate(h.parseHex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a")))); + System.out.println("probe_base " + X25519Bytes.passesSmallOrderProbe(X25519Bytes.BASE_POINT)); + System.out.println("probe_zero " + X25519Bytes.passesSmallOrderProbe(new byte[32])); + try { + Hpke.openBase(new byte[32], skR, info, new byte[0], s.ct()); + System.out.println("small_order_enc accepted"); + } catch (Hpke.HpkeException e) { + System.out.println("small_order_enc refused"); + } + System.out.println("open_private_key " + h.formatHex(Hpke.openBase(s.enc(), X25519Bytes.privateKey(skR), pkR, info, + "Count-0".getBytes(StandardCharsets.US_ASCII), s.ct()))); + Hpke.Sealed fresh = Hpke.sealBase(pkR, info, new byte[0], pt, new SecureRandom()); + System.out.println("random_roundtrip " + h.formatHex(Hpke.openBase(fresh.enc(), skR, info, new byte[0], fresh.ct()))); + } +} diff --git a/zeroj-circuit-lib/src/test/resources/dkg-share-delivery-reference/README.md b/zeroj-circuit-lib/src/test/resources/dkg-share-delivery-reference/README.md new file mode 100644 index 00000000..47952495 --- /dev/null +++ b/zeroj-circuit-lib/src/test/resources/dkg-share-delivery-reference/README.md @@ -0,0 +1,543 @@ +# DKG share delivery with HPKE v1: independent reference + +This is an independent reproduction of the `dkg-share-delivery-hpke-v1` transport profile +(ADR-0054, milestone M0). It covers HPKE Base mode from RFC 9180, the announcements, the key +directory, abort T1, the envelopes, the processing barrier, the D7a posting order and the +exposure counting rule. It was written from the spec, the RFC texts and the existing Python +reference of the threshold DKG. Its output is evidence for checking ZeroJ's Java implementation. +It is not a security proof. The composition argument (Assumption A1) stays an external-review +gate. + +## Files + +- `dkg_share_delivery_hpke_v1_reference.py`: Python 3. It uses pyca `cryptography` 46.0.5 for + four things only: X25519, HMAC-SHA256, ChaCha20Poly1305, and HKDF (HKDF only as a + differential). Everything else uses the standard library. It contains: + - **HPKE, from the RFC 9180 text:** + - LabeledExtract and LabeledExpand (§4); + - DHKEM(X25519, HKDF-SHA256): Encap, Decap, ExtractAndExpand and `kem_context` (§4.1); + - DeriveKeyPair (§7.1.3); + - KeySchedule, with VerifyPSKInputs (§5.1); + - a context with a sequence number, ComputeNonce, the overflow error and Export (§5.2, §5.3); + - SealBase and OpenBase (§6.1); + - the all-zero DH check (§7.1.4), for both sender and recipient. + + HKDF Extract and Expand are written from RFC 5869 on pyca's HMAC. A pure-Python X25519 + ladder, transcribed from RFC 7748 §5, is used as a differential. It also evaluates + small-order inputs, which pyca refuses. + - **The profile:** + - canonicality and the small-order probe (§2); + - announcements, the directory and T1, including its key-mismatch clause (§3); + - `info`, sealing, and the 6-step opening rule, with de-duplication only after + authentication (§4); + - a board with windows, cutoffs, processing lags, the barrier and D7a (§5); + - the counting rule (§6); + - session-bound, destroyable recipient keys (§7); + - the test keys `sk(tag)` (§9.1). + - **DKG mechanics:** imported from + `../elgamal-threshold-reference/elgamal_jubjub_threshold_v1_reference.py`, not + reimplemented. That covers `Config`/session, the §11 dealings, `SHARE`/`COMMITMENTS` + encodings, `parse`, `simulate` (rounds 1–7, `QUAL`, complaints, answers, aborts), + `delivered_round` and the transcript digest. Decrypted `SHARE`s enter `simulate` only + through its private channel (`Script.private_raw`). No transport message enters a DKG + round. +- `reference-output.txt`: the output, one `key=value` per line, sorted by key, with no header. + +## Running + +``` +cd zeroj-circuit-lib/src/test/resources/dkg-share-delivery-reference +python3 dkg_share_delivery_hpke_v1_reference.py +``` + +The run takes about 10 s. It prints the output and rewrites `reference-output.txt`. +- **Exit status:** 0 if every check passes. Otherwise 1, with the failing keys on stderr; a crash + also gives 1. +- **Determinism:** the output depends only on the code and the vendored inputs. It contains no + Python version and no timing. Two runs, and runs with `PYTHONHASHSEED` set to 0, 1 and 12345, + gave byte-identical files (SHA-256 at the end of this README). + +## Independence + +Read: +- `docs/specs/dkg-share-delivery-hpke-v1.md`, `docs/adr/0054-hpke-dkg-share-delivery.md` and + `docs/specs/elgamal-jubjub-threshold-v1.md`. During the work, an informative paragraph about + this profile was added to §5.2 of that spec; it changes no rule; +- the RFC texts: RFC 9180, RFC 7748, RFC 8439 and RFC 5869; +- the vendored vectors in `../standard-vectors/` and their README; +- the threshold reference's README and Python source. + +The spec was read again at its second revision (resolving S1–S7), with the same rules. + +Not read: any Java source (`*/src/main/java`, `*/src/test/java`) and any other ZeroJ code. A +`git diff --stat` printed some Java file names, but no Java content was opened. + +Every expected value of the primitives comes from published vectors: the RFC texts, the CFRG +A.2.1 JSON and Wycheproof. The profile vectors are this reference's own outputs. Where the code +could have got one of them wrong, a hand-written intent check states the outcome the case was +built to show (see "Checks"). + +## Results + +This README describes the run against the **second revision** of the spec, which resolves +findings S1–S7 of the first run (see "Spec findings"). + +All 294 checks pass. There are 110 replayable vectors, and each replays from its own keys. + +| Area | Result | +|---|---| +| RFC 9180 A.2.1 | `DeriveKeyPair(ikmE)` and `DeriveKeyPair(ikmR)` give `skEm`/`pkEm` and `skRm`/`pkRm`. `enc`, `shared_secret` (Encap and Decap), `key_schedule_context`, `secret`, `key`, `base_nonce` and `exporter_secret` all match. **All 257 encryptions (sequence numbers 0–256) match**, sealed and opened through one sender context and one receiver context, with each nonce checked against `base_nonce XOR seq`. All 3 exported values match on both sides. Single-shot SealBase/OpenBase matches. Wrong `info`, wrong `aad`, wrong key and an out-of-sequence ciphertext are refused, and sequence overflow raises. | +| RFC 7748 | §5.2: both vectors and the 1-iteration and 1,000-iteration results match, through pyca and through the ladder. The 1,000,000-iteration result is not run, for cost. §6.1: Alice's and Bob's public keys and `K` match. | +| Wycheproof X25519 (518 tests) | All 518 pass. See "Handling of acceptable cases" below. | +| RFC 8439 §2.8.2, Wycheproof ChaCha20-Poly1305 (325 tests) | The KAT seals and opens, and a modified tag is refused. Wycheproof: 256 valid tests seal to `ct‖tag` and open. 69 invalid tests fail to open: 60 have a modified tag, and 9 have a wrong nonce size. | +| RFC 5869 A.1–A.3, Wycheproof HKDF-SHA256 (86 tests) | PRK and OKM match. 83 valid tests match, both in this reference's HKDF and in pyca's. 3 invalid tests (`SizeTooLarge`) are refused by both. | +| §2.2 claim | Verified independently (see "Small-order points"). | + +### Handling of "acceptable" Wycheproof X25519 cases + +The file has 264 `valid` tests, 254 `acceptable` tests and no `invalid` ones. + +| Category | Count | Handling | +|---|---|---| +| `valid` | 264 | pyca, the ladder and the HPKE `DH` all give `shared`. Every public value is canonical. | +| `acceptable`, non-zero `shared` (twist, non-canonical or edge-case public values) | 223 | **Computed.** pyca and the ladder both give `shared`, as RFC 7748 §5 requires the X25519 function to accept these values. At the profile layer, the 13 with a non-canonical public value would be refused before any X25519 call (§2.1). The other 210, including twist points, are canonical and pass the probe. | +| `acceptable`, all-zero `shared` (`ZeroSharedSecret`) | 31 | **Refused.** The ladder gives `0^32`, pyca raises, and the HPKE `DH` raises `ValidationError` (RFC 9180 §7.1.4). At the profile layer, all 31 public values fail canonicality or the probe. | + +pyca raises exactly on the all-zero output. That was checked against the ladder on every +Wycheproof input and every small-order point. + +### Small-order points (§2.2) + +There are exactly 5 canonical small-order u-coordinates: `0`, `1`, the two order-8 values, and +`p − 1`. They were found two independent ways: +- **From Wycheproof:** reduce every public value with an all-zero shared secret (mask bit 255, + then reduce mod `p`). +- **Algebraically:** the order-2 points (`x = 0`, and the roots of `x² + Ax + 1`, which have none + in `F_p`). Then repeated x-only halving, solving `x(2P) = c` through `w = x + 1/x`. + +The two sets are equal (`check.small_order.algebraic_equals_wycheproof_set`). There are no +order-16 points. + +The spec's claim was then checked in both directions: +- `X25519(k, u) = 0^32` for `PROBE` and for five other test scalars, on every small-order `u`; +- `X25519(PROBE, u) ≠ 0` for every other public value in the file. + +The reason, in brief: a clamped `k` is `8m` with `2^251 ≤ m < 2^252`, which is below both the +curve's prime order `l` and the twist's `l'`. So `[k]P = O` exactly when the order of `P` +divides 8. + +## Output keys + +| Key | Content | +|---|---| +| `profile`, `profile.*` | The suite, `TAG_A`, `TAG_I` and `TAG_E` with their lengths, `PROBE`, and the §9.1 prefix. | +| `session.` | The threshold-profile sessions used: `honest-2of3`, `honest-3of5` and `honest-4of7` (`ctx = "zeroj.test.honest"`, attempt 1, threshold §11 roster). `*-attempt2` is the same configuration at attempt 2. | +| `small_order.*` | The Wycheproof-derived and algebraic sets, in hex of the big-endian integer. | +| `check.*` | Checks, each `true` or `false`. | +| `info.*` | Informative values, which are not checks. Among them: the Wycheproof counts per category (`info.wycheproof.*.count.*`), the failed test ids (empty), `info.rfc9180.a21.encryptions.*`, the per-trace values `info.timing.*`, `info.case_count.*`, `info.check_count` and `info.failed_checks`. | +| `case...*` | Replayable vectors (below). | +| `result` | `pass` or `fail`. | + +Value conventions: +- byte strings are bare lowercase hex; +- lists of ids are comma-separated and may be empty; +- `i->j` pairs are comma-separated, sorted, and mean (sender, subject): + - a complaint `j->i` is "participant `j` complains about dealer `i`"; + - an answer `i->j` is "dealer `i` answers complainer `j`". + +## Test keys + +All keys are `sk(tag)` of spec §9.1: `SHA-256("zeroj.dkg-share-delivery-hpke.v1.test." ‖ tag)`. +The tag scheme below is normative since the second revision (§9.1). +The 32 bytes are used directly as an X25519 scalar, which X25519 clamps; they are **not** passed +through DeriveKeyPair. Then `pk = X25519(sk, 9)`. Production keys must come from a secure +generator (§2.3). + +| Tag | Use | +|---|---| +| `.recipient.` | Participant `j`'s recipient key. The prefix is the fixture (`honest-2of3`, …), `timing.`, `directory`, `directory.conflicts`, `envelope`, `envelope.attempt2` or `announce`. | +| `.ephemeral..` | The ephemeral key of envelope `i → j` in a board scenario. | +| `envelope.ephemeral.` | The ephemeral key of a sealed `envelope` case. The good case uses `envelope.ephemeral.good`. | +| `directory.recipient.3.second`, `directory.forged.2`, `directory.other_session.1`, `directory.recipient.1.late`, `directory.conflicts.recipient..second`, `directory..substitute.2` | Extra announced keys in the directory cases. | +| `small-order.scalar.` | The extra scalars used for the §2.2 claim. | + +Every ephemeral tag is used once, and every test key is distinct +(`check.lifecycle.ephemeral_tags_never_reused`, `check.lifecycle.all_test_keys_distinct`). + +## Replayable vectors + +Counts: `announce` 21, `envelope` 42, `directory` 4, `run` 3, `timing` 16, `exposure` 24, so +110 in all. `config` is always `t,n,ctx-hex,attempt`, and the roster is the threshold §11 standard +one (`key_j` = 32 bytes, each equal to `j`). + +### `case.announce..*` (§3.1 well-formedness) + +| Key | Content | +|---|---| +| `config` | The configuration the announcement is checked against (`honest-2of3`). | +| `bytes` | The announcement. | +| `expect` | `accept` or `reject`. | +| `reason` | Informative: `length_or_tag`, `session`, `index`, `non_canonical`, `small_order` or `none`. The spec sets no precedence among reasons. | +| `u` | `small_order_` only: the small-order `u`. | + +Cases: +- accepted: `well_formed_j1`, `well_formed_j_n`, `canonical_u_p_minus_2` (the largest canonical + value that is not small-order) and `canonical_base_point_u_9`; +- rejected: + - `wrong_tag_first_byte`, `tag_of_envelope`, `length_105`, `length_107`; + - `other_session` (attempt 2), `j_zero`, `j_n_plus_1`; + - `non_canonical_bit255_set`, `non_canonical_u_p`, `non_canonical_u_p_plus_1`, + `non_canonical_u_p_plus_9`, `non_canonical_u_2_255_minus_1`; + - `small_order_1` … `small_order_5`, all five canonical small-order points. + +Authentication and windows are not part of well-formedness. The directory vectors cover them. + +### `case.envelope..*` (§4.2 acceptance) + +| Key | Content | +|---|---| +| `config` | Mostly `honest-2of3`. The cross-attempt cases use attempt 2. | +| `recipient` | `j`, the participant that opens the envelope. | +| `recipient_key_tag` | `j`'s key, `sk(tag)`, bound to `(config session, j)`. | +| `auth`, `bytes` | One envelope and the participant its post is authenticated as (`none`: unauthenticated). Multi-envelope cases use `auth.` and `bytes.`. | +| `expect` | Envelopes are processed in the listed order. `share:` (one `SHARE` delivered), `absent`, or `shares:,` (two different `SHARE`s, which the threshold profile treats as a conflict, so `j` complains). | +| `step` | Informative: the first §4.2 step that fails (1–6), or `none` (for several envelopes: `none` if any is accepted). | +| `good` only: `info`, `enc`, `ct`, `plaintext`, `pkR`, `ephemeral_tag`, `shared_secret`, `key`, `base_nonce`, `key_schedule_context` | Intermediate values, for debugging. | + +The cases are listed below. Dealer 1 seals to recipient 2 unless the name says otherwise. The +step that fails is in parentheses. +- Delivered: + - `good`; + - `duplicate_byte_identical`: one share; + - `duplicate_unauthentic_copy_first`: a byte-identical copy authenticated as 3 is listed before + the genuine envelope. Each is authenticated on its own (step 3) before de-duplication, so the + copy fails and the genuine one delivers the share. + `check.envelope.duplicate_unauthentic_copy_first.dedup_before_auth_would_lose_share` shows + that de-duplicating first would lose it; + - `reencrypted_same_share`: two different envelopes of the same `SHARE` give one share (§4.2); + - `canonical_enc_u_9_control`: `enc = 9`, so the DH output is `pkR`, which is public. It is + accepted: a dealer can always reveal its own share. +- Two shares: `two_different_shares_conflict`. +- Absent: + - (1) `truncated_222`, `extended_224`, `wrong_tag_first_byte`, `tag_of_announce`, + `plaintext_99_bytes`; + - (2) `wrong_session_header`, `sender_zero`, `sender_n_plus_1`, `self_envelope_i_equals_j`, + `wrong_recipient_header_seen_by_2`, `cross_attempt_replay` (an attempt-1 envelope seen in + attempt 2); + - (3) `wrong_sender_header_auth_mismatch`, `unauthenticated`; + - (4) `non_canonical_enc_bit255_set`, `non_canonical_enc_u_p_plus_9`, + `non_canonical_small_order_enc_u_p`, `non_canonical_small_order_enc_u_p_plus_1`; + - (5) `reposted_by_other_sender` (header and authentication say 3), `wrong_recipient_key`, + `wrong_recipient_header_opened_by_3`, `tampered_enc_byte0`, `tampered_ct_byte0`, + `tampered_tag_last_byte`, `small_order_enc_1` … `_5`, `cross_attempt_replay_header_rewritten` + and `cross_attempt_replay_header_rewritten_key_reused` (the attempt-1 key reused, against + §7); + - (6) `plaintext_answer_message`, `plaintext_random_100_bytes`, `plaintext_share_wrong_sender`, + `plaintext_share_wrong_subject`, `plaintext_share_other_session`, + `plaintext_share_scalar_not_below_l`. + +The adversarial `enc` cases are built so that only the check named refuses them: +- the non-canonical ones encrypt under the `kem_context` of the non-canonical bytes; +- `u = p + 9` uses the DH output `X25519(skR, 9) = pkR`; +- the small-order ones encrypt under a DH output of `0^32`. + +`check.envelope.*.opens_without_step4` and +`check.envelope.small_order_enc.all_open_without_zero_check` show that OpenBase would deliver +the share if step 4, or the all-zero check, were skipped. + +### Board vectors: `case.directory.*`, `case.timing.*` + +The board model: +- Times are integers. Round 0 is the window `[0, cut0)`, and round 1 is `[cut0, cut1)` (`cut0 = + 10`, `cut1 = 20`). A post's time is its inclusion and finality time. A post outside its round's + window belongs to no window; in particular round 1 opens when round 0 closes (§5). +- In each window, every post is first authenticated on its own (announcements §3.1, envelopes + §4.2 step 3, `COMMITMENTS` threshold §4–§5), and only then are byte-identical copies counted + once. With `dedup_before_auth=true` (negative control only), posts are de-duplicated by bytes + first, keeping the earliest, which is the defect the spec forbids. +- Participant `j` finishes processing post `p` at `p.time + lag(j, p)`. The default lag is 0. +- With `barrier=true` (§5.1), each participant uses every post of the final window. With + `barrier=false` (negative control), it closes at the cutoff and uses only the posts it + finished processing before then. +- Rounds 2–7 are run by the threshold reference's `simulate`, with timely broadcast. Each + participant's private deliveries are the `SHARE`s accepted by §4.2 from the envelopes it + processed. +- T1 (§3.3) fires when the participant's directory has no key for it, or a key other than the + one it holds (`recipient_key_tag.`). A T1 participant posts nothing after round 0: no + complaint and no answer. Participants in `t1_ignored_by` are corrupted and deviate: they do + not apply T1. +- `extra_complaint` entries are additional round-2 `COMPLAINT`s posted by corrupted + participants. + +| Key | Content | +|---|---| +| `config`, `cut0`, `cut1` | The configuration and the window cutoffs. | +| `barrier`, `d7a`, `t1_rule` | `true` or `false`; `false` marks a negative control. `d7a` affects only how the board was generated: the posts are given, and replay does not need it. | +| `corrupted` | The adversary's set, for the coalition analysis and for I15. | +| `t1_ignored_by` | Deviating participants that do not apply T1. | +| `dedup_before_auth` | `true` only in the two front-running negative controls. | +| `withhold_extraction` | Dealers whose round-4 `EXTRACTION` is not delivered. | +| `recipient_key_tag.` | Each participant's recipient key. | +| `post.` | `time,author,label,hex`. `author` is the authenticated sender. `label` names the post (`announce.[.]`, `envelope..`, `commitments.[.early]`; a front-running copy is `