From 7f9e48c11e489a799effaa005885b7038b29e878 Mon Sep 17 00:00:00 2001 From: FEDDIE Date: Fri, 6 Nov 2026 22:44:34 +0000 Subject: [PATCH 1/3] Auth: accept only the canonical encoding of a session MAC verifySession compared decoded MAC bytes. base64url's spare low bits in the final character meant several spellings of one MAC verified. That isn't exploitable (the real MAC is still required), but a token should have exactly one valid form. Compare the canonical string instead. This surfaced as a flaky test: flipping 'A'<->'B' in the last character only touches padding bits. The test now tampers at fixed positions, including the last one. Co-Authored-By: Claude Opus 5.5 --- backend/src/services/authService.ts | 6 ++++-- backend/tests/auth.test.ts | 8 ++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/backend/src/services/authService.ts b/backend/src/services/authService.ts index 56aced9..9c3c144 100644 --- a/backend/src/services/authService.ts +++ b/backend/src/services/authService.ts @@ -125,8 +125,10 @@ export const authService = { verifySession(token: string): Session | null { const [payload, mac, extra] = token.split('.'); if (!payload || !mac || extra !== undefined) return null; - const expected = hmac('session.', payload); - const given = Buffer.from(mac, 'base64url'); + // Compare the canonical encoding, not decoded bytes: base64url's spare + // padding bits would otherwise let several spellings of one MAC verify. + const expected = Buffer.from(hmac('session.', payload).toString('base64url')); + const given = Buffer.from(mac); if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return null; try { const { a, e } = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')); diff --git a/backend/tests/auth.test.ts b/backend/tests/auth.test.ts index 4599ea1..604e65b 100644 --- a/backend/tests/auth.test.ts +++ b/backend/tests/auth.test.ts @@ -74,8 +74,12 @@ describe('wallet-signature auth', () => { (await request(app).post('/api/orders').set('x-user-address', user.address).send({})).status ).toBe(401); const { authorization } = await authHeaders(app, user); - const tampered = authorization.replace(/.$/, (c) => (c === 'A' ? 'B' : 'A')); - expect((await request(app).post('/api/orders').set('authorization', tampered).send({})).status).toBe(401); + const flip = (c: string) => (c === 'A' ? 'B' : 'A'); + // Every character position, including the final one whose low bits are base64url padding. + for (const i of [authorization.length - 1, authorization.length - 10, 'Bearer '.length + 2]) { + const tampered = authorization.slice(0, i) + flip(authorization[i]) + authorization.slice(i + 1); + expect((await request(app).post('/api/orders').set('authorization', tampered).send({})).status).toBe(401); + } }); it('binds orders to the authenticated address, and keeps order history private', async () => { From 60dfe4cec2679a34bf93eb4128f0df6a55fdda80 Mon Sep 17 00:00:00 2001 From: FEDDIE Date: Fri, 6 Nov 2026 22:44:34 +0000 Subject: [PATCH 2/3] Replace trusted-dealer keygen with distributed key generation Validators now jointly generate the threshold key (Joint-Feldman DKG with complaints, Pedersen '91 / GJKR '99), so no party ever holds the group secret: - crypto/dkg.ts: each validator deals a random polynomial with Feldman commitments. Shares are encrypted to the recipient's transport key using the order cipher, with AAD binding session, dealer and recipient, so the routing coordinator never sees them. Recipients verify against the commitments and complain. Accused dealers must reveal publicly or be disqualified. QUAL, the group key and the verification keys are derived deterministically from the public transcript. The protocol aborts if |QUAL| < t. - validatorNetwork: the ValidatorNode interface gains the DKG rounds, and runDkg drives them, checking that all validators agree. Each simulated validator persists only its own share (data/validators/validator-.json, mode 0600) plus a public transcript. Restarts reload the shares; the first start runs DKG. VALIDATOR_KEY_FILE becomes VALIDATOR_KEY_DIR. - The trusted dealer is gone from production code; it lives only in tests/fixtures for unit-testing the threshold math. - Commitment evaluation uses variable-time multiplication, which is safe because every input is public. This makes DKG about 4x faster. 10 new DKG tests: consistent keys across t-subsets, the coordinator never seeing a share, complaint resolved by an honest reveal, a lying dealer disqualified, abort on too few qualified dealers, misrouted and cross-session replayed shares, and equivocating commitments. The pipeline tests now run on DKG-generated keys. 41 backend tests pass. Co-Authored-By: Claude Opus 5.5 --- backend/.env.example | 4 +- backend/.gitignore | 2 +- backend/README.md | 6 +- backend/src/config.ts | 8 +- backend/src/crypto/dkg.ts | 266 +++++++++++++++++++++ backend/src/crypto/threshold.ts | 47 +--- backend/src/services/validatorNetwork.ts | 284 ++++++++++++++++++----- backend/src/services/validatorService.ts | 4 +- backend/tests/dkg.test.ts | 155 +++++++++++++ backend/tests/fixtures/dealer.ts | 21 ++ backend/tests/pipeline.test.ts | 12 +- backend/tests/setupEnv.ts | 2 +- backend/tests/threshold.test.ts | 8 +- 13 files changed, 705 insertions(+), 114 deletions(-) create mode 100644 backend/src/crypto/dkg.ts create mode 100644 backend/tests/dkg.test.ts create mode 100644 backend/tests/fixtures/dealer.ts diff --git a/backend/.env.example b/backend/.env.example index 6133482..c3c48f9 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -21,7 +21,9 @@ BATCH_TIMEOUT_MS=30000 # Simulated validator set: any VALIDATOR_THRESHOLD of VALIDATOR_COUNT shares # decrypt an order; fewer reveal nothing. Key shares are generated on first -# start and kept in data/validator-keys.json (dev only, gitignored). +# start by a distributed key generation among the validators; each +# validator's own share is kept in data/validators/validator-.json +# (dev only, gitignored). Delete the directory to re-run DKG. VALIDATOR_COUNT=5 VALIDATOR_THRESHOLD=3 # Indices of validators that return invalid shares, to demo proof checking. diff --git a/backend/.gitignore b/backend/.gitignore index 6e79cd4..d03b084 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -3,4 +3,4 @@ dist .env data/*.sqlite3 *.local -data/validator-keys.json +data/validators/ diff --git a/backend/README.md b/backend/README.md index b5aff16..eab9f69 100644 --- a/backend/README.md +++ b/backend/README.md @@ -30,8 +30,10 @@ two contracts (see `contracts/README.md`) — every on-chain call the backend makes (batch attestations, settlement, fee collection) is signed by it. **Never commit this value** — `.env` is gitignored for exactly this reason. -On first start the backend generates a simulated 3-of-5 validator key set -in `data/validator-keys.json` (gitignored). Set `AUTH_TOKEN_SECRET` (≥ 32 +On first start the 5 simulated validators run a distributed key generation +for a 3-of-5 key. No dealer is involved, and each validator writes only its +own share to `data/validators/validator-.json` (gitignored), next to the +public `dkg-transcript.json`. Delete that directory to re-key. Set `AUTH_TOKEN_SECRET` (≥ 32 chars, e.g. `openssl rand -hex 32`) so sessions survive restarts. To watch the DLEQ proofs reject bad validators, set `BYZANTINE_VALIDATORS=2,4`. With 3-of-5, orders still settle, and with three bad validators they fail cleanly. diff --git a/backend/src/config.ts b/backend/src/config.ts index e3778d9..cced5f4 100644 --- a/backend/src/config.ts +++ b/backend/src/config.ts @@ -34,10 +34,10 @@ export const config = { * shares are needed to decrypt any order. */ validatorCount: Number(process.env.VALIDATOR_COUNT) || 5, validatorThreshold: Number(process.env.VALIDATOR_THRESHOLD) || 3, - /** Where the simulated validators' key shares live (dev only — a real - * deployment has each share on a different machine). Empty = in-memory. */ - validatorKeyFile: - process.env.VALIDATOR_KEY_FILE ?? path.join(__dirname, '..', 'data', 'validator-keys.json'), + /** Directory holding one key file per simulated validator, written by the + * DKG on first start (a real deployment keeps each on its own machine). + * Empty = in-memory, re-run DKG every start. */ + validatorKeyDir: process.env.VALIDATOR_KEY_DIR ?? path.join(__dirname, '..', 'data', 'validators'), /** Validator indices that misbehave (return invalid shares) — for * demonstrating that DLEQ proofs catch them. e.g. "2,4". */ byzantineValidators: (process.env.BYZANTINE_VALIDATORS || '') diff --git a/backend/src/crypto/dkg.ts b/backend/src/crypto/dkg.ts new file mode 100644 index 0000000..17b8f7f --- /dev/null +++ b/backend/src/crypto/dkg.ts @@ -0,0 +1,266 @@ +/** + * Distributed key generation (Joint-Feldman with complaints, after + * Pedersen '91 / Gennaro–Jarecki–Krawczyk–Rabin '99). + * + * Every validator j ends up with a secret share y_j of a group secret + * y = Σ_{i∈QUAL} a_{i,0} that no party — validator, coordinator, or the + * backend operator — ever holds. Rounds: + * + * 1. Deal. Validator i picks a random degree-(t−1) polynomial f_i, + * broadcasts Feldman commitments C_{i,k} = a_{i,k}·G, and + * sends s_{i→j} = f_i(j) to each j, *encrypted to j's + * transport key* (the same ElGamal+AES-GCM cipher used for + * orders), so whoever routes the messages learns nothing. + * 2. Verify. j decrypts its shares and checks + * s_{i→j}·G == Σ_k j^k·C_{i,k}. Any failure → complaint(i). + * 3. Respond. An accused dealer must publish s_{i→j}. Everyone checks it + * against i's commitments; a dealer that fails (or stays + * silent) is disqualified. + * 4. Finalize. QUAL = dealers with well-formed commitments and no + * unanswered complaint. Then + * y_j = Σ_{i∈QUAL} s_{i→j} (secret, j only) + * Y = Σ_{i∈QUAL} C_{i,0} (public group key) + * Y_j = Σ_{i∈QUAL} Σ_k j^k·C_{i,k} (public verification keys) + * + * Known limitation (documented in docs/THRESHOLD_ENCRYPTION.md): plain + * Joint-Feldman lets a rushing dealer bias the *distribution* of Y (not learn + * y). GJKR's Pedersen-commitment first round removes that bias; it's a + * contained follow-up since only round 1 changes. + */ +import { + decryptWithSharedPoint, + encryptOrder, + parseCiphertext, + parsePoint, + randomScalar, +} from './orderCipher'; +import { KeyShare, L, Point, RistrettoPoint, hexToScalar, mod, scalarToHex } from './threshold'; + +export interface DealerBroadcast { + dealer: number; + /** Feldman commitments C_{dealer,0..t−1}, hex points. */ + commitments: string[]; +} + +export interface EncryptedShare { + dealer: number; + recipient: number; + ciphertext: string; +} + +export interface Complaint { + complainer: number; + dealer: number; +} + +export interface Reveal { + dealer: number; + recipient: number; + share: string; +} + +export interface DkgTranscript { + broadcasts: DealerBroadcast[]; + complaints: Complaint[]; + reveals: Reveal[]; +} + +/** Public outcome every honest participant computes identically. */ +export interface DkgPublicResult { + threshold: number; + qualified: number[]; + groupPublicKey: string; + verificationKeys: Record; +} + +/** Binds an encrypted share to (session, dealer, recipient): no replay across sessions or misrouting. */ +const shareContext = (sessionId: string, dealer: number, recipient: number) => + `cipher-protocol/dkg/${sessionId}/${dealer}->${recipient}`; + +/** + * Σ_k j^k·C_k — the commitment to f(j). Every input is public, so the + * faster variable-time multiply is safe here (no secret-dependent timing). + */ +export function evalCommitments(commitments: RistrettoPoint[], j: number): RistrettoPoint { + let acc = Point.ZERO; + let power = 1n; + for (const C of commitments) { + acc = acc.add(C.multiplyUnsafe(power)); + power = mod(power * BigInt(j)); + } + return acc; +} + +function parseCommitments(b: DealerBroadcast | undefined, threshold: number): RistrettoPoint[] | null { + if (!b || !Array.isArray(b.commitments) || b.commitments.length !== threshold) return null; + try { + return b.commitments.map(parsePoint); + } catch { + return null; + } +} + +function shareMatches(shareHex: string, commitments: RistrettoPoint[], recipient: number): boolean { + try { + return Point.BASE.multiply(hexToScalar(shareHex)).equals(evalCommitments(commitments, recipient)); + } catch { + return false; + } +} + +/** + * Deterministic from the public transcript, so every honest participant + * (and any auditor) derives the same QUAL set and keys. + */ +export function computePublicResult( + transcript: DkgTranscript, + participants: number[], + threshold: number +): DkgPublicResult { + const commitmentsBy = new Map(); + for (const dealer of participants) { + const own = transcript.broadcasts.filter((b) => b.dealer === dealer); + const parsed = own.length === 1 ? parseCommitments(own[0], threshold) : null; // equivocation → out + if (parsed) commitmentsBy.set(dealer, parsed); + } + + const qualified = participants.filter((dealer) => { + const C = commitmentsBy.get(dealer); + if (!C) return false; + const against = transcript.complaints.filter((c) => c.dealer === dealer && participants.includes(c.complainer)); + return against.every((c) => + transcript.reveals.some( + (r) => r.dealer === dealer && r.recipient === c.complainer && shareMatches(r.share, C, c.complainer) + ) + ); + }); + + if (qualified.length < threshold) { + throw new Error(`DKG failed: only ${qualified.length} qualified dealers, need at least ${threshold}`); + } + + let Y = Point.ZERO; + for (const d of qualified) Y = Y.add(commitmentsBy.get(d)![0]); + if (Y.equals(Point.ZERO)) throw new Error('DKG failed: group key is the identity'); + + const verificationKeys: Record = {}; + for (const j of participants) { + let Yj = Point.ZERO; + for (const d of qualified) Yj = Yj.add(evalCommitments(commitmentsBy.get(d)!, j)); + verificationKeys[j] = Yj.toHex(); + } + + return { threshold, qualified, groupPublicKey: Y.toHex(), verificationKeys }; +} + +export interface DkgFaults { + /** Send corrupted shares to these recipients (complaints follow). */ + corruptSharesTo?: number[]; + /** When accused, publish a wrong share instead of the real one (→ disqualified). */ + lieOnReveal?: boolean; +} + +/** + * One validator's side of the DKG. Holds its polynomial and transport key + * privately; everything it returns is safe to broadcast or route. + */ +export class DkgParticipant { + private readonly transportSecret = randomScalar(); + readonly transportPublicKey = Point.BASE.multiply(this.transportSecret).toHex(); + private readonly coeffs: bigint[]; + private readonly received = new Map(); + + constructor( + readonly index: number, + readonly threshold: number, + readonly participants: number[], + readonly sessionId: string, + private readonly faults: DkgFaults = {} + ) { + if (!participants.includes(index)) throw new Error('participant not in the participant list'); + if (threshold < 1 || threshold > participants.length) throw new Error('invalid threshold'); + this.coeffs = Array.from({ length: threshold }, () => randomScalar()); + } + + private f(x: number): bigint { + return this.coeffs.reduceRight((acc, a) => mod(acc * BigInt(x) + a), 0n); + } + + /** Round 1. `transportKeys` maps recipient index → its transport public key. */ + async deal(transportKeys: Record): Promise<{ broadcast: DealerBroadcast; shares: EncryptedShare[] }> { + const broadcast = { + dealer: this.index, + commitments: this.coeffs.map((a) => Point.BASE.multiply(a).toHex()), + }; + const shares = await Promise.all( + this.participants.map(async (j) => { + let s = this.f(j); + if (this.faults.corruptSharesTo?.includes(j)) s = mod(s + 1n); + const ciphertext = await encryptOrder( + scalarToHex(s), + transportKeys[j], + shareContext(this.sessionId, this.index, j) + ); + return { dealer: this.index, recipient: j, ciphertext }; + }) + ); + return { broadcast, shares }; + } + + /** Round 2. Decrypt and verify the shares addressed to us; return complaints. */ + async receive(broadcasts: DealerBroadcast[], shares: EncryptedShare[]): Promise { + const complaints: Complaint[] = []; + for (const dealer of this.participants) { + const commitments = parseCommitments( + broadcasts.find((b) => b.dealer === dealer), + this.threshold + ); + const msg = shares.find((s) => s.dealer === dealer && s.recipient === this.index); + let share: string | null = null; + if (commitments && msg) { + try { + const K = Point.fromBytes(parseCiphertext(msg.ciphertext).R).multiply(this.transportSecret).toBytes(); + share = await decryptWithSharedPoint(msg.ciphertext, K, shareContext(this.sessionId, dealer, this.index)); + } catch { + share = null; + } + } + if (share && commitments && shareMatches(share, commitments, this.index)) { + this.received.set(dealer, share); + } else if (commitments) { + // Malformed commitments disqualify a dealer outright; no complaint needed. + complaints.push({ complainer: this.index, dealer }); + } + } + return complaints; + } + + /** Round 3. Answer complaints against us by publishing the disputed share. */ + respond(complaints: Complaint[]): Reveal[] { + return complaints + .filter((c) => c.dealer === this.index) + .map((c) => { + const s = this.faults.lieOnReveal ? mod(this.f(c.complainer) + 7n) : this.f(c.complainer); + return { dealer: this.index, recipient: c.complainer, share: scalarToHex(s) }; + }); + } + + /** Round 4. Derive our secret share and the public result from the transcript. */ + finalize(transcript: DkgTranscript): { keyShare: KeyShare; result: DkgPublicResult } { + const result = computePublicResult(transcript, this.participants, this.threshold); + let y = 0n; + for (const dealer of result.qualified) { + const revealed = transcript.reveals.find((r) => r.dealer === dealer && r.recipient === this.index); + const s = this.received.get(dealer) ?? revealed?.share; + if (!s) throw new Error(`no valid share from qualified dealer ${dealer}`); + y = mod(y + hexToScalar(s)); + } + if (y === 0n || y >= L) throw new Error('degenerate key share'); + const verificationKey = Point.BASE.multiply(y).toHex(); + if (verificationKey !== result.verificationKeys[this.index]) { + throw new Error('own key share is inconsistent with the public commitments'); + } + return { keyShare: { index: this.index, secret: scalarToHex(y), verificationKey }, result }; + } +} + diff --git a/backend/src/crypto/threshold.ts b/backend/src/crypto/threshold.ts index aa18cdc..858d154 100644 --- a/backend/src/crypto/threshold.ts +++ b/backend/src/crypto/threshold.ts @@ -2,29 +2,28 @@ * Threshold side of the order cipher (validator-only; never shipped to the * browser). See orderCipher.ts for the encryption scheme. * - * - keygen: t-of-n Shamir sharing of the group secret y. + * - keygen: see dkg.ts — validators jointly generate y so that it + * never exists in one place; each ends up with y_i only. * - partialDecrypt: validator i returns D_i = y_i·R with a Chaum–Pedersen * DLEQ proof that log_G(Y_i) = log_R(D_i), i.e. that it * used its real share and not garbage. * - combine: any t verified shares → K = Σ λ_i·D_i = y·R. * - * Keygen here is a trusted dealer, which is fine for the simulated validator - * set (one process plays every validator). A real deployment needs a DKG - * (e.g. Pedersen/Feldman) so no dealer ever sees y — see - * docs/THRESHOLD_ENCRYPTION.md. + * See docs/THRESHOLD_ENCRYPTION.md for the full design. */ import { ristretto255 } from '@noble/curves/ed25519'; import { sha512 } from '@noble/hashes/sha2'; import { bytesToHex, hexToBytes, parsePoint, randomScalar } from './orderCipher'; -const Point = ristretto255.Point; -type RistrettoPoint = InstanceType; -const L = Point.Fn.ORDER; +export const Point = ristretto255.Point; +export type RistrettoPoint = InstanceType; +export const L = Point.Fn.ORDER; const DLEQ_DOMAIN = new TextEncoder().encode('cipher-protocol/dleq/v1'); -const mod = (a: bigint) => ((a % L) + L) % L; -const scalarToHex = (s: bigint) => s.toString(16).padStart(64, '0'); -const hexToScalar = (h: string) => { +export const mod = (a: bigint) => ((a % L) + L) % L; +export const scalarToHex = (s: bigint) => s.toString(16).padStart(64, '0'); +export const hexToScalar = (h: string) => { + if (!/^[0-9a-f]{64}$/i.test(h)) throw new Error('malformed scalar'); const s = BigInt('0x' + h); if (s <= 0n || s >= L) throw new Error('scalar out of range'); return s; @@ -39,12 +38,6 @@ export interface KeyShare { verificationKey: string; } -export interface ThresholdKeySet { - threshold: number; - groupPublicKey: string; - shares: KeyShare[]; -} - export interface DecryptionShare { index: number; /** D_i = y_i·R, hex. */ @@ -53,26 +46,6 @@ export interface DecryptionShare { proof: { c: string; z: string }; } -export function generateKeySet(threshold: number, total: number): ThresholdKeySet { - if (!Number.isInteger(threshold) || !Number.isInteger(total) || threshold < 1 || threshold > total) { - throw new Error(`invalid threshold ${threshold}-of-${total}`); - } - // f(x) = a_0 + a_1 x + … + a_{t-1} x^{t-1}, with a_0 = y the group secret. - const coeffs = Array.from({ length: threshold }, () => randomScalar()); - const evalAt = (x: bigint) => coeffs.reduceRight((acc, a) => mod(acc * x + a), 0n); - - const shares: KeyShare[] = []; - for (let i = 1; i <= total; i++) { - const secret = evalAt(BigInt(i)); - shares.push({ - index: i, - secret: scalarToHex(secret), - verificationKey: Point.BASE.multiply(secret).toHex(), - }); - } - return { threshold, groupPublicKey: Point.BASE.multiply(coeffs[0]).toHex(), shares }; -} - function challenge(...points: RistrettoPoint[]): bigint { const h = sha512.create().update(DLEQ_DOMAIN); for (const p of points) h.update(p.toBytes()); diff --git a/backend/src/services/validatorNetwork.ts b/backend/src/services/validatorNetwork.ts index c59d678..966088c 100644 --- a/backend/src/services/validatorNetwork.ts +++ b/backend/src/services/validatorNetwork.ts @@ -1,56 +1,189 @@ +import crypto from 'crypto'; import fs from 'fs'; import path from 'path'; -import { ristretto255 } from '@noble/curves/ed25519'; import { config } from '../config'; import { parseCiphertext } from '../crypto/orderCipher'; +import { DecryptionShare, KeyShare, Point, partialDecrypt } from '../crypto/threshold'; import { - DecryptionShare, - KeyShare, - ThresholdKeySet, - generateKeySet, - partialDecrypt, -} from '../crypto/threshold'; + Complaint, + DealerBroadcast, + DkgFaults, + DkgParticipant, + DkgPublicResult, + DkgTranscript, + EncryptedShare, + Reveal, + computePublicResult, +} from '../crypto/dkg'; import logger from '../utils/logger'; /** - * One validator. Holds exactly one secret key share and nothing else — it - * cannot decrypt any order on its own, only contribute y_i·R plus a proof. - * - * SIMULATED: every validator currently lives in this process (keys loaded - * from one file). The interface is deliberately async and per-validator so - * replacing `SimulatedValidator` with an HTTP/gRPC client for a remote - * validator doesn't touch the coordination logic in validatorService. + * A validator as the coordinator sees it. Every method is async and + * per-validator, and nothing in it exposes a secret: swapping + * `SimulatedValidator` for an HTTP/gRPC client to a remote validator + * process doesn't touch validatorService or runDkg. */ export interface ValidatorNode { readonly index: number; readonly address: string; + /** Y_i = y_i·G, known after DKG (or after loading a persisted share). */ readonly verificationKey: string; requestDecryptionShares(ciphertexts: string[]): Promise; + + dkgBegin(sessionId: string, threshold: number, participants: number[]): Promise; + dkgDeal(transportKeys: Record): Promise<{ broadcast: DealerBroadcast; shares: EncryptedShare[] }>; + dkgReceive(broadcasts: DealerBroadcast[], sharesForMe: EncryptedShare[]): Promise; + dkgRespond(complaints: Complaint[]): Promise; + dkgFinalize(transcript: DkgTranscript): Promise; +} + +interface PersistedValidatorKey { + index: number; + threshold: number; + participants: number[]; + groupPublicKey: string; + verificationKeys: Record; + secret: string; +} + +export interface SimulatedValidatorOptions { + /** Return invalid decryption shares (DLEQ verification must reject them). */ + byzantine?: boolean; + /** Misbehave during DKG. */ + dkgFaults?: DkgFaults; + /** Persist this validator's own share here after DKG ('' = memory only). */ + keyFile?: string; } +/** + * SIMULATED: runs inside the backend process. It still keeps exactly one + * secret share, which only it ever sees: the DKG delivers that share + * encrypted to this validator's transport key, and it is stored in this + * validator's own key file. + */ export class SimulatedValidator implements ValidatorNode { - readonly index: number; readonly address: string; - readonly verificationKey: string; + private keyShare: KeyShare | null = null; + private dkg: DkgParticipant | null = null; constructor( - private readonly keyShare: KeyShare, - /** Fault injection for tests/demos: return wrong shares (proofs must catch it). */ - private readonly byzantine = false + readonly index: number, + private readonly opts: SimulatedValidatorOptions = {} ) { - this.index = keyShare.index; - this.address = `sim-validator-${keyShare.index}`; - this.verificationKey = keyShare.verificationKey; + this.address = `sim-validator-${index}`; + } + + static fromPersisted(key: PersistedValidatorKey, opts: SimulatedValidatorOptions = {}) { + const v = new SimulatedValidator(key.index, opts); + v.keyShare = { index: key.index, secret: key.secret, verificationKey: key.verificationKeys[key.index] }; + return v; + } + + get verificationKey(): string { + if (!this.keyShare) throw new Error(`${this.address} has no key share yet (DKG not run)`); + return this.keyShare.verificationKey; } async requestDecryptionShares(ciphertexts: string[]): Promise { + if (!this.keyShare) throw new Error(`${this.address} has no key share`); + const keyShare = this.keyShare; return ciphertexts.map((ct) => { - const share = partialDecrypt(this.keyShare, parseCiphertext(ct).R); + const share = partialDecrypt(keyShare, parseCiphertext(ct).R); // A byzantine validator substitutes a valid-looking point that is not // y_i·R; its DLEQ proof then fails and the coordinator discards it. - return this.byzantine ? { ...share, share: ristretto255.Point.BASE.toHex() } : share; + return this.opts.byzantine ? { ...share, share: Point.BASE.toHex() } : share; }); } + + async dkgBegin(sessionId: string, threshold: number, participants: number[]) { + this.dkg = new DkgParticipant(this.index, threshold, participants, sessionId, this.opts.dkgFaults); + return this.dkg.transportPublicKey; + } + + private session(): DkgParticipant { + if (!this.dkg) throw new Error('no DKG session in progress'); + return this.dkg; + } + + async dkgDeal(transportKeys: Record) { + return this.session().deal(transportKeys); + } + + async dkgReceive(broadcasts: DealerBroadcast[], sharesForMe: EncryptedShare[]) { + return this.session().receive(broadcasts, sharesForMe); + } + + async dkgRespond(complaints: Complaint[]) { + return this.session().respond(complaints); + } + + async dkgFinalize(transcript: DkgTranscript) { + const session = this.session(); + const { keyShare, result } = session.finalize(transcript); + this.keyShare = keyShare; + this.dkg = null; + if (this.opts.keyFile) { + const persisted: PersistedValidatorKey = { + index: this.index, + threshold: result.threshold, + participants: session.participants, + groupPublicKey: result.groupPublicKey, + verificationKeys: result.verificationKeys, + secret: keyShare.secret, + }; + fs.mkdirSync(path.dirname(this.opts.keyFile), { recursive: true }); + fs.writeFileSync(this.opts.keyFile, JSON.stringify(persisted, null, 2), { mode: 0o600 }); + } + return result; + } +} + +/** + * Drives the DKG rounds. The coordinator only routes messages: shares + * travel encrypted to their recipient, so it never sees a secret. It ends by + * checking that every validator derived the same public result. + */ +export async function runDkg(nodes: ValidatorNode[], threshold: number, sessionId = crypto.randomUUID()) { + const participants = nodes.map((n) => n.index); + const transportKeys: Record = {}; + await Promise.all( + nodes.map(async (n) => { + transportKeys[n.index] = await n.dkgBegin(sessionId, threshold, participants); + }) + ); + + // A dealer that fails to deal simply ends up outside QUAL. + const dealt = await Promise.allSettled(nodes.map((n) => n.dkgDeal(transportKeys))); + const broadcasts: DealerBroadcast[] = []; + const shares: EncryptedShare[] = []; + dealt.forEach((d, k) => { + if (d.status === 'fulfilled') { + broadcasts.push(d.value.broadcast); + shares.push(...d.value.shares); + } else { + logger.warn(`[dkg ${sessionId}] validator ${nodes[k].index} failed to deal: ${d.reason}`); + } + }); + + const complaints = ( + await Promise.all(nodes.map((n) => n.dkgReceive(broadcasts, shares.filter((s) => s.recipient === n.index)))) + ).flat(); + const reveals = (await Promise.all(nodes.map((n) => n.dkgRespond(complaints)))).flat(); + const transcript: DkgTranscript = { broadcasts, complaints, reveals }; + + const expected = computePublicResult(transcript, participants, threshold); + const results = await Promise.all(nodes.map((n) => n.dkgFinalize(transcript))); + for (const r of results) { + if (r.groupPublicKey !== expected.groupPublicKey) throw new Error('DKG failed: validators disagree on the group key'); + } + for (const c of complaints) { + const resolved = expected.qualified.includes(c.dealer); + logger.warn( + `[dkg ${sessionId}] validator ${c.complainer} complained about dealer ${c.dealer}: ` + + (resolved ? 'resolved by a valid public reveal' : 'dealer disqualified') + ); + } + return { result: expected, transcript }; } export interface ValidatorNetwork { @@ -60,46 +193,91 @@ export interface ValidatorNetwork { } let network: ValidatorNetwork | null = null; +let initializing: Promise | null = null; -function loadOrCreateKeySet(): ThresholdKeySet { - const file = config.validatorKeyFile; - if (file && fs.existsSync(file)) { - const keySet = JSON.parse(fs.readFileSync(file, 'utf8')) as ThresholdKeySet; - if (keySet.shares.length !== config.validatorCount || keySet.threshold !== config.validatorThreshold) { - throw new Error( - `${file} holds a ${keySet.threshold}-of-${keySet.shares.length} key set but config asks for ` + - `${config.validatorThreshold}-of-${config.validatorCount}; delete it to re-key (pending orders become undecryptable)` - ); - } - return keySet; +const keyFileFor = (dir: string, index: number) => (dir ? path.join(dir, `validator-${index}.json`) : ''); + +export interface CreateNetworkOptions { + count: number; + threshold: number; + byzantine?: number[]; + dkgFaults?: Record; + keyDir?: string; +} + +/** Spins up `count` simulated validators and has them run a fresh DKG. */ +export async function createSimulatedNetwork(opts: CreateNetworkOptions): Promise { + const validators = Array.from( + { length: opts.count }, + (_, k) => + new SimulatedValidator(k + 1, { + byzantine: opts.byzantine?.includes(k + 1), + dkgFaults: opts.dkgFaults?.[k + 1], + keyFile: keyFileFor(opts.keyDir ?? '', k + 1), + }) + ); + const { result, transcript } = await runDkg(validators, opts.threshold); + if (opts.keyDir) { + fs.writeFileSync(path.join(opts.keyDir, 'dkg-transcript.json'), JSON.stringify({ result, transcript }, null, 2)); } + return { threshold: result.threshold, groupPublicKey: result.groupPublicKey, validators, dkg: result }; +} - const keySet = generateKeySet(config.validatorThreshold, config.validatorCount); - if (file) { - fs.mkdirSync(path.dirname(file), { recursive: true }); - fs.writeFileSync(file, JSON.stringify(keySet, null, 2), { mode: 0o600 }); - logger.warn( - `Generated a new simulated ${keySet.threshold}-of-${keySet.shares.length} validator key set at ${file}. ` + - 'Trusted-dealer keygen is for development only.' +function loadPersistedNetwork(dir: string): ValidatorNetwork | null { + const files = Array.from({ length: config.validatorCount }, (_, k) => keyFileFor(dir, k + 1)); + const present = files.filter((f) => fs.existsSync(f)); + if (present.length === 0) return null; + if (present.length !== files.length) { + throw new Error(`${dir} has ${present.length}/${files.length} validator key files; restore them or delete all to re-run DKG`); + } + const keys = files.map((f) => JSON.parse(fs.readFileSync(f, 'utf8')) as PersistedValidatorKey); + const { groupPublicKey, threshold } = keys[0]; + if (keys.some((k) => k.groupPublicKey !== groupPublicKey || k.threshold !== threshold)) { + throw new Error(`validator key files in ${dir} come from different DKG sessions`); + } + if (threshold !== config.validatorThreshold) { + throw new Error( + `persisted keys are ${threshold}-of-${keys.length} but config asks for ${config.validatorThreshold}-of-${config.validatorCount}; ` + + 'delete the key directory to re-run DKG (pending orders become undecryptable)' ); } - return keySet; + const validators = keys.map((k) => + SimulatedValidator.fromPersisted(k, { byzantine: config.byzantineValidators.includes(k.index) }) + ); + return { threshold, groupPublicKey, validators }; } -export function getValidatorNetwork(): ValidatorNetwork { +/** Loads persisted validator shares, or runs a fresh DKG on first start. */ +export async function initValidatorNetwork(): Promise { if (network) return network; - const keySet = loadOrCreateKeySet(); - network = { - threshold: keySet.threshold, - groupPublicKey: keySet.groupPublicKey, - validators: keySet.shares.map( - (share) => new SimulatedValidator(share, config.byzantineValidators.includes(share.index)) - ), - }; + initializing ??= (async () => { + const dir = config.validatorKeyDir; + const loaded = dir ? loadPersistedNetwork(dir) : null; + if (loaded) return loaded; + const created = await createSimulatedNetwork({ + count: config.validatorCount, + threshold: config.validatorThreshold, + byzantine: config.byzantineValidators, + keyDir: dir, + }); + logger.info( + `DKG complete: ${created.threshold}-of-${created.validators.length}, ` + + `${created.dkg.qualified.length} qualified dealers${dir ? `, shares stored per validator in ${dir}` : ''}` + ); + return created; + })().finally(() => { + initializing = null; + }); + network = await initializing; + return network; +} + +export function getValidatorNetwork(): ValidatorNetwork { + if (!network) throw new Error('validator network not initialized; call initValidatorNetwork() first'); return network; } -/** Test hook: swap in a specific network (or reset to lazy-load from config). */ +/** Test hook: swap in a specific network (or reset so the next init reloads from config). */ export function setValidatorNetwork(next: ValidatorNetwork | null): void { network = next; } diff --git a/backend/src/services/validatorService.ts b/backend/src/services/validatorService.ts index 556b36e..73eebc3 100644 --- a/backend/src/services/validatorService.ts +++ b/backend/src/services/validatorService.ts @@ -5,7 +5,7 @@ import { DecryptionShare, combineShares, verifyDecryptionShare } from '../crypto import { DecryptedOrder } from '../types/order'; import { getErrorMessage } from '../utils/errors'; import logger from '../utils/logger'; -import { getValidatorNetwork } from './validatorNetwork'; +import { getValidatorNetwork, initValidatorNetwork } from './validatorNetwork'; export type DecryptionOutcome = | { orderId: string; ok: true; order: DecryptedOrder } @@ -51,7 +51,7 @@ export const validatorService = { * claims about itself. */ async syncValidatorRegistry() { - const { validators } = getValidatorNetwork(); + const { validators } = await initValidatorNetwork(); for (const v of validators) { const [row] = await Validator.findOrCreate({ where: { address: v.address }, diff --git a/backend/tests/dkg.test.ts b/backend/tests/dkg.test.ts new file mode 100644 index 0000000..c014f79 --- /dev/null +++ b/backend/tests/dkg.test.ts @@ -0,0 +1,155 @@ +import { describe, it, expect } from 'vitest'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { decryptWithSharedPoint, encryptOrder, parseCiphertext } from '../src/crypto/orderCipher'; +import { Point, combineShares, lagrangeAtZero, mod, partialDecrypt, KeyShare } from '../src/crypto/threshold'; +import { DkgParticipant, computePublicResult } from '../src/crypto/dkg'; +import { createSimulatedNetwork, runDkg, SimulatedValidator } from '../src/services/validatorNetwork'; + +const USER = 'GTESTUSER'; + +/** TEST-ONLY peek: reconstruct y from t shares to check it matches Y. No production code can do this. */ +function reconstructSecret(shares: KeyShare[]): bigint { + const idx = shares.map((s) => s.index); + return shares.reduce((acc, s) => mod(acc + BigInt('0x' + s.secret) * lagrangeAtZero(s.index, idx)), 0n); +} + +function sharesOf(validators: SimulatedValidator[]): KeyShare[] { + // Reach into the simulated validators — only possible because they're in-process. + return validators.map((v) => (v as unknown as { keyShare: KeyShare }).keyShare); +} + +async function roundTrip(groupKey: string, shares: KeyShare[], subset: number[]) { + const ct = await encryptOrder('{"order":1}', groupKey, USER); + const R = parseCiphertext(ct).R; + const ds = subset.map((i) => partialDecrypt(shares[i - 1], R)); + return decryptWithSharedPoint(ct, combineShares(ds, 3), USER); +} + +describe('distributed key generation', () => { + it('produces a consistent t-of-n key that any t validators can use', async () => { + const net = await createSimulatedNetwork({ count: 5, threshold: 3 }); + const shares = sharesOf(net.validators as SimulatedValidator[]); + + expect(net.dkg.qualified).toEqual([1, 2, 3, 4, 5]); + for (const s of shares) { + expect(Point.BASE.multiply(BigInt('0x' + s.secret)).toHex()).toBe(net.dkg.verificationKeys[s.index]); + } + // Every t-subset interpolates to the same secret, matching the public group key. + for (const subset of [[0, 1, 2], [2, 3, 4], [0, 2, 4]]) { + const y = reconstructSecret(subset.map((i) => shares[i])); + expect(Point.BASE.multiply(y).toHex()).toBe(net.groupPublicKey); + } + expect(await roundTrip(net.groupPublicKey, shares, [1, 4, 5])).toBe('{"order":1}'); + }); + + it('two runs produce independent keys', async () => { + const a = await createSimulatedNetwork({ count: 3, threshold: 2 }); + const b = await createSimulatedNetwork({ count: 3, threshold: 2 }); + expect(a.groupPublicKey).not.toBe(b.groupPublicKey); + }); + + it('the coordinator never sees a secret share: the transcript holds only ciphertext and commitments', async () => { + const validators = Array.from({ length: 5 }, (_, k) => new SimulatedValidator(k + 1)); + const routed: string[] = []; + // Wrap deal() to capture exactly what passes through the coordinator. + for (const v of validators) { + const deal = v.dkgDeal.bind(v); + v.dkgDeal = async (keys) => { + const out = await deal(keys); + routed.push(JSON.stringify(out)); + return out; + }; + } + const { transcript } = await runDkg(validators, 3); + const seen = routed.join('') + JSON.stringify(transcript); + for (const s of sharesOf(validators)) expect(seen).not.toContain(s.secret); + expect(transcript.complaints).toEqual([]); + expect(transcript.reveals).toEqual([]); + }); + + it('a dealer that sends a bad share but answers the complaint honestly stays qualified', async () => { + const net = await createSimulatedNetwork({ count: 5, threshold: 3, dkgFaults: { 2: { corruptSharesTo: [4] } } }); + expect(net.dkg.qualified).toEqual([1, 2, 3, 4, 5]); + const shares = sharesOf(net.validators as SimulatedValidator[]); + expect(await roundTrip(net.groupPublicKey, shares, [2, 3, 4])).toBe('{"order":1}'); + }); + + it('a dealer that lies when accused is disqualified, and the rest still produce a working key', async () => { + const net = await createSimulatedNetwork({ + count: 5, + threshold: 3, + dkgFaults: { 3: { corruptSharesTo: [1, 5], lieOnReveal: true } }, + }); + expect(net.dkg.qualified).toEqual([1, 2, 4, 5]); + const shares = sharesOf(net.validators as SimulatedValidator[]); + // The disqualified dealer is still a share-holder (QUAL is about dealing). + expect(await roundTrip(net.groupPublicKey, shares, [3, 4, 5])).toBe('{"order":1}'); + }); + + it('aborts when too many dealers are disqualified', async () => { + const liar = { corruptSharesTo: [1], lieOnReveal: true }; + await expect( + createSimulatedNetwork({ count: 5, threshold: 3, dkgFaults: { 2: liar, 3: liar, 4: liar } }) + ).rejects.toThrow(/only 2 qualified dealers, need at least 3/); + }); + + it('a share delivered to the wrong recipient fails to decrypt and draws a complaint', async () => { + const ps = [1, 2, 3].map((i) => new DkgParticipant(i, 2, [1, 2, 3], 'session-x')); + const keys = Object.fromEntries(ps.map((p) => [p.index, p.transportPublicKey])); + const dealt = await Promise.all(ps.map((p) => p.deal(keys))); + const broadcasts = dealt.map((d) => d.broadcast); + const shares = dealt.flatMap((d) => d.shares); + // Dealer 1's share for validator 2, relabelled and routed to validator 3. + const misrouted = shares.map((s) => + s.dealer === 1 && s.recipient === 3 ? { ...shares.find((x) => x.dealer === 1 && x.recipient === 2)!, recipient: 3 } : s + ); + expect(await ps[2].receive(broadcasts, misrouted.filter((s) => s.recipient === 3))).toEqual([ + { complainer: 3, dealer: 1 }, + ]); + }); + + it('a share replayed from another DKG session is rejected', async () => { + const mk = (session: string) => [1, 2].map((i) => new DkgParticipant(i, 2, [1, 2], session)); + const [a, b] = [mk('s1'), mk('s2')]; + // Same recipient transport key in both sessions to isolate session binding. + const keysA = Object.fromEntries(a.map((p) => [p.index, p.transportPublicKey])); + const dealtA = await Promise.all(a.map((p) => p.deal(keysA))); + const dealtB = await Promise.all(b.map((p) => p.deal(keysA))); + const replayed = dealtB.flatMap((d) => d.shares).filter((s) => s.recipient === 1); + const complaints = await a[0].receive(dealtA.map((d) => d.broadcast), replayed); + expect(complaints.map((c) => c.dealer).sort()).toEqual([1, 2]); + }); + + it('malformed or equivocating commitments disqualify a dealer without a complaint round', () => { + const G = Point.BASE.toHex(); + const good = (dealer: number) => ({ dealer, commitments: [G, G] }); + const base = { complaints: [], reveals: [] }; + expect( + computePublicResult({ ...base, broadcasts: [good(1), good(2), { dealer: 3, commitments: [G] }] }, [1, 2, 3], 2) + .qualified + ).toEqual([1, 2]); + expect( + computePublicResult({ ...base, broadcasts: [good(1), good(2), good(3), good(3)] }, [1, 2, 3], 2).qualified + ).toEqual([1, 2]); + }); + + it('persists one key file per validator, each holding only its own share', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cipher-dkg-')); + try { + const net = await createSimulatedNetwork({ count: 3, threshold: 2, keyDir: dir }); + const shares = sharesOf(net.validators as SimulatedValidator[]); + for (const s of shares) { + const file = fs.readFileSync(path.join(dir, `validator-${s.index}.json`), 'utf8'); + expect(JSON.parse(file).secret).toBe(s.secret); + for (const other of shares) if (other.index !== s.index) expect(file).not.toContain(other.secret); + expect(fs.statSync(path.join(dir, `validator-${s.index}.json`)).mode & 0o077).toBe(0); + } + const transcript = fs.readFileSync(path.join(dir, 'dkg-transcript.json'), 'utf8'); + for (const s of shares) expect(transcript).not.toContain(s.secret); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/backend/tests/fixtures/dealer.ts b/backend/tests/fixtures/dealer.ts new file mode 100644 index 0000000..0d441a8 --- /dev/null +++ b/backend/tests/fixtures/dealer.ts @@ -0,0 +1,21 @@ +import { KeyShare, Point, mod, scalarToHex } from '../../src/crypto/threshold'; +import { randomScalar } from '../../src/crypto/orderCipher'; + +/** + * Trusted-dealer Shamir sharing — TEST FIXTURE ONLY. Production keys come + * from the DKG (src/crypto/dkg.ts); this exists so the threshold math can be + * unit-tested independently of the DKG protocol. + */ +export function dealKeySet(threshold: number, total: number) { + if (!Number.isInteger(threshold) || threshold < 1 || threshold > total) { + throw new Error(`invalid threshold ${threshold}-of-${total}`); + } + const coeffs = Array.from({ length: threshold }, () => randomScalar()); + const evalAt = (x: bigint) => coeffs.reduceRight((acc, a) => mod(acc * x + a), 0n); + const shares: KeyShare[] = []; + for (let i = 1; i <= total; i++) { + const secret = evalAt(BigInt(i)); + shares.push({ index: i, secret: scalarToHex(secret), verificationKey: Point.BASE.multiply(secret).toHex() }); + } + return { threshold, groupPublicKey: Point.BASE.multiply(coeffs[0]).toHex(), shares }; +} diff --git a/backend/tests/pipeline.test.ts b/backend/tests/pipeline.test.ts index 2ebe531..63f8ad6 100644 --- a/backend/tests/pipeline.test.ts +++ b/backend/tests/pipeline.test.ts @@ -4,22 +4,16 @@ import { createApp } from '../src/app'; import { sequelize } from '../src/db'; import { Order } from '../src/db/models/Order'; import { Batch } from '../src/db/models/Batch'; -import { generateKeySet } from '../src/crypto/threshold'; import { batchingService } from '../src/services/batchingService'; -import { SimulatedValidator, setValidatorNetwork } from '../src/services/validatorNetwork'; +import { createSimulatedNetwork, setValidatorNetwork } from '../src/services/validatorNetwork'; import { validatorService } from '../src/services/validatorService'; import { authHeaders, newUser, submitSwap } from './helpers'; const app = createApp(); -/** Fresh 3-of-5 validator set where the listed indices misbehave. */ +/** Fresh 3-of-5 validator set, keyed by a real DKG, where the listed indices misbehave. */ async function useNetwork(byzantine: number[] = []) { - const keys = generateKeySet(3, 5); - setValidatorNetwork({ - threshold: keys.threshold, - groupPublicKey: keys.groupPublicKey, - validators: keys.shares.map((s) => new SimulatedValidator(s, byzantine.includes(s.index))), - }); + setValidatorNetwork(await createSimulatedNetwork({ count: 5, threshold: 3, byzantine })); await validatorService.syncValidatorRegistry(); } diff --git a/backend/tests/setupEnv.ts b/backend/tests/setupEnv.ts index 5f85e4d..9fcf045 100644 --- a/backend/tests/setupEnv.ts +++ b/backend/tests/setupEnv.ts @@ -1,7 +1,7 @@ // Runs before any module is imported: isolated in-memory DB, in-memory // validator keys, no on-chain calls (contract IDs unset → stubbed results). process.env.DATABASE_URL = ':memory:'; -process.env.VALIDATOR_KEY_FILE = ''; +process.env.VALIDATOR_KEY_DIR = ''; process.env.VALIDATOR_COUNT = '5'; process.env.VALIDATOR_THRESHOLD = '3'; process.env.ORDER_VAULT_CONTRACT = ''; diff --git a/backend/tests/threshold.test.ts b/backend/tests/threshold.test.ts index be986fa..3bd58a8 100644 --- a/backend/tests/threshold.test.ts +++ b/backend/tests/threshold.test.ts @@ -4,16 +4,16 @@ import path from 'path'; import { decryptWithSharedPoint, encryptOrder, parseCiphertext } from '../src/crypto/orderCipher'; import { combineShares, - generateKeySet, lagrangeAtZero, partialDecrypt, verifyDecryptionShare, } from '../src/crypto/threshold'; +import { dealKeySet } from './fixtures/dealer'; const USER = 'GBUSERADDRESSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; describe('threshold order cipher', () => { - const keys = generateKeySet(3, 5); + const keys = dealKeySet(3, 5); async function sealed(msg = '{"swap":1}') { const ct = await encryptOrder(msg, keys.groupPublicKey, USER); @@ -91,8 +91,8 @@ describe('threshold order cipher', () => { }); it('rejects invalid threshold parameters', () => { - expect(() => generateKeySet(0, 3)).toThrow(); - expect(() => generateKeySet(4, 3)).toThrow(); + expect(() => dealKeySet(0, 3)).toThrow(); + expect(() => dealKeySet(4, 3)).toThrow(); }); it('frontend ships a byte-identical copy of the cipher', () => { From f4cad4773ba2fde6b4e0929e3bfdc783ebff18fa Mon Sep 17 00:00:00 2001 From: FEDDIE Date: Fri, 6 Nov 2026 22:44:34 +0000 Subject: [PATCH 3/3] Docs: describe the DKG, and narrow the remaining trust gap Explain the DKG rounds, map each DKG property to its test, and state its limitations (Joint-Feldman key bias, broadcast assumption). The 'simulated' caveat is now precise: there is no dealer, but validators sharing one process means one operator could still collect t shares until the validators run remotely. Contributor issue #1 becomes the GJKR unbiased-DKG upgrade. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 4 +- README.md | 15 ++++--- SECURITY.md | 3 +- docs/CONTRIBUTOR_ISSUES.md | 41 +++++++++-------- docs/THRESHOLD_ENCRYPTION.md | 78 +++++++++++++++++++++++++++------ frontend/src/pages/DocsPage.tsx | 8 ++-- 6 files changed, 106 insertions(+), 43 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f90623c..8cc1023 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -51,8 +51,8 @@ understand the scope of the fix. ## Security -Known, documented gaps (the simulated validator set and the trusted-dealer -keygen) are tracked in [docs/THRESHOLD_ENCRYPTION.md](docs/THRESHOLD_ENCRYPTION.md) +Known, documented gaps (validators sharing one process, and the +Joint-Feldman DKG's key-bias limitation) are tracked in [docs/THRESHOLD_ENCRYPTION.md](docs/THRESHOLD_ENCRYPTION.md) and in the open issues. If you find a *new* vulnerability, report it privately through GitHub's **Security → Report a vulnerability** tab rather than in a public issue (see [SECURITY.md](SECURITY.md)). diff --git a/README.md b/README.md index fe47a1a..452cc1b 100644 --- a/README.md +++ b/README.md @@ -69,16 +69,21 @@ What's real and tested: - **Contracts** (`contracts/`): `order-vault` and `settlement-engine`, deployed to testnet. `settle_batch` executes a real x*y=k AMM swap with fees, verified against on-chain token balances. -- **Tests and CI**: 31 backend tests (crypto, end-to-end pipeline, auth), +- **Distributed key generation** (`backend/src/crypto/dkg.ts`): validators + jointly generate the threshold key (Joint-Feldman with complaints), so no + dealer ever knows the group secret. Shares travel encrypted to their + recipient, and dealers who cheat are disqualified. +- **Tests and CI**: 41 backend tests (crypto, DKG, end-to-end pipeline, auth), 8 frontend tests, and the contract suites. They run on every PR, together with a source-integrity check that blocks hidden or obfuscated code. What's **not** real yet: -- **The validator set is simulated.** All `n` validators run inside the - backend process, and keys come from a trusted dealer. So the operator - could still reconstruct the group key. The cryptography is real, but the - distribution of trust isn't yet. Next steps: DKG and remote validators +- **The validators share one process.** There's no dealer anymore, but all + `n` validators run inside the backend and keep their share files on one + disk. So the operator of that machine could still collect `t` shares. The + cryptography is real, but trust is only truly distributed once each + validator runs on its own machine. Next step: remote validators (see [the design doc](docs/THRESHOLD_ENCRYPTION.md#what-is-simulated-and-whats-next)). - **The on-chain vault is an attestation, not a ledger of orders.** `order-vault.create_batch` records an admin-signed hash and count. The diff --git a/SECURITY.md b/SECURITY.md index 684e47b..de82f13 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -16,7 +16,8 @@ In scope: the threshold encryption and share verification the Soroban contracts. Known, already-documented limitations, and therefore not new reports: the -validator set is simulated in-process, and keygen uses a trusted dealer. See +validators run in one process, and DKG uses Joint-Feldman, which allows +bias of the group key's distribution but not its disclosure. See [docs/THRESHOLD_ENCRYPTION.md](docs/THRESHOLD_ENCRYPTION.md). ## Supply-chain hygiene diff --git a/docs/CONTRIBUTOR_ISSUES.md b/docs/CONTRIBUTOR_ISSUES.md index da033dc..a35f5cb 100644 --- a/docs/CONTRIBUTOR_ISSUES.md +++ b/docs/CONTRIBUTOR_ISSUES.md @@ -3,38 +3,43 @@ Point values follow Drips Wave's complexity bands (100/150/200). Each section is a ready-to-post issue body. See the commands at the bottom. -**Already done** (were issues #1–#5 and #8 in the first draft): threshold -encryption, validator share coordination (simulated set), signature auth, +**Already done:** threshold encryption, validator share coordination, +distributed key generation (Joint-Feldman with complaints), signature auth, backend and frontend test suites, and CI. See the root README's Status section. --- -### 1. Distributed key generation for the validator set (200) +### 1. Unbiased DKG: Pedersen commitments in round 1 (150) -`backend/src/crypto/threshold.ts#generateKeySet` is a trusted dealer, so -whoever runs keygen learns the group secret `y`. Replace it with a -Pedersen/Feldman DKG so `y` never exists in one place. Every validator -should end up with only its own share `y_i`, plus public `Y` and -`Y_i = y_i·G` for all `i`. +`backend/src/crypto/dkg.ts` implements Joint-Feldman DKG with complaints. +A dealer that waits to see the others' Feldman commitments can bias the +distribution of the group key (it still can't learn the secret). Upgrade +round 1 to GJKR: deal with Pedersen commitments `a·G + b·H` (with `H` from +`Point.hashToCurve`), and only publish Feldman commitments for `QUAL` +afterwards. -**Scope:** DKG rounds (commitments, share distribution, complaint and -verification), run across the in-process `SimulatedValidator`s, plus tests -showing (a) the result decrypts through the existing `combineShares` path -and (b) a dealer that sends an inconsistent share is detected. -**Read first:** [docs/THRESHOLD_ENCRYPTION.md](THRESHOLD_ENCRYPTION.md). +**Scope:** `DkgParticipant` round 1 and the extraction round, plus tests. +All existing `dkg.test.ts` cases must still pass. +**Read first:** the "Key generation (DKG)" section of +[docs/THRESHOLD_ENCRYPTION.md](THRESHOLD_ENCRYPTION.md). --- ### 2. Remote validator nodes (200) All validators are `SimulatedValidator` instances inside the backend -process. Build a standalone validator service (one share per process) and a +process. The DKG removed the dealer, but co-located validators mean one +operator could still collect `t` shares. Build a standalone validator service (one share per process) and a `RemoteValidator` client implementing the existing `ValidatorNode` interface in `backend/src/services/validatorNetwork.ts`. -**Acceptance:** the pipeline tests pass against 5 validator processes, and -the same tests pass with 2 of them killed. The validator only releases +Both the decryption calls and the DKG rounds already go through that +interface. Broadcasts need sender signatures once they cross the network. + +**Acceptance:** DKG runs across 5 validator processes, each persisting only +its own share. The pipeline tests pass against them, and still pass with 2 +of them killed. The validator only releases shares for a batch whose `order-vault` attestation exists on-chain. --- @@ -102,7 +107,7 @@ done gh label create "help wanted" --repo CiipherProtocol/CipherProtocol --color 008672 gh issue create --repo CiipherProtocol/CipherProtocol \ - --title "Distributed key generation for the validator set" \ - --label "help wanted,points:200" --body-file issue-1.md + --title "Unbiased DKG: Pedersen commitments in round 1" \ + --label "help wanted,points:150" --body-file issue-1.md # …repeat per issue with its points label ``` diff --git a/docs/THRESHOLD_ENCRYPTION.md b/docs/THRESHOLD_ENCRYPTION.md index 3f5aacb..0e55c5b 100644 --- a/docs/THRESHOLD_ENCRYPTION.md +++ b/docs/THRESHOLD_ENCRYPTION.md @@ -19,9 +19,11 @@ HKDF-SHA256 and AES-256-GCM. The code is in (`orderCipher.ts`) is shipped byte-identically to the frontend, and a test enforces that. -**Setup (t-of-n).** The group secret `y` is split with Shamir secret sharing -into shares `y_1 … y_n`. Validator `i` holds `y_i`. Everyone knows the group -key `Y = y·G` and each validator's verification key `Y_i = y_i·G`. +**Setup (t-of-n), by distributed key generation.** The validators jointly +generate a group secret `y` that **no party ever holds**: not a validator, +not the coordinator, not the operator. Validator `i` ends up with only a +Shamir share `y_i`. Everyone knows the group key `Y = y·G` and each +validator's verification key `Y_i = y_i·G`. See [Key generation](#key-generation-dkg). **Encrypt (browser).** For an order `m` from user address `addr`: @@ -55,21 +57,71 @@ derive `k` and open the ciphertext. | The backend stores no plaintext before settlement | The client sends only `{encrypted_data, threshold_pubkey, nonce}` | `pipeline.test.ts`, `SwapForm.test.tsx` | | Ordering is fixed before contents are known | The batch is sealed (and attested on-chain) before decryption is requested | `batchingService.runOnce` | +## Key generation (DKG) + +Joint-Feldman DKG with a complaint round (Pedersen '91; Gennaro, Jarecki, +Krawczyk and Rabin '99), in [`dkg.ts`](../backend/src/crypto/dkg.ts): + +1. **Deal.** Each validator `i` picks a random polynomial `f_i` of degree + `t−1` and broadcasts Feldman commitments `C_{i,k} = a_{i,k}·G`. It sends + `s_{i→j} = f_i(j)` to each `j`, **encrypted to `j`'s transport key** with + the same ElGamal + AES-GCM cipher used for orders. The AAD binds each + share to the session, dealer and recipient. The coordinator routing these + messages never sees a share, and a test checks that. +2. **Verify.** `j` decrypts and checks `s_{i→j}·G = Σ_k j^k·C_{i,k}`. A + missing, undecryptable or inconsistent share means `j` complains about `i`. +3. **Respond.** An accused dealer must publish the disputed share. If it + checks out against the dealer's commitments, `j` uses it. If not, or if + the dealer stays silent, the dealer is disqualified. +4. **Finalize.** `QUAL` is the set of dealers with well-formed commitments, + no equivocation, and no unanswered complaint. Then + `y_j = Σ_{i∈QUAL} s_{i→j}`, `Y = Σ_{i∈QUAL} C_{i,0}`, and the verification + keys follow from the commitments alone. Everything is computed from the + public transcript, so every honest validator, and any auditor, derives + the same `QUAL` and keys. The DKG aborts if `|QUAL| < t`. Each validator + also checks that `y_j·G` matches its public `Y_j`. + +Each validator persists only its own share, in +`data/validators/validator-.json` (mode 0600). The public transcript goes +to `dkg-transcript.json` for audit. + +| DKG property | Test (`dkg.test.ts`) | +|---|---| +| Any t shares interpolate to the secret behind `Y`, and orders decrypt | "consistent t-of-n key" | +| The coordinator never sees a secret share | "never sees a secret share" | +| Bad share + honest reveal: complaint resolved, dealer kept | "answers the complaint honestly" | +| Bad share + lying reveal: dealer disqualified, key still works | "lies when accused" | +| Too few qualified dealers: abort | "too many dealers are disqualified" | +| Misrouted or cross-session replayed shares are rejected | "wrong recipient", "another DKG session" | +| Malformed or equivocating commitments: disqualified | "equivocating commitments" | + +**Known DKG limitations:** + +- *Key bias.* Plain Joint-Feldman lets a dealer who waits for the others' + commitments bias the **distribution** of `Y`. It still can't learn `y`. + GJKR fixes this with Pedersen commitments in round 1, and only round 1 + changes. +- *Broadcast channel.* The protocol assumes everyone sees the same + broadcasts. In-process, that's trivially true. With remote validators, + broadcasts must be signed by their sender, and equivocation (two different + commitments from one dealer) is already treated as disqualifying. + ## What is simulated, and what's next Being honest about the remaining gaps: -1. **Trusted-dealer keygen.** One process generates `y` and splits it, so at - that moment it knows `y`. Production needs a distributed key generation - (Pedersen/Feldman DKG) so `y` never exists in one place. -2. **Validators run in-process.** `SimulatedValidator` implements the - `ValidatorNode` interface, and all five live in the backend with their - shares in one dev-only file. The interface is async and per-validator, - so a remote validator (HTTP/gRPC client) can replace it without changing - the coordinator. Each real validator should also check the batch's - on-chain attestation before releasing shares. -3. **The coordinator is the backend.** After combining shares, the backend +1. **Validators run in-process.** This is now the main gap. The DKG means + no dealer ever knows `y`. But all five `SimulatedValidator`s live in the + backend process, and their key files sit on one disk, so whoever operates + that machine could still read `t` shares. The fix is to run each + validator on its own machine with its own operator. The `ValidatorNode` + interface (decryption *and* DKG rounds) is async and per-validator, so a + remote client can replace `SimulatedValidator` without changing the + coordinator or `runDkg`. Each real validator should also check the + batch's on-chain attestation before releasing shares. +2. **The coordinator is the backend.** After combining shares, the backend sees the plaintext, but only for sealed batches. Moving combination on-chain or into the settlement transaction is future work. +3. **DKG key bias** (see above): upgrade round 1 to Pedersen commitments. The [contributor issues](CONTRIBUTOR_ISSUES.md) track each of these. diff --git a/frontend/src/pages/DocsPage.tsx b/frontend/src/pages/DocsPage.tsx index e76581c..aca3a7b 100644 --- a/frontend/src/pages/DocsPage.tsx +++ b/frontend/src/pages/DocsPage.tsx @@ -13,7 +13,7 @@ const SECTIONS = [ }, { title: '4. Threshold decryption', - body: 'Only after sealing does each validator compute a decryption share with a zero-knowledge proof that it’s correct. Any t of n valid shares decrypt the batch. Fewer reveal nothing, and invalid shares are detected and discarded.', + body: 'The validators generated the encryption key together (distributed key generation), so no one ever held the whole key. Only after sealing does each validator compute a decryption share with a zero-knowledge proof that it’s correct. Any t of n valid shares decrypt the batch. Fewer reveal nothing, and invalid shares are detected and discarded.', }, { title: '5. Atomic settlement', @@ -36,9 +36,9 @@ export default function DocsPage() {

Still simulated

- The encryption and share verification are real, but all validators currently run inside one backend - process with keys from a trusted dealer. Distributed key generation and independent validator operators - are next. See the{' '} + The encryption, share verification, and distributed key generation are real. No dealer ever knows the + group key. But all validators currently run inside one backend process, so trust isn't truly + distributed until each runs on its own machine, which is the next step. See the{' '}