Status: foundation stage. This document describes the engineering structure of the repository. Protocol semantics belong in
PROTOCOL.md, cryptographic design inCRYPTOGRAPHY.mdand adversary assumptions inTHREAT_MODEL.md(to be written). Significant decisions are recorded indocs/adr/.
1. Goals that shape the structure
- Auditability. Security-relevant code must be small, isolated and easy to locate. Cryptography lives behind interfaces in a few known places.
- Replaceable cryptography. Algorithms (classical, post-quantum, ZK proving systems) will change. Domain logic must not know which library is in use.
- Explicit boundaries. Every package has one responsibility and a public
API declared through
package.json#exports. Dependencies flow one way. - Fail fast, fail loudly, leak nothing. Invalid configuration stops a process at startup; errors are structured; secrets never reach logs or responses.
2. Repository map
| Path | Kind | Responsibility |
|---|---|---|
packages/shared | library | Error model (QuantLayerError, ErrorCode), branded types, assertNever, log levels. Zero dependencies. |
packages/config | library | Zod-validated environment loading (parseEnv) and reusable schema parts. |
packages/runtime | library | Node-only. Structured logger, health server, service lifecycle (runService). |
packages/crypto | library | Algorithm registry and policy, versioned key lifecycle, SignatureProvider/KeyManager ports. No implementations. |
packages/core | library | Protocol kernel: error taxonomy, state machines, aggregates, domain events, canonical encoding, versioned codecs, verification results, NetworkAdapter. |
packages/identity | library | did:quantlayer, identity lifecycle, versioned keys, account links, guardian recovery, replay-protected authorization, IdentityService. |
packages/credentials | library | Credential v1 model plus quantlayer.credential/2: selective disclosure, subject commitments, status lists, holder presentations, verifier, issuer. |
packages/financial | library | Financial credential types and schemas, signed data-source attestations, financial issuer. |
packages/privacy | library | Canonical field encoding, domain separation, Poseidon commitments, nullifiers, Merkle membership, membership circuit statement (mirrors circuits/). |
packages/zk-engine | library | Circuit registry and public-input layouts, statements, witness construction, context/scope binding, proof lifecycle, ports, on-chain receipt check. |
packages/zk-noir | library | Noir 1.0 + Barretenberg 6 (UltraHonk) engine: artifact integrity, witness generation, proving, verification, EVM calldata (@quantlayer-protocol/sdk/zk). |
packages/pqc-engine | library | QuantLayer Quantum for TS: PQCKeyProvider/PQCSignatureProvider/PQCVerificationProvider/HybridAuthorizationProvider/PQCKeyManager over the Rust module. |
packages/authorization | library | Hybrid authorization engine (classical, PQC, hybrid, credential, ZK policies; versioned; replay-safe) and the access-rule evaluator. |
packages/authorization-pqc | library | Rust (QuantLayer Quantum) adapters for the engine: PQC verifier, post-quantum and hybrid request signers. |
packages/evm | library | EIP-55, CAIP-10 eip155, EIP-712 hashing, signer recovery, EIP-712/EIP-1271 ownership verifier. |
packages/networks | library | Multi-network layer (Viem): Arbitrum and Robinhood Chain config, discovery, contract registry and version fingerprints, tx submission/confirmation, event monitoring with reorgs, cross-chain credential verification. See docs/networks/. |
packages/crypto-classical | library | Audited @noble adapters: SHA-256, Keccak-256, Poseidon-BN254, verify-only Ed25519/ES256K, secp256k1 recovery, CSPRNG. |
packages/sdk | library | The only public package. Curated, browser-safe re-export surface. |
apps/api | deployable | QuantLayer backend (NestJS on Fastify, PostgreSQL/Prisma, Redis/BullMQ): HTTP API plus worker and indexer roles. See docs/backend/BACKEND.md. |
apps/web | deployable | Next.js web application. |
contracts/ | Foundry | Solidity on-chain layer: identity, key, credential and nullifier registries, QuantLayerProofVerifier (+ generated UltraHonk verifiers), QuantLayerPqcAttestationVerifier, QuantLayerAuthorizationManager. See docs/contracts/ONCHAIN_PROTOCOL.md. |
circuits/ | ZK | noir/: production Noir circuits, artifacts, vectors. Circom templates (FEAT-05 reference for the primitives). |
rust/ | Cargo | quantlayer-pqc (QuantLayer Quantum: ML-DSA, SLH-DSA, ML-KEM via libcrux/fips205), quantlayer-pqc-node (Node-API), quantlayer-pqc-bench, quantlayer-crypto-wasm (placeholder). |
infrastructure/ | ops | Dockerfiles, compose, monitoring and deployment notes. |
packages/database and apps/docs from the original plan are intentionally not
created yet — an empty package is an abstraction without a responsibility. They
will be added together with their first real content (schema / docs site).
3. Dependency rules
shared (no deps: QuantLayerError, ErrorCode, Brand)
▲
┌────────┬────┴─────┐
config runtime core (protocol kernel)
▲
┌──────────┼──────────┐
privacy crypto │
▲ │
┌──────────┬───────┼──────────┴───┐
identity zk-engine pqc-engine crypto-classical (@noble, ADR-0009)
(+privacy)
▲
zk-noir (noir_js + bb.js, ADR-0013)
▲ ▲
credentials ◄──────── evm ──────────────┘ (evm adapts identity's ownership port)
▲ ▲
│ authorization
financial
sdk → curated facade over the libraries above (browser-safe)
apps/* and services/* → may depend on any library, never on each other.Enforced mechanically:
| Rule | Enforced by |
|---|---|
| Library → library edges follow the allowed layer map | scripts/check-dependency-layers.mjs |
| Nothing depends on a deployable | scripts/check-dependency-layers.mjs |
Internal deps use workspace:* | scripts/check-dependency-layers.mjs |
| No cyclic package graph | Turborepo (refuses to run) + layer map |
| No circular imports between files | dependency-cruiser no-circular |
| No relative imports into another package's sources | dependency-cruiser |
| Production code never imports test files | dependency-cruiser |
| SDK and domain packages cannot use Node APIs | types: [] in tsconfig.base.json; only runtime and deployables opt into @types/node |
Run all of them with pnpm check:deps.
4. Package contract
Each library:
- is ESM (
"type": "module"), compiled bytsctodist/with declarations and source maps; - exposes one entry point via
exports["."]; deep imports are impossible; - declares only the dependencies it imports;
- colocates tests as
src/**/*.test.ts(excluded from the build); - has
build,typecheck,lint,test,cleanscripts, orchestrated and cached by Turborepo (dependsOn: ["^build"]).
Third-party versions are declared once in the catalog: of
pnpm-workspace.yaml.
5. Configuration
Every deployable defines its own Zod schema by extending baseEnvSchema
(NODE_ENV, LOG_LEVEL) and loads it once at startup with parseEnv. There is
no global configuration object.
- Validation reports all problems at once and names variables, never values.
- Non-secret settings may have development defaults. Secrets never have
defaults and are never committed;
.env.examplefiles document variables. - Browser-exposed variables (
NEXT_PUBLIC_*) are inlined at build time and are therefore public by definition.
6. Errors
- Deliberate failures throw
QuantLayerError(code, message, { details, cause }). ErrorCodeis transport-agnostic. Onlyapps/apimaps codes to HTTP status (apps/api/src/errors/error-mapping.ts, exhaustive by type).- A global Nest filter returns a single error shape:
{ "error": { "code", "message", "requestId" } }. - 5xx responses never expose the underlying message; the full error is logged
and correlated through
requestId.
7. Logging and process lifecycle
- One logger factory (
createLoggerin@quantlayer-protocol/runtime, pino): JSON lines, ISO timestamps,servicefield, textuallevel, default redaction of credentials/tokens/keys/auth headers. Errors are logged undererr. - The API binds the logger into NestJS via
nestjs-pino, adds per-request logs and propagates/mintsx-request-id. - Workers use
runService: validated env → logger → health endpoints (/healthz/live,/healthz/ready) →start→ gracefulSIGTERM/SIGINTshutdown within a deadline → exit code. Startup and configuration failures are logged asfataland exit non-zero.
8. Cryptography boundary
No cryptography is implemented in the foundation stage (see ADR-0007). When it is:
- interfaces stay in
packages/crypto; - post-quantum implementations come from
rust/quantlayer-pqcvia the Node-API addonrust/quantlayer-pqc-nodeand are adapted inpackages/pqc-engine; - proving lives in
packages/zk-engine/packages/zk-noirand runs server-side only in the backend'sworkerrole (sealed witnesses), with circuits incircuits/; - no other package may import a cryptographic library directly.
9. Protocol core domain model
Introduced in FEAT-02; rationale in ADR-0008.
Functional aggregates. Identities, credentials, proof jobs and key
versions are immutable values. Commands are pure functions
(state, input, context) → { state, events }; time (Clock) and identifiers
(IdGenerator) are injected through DomainContext. Domain code performs no
I/O and imports no framework, database, UI or RPC library.
Lifecycles. Each aggregate's lifecycle is a defineStateMachine table
(validated at load: no unknown states, self-loops or unreachable states).
Commands check the transition before any business guard, so an illegal move
always reports INVALID_TRANSITION. Tests enumerate every (state, event) pair.
| Aggregate | States | Package |
|---|---|---|
| Identity | pending → active ⇄ suspended → deactivated | identity |
| Credential | pending → active ⇄ suspended → revoked | expired | credentials |
| Proof job | requested → generating → generated → verified | rejected; failed ↺ | zk-engine |
| Key | pending → active → retired → revoked | crypto |
Errors. ProtocolError extends QuantLayerError with a fine-grained
ProtocolErrorReason (append-only), each mapped to one coarse ErrorCode.
The same reasons label failed checks in a VerificationResult.
Verification. Verifiers return VerificationResult: every check is
reported (passed/failed/skipped), evaluation stops at the first failure,
and the result fails closed if nothing passed.
Canonical encoding and signing. Anything signed is encoded as QuantLayer
canonical JSON (RFC 8785 restricted to safe integers, plain objects, no
undefined). Signature input is "QUANTLAYER-SIG-V1:" + purpose + "\n" + canonical,
giving domain separation between document kinds. Credentials sign only their
immutable document; lifecycle state is established through status resolution.
Versioned serialization. defineCodec wraps payloads in
{ type, version, payload }, validates with Zod, upgrades old versions
through registered migrations, and refuses to emit what it cannot read.
Binary values are base64url (strict, canonical).
Ports (dependency inversion).
| Port | Package | Implemented by (future) |
|---|---|---|
IdentityProvider | identity | DID method / registry adapters |
IdentityRepository | identity | database adapter with account index |
ChallengeStore | identity | Redis/DB with atomic consume |
AccountOwnershipVerifier | identity | evm (EIP-712 / EIP-1271) |
CredentialIssuer | credentials | createCredentialIssuer (domain) |
CredentialVerifier | credentials | createCredentialVerifier (domain) |
ProofProver | zk-engine | zk-noir (createZkEngine) |
ProofVerifier | zk-engine | createProofVerifier (domain) |
ProofSystemBackend | zk-engine | zk-noir (UltraHonk-BN254) |
SignatureProvider | crypto | KMS/HSM, wallets, quantlayer-crypto-wasm |
SignatureVerifier | crypto | crypto-classical, quantlayer-crypto-wasm |
RandomSource | crypto | crypto-classical (CSPRNG) |
FieldHasher | crypto | crypto-classical (Poseidon-BN254) |
NullifierStore | privacy | DB with unique (scope, nullifier) |
KeyManager | crypto | KMS/HSM adapters |
NetworkAdapter | core | packages/evm adapters |
EventPublisher | core | API / worker infrastructure |
Hybrid authorization (FEAT-08). See AUTHORIZATION.md and ADR-0015.
QuantLayer Quantum (FEAT-07). See QUANTLAYER_QUANTUM.md, benchmarks and ADR-0014.
ZK engine (FEAT-06). See ZK_ENGINE.md, benchmarks and ADR-0013.
Privacy primitives (FEAT-05). See the security notes, ADR-0012 and circuits.
Financial credentials (FEAT-04). See the protocol specification and ADR-0011.
Identity (FEAT-03). See ADR-0010 and the identity security design.
10. Toolchain
Node.js 26 LTS · pnpm 12 · Turborepo 2 · TypeScript 6.0 (strict) · ESLint 10 +
typescript-eslint (strict, type-checked) · Prettier · Vitest · NestJS 12 ·
Next.js 16 · Foundry · Rust 2024 · Docker. CI runs every check on each pull request
(.github/workflows/ci.yml).