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
7 changes: 7 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,10 @@ jobs:
with:
workspaces: contracts
- run: cargo test --locked

docker:
name: Docker images build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: docker compose build
24 changes: 22 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ 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)

## Try it

**Live demo:** _link coming soon_ (Stellar testnet). No wallet extension
needed: click **Try demo wallet** for a throwaway key in your tab, or connect
Freighter. A banner shows exactly what's on-chain and what's simulated.

**Run the whole system locally**, with 5 validators in separate containers:

```bash
docker compose up --build # then open http://localhost:8080
docker compose stop validator-2 validator-4 # still works: 3 of 5 suffice
```

Hosting on Render, Vercel or Netlify, and enabling on-chain sealing, are
covered in [docs/DEPLOY.md](docs/DEPLOY.md).

## Architecture

```
Expand Down Expand Up @@ -85,9 +101,13 @@ What's real and tested:
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,
- **Deployable demo**: Docker Compose stack (each validator container mounts
only its own key), a Render blueprint, a demo wallet for reviewers without
Freighter, per-IP rate limiting, and an in-app banner that reports which
parts run on-chain and which are simulated.
- **Tests and CI**: 73 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
11 frontend tests, the contract suites, and a Docker image build. They run on every PR, together
with a source-integrity check that blocks hidden or obfuscated code.

What's **not** real yet:
Expand Down
6 changes: 6 additions & 0 deletions backend/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
node_modules
dist
data
.env
*.log
tests
24 changes: 24 additions & 0 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# One image for the API and for validator processes:
# API: node dist/index.js (default)
# validator: node dist/validator/main.js
# bootstrap: node dist/validator/initCluster.js
FROM node:22-bookworm-slim AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev

FROM node:22-bookworm-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /app/package.json ./
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
RUN mkdir -p /app/data /data /cluster && chown -R node:node /app/data /data /cluster
USER node
EXPOSE 5001
HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=5 \
CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||5001)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "dist/index.js"]
5 changes: 4 additions & 1 deletion backend/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import express, { Express, Request, Response } from 'express';
import cors from 'cors';
import { errorHandler } from './middleware/errorHandler';
import * as routes from './routes';
import { config } from './config';
import { rateLimit } from './middleware/rateLimit';

export function createApp(): Express {
const app = express();
if (config.trustProxy) app.set('trust proxy', config.trustProxy);

app.use(cors());
app.use(express.json({ limit: '100kb' }));
Expand All @@ -17,7 +20,7 @@ export function createApp(): Express {
app.use('/api/batches', routes.batches);
app.use('/api/settlement', routes.settlement);
app.use('/api/config', routes.config);
app.use('/api/auth', routes.auth);
app.use('/api/auth', rateLimit({ name: 'sign-in', windowMs: 60_000, max: config.rateLimitAuthPerMin }), routes.auth);

app.use(errorHandler);
return app;
Expand Down
7 changes: 7 additions & 0 deletions backend/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ export const config = {
* a random per-process key is used and sessions reset on restart. */
authTokenSecret: process.env.AUTH_TOKEN_SECRET || '',

/** Number of reverse-proxy hops to trust for the client IP (e.g. 1 on
* Render/Fly/Railway). 0 = use the socket address. */
trustProxy: Number(process.env.TRUST_PROXY) || 0,
/** Per-IP limits for public endpoints (per minute). */
rateLimitAuthPerMin: Number(process.env.RATE_LIMIT_AUTH_PER_MIN) || 30,
rateLimitOrdersPerMin: Number(process.env.RATE_LIMIT_ORDERS_PER_MIN) || 20,

/** Token symbol -> Soroban contract address, until there's a real token
* registry. Populated with testnet addresses for local/dev use. */
tokenContracts: parseTokenContracts(process.env.TOKEN_CONTRACTS),
Expand Down
12 changes: 11 additions & 1 deletion backend/src/controllers/configController.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import { validatorService } from '../services/validatorService';
import { getValidatorNetwork } from '../services/validatorNetwork';
import { config } from '../config';

export const configController = {
/** The validator set's group public key — what clients encrypt orders to. */
getPublicConfig() {
return validatorService.getPublicKeyInfo();
return {
...validatorService.getPublicKeyInfo(),
/** Where batches are sealed: the real order-vault on-chain, or the in-memory dev ledger. */
sealing: config.orderVaultContract ? 'onchain' : 'dev-ledger',
order_vault_contract: config.orderVaultContract || null,
/** 'simulated' = orders are decrypted and validated but no tokens move (e.g. public demo). */
settlement: config.settlementEngineContract ? 'onchain' : 'simulated',
validator_mode: getValidatorNetwork().mode,
};
},
};
8 changes: 7 additions & 1 deletion backend/src/controllers/settlementController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { sorobanService } from '../services/sorobanService';
import { validatorService } from '../services/validatorService';
import { AppError, NotFoundError } from '../utils/errors';
import logger from '../utils/logger';
import { config } from '../config';

export const settlementController = {
async getSettlementResults(batchId: string) {
Expand Down Expand Up @@ -47,7 +48,12 @@ export const settlementController = {
await Promise.all([
...decrypted.map((d, i) =>
Order.update(
{ ...d.order, amount_out: results[i]?.amount_out ?? null, status: 'settled' },
{
...d.order,
// Simulated settlement moves no tokens, so there is no real amount_out to record.
amount_out: config.settlementEngineContract ? (results[i]?.amount_out ?? null) : null,
status: 'settled',
},
{ where: { id: d.id } }
)
),
Expand Down
36 changes: 36 additions & 0 deletions backend/src/middleware/rateLimit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Request, Response, NextFunction } from 'express';

/**
* Small fixed-window rate limiter (in-memory, per process). Enough to keep
* a public demo from being trivially flooded. A multi-instance deployment
* would move the counters to a shared store such as Redis.
*/
export function rateLimit(opts: { windowMs: number; max: number; key?: (req: Request) => string; name: string }) {
const hits = new Map<string, { count: number; resetAt: number }>();
const keyOf = opts.key ?? ((req: Request) => req.ip ?? 'unknown');

const sweep = setInterval(() => {
const now = Date.now();
for (const [k, v] of hits) if (v.resetAt <= now) hits.delete(k);
}, opts.windowMs);
sweep.unref();

return (req: Request, res: Response, next: NextFunction) => {
const now = Date.now();
const k = keyOf(req);
let entry = hits.get(k);
if (!entry || entry.resetAt <= now) {
entry = { count: 0, resetAt: now + opts.windowMs };
hits.set(k, entry);
}
entry.count++;
res.setHeader('RateLimit-Limit', String(opts.max));
res.setHeader('RateLimit-Remaining', String(Math.max(0, opts.max - entry.count)));
if (entry.count > opts.max) {
res.setHeader('Retry-After', String(Math.ceil((entry.resetAt - now) / 1000)));
res.status(429).json({ error: `Too many ${opts.name} requests; try again shortly` });
return;
}
next();
};
}
10 changes: 10 additions & 0 deletions backend/src/routes/orders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,23 @@ import { Router, Request, Response, NextFunction } from 'express';
import { orderController } from '../controllers/orderController';
import { validateAuth } from '../middleware/auth';
import { validateOrderInput } from '../middleware/validation';
import { rateLimit } from '../middleware/rateLimit';
import { config } from '../config';
import { SubmitOrderBody } from '../types/order';

const router = Router();

const submitLimit = rateLimit({
name: 'order',
windowMs: 60_000,
max: config.rateLimitOrdersPerMin,
key: (req) => `${req.ip}|${req.user?.address ?? ''}`,
});

router.post(
'/',
validateAuth,
submitLimit,
validateOrderInput,
async (req: Request<unknown, unknown, SubmitOrderBody>, res: Response, next: NextFunction) => {
try {
Expand Down
60 changes: 60 additions & 0 deletions backend/src/validator/initCluster.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* One-shot cluster bootstrap for Docker Compose (the `validator-init`
* service). Writes into the shared /cluster volume:
*
* validator-<i>/identity.json that validator's identity key
* validator-<i>/validator.env its API token, peer keys, sealing config
* coordinator/cluster.json what the backend needs to reach them
*
* Each container then mounts only its own subdirectory, so a validator
* never sees another validator's files. Idempotent: existing identities
* and tokens are kept, so restarts don't re-key anything.
*
* NOTE: this bootstrap is run by one operator, so it is a single-operator
* demo. Real independent validators generate their own identity and
* exchange only public keys.
*/
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { loadOrCreateIdentity } from './main';
import { ClusterFile } from './remoteValidator';

const root = process.env.CLUSTER_DIR || '/cluster';
const count = Number(process.env.VALIDATOR_COUNT) || 5;
const urlFor = (i: number) => (process.env.VALIDATOR_URL_TEMPLATE || 'http://validator-{i}:7700').replace('{i}', String(i));

const clusterPath = path.join(root, 'coordinator', 'cluster.json');
const previous: ClusterFile | null = fs.existsSync(clusterPath) ? JSON.parse(fs.readFileSync(clusterPath, 'utf8')) : null;

const members = Array.from({ length: count }, (_, k) => {
const index = k + 1;
const dir = path.join(root, `validator-${index}`);
const identity = loadOrCreateIdentity(dir);
const apiToken = previous?.validators.find((v) => v.index === index)?.apiToken ?? crypto.randomBytes(32).toString('hex');
return { index, dir, identity, apiToken };
});

const peerKeys = members.map((m) => `${m.index}:${m.identity.publicKey}`).join(',');
const sealing = 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'];

for (const m of members) {
const env = [`VALIDATOR_API_TOKEN=${m.apiToken}`, `VALIDATOR_PEER_KEYS=${peerKeys}`, ...sealing].join('\n') + '\n';
fs.writeFileSync(path.join(m.dir, 'validator.env'), env, { mode: 0o600 });
}

const cluster: ClusterFile = {
validators: members.map((m) => ({ index: m.index, url: urlFor(m.index), identityKey: m.identity.publicKey, apiToken: m.apiToken })),
};
fs.mkdirSync(path.dirname(clusterPath), { recursive: true });
fs.writeFileSync(clusterPath, JSON.stringify(cluster, null, 2), { mode: 0o600 });

console.log(
`cluster ready: ${count} validators, sealing check ${process.env.ORDER_VAULT_CONTRACT ? 'ON (on-chain)' : 'OFF (no ORDER_VAULT_CONTRACT)'}`
);
51 changes: 51 additions & 0 deletions backend/tests/demoReadiness.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import express from 'express';
import request from 'supertest';
import { rateLimit } from '../src/middleware/rateLimit';
import { createApp } from '../src/app';
import { sequelize } from '../src/db';
import { Order } from '../src/db/models/Order';
import { validatorService } from '../src/services/validatorService';
import { batchingService } from '../src/services/batchingService';
import { newUser, submitSwap } from './helpers';

describe('rate limiting', () => {
const app = express();
app.set('trust proxy', 1);
app.get('/x', rateLimit({ name: 'test', windowMs: 60_000, max: 3 }), (_req, res) => {
res.json({ ok: true });
});

it('allows up to the limit per client, then answers 429 with Retry-After', async () => {
const ip = { 'x-forwarded-for': '203.0.113.7' };
for (let i = 0; i < 3; i++) expect((await request(app).get('/x').set(ip)).status).toBe(200);
const blocked = await request(app).get('/x').set(ip);
expect(blocked.status).toBe(429);
expect(Number(blocked.headers['retry-after'])).toBeGreaterThan(0);
// A different client is unaffected.
expect((await request(app).get('/x').set({ 'x-forwarded-for': '203.0.113.8' })).status).toBe(200);
});
});

describe('demo mode reporting', () => {
const app = createApp();
beforeAll(async () => {
await sequelize.sync({ force: true });
await validatorService.syncValidatorRegistry();
});
afterAll(() => sequelize.close());

it('says how sealing and settlement actually run', async () => {
const { body } = await request(app).get('/api/config');
expect(body).toMatchObject({ sealing: 'dev-ledger', settlement: 'simulated', validator_mode: 'local' });
});

it('simulated settlement reveals the order but records no fake amount received', async () => {
const res = await submitSwap(app, newUser());
await batchingService.runOnce();
const order = await Order.findByPk(res.body.order.id);
expect(order!.status).toBe('settled');
expect(order!.amount_in).toBe('15000000');
expect(order!.amount_out).toBeNull();
});
});
2 changes: 2 additions & 0 deletions backend/tests/setupEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ process.env.VALIDATOR_THRESHOLD = '3';
process.env.ORDER_VAULT_CONTRACT = '';
process.env.SETTLEMENT_ENGINE_CONTRACT = '';
process.env.AUTH_TOKEN_SECRET = 'test-secret-test-secret-test-secret';
process.env.RATE_LIMIT_AUTH_PER_MIN = '100000';
process.env.RATE_LIMIT_ORDERS_PER_MIN = '100000';
Loading
Loading