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 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)).
Expand Down
26 changes: 17 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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
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 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
Expand Down
5 changes: 5 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=
4 changes: 2 additions & 2 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -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/
27 changes: 23 additions & 4 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<i>.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-<i>.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.
Expand All @@ -52,13 +65,19 @@ 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)
- `npm run build` / `npm start` — compile to `dist/` and run it
- `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

Expand Down
3 changes: 3 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
4 changes: 4 additions & 0 deletions backend/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 || '')
Expand Down
10 changes: 9 additions & 1 deletion backend/src/crypto/dkg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down
61 changes: 61 additions & 0 deletions backend/src/crypto/signing.ts
Original file line number Diff line number Diff line change
@@ -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<T> {
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<string, unknown>;
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<T>(domain: string, payload: T, signer: number, secretKeyHex: string): Signed<T> {
const signature = ed25519.sign(message(domain, signer, payload), hexToBytes(secretKeyHex));
return { payload, signer, signature: bytesToHex(signature) };
}

export function verifySigned(domain: string, signed: Signed<unknown>, 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;
}
}
Loading
Loading