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
66 changes: 66 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
name: CI

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
integrity:
name: Source integrity
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: ./scripts/check-source-integrity.sh

backend:
name: Backend (typecheck, test, build)
runs-on: ubuntu-latest
defaults:
run:
working-directory: backend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: backend/package-lock.json
- run: npm ci
- run: npm run typecheck
- run: npm test
- run: npm run build

frontend:
name: Frontend (test, build)
runs-on: ubuntu-latest
defaults:
run:
working-directory: frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
- run: npm ci
- run: npm test
- run: npm run build

contracts:
name: Contracts (cargo test)
runs-on: ubuntu-latest
defaults:
run:
working-directory: contracts
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
workspaces: contracts
- run: cargo test --locked
20 changes: 13 additions & 7 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@ understand the scope of the fix.
3. **Run the relevant test suite before opening a PR:**
- `contracts/`: `cargo test` (both contracts have real test coverage —
match that bar for new contract code)
- `backend/` / `frontend/`: `npx tsc --noEmit` at minimum; there's no
automated test suite yet for either (that's an open issue itself) —
if your change is hard to verify by hand, a smoke test is welcome.
- `backend/`: `npm run typecheck && npm test`
- `frontend/`: `npm test && npm run build`
- repo root: `./scripts/check-source-integrity.sh`

CI runs all of these on every PR.
4. Open a PR describing what changed and, for anything touching the
contracts or backend's Soroban integration, how you verified it (unit
test, or a testnet call with the tx hash).
Expand All @@ -49,7 +51,11 @@ understand the scope of the fix.

## Security

Two known gaps — encryption (placeholder AES/base64) and auth (placeholder
header, no signature verification) — are already tracked as issues, not
secret. If you find a *new* security issue, please don't open a public issue
for it; reach out to a maintainer directly first.
Known, documented gaps (the simulated validator set and the trusted-dealer
keygen) 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)).

Any change to `crypto/orderCipher.ts` must be made identically in the
backend and frontend copies. A test fails if they differ.
89 changes: 49 additions & 40 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ encrypted before they leave the user's browser, batched, and settled
atomically — so no single party (not a validator, not the backend, not a
miner-equivalent) can see or front-run an order before it executes.

**Status: early, working proof-of-concept.** The batching → settlement →
AMM pipeline is real and runs end-to-end against deployed Stellar testnet
contracts. The actual encryption is not — see [Status](#status) before you
assume anything here is safe to put real funds behind.
**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.

[![CI](https://github.com/CiipherProtocol/CipherProtocol/actions/workflows/ci.yml/badge.svg)](https://github.com/CiipherProtocol/CipherProtocol/actions/workflows/ci.yml)

## Architecture

Expand All @@ -32,50 +35,56 @@ Each has its own README with setup/run instructions:
### Data flow

```
User signs in: Freighter signs a never-submittable challenge tx -> session token
User submits a swap
-> frontend encrypts it (currently a placeholder, see Status)
-> POST /api/orders (backend stores it, status=pending)
-> backend batches pending orders on a timer
-> order-vault.create_batch attests to the batch on-chain (order count + content hash)
-> validators would cooperatively decrypt the batch (unimplemented, see Status)
-> browser encrypts it to the validator group key
(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
-> any t valid shares combine to decrypt; each payload is validated
-> settlement-engine.settle_batch executes the swaps atomically against its AMM pool
-> results stored, orders marked settled
-> orders revealed and marked settled (or failed, with a reason)
```

## Status
Full cryptographic design, threat model, and remaining gaps:
[docs/THRESHOLD_ENCRYPTION.md](docs/THRESHOLD_ENCRYPTION.md).

What's real, tested, and running against live Stellar testnet contracts:
## Status

What's real and tested:

- **Threshold encryption** (`backend/src/crypto/`): t-of-n ElGamal KEM over
ristretto255 with AES-256-GCM, Shamir-shared keys, Chaum–Pedersen DLEQ
proofs on every decryption share, and Lagrange combination. The browser
runs a byte-identical copy of the encryption code, and a test enforces it.
- **Validator coordination** (`backend/src/services/validatorService.ts`):
shares are collected per sealed batch, proofs are verified against
registered keys, and up to `n − t` byzantine validators are tolerated.
A bad order fails on its own without blocking the batch.
- **Wallet-signature auth** (`backend/src/services/authService.ts`): a
SEP-10-style challenge, signed in Freighter and verified as ed25519
against the claimed account. No more trusting a header.
- **Contracts** (`contracts/`): `order-vault` and `settlement-engine`,
12 passing tests, deployed to testnet. `settle_batch` executes a real
x*y=k AMM swap with fees, verified against on-chain token balances.
- **Backend** (`backend/`): full submit → batch → settle pipeline,
wired to the real deployed contracts (not stubs) via `@stellar/stellar-sdk`.
- **Frontend** (`frontend/`): wallet connect, swap form, live batch monitor,
talks to the backend.

What's **not** real yet — the important part for anyone evaluating this:

- **Encryption is a placeholder.** `backend/src/services/encryptionService.ts`
and `frontend/src/services/encryption.ts` do plain AES/base64, not
threshold encryption. Anyone who can see the ciphertext and knows the
scheme can decrypt it alone — this defeats the entire MEV-resistance
premise until real threshold ECIES (or similar) is implemented.
- **Auth is a placeholder.** `backend/src/middleware/auth.ts` trusts an
`x-user-address` header with no signature verification — the backend
cannot currently tell if a request is really from the address it claims.
- **Threshold decryption is unimplemented.** `backend/src/services/validatorService.ts`
has no real validator coordination; there is no validator set.
deployed to testnet. `settle_batch` executes a real x*y=k AMM swap with
fees, verified against on-chain token balances.
- **Tests and CI**: 31 backend tests (crypto, end-to-end pipeline, auth),
8 frontend tests, and the contract suites. They run on every PR, together
with a source-integrity check that blocks hidden or obfuscated code.

What's **not** real yet:

- **The validator set is simulated.** All `n` validators run inside the
backend process, and keys come from a trusted dealer. So the operator
could still reconstruct the group key. The cryptography is real, but the
distribution of trust isn't yet. Next steps: DKG and remote validators
(see [the design doc](docs/THRESHOLD_ENCRYPTION.md#what-is-simulated-and-whats-next)).
- **The on-chain vault is an attestation, not a ledger of orders.**
`order-vault.create_batch` records an admin-signed hash + count for a
batch; the backend's database is still the actual order mempool. Real
on-chain order submission (users signing `submit_order` directly) is a
separate, unbuilt path.
- No automated test suite for the backend or frontend yet (contracts have
one — see `contracts/*/src/test.rs`).

None of this is hidden in the code — every placeholder above has a comment
at its definition explaining what it fakes and why.
`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.
- **Schema setup uses `sequelize.sync`** rather than real migrations.

## Deployed contracts (Stellar testnet)

Expand Down
27 changes: 27 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Security policy

Cipher Protocol is a testnet proof-of-concept. Do not use it with real funds.

## Reporting a vulnerability

Please report vulnerabilities privately through GitHub's
**Security → Report a vulnerability** tab on this repository, not in a
public issue. Include steps to reproduce and the affected commit. Expect an
acknowledgement within a few days.

## Scope

In scope: the threshold encryption and share verification
(`backend/src/crypto/`), validator coordination, wallet-signature auth, and
the Soroban contracts.

Known, already-documented limitations, and therefore not new reports: the
validator set is simulated in-process, and keygen uses a trusted dealer. See
[docs/THRESHOLD_ENCRYPTION.md](docs/THRESHOLD_ENCRYPTION.md).

## Supply-chain hygiene

Every PR runs `scripts/check-source-integrity.sh`. It fails on
minified-length lines, code hidden behind long whitespace runs, and dynamic
code evaluation (`eval`, the `Function` constructor, large `atob` blobs).
Crypto dependencies are pinned to exact versions.
12 changes: 12 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,15 @@ TOKEN_CONTRACTS=

BATCH_SIZE=100
BATCH_TIMEOUT_MS=30000

# Simulated validator set: any VALIDATOR_THRESHOLD of VALIDATOR_COUNT shares
# decrypt an order; fewer reveal nothing. Key shares are generated on first
# start and kept in data/validator-keys.json (dev only, gitignored).
VALIDATOR_COUNT=5
VALIDATOR_THRESHOLD=3
# Indices of validators that return invalid shares, to demo proof checking.
BYZANTINE_VALIDATORS=

# HMAC key for wallet-signature auth challenges and session tokens (>= 32
# chars). Generate with: openssl rand -hex 32
AUTH_TOKEN_SECRET=
1 change: 1 addition & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ dist
.env
data/*.sqlite3
*.local
data/validator-keys.json
28 changes: 26 additions & 2 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,40 @@ two contracts (see `contracts/README.md`) — every on-chain call the backend
makes (batch attestations, settlement, fee collection) is signed by it.
**Never commit this value** — `.env` is gitignored for exactly this reason.

On first start the backend generates a simulated 3-of-5 validator key set
in `data/validator-keys.json` (gitignored). Set `AUTH_TOKEN_SECRET` (≥ 32
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.

## API

| Method | Path | Auth | Purpose |
|---|---|---|---|
| GET | `/api/config` | – | Threshold group public key, `t`, `n` |
| POST | `/api/auth/challenge` | – | `{address}` → challenge tx to sign |
| POST | `/api/auth/verify` | – | `{transaction}` (signed XDR) → session token |
| 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/settlement/:batchId` | – | Settlement results |
| POST | `/api/settlement/:batchId/settle` | – | Retry a failed batch (idempotent) |

## Scripts

- `npm run dev` — dev server (`ts-node-dev`, auto-restart)
- `npm run build` / `npm start` — compile to `dist/` and run it
- `npm test` — Jest (no tests written yet — see open issues)
- `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

## Structure

`src/routes` → `src/controllers` → `src/services` → `src/db/models`. The
Soroban integration lives in `src/services/sorobanService.ts`; the batching
loop (timer-based, sweeps pending orders) is in
`src/services/batchingService.ts`. See the root
`src/services/batchingService.ts`. Cryptography is in `src/crypto/`, and
validator coordination is in `src/services/validatorService.ts` and
`validatorNetwork.ts`. See the root
[README](../README.md#status) for which pieces are real versus placeholder.
Loading
Loading