From 38058704006239f6f64ae9fc21b9aa3c4a90c3e6 Mon Sep 17 00:00:00 2001 From: FEDDIE Date: Fri, 6 Nov 2026 23:01:42 +0000 Subject: [PATCH 1/2] Run validators as separate processes with signed DKG messages - Standalone validator process (src/validator/main.ts): one key share plus an ed25519 identity key, behind a bearer-token HTTP API. RemoteValidator implements the same ValidatorNode interface as the in-process LocalValidator. - The DKG coordinator is treated as hostile: every DKG message is signed by its sender and session-bound. Dealers refuse to deal on a missing or forged transport key, forged complaints are ignored, and a missing share aborts instead of triggering a public reveal. Validators sign the result with a transcript hash, and the coordinator aborts on any mismatch. - Validators refuse to re-key while holding a share. - The backend connects via VALIDATOR_CLUSTER_FILE: it runs the DKG over HTTP on first start, reuses shares afterwards, and tolerates up to n-t unreachable validators. - npm run validators:dev starts a local 5-process cluster. - data/ is now fully gitignored (shares, identities, API tokens). New tests: 7 malicious-coordinator DKG tests, and 6 remote-validator tests over real HTTP (DKG, settlement, auth, n-t down, below-t failure). 55 backend tests pass. --- backend/.env.example | 5 + backend/.gitignore | 4 +- backend/package.json | 3 + backend/src/config.ts | 4 + backend/src/crypto/dkg.ts | 10 +- backend/src/crypto/signing.ts | 61 +++++ backend/src/services/validatorNetwork.ts | 307 ++++++++++------------- backend/src/services/validatorService.ts | 11 +- backend/src/validator/devCluster.ts | 74 ++++++ backend/src/validator/localValidator.ts | 198 +++++++++++++++ backend/src/validator/main.ts | 83 ++++++ backend/src/validator/protocol.ts | 65 +++++ backend/src/validator/remoteValidator.ts | 94 +++++++ backend/src/validator/server.ts | 48 ++++ backend/tests/dkg.test.ts | 42 ++-- backend/tests/dkgAdversarial.test.ts | 94 +++++++ backend/tests/pipeline.test.ts | 4 +- backend/tests/remoteValidators.test.ts | 134 ++++++++++ 18 files changed, 1043 insertions(+), 198 deletions(-) create mode 100644 backend/src/crypto/signing.ts create mode 100644 backend/src/validator/devCluster.ts create mode 100644 backend/src/validator/localValidator.ts create mode 100644 backend/src/validator/main.ts create mode 100644 backend/src/validator/protocol.ts create mode 100644 backend/src/validator/remoteValidator.ts create mode 100644 backend/src/validator/server.ts create mode 100644 backend/tests/dkgAdversarial.test.ts create mode 100644 backend/tests/remoteValidators.test.ts diff --git a/backend/.env.example b/backend/.env.example index c3c48f9..f6fadda 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -32,3 +32,8 @@ BYZANTINE_VALIDATORS= # HMAC key for wallet-signature auth challenges and session tokens (>= 32 # chars). Generate with: openssl rand -hex 32 AUTH_TOKEN_SECRET= + +# Run validators as separate processes instead of in-process: +# npm run validators:dev (starts 5 validator processes, writes the file below) +# then start the backend with this set. The first start runs the DKG over HTTP. +VALIDATOR_CLUSTER_FILE= diff --git a/backend/.gitignore b/backend/.gitignore index d03b084..b8eb3f5 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -1,6 +1,6 @@ node_modules dist .env -data/*.sqlite3 *.local -data/validators/ +# Local DB, validator key shares, identities and API tokens — never commit. +data/ diff --git a/backend/package.json b/backend/package.json index ba3c594..448711f 100644 --- a/backend/package.json +++ b/backend/package.json @@ -8,6 +8,9 @@ "build": "tsc", "start": "node dist/index.js", "test": "vitest run", + "validator": "ts-node --transpile-only src/validator/main.ts", + "validators:dev": "ts-node --transpile-only src/validator/devCluster.ts", + "validator:start": "node dist/validator/main.js", "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json" }, "dependencies": { diff --git a/backend/src/config.ts b/backend/src/config.ts index cced5f4..7c3cb87 100644 --- a/backend/src/config.ts +++ b/backend/src/config.ts @@ -38,6 +38,10 @@ export const config = { * 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'), + /** If set, validators are separate processes listed in this JSON file + * (see validator/devCluster.ts) and reached over HTTP; the in-process + * validators and VALIDATOR_KEY_DIR are not used. */ + validatorClusterFile: process.env.VALIDATOR_CLUSTER_FILE || '', /** 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 index 17b8f7f..53c48df 100644 --- a/backend/src/crypto/dkg.ts +++ b/backend/src/crypto/dkg.ts @@ -12,7 +12,9 @@ * 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). + * s_{i→j}·G == Σ_k j^k·C_{i,k}. A share that fails → + * complaint(i). A share that is *missing* aborts the DKG + * instead (see receive()). * 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. @@ -216,6 +218,12 @@ export class DkgParticipant { this.threshold ); const msg = shares.find((s) => s.dealer === dealer && s.recipient === this.index); + if (commitments && !msg) { + // Don't complain about a *missing* share: the answer would be a public + // reveal, so a router that drops messages could harvest our share. + // Abort instead — dropping messages can then only stall the DKG. + throw new Error(`no share received from dealer ${dealer}; aborting DKG`); + } let share: string | null = null; if (commitments && msg) { try { diff --git a/backend/src/crypto/signing.ts b/backend/src/crypto/signing.ts new file mode 100644 index 0000000..2e87ec7 --- /dev/null +++ b/backend/src/crypto/signing.ts @@ -0,0 +1,61 @@ +/** + * Validator identity signatures (ed25519). Once validators talk over a + * network, the coordinator routing their messages is untrusted: without + * signatures it could swap in its own DKG transport key for a validator, + * forge complaints to force public share reveals, or forge broadcasts. + * Every DKG message is therefore signed by its sender's long-term + * identity key and checked by every recipient. + */ +import { ed25519 } from '@noble/curves/ed25519'; +import { bytesToHex, hexToBytes } from './orderCipher'; + +export interface Signed { + payload: T; + signer: number; + signature: string; +} + +export interface Identity { + secretKey: string; + publicKey: string; +} + +/** Deterministic JSON (recursively sorted keys) so signer and verifier hash the same bytes. */ +export function canonicalJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; + if (value && typeof value === 'object') { + const obj = value as Record; + return `{${Object.keys(obj) + .filter((k) => obj[k] !== undefined) + .sort() + .map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`) + .join(',')}}`; + } + return JSON.stringify(value); +} + +const message = (domain: string, signer: number, payload: unknown) => + new TextEncoder().encode(`cipher-protocol/${domain}\n${signer}\n${canonicalJson(payload)}`); + +export function generateIdentity(): Identity { + const secret = ed25519.utils.randomPrivateKey(); + return { secretKey: bytesToHex(secret), publicKey: bytesToHex(ed25519.getPublicKey(secret)) }; +} + +export function publicKeyOf(secretKeyHex: string): string { + return bytesToHex(ed25519.getPublicKey(hexToBytes(secretKeyHex))); +} + +export function signPayload(domain: string, payload: T, signer: number, secretKeyHex: string): Signed { + const signature = ed25519.sign(message(domain, signer, payload), hexToBytes(secretKeyHex)); + return { payload, signer, signature: bytesToHex(signature) }; +} + +export function verifySigned(domain: string, signed: Signed, publicKeyHex: string | undefined): boolean { + if (!publicKeyHex || !signed || typeof signed.signature !== 'string' || !Number.isInteger(signed.signer)) return false; + try { + return ed25519.verify(hexToBytes(signed.signature), message(domain, signed.signer, signed.payload), hexToBytes(publicKeyHex)); + } catch { + return false; + } +} diff --git a/backend/src/services/validatorNetwork.ts b/backend/src/services/validatorNetwork.ts index 966088c..79abd61 100644 --- a/backend/src/services/validatorNetwork.ts +++ b/backend/src/services/validatorNetwork.ts @@ -2,194 +2,83 @@ import crypto from 'crypto'; import fs from 'fs'; import path from 'path'; import { config } from '../config'; -import { parseCiphertext } from '../crypto/orderCipher'; -import { DecryptionShare, KeyShare, Point, partialDecrypt } from '../crypto/threshold'; -import { - Complaint, - DealerBroadcast, - DkgFaults, - DkgParticipant, - DkgPublicResult, - DkgTranscript, - EncryptedShare, - Reveal, - computePublicResult, -} from '../crypto/dkg'; +import { DkgFaults, DkgPublicResult } from '../crypto/dkg'; +import { generateIdentity, verifySigned } from '../crypto/signing'; +import { LocalValidator, PersistedValidatorKey } from '../validator/localValidator'; +import { DOMAIN, SignedBroadcast, SignedShare, SignedTranscript, ValidatorNode } from '../validator/protocol'; +import { RemoteValidator, loadClusterFile } from '../validator/remoteValidator'; import logger from '../utils/logger'; -/** - * 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 address: string; - private keyShare: KeyShare | null = null; - private dkg: DkgParticipant | null = null; - - constructor( - readonly index: number, - private readonly opts: SimulatedValidatorOptions = {} - ) { - 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(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.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; - } -} +export type { ValidatorNode }; /** - * 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. + * Drives the DKG rounds. The coordinator only routes messages, and it is + * treated as untrusted: shares travel encrypted to their recipient, every + * message is signed by its sender, and validators refuse to deal or + * complain in ways a malicious router could exploit. It ends by checking + * every validator signed the same result and transcript hash. */ -export async function runDkg(nodes: ValidatorNode[], threshold: number, sessionId = crypto.randomUUID()) { +export async function runDkg( + nodes: ValidatorNode[], + threshold: number, + identityKeys: Record, + session = 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); - }) - ); + const transportKeys = await Promise.all(nodes.map((n) => n.dkgBegin(session, 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[] = []; + const broadcasts: SignedBroadcast[] = []; + const shares: SignedShare[] = []; 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}`); + logger.warn(`[dkg ${session}] validator ${nodes[k].index} did not deal: ${d.reason}`); } }); + if (broadcasts.length < threshold) throw new Error(`DKG failed: only ${broadcasts.length} validators dealt`); const complaints = ( - await Promise.all(nodes.map((n) => n.dkgReceive(broadcasts, shares.filter((s) => s.recipient === n.index)))) + await Promise.all(nodes.map((n) => n.dkgReceive(broadcasts, shares.filter((s) => s.payload.recipient === n.index)))) ).flat(); const reveals = (await Promise.all(nodes.map((n) => n.dkgRespond(complaints)))).flat(); - const transcript: DkgTranscript = { broadcasts, complaints, reveals }; + const transcript: SignedTranscript = { 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'); + const statements = await Promise.all(nodes.map((n) => n.dkgFinalize(transcript))); + const first = statements[0].payload; + for (const s of statements) { + if (!verifySigned(DOMAIN.result, s, identityKeys[s.signer])) { + throw new Error(`DKG failed: bad result signature from validator ${s.signer}`); + } + if (s.payload.groupPublicKey !== first.groupPublicKey || s.payload.transcriptHash !== first.transcriptHash) { + throw new Error('DKG failed: validators disagree on the result'); + } } for (const c of complaints) { - const resolved = expected.qualified.includes(c.dealer); + const resolved = first.qualified.includes(c.payload.dealer); logger.warn( - `[dkg ${sessionId}] validator ${c.complainer} complained about dealer ${c.dealer}: ` + + `[dkg ${session}] validator ${c.payload.complainer} complained about dealer ${c.payload.dealer}: ` + (resolved ? 'resolved by a valid public reveal' : 'dealer disqualified') ); } - return { result: expected, transcript }; + const result: DkgPublicResult = { + threshold: first.threshold, + qualified: first.qualified, + groupPublicKey: first.groupPublicKey, + verificationKeys: first.verificationKeys, + }; + return { result, transcript, statements }; } export interface ValidatorNetwork { threshold: number; groupPublicKey: string; + verificationKeys: Record; validators: ValidatorNode[]; + mode: 'local' | 'remote'; } let network: ValidatorNetwork | null = null; @@ -197,7 +86,7 @@ let initializing: Promise | null = null; const keyFileFor = (dir: string, index: number) => (dir ? path.join(dir, `validator-${index}.json`) : ''); -export interface CreateNetworkOptions { +export interface CreateLocalNetworkOptions { count: number; threshold: number; byzantine?: number[]; @@ -205,25 +94,37 @@ export interface CreateNetworkOptions { 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, { +/** In-process validators (dev/tests): fresh identities, then a real DKG among them. */ +export async function createLocalNetwork(opts: CreateLocalNetworkOptions) { + const identities = Array.from({ length: opts.count }, () => generateIdentity()); + const peers = Object.fromEntries(identities.map((id, k) => [k + 1, id.publicKey])); + const validators = identities.map( + (identity, k) => + new LocalValidator(k + 1, { + identity, + peers, 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); + const { result, transcript } = await runDkg(validators, opts.threshold, peers); 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 net: ValidatorNetwork & { dkg: DkgPublicResult; identities: typeof identities } = { + threshold: result.threshold, + groupPublicKey: result.groupPublicKey, + verificationKeys: result.verificationKeys, + validators, + mode: 'local', + dkg: result, + identities, + }; + return net; } -function loadPersistedNetwork(dir: string): ValidatorNetwork | null { +function loadLocalNetwork(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; @@ -231,7 +132,7 @@ function loadPersistedNetwork(dir: string): ValidatorNetwork | null { 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]; + const { groupPublicKey, threshold, verificationKeys } = 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`); } @@ -241,27 +142,87 @@ function loadPersistedNetwork(dir: string): ValidatorNetwork | null { 'delete the key directory to re-run DKG (pending orders become undecryptable)' ); } - const validators = keys.map((k) => - SimulatedValidator.fromPersisted(k, { byzantine: config.byzantineValidators.includes(k.index) }) + // Identity keys only matter for running a DKG; reloaded local validators get fresh ones. + const identities = keys.map(() => generateIdentity()); + const peers = Object.fromEntries(identities.map((id, k) => [keys[k].index, id.publicKey])); + const validators = keys.map((k, n) => + LocalValidator.fromPersisted(k, { + identity: identities[n], + peers, + byzantine: config.byzantineValidators.includes(k.index), + }) ); - return { threshold, groupPublicKey, validators }; + return { threshold, groupPublicKey, verificationKeys, validators, mode: 'local' }; } -/** Loads persisted validator shares, or runs a fresh DKG on first start. */ +/** + * Remote validators: each is its own process holding its own share. Uses + * the existing key if the validators already agree on one; runs a DKG over + * HTTP if none has a key yet; refuses a mixed state. + */ +export async function connectRemoteNetwork(clusterFile: string, threshold: number): Promise { + const cluster = loadClusterFile(clusterFile); + const validators = cluster.validators.map((v) => new RemoteValidator(v)); + const identityKeys = Object.fromEntries(cluster.validators.map((v) => [v.index, v.identityKey])); + + const infos = await Promise.allSettled(validators.map((v) => v.info())); + const reachable = infos.flatMap((r) => (r.status === 'fulfilled' ? [r.value] : [])); + for (const info of reachable) { + if (info.identityKey !== identityKeys[info.index]) { + throw new Error(`validator ${info.index} reports identity ${info.identityKey}, cluster file expects ${identityKeys[info.index]}`); + } + } + const keyed = reachable.filter((i) => i.hasKey); + + if (keyed.length === 0) { + if (reachable.length !== validators.length) { + throw new Error(`DKG needs all ${validators.length} validators reachable; only ${reachable.length} are`); + } + const { result } = await runDkg(validators, threshold, identityKeys); + logger.info(`DKG over HTTP complete: ${threshold}-of-${validators.length}, ${result.qualified.length} qualified dealers`); + return { ...result, validators, mode: 'remote' }; + } + + if (keyed.length !== reachable.length) { + throw new Error('some validators hold a key share and others do not; re-key all of them or restore their key files'); + } + const [ref] = keyed; + if (keyed.some((i) => i.groupPublicKey !== ref.groupPublicKey || i.threshold !== ref.threshold)) { + throw new Error('remote validators hold shares from different DKG sessions'); + } + if (keyed.length < ref.threshold!) { + throw new Error(`only ${keyed.length} validators reachable, ${ref.threshold} needed to decrypt`); + } + if (keyed.length < validators.length) { + logger.warn(`${validators.length - keyed.length} validator(s) unreachable at startup; continuing with ${keyed.length}`); + } + return { + threshold: ref.threshold!, + groupPublicKey: ref.groupPublicKey!, + verificationKeys: ref.verificationKeys!, + validators, + mode: 'remote', + }; +} + +/** Remote cluster if VALIDATOR_CLUSTER_FILE is set; otherwise in-process validators (load or DKG). */ export async function initValidatorNetwork(): Promise { if (network) return network; initializing ??= (async () => { + if (config.validatorClusterFile) { + return connectRemoteNetwork(config.validatorClusterFile, config.validatorThreshold); + } const dir = config.validatorKeyDir; - const loaded = dir ? loadPersistedNetwork(dir) : null; + const loaded = dir ? loadLocalNetwork(dir) : null; if (loaded) return loaded; - const created = await createSimulatedNetwork({ + const created = await createLocalNetwork({ count: config.validatorCount, threshold: config.validatorThreshold, byzantine: config.byzantineValidators, keyDir: dir, }); logger.info( - `DKG complete: ${created.threshold}-of-${created.validators.length}, ` + + `DKG complete (in-process validators): ${created.threshold}-of-${created.validators.length}, ` + `${created.dkg.qualified.length} qualified dealers${dir ? `, shares stored per validator in ${dir}` : ''}` ); return created; diff --git a/backend/src/services/validatorService.ts b/backend/src/services/validatorService.ts index 73eebc3..19ea83e 100644 --- a/backend/src/services/validatorService.ts +++ b/backend/src/services/validatorService.ts @@ -51,14 +51,15 @@ export const validatorService = { * claims about itself. */ async syncValidatorRegistry() { - const { validators } = await initValidatorNetwork(); + const { validators, verificationKeys } = await initValidatorNetwork(); for (const v of validators) { + const verificationKey = verificationKeys[v.index]; const [row] = await Validator.findOrCreate({ where: { address: v.address }, - defaults: { address: v.address, public_share: v.verificationKey, status: 'active' }, + defaults: { address: v.address, public_share: verificationKey, status: 'active' }, }); - if (row.public_share !== v.verificationKey) { - await row.update({ public_share: v.verificationKey, status: 'active' }); + if (row.public_share !== verificationKey) { + await row.update({ public_share: verificationKey, status: 'active' }); } } }, @@ -95,7 +96,7 @@ export const validatorService = { const ciphertexts = orders.map((o) => o.encrypted_data); const responses = await Promise.allSettled( - net.validators.map(async (v) => ({ v, shares: await v.requestDecryptionShares(ciphertexts) })) + net.validators.map(async (v) => ({ v, shares: await v.requestDecryptionShares(batchId, ciphertexts) })) ); // validShares[k] = verified shares for orders[k] diff --git a/backend/src/validator/devCluster.ts b/backend/src/validator/devCluster.ts new file mode 100644 index 0000000..2fbba40 --- /dev/null +++ b/backend/src/validator/devCluster.ts @@ -0,0 +1,74 @@ +/** + * Local multi-process validator cluster for development: + * + * npm run validators:dev # 5 validators on ports 6001–6005 + * VALIDATOR_COUNT=7 npm run validators:dev + * + * Each validator runs as its own OS process with its own key directory + * (data/cluster/validator-/), so no process ever holds another's share. + * Writes data/cluster/cluster.json for the backend; point the backend at it + * with VALIDATOR_CLUSTER_FILE=data/cluster/cluster.json. The first backend + * start runs the DKG over HTTP; later starts reuse the shares. + */ +import { ChildProcess, spawn } from 'child_process'; +import crypto from 'crypto'; +import fs from 'fs'; +import path from 'path'; +import { loadOrCreateIdentity } from './main'; +import { ClusterFile } from './remoteValidator'; + +const root = path.join(__dirname, '..', '..', 'data', 'cluster'); +const count = Number(process.env.VALIDATOR_COUNT) || 5; +const basePort = Number(process.env.VALIDATOR_BASE_PORT) || 6000; + +const clusterPath = path.join(root, 'cluster.json'); +const previous: ClusterFile | null = fs.existsSync(clusterPath) ? JSON.parse(fs.readFileSync(clusterPath, 'utf8')) : null; + +const members = Array.from({ length: count }, (_, k) => { + const index = k + 1; + const keyDir = path.join(root, `validator-${index}`); + const identity = loadOrCreateIdentity(keyDir); + const apiToken = + previous?.validators.find((v) => v.index === index)?.apiToken ?? crypto.randomBytes(32).toString('hex'); + return { index, keyDir, identity, apiToken, port: basePort + index }; +}); + +const cluster: ClusterFile = { + validators: members.map((m) => ({ + index: m.index, + url: `http://127.0.0.1:${m.port}`, + identityKey: m.identity.publicKey, + apiToken: m.apiToken, + })), +}; +fs.mkdirSync(root, { recursive: true }); +fs.writeFileSync(clusterPath, JSON.stringify(cluster, null, 2), { mode: 0o600 }); + +const peerKeys = members.map((m) => `${m.index}:${m.identity.publicKey}`).join(','); +// Works both from source (ts-node) and from the compiled dist/ build. +const runningTs = path.extname(__filename) === '.ts'; +const entry = path.join(__dirname, `main${path.extname(__filename)}`); +const nodeArgs = runningTs ? ['-r', 'ts-node/register/transpile-only', entry] : [entry]; +const children: ChildProcess[] = members.map((m) => + spawn(process.execPath, nodeArgs, { + stdio: 'inherit', + env: { + ...process.env, + VALIDATOR_INDEX: String(m.index), + VALIDATOR_PORT: String(m.port), + VALIDATOR_KEY_DIR: m.keyDir, + VALIDATOR_API_TOKEN: m.apiToken, + VALIDATOR_PEER_KEYS: peerKeys, + }, + }) +); + +console.log(`\nStarted ${count} validator processes. Run the backend with:\n`); +console.log(` VALIDATOR_CLUSTER_FILE=${path.relative(process.cwd(), clusterPath)} npm run dev\n`); + +const stop = () => { + for (const c of children) c.kill('SIGTERM'); + process.exit(0); +}; +process.on('SIGINT', stop); +process.on('SIGTERM', stop); diff --git a/backend/src/validator/localValidator.ts b/backend/src/validator/localValidator.ts new file mode 100644 index 0000000..e4efc85 --- /dev/null +++ b/backend/src/validator/localValidator.ts @@ -0,0 +1,198 @@ +import crypto from 'crypto'; +import fs from 'fs'; +import path from 'path'; +import { parseCiphertext } from '../crypto/orderCipher'; +import { DecryptionShare, KeyShare, Point, partialDecrypt } from '../crypto/threshold'; +import { DkgFaults, DkgParticipant, DkgTranscript } from '../crypto/dkg'; +import { Identity, Signed, canonicalJson, signPayload, verifySigned } from '../crypto/signing'; +import { + DOMAIN, + DkgResultStatement, + SignedBroadcast, + SignedComplaint, + SignedReveal, + SignedShare, + SignedTranscript, + SignedTransportKey, + ValidatorInfo, + ValidatorNode, +} from './protocol'; + +export interface PersistedValidatorKey { + index: number; + threshold: number; + participants: number[]; + groupPublicKey: string; + verificationKeys: Record; + secret: string; +} + +export interface LocalValidatorOptions { + identity: Identity; + /** Identity public keys of every validator (including this one), by index. */ + peers: Record; + /** Return invalid decryption shares (DLEQ verification must reject them). */ + byzantine?: boolean; + dkgFaults?: DkgFaults; + /** Persist this validator's own share here after DKG ('' = memory only). */ + keyFile?: string; +} + +/** + * One validator: one secret key share, one identity key, nothing else. + * Runs either inside the backend (dev/tests) or as its own process behind + * validator/server.ts — the code is the same; only the transport differs. + */ +export class LocalValidator implements ValidatorNode { + readonly address: string; + private keyShare: KeyShare | null = null; + private keyInfo: Omit | null = null; + private dkg: DkgParticipant | null = null; + + constructor( + readonly index: number, + private readonly opts: LocalValidatorOptions + ) { + this.address = `validator-${index}`; + if (opts.peers[index] !== opts.identity.publicKey) { + throw new Error(`validator ${index}: own identity key is not the one listed for it in peers`); + } + } + + static fromPersisted(key: PersistedValidatorKey, opts: LocalValidatorOptions) { + const v = new LocalValidator(key.index, opts); + v.keyShare = { index: key.index, secret: key.secret, verificationKey: key.verificationKeys[key.index] }; + const { secret: _secret, ...info } = key; + v.keyInfo = info; + return v; + } + + async info(): Promise { + return { + index: this.index, + identityKey: this.opts.identity.publicKey, + hasKey: !!this.keyShare, + threshold: this.keyInfo?.threshold, + groupPublicKey: this.keyInfo?.groupPublicKey, + verificationKeys: this.keyInfo?.verificationKeys, + }; + } + + async requestDecryptionShares(_batchId: string, ciphertexts: string[]): Promise { + const keyShare = this.keyShare; + if (!keyShare) throw new Error(`${this.address} has no key share`); + return ciphertexts.map((ct) => { + 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.opts.byzantine ? { ...share, share: Point.BASE.toHex() } : share; + }); + } + + // ── DKG ────────────────────────────────────────────────────────────── + + private sign(domain: string, payload: T): Signed { + return signPayload(domain, payload, this.index, this.opts.identity.secretKey); + } + + /** Signed by `expectedSigner`, under our session, from a known peer. */ + private valid(domain: string, msg: Signed<{ session: string }>, expectedSigner: number): boolean { + const session = this.dkg?.sessionId; + return ( + msg?.signer === expectedSigner && + msg.payload?.session === session && + verifySigned(domain, msg, this.opts.peers[expectedSigner]) + ); + } + + private session(): DkgParticipant { + if (!this.dkg) throw new Error('no DKG session in progress'); + return this.dkg; + } + + async dkgBegin(session: string, threshold: number, participants: number[]): Promise { + if (this.keyShare) throw new Error(`${this.address} already holds a key share; refusing to re-key`); + for (const p of participants) { + if (!this.opts.peers[p]) throw new Error(`unknown participant ${p}`); + } + this.dkg = new DkgParticipant(this.index, threshold, participants, session, this.opts.dkgFaults); + return this.sign(DOMAIN.transportKey, { session, index: this.index, transportKey: this.dkg.transportPublicKey }); + } + + async dkgDeal(transportKeys: SignedTransportKey[]) { + const dkg = this.session(); + const keys: Record = {}; + for (const p of dkg.participants) { + const mine = transportKeys.filter((k) => k?.payload?.index === p && this.valid(DOMAIN.transportKey, k, p)); + // A missing or forged transport key could route someone's share to an + // attacker-controlled key. Refuse to deal at all. + if (mine.length !== 1) throw new Error(`no valid transport key for validator ${p}; refusing to deal`); + keys[p] = mine[0].payload.transportKey; + } + const { broadcast, shares } = await dkg.deal(keys); + return { + broadcast: this.sign(DOMAIN.broadcast, { session: dkg.sessionId, ...broadcast }), + shares: shares.map((s) => this.sign(DOMAIN.share, { session: dkg.sessionId, ...s })), + }; + } + + private verifiedBroadcasts(broadcasts: SignedBroadcast[]) { + return broadcasts + .filter((b) => this.valid(DOMAIN.broadcast, b, b?.payload?.dealer)) + .map(({ payload: { dealer, commitments } }) => ({ dealer, commitments })); + } + + async dkgReceive(broadcasts: SignedBroadcast[], sharesForMe: SignedShare[]): Promise { + const dkg = this.session(); + const shares = sharesForMe + .filter((s) => s?.payload?.recipient === this.index && this.valid(DOMAIN.share, s, s.payload.dealer)) + .map(({ payload: { dealer, recipient, ciphertext } }) => ({ dealer, recipient, ciphertext })); + const complaints = await dkg.receive(this.verifiedBroadcasts(broadcasts), shares); + return complaints.map((c) => this.sign(DOMAIN.complaint, { session: dkg.sessionId, ...c })); + } + + async dkgRespond(complaints: SignedComplaint[]): Promise { + const dkg = this.session(); + // Only answer complaints the complainer actually signed — otherwise a + // router could forge complaints and harvest public reveals. + const genuine = complaints + .filter((c) => this.valid(DOMAIN.complaint, c, c?.payload?.complainer)) + .map(({ payload: { complainer, dealer } }) => ({ complainer, dealer })); + return dkg.respond(genuine).map((r) => this.sign(DOMAIN.reveal, { session: dkg.sessionId, ...r })); + } + + /** The transcript after dropping anything not signed by its rightful sender. */ + verifyTranscript(t: SignedTranscript): DkgTranscript { + return { + broadcasts: this.verifiedBroadcasts(t.broadcasts), + complaints: t.complaints + .filter((c) => this.valid(DOMAIN.complaint, c, c?.payload?.complainer)) + .map(({ payload: { complainer, dealer } }) => ({ complainer, dealer })), + reveals: t.reveals + .filter((r) => this.valid(DOMAIN.reveal, r, r?.payload?.dealer)) + .map(({ payload: { dealer, recipient, share } }) => ({ dealer, recipient, share })), + }; + } + + async dkgFinalize(signedTranscript: SignedTranscript): Promise> { + const dkg = this.session(); + const transcript = this.verifyTranscript(signedTranscript); + const { keyShare, result } = dkg.finalize(transcript); + this.keyShare = keyShare; + this.keyInfo = { + index: this.index, + threshold: result.threshold, + participants: dkg.participants, + groupPublicKey: result.groupPublicKey, + verificationKeys: result.verificationKeys, + }; + this.dkg = null; + if (this.opts.keyFile) { + const persisted: PersistedValidatorKey = { ...this.keyInfo, secret: keyShare.secret }; + fs.mkdirSync(path.dirname(this.opts.keyFile), { recursive: true }); + fs.writeFileSync(this.opts.keyFile, JSON.stringify(persisted, null, 2), { mode: 0o600 }); + } + const transcriptHash = crypto.createHash('sha256').update(canonicalJson(transcript)).digest('hex'); + return this.sign(DOMAIN.result, { session: dkg.sessionId, transcriptHash, ...result }); + } +} diff --git a/backend/src/validator/main.ts b/backend/src/validator/main.ts new file mode 100644 index 0000000..0b46836 --- /dev/null +++ b/backend/src/validator/main.ts @@ -0,0 +1,83 @@ +/** + * Standalone validator process: one key share, one identity, one port. + * + * VALIDATOR_INDEX this validator's index (1..n) + * VALIDATOR_PORT port to listen on (default 6000 + index) + * VALIDATOR_HOST interface to bind (default 127.0.0.1) + * VALIDATOR_KEY_DIR where this validator keeps identity.json and its share + * VALIDATOR_API_TOKEN bearer token the coordinator must present (≥ 32 chars) + * VALIDATOR_PEER_KEYS identity public keys of all validators: "1:hex,2:hex,…" + */ +import dotenv from 'dotenv'; +import fs from 'fs'; +import path from 'path'; +import { Identity, generateIdentity, publicKeyOf } from '../crypto/signing'; +import { LocalValidator, PersistedValidatorKey } from './localValidator'; +import { createValidatorApp } from './server'; + +dotenv.config(); + +function required(name: string): string { + const v = process.env[name]; + if (!v) throw new Error(`${name} is required`); + return v; +} + +export function parsePeerKeys(raw: string): Record { + return Object.fromEntries( + raw + .split(',') + .map((p) => p.trim()) + .filter(Boolean) + .map((p) => { + const [i, key] = p.split(':'); + if (!/^\d+$/.test(i) || !/^[0-9a-f]{64}$/.test(key ?? '')) throw new Error(`bad VALIDATOR_PEER_KEYS entry "${p}"`); + return [Number(i), key]; + }) + ); +} + +/** Loads this validator's identity key, creating it on first run. */ +export function loadOrCreateIdentity(keyDir: string): Identity { + const file = path.join(keyDir, 'identity.json'); + if (fs.existsSync(file)) { + const { secretKey } = JSON.parse(fs.readFileSync(file, 'utf8')) as Identity; + return { secretKey, publicKey: publicKeyOf(secretKey) }; + } + const identity = generateIdentity(); + fs.mkdirSync(keyDir, { recursive: true }); + fs.writeFileSync(file, JSON.stringify(identity, null, 2), { mode: 0o600 }); + return identity; +} + +export function startValidator() { + const index = Number(required('VALIDATOR_INDEX')); + const keyDir = required('VALIDATOR_KEY_DIR'); + const port = Number(process.env.VALIDATOR_PORT || 6000 + index); + const host = process.env.VALIDATOR_HOST || '127.0.0.1'; + const identity = loadOrCreateIdentity(keyDir); + const peers = parsePeerKeys(required('VALIDATOR_PEER_KEYS')); + const keyFile = path.join(keyDir, `validator-${index}.json`); + const opts = { identity, peers, keyFile }; + + const validator = fs.existsSync(keyFile) + ? LocalValidator.fromPersisted(JSON.parse(fs.readFileSync(keyFile, 'utf8')) as PersistedValidatorKey, opts) + : new LocalValidator(index, opts); + + const app = createValidatorApp(validator, required('VALIDATOR_API_TOKEN')); + app.listen(port, host, () => { + console.log( + `validator ${index} listening on http://${host}:${port} ` + + `(identity ${identity.publicKey.slice(0, 16)}…, ${fs.existsSync(keyFile) ? 'key share loaded' : 'awaiting DKG'})` + ); + }); +} + +if (require.main === module) { + try { + startValidator(); + } catch (err) { + console.error(`validator failed to start: ${(err as Error).message}`); + process.exit(1); + } +} diff --git a/backend/src/validator/protocol.ts b/backend/src/validator/protocol.ts new file mode 100644 index 0000000..9cba859 --- /dev/null +++ b/backend/src/validator/protocol.ts @@ -0,0 +1,65 @@ +import { DecryptionShare } from '../crypto/threshold'; +import { Complaint, DealerBroadcast, DkgPublicResult, EncryptedShare, Reveal } from '../crypto/dkg'; +import { Signed } from '../crypto/signing'; + +/** Signature domains, one per message kind, so a signature can't be replayed as a different message. */ +export const DOMAIN = { + transportKey: 'dkg/transport-key/v1', + broadcast: 'dkg/broadcast/v1', + share: 'dkg/share/v1', + complaint: 'dkg/complaint/v1', + reveal: 'dkg/reveal/v1', + result: 'dkg/result/v1', +} as const; + +type InSession = T & { session: string }; + +export interface TransportKey { + session: string; + index: number; + transportKey: string; +} +export type SignedTransportKey = Signed; +export type SignedBroadcast = Signed>; +export type SignedShare = Signed>; +export type SignedComplaint = Signed>; +export type SignedReveal = Signed>; + +export interface SignedTranscript { + broadcasts: SignedBroadcast[]; + complaints: SignedComplaint[]; + reveals: SignedReveal[]; +} + +export interface DkgResultStatement extends DkgPublicResult { + session: string; + /** sha256 of the canonical verified transcript — lets validators detect a coordinator showing them different views. */ + transcriptHash: string; +} + +export interface ValidatorInfo { + index: number; + identityKey: string; + hasKey: boolean; + threshold?: number; + groupPublicKey?: string; + verificationKeys?: Record; +} + +/** + * A validator as the coordinator sees it — local object or remote process. + * Nothing here exposes a secret, and every DKG output is signed by the + * validator's identity key. + */ +export interface ValidatorNode { + readonly index: number; + readonly address: string; + info(): Promise; + requestDecryptionShares(batchId: string, ciphertexts: string[]): Promise; + + dkgBegin(session: string, threshold: number, participants: number[]): Promise; + dkgDeal(transportKeys: SignedTransportKey[]): Promise<{ broadcast: SignedBroadcast; shares: SignedShare[] }>; + dkgReceive(broadcasts: SignedBroadcast[], sharesForMe: SignedShare[]): Promise; + dkgRespond(complaints: SignedComplaint[]): Promise; + dkgFinalize(transcript: SignedTranscript): Promise>; +} diff --git a/backend/src/validator/remoteValidator.ts b/backend/src/validator/remoteValidator.ts new file mode 100644 index 0000000..68f4150 --- /dev/null +++ b/backend/src/validator/remoteValidator.ts @@ -0,0 +1,94 @@ +import fs from 'fs'; +import { DecryptionShare } from '../crypto/threshold'; +import { Signed } from '../crypto/signing'; +import { + DkgResultStatement, + SignedBroadcast, + SignedComplaint, + SignedReveal, + SignedShare, + SignedTranscript, + SignedTransportKey, + ValidatorInfo, + ValidatorNode, +} from './protocol'; + +export interface ClusterMember { + index: number; + url: string; + /** ed25519 identity public key, hex — pinned so a swapped validator is detected. */ + identityKey: string; + /** Bearer token this coordinator presents to that validator. */ + apiToken: string; +} + +export interface ClusterFile { + validators: ClusterMember[]; +} + +export function loadClusterFile(file: string): ClusterFile { + const cluster = JSON.parse(fs.readFileSync(file, 'utf8')) as ClusterFile; + const seen = new Set(); + for (const v of cluster.validators ?? []) { + if (!Number.isInteger(v.index) || v.index < 1 || seen.has(v.index)) throw new Error(`bad validator index ${v.index}`); + if (!/^https?:\/\//.test(v.url)) throw new Error(`validator ${v.index}: bad url`); + if (!/^[0-9a-f]{64}$/.test(v.identityKey)) throw new Error(`validator ${v.index}: bad identityKey`); + if (!v.apiToken || v.apiToken.length < 32) throw new Error(`validator ${v.index}: apiToken must be ≥ 32 chars`); + seen.add(v.index); + } + if (seen.size === 0) throw new Error(`${file} lists no validators`); + return cluster; +} + +const TIMEOUT_MS = 15_000; + +/** HTTP client for a validator process (see validator/server.ts). */ +export class RemoteValidator implements ValidatorNode { + readonly index: number; + readonly address: string; + + constructor(private readonly member: ClusterMember) { + this.index = member.index; + this.address = `validator-${member.index}`; + } + + private async call(method: 'GET' | 'POST', route: string, body?: unknown): Promise { + const res = await fetch(new URL(route, this.member.url), { + method, + headers: { authorization: `Bearer ${this.member.apiToken}`, 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + const data = (await res.json().catch(() => ({}))) as { error?: string }; + if (!res.ok) throw new Error(`${this.address} ${route}: ${res.status} ${data.error ?? ''}`.trim()); + return data as T; + } + + info() { + return this.call('GET', '/v1/info'); + } + + requestDecryptionShares(batchId: string, ciphertexts: string[]) { + return this.call('POST', '/v1/decryption-shares', { batchId, ciphertexts }); + } + + dkgBegin(session: string, threshold: number, participants: number[]) { + return this.call('POST', '/v1/dkg/begin', { session, threshold, participants }); + } + + dkgDeal(transportKeys: SignedTransportKey[]) { + return this.call<{ broadcast: SignedBroadcast; shares: SignedShare[] }>('POST', '/v1/dkg/deal', { transportKeys }); + } + + dkgReceive(broadcasts: SignedBroadcast[], sharesForMe: SignedShare[]) { + return this.call('POST', '/v1/dkg/receive', { broadcasts, sharesForMe }); + } + + dkgRespond(complaints: SignedComplaint[]) { + return this.call('POST', '/v1/dkg/respond', { complaints }); + } + + dkgFinalize(transcript: SignedTranscript) { + return this.call>('POST', '/v1/dkg/finalize', { transcript }); + } +} diff --git a/backend/src/validator/server.ts b/backend/src/validator/server.ts new file mode 100644 index 0000000..c9b61bb --- /dev/null +++ b/backend/src/validator/server.ts @@ -0,0 +1,48 @@ +import crypto from 'crypto'; +import express, { Express, NextFunction, Request, Response } from 'express'; +import { LocalValidator } from './localValidator'; + +/** + * HTTP face of one validator process. Every route needs the coordinator's + * bearer token: the decryption-shares route in particular must never be + * open, or anyone could collect t shares for a pending order. + */ +export function createValidatorApp(validator: LocalValidator, apiToken: string): Express { + if (apiToken.length < 32) throw new Error('validator API token must be at least 32 characters'); + const expected = Buffer.from(apiToken); + const app = express(); + app.use(express.json({ limit: '5mb' })); + + app.get('/health', (_req, res) => { + res.json({ status: 'ok', index: validator.index }); + }); + + app.use('/v1', (req: Request, res: Response, next: NextFunction) => { + const given = Buffer.from(/^Bearer (\S+)$/.exec(req.header('authorization') ?? '')?.[1] ?? ''); + if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) { + res.status(401).json({ error: 'unauthorized' }); + return; + } + next(); + }); + + const route = + (fn: (body: any) => Promise) => // eslint-disable-line @typescript-eslint/no-explicit-any + async (req: Request, res: Response) => { + try { + res.json(await fn(req.body ?? {})); + } catch (err) { + res.status(400).json({ error: (err as Error).message }); + } + }; + + app.get('/v1/info', route(() => validator.info())); + app.post('/v1/decryption-shares', route((b) => validator.requestDecryptionShares(String(b.batchId), b.ciphertexts))); + app.post('/v1/dkg/begin', route((b) => validator.dkgBegin(String(b.session), b.threshold, b.participants))); + app.post('/v1/dkg/deal', route((b) => validator.dkgDeal(b.transportKeys ?? []))); + app.post('/v1/dkg/receive', route((b) => validator.dkgReceive(b.broadcasts ?? [], b.sharesForMe ?? []))); + app.post('/v1/dkg/respond', route((b) => validator.dkgRespond(b.complaints ?? []))); + app.post('/v1/dkg/finalize', route((b) => validator.dkgFinalize(b.transcript ?? { broadcasts: [], complaints: [], reveals: [] }))); + + return app; +} diff --git a/backend/tests/dkg.test.ts b/backend/tests/dkg.test.ts index c014f79..57daeff 100644 --- a/backend/tests/dkg.test.ts +++ b/backend/tests/dkg.test.ts @@ -5,7 +5,9 @@ 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'; +import { createLocalNetwork, runDkg } from '../src/services/validatorNetwork'; +import { LocalValidator } from '../src/validator/localValidator'; +import { generateIdentity } from '../src/crypto/signing'; const USER = 'GTESTUSER'; @@ -15,7 +17,7 @@ function reconstructSecret(shares: KeyShare[]): bigint { return shares.reduce((acc, s) => mod(acc + BigInt('0x' + s.secret) * lagrangeAtZero(s.index, idx)), 0n); } -function sharesOf(validators: SimulatedValidator[]): KeyShare[] { +function sharesOf(validators: LocalValidator[]): KeyShare[] { // Reach into the simulated validators — only possible because they're in-process. return validators.map((v) => (v as unknown as { keyShare: KeyShare }).keyShare); } @@ -29,8 +31,8 @@ async function roundTrip(groupKey: string, shares: KeyShare[], subset: number[]) 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[]); + const net = await createLocalNetwork({ count: 5, threshold: 3 }); + const shares = sharesOf(net.validators as LocalValidator[]); expect(net.dkg.qualified).toEqual([1, 2, 3, 4, 5]); for (const s of shares) { @@ -45,13 +47,15 @@ describe('distributed key generation', () => { }); it('two runs produce independent keys', async () => { - const a = await createSimulatedNetwork({ count: 3, threshold: 2 }); - const b = await createSimulatedNetwork({ count: 3, threshold: 2 }); + const a = await createLocalNetwork({ count: 3, threshold: 2 }); + const b = await createLocalNetwork({ 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 ids = Array.from({ length: 5 }, () => generateIdentity()); + const peers = Object.fromEntries(ids.map((id, k) => [k + 1, id.publicKey])); + const validators = ids.map((identity, k) => new LocalValidator(k + 1, { identity, peers })); const routed: string[] = []; // Wrap deal() to capture exactly what passes through the coordinator. for (const v of validators) { @@ -62,7 +66,7 @@ describe('distributed key generation', () => { return out; }; } - const { transcript } = await runDkg(validators, 3); + const { transcript } = await runDkg(validators, 3, peers); const seen = routed.join('') + JSON.stringify(transcript); for (const s of sharesOf(validators)) expect(seen).not.toContain(s.secret); expect(transcript.complaints).toEqual([]); @@ -70,20 +74,20 @@ describe('distributed key generation', () => { }); 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] } } }); + const net = await createLocalNetwork({ 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[]); + const shares = sharesOf(net.validators as LocalValidator[]); 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({ + const net = await createLocalNetwork({ 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[]); + const shares = sharesOf(net.validators as LocalValidator[]); // The disqualified dealer is still a share-holder (QUAL is about dealing). expect(await roundTrip(net.groupPublicKey, shares, [3, 4, 5])).toBe('{"order":1}'); }); @@ -91,7 +95,7 @@ describe('distributed key generation', () => { 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 } }) + createLocalNetwork({ count: 5, threshold: 3, dkgFaults: { 2: liar, 3: liar, 4: liar } }) ).rejects.toThrow(/only 2 qualified dealers, need at least 3/); }); @@ -110,6 +114,14 @@ describe('distributed key generation', () => { ]); }); + it('a missing share aborts instead of drawing a complaint (no reveal for a router to harvest)', async () => { + const ps = [1, 2, 3].map((i) => new DkgParticipant(i, 2, [1, 2, 3], 'session-m')); + const keys = Object.fromEntries(ps.map((p) => [p.index, p.transportPublicKey])); + const dealt = await Promise.all(ps.map((p) => p.deal(keys))); + const withheld = dealt.flatMap((d) => d.shares).filter((s) => s.recipient === 3 && s.dealer !== 2); + await expect(ps[2].receive(dealt.map((d) => d.broadcast), withheld)).rejects.toThrow(/no share received from dealer 2/); + }); + 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')]; @@ -138,8 +150,8 @@ describe('distributed key generation', () => { 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[]); + const net = await createLocalNetwork({ count: 3, threshold: 2, keyDir: dir }); + const shares = sharesOf(net.validators as LocalValidator[]); 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); diff --git a/backend/tests/dkgAdversarial.test.ts b/backend/tests/dkgAdversarial.test.ts new file mode 100644 index 0000000..26dc6d2 --- /dev/null +++ b/backend/tests/dkgAdversarial.test.ts @@ -0,0 +1,94 @@ +import { describe, it, expect } from 'vitest'; +import crypto from 'crypto'; +import { generateIdentity, signPayload } from '../src/crypto/signing'; +import { LocalValidator } from '../src/validator/localValidator'; +import { DOMAIN, SignedComplaint, SignedTransportKey } from '../src/validator/protocol'; +import { runDkg } from '../src/services/validatorNetwork'; + +/** + * The DKG coordinator only routes messages and must be treated as hostile. + * These tests play a malicious coordinator against honest validators. + */ +function cluster(n = 3) { + const ids = Array.from({ length: n }, () => generateIdentity()); + const peers = Object.fromEntries(ids.map((id, k) => [k + 1, id.publicKey])); + const validators = ids.map((identity, k) => new LocalValidator(k + 1, { identity, peers })); + return { validators, peers, participants: validators.map((v) => v.index) }; +} + +const attacker = generateIdentity(); + +describe('DKG against a malicious coordinator', () => { + it('validators refuse to deal if a transport key is swapped for the coordinator’s own', async () => { + const { validators, participants } = cluster(); + const session = crypto.randomUUID(); + const keys = await Promise.all(validators.map((v) => v.dkgBegin(session, 2, participants))); + // Replace validator 3's transport key with one the attacker controls, re-signed by the attacker. + const swapped: SignedTransportKey = signPayload( + DOMAIN.transportKey, + { session, index: 3, transportKey: keys[0].payload.transportKey }, + 3, + attacker.secretKey + ); + const tampered = [keys[0], keys[1], swapped]; + for (const v of validators) { + await expect(v.dkgDeal(tampered)).rejects.toThrow(/no valid transport key for validator 3/); + } + }); + + it('forged complaints are ignored, so no share is revealed', async () => { + const { validators, participants } = cluster(); + const session = crypto.randomUUID(); + const keys = await Promise.all(validators.map((v) => v.dkgBegin(session, 2, participants))); + const dealt = await Promise.all(validators.map((v) => v.dkgDeal(keys))); + const broadcasts = dealt.map((d) => d.broadcast); + const shares = dealt.flatMap((d) => d.shares); + for (const v of validators) { + expect(await v.dkgReceive(broadcasts, shares.filter((s) => s.payload.recipient === v.index))).toEqual([]); + } + // The coordinator fabricates "validator 3 complains about dealer 1", signed with its own key. + const forged: SignedComplaint = signPayload(DOMAIN.complaint, { session, complainer: 3, dealer: 1 }, 3, attacker.secretKey); + expect(await validators[0].dkgRespond([forged])).toEqual([]); + }); + + it('withholding a share stalls the DKG rather than leaking it', async () => { + const { validators, participants } = cluster(); + const session = crypto.randomUUID(); + const keys = await Promise.all(validators.map((v) => v.dkgBegin(session, 2, participants))); + const dealt = await Promise.all(validators.map((v) => v.dkgDeal(keys))); + const toThree = dealt.flatMap((d) => d.shares).filter((s) => s.payload.recipient === 3 && s.payload.dealer !== 1); + await expect(validators[2].dkgReceive(dealt.map((d) => d.broadcast), toThree)).rejects.toThrow(/aborting DKG/); + }); + + it('a broadcast altered in transit is dropped consistently by every validator', async () => { + const { validators, participants } = cluster(4); + const session = crypto.randomUUID(); + const keys = await Promise.all(validators.map((v) => v.dkgBegin(session, 2, participants))); + const dealt = await Promise.all(validators.map((v) => v.dkgDeal(keys))); + const broadcasts = dealt.map((d) => d.broadcast); + const altered = { ...broadcasts[3], payload: { ...broadcasts[3].payload, commitments: [...broadcasts[0].payload.commitments] } }; + const transcript = { broadcasts: [broadcasts[0], broadcasts[1], broadcasts[2], altered], complaints: [], reveals: [] }; + for (const v of validators) expect(v.verifyTranscript(transcript).broadcasts.map((b) => b.dealer)).toEqual([1, 2, 3]); + }); + + it('signed messages from an earlier session are rejected', async () => { + const { validators, participants } = cluster(); + const old = await Promise.all(validators.map((v) => v.dkgBegin('old-session', 2, participants))); + for (const v of validators) { + await v.dkgBegin('new-session', 2, participants); // session restarted (e.g. after an abort) + await expect(v.dkgDeal(old)).rejects.toThrow(/no valid transport key/); + } + }); + + it('a validator that already holds a key refuses to re-key', async () => { + const { validators, peers } = cluster(); + await runDkg(validators, 2, peers); + await expect(validators[0].dkgBegin('again', 2, [1, 2, 3])).rejects.toThrow(/refusing to re-key/); + }); + + it('the coordinator rejects a result statement not signed by the validator', async () => { + const { validators } = cluster(); + const wrongKeys = Object.fromEntries(validators.map((v) => [v.index, attacker.publicKey])); + await expect(runDkg(validators, 2, wrongKeys)).rejects.toThrow(/bad result signature/); + }); +}); diff --git a/backend/tests/pipeline.test.ts b/backend/tests/pipeline.test.ts index 63f8ad6..179fe35 100644 --- a/backend/tests/pipeline.test.ts +++ b/backend/tests/pipeline.test.ts @@ -5,7 +5,7 @@ import { sequelize } from '../src/db'; import { Order } from '../src/db/models/Order'; import { Batch } from '../src/db/models/Batch'; import { batchingService } from '../src/services/batchingService'; -import { createSimulatedNetwork, setValidatorNetwork } from '../src/services/validatorNetwork'; +import { createLocalNetwork, setValidatorNetwork } from '../src/services/validatorNetwork'; import { validatorService } from '../src/services/validatorService'; import { authHeaders, newUser, submitSwap } from './helpers'; @@ -13,7 +13,7 @@ const app = createApp(); /** Fresh 3-of-5 validator set, keyed by a real DKG, where the listed indices misbehave. */ async function useNetwork(byzantine: number[] = []) { - setValidatorNetwork(await createSimulatedNetwork({ count: 5, threshold: 3, byzantine })); + setValidatorNetwork(await createLocalNetwork({ count: 5, threshold: 3, byzantine })); await validatorService.syncValidatorRegistry(); } diff --git a/backend/tests/remoteValidators.test.ts b/backend/tests/remoteValidators.test.ts new file mode 100644 index 0000000..d88909f --- /dev/null +++ b/backend/tests/remoteValidators.test.ts @@ -0,0 +1,134 @@ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import crypto from 'crypto'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { AddressInfo } from 'net'; +import { Server } from 'http'; +import request from 'supertest'; +import { createApp } from '../src/app'; +import { sequelize } from '../src/db'; +import { Order } from '../src/db/models/Order'; +import { generateIdentity } from '../src/crypto/signing'; +import { LocalValidator } from '../src/validator/localValidator'; +import { createValidatorApp } from '../src/validator/server'; +import { RemoteValidator } from '../src/validator/remoteValidator'; +import { connectRemoteNetwork, setValidatorNetwork } from '../src/services/validatorNetwork'; +import { validatorService } from '../src/services/validatorService'; +import { batchingService } from '../src/services/batchingService'; +import { newUser, submitSwap } from './helpers'; + +/** + * Five validators, each behind its own HTTP server with its own key + * directory, reached only through RemoteValidator — the same code path as + * separate processes (`npm run validators:dev`), minus the process spawn. + */ +const N = 5; +const T = 3; +const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cipher-remote-')); +const ids = Array.from({ length: N }, () => generateIdentity()); +const peers = Object.fromEntries(ids.map((id, k) => [k + 1, id.publicKey])); +const tokens = ids.map(() => crypto.randomBytes(32).toString('hex')); +const servers: Server[] = []; +const keyDir = (i: number) => path.join(root, `validator-${i}`); +const clusterFile = path.join(root, 'cluster.json'); +const app = createApp(); + +function startValidator(k: number): Promise { + const index = k + 1; + const validator = new LocalValidator(index, { + identity: ids[k], + peers, + keyFile: path.join(keyDir(index), `validator-${index}.json`), + }); + return new Promise((resolve) => { + const s = createValidatorApp(validator, tokens[k]).listen(0, '127.0.0.1', () => resolve(s)); + }); +} + +beforeAll(async () => { + for (let k = 0; k < N; k++) servers.push(await startValidator(k)); + fs.writeFileSync( + clusterFile, + JSON.stringify({ + validators: servers.map((s, k) => ({ + index: k + 1, + url: `http://127.0.0.1:${(s.address() as AddressInfo).port}`, + identityKey: ids[k].publicKey, + apiToken: tokens[k], + })), + }) + ); + await sequelize.sync({ force: true }); +}); + +afterAll(async () => { + await Promise.all(servers.map((s) => new Promise((r) => s.close(r)))); + await sequelize.close(); + fs.rmSync(root, { recursive: true, force: true }); +}); + +describe('validators as separate network services', () => { + let groupKey = ''; + + it('runs the DKG over HTTP; each validator stores only its own share', async () => { + const net = await connectRemoteNetwork(clusterFile, T); + expect(net.mode).toBe('remote'); + groupKey = net.groupPublicKey; + setValidatorNetwork(net); + await validatorService.syncValidatorRegistry(); + + const secrets = Array.from({ length: N }, (_, k) => + JSON.parse(fs.readFileSync(path.join(keyDir(k + 1), `validator-${k + 1}.json`), 'utf8')).secret as string + ); + expect(new Set(secrets).size).toBe(N); + for (let k = 0; k < N; k++) { + const files = fs.readdirSync(keyDir(k + 1)); + expect(files).toEqual([`validator-${k + 1}.json`]); + const content = fs.readFileSync(path.join(keyDir(k + 1), files[0]), 'utf8'); + secrets.forEach((s, j) => j !== k && expect(content).not.toContain(s)); + } + }); + + it('settles orders by collecting shares over HTTP', async () => { + const res = await submitSwap(app, newUser()); + await batchingService.runOnce(); + expect((await Order.findByPk(res.body.order.id))!.status).toBe('settled'); + }); + + it('a restarted coordinator reuses the existing key instead of re-keying', async () => { + const net = await connectRemoteNetwork(clusterFile, T); + expect(net.groupPublicKey).toBe(groupKey); + }); + + it('rejects callers without the validator API token', async () => { + const url = `http://127.0.0.1:${(servers[0].address() as AddressInfo).port}`; + const res = await fetch(`${url}/v1/decryption-shares`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ batchId: 'x', ciphertexts: [] }), + }); + expect(res.status).toBe(401); + const wrong = new RemoteValidator({ index: 1, url, identityKey: ids[0].publicKey, apiToken: 'f'.repeat(64) }); + await expect(wrong.info()).rejects.toThrow(/401/); + expect((await request(url).get('/health')).status).toBe(200); + }); + + it('keeps settling with n − t validators down', async () => { + await new Promise((r) => servers[1].close(r)); + await new Promise((r) => servers[3].close(r)); + const res = await submitSwap(app, newUser()); + await batchingService.runOnce(); + expect((await Order.findByPk(res.body.order.id))!.status).toBe('settled'); + }); + + it('fails orders cleanly (no plaintext revealed) when fewer than t validators are up', async () => { + await new Promise((r) => servers[4].close(r)); + const res = await submitSwap(app, newUser()); + await batchingService.runOnce(); + const order = await Order.findByPk(res.body.order.id); + expect(order!.status).toBe('failed'); + expect(order!.failure_reason).toMatch(/2\/3 valid decryption shares/); + expect(order!.token_in).toBeNull(); + }); +}); From 67fb61025c95ef280daeb39682991ab0a56cc7a4 Mon Sep 17 00:00:00 2001 From: FEDDIE Date: Fri, 6 Nov 2026 23:01:42 +0000 Subject: [PATCH 2/2] Docs: separate validator processes, coordinator threat model, remaining trust Document how to run validators as separate processes, list each coordinator attack with its defence, and state precisely what is still trusted: validators don't yet verify on-chain batch sealing before releasing shares, and validators are run by one party. Contributor issues updated: Docker Compose + TLS deployment, and on-chain ciphertext commitments checked by validators. --- CONTRIBUTING.md | 4 +-- README.md | 26 +++++++++----- SECURITY.md | 5 +-- backend/README.md | 27 +++++++++++--- docs/CONTRIBUTOR_ISSUES.md | 31 ++++++++-------- docs/THRESHOLD_ENCRYPTION.md | 63 ++++++++++++++++++++++++--------- frontend/src/pages/DocsPage.tsx | 8 ++--- 7 files changed, 110 insertions(+), 54 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8cc1023..f4c45dc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -51,8 +51,8 @@ understand the scope of the fix. ## Security -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) +Known, documented gaps (validators trusting the coordinator about batch +sealing, 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 452cc1b..2401572 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,8 @@ miner-equivalent) can see or front-run an order before it executes. **Status: working proof-of-concept on Stellar testnet.** Orders are encrypted in the browser with real t-of-n threshold encryption and are only decrypted, with verifiable validator shares, after their batch is sealed. -The validator set is still simulated in one process. See [Status](#status) -before trusting this with real funds. +Validators generate the key together and can run as separate processes. +See [Status](#status) before trusting this with real funds. [![CI](https://github.com/CiipherProtocol/CipherProtocol/actions/workflows/ci.yml/badge.svg)](https://github.com/CiipherProtocol/CipherProtocol/actions/workflows/ci.yml) @@ -73,18 +73,26 @@ What's real and tested: 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), +- **Validators as separate processes** (`backend/src/validator/`): each + holds one share and an identity key, behind an authenticated HTTP API. + The coordinator is treated as hostile: every DKG message is signed, and + share-harvesting tricks abort the DKG instead of leaking. Run + `npm run validators:dev` for a 5-process cluster. +- **Tests and CI**: 55 backend tests (crypto, DKG, malicious coordinator, + remote validators, 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 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)). +- **Validators trust the coordinator about *when* to decrypt.** They + authenticate it, but they don't yet check on-chain that a batch is sealed + before releasing shares. Next step: commit ciphertext hashes on-chain and + have validators verify them. +- **No independent operators yet.** Validators can run on separate + machines, but today they're run by one party (in-process by default, or + `validators:dev` on one host). See + [the design doc](docs/THRESHOLD_ENCRYPTION.md#what-is-still-trusted-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 backend database is still the mempool, and it doesn't yet commit to diff --git a/SECURITY.md b/SECURITY.md index de82f13..797d5aa 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -16,8 +16,9 @@ In scope: the threshold encryption and share verification the Soroban contracts. Known, already-documented limitations, and therefore not new reports: the -validators run in one process, and DKG uses Joint-Feldman, which allows -bias of the group key's distribution but not its disclosure. See +validators don't yet verify on-chain that a batch is sealed before +releasing shares; they're run by one party; 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/backend/README.md b/backend/README.md index eab9f69..fbf85a1 100644 --- a/backend/README.md +++ b/backend/README.md @@ -30,10 +30,23 @@ 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 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 +By default the 5 validators run inside the backend. On first start they 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. + +To run validators as **separate processes** instead: + +```bash +npm run validators:dev # terminal 1: 5 validator processes on :6001-6005 +VALIDATOR_CLUSTER_FILE=data/cluster/cluster.json npm run dev # terminal 2 +``` + +The first backend start runs the DKG over HTTP. Later starts reuse the +shares, and the backend keeps working with up to 2 validators down. A +single production validator runs with `npm run validator:start`, configured +via the env vars documented in `src/validator/main.ts`. 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. @@ -52,6 +65,10 @@ the DLEQ proofs reject bad validators, set `BYZANTINE_VALIDATORS=2,4`. With | GET | `/api/settlement/:batchId` | – | Settlement results | | POST | `/api/settlement/:batchId/settle` | – | Retry a failed batch (idempotent) | +Validator processes expose their own API under `/v1/*` (DKG rounds, +`decryption-shares`, `info`), and every route needs the coordinator's bearer +token. See `src/validator/server.ts`. + ## Scripts - `npm run dev` — dev server (`ts-node-dev`, auto-restart) @@ -59,6 +76,8 @@ the DLEQ proofs reject bad validators, set `BYZANTINE_VALIDATORS=2,4`. With - `npm test` — Vitest: threshold crypto, the end-to-end submit → batch → decrypt → settle pipeline, and auth (in-memory SQLite, no network) - `npm run typecheck` — `tsc` over sources and tests +- `npm run validators:dev` — local 5-process validator cluster +- `npm run validator` / `validator:start` — run one validator (source / built) ## Structure diff --git a/docs/CONTRIBUTOR_ISSUES.md b/docs/CONTRIBUTOR_ISSUES.md index a35f5cb..625a265 100644 --- a/docs/CONTRIBUTOR_ISSUES.md +++ b/docs/CONTRIBUTOR_ISSUES.md @@ -4,7 +4,8 @@ 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:** threshold encryption, validator share coordination, -distributed key generation (Joint-Feldman with complaints), signature auth, +distributed key generation (Joint-Feldman with complaints), validators as +separate processes with signed DKG messages, signature auth, backend and frontend test suites, and CI. See the root README's Status section. @@ -26,31 +27,27 @@ All existing `dkg.test.ts` cases must still pass. --- -### 2. Remote validator nodes (200) +### 2. Validator deployment: Docker Compose + TLS (150) -All validators are `SimulatedValidator` instances inside the backend -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`. +Validators already run as separate processes (`npm run validators:dev`), +but only on one host over plain HTTP. Add a Docker Compose setup (one +container and one volume per validator, plus the backend), and put the +coordinator-to-validator transport behind TLS. Mutual TLS is a bonus. -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. +**Acceptance:** `docker compose up` brings up 5 validators and the backend. +The DKG completes, and an order settles. Stopping 2 validator containers +doesn't stop settlement. --- -### 3. Commit ciphertext hashes on-chain before decryption (150) +### 3. Commit ciphertext hashes on-chain; validators verify before decrypting (200) `order-vault.create_batch` attests to a hash of order *IDs*. Make it commit to the hash of the ordered list of *ciphertexts*, so the batch contents and order are provably fixed before any validator releases a share. Then have -`validatorService.coordinateDecryption` (and later issue #2's remote -validators) check it. +each validator (`src/validator/localValidator.ts#requestDecryptionShares`) +check that commitment on-chain itself before contributing. This is the +remaining place where validators trust the coordinator. **Scope:** contract change and tests in `contracts/order-vault`, plus the `sorobanService.createBatch` update. diff --git a/docs/THRESHOLD_ENCRYPTION.md b/docs/THRESHOLD_ENCRYPTION.md index 0e55c5b..755b83d 100644 --- a/docs/THRESHOLD_ENCRYPTION.md +++ b/docs/THRESHOLD_ENCRYPTION.md @@ -1,7 +1,7 @@ # Threshold order encryption How Cipher Protocol keeps a swap order secret until the batch it belongs to -is sealed, and what is still simulated. +is sealed, and what is still trusted. ## Goal @@ -102,26 +102,57 @@ to `dkg-transcript.json` for audit. 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. + broadcasts, but the coordinator relaying them could show validators + different views. Each validator signs its final result together with a + hash of the transcript it verified, and the coordinator aborts unless all + of them match. A coordinator that lies anyway can only produce + inconsistent keys (an availability failure). It can't extract `y`. -## What is simulated, and what's next +## Validators as separate processes + +Each validator can run as its own OS process (`src/validator/main.ts`), +holding its own key share and an ed25519 **identity key**. The backend +reaches validators over HTTP through `RemoteValidator`, which implements the +same `ValidatorNode` interface as the in-process `LocalValidator`. Run +`npm run validators:dev` to start 5 such processes. + +Once messages cross a network, the coordinator routing them is treated as +**hostile**. Each attack below is blocked, and `dkgAdversarial.test.ts` +covers it: + +| Coordinator attack | Defence | +|---|---| +| Swap a validator's DKG transport key for its own, to read the shares sent to it | Transport keys are signed by the validator's identity key. Dealers refuse to deal if any key is missing or forged. | +| Forge complaints so dealers publicly reveal shares | Complaints must be signed by the complainer. Unsigned ones are ignored. | +| Drop shares so the victim complains and the reveal leaks its share | A *missing* share aborts the DKG instead of producing a complaint, so dropping messages only stalls it. | +| Alter or forge broadcasts | Broadcasts are signed. Altered ones are dropped identically by every validator. | +| Replay messages from an earlier DKG | Every signed payload carries the session id. | +| Re-key validators that already hold a share | Validators refuse to start a new DKG while holding a key. | +| Ask validators for decryption shares directly | Every validator route requires the coordinator's bearer token. | + +Verified end to end: 5 separate validator processes ran the DKG over HTTP +and an order was submitted, decrypted and settled. After 2 processes were +killed and the backend restarted, it reused the same key and still settled. +`remoteValidators.test.ts` covers the same flows in CI. + +## What is still trusted, and what's next Being honest about the remaining gaps: -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 +1. **Validators release shares whenever the coordinator asks.** They + authenticate the coordinator, but they don't yet check on their own that + a batch was sealed on-chain before contributing. A malicious backend + holding the API tokens could therefore request early decryption. The fix + is for validators to verify the `order-vault` commitment to the batch's + ciphertexts (contributor issue #3) before releasing anything. +2. **Independent operators.** The code supports one validator per machine, + but the dev cluster runs all of them on one host, and the default dev + mode keeps them in-process. Real decentralization means deploying + validators run by different parties. Their HTTP transport should then + sit behind TLS. +3. **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. +4. **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 aca3a7b..0c784f9 100644 --- a/frontend/src/pages/DocsPage.tsx +++ b/frontend/src/pages/DocsPage.tsx @@ -34,11 +34,11 @@ export default function DocsPage() { ))}
-

Still simulated

+

Not fully decentralized yet

- 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{' '} + The encryption, share verification, distributed key generation, and separate validator processes are + real. But validators are still run by one party and still trust the backend about when a batch is sealed. + Next, validators will verify an on-chain commitment before decrypting. See the{' '}