From cc6d7f239a71321365b4f7b8661bd713222d289d Mon Sep 17 00:00:00 2001 From: FEDDIE Date: Fri, 6 Nov 2026 23:10:53 +0000 Subject: [PATCH 1/2] Seal batches on-chain; validators verify the seal before decrypting - Batch commitment is now sha256 over the batch's ciphertexts in settlement order (domain-separated, length-prefixed), recorded via order-vault.create_batch before any decryption. It previously hashed sorted order ids. Batches store content_hash and commitment_tx. - Each validator reads get_batch from Soroban itself (read-only simulation) and refuses shares unless the count and hash match the exact ordered ciphertexts it's asked to decrypt. A pending order can't be decrypted early, even by a coordinator holding every validator token, and nothing can be added, dropped or reordered after sealing. - No silent fallback: validators without a ledger refuse to decrypt. Separate processes must set VALIDATOR_ORDER_VAULT_CONTRACT or opt out explicitly with VALIDATOR_INSECURE_SKIP_COMMITMENT_CHECK=1. Without a contract, the in-process dev ledger stands in. - Settlement keeps the sealed order of the batch. - Batch monitor shows each batch's seal, linked to its transaction. - Works with the already-deployed order-vault (no redeploy). 14 new tests (commitment encoding, sealing-check rejections, Soroban record decoding, early-decrypt and late-insert attacks). 70 backend tests pass. --- backend/src/chain/batchCommitment.ts | 131 +++++++++++++++++ backend/src/controllers/batchController.ts | 14 +- .../src/controllers/settlementController.ts | 6 +- backend/src/db/models/Batch.ts | 12 ++ backend/src/services/sorobanService.ts | 47 +++--- backend/src/services/validatorNetwork.ts | 19 +++ backend/src/validator/devCluster.ts | 17 +++ backend/src/validator/localValidator.ts | 27 +++- backend/src/validator/main.ts | 32 +++- backend/src/validator/protocol.ts | 2 + backend/tests/batchCommitment.test.ts | 137 ++++++++++++++++++ backend/tests/remoteValidators.test.ts | 14 ++ .../src/components/batches/BatchMonitor.tsx | 26 ++++ frontend/src/constants/config.ts | 3 + frontend/src/types/batch.ts | 4 + frontend/src/vite-env.d.ts | 1 + 16 files changed, 461 insertions(+), 31 deletions(-) create mode 100644 backend/src/chain/batchCommitment.ts create mode 100644 backend/tests/batchCommitment.test.ts diff --git a/backend/src/chain/batchCommitment.ts b/backend/src/chain/batchCommitment.ts new file mode 100644 index 0000000..6202e27 --- /dev/null +++ b/backend/src/chain/batchCommitment.ts @@ -0,0 +1,131 @@ +import crypto from 'crypto'; +import { Account, BASE_FEE, Contract, Keypair, TransactionBuilder, nativeToScVal, rpc, scValToNative, xdr } from '@stellar/stellar-sdk'; + +/** + * The on-chain commitment that seals a batch before anyone can decrypt it. + * + * H = sha256( "cipher-protocol/batch-commitment/v1" + * ‖ u32be(n) ‖ for each ciphertext in settlement order: u32be(len) ‖ utf8 ) + * + * Length-prefixed so ["ab","c"] and ["a","bc"] can't collide, and ordered + * because order is what front-running exploits. The backend records + * (n, H) via order-vault.create_batch; every validator independently reads it + * back from chain and recomputes H over the ciphertexts it's asked to + * decrypt, refusing on any mismatch. + */ +const DOMAIN = Buffer.from('cipher-protocol/batch-commitment/v1'); + +export function batchCommitment(ciphertexts: string[]): string { + const h = crypto.createHash('sha256').update(DOMAIN); + const u32 = (n: number) => { + const b = Buffer.alloc(4); + b.writeUInt32BE(n); + return b; + }; + h.update(u32(ciphertexts.length)); + for (const ct of ciphertexts) { + const bytes = Buffer.from(ct, 'utf8'); + h.update(u32(bytes.length)).update(bytes); + } + return h.digest('hex'); +} + +export interface BatchRecord { + orderCount: number; + /** hex */ + contentHash: string; + /** ledger timestamp (seconds) when the batch was sealed */ + timestamp: number; +} + +/** Where validators read sealed-batch commitments from. */ +export interface CommitmentLedger { + readonly kind: 'soroban' | 'dev-in-memory'; + getBatch(batchId: string): Promise; +} + +export function batchIdBytes(batchId: string): Buffer { + const hex = batchId.replace(/-/g, ''); + if (!/^[0-9a-f]{32}$/i.test(hex)) throw new Error(`batch id "${batchId}" is not a UUID`); + return Buffer.from(hex, 'hex'); +} + +export function batchIdToScVal(batchId: string): xdr.ScVal { + return nativeToScVal(batchIdBytes(batchId), { type: 'bytes' }); +} + +type Simulator = Pick; + +/** + * Reads order-vault.get_batch through a read-only simulation: nothing is + * signed or submitted, so validators need no Stellar account or funds. + */ +export class SorobanCommitmentLedger implements CommitmentLedger { + readonly kind = 'soroban' as const; + private readonly server: Simulator; + + constructor( + private readonly contractId: string, + private readonly networkPassphrase: string, + rpcUrlOrServer: string | Simulator + ) { + this.server = typeof rpcUrlOrServer === 'string' ? new rpc.Server(rpcUrlOrServer) : rpcUrlOrServer; + } + + async getBatch(batchId: string): Promise { + // Simulation doesn't check the source account, so a throwaway one is fine. + const source = new Account(Keypair.random().publicKey(), '0'); + const tx = new TransactionBuilder(source, { fee: BASE_FEE, networkPassphrase: this.networkPassphrase }) + .addOperation(new Contract(this.contractId).call('get_batch', batchIdToScVal(batchId))) + .setTimeout(30) + .build(); + const sim = await this.server.simulateTransaction(tx); + if (rpc.Api.isSimulationError(sim)) throw new Error(`get_batch simulation failed: ${sim.error}`); + const retval = (sim as rpc.Api.SimulateTransactionSuccessResponse).result?.retval; + const native = retval ? (scValToNative(retval) as Record | null | undefined) : null; + if (!native) return null; + return { + orderCount: Number(native.order_count), + contentHash: Buffer.from(native.content_hash as Uint8Array).toString('hex'), + timestamp: Number(native.timestamp), + }; + } +} + +/** + * Stand-in for the chain when no ORDER_VAULT_CONTRACT is configured (local + * dev, tests). It only means something when the validators reading it are + * in the same process as the backend writing it — remote validators must + * use SorobanCommitmentLedger. + */ +export class InMemoryCommitmentLedger implements CommitmentLedger { + readonly kind = 'dev-in-memory' as const; + private readonly batches = new Map(); + + async getBatch(batchId: string) { + return this.batches.get(batchId) ?? null; + } + + record(batchId: string, orderCount: number, contentHash: string) { + if (this.batches.has(batchId)) throw new Error('batch already exists'); // mirrors BatchAlreadyExists + this.batches.set(batchId, { orderCount, contentHash, timestamp: Math.floor(Date.now() / 1000) }); + } +} + +export const devCommitmentLedger = new InMemoryCommitmentLedger(); + +/** + * The check every validator runs before releasing decryption shares: the + * exact ordered ciphertext list must match what was sealed on-chain. + */ +export async function assertBatchSealed(ledger: CommitmentLedger, batchId: string, ciphertexts: string[]) { + const record = await ledger.getBatch(batchId); + if (!record) throw new Error(`batch ${batchId} is not committed on-chain; refusing to decrypt`); + if (record.orderCount !== ciphertexts.length) { + throw new Error(`batch ${batchId} was sealed with ${record.orderCount} orders, asked to decrypt ${ciphertexts.length}`); + } + if (record.contentHash !== batchCommitment(ciphertexts)) { + throw new Error(`ciphertexts do not match batch ${batchId}'s on-chain commitment; refusing to decrypt`); + } + return record; +} diff --git a/backend/src/controllers/batchController.ts b/backend/src/controllers/batchController.ts index ef09ca2..c518463 100644 --- a/backend/src/controllers/batchController.ts +++ b/backend/src/controllers/batchController.ts @@ -16,15 +16,21 @@ export const batchController = { throw new AppError('Some orders not found or not pending'); } orderIds = uniqueIds; + const byId = new Map(orders.map((o) => [o.id, o])); + const ciphertexts = orderIds.map((id) => byId.get(id)!.encrypted_data); + + // Seal on-chain first: once this succeeds the batch's contents and order + // are fixed publicly, and only then can validators be asked to decrypt. + const id = crypto.randomUUID(); + const { contentHash, txHash } = await sorobanService.createBatch(id, ciphertexts); const batch = await Batch.create({ - id: crypto.randomUUID(), + id, order_ids: orderIds, status: 'created', + content_hash: contentHash, + commitment_tx: txHash, }); - - await sorobanService.createBatch(batch.id, orderIds); - await Order.update({ status: 'batched', batch_id: batch.id }, { where: { id: orderIds } }); return batch; diff --git a/backend/src/controllers/settlementController.ts b/backend/src/controllers/settlementController.ts index 17f3443..d0cc5c0 100644 --- a/backend/src/controllers/settlementController.ts +++ b/backend/src/controllers/settlementController.ts @@ -31,7 +31,11 @@ export const settlementController = { if (claimed === 0) throw new AppError('Batch already settled or settling', 409); try { - const orders = await Order.findAll({ where: { id: batch.order_ids } }); + // Keep the sealed order: validators recompute the on-chain commitment + // over the ciphertexts exactly as listed. + const rows = await Order.findAll({ where: { id: batch.order_ids } }); + const byId = new Map(rows.map((o) => [o.id, o])); + const orders = batch.order_ids.map((id) => byId.get(id)).filter((o): o is Order => !!o); const outcomes = await validatorService.coordinateDecryption(batchId, orders); const decrypted = outcomes.flatMap((o) => (o.ok ? [{ id: o.orderId, order: o.order }] : [])); diff --git a/backend/src/db/models/Batch.ts b/backend/src/db/models/Batch.ts index 2795d16..0b52518 100644 --- a/backend/src/db/models/Batch.ts +++ b/backend/src/db/models/Batch.ts @@ -6,6 +6,10 @@ export class Batch extends Model, InferCreationAttributes declare id: string; declare order_ids: string[]; declare status: CreationOptional; + /** sha256 commitment to the batch's ordered ciphertexts, as sealed on-chain (hex). */ + declare content_hash: CreationOptional; + /** Stellar transaction that sealed it (null when using the dev in-memory ledger). */ + declare commitment_tx: CreationOptional; declare created_at: CreationOptional; } @@ -19,6 +23,14 @@ Batch.init( type: DataTypes.JSON, allowNull: false, }, + content_hash: { + type: DataTypes.STRING(64), + allowNull: true, + }, + commitment_tx: { + type: DataTypes.STRING(64), + allowNull: true, + }, status: { type: DataTypes.ENUM('created', 'submitted', 'settled', 'failed'), defaultValue: 'created', diff --git a/backend/src/services/sorobanService.ts b/backend/src/services/sorobanService.ts index d3e1522..d01c8fe 100644 --- a/backend/src/services/sorobanService.ts +++ b/backend/src/services/sorobanService.ts @@ -1,4 +1,3 @@ -import crypto from 'crypto'; import { Address, BASE_FEE, @@ -11,6 +10,7 @@ import { xdr, } from '@stellar/stellar-sdk'; import { config } from '../config'; +import { batchCommitment, batchIdToScVal, devCommitmentLedger } from '../chain/batchCommitment'; import { DecryptedOrder } from '../types/order'; import { SettlementResult } from '../types/settlement'; import { AppError } from '../utils/errors'; @@ -47,14 +47,6 @@ function scMap(fields: Record): xdr.ScVal { return xdr.ScVal.scvMap(entries); } -function batchIdToScVal(batchId: string): xdr.ScVal { - const hex = batchId.replace(/-/g, ''); - if (hex.length !== 32) { - throw new AppError(`batch id "${batchId}" is not a UUID (expected 16 bytes)`, 500); - } - return nativeToScVal(Buffer.from(hex, 'hex'), { type: 'bytes' }); -} - function decryptedOrderToScVal(order: DecryptedOrder): xdr.ScVal { return scMap({ user: new Address(order.user).toScVal(), @@ -79,7 +71,11 @@ function nativeSettlementResult(value: unknown): SettlementResult { }; } -async function invokeContract(contractId: string, method: string, args: xdr.ScVal[]): Promise { +async function invokeContract( + contractId: string, + method: string, + args: xdr.ScVal[] +): Promise<{ value: unknown; txHash: string }> { const signer = getSignerKeypair(); const account = await server.getAccount(signer.publicKey()); const contract = new Contract(contractId); @@ -114,7 +110,7 @@ async function invokeContract(contractId: string, method: string, args: xdr.ScVa throw new AppError(`${method} failed on-chain: ${getResult.status}`, 502); } - return getResult.returnValue ? scValToNative(getResult.returnValue) : undefined; + return { value: getResult.returnValue ? scValToNative(getResult.returnValue) : undefined, txHash: sendResult.hash }; } export const sorobanService = { @@ -122,22 +118,27 @@ export const sorobanService = { return server; }, - async createBatch(batchId: string, orderIds: string[]): Promise { + /** + * Seals a batch on-chain: records the commitment to its ordered + * ciphertexts in order-vault. Validators check this record themselves + * before releasing any decryption share, so this must happen first. + */ + async createBatch(batchId: string, ciphertexts: string[]): Promise<{ contentHash: string; txHash: string | null }> { + const contentHash = batchCommitment(ciphertexts); if (!config.orderVaultContract) { - logger.warn(`[sorobanService] ORDER_VAULT_CONTRACT unset — skipping on-chain createBatch for ${batchId}`); - return; + logger.warn( + `[sorobanService] ORDER_VAULT_CONTRACT unset — sealing batch ${batchId} in the in-memory dev ledger (in-process validators only)` + ); + devCommitmentLedger.record(batchId, ciphertexts.length, contentHash); + return { contentHash, txHash: null }; } - const contentHash = crypto - .createHash('sha256') - .update([...orderIds].sort().join(',')) - .digest(); - - await invokeContract(config.orderVaultContract, 'create_batch', [ + const { txHash } = await invokeContract(config.orderVaultContract, 'create_batch', [ batchIdToScVal(batchId), - nativeToScVal(orderIds.length, { type: 'u32' }), - nativeToScVal(contentHash, { type: 'bytes' }), + nativeToScVal(ciphertexts.length, { type: 'u32' }), + nativeToScVal(Buffer.from(contentHash, 'hex'), { type: 'bytes' }), ]); + return { contentHash, txHash }; }, async settleBatch(batchId: string, decryptedOrders: DecryptedOrder[]): Promise { @@ -157,7 +158,7 @@ export const sorobanService = { const ordersScVal = xdr.ScVal.scvVec(decryptedOrders.map(decryptedOrderToScVal)); - const raw = await invokeContract(config.settlementEngineContract, 'settle_batch', [ + const { value: raw } = await invokeContract(config.settlementEngineContract, 'settle_batch', [ batchIdToScVal(batchId), ordersScVal, ]); diff --git a/backend/src/services/validatorNetwork.ts b/backend/src/services/validatorNetwork.ts index 79abd61..e91a0bc 100644 --- a/backend/src/services/validatorNetwork.ts +++ b/backend/src/services/validatorNetwork.ts @@ -7,6 +7,7 @@ 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 { CommitmentLedger, SorobanCommitmentLedger, devCommitmentLedger } from '../chain/batchCommitment'; import logger from '../utils/logger'; export type { ValidatorNode }; @@ -86,12 +87,20 @@ let initializing: Promise | null = null; const keyFileFor = (dir: string, index: number) => (dir ? path.join(dir, `validator-${index}.json`) : ''); +/** What in-process validators check sealing against: the real order-vault if configured, else the dev ledger. */ +export function defaultCommitmentLedger(): CommitmentLedger { + return config.orderVaultContract + ? new SorobanCommitmentLedger(config.orderVaultContract, config.networkPassphrase, config.sorobanRpcUrl) + : devCommitmentLedger; +} + export interface CreateLocalNetworkOptions { count: number; threshold: number; byzantine?: number[]; dkgFaults?: Record; keyDir?: string; + commitments?: CommitmentLedger | 'insecure-skip'; } /** In-process validators (dev/tests): fresh identities, then a real DKG among them. */ @@ -106,6 +115,7 @@ export async function createLocalNetwork(opts: CreateLocalNetworkOptions) { byzantine: opts.byzantine?.includes(k + 1), dkgFaults: opts.dkgFaults?.[k + 1], keyFile: keyFileFor(opts.keyDir ?? '', k + 1), + commitments: opts.commitments ?? defaultCommitmentLedger(), }) ); const { result, transcript } = await runDkg(validators, opts.threshold, peers); @@ -150,6 +160,7 @@ function loadLocalNetwork(dir: string): ValidatorNetwork | null { identity: identities[n], peers, byzantine: config.byzantineValidators.includes(k.index), + commitments: defaultCommitmentLedger(), }) ); return { threshold, groupPublicKey, verificationKeys, validators, mode: 'local' }; @@ -172,6 +183,14 @@ export async function connectRemoteNetwork(clusterFile: string, threshold: numbe throw new Error(`validator ${info.index} reports identity ${info.identityKey}, cluster file expects ${identityKeys[info.index]}`); } } + for (const info of reachable) { + if (info.commitmentCheck !== 'soroban') { + logger.warn( + `validator ${info.index} verifies batch sealing via "${info.commitmentCheck ?? 'unknown'}", not the chain — ` + + 'it will trust this coordinator about when a batch is sealed' + ); + } + } const keyed = reachable.filter((i) => i.hasKey); if (keyed.length === 0) { diff --git a/backend/src/validator/devCluster.ts b/backend/src/validator/devCluster.ts index 2fbba40..c34be98 100644 --- a/backend/src/validator/devCluster.ts +++ b/backend/src/validator/devCluster.ts @@ -10,6 +10,7 @@ * with VALIDATOR_CLUSTER_FILE=data/cluster/cluster.json. The first backend * start runs the DKG over HTTP; later starts reuse the shares. */ +import dotenv from 'dotenv'; import { ChildProcess, spawn } from 'child_process'; import crypto from 'crypto'; import fs from 'fs'; @@ -17,6 +18,8 @@ import path from 'path'; import { loadOrCreateIdentity } from './main'; import { ClusterFile } from './remoteValidator'; +dotenv.config(); + const root = path.join(__dirname, '..', '..', 'data', 'cluster'); const count = Number(process.env.VALIDATOR_COUNT) || 5; const basePort = Number(process.env.VALIDATOR_BASE_PORT) || 6000; @@ -45,6 +48,19 @@ 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(','); + +// Validators verify batch sealing on-chain when a contract is configured. +// Without one there is no shared chain to read, so the check is disabled. +const sealing: Record = process.env.ORDER_VAULT_CONTRACT + ? { + VALIDATOR_ORDER_VAULT_CONTRACT: process.env.ORDER_VAULT_CONTRACT, + VALIDATOR_SOROBAN_RPC_URL: process.env.SOROBAN_RPC_URL || 'https://soroban-testnet.stellar.org', + VALIDATOR_NETWORK_PASSPHRASE: process.env.STELLAR_NETWORK_PASSPHRASE || 'Test SDF Network ; September 2015', + } + : { VALIDATOR_INSECURE_SKIP_COMMITMENT_CHECK: '1' }; +if (!process.env.ORDER_VAULT_CONTRACT) { + console.warn('ORDER_VAULT_CONTRACT not set: validators will NOT verify batch sealing on-chain (dev only).'); +} // 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)}`); @@ -59,6 +75,7 @@ const children: ChildProcess[] = members.map((m) => VALIDATOR_KEY_DIR: m.keyDir, VALIDATOR_API_TOKEN: m.apiToken, VALIDATOR_PEER_KEYS: peerKeys, + ...sealing, }, }) ); diff --git a/backend/src/validator/localValidator.ts b/backend/src/validator/localValidator.ts index e4efc85..d894698 100644 --- a/backend/src/validator/localValidator.ts +++ b/backend/src/validator/localValidator.ts @@ -5,6 +5,7 @@ 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 { CommitmentLedger, assertBatchSealed } from '../chain/batchCommitment'; import { DOMAIN, DkgResultStatement, @@ -36,6 +37,12 @@ export interface LocalValidatorOptions { dkgFaults?: DkgFaults; /** Persist this validator's own share here after DKG ('' = memory only). */ keyFile?: string; + /** + * Where to check that a batch is sealed on-chain before decrypting it. + * There is deliberately no silent default: without a ledger the validator + * refuses to decrypt. 'insecure-skip' must be chosen explicitly. + */ + commitments?: CommitmentLedger | 'insecure-skip'; } /** @@ -72,15 +79,33 @@ export class LocalValidator implements ValidatorNode { index: this.index, identityKey: this.opts.identity.publicKey, hasKey: !!this.keyShare, + commitmentCheck: this.commitmentCheck(), threshold: this.keyInfo?.threshold, groupPublicKey: this.keyInfo?.groupPublicKey, verificationKeys: this.keyInfo?.verificationKeys, }; } - async requestDecryptionShares(_batchId: string, ciphertexts: string[]): Promise { + private commitmentCheck(): ValidatorInfo['commitmentCheck'] { + const c = this.opts.commitments; + return !c ? 'unconfigured' : c === 'insecure-skip' ? 'disabled' : c.kind; + } + + /** + * Releases this validator's shares for a batch — but only after checking, + * independently of the coordinator, that exactly these ciphertexts in + * exactly this order were sealed on-chain under `batchId`. A coordinator + * can't decrypt a pending order early, or slip one into a sealed batch. + */ + async requestDecryptionShares(batchId: string, ciphertexts: string[]): Promise { const keyShare = this.keyShare; if (!keyShare) throw new Error(`${this.address} has no key share`); + if (!Array.isArray(ciphertexts) || ciphertexts.some((c) => typeof c !== 'string')) { + throw new Error('ciphertexts must be an array of strings'); + } + const ledger = this.opts.commitments; + if (!ledger) throw new Error(`${this.address} has no commitment ledger configured; refusing to decrypt`); + if (ledger !== 'insecure-skip') await assertBatchSealed(ledger, batchId, ciphertexts); return ciphertexts.map((ct) => { const share = partialDecrypt(keyShare, parseCiphertext(ct).R); // A byzantine validator substitutes a valid-looking point that is not diff --git a/backend/src/validator/main.ts b/backend/src/validator/main.ts index 0b46836..0323737 100644 --- a/backend/src/validator/main.ts +++ b/backend/src/validator/main.ts @@ -7,11 +7,19 @@ * 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,…" + * + * Batch-sealing check (required — the validator refuses to decrypt without one): + * VALIDATOR_ORDER_VAULT_CONTRACT order-vault contract id to read commitments from + * VALIDATOR_SOROBAN_RPC_URL (default https://soroban-testnet.stellar.org) + * VALIDATOR_NETWORK_PASSPHRASE (default testnet) + * or, for local development only: + * VALIDATOR_INSECURE_SKIP_COMMITMENT_CHECK=1 */ import dotenv from 'dotenv'; import fs from 'fs'; import path from 'path'; import { Identity, generateIdentity, publicKeyOf } from '../crypto/signing'; +import { CommitmentLedger, SorobanCommitmentLedger } from '../chain/batchCommitment'; import { LocalValidator, PersistedValidatorKey } from './localValidator'; import { createValidatorApp } from './server'; @@ -50,6 +58,25 @@ export function loadOrCreateIdentity(keyDir: string): Identity { return identity; } +function commitmentLedgerFromEnv(): CommitmentLedger | 'insecure-skip' { + const contract = process.env.VALIDATOR_ORDER_VAULT_CONTRACT; + if (contract) { + return new SorobanCommitmentLedger( + contract, + process.env.VALIDATOR_NETWORK_PASSPHRASE || 'Test SDF Network ; September 2015', + process.env.VALIDATOR_SOROBAN_RPC_URL || 'https://soroban-testnet.stellar.org' + ); + } + if (process.env.VALIDATOR_INSECURE_SKIP_COMMITMENT_CHECK === '1') { + console.warn( + 'WARNING: VALIDATOR_INSECURE_SKIP_COMMITMENT_CHECK=1 — this validator will release shares without ' + + 'checking that batches are sealed on-chain. Development only.' + ); + return 'insecure-skip'; + } + throw new Error('set VALIDATOR_ORDER_VAULT_CONTRACT (or VALIDATOR_INSECURE_SKIP_COMMITMENT_CHECK=1 for local dev)'); +} + export function startValidator() { const index = Number(required('VALIDATOR_INDEX')); const keyDir = required('VALIDATOR_KEY_DIR'); @@ -58,7 +85,7 @@ export function startValidator() { 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 opts = { identity, peers, keyFile, commitments: commitmentLedgerFromEnv() }; const validator = fs.existsSync(keyFile) ? LocalValidator.fromPersisted(JSON.parse(fs.readFileSync(keyFile, 'utf8')) as PersistedValidatorKey, opts) @@ -68,7 +95,8 @@ export function startValidator() { 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'})` + `(identity ${identity.publicKey.slice(0, 16)}…, ${fs.existsSync(keyFile) ? 'key share loaded' : 'awaiting DKG'}, ` + + `sealing check: ${opts.commitments === 'insecure-skip' ? 'DISABLED' : 'on-chain'})` ); }); } diff --git a/backend/src/validator/protocol.ts b/backend/src/validator/protocol.ts index 9cba859..e9b61df 100644 --- a/backend/src/validator/protocol.ts +++ b/backend/src/validator/protocol.ts @@ -41,6 +41,8 @@ export interface ValidatorInfo { index: number; identityKey: string; hasKey: boolean; + /** How this validator verifies batch sealing before decrypting. */ + commitmentCheck?: 'soroban' | 'dev-in-memory' | 'disabled' | 'unconfigured'; threshold?: number; groupPublicKey?: string; verificationKeys?: Record; diff --git a/backend/tests/batchCommitment.test.ts b/backend/tests/batchCommitment.test.ts new file mode 100644 index 0000000..6f85ca1 --- /dev/null +++ b/backend/tests/batchCommitment.test.ts @@ -0,0 +1,137 @@ +import { describe, it, expect, beforeEach, afterAll } from 'vitest'; +import crypto from 'crypto'; +import { StrKey, nativeToScVal, rpc, xdr } from '@stellar/stellar-sdk'; +import { + InMemoryCommitmentLedger, + SorobanCommitmentLedger, + assertBatchSealed, + batchCommitment, +} from '../src/chain/batchCommitment'; +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 { batchingService } from '../src/services/batchingService'; +import { createLocalNetwork, setValidatorNetwork } from '../src/services/validatorNetwork'; +import { validatorService } from '../src/services/validatorService'; +import { newUser, submitSwap } from './helpers'; + +describe('batch commitment', () => { + it('is deterministic, order-sensitive, and length-prefixed', () => { + expect(batchCommitment(['a', 'b'])).toBe(batchCommitment(['a', 'b'])); + expect(batchCommitment(['a', 'b'])).not.toBe(batchCommitment(['b', 'a'])); + expect(batchCommitment(['ab', 'c'])).not.toBe(batchCommitment(['a', 'bc'])); + expect(batchCommitment([])).not.toBe(batchCommitment([''])); + expect(batchCommitment(['x'])).toMatch(/^[0-9a-f]{64}$/); + }); +}); + +describe('validator sealing check', () => { + const ledger = new InMemoryCommitmentLedger(); + const id = crypto.randomUUID(); + const cts = ['ctp1.one', 'ctp1.two', 'ctp1.three']; + ledger.record(id, cts.length, batchCommitment(cts)); + + it('accepts exactly the sealed ciphertexts in the sealed order', async () => { + await expect(assertBatchSealed(ledger, id, cts)).resolves.toMatchObject({ orderCount: 3 }); + }); + + it.each([ + ['an unknown batch', crypto.randomUUID(), cts, /not committed on-chain/], + ['a missing ciphertext', id, cts.slice(0, 2), /sealed with 3 orders/], + ['an extra ciphertext', id, [...cts, 'ctp1.four'], /sealed with 3 orders/], + ['a reordered batch', id, [cts[1], cts[0], cts[2]], /do not match/], + ['a swapped-in ciphertext', id, ['ctp1.one', 'ctp1.EVIL', 'ctp1.three'], /do not match/], + ])('refuses %s', async (_label, batchId, list, err) => { + await expect(assertBatchSealed(ledger, batchId as string, list as string[])).rejects.toThrow(err as RegExp); + }); + + it('a batch id can only be sealed once', () => { + expect(() => ledger.record(id, 1, batchCommitment(['x']))).toThrow(/already exists/); + }); +}); + +describe('reading commitments from order-vault (Soroban)', () => { + const CONTRACT = 'CD6IHURX2DJIKYZLDD24VZTAL347NC6UUW5WYJEF6VJRCAYSULRWTNW4'; + + /** Encodes a BatchAttestation the way the contract returns it (struct = sorted-key map). */ + function attestation(orderCount: number, hashHex: string, ts: number): xdr.ScVal { + const entry = (k: string, v: xdr.ScVal) => new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol(k), val: v }); + return xdr.ScVal.scvMap([ + entry('content_hash', nativeToScVal(Buffer.from(hashHex, 'hex'), { type: 'bytes' })), + entry('order_count', nativeToScVal(orderCount, { type: 'u32' })), + entry('timestamp', nativeToScVal(ts, { type: 'u64' })), + ]); + } + + function fakeServer(retval: xdr.ScVal, seen: string[] = []) { + return { + async simulateTransaction(tx: { operations: { func: unknown }[] }) { + const call = (tx.operations[0].func as { + invokeContract: { contractAddress: { contractId: { toXdrObject(): Uint8Array } }; functionName: unknown }; + }).invokeContract; + seen.push(StrKey.encodeContract(Buffer.from(call.contractAddress.contractId.toXdrObject())), String(call.functionName)); + return { result: { retval }, latestLedger: 1, events: [], id: '1', _parsed: true } as unknown as rpc.Api.SimulateTransactionSuccessResponse; + }, + }; + } + + it('decodes a sealed batch record', async () => { + const hash = batchCommitment(['a', 'b']); + const seen: string[] = []; + const ledger = new SorobanCommitmentLedger(CONTRACT, 'Test SDF Network ; September 2015', fakeServer(attestation(2, hash, 1700000000), seen)); + expect(await ledger.getBatch(crypto.randomUUID())).toEqual({ orderCount: 2, contentHash: hash, timestamp: 1700000000 }); + expect(seen).toEqual([CONTRACT, 'get_batch']); + }); + + it('returns null for a batch that was never sealed (Option::None)', async () => { + const ledger = new SorobanCommitmentLedger(CONTRACT, 'Test SDF Network ; September 2015', fakeServer(xdr.ScVal.scvVoid())); + expect(await ledger.getBatch(crypto.randomUUID())).toBeNull(); + }); +}); + +describe('backend seals before decrypting', () => { + const app = createApp(); + beforeEach(async () => { + await sequelize.sync({ force: true }); + setValidatorNetwork(await createLocalNetwork({ count: 5, threshold: 3 })); + await validatorService.syncValidatorRegistry(); + }); + afterAll(() => sequelize.close()); + + it('records the commitment over the ordered ciphertexts on the batch', async () => { + const a = await submitSwap(app, newUser()); + const b = await submitSwap(app, newUser()); + const batch = (await batchingService.runOnce())!; + const saved = (await Batch.findByPk(batch.id))!; + const orders = await Order.findAll({ where: { id: saved.order_ids } }); + const byId = new Map(orders.map((o) => [o.id, o.encrypted_data])); + expect(saved.content_hash).toBe(batchCommitment(saved.order_ids.map((id) => byId.get(id)!))); + expect(new Set(saved.order_ids)).toEqual(new Set([a.body.order.id, b.body.order.id])); + expect((await Order.findByPk(a.body.order.id))!.status).toBe('settled'); + }); + + it('a coordinator cannot decrypt a pending order without sealing it first', async () => { + const res = await submitSwap(app, newUser()); + const order = (await Order.findByPk(res.body.order.id))!; + const [outcome] = await validatorService.coordinateDecryption(crypto.randomUUID(), [order]); + expect(outcome).toMatchObject({ ok: false, reason: expect.stringMatching(/0\/3 valid decryption shares/) }); + }); + + it('a coordinator cannot slip an extra order into an already-sealed batch', async () => { + await submitSwap(app, newUser()); + const sealed = (await batchingService.runOnce())!; + const late = await submitSwap(app, newUser()); + const sealedOrders = await Order.findAll({ where: { id: sealed.order_ids } }); + const lateOrder = (await Order.findByPk(late.body.order.id))!; + const outcomes = await validatorService.coordinateDecryption(sealed.id, [...sealedOrders, lateOrder]); + expect(outcomes.every((o) => !o.ok)).toBe(true); + }); + + it('validators with no commitment ledger refuse to decrypt at all', async () => { + const net = await createLocalNetwork({ count: 3, threshold: 2 }); + const bare = net.validators[0] as unknown as { opts: { commitments?: unknown } }; + bare.opts.commitments = undefined; + await expect(net.validators[0].requestDecryptionShares(crypto.randomUUID(), [])).rejects.toThrow(/no commitment ledger/); + }); +}); diff --git a/backend/tests/remoteValidators.test.ts b/backend/tests/remoteValidators.test.ts index d88909f..87c1e95 100644 --- a/backend/tests/remoteValidators.test.ts +++ b/backend/tests/remoteValidators.test.ts @@ -16,6 +16,7 @@ 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 { devCommitmentLedger } from '../src/chain/batchCommitment'; import { newUser, submitSwap } from './helpers'; /** @@ -40,6 +41,8 @@ function startValidator(k: number): Promise { identity: ids[k], peers, keyFile: path.join(keyDir(index), `validator-${index}.json`), + // Stands in for the chain: the backend seals into it, validators read it. + commitments: devCommitmentLedger, }); return new Promise((resolve) => { const s = createValidatorApp(validator, tokens[k]).listen(0, '127.0.0.1', () => resolve(s)); @@ -101,6 +104,17 @@ describe('validators as separate network services', () => { expect(net.groupPublicKey).toBe(groupKey); }); + it('validators refuse shares for an order that was never sealed in a batch', async () => { + const res = await submitSwap(app, newUser()); + const order = (await Order.findByPk(res.body.order.id))!; + // A coordinator holding every API token tries to decrypt a pending order early. + const [outcome] = await validatorService.coordinateDecryption(crypto.randomUUID(), [order]); + expect(outcome.ok).toBe(false); + expect((await Order.findByPk(order.id))!.status).toBe('pending'); + await batchingService.runOnce(); // the honest path still works afterwards + expect((await Order.findByPk(order.id))!.status).toBe('settled'); + }); + 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`, { diff --git a/frontend/src/components/batches/BatchMonitor.tsx b/frontend/src/components/batches/BatchMonitor.tsx index e12fdef..8795c67 100644 --- a/frontend/src/components/batches/BatchMonitor.tsx +++ b/frontend/src/components/batches/BatchMonitor.tsx @@ -3,6 +3,8 @@ import { useBatches } from '../../hooks/useBatches'; import { formatTimestamp } from '../../utils/formatting'; import Loading from '../common/Loading'; import BatchStats from './BatchStats'; +import { Batch } from '../../types/batch'; +import { STELLAR_EXPLORER_TX_URL } from '../../constants/config'; const STATUS_TEXT_CLASSES: Record = { settled: 'text-green-600 dark:text-green-400', @@ -11,6 +13,29 @@ const STATUS_TEXT_CLASSES: Record = { failed: 'text-red-600 dark:text-red-400', }; +/** Shows the on-chain commitment that sealed this batch before any validator would decrypt it. */ +function BatchSeal({ batch }: { batch: Batch }) { + if (!batch.content_hash) return null; + const short = `${batch.content_hash.slice(0, 10)}…`; + return ( +

+ 🔏 Sealed:{' '} + {batch.commitment_tx ? ( + + {short} + + ) : ( + {short} (local dev ledger) + )} +

+ ); +} + export default function BatchMonitor() { const [autoRefresh, setAutoRefresh] = useState(true); const { batches, stats, loading } = useBatches(autoRefresh); @@ -46,6 +71,7 @@ export default function BatchMonitor() {

{batch.id.slice(0, 8)}...

{batch.order_ids.length} orders

+

Date: Fri, 6 Nov 2026 23:10:53 +0000 Subject: [PATCH 2/2] Docs: on-chain batch sealing and the remaining trust in batch composition Document the batch commitment, the validator-side check, and the no-fallback rule. Narrow the trust section to what remains: the coordinator choosing batch composition, settlement not yet bound to the seal, and validators trusting their RPC endpoint. New contributor issues cover a validator batch policy and binding settle_batch to the seal. --- CONTRIBUTING.md | 4 +-- README.md | 30 +++++++++------- SECURITY.md | 5 +-- backend/README.md | 6 +++- contracts/README.md | 8 +++-- docs/CONTRIBUTOR_ISSUES.md | 31 +++++++++++------ docs/THRESHOLD_ENCRYPTION.md | 61 ++++++++++++++++++++++++++------- frontend/src/pages/DocsPage.tsx | 24 +++++++++---- 8 files changed, 120 insertions(+), 49 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f4c45dc..01573fd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -51,8 +51,8 @@ understand the scope of the fix. ## Security -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) +Known, documented gaps (the coordinator choosing batch composition, 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 2401572..1e2b92f 100644 --- a/README.md +++ b/README.md @@ -41,8 +41,9 @@ User submits a swap (ElGamal KEM on ristretto255 + AES-256-GCM, bound to the user's address) -> POST /api/orders carries ciphertext only; the backend stores it with no plaintext -> batching loop seals pending orders into a batch - -> order-vault.create_batch attests to the batch on-chain - -> validators each return y_i*R plus a DLEQ proof; bad shares are discarded + -> order-vault.create_batch seals it on-chain: sha256 over its ordered ciphertexts + -> each validator reads that seal from Soroban itself, then returns y_i*R plus a + DLEQ proof, refusing if the ciphertexts don't match; bad shares are discarded -> any t valid shares combine to decrypt; each payload is validated -> settlement-engine.settle_batch executes the swaps atomically against its AMM pool -> orders revealed and marked settled (or failed, with a reason) @@ -78,25 +79,30 @@ What's real and tested: 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), +- **On-chain batch sealing, verified by validators** + (`backend/src/chain/`): each batch's ordered ciphertexts are committed to + `order-vault` before decryption. Every validator reads that commitment + from Soroban itself and refuses to decrypt anything that doesn't match, so + a pending order can't be decrypted early, even by the backend. The batch + monitor links each batch to its sealing transaction. +- **Tests and CI**: 70 backend tests (crypto, DKG, malicious coordinator, + remote validators, batch sealing, 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: -- **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. +- **The backend still chooses batch composition.** It can't decrypt + without sealing publicly first, but it could censor orders or seal tiny + batches. Validators don't enforce a batch policy yet, and `settle_batch` + doesn't yet cross-check the seal. - **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 - ciphertext hashes on-chain. +- **The on-chain vault records sealed batches, not individual orders.** + The backend database is still the mempool. Users can't yet submit orders + directly on-chain. - **Schema setup uses `sequelize.sync`** rather than real migrations. ## Deployed contracts (Stellar testnet) diff --git a/SECURITY.md b/SECURITY.md index 797d5aa..14dd2c3 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 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, +the coordinator chooses batch composition, and validators don't yet +enforce a batch policy; settlement isn't yet bound to the on-chain seal; +validators are 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). diff --git a/backend/README.md b/backend/README.md index fbf85a1..90a4751 100644 --- a/backend/README.md +++ b/backend/README.md @@ -43,6 +43,10 @@ npm run validators:dev # terminal 1: 5 validator processes on :6001-6005 VALIDATOR_CLUSTER_FILE=data/cluster/cluster.json npm run dev # terminal 2 ``` +Set `ORDER_VAULT_CONTRACT` before `validators:dev` so each validator +verifies batch seals on-chain. Without it there is no shared chain, so the +dev cluster disables that check and warns. + 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 @@ -61,7 +65,7 @@ the DLEQ proofs reject bad validators, set `BYZANTINE_VALIDATORS=2,4`. With | POST | `/api/orders` | Bearer | `{encrypted_data, threshold_pubkey, nonce}`, ciphertext only | | GET | `/api/orders/user/:address` | Bearer (own address) | Your order history | | GET | `/api/orders/:id` | – | One order (plaintext fields `null` until settled) | -| GET | `/api/batches`, `/api/batches/:id` | – | Batches | +| GET | `/api/batches`, `/api/batches/:id` | – | Batches, with `content_hash` (the on-chain seal) and `commitment_tx` | | GET | `/api/settlement/:batchId` | – | Settlement results | | POST | `/api/settlement/:batchId/settle` | – | Retry a failed batch (idempotent) | diff --git a/contracts/README.md b/contracts/README.md index 253a221..7014b57 100644 --- a/contracts/README.md +++ b/contracts/README.md @@ -62,9 +62,11 @@ Currently deployed testnet instances are listed in the root ## Design notes -- `order-vault.create_batch` records an **admin-attested** batch (order - count + content hash), not a copy of the orders themselves — see the root - README's Status section for why. `submit_order`/`get_pending_orders` exist +- `order-vault.create_batch` **seals** a batch: order count plus + `content_hash`, a sha256 commitment to the batch's ciphertexts in + settlement order (see `backend/src/chain/batchCommitment.ts`). Validators + read it back with `get_batch` and refuse to decrypt anything that doesn't + match. It records a commitment, not a copy of the orders. `submit_order`/`get_pending_orders` exist for a possible future direct-submission path but aren't wired to anything yet. - `settlement-engine` combines settlement, the AMM liquidity pool, and fee diff --git a/docs/CONTRIBUTOR_ISSUES.md b/docs/CONTRIBUTOR_ISSUES.md index 625a265..0fd91f7 100644 --- a/docs/CONTRIBUTOR_ISSUES.md +++ b/docs/CONTRIBUTOR_ISSUES.md @@ -5,7 +5,8 @@ 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), validators as -separate processes with signed DKG messages, signature auth, +separate processes with signed DKG messages, on-chain batch sealing +verified by every validator, signature auth, backend and frontend test suites, and CI. See the root README's Status section. @@ -40,17 +41,27 @@ doesn't stop settlement. --- -### 3. Commit ciphertext hashes on-chain; validators verify before decrypting (200) +### 3. Validators enforce a batch policy before decrypting (150) -`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 -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. +Validators already refuse to decrypt anything not sealed on-chain +(`src/chain/batchCommitment.ts#assertBatchSealed`). But the coordinator +still chooses what goes into a batch, and it could seal a batch of one to +single out an order. Add a validator-side policy, checked against the +on-chain record: a minimum order count *or* a minimum age since the last +sealed batch. Make it configurable per validator. -**Scope:** contract change and tests in `contracts/order-vault`, plus the -`sorobanService.createBatch` update. +**Acceptance:** tests show a 1-order batch is refused while the policy is +unmet and accepted once the age threshold passes, with no change to the +honest pipeline. + +--- + +### 3b. Bind settlement to the on-chain seal (150) + +`settlement-engine.settle_batch` doesn't check `order-vault`. Make it read +`order-vault.get_batch(batch_id)` (cross-contract call) and reject settling +a batch that wasn't sealed, or whose order count doesn't match. Add contract +tests for both rejections and for the happy path. --- diff --git a/docs/THRESHOLD_ENCRYPTION.md b/docs/THRESHOLD_ENCRYPTION.md index 755b83d..bfd90f6 100644 --- a/docs/THRESHOLD_ENCRYPTION.md +++ b/docs/THRESHOLD_ENCRYPTION.md @@ -55,7 +55,8 @@ derive `k` and open the ciphertext. | A ciphertext can't be resubmitted under another account | User address is GCM AAD; the decrypted `user` must match the submitter | `pipeline.test.ts` ("replayed", "different user") | | Tampering is detected | AES-GCM authentication | `threshold.test.ts` | | 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` | +| Contents and order are fixed on-chain before anything is decrypted | Each validator checks the `order-vault` commitment itself before releasing a share (see [Batch sealing](#batch-sealing-on-chain)) | `batchCommitment.test.ts`, `remoteValidators.test.ts` | +| A pending order can't be decrypted early, even by a coordinator holding every validator token | No sealed batch on-chain means no shares | `batchCommitment.test.ts`, `remoteValidators.test.ts` ("never sealed") | ## Key generation (DKG) @@ -135,24 +136,60 @@ 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. +## Batch sealing on-chain + +Before any decryption, the backend seals the batch by calling +`order-vault.create_batch(batch_id, n, H)`, where + +``` +H = sha256("cipher-protocol/batch-commitment/v1" ‖ u32be(n) ‖ Σ u32be(len(ct_i)) ‖ ct_i) +``` + +over the batch's ciphertexts **in settlement order**. The length prefixes +prevent boundary collisions, and the ordering matters because order is what +front-running exploits. The contract refuses to re-seal a batch id, and the +record is public and timestamped. + +**Every validator checks this itself.** When asked for decryption shares +for `(batch_id, [ct_1 … ct_n])`, a validator reads `get_batch(batch_id)` +from Soroban through a read-only simulation (no account or funds needed), +recomputes `H`, and refuses unless the count and hash match exactly. So +neither the backend nor anyone holding every validator's API token can: + +- decrypt a pending order before its batch is publicly sealed; +- add, drop, swap or reorder ciphertexts after sealing; +- decrypt anything without leaving a public, timestamped commitment first. + +There is deliberately **no silent fallback**. A validator without a ledger +refuses to decrypt. Local development without a deployed contract uses an +in-memory stand-in that only works for in-process validators, and separate +validator processes must opt out explicitly with +`VALIDATOR_INSECURE_SKIP_COMMITMENT_CHECK=1`, which they warn about loudly. +The deployed testnet `order-vault` needed **no redeploy**: it already stored +`(order_count, content_hash, timestamp)`. What changed is that the hash now +commits to ciphertexts rather than order ids, and that validators verify it. + ## What is still trusted, and what's next Being honest about the remaining gaps: -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, +1. **The coordinator chooses which orders go into a batch.** It can't + decrypt anything without sealing it publicly first. But it could censor + orders, or seal very small batches. Next step: validators enforce a batch + policy (minimum size or age) before contributing. +2. **Settlement isn't bound to the seal on-chain.** `settle_batch` doesn't + yet check that the batch id was sealed in `order-vault` with a matching + order count. +3. **Validators trust their Soroban RPC endpoint** to report the chain + honestly. Production validators should each query their own RPC node. +4. **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. -4. **DKG key bias** (see above): upgrade round 1 to Pedersen commitments. +5. **The coordinator is the backend.** After combining shares, the backend + sees the plaintext, but only for batches already sealed on-chain. Moving + combination into the settlement transaction is future work. +6. **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 0c784f9..84d5292 100644 --- a/frontend/src/pages/DocsPage.tsx +++ b/frontend/src/pages/DocsPage.tsx @@ -5,19 +5,29 @@ const SECTIONS = [ }, { title: '2. Submit an encrypted order', - body: 'Your swap is encrypted in the browser to the validator set’s threshold public key (ElGamal on ristretto255 + AES-256-GCM) and bound to your address. The server only ever receives ciphertext.', + body: + 'Your swap is encrypted in the browser to the validator set’s threshold public key (ElGamal on ristretto255 + AES-256-GCM) and bound to your address. ' + + 'The server only ever receives ciphertext.', }, { title: '3. Batching', - body: 'Pending orders are sealed into a batch in arrival order, and an attestation (order count + content hash) is recorded on-chain through the order-vault contract. Once a batch is sealed, its contents and order can’t change.', + body: + 'Pending orders are sealed into a batch in arrival order: a hash of the batch’s encrypted orders, in order, is recorded on-chain in the order-vault contract. ' + + 'Once sealed, a batch’s contents and order can’t change, and the Batches page links to the sealing transaction.', }, { title: '4. Threshold decryption', - 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.', + body: + 'The validators generated the encryption key together (distributed key generation), so no one ever held the whole key. ' + + 'Each validator reads the batch’s seal from the chain itself and refuses to decrypt anything that doesn’t match it, so not even the server can open an order early. ' + + 'Only then 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', - body: 'Decrypted orders are executed together by the settlement-engine contract against its AMM liquidity pool. All orders in a batch settle together or not at all. Live on Stellar testnet with real token transfers.', + body: + 'Decrypted orders are executed together by the settlement-engine contract against its AMM liquidity pool. ' + + 'All orders in a batch settle together or not at all. Live on Stellar testnet with real token transfers.', }, ]; @@ -36,9 +46,9 @@ export default function DocsPage() {

Not fully decentralized yet

- 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{' '} + The encryption, share verification, distributed key generation, separate validator processes, and on-chain + batch sealing are real. But validators are still run by one party, and the server still decides which + orders go into each batch. See the{' '}