QuantLayer Architecture

Design document, published from the repository at docs/ARCHITECTURE.md.

Status: foundation stage. This document describes the engineering structure of the repository. Protocol semantics belong in PROTOCOL.md, cryptographic design in CRYPTOGRAPHY.md and adversary assumptions in THREAT_MODEL.md (to be written). Significant decisions are recorded in docs/adr/.

1. Goals that shape the structure

  1. Auditability. Security-relevant code must be small, isolated and easy to locate. Cryptography lives behind interfaces in a few known places.
  2. Replaceable cryptography. Algorithms (classical, post-quantum, ZK proving systems) will change. Domain logic must not know which library is in use.
  3. Explicit boundaries. Every package has one responsibility and a public API declared through package.json#exports. Dependencies flow one way.
  4. 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

PathKindResponsibility
packages/sharedlibraryError model (QuantLayerError, ErrorCode), branded types, assertNever, log levels. Zero dependencies.
packages/configlibraryZod-validated environment loading (parseEnv) and reusable schema parts.
packages/runtimelibraryNode-only. Structured logger, health server, service lifecycle (runService).
packages/cryptolibraryAlgorithm registry and policy, versioned key lifecycle, SignatureProvider/KeyManager ports. No implementations.
packages/corelibraryProtocol kernel: error taxonomy, state machines, aggregates, domain events, canonical encoding, versioned codecs, verification results, NetworkAdapter.
packages/identitylibrarydid:quantlayer, identity lifecycle, versioned keys, account links, guardian recovery, replay-protected authorization, IdentityService.
packages/credentialslibraryCredential v1 model plus quantlayer.credential/2: selective disclosure, subject commitments, status lists, holder presentations, verifier, issuer.
packages/financiallibraryFinancial credential types and schemas, signed data-source attestations, financial issuer.
packages/privacylibraryCanonical field encoding, domain separation, Poseidon commitments, nullifiers, Merkle membership, membership circuit statement (mirrors circuits/).
packages/zk-enginelibraryCircuit registry and public-input layouts, statements, witness construction, context/scope binding, proof lifecycle, ports, on-chain receipt check.
packages/zk-noirlibraryNoir 1.0 + Barretenberg 6 (UltraHonk) engine: artifact integrity, witness generation, proving, verification, EVM calldata (@quantlayer-protocol/sdk/zk).
packages/pqc-enginelibraryQuantLayer Quantum for TS: PQCKeyProvider/PQCSignatureProvider/PQCVerificationProvider/HybridAuthorizationProvider/PQCKeyManager over the Rust module.
packages/authorizationlibraryHybrid authorization engine (classical, PQC, hybrid, credential, ZK policies; versioned; replay-safe) and the access-rule evaluator.
packages/authorization-pqclibraryRust (QuantLayer Quantum) adapters for the engine: PQC verifier, post-quantum and hybrid request signers.
packages/evmlibraryEIP-55, CAIP-10 eip155, EIP-712 hashing, signer recovery, EIP-712/EIP-1271 ownership verifier.
packages/networkslibraryMulti-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-classicallibraryAudited @noble adapters: SHA-256, Keccak-256, Poseidon-BN254, verify-only Ed25519/ES256K, secp256k1 recovery, CSPRNG.
packages/sdklibraryThe only public package. Curated, browser-safe re-export surface.
apps/apideployableQuantLayer backend (NestJS on Fastify, PostgreSQL/Prisma, Redis/BullMQ): HTTP API plus worker and indexer roles. See docs/backend/BACKEND.md.
apps/webdeployableNext.js web application.
contracts/FoundrySolidity on-chain layer: identity, key, credential and nullifier registries, QuantLayerProofVerifier (+ generated UltraHonk verifiers), QuantLayerPqcAttestationVerifier, QuantLayerAuthorizationManager. See docs/contracts/ONCHAIN_PROTOCOL.md.
circuits/ZKnoir/: production Noir circuits, artifacts, vectors. Circom templates (FEAT-05 reference for the primitives).
rust/Cargoquantlayer-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/opsDockerfiles, 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:

RuleEnforced by
Library → library edges follow the allowed layer mapscripts/check-dependency-layers.mjs
Nothing depends on a deployablescripts/check-dependency-layers.mjs
Internal deps use workspace:*scripts/check-dependency-layers.mjs
No cyclic package graphTurborepo (refuses to run) + layer map
No circular imports between filesdependency-cruiser no-circular
No relative imports into another package's sourcesdependency-cruiser
Production code never imports test filesdependency-cruiser
SDK and domain packages cannot use Node APIstypes: [] 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 by tsc to dist/ 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, clean scripts, 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.example files 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 }).
  • ErrorCode is transport-agnostic. Only apps/api maps 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 (createLogger in @quantlayer-protocol/runtime, pino): JSON lines, ISO timestamps, service field, textual level, default redaction of credentials/tokens/keys/auth headers. Errors are logged under err.
  • The API binds the logger into NestJS via nestjs-pino, adds per-request logs and propagates/mints x-request-id.
  • Workers use runService: validated env → logger → health endpoints (/healthz/live, /healthz/ready) → start → graceful SIGTERM/SIGINT shutdown within a deadline → exit code. Startup and configuration failures are logged as fatal and 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-pqc via the Node-API addon rust/quantlayer-pqc-node and are adapted in packages/pqc-engine;
  • proving lives in packages/zk-engine / packages/zk-noir and runs server-side only in the backend's worker role (sealed witnesses), with circuits in circuits/;
  • 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.

AggregateStatesPackage
Identitypending → active ⇄ suspended → deactivatedidentity
Credentialpending → active ⇄ suspended → revoked | expiredcredentials
Proof jobrequested → generating → generated → verified | rejected; failed ↺zk-engine
Keypending → active → retired → revokedcrypto

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).

PortPackageImplemented by (future)
IdentityProvideridentityDID method / registry adapters
IdentityRepositoryidentitydatabase adapter with account index
ChallengeStoreidentityRedis/DB with atomic consume
AccountOwnershipVerifieridentityevm (EIP-712 / EIP-1271)
CredentialIssuercredentialscreateCredentialIssuer (domain)
CredentialVerifiercredentialscreateCredentialVerifier (domain)
ProofProverzk-enginezk-noir (createZkEngine)
ProofVerifierzk-enginecreateProofVerifier (domain)
ProofSystemBackendzk-enginezk-noir (UltraHonk-BN254)
SignatureProvidercryptoKMS/HSM, wallets, quantlayer-crypto-wasm
SignatureVerifiercryptocrypto-classical, quantlayer-crypto-wasm
RandomSourcecryptocrypto-classical (CSPRNG)
FieldHashercryptocrypto-classical (Poseidon-BN254)
NullifierStoreprivacyDB with unique (scope, nullifier)
KeyManagercryptoKMS/HSM adapters
NetworkAdaptercorepackages/evm adapters
EventPublishercoreAPI / 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).