QuantLayer ZK engine

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

Status: implemented (FEAT-06). Decision record: ADR-0013. Benchmarks: BENCHMARKS.md. Primitives: privacy SECURITY_NOTES.

1. Stack and compatibility verification

ComponentVersion (exact pin)Role
Noir1.0.0 (@noir-lang/noir_wasm, noir_js)Circuit language, compiler (WASM), witness execution
Barretenberg6.0.0 (@aztec-foundation/bb.js)UltraHonk prover/verifier, verification keys, Solidity verifiers
noir-lang/poseidonv0.4.0 (Nargo git tag)circomlib-compatible Poseidon over BN254
solc0.8.28Contracts (same as contracts/foundry.toml)

The following was checked on 2026-11-13, before any implementation:

  • Pairing. Noir 1.0.0 (released 2026-10-29) pairs with Barretenberg 6.0.0 (2026-10-22). From version 6, bb.js is published as @aztec-foundation/bb.js; @aztec/bb.js stops at 5.3.0. bb 6 changed the proof layout (full-width Fiat–Shamir challenges): bb 5 proofs don't verify under bb 6 verifiers, and the reverse also fails. Every bb version before 5.0.0 was reported to contain an unsound component, which is why all versions are pinned exactly.
  • Proof format. The evm target is UltraHonk with zero-knowledge and a Keccak-256 transcript. It produced 8,768-byte proofs for every QuantLayer circuit (2^16 gates), plus bytes32 public inputs. bb appends 8 pairing-point limbs internally, so the generated verifier's NUMBER_OF_PUBLIC_INPUTS is the circuit's count plus 8.
  • Verifier generation and EVM. UltraHonkBackend.getSolidityVerifier(vk) emits a self-contained HonkVerifier with two externally linked libraries (RelationsLib, ZKTranscriptLib). It compiles with solc 0.8.28 and is about 18 KB, under EIP-170. Real proofs verified on a Cancun EVM (ethereumjs), and tampered proofs and public inputs reverted.
  • Hash compatibility. Noir's poseidon::bn254::hash_2([1, 2]) equals the circomlib value 0x115cc0f5…189a, so the FEAT-05 suite quantlayer.privacy.poseidon-bn254.v1 is used unchanged in-circuit. std::hash::poseidon was removed from the Noir 1.0 standard library.
  • Backends. bb.js bundles native bb builds for macOS and Linux (x64, arm64). NativeUnixSocket (a child process) and WASM work. Forcing NativeSharedMemory crashed (SIGABRT) on macOS arm64, so the engine never selects it.

2. Architecture

packages/privacy     FieldElement, Poseidon domains, identity, nullifier, Merkle, ZkCredential
packages/zk-engine   circuits registry · statements · witness construction · context/scope
                     binding · ProofProver/ProofVerifier/ProofSystemBackend ports · receipt check
packages/zk-noir     artifacts (load + integrity) · createZkEngine (noir_js + bb.js) · EVM calldata
circuits/noir        Nargo workspace: lib `quantlayer` + 6 circuits · artifacts/ · vectors/
contracts/src/zk     QuantLayerProofVerifier · UltraHonkVerifierAdapter · QuantLayerNullifierRegistry · QuantLayerZk
contracts/src/verifiers   generated UltraHonk verifiers (one per circuit)

zk-engine is framework-neutral and browser-safe. zk-noir is the only package that knows Noir or Barretenberg, and the SDK exposes it on the opt-in entry point @quantlayer-protocol/sdk/zk.

3. Circuits

All circuits use depth-20 trees (about 1M leaves) and the shared library circuits/noir/quantlayer, which mirrors packages/privacy exactly. Public inputs always start with [context, root]. Returned values come last.

Id (circuits/noir/…)Public inputs (circuit order)Private witnessStatement
membership (membership)context, root, scope → nullifieridentity, pathMember of identity set root; nullifier for scope
credential-ownershipcontext, root, issuer, credentialTypeidentity, credential, pathHolds a credentialType credential in issuer's tree
credential-validitycontext, root, issuer, credentialType, nowidentity, credential, pathOwnership, and issuedAt ≤ now < expiresAt
balance-thresholdcontext, root, issuer, credentialType, now, thresholdidentity, credential, pathValid credential with hidden attribute ≥ threshold
nullifier-uniquenesscontext, root, issuer, credentialType, scope → nullifieridentity, credential, pathOwnership; one-time nullifier per scope
eligibilitycontext, root, issuer, credentialType, now, threshold, scope → nullifieridentity, credential, pathValid, attribute ≥ threshold, once per scope

Credential model. An issuer commits each credential as a leaf of its credential tree:

leaf = Poseidon(tag("quantlayer.zk-credential.v1"), issuer, holder, credentialType,
                attribute, issuedAt, expiresAt, salt)

Here holder is the holder's identity commitment. Only the issuer's authority account may publish the root, in QuantLayerCredentialRegistry. Authenticity therefore comes from that on-chain write, not from an in-circuit signature; Semaphore groups and iden3 claim trees use the same pattern. attribute is u128 and timestamps are u64 Unix seconds, all range-checked by Noir's typed inputs.

Revocation. The issuer removes the leaf (MerkleTree.remove) and publishes the new root. The registry accepts a superseded root only for gracePeriod seconds, and a published root can never be republished.

Rules the circuits enforce themselves (tested with the TypeScript pre-checks bypassed):

  • the leaf is recomputed from the secrets, so a forged or edited credential fails;
  • the path index is decomposed into exactly 20 bits, so leaf positions can't alias;
  • the validity window;
  • the threshold;
  • context and scope must be non-zero.

4. Circuit infrastructure

ConcernWhere
Source managementcircuits/noir (Nargo workspace). Dependencies pinned by tag. nargo test --workspace runs the Noir known-answer and failure tests (CI job zk).
Input schemasCIRCUITS in zk-engine/src/circuits.ts (public inputs, outputs, statement). Noir ABI types (Field, u64, u128, structs). parseStatement accepts only 0x + 64-hex values, in exactly the circuit's names.
Witness constructionbuildCircuitInputs checks every relation first (holder, issuer, type, path, root, window, threshold) and returns the exact Noir input map. Errors never contain values.
Witness generationengine.generateWitness: noir_js execution. Circuit outputs must equal the TypeScript values, or the call fails with INVARIANT_VIOLATION.
Compilationpnpm --filter @quantlayer-protocol/zk-noir circuits:build (Noir WASM compiler with bb.js) produces artifacts, verification keys and Solidity verifiers.
Artifact versioningquantlayer.zk-artifact/1 per circuit: toolchain, ABI, bytecode and its SHA-256, VK and its SHA-256, VK_HASH, log₂ size, verifier path and SHA-256. manifest.json lists them. loadArtifact rejects any mismatch. The on-chain circuit id is keccak256("quantlayer.zk.circuit/<id>/v<version>").
Reproducibilitycircuits:check rebuilds and fails on any byte difference (CI job zk). Artifacts are about 1.5 MB each, mostly ACIR (circomlib Poseidon isn't a bb black box).
Public inputsCIRCUITS[id].publicInputs, orderedPublicInputs. The same indices are configured in QuantLayerProofVerifier.registerCircuit.

5. TypeScript proving engine

import { createZkEngine } from '@quantlayer-protocol/sdk/zk';
const engine = await createZkEngine({ artifacts, suite, sha256, backend: 'auto' });
const proof = await engine.prove(request, { identity, credential, path }); // ProofProver
await engine.verify(proof); // off-chain cryptographic check only
await engine.destroy();
  • Validation. loadArtifact checks the schema, toolchain, hashes, and that the ABI matches the definition. prove checks the request statement and the witness relations. verify fails closed: it returns false for an empty, unaligned (not 32-byte) or oversized proof (32 KiB or more), a non-canonical input, extra or missing inputs, another circuit's key, or another proof system.
  • Errors.
    • WITNESS_INVALID, EXPIRED and NOT_YET_VALID mean the inputs don't satisfy the circuit, whether caught by the pre-checks or by the circuit's own assertions.
    • PROVING_FAILED means the backend failed.
    • ARTIFACT_INVALID means an artifact failed its checks.
    • INVARIANT_VIOLATION means TypeScript and the circuit disagree; this is drift, not user error.
    • Underlying error messages and causes are dropped, because Noir and ABI errors can echo input values.
  • Serialization. Proof uses the quantlayer.proof codec (proof as base64url, public inputs as named 0x + 64-hex values, size-capped at 64 KiB). toVerifyProofArguments and encodeVerifyProofCall produce the exact verifyProof calldata.
  • Backends.
    • auto (the default) uses native bb when available, otherwise WASM.
    • native uses NativeUnixSocket.
    • wasm forces WASM, as used in browsers.
    • The KZG reference string is cached in ~/.bb-crs (configure with crsPath).

6. On-chain verification

QuantLayerProofVerifier.verifyProof(circuitId, proof, publicInputs, ctx) checks the following, in order, and reverts on the first failure:

#CheckRevert
1The circuit is registered and enabled; the public-input count matchesUnknownCircuit, PublicInputCountMismatch
2Every public input is below p (the BN254 field)PublicInputOutOfField(i)
3context equals QuantLayerZk.computeContext(block.chainid, this, msg.sender, appId, circuitId, nonce)ContextMismatch
4The proof system is enabled (versioned adapters, see docs/contracts/ONCHAIN_PROTOCOL.md)ProofSystemDisabled
5root is valid for ctx.rootId in QuantLayerCredentialRegistry (active issuer; current, or within grace; not revoked)UnknownRoot
6Credential circuits: issuer == ctx.rootIdIssuerMismatch
7now ≤ block.timestamp and block.timestamp − now ≤ maxProofAgeProofFromFuture, StaleProof
8Nullifier circuits: scope == QuantLayerZk.computeScope(chainid, this, appId, action)ScopeMismatch
9The proof verifies (adapter → generated UltraHonk verifier, staticcall)InvalidProof
10Consume the context and spend the nullifier in QuantLayerNullifierRegistry; emit ProofVerified(…)ContextAlreadyConsumed, NullifierAlreadySpent

Integration. A dApp contract calls verifyProof and then applies its own policy to the public inputs: for example, the required credentialType, a minimum threshold, or a specific issuer, read by index from CIRCUITS. Because msg.sender is part of the context, a proof is usable only by the consumer it was made for.

Deployment.

contracts/script/DeployQuantLayer.s.sol performs all of this; see docs/contracts/ONCHAIN_PROTOCOL.md §8.

  1. Deploy RelationsLib and ZKTranscriptLib for each verifier, the verifier, and an UltraHonkVerifierAdapter(verifier, vkHash).
  2. Deploy QuantLayerCredentialRegistry(admin, gracePeriod), QuantLayerNullifierRegistry(admin), then QuantLayerProofVerifier(admin, credentials, nullifiers, maxProofAge); grant the verifier CONSUMER on the nullifier registry.
  3. setProofSystem(1, "ultrahonk/bb-6.0.0/evm", true), then registerCircuit with the indices shown in CIRCUITS.
  4. registerIssuer(rootId, issuerAccount, didHash) for each issuer or set.

A new circuit version gets a new id. Register it, then disableCircuit the old one.

An API response is not on-chain verification. A relying party must fetch the transaction receipt from its own node and call confirmOnChainVerification. That function requires a successful status, the configured number of confirmations, and a ProofVerified log from the expected verifier address with the expected circuit, consumer, app, context and nullifier.

7. Binding and replay

context = uint256(keccak256(abi.encode(keccak256("QUANTLAYER-ZK-CONTEXT-V1"), chainId, verifier,
                  consumer, appId, circuitId, nonce))) >> 8
scope   = uint256(keccak256(abi.encode(keccak256("QUANTLAYER-ZK-SCOPE-V1"), chainId, verifier,
                  appId, action))) >> 8
nonce   = keccak256(challengeBytes)          // ProofRequest.challenge, at least 16 random bytes
Replay attemptStopped by
Same proof, same transaction target, againEach context is single-use (ContextAlreadyConsumed)
Another chain, verifier deployment, consumer, app, circuit or noncecontext recomputed on-chain differs (ContextMismatch); off-chain, isProofBoundTo
Fresh proof, same identity, same actionNullifier per (identity, scope), shared by all circuits (NullifierAlreadySpent)
Old proof after revocationRoot registry grace period (UnknownRoot) and maxProofAge (StaleProof)
Proof dated in the futureProofFromFuture

8. Privacy requirements

  • Calldata carries only the proof, the public inputs and (appId, action, nonce, rootId). Proofs are zero-knowledge (evm target; evm-no-zk artifacts are rejected). Tests assert that identity secrets, salts, leaves and attributes appear in neither the calldata nor the serialized proof.
  • Witness data never reaches logs.
    • Identity secrets and credentials are sensitive() (they render as [REDACTED]).
    • The runtime logger redacts nullifierSecret, trapdoor, blinding, opening, siblings and witness.
    • Engine errors discard underlying messages and causes; a test feeds a secret-looking out-of-range value and checks it isn't echoed.
  • Publicly revealed per proof. The root (which set or issuer tree), the issuer and credential type, the threshold (not the balance), now, and, for nullifier circuits, a scope-specific nullifier. That nullifier is unlinkable across scopes, but each submitting account (msg.sender) is visible. Use relayers if account linkability matters.
  • The witness stays on the holder's device. Prove on the client or in the holder's own enclave. A shared proving server would see the witness.

9. Trusted setup and security assumptions

Trusted setup. UltraHonk uses the KZG polynomial commitment over BN254 with a universal structured reference string. There is no per-circuit ceremony (unlike Groth16): circuits can change without a new ceremony. QuantLayer uses Aztec's Ignition SRS, which bb downloads from crs.aztec-cdn.foundation (with fallbacks) and caches in ~/.bb-crs.

  • Soundness holds if at least one ceremony participant destroyed their secret. Anyone who knows the trapdoor could forge proofs of false statements.
  • Zero-knowledge relies on the prover's own randomness (masking), not on the setup.
  • Operations. Bb.js doesn't let QuantLayer independently verify the CRS download. Production provers should pre-provision the CRS from a source they trust (crsPath) and avoid fetching at run time. Verifiers don't need the CRS: the Solidity verifier embeds the G2 points it uses.

Proving system and implementation.

  • UltraHonk soundness rests on KZG security (q-type assumptions in the algebraic group model over BN254), the Fiat–Shamir transform with Keccak-256 modelled as a random oracle, and Barretenberg's implementation. BN254 provides about 100 bits of security after TNFS. Nothing here is post-quantum: a quantum adversary could forge proofs, though past proofs stay private.
  • The generated Solidity verifier is Aztec's code and was not audited by QuantLayer. It is pinned with its hash in the manifest, and the build check rejects any drift.
  • The Noir compiler and stdlib are trusted to compile constraints faithfully. A compiler bug could leave a circuit under-constrained, which is why negative tests run against the compiled circuits with the TypeScript checks bypassed.
  • Poseidon (circomlib parameters; see the privacy SECURITY_NOTES) is assumed collision-resistant and to behave as a PRF for nullifiers and commitments.
  • Issuer and set authorities are trusted to publish only correct roots; their account keys are critical. Admin: CIRCUIT_ADMIN can register or disable circuits and proof systems; ISSUER_ADMIN registers issuers (OpenZeppelin AccessControl). Use a multisig or timelock in production.
  • Time. block.timestamp can be skewed slightly by block producers; maxProofAge bounds the effect.

10. Operations

TaskCommand
Rebuild artifacts and verifierspnpm --filter @quantlayer-protocol/zk-noir circuits:build
Check reproducibilitypnpm --filter @quantlayer-protocol/zk-noir circuits:check
Regenerate the TS ↔ Noir vectorsQUANTLAYER_UPDATE_VECTORS=1 pnpm --filter @quantlayer-protocol/zk-noir test
Regenerate on-chain fixturesQUANTLAYER_UPDATE_FIXTURES=1 pnpm --filter @quantlayer-protocol/zk-noir test (after a build)
BenchmarksQUANTLAYER_BENCH=1 pnpm --filter @quantlayer-protocol/zk-noir exec vitest run src/bench.test.ts
Noir unit testscd circuits/noir && nargo test --workspace (Nargo 1.0.0)
Foundry testscd contracts && forge test

Verification status of this delivery. Run locally and passing:

  • compilation, proving and verification (native and WASM);
  • the TS ↔ Noir vectors;
  • the on-chain flows on the EVM harness (31 tests);
  • the reproducibility check;
  • benchmarks.

Not yet run, because the toolchains aren't installed locally: nargo test and forge test. Their first run is CI (jobs zk and contracts). The forge test contract exceeds 24 KB because it embeds six verifiers. Foundry normally exempts test contracts from EIP-170, but this hasn't been run here.