Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)).
Expand Down
30 changes: 18 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
6 changes: 5 additions & 1 deletion backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) |

Expand Down
131 changes: 131 additions & 0 deletions backend/src/chain/batchCommitment.ts
Original file line number Diff line number Diff line change
@@ -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<BatchRecord | null>;
}

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<rpc.Server, 'simulateTransaction'>;

/**
* 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<BatchRecord | null> {
// 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<string, unknown> | 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<string, BatchRecord>();

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;
}
14 changes: 10 additions & 4 deletions backend/src/controllers/batchController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 5 additions & 1 deletion backend/src/controllers/settlementController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }] : []));

Expand Down
12 changes: 12 additions & 0 deletions backend/src/db/models/Batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ export class Batch extends Model<InferAttributes<Batch>, InferCreationAttributes
declare id: string;
declare order_ids: string[];
declare status: CreationOptional<BatchStatus>;
/** sha256 commitment to the batch's ordered ciphertexts, as sealed on-chain (hex). */
declare content_hash: CreationOptional<string | null>;
/** Stellar transaction that sealed it (null when using the dev in-memory ledger). */
declare commitment_tx: CreationOptional<string | null>;
declare created_at: CreationOptional<Date>;
}

Expand All @@ -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',
Expand Down
47 changes: 24 additions & 23 deletions backend/src/services/sorobanService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import crypto from 'crypto';
import {
Address,
BASE_FEE,
Expand All @@ -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';
Expand Down Expand Up @@ -47,14 +47,6 @@ function scMap(fields: Record<string, xdr.ScVal>): 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(),
Expand All @@ -79,7 +71,11 @@ function nativeSettlementResult(value: unknown): SettlementResult {
};
}

async function invokeContract(contractId: string, method: string, args: xdr.ScVal[]): Promise<unknown> {
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);
Expand Down Expand Up @@ -114,30 +110,35 @@ 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 = {
getServer(): rpc.Server {
return server;
},

async createBatch(batchId: string, orderIds: string[]): Promise<void> {
/**
* 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<SettlementResult[]> {
Expand All @@ -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,
]);
Expand Down
Loading
Loading