From 26202e6feec5bcbc971fa59bfa879db165731c0b Mon Sep 17 00:00:00 2001 From: Meyanis95 Date: Thu, 23 Apr 2026 16:34:45 +0200 Subject: [PATCH 1/6] feat(patterns): migrate batch 2 (29 cards) to schema v2 (#150) --- patterns/pattern-private-mtp-auth.md | 120 ++++++--- ...pattern-private-pvp-stablecoins-erc7573.md | 130 ++++++---- ...attern-private-set-intersection-circuit.md | 129 +++++---- .../pattern-private-set-intersection-dh.md | 135 ++++++---- .../pattern-private-set-intersection-fhe.md | 143 +++++----- .../pattern-private-set-intersection-oprf.md | 145 ++++++----- .../pattern-private-shared-state-cosnark.md | 133 ++++++---- patterns/pattern-private-shared-state-fhe.md | 133 ++++++---- patterns/pattern-private-shared-state-tee.md | 136 ++++++---- ...rn-private-stablecoin-shielded-payments.md | 147 +++++++---- ...attern-private-transaction-broadcasting.md | 185 ++++++------- patterns/pattern-private-vaults.md | 121 ++++++--- patterns/pattern-proof-of-innocence.md | 152 ++++++----- ...ttern-regulatory-disclosure-keys-proofs.md | 119 ++++++--- patterns/pattern-safe-proof-delegation.md | 124 +++++---- patterns/pattern-stealth-addresses.md | 131 +++++----- patterns/pattern-tee-based-privacy.md | 245 ++++++++---------- patterns/pattern-tee-key-manager.md | 189 +++++++------- patterns/pattern-tee-network-anonymity.md | 132 ++++++---- patterns/pattern-tee-zk-settlement.md | 193 ++++++-------- .../pattern-threshold-encrypted-mempool.md | 205 ++++++--------- patterns/pattern-tls-payment-bridge.md | 123 +++++---- .../pattern-user-controlled-viewing-keys.md | 132 ++++++---- patterns/pattern-verifiable-attestation.md | 139 +++++----- patterns/pattern-voprf-nullifiers.md | 202 ++++++--------- patterns/pattern-zk-kyc-ml-id-erc734-735.md | 114 ++++++-- patterns/pattern-zk-promises.md | 123 +++++---- patterns/pattern-zk-proof-systems.md | 153 +++++++---- patterns/pattern-zk-tls.md | 108 +++++--- 29 files changed, 2415 insertions(+), 1826 deletions(-) diff --git a/patterns/pattern-private-mtp-auth.md b/patterns/pattern-private-mtp-auth.md index 0b4c981..8c0e9ce 100644 --- a/patterns/pattern-private-mtp-auth.md +++ b/patterns/pattern-private-mtp-auth.md @@ -1,74 +1,108 @@ --- title: "Pattern: Private Client Authentication for Institutional EOAs" status: draft -maturity: pilot +maturity: testnet +type: standard layer: hybrid -privacy_goal: Authenticate client EOAs via Merkle proofs without revealing identity or linking addresses -assumptions: ZK circuits for Merkle membership, on-chain Merkle root registry, Semaphore or similar -last_reviewed: 2026-01-14 +last_reviewed: 2026-04-22 + works-best-when: - - Institutions must comply with KYC/AML but want to protect client privacy onchain. + - Institutions must comply with KYC/AML but want to protect client privacy on-chain. - Clients need to prove control of EOAs without revealing identity. - Multi-address support is desired (same seed, different EOAs). avoid-when: - - Regulators require explicit PII disclosure onchain. - - Institutions lack capacity to manage ZK infrastructure or Merkle registry. -dependencies: [ERC-3643, EIP-7573, EAS, Semaphore, MTP, ZK-Proofs] + - Regulators require explicit PII disclosure on-chain. + - Institutions lack capacity to manage zero-knowledge infrastructure or Merkle registry. + context: both +context_differentiation: + i2i: "Between institutions, peers can negotiate mutual inclusion terms and publish roots to shared registries. Authentication is typically bilateral, with each institution trusting the other's KYC process, and disputes have legal recourse." + i2u: "For end users, the institution is the sole gatekeeper of client inclusion. Users have no unilateral escape path if removed from the registry. Censorship resistance depends on how the Merkle root is governed (single issuer, multi-institution registry, or DAO)." + crops_profile: cr: low - os: yes - privacy: full - security: high + o: yes + p: full + s: high + +crops_context: + cr: "Reaches `medium` or `high` when Merkle membership is managed by a decentralized registry or multi-institutional DAO rather than a single institution. Drops to `low` when a single institution controls inclusion and root updates with no user recourse." + o: "Zero-knowledge circuits and attestation schemas are open source. Institutional registries and KYC backends are typically proprietary." + p: "Hides client identity, KYC details, and linkage between EOAs of the same client. On-chain observers see only the proof and the nullifier." + s: "Rides on the soundness of the zero-knowledge proof system, collision-resistance of the Merkle hash function, and honest tree construction by the institution. Nullifiers prevent replay but do not prevent a malicious issuer from inserting fake leaves." + +post_quantum: + risk: high + vector: "Pairing-based and elliptic-curve proof systems (Groth16, PLONK/KZG) are broken by a CRQC, letting an attacker forge membership proofs. HNDL risk is bounded because the Merkle tree itself uses hash-based commitments." + mitigation: "Migrate to STARK-based membership circuits with hash-based commitments. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [ERC-3643, EIP-7573, ERC-735] + +related_patterns: + composes_with: [pattern-verifiable-attestation, pattern-voprf-nullifiers, pattern-regulatory-disclosure-keys-proofs, pattern-zk-kyc-ml-id-erc734-735] + see_also: [pattern-zk-tls, pattern-user-controlled-viewing-keys] + +open_source_implementations: + - url: https://github.com/semaphore-protocol/semaphore + description: "Semaphore: zero-knowledge signaling with Merkle membership and nullifiers" + language: "Circom, Solidity" + - url: https://github.com/privacy-scaling-explorations/zk-kit + description: "PSE zk-kit: Merkle tree libraries used by Semaphore and similar membership-proof systems" + language: "TypeScript" --- ## Intent -Enable institutions to authenticate client EOAs in a way that satisfies regulatory KYC/AML requirements while preserving privacy. This pattern uses **Merkle tree membership proofs** (e.g., via Semaphore) so clients can demonstrate inclusion in an approved/KYC’d registry without revealing identity or linking other addresses. +Authenticate client externally-owned accounts in a way that satisfies regulatory KYC/AML requirements while preserving on-chain privacy. The institution maintains a Merkle tree of approved client EOAs; clients prove inclusion with a zero-knowledge proof plus a nullifier. Observers see neither the client's identity nor links between the client's other EOAs. + +## Components + +- Off-chain KYC process operated by the institution or a regulated distributor, producing a per-client approval record. +- Merkle tree of approved EOAs maintained off-chain and committed on-chain as a root. +- On-chain root registry contract that holds the current and recent roots for proof verification. +- Membership circuit that proves Merkle inclusion, binds a nullifier to the leaf, and proves control of the private key for the EOA. +- Nullifier set stored on-chain or in the verifier contract to prevent proof replay. +- Client wallet with zero-knowledge prover integration for generating membership proofs. +- Audit interface so regulators can verify tree updates and proof validity without learning which leaf belongs to whom. + +## Protocol -## Ingredients +1. [institution] Run KYC off-chain with the client and record approval. +2. [institution] Insert the client's EOA into the approved-set Merkle tree and publish the updated root on-chain. +3. [user] Generate a membership proof: Merkle path from the client's leaf to the current root, a nullifier bound to the leaf, and a signature proving control of the EOA. +4. [user] Submit the proof and nullifier to the institution's verifier contract or off-chain verifier. +5. [contract] Verify the proof against the published root, check the nullifier has not been used, and record the nullifier. +6. [regulator] Audit the tree, the nullifier set, and sampled proofs without learning the mapping from leaves to clients. -- **Standards/ER(C|IP)s**: ERC-3643 (permissioned tokens), EAS (attestation registry). -- **Infra**: Ethereum L1/L2s, wallet, ZK circuits for Merkle membership proofs. -- **Off-chain services**: KYC registries, institutional Merkle tree builder, key management systems, On-chain contract to maintain MT root. +## Guarantees & threat model -## Protocol (concise) +Guarantees: -1. Client undergoes KYC off-chain with institution or distributor. -2. Institution inserts client EOA into a Merkle tree of approved addresses; commits root onchain. -3. Client wallet generates a **Semaphore proof**: Merkle membership + nullifier (anti-replay) + private key control. -4. Proof submitted to institution’s contract or off-chain verifier. -5. Institution verifies ZK proof; accepts EOA as authenticated. -6. (Future) Clients prove multiple EOAs derive from same seed via multi-ownership extension. -7. Regulators/auditors can verify tree updates and proof validity without learning which leaf belongs to whom. +- Hides client identity, KYC record, and linkage across the client's other EOAs. +- Proves Merkle membership in the approved set, control of the corresponding private key, and non-replay via the nullifier. +- Scoped disclosure to regulators: the registry operator can selectively reveal the mapping between leaves and client identities under a legal process. -## Guarantees +Threat model: -- **Hides**: identity, KYC details, linkage between EOAs. -- **Proves**: KYC membership, private key control, non-reusability (via nullifiers). -- **Atomicity**: proof verification and transaction execution tied. -- **Audit**: regulator can validate registry and roots without deanonymizing clients. +- Soundness of the zero-knowledge proof system and the Merkle hash function. +- Honest tree construction by the institution. A dishonest issuer can insert unapproved leaves, inflating the anonymity set with accounts that did not go through KYC. +- Non-censoring root publication path. If the institution freezes root updates, newly-approved clients cannot authenticate. +- Out of scope: network-layer metadata (IP, timing), on-chain behavioural fingerprints after authentication, and deanonymisation via transaction graph analysis. ## Trade-offs -- **Performance/cost**: ZK proof generation adds latency; tree updates must be frequent. -- **DX**: client wallets need Semaphore/ZK integration. -- **Limitations**: current Semaphore-style MT proofs don’t support efficient multi-ownership (same seed, many EOAs). -- **CROPS context (both)**: CR could reach `high` if Merkle membership is managed by a decentralized registry or DAO rather than a single institution. In I2U, CR risk is acute: institution is sole gatekeeper of client inclusion with no user escape path. In I2I, peers can negotiate mutual inclusion terms. +- Proof generation adds latency (seconds on commodity hardware, longer in browser WASM). Wallets need a prover integration. +- Tree updates must be frequent enough for newly-approved clients to transact. Batch cadence is a governance parameter. +- Current Semaphore-style membership circuits do not natively support proving that several EOAs derive from the same seed. Multi-address support requires an extended circuit or a separate attestation layer. +- Revocation requires a root update and careful handling of in-flight proofs against the previous root. ## Example -- The bank runs a KYC registry; inserts approved EOAs into a Merkle tree. -- Client generates a Semaphore proof showing inclusion in the tree. -- The bank contract validates the proof before processing a tokenized security transfer. -- Observers see the transaction but cannot link EOA to a specific client or discover other addresses. -- Regulator can later audit the registry root and inclusion proof. +A custodian runs a KYC registry and inserts approved client EOAs into a Merkle tree. A client generates a membership proof showing inclusion in the current root, bound to a fresh nullifier. The custodian's contract validates the proof before processing a tokenised-security transfer. External observers see the transaction and a nullifier but cannot link the EOA to a specific client or discover the client's other addresses. The regulator can later audit the registry root, the nullifier set, and sampled inclusion proofs. ## See also +- [Semaphore protocol](https://semaphore.pse.dev/): Merkle membership, nullifiers, and signaling primitives used by this pattern +- [ERC-3643: T-REX permissioned token standard](https://eips.ethereum.org/EIPS/eip-3643) +- [EAS: Ethereum Attestation Service](https://attest.org/) - [Approach: Private Identity](../approaches/approach-private-identity.md) -- [Verifiable Attestation](pattern-verifiable-attestation.md) -- [vOPRF Nullifiers](pattern-voprf-nullifiers.md) -- [Selective Disclosure](pattern-regulatory-disclosure-keys-proofs.md) -- [ZK-KYC/ML + ONCHAINID](pattern-zk-kyc-ml-id-erc734-735.md) -- [zk-TLS](pattern-zk-tls.md) diff --git a/patterns/pattern-private-pvp-stablecoins-erc7573.md b/patterns/pattern-private-pvp-stablecoins-erc7573.md index 1161aca..52f6c9b 100644 --- a/patterns/pattern-private-pvp-stablecoins-erc7573.md +++ b/patterns/pattern-private-pvp-stablecoins-erc7573.md @@ -1,63 +1,101 @@ --- -title: "Pattern: Private PvP (cash↔cash) Settlement via ERC‑7573" +title: "Pattern: Private PvP (cash to cash) Settlement via ERC-7573" status: draft -maturity: PoC +maturity: concept +type: standard layer: hybrid -privacy_goal: Atomic PvP between stablecoins with amount privacy and stakeholder-only visibility -assumptions: ERC-7573 escrows, FX/price oracles, shielded transfer infrastructure on both legs -last_reviewed: 2026-01-14 +last_reviewed: 2026-04-22 + works-best-when: - - Two permissioned/regulated stablecoins (same L2 or cross‑L2) must settle **atomically** with **amount privacy**. - - FX or cross‑issuer settlement requires on‑chain finality sensing and pricing. + - Two permissioned or regulated stablecoins (same L2 or cross-L2) must settle atomically with amount privacy. + - Finality sensing and pricing for FX or cross-issuer settlement can be served by an oracle feed both parties accept. avoid-when: - - Bilateral netting/off‑chain wires suffice; or HTLC timeouts are acceptable. -dependencies: [ERC-7573, EAS, Chainlink Data Feeds, optional CCIP] + - Bilateral netting or off-chain wires already satisfy the settlement requirement. + - HTLC timeouts with public amounts are acceptable and operational simplicity outweighs privacy. + context: i2i + crops_profile: cr: medium - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "Censorship resistance depends on the oracle feed and the finality-relayer path. If the oracle or the cross-domain relayer censors, settlement can stall even though the escrow contracts are non-custodial." + o: "The ERC-7573 escrow standard is open; oracle feeds and cross-chain messaging infrastructure are typically proprietary. Parties can substitute alternative oracles and relayers at deployment time." + p: "Amounts and counterparties are hidden from the public chain, but the escrow contracts, oracle verdicts, and minimal settlement anchors remain visible. Metadata about when settlement happened and which assets are involved is not hidden." + s: "Rides on the correctness of the escrow contracts, oracle honesty, and finality-sensing correctness on the paying leg. Ops procedures must cover oracle outages and cross-domain message delays." + +post_quantum: + risk: medium + vector: "Signatures over oracle reports, cross-domain proofs, and shielded-layer zero-knowledge proofs use elliptic-curve primitives that are broken by a CRQC." + mitigation: "Migrate oracle attestations and cross-domain proofs to post-quantum signature schemes; compose with a post-quantum shielding layer on each leg. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [ERC-7573, ERC-20] + +related_patterns: + requires: [pattern-private-stablecoin-shielded-payments] + composes_with: [pattern-dvp-erc7573, pattern-shielding, pattern-l2-encrypted-offchain-audit, pattern-regulatory-disclosure-keys-proofs] + see_also: [pattern-cross-chain-privacy-bridge, pattern-pretrade-privacy-encryption] + +open_source_implementations: + - url: https://github.com/ercs-eth/erc-7573 + description: "ERC-7573 reference escrow contracts for atomic asset transfer" + language: Solidity --- ## Intent -Enable **atomic PvP (cash↔cash)** between two stablecoins while preserving **stakeholder‑only visibility** and providing **verifiable settlement** and **audit trails**—without relying on HTLC timeouts. - -## Ingredients -- **Standards:** [ERC‑7573](https://ercs.ethereum.org/ERCS/erc-7573) on each leg; [EAS](https://attest.org/) for disclosure/audit attestations. -- **Oracles:** **FX/price feeds** for settlement checks (e.g., [Chainlink Data Feeds](https://docs.chain.link/data-feeds/price-feeds)). -- **Infra:** Same L2/app‑chain or cross‑L2; finality sensing/relayer if cross‑domain. -- **(Optional) Interop:** [Chainlink CCIP](https://docs.chain.link/ccip) for cross‑chain messaging/token movement where appropriate. -- **Privacy layer:** Each stablecoin uses shielded transfers (ZK/FHE) or lives on a privacy L2 (see related pattern). - -## Protocol (concise) -1. **Quote & terms:** Parties agree PvP notional and FX rate (if cross‑currency), referenced via oracle feed ID. -2. **Prepare escrows:** Each side escrows shielded stablecoin under **ERC‑7573** conditions: "release if other leg finalized at or above X units per oracle at T." -3. **Finalize leg A:** Detect finality on A's chain; produce proof/message to leg B. -4. **Release leg B:** Upon proof and price check, B's escrow releases to counterparty. -5. **Symmetric completion:** Both legs either settle or both revert; on failure, runbooks handle retry/cancel. -6. **Selective disclosure:** Log regulator access via **EAS** attestations; no public amounts leaked. - -## Guarantees -- **Atomicity:** True cash↔cash atomic settlement; no HTLC timeouts. -- **Privacy:** Amounts and counterparties remain private to stakeholders; only oracle verdicts and minimal anchors are public. -- **Audit:** Disclosures are scoped and logged (EAS); replayable proofs of settlement. + +Settle two stablecoin legs against each other atomically while keeping amounts and counterparties visible only to the transacting parties and their auditors. Each leg uses a shielded transfer layer for privacy; the ERC-7573 escrow pattern on both chains conditions release on verified finality of the opposite leg, so neither side settles without the other. The construction avoids the public amounts and timing leakage of plain HTLCs and avoids relying on time-locks for safety. + +## Components + +- ERC-7573 conditional-escrow contract on each chain, parameterised with the release condition for the opposite leg. +- Shielded transfer layer on each chain that hides amounts and counterparties on the transacting side. +- Price or FX oracle feed, referenced by feed identifier, used to check the rate condition at settlement time when the legs are in different units. +- Finality-sensing component that produces an attestation (or cross-domain message) proving the paying leg finalised at or above the agreed terms. +- Optional cross-domain messaging layer when the two legs live on different L2s or app-chains. +- Attestation layer for scoped disclosure to auditors, recording which parties settled, at what rate, and when, without exposing amounts publicly. + +## Protocol + +1. [counterparty] Agree bilaterally on notional, FX rate (if cross-currency), oracle feed identifier, and tolerance band. +2. [counterparty] Each side deposits the shielded stablecoin into the ERC-7573 escrow on its chain, encoding the release condition that references the opposite leg and the oracle feed. +3. [counterparty] The first leg executes: shielded payment settles and finality is reached on the originating chain. +4. [relayer] Produce a finality attestation or cross-domain message proving the first leg finalised within the agreed terms. +5. [contract] The second-leg escrow verifies the attestation and the oracle rate, then releases the shielded payment to the counterparty. +6. [counterparty] On failure (missed finality window, oracle outside tolerance), both escrows revert and operational runbooks handle retry or cancel. +7. [auditor] Use the attestation record and viewing keys on each leg to reconstruct the full settlement for compliance review. + +## Guarantees & threat model + +Guarantees: + +- Atomic settlement across two chains or two assets: both legs settle or both revert, without relying on time-locks for safety. +- Amount privacy: amounts are hidden on the chains themselves; only stakeholders and auditors with the viewing keys see the full trade. +- Scoped disclosure: attestations log regulator access without exposing amounts publicly. + +Threat model: + +- Oracle honesty and update cadence. A compromised or stale feed lets an attacker settle outside the agreed tolerance band. +- Finality-sensing correctness on the paying leg. A fake or premature finality attestation can trigger a one-sided release. +- Non-censoring cross-domain relayer. A relayer that withholds messages stalls settlement; escrows must fail safe back to the originator. +- Upgrade governance on both escrow contracts. A unilateral upgrade on one leg can freeze settled funds. +- Out of scope: correlation of settlement windows across the two chains by a global network observer. ## Trade-offs -- **Oracle trust:** FX checks rely on oracle security and update cadence. -- **Complexity:** Cross‑L2 finality sensing and failure handling add ops overhead. -- **Liquidity:** Fragmentation across issuers/L2s; consider market‑making facilities. -- **CROPS context (I2I)**: CR depends on oracle and relayer availability. ERC-7573 is an open standard; oracle/finality infrastructure (e.g. Chainlink) is proprietary. + +- Oracle dependence is the main operational risk: outage, stale data, or price manipulation can each block settlement or produce an unfair release. +- Cross-L2 finality sensing and the failure-recovery path add operational overhead relative to a single-chain DvP. +- Fragmentation across issuers and L2s may require market-making facilities to source liquidity on both sides. +- Debuggability: amounts and counterparties are hidden on-chain, so post-mortems require coordinated viewing-key access with the counterparty. ## Example -- **USDc(L2‑A)** ↔ **EURc(L2‑B)**: Bank A pays USDc; Bank B pays EURc. **ERC‑7573** escrows on both sides reference **EUR/USD** price feed. When A's transfer finalizes and oracle confirms rate within tolerance, B's leg releases atomically; selective disclosure granted to auditor for both legs. + +Two regulated banks settle a shielded USD-stablecoin leg against a shielded EUR-stablecoin leg on separate L2s. Each bank deposits its shielded leg into an ERC-7573 escrow that references an EUR/USD price feed and the opposite escrow's finality proof. When the USD leg finalises within tolerance, a cross-domain attestation releases the EUR escrow to the USD-paying bank. Chain observers see that two escrow contracts settled but not the amounts or identities. The banks' auditors reconstruct the full trade via the shielded viewing keys and the attestation log. ## See also -- `pattern-private-stablecoin-shielded-payments.md` -- `pattern-dvp-erc7573.md` -- `pattern-l2-encrypted-offchain-audit.md` - -## References -- ERC‑7573 spec: -- Chainlink Data Feeds (FX): -- Chainlink CCIP (messaging): \ No newline at end of file + +- [ERC-7573: Conditional-upon-Event Asset Transfer](https://eips.ethereum.org/EIPS/eip-7573) +- [Delivery versus Payment via ERC-7573](pattern-dvp-erc7573.md) diff --git a/patterns/pattern-private-set-intersection-circuit.md b/patterns/pattern-private-set-intersection-circuit.md index 8988125..fe1689e 100644 --- a/patterns/pattern-private-set-intersection-circuit.md +++ b/patterns/pattern-private-set-intersection-circuit.md @@ -1,77 +1,110 @@ --- title: "Pattern: Private Set Intersection (Circuit-based)" status: draft -maturity: PoC +maturity: testnet +type: standard layer: offchain -privacy_goal: Two parties discover shared set elements and compute arbitrary functions over the intersection without revealing non-matching entries -assumptions: Bilateral communication channel, OT security, function to compute is fixed at circuit-compile time -last_reviewed: 2026-03-18 +last_reviewed: 2026-04-22 + works-best-when: - - The result needed is a function over the intersection (count, sum, threshold), not the raw intersection itself - - Set sizes are small to moderate (circuit size scales with O((n+m) log(n+m) * σ) Boolean gates, where σ is element bit-width) - - The function and set sizes are known at circuit-compile time + - The result needed is a function over the intersection (count, sum, threshold), not the raw intersection itself. + - Set sizes are small to moderate (circuit size scales with O((n+m) log(n+m) * sigma) Boolean gates, where sigma is element bit-width). + - The function and set sizes are known at circuit-compile time. avoid-when: - - Only the intersection itself is needed (DH or OPRF variants are simpler and faster) - - Sets are large (Boolean circuit blowup makes this impractical beyond ~10k elements for 256-bit identifiers) - - Compilation and garbling cost per execution is prohibitive for the use case -dependencies: [Authenticated garbling, OT extensions, Boolean circuit compiler] + - Only the raw intersection is needed (DH or OPRF variants are simpler and faster). + - Sets are large (Boolean-circuit blowup makes this impractical beyond about 10k elements for 256-bit identifiers). + - Compilation and garbling cost per execution is prohibitive for the use case. + context: both +context_differentiation: + i2i: "Between institutions, circuit-based intersection is typically contracted between known parties, with the function and set sizes fixed up front in the agreement. Roles are assigned bilaterally (who garbles, who evaluates) and SLAs cover delivery of the output decoding table." + i2u: "For users, the institution typically holds the garbler role, which means the institution can withhold the output decoding table. Users should rely on authenticated garbling with output commitments so that withheld outputs are detectable and punishable." + crops_profile: cr: high - os: yes - privacy: full - security: medium + o: yes + p: full + s: medium + +crops_context: + cr: "Both parties participate directly in the circuit evaluation over a bilateral channel. No on-chain component is required, so chain-level censorship does not apply." + o: "Open-source MPC and garbled-circuit toolkits are widely available; circuit compilers and evaluation runtimes are published under permissive licenses." + p: "The garbled circuit hides both inputs and intermediate computation. Output is limited to the agreed function F(intersection), so neither party sees the raw matches unless F is chosen to reveal them." + s: "Semi-honest by default. Authenticated garbling achieves malicious security at roughly 2 to 3 times overhead. Soundness of the result depends on the honesty of the garbler; withholding the output decoding table blocks the evaluator from learning F." + +post_quantum: + risk: medium + vector: "Base OT and authenticated-garbling MACs in standard MPC pipelines use elliptic-curve primitives broken by a CRQC. Garbling itself is symmetric and resists quantum analysis once base OT is secure." + mitigation: "Swap base OT for a lattice-based or code-based post-quantum OT construction and use hash-based MACs. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + alternative_to: [pattern-private-set-intersection-dh, pattern-private-set-intersection-oprf, pattern-private-set-intersection-fhe] + composes_with: [pattern-dvp-erc7573, pattern-pretrade-privacy-encryption] + see_also: [pattern-private-shared-state-cosnark, pattern-co-snark, pattern-mpc-custody] + +open_source_implementations: + - url: https://github.com/encryptogroup/ABY + description: "ABY: mixed-protocol framework supporting arithmetic, Boolean, and Yao sharing for two-party computation" + language: "C++" + - url: https://github.com/emp-toolkit + description: "EMP-toolkit: MPC toolkit with garbled-circuit implementations and semi-honest and malicious protocols" + language: "C++" + - url: https://github.com/encryptogroup/MOTION + description: "MOTION: mixed-protocol MPC framework supporting BMR (multi-party garbled circuits), GMW, and arithmetic sharing for two or more parties" + language: "C++" --- ## Intent -Two parties each hold a private set and want to compute a function over their shared elements without either party learning the raw intersection. Intersection-finding logic is embedded inside the circuit alongside the aggregate function F, so the output is limited to F(intersection). The raw matches are not revealed to either party. The circuit is evaluated jointly using authenticated garbling or secret-shared circuits (GMW). +Two parties each hold a private set and want to compute a function over their shared elements without either party learning the raw intersection. Intersection-finding logic is embedded in a Boolean circuit alongside the aggregate function F, so the output is limited to F(intersection). The circuit is evaluated jointly using authenticated garbling or secret-shared circuits, and the raw matches are not revealed to either party. -## Ingredients +## Components -- **Cryptography**: Authenticated garbling (Wang-Ranellucci-Katz 2017) or secret-shared circuits (GMW), Oblivious Transfer (OT) extensions, sort-compare-shuffle or hash-based circuit design -- **Infra**: Authenticated bilateral channel (TLS, Noise, or similar) -- **Off-chain**: Circuit compiler (Bristol format or equivalent), ephemeral computation +- Circuit compiler (Bristol format or equivalent) that emits a Boolean circuit encoding the matching logic (sort-compare-shuffle or hash-based) plus the aggregate function F. +- Garbled-circuit or GMW runtime that turns the compiled circuit into an interactive protocol. +- OT extension library providing base OTs for garbled-label transfer. +- Authenticated bilateral channel for garbled-table transmission and OT. +- Output decoding table and, for authenticated garbling, commitments binding the garbler to the circuit it sent. ## Protocol -1. **Compile**: Parties agree on function F and set sizes. Both compile a Boolean circuit C encoding matching logic (sort-compare-shuffle or hash-based) plus F. Circuit size is fixed to the agreed parameters. -2. **Garble**: A generates fresh garbled tables for every gate in C and sends the garbled circuit to B. -3. **Transfer inputs**: A encodes its inputs into garbled labels directly. B obtains garbled labels for its inputs via OT. -4. **Evaluate**: B evaluates the garbled circuit gate-by-gate, producing the garbled output. -5. **Reveal**: A shares the output decoding table with B. B decodes locally, then sends the garbled output labels to A. Both parties learn F(intersection). +1. [counterparty] Parties agree on function F and set sizes, then compile a Boolean circuit C encoding the matching logic plus F. Circuit size is fixed to the agreed parameters. +2. [counterparty] Party A generates fresh garbled tables for every gate in C and sends the garbled circuit to Party B. +3. [counterparty] A encodes its inputs into garbled labels directly. B obtains garbled labels for its inputs via OT. +4. [counterparty] B evaluates the garbled circuit gate by gate, producing the garbled output. +5. [counterparty] A sends the output decoding table to B. B decodes locally, then sends the garbled output labels to A so that A can also decode. + +## Guarantees & threat model + +Guarantees: + +- Input privacy: each party's set is opaque to the other inside the garbled circuit. +- Function generality: encodes any Boolean function over the intersection, including cardinality, weighted sums, or threshold predicates. +- Completeness: deterministic evaluation over all shared elements (zero false negatives). +- Output confined to F: neither party learns the raw matches unless F is chosen to reveal them. -## Guarantees +Threat model: -- **Input privacy**: Each party's set remains opaque to the other inside the garbled circuit. -- **Function generality**: Encodes any Boolean function over the intersection, including cardinality, weighted sums, or threshold predicates. -- **Completeness**: Deterministic evaluation over all shared elements (zero false negatives). -- **I2I**: Institutions compute aggregates over shared portfolios or flagged-entity overlaps without exposing full books. -- **I2U**: A user verifies whether their credential set meets an institution's threshold without revealing which credentials they hold. +- Soundness of the garbling scheme and OT extension. +- Honest garbler (semi-honest baseline); authenticated garbling (Wang-Ranellucci-Katz 2017) achieves malicious security at about 2 to 3 times overhead. +- Non-withholding garbler: the garbler holds the output decoding table and can refuse to release it, preventing the evaluator from learning F. Commit-and-open variants make withholding detectable. +- Authenticated transport between the parties; otherwise a network attacker can swap labels or tables. ## Trade-offs -- Circuit size scales with O((n + m) log(n + m) * σ) gates for sort-compare-shuffle, where σ is the element bit-width. For 256-bit identifiers, this becomes costly beyond ~10k elements per party. -- Circuit must be compiled for a fixed function and fixed set sizes. Each execution requires fresh garbling (single-use). Input-independent preprocessing can be done ahead of time. -- Semi-honest security by default. Authenticated garbling (Wang-Ranellucci-Katz 2017) achieves malicious security at ~2-3x overhead. -- Garbling has asymmetric roles (garbler transmits the full circuit). The garbler holds the output decoding table and can withhold it, preventing the evaluator from learning the result. In I2U, the institution typically garbles. GMW supports more than 2 parties but requires MPC-based garbling or a trusted dealer for preprocessing. -- **CROPS context**: Applies to both I2I and I2U. CR is `high` because both parties participate directly in circuit evaluation over a bilateral channel. In I2I, institutions jointly evaluate the circuit over an authenticated channel. In I2U, the user evaluates their side on commodity hardware. Privacy is `full` because the garbled circuit hides both inputs and intermediate computation; the output is limited to the agreed-upon function result. +- Circuit size scales with O((n + m) log(n + m) * sigma) gates for sort-compare-shuffle, where sigma is the element bit-width. For 256-bit identifiers this becomes costly beyond about 10k elements per party. +- Circuit is fixed to a function and set size: each execution needs fresh garbling, though input-independent preprocessing can be done ahead of time. +- Asymmetric roles: the garbler transmits the full circuit and holds the output decoding table. Role assignment matters in I2U deployments. +- GMW supports more than two parties but requires MPC-based garbling or a trusted dealer for preprocessing. ## Example -- Compliance Team A holds 2,000 flagged wallet addresses; Team B holds 3,500. -- Both compile a PSI-cardinality circuit that outputs the intersection count. -- After garbling, OT, and evaluation, both learn the count: 47 shared flags. -- The matching addresses themselves stay private. If the count exceeds a threshold, they escalate to supervised disclosure. +Two compliance teams want to count how many wallet addresses appear on both of their flagged lists without revealing which addresses match. Team A holds 2,000 flagged addresses and Team B holds 3,500. Both compile a PSI-cardinality circuit that outputs the intersection count. After garbling, OT, and evaluation, both learn the count (47 shared flags). The matching addresses themselves stay private, and if the count exceeds a threshold the teams escalate to supervised disclosure. ## See also -- [Private Set Intersection (DH-based)](pattern-private-set-intersection-dh.md): simpler ECDH variant for when the raw intersection is sufficient -- [Private Set Intersection (OPRF-based)](pattern-private-set-intersection-oprf.md): OT/OPRF variant for large sets (10k+ elements) -- [Private Set Intersection (FHE-based)](pattern-private-set-intersection-fhe.md): FHE variant for asymmetric set sizes with post-quantum security -- [Private Shared State (co-SNARKs)](pattern-private-shared-state-cosnark.md): MPC for ongoing shared state, vs one-shot computation here -- [DvP (ERC-7573)](pattern-dvp-erc7573.md): downstream consumer when matched trades feed into settlement -- [Pre-trade Privacy Encryption](pattern-pretrade-privacy-encryption.md): alternative approach for pre-trade discovery -- [ABY Framework](https://github.com/encryptogroup/ABY): mixed-protocol framework supporting arithmetic, Boolean, and Yao sharing for two-party computation -- [EMP-toolkit](https://github.com/emp-toolkit): efficient MPC toolkit with garbled circuit implementations and semi-honest/malicious protocols -- [MOTION Framework](https://github.com/encryptogroup/MOTION): mixed-protocol MPC framework supporting BMR (multi-party garbled circuits), GMW, and arithmetic sharing for two or more parties +- [Huang et al. 2012: Faster Secure Two-Party Computation Using Garbled Circuits](https://www.usenix.org/system/files/conference/usenixsecurity11/sec11-final229.pdf) +- [Wang, Ranellucci, Katz 2017: Authenticated Garbling and Efficient Maliciously Secure Two-Party Computation](https://eprint.iacr.org/2017/030) +- [Pinkas et al. 2019: Efficient Circuit-based PSI with Linear Communication](https://eprint.iacr.org/2019/241) diff --git a/patterns/pattern-private-set-intersection-dh.md b/patterns/pattern-private-set-intersection-dh.md index 091af9f..74de33c 100644 --- a/patterns/pattern-private-set-intersection-dh.md +++ b/patterns/pattern-private-set-intersection-dh.md @@ -1,87 +1,108 @@ --- title: "Pattern: Private Set Intersection (DH-based)" status: draft -maturity: PoC +maturity: testnet +type: standard layer: offchain -privacy_goal: Two parties discover shared set elements without revealing non-matching entries -assumptions: Bilateral communication channel, DDH hardness, sets contain exact-match identifiers -last_reviewed: 2026-03-18 +last_reviewed: 2026-04-22 + works-best-when: - - Both parties hold private sets of comparable size (< 10k elements) - - Matching is bilateral (exactly two parties) - - Elements are exact-match identifiers (addresses, ISINs, LEIs) + - Both parties hold private sets of comparable size (under 10k elements). + - Matching is bilateral (exactly two parties). + - Elements are exact-match identifiers (addresses, ISINs, LEIs). avoid-when: - - More than two parties need to participate (use circuit-based or MPC variant) - - Fuzzy or approximate matching is required - - One party's set is already public (use Merkle inclusion proof instead) -dependencies: [ECDH, hash-to-curve] + - More than two parties need to participate. + - Fuzzy or approximate matching is required. + - One party's set is already public (use a Merkle inclusion proof instead). + context: both +context_differentiation: + i2i: "Between institutions, both parties run the protocol bilaterally over an authenticated channel. Minimum-set-size policies are negotiated up front. Semi-honest security is usually sufficient when both parties have legal recourse; malicious security can be added when the relationship is less established." + i2u: "For end users, the user runs their side on commodity hardware. The institution cannot learn the user's other identifiers beyond the submitted set. Users should submit sets larger than the minimum-set-size threshold to avoid turning the protocol into a yes/no membership oracle for a single identifier." + crops_profile: cr: high - os: yes - privacy: full - security: high + o: yes + p: full + s: high + +crops_context: + cr: "Both parties run the protocol directly without an intermediary that could censor or filter matches. No on-chain component is required, so chain-level censorship does not apply." + o: "Open-source implementations exist across multiple languages and the underlying primitives (ECDH, hash-to-curve) are standard." + p: "Non-intersecting elements are computationally hidden under DDH. Privacy degrades from `full` to `partial` when a party submits a very small set, because intersection membership becomes attributable to specific elements." + s: "Semi-honest by default. Malicious security requires additional commitments and zero-knowledge proofs binding the blinded set to a committed set." + +post_quantum: + risk: high + vector: "DDH is broken by Shor's algorithm on a CRQC; commutative ECDH blinding no longer hides non-intersecting elements. HNDL applies to recorded exchanges." + mitigation: "Migrate to lattice-based or isogeny-based PSI constructions. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + alternative_to: [pattern-private-set-intersection-oprf, pattern-private-set-intersection-circuit, pattern-private-set-intersection-fhe] + composes_with: [pattern-dvp-erc7573, pattern-pretrade-privacy-encryption] + see_also: [pattern-voprf-nullifiers, pattern-mpc-custody, pattern-private-shared-state-cosnark] + +open_source_implementations: + - url: https://github.com/google/private-join-and-compute + description: "Google Private Join and Compute: ECDH-PSI plus homomorphic encryption for aggregate computation over intersections" + language: "C++" + - url: https://github.com/OpenMined/PSI + description: "OpenMined PSI: ECDH-PSI with Bloom filters, bindings for C++, Python, Go, and JavaScript" + language: "C++" + - url: https://github.com/encryptogroup/PSI + description: "Encrypto Group PSI: benchmarking implementations of multiple PSI protocol variants including ECDH" + language: "C++" --- ## Intent -Two parties each hold a private set of identifiers and want to learn which elements they share without exposing the rest. This variant uses commutative encryption via ECDH: both parties blind their inputs with secret scalars, and the commutativity of scalar multiplication lets them compare double-blinded values without revealing the originals. The protocol runs bilaterally between the two parties. +Two parties each hold a private set of identifiers and want to learn which elements they share without exposing the rest. This variant uses commutative encryption via elliptic-curve Diffie-Hellman: both parties blind their inputs with secret scalars, and the commutativity of scalar multiplication lets them compare double-blinded values without revealing the originals. The protocol runs bilaterally between the two parties. -## Ingredients +## Components -- **Cryptography**: ECDH (commutative scalar multiplication), hash-to-curve -- **Infra**: Authenticated bilateral channel (TLS, Noise, or similar) -- **Off-chain**: Ephemeral computation, no persistent infrastructure required +- Elliptic curve and hash-to-curve function, agreed by both parties at session setup. +- Ephemeral secret scalars, one per party, freshly sampled per session. +- Authenticated bilateral channel for exchanging blinded and double-blinded sets. +- Local matcher that compares double-blinded points and maps matches back to plaintext on each side. ## Protocol -1. **Agree**: Parties A and B fix an elliptic curve and hash-to-curve function. Each generates an ephemeral secret scalar (a, b). -2. **Blind**: A hashes each element to a curve point and multiplies by a, sending {aH(x)} to B. B does the same with scalar b, sending {bH(y)} to A. -3. **Double-blind**: B multiplies A's blinded set by b, sending {abH(x)} to A. A multiplies B's blinded set by a, sending {abH(y)} to B. -4. **Match**: Each party now holds both {abH(x)} and {abH(y)}. Each compares the two sets; equal points are the intersection. -5. **Output**: Each party maps matched points back to their own plaintext elements. Non-matching elements stay hidden behind the other party's scalar. +1. [counterparty] Parties A and B fix the curve and hash-to-curve function and each sample an ephemeral secret scalar (a for A, b for B). +2. [counterparty] A hashes each element to a curve point and multiplies by a, sending the blinded set to B. B does the same with scalar b, sending its blinded set to A. +3. [counterparty] B multiplies A's blinded set by b and returns the double-blinded points. A does the same with B's blinded set and returns them. +4. [counterparty] Each party now holds both double-blinded sets and locally compares points. Equal points identify the intersection. +5. [counterparty] Each party maps matched points back to its own plaintext elements. Non-matching elements stay hidden behind the other party's scalar. + +## Guarantees & threat model -## Guarantees +Guarantees: -- **Input privacy**: Non-intersecting elements are computationally hidden under DDH. -- **Bilateral**: Runs directly between two parties without a server or operator. -- **Completeness**: All shared elements are found (zero false negatives). -- **Soundness**: Minimal false positives (collision-resistant hash-to-curve). -- **I2I**: Institutions match order books, reconcile settlement, or deduplicate KYC without revealing full client lists. -- **I2U**: A user checks if their address appears in an institution's eligibility list without the institution learning the user's other addresses. +- Input privacy: non-intersecting elements are computationally hidden under DDH. +- Bilateral: runs directly between the two parties without a server or operator. +- Completeness: all shared elements are found (zero false negatives). +- Soundness: negligible false-positive rate under a collision-resistant hash-to-curve. + +Threat model: + +- DDH hardness on the chosen curve. +- Honest execution by both parties. A malicious party can craft blinded sets that do not correspond to a committed input; mitigate with commit-and-prove variants. +- Authenticated transport between the parties; otherwise a network attacker can swap blinded sets. +- Set-size hygiene: a singleton or near-singleton set turns the protocol into a yes/no oracle on that element. Enforce a minimum-set-size policy. ## Trade-offs -- O(n + m) curve points exchanged. Practical for sets under 10k; for larger sets, use the OT/OPRF-based variant. +- O(n + m) curve points exchanged. Practical for sets under 10k; for larger sets, use an OT/OPRF-based variant. - 2(n + m) scalar multiplications. Seconds for 10k elements on commodity hardware. -- Limited to equality checks. Aggregates over the intersection require the circuit-based variant. -- Semi-honest security by default. Malicious security requires additional ZK commitments proving the blinded set matches a committed set. -- Privacy degrades if a party submits a singleton set (reveals whether that element is in the other's set). Mitigate with a minimum set-size policy. -- **CROPS context**: Applies to both I2I and I2U. CR is `high` because both parties run the protocol directly without an intermediary that could censor or filter matches. In I2I, institutions execute the protocol bilaterally over an authenticated channel. In I2U, the user runs their side independently on commodity hardware. Privacy degrades from `full` to `partial` if either party submits a very small set, since intersection membership becomes attributable to specific elements. -- **Post-quantum exposure**: DDH assumption (commutative ECDH encryption) is broken by CRQC. Mitigation: lattice-based PSI protocols. See [Post-Quantum Threats](../domains/post-quantum.md). +- Equality-only: aggregates over the intersection require a circuit-based variant. +- Limited to two parties: for more than two, use an MPC-based variant. ## Example -- Bank A holds 500 ISINs it wants to buy. -- Bank B holds 300 ISINs it wants to sell. -- Both run ECDH-PSI bilaterally. -- They discover 12 ISINs overlap as potential trades. -- The remaining 488 and 288 non-overlapping ISINs stay hidden. -- The 12 matched ISINs feed into [ERC-7573 DvP](pattern-dvp-erc7573.md) for execution. +Bank A holds 500 ISINs it wants to buy and Bank B holds 300 ISINs it wants to sell. Both run the bilateral ECDH intersection protocol. They discover 12 ISINs overlap as potential trades; the remaining 488 and 288 non-overlapping identifiers stay hidden from the counterparty. The 12 matched ISINs feed into an ERC-7573 DvP flow for execution. ## See also -- [Private Set Intersection (OPRF-based)](pattern-private-set-intersection-oprf.md): OT/OPRF variant for large sets (10k+ elements) -- [Private Set Intersection (Circuit-based)](pattern-private-set-intersection-circuit.md): garbled circuit variant for computing functions over intersections -- [Private Set Intersection (FHE-based)](pattern-private-set-intersection-fhe.md): FHE variant for asymmetric set sizes with post-quantum security -- [Private Shared State (co-SNARKs)](pattern-private-shared-state-cosnark.md): MPC for ongoing shared state, vs one-shot matching here -- [VOPRF Nullifiers](pattern-voprf-nullifiers.md): OPRF is a building block in OT-based PSI variants -- [DvP (ERC-7573)](pattern-dvp-erc7573.md): downstream consumer, matched trade to settlement -- [Pre-trade Privacy Encryption](pattern-pretrade-privacy-encryption.md): alternative approach for pre-trade discovery -- [MPC Custody](pattern-mpc-custody.md): shares the MPC trust model family - -## See also (external) - -- [Google Private Join and Compute](https://github.com/google/private-join-and-compute): ECDH-PSI + homomorphic encryption for aggregate computation over intersections -- [OpenMined PSI](https://github.com/OpenMined/PSI): ECDH-PSI with Bloom filters, available in C++, Python, Go, and JavaScript -- [Encrypto Group PSI](https://github.com/encryptogroup/PSI): benchmarking implementations of multiple PSI protocol variants +- [RFC 9497: Oblivious Pseudorandom Functions (OPRFs) using Prime-Order Groups](https://datatracker.ietf.org/doc/rfc9497/) +- [Meadows 1986: A more efficient cryptographic matchmaking protocol for use in the absence of a continuously available third party](https://ieeexplore.ieee.org/document/6234898): early treatment of the DH-based intersection construction diff --git a/patterns/pattern-private-set-intersection-fhe.md b/patterns/pattern-private-set-intersection-fhe.md index 155cc53..c8d668b 100644 --- a/patterns/pattern-private-set-intersection-fhe.md +++ b/patterns/pattern-private-set-intersection-fhe.md @@ -1,87 +1,114 @@ --- title: "Pattern: Private Set Intersection (FHE-based)" status: draft -maturity: PoC +maturity: testnet +type: standard layer: offchain -privacy_goal: Two parties discover shared set elements using Fully Homomorphic Encryption, suited to asymmetric set sizes -assumptions: One party runs FHE encryption/decryption, the other evaluates a matching function homomorphically, LWE/RLWE hardness -last_reviewed: 2026-03-18 +last_reviewed: 2026-04-22 + works-best-when: - - Set sizes are asymmetric (one party holds a much larger set than the other) - - Minimal round count is critical (1-2 rounds; GC is also constant-round at 3-5) - - Post-quantum security from lattice assumptions is preferred (GC can also be PQ via PQ-secure OT) - - Labeled PSI is needed (return associated metadata for matched items) + - Set sizes are asymmetric (one party holds a much larger set than the other). + - Minimal round count matters (1 to 2 rounds per direction). + - Post-quantum security from lattice assumptions is preferred. + - Labelled PSI is needed (return associated metadata for matched items). avoid-when: - - Both sets are large and comparable in size (ciphertext expansion makes communication costly) - - Low-latency matching is needed (FHE evaluation is compute-intensive) - - Simple equality intersection on small sets suffices (DH-based variant is simpler) -dependencies: [BFV/BGV FHE scheme, polynomial evaluation, batching/SIMD encoding] + - Both sets are large and comparable in size (ciphertext expansion makes communication costly). + - Low-latency matching is critical (homomorphic evaluation is compute-intensive). + - Simple equality intersection on small sets suffices (the DH-based variant is simpler). + context: both +context_differentiation: + i2i: "Between institutions, either side can act as receiver by generating the key pair and encrypting its smaller set. Roles are typically negotiated bilaterally based on set sizes and compute capacity. Both institutions can re-run the protocol with roles reversed to learn the intersection symmetrically." + i2u: "For users, the user acts as receiver and decrypts on commodity hardware. The institution bears the heavier homomorphic evaluation cost. The user learns which of their own elements match; the institution learns nothing about non-matching user elements." + crops_profile: cr: high - os: yes - privacy: full - security: medium + o: yes + p: full + s: medium + +crops_context: + cr: "The receiver holds the decryption key and runs the protocol directly, with no intermediary controlling match results. No on-chain component is required, so chain-level censorship does not apply." + o: "Open-source homomorphic-encryption libraries and FHE-based PSI toolkits are available. Parameter selection and security-level calibration are publishable and reproducible." + p: "The sender sees only ciphertexts. The receiver learns which of their own elements match, not the sender's full set. Masking of non-matching positions prevents side-channel leakage through non-match values." + s: "Semi-honest by default. Malicious security requires zero-knowledge proofs over the sender's polynomial evaluation. Underlying LWE and RLWE assumptions provide post-quantum resistance." + +post_quantum: + risk: low + vector: "LWE and RLWE are the main post-quantum candidates for lattice cryptography; no known CRQC attack beats current lattice reductions. Transport and authentication around the protocol still use classical primitives that need PQ migration separately." + mitigation: "Keep LWE/RLWE parameters aligned with NIST post-quantum guidance and migrate channel authentication to PQ signatures. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + alternative_to: [pattern-private-set-intersection-dh, pattern-private-set-intersection-oprf, pattern-private-set-intersection-circuit] + composes_with: [pattern-dvp-erc7573, pattern-pretrade-privacy-encryption] + see_also: [pattern-private-shared-state-fhe, pattern-private-shared-state-cosnark, pattern-mpc-custody] + +open_source_implementations: + - url: https://github.com/microsoft/APSI + description: "Microsoft APSI: Asymmetric PSI library using homomorphic encryption, supports labelled PSI and sender payloads" + language: "C++" + - url: https://github.com/microsoft/SEAL + description: "Microsoft SEAL: BFV/BGV homomorphic encryption library used by APSI" + language: "C++" + - url: https://github.com/zama-ai/tfhe-rs + description: "Zama TFHE-rs: FHE library in Rust suitable for building custom FHE-PSI protocols" + language: "Rust" --- ## Intent -Two parties want to learn which elements they share without exposing non-matching entries. This variant uses Fully Homomorphic Encryption: one party (the receiver) encrypts their set under an FHE scheme and sends ciphertexts. The other party (the sender) homomorphically evaluates a matching function against their own plaintext set and returns encrypted results. The receiver decrypts to learn the intersection. For the sender to also learn results, the parties reverse roles and run a second round. FHE-based PSI suits asymmetric settings where one party holds a much larger set, and the low round count (1-2 rounds per direction) minimizes network latency. +Two parties want to learn which elements they share without exposing non-matching entries. This variant uses Fully Homomorphic Encryption: the receiver encrypts their set under an FHE scheme and sends the ciphertexts; the sender homomorphically evaluates a matching polynomial against its own plaintext set and returns masked encrypted results; the receiver decrypts to learn the intersection. The construction suits asymmetric set sizes, minimises round count, and reduces to LWE/RLWE hardness for post-quantum security. -## Ingredients +## Components -- **Cryptography**: BFV or BGV FHE scheme, polynomial evaluation for membership testing, SIMD/batching encoding -- **Infra**: Authenticated channel (TLS, Noise, or similar) -- **Off-chain**: Ephemeral computation. Sender bears the heavier compute load; receiver performs encryption and decryption. +- FHE scheme (BFV or BGV) with SIMD/batching encoding so multiple plaintexts pack into one ciphertext. +- Receiver's public and secret key pair, freshly generated per session. +- Authenticated channel for ciphertext transport in both directions. +- Sender-side matching polynomial construction, homomorphic evaluation, and randomised masking of result ciphertexts. +- Optional labelled-PSI extension that attaches encrypted payloads to matched items so the receiver also recovers associated metadata. ## Protocol -1. **Setup**: Parties agree on FHE parameters (scheme, polynomial modulus, plaintext modulus). The receiver generates a public/secret key pair. -2. **Encrypt**: The receiver encodes their m elements into FHE ciphertexts, sends them to the sender along with the public key. -3. **Evaluate**: The sender constructs a matching polynomial from their n elements and homomorphically evaluates it over each encrypted receiver element. The result encrypts zero for matches, a deterministic nonzero value otherwise. -4. **Mask**: The sender multiplies each result ciphertext by a fresh random nonzero scalar, ensuring non-matches decrypt to uniformly random values. -5. **Return**: The sender sends the masked encrypted result vector to the receiver. -6. **Decrypt**: The receiver decrypts. Zeros indicate intersection members; all other values indicate non-matches. -7. **Symmetric round** (optional): To let the sender also learn the intersection, the parties repeat steps 1-6 with reversed roles. +1. [counterparty] Parties agree on FHE parameters (scheme, polynomial modulus, plaintext modulus). The receiver generates a public and secret key pair. +2. [counterparty] The receiver encodes its m elements into FHE ciphertexts and sends them to the sender along with the public key. +3. [counterparty] The sender constructs a matching polynomial from its n elements and homomorphically evaluates it over each encrypted receiver element. The result encrypts zero for matches and a deterministic non-zero value otherwise. +4. [counterparty] The sender multiplies each result ciphertext by a fresh random non-zero scalar, ensuring non-matches decrypt to uniformly random values. +5. [counterparty] The sender returns the masked encrypted result vector to the receiver. +6. [counterparty] The receiver decrypts. Zeros indicate intersection members; all other values indicate non-matches. +7. [counterparty] Optional symmetric round: the parties repeat steps 1 to 6 with reversed roles so the sender also learns the intersection. + +## Guarantees & threat model + +Guarantees: + +- Input privacy: the sender sees only ciphertexts, the receiver learns matches on its own elements only. +- Post-quantum security at the cryptographic layer: reduces to LWE and RLWE, which resist known quantum attacks. +- Completeness: all shared elements are surfaced at the receiver's side (minimal false negatives). +- Soundness: randomised masking on the sender side keeps false positives negligible. -## Guarantees +Threat model: -- **Input privacy**: The sender sees FHE ciphertexts. The receiver learns which of their own elements match, not the sender's full set. -- **Post-quantum security**: Security reduces to LWE/RLWE, believed resistant to quantum attacks. -- **Completeness**: All shared elements are found (minimal false negatives). -- **Soundness**: Randomized masking in step 4 prevents false positives. -- **I2I**: A regulator screens an institution's client list against a watchlist without the institution revealing non-matching clients. -- **I2U**: A user checks whether their identifiers appear on an institutional eligibility list without revealing their full set. +- LWE and RLWE hardness at the chosen parameters, with parameter selection tracking post-quantum guidance. +- Honest key generation by the receiver and honest polynomial construction and masking by the sender. +- Authenticated transport around the ciphertext exchange; classical authentication layers still need separate PQ migration. +- Out of scope: statistical leakage from repeated sessions if the receiver reuses identical inputs without rerandomising. ## Trade-offs -- Ciphertext expansion is significant (orders of magnitude larger than plaintext). Communication cost scales with receiver set size, so the receiver should hold the smaller set. -- Homomorphic polynomial evaluation is compute-intensive on the sender side. Cost is roughly O(m * sqrt(n)) FHE multiplications. -- SIMD batching (packing multiple plaintexts per ciphertext) is essential for practical performance. -- The base protocol reveals the intersection to the receiver. A bilateral result requires a second round (step 7), doubling communication and compute. -- Labeled PSI extension: the sender attaches encrypted payloads to matched items, so the receiver decrypts both match status and associated metadata. -- Semi-honest security by default. Malicious security requires ZK proofs over the sender's polynomial evaluation. -- **CROPS context**: Applies to both I2I and I2U. CR is `high` because the receiver holds the decryption key and runs the protocol directly, with no intermediary controlling match results. In I2I, both institutions can initiate a round as receiver. In I2U, the user acts as receiver and decrypts on commodity hardware; the institution acts as sender and bears the heavier FHE evaluation cost. Security is `medium` (semi-honest by default); lattice-based assumptions (LWE/RLWE) provide post-quantum resistance. +- Ciphertext expansion is significant (orders of magnitude larger than plaintext). Communication scales with the receiver's set size, so the receiver should hold the smaller set. +- Homomorphic polynomial evaluation is compute-intensive on the sender side; cost is roughly O(m * sqrt(n)) FHE multiplications. +- SIMD batching is essential for practical performance. +- The base protocol reveals the intersection only to the receiver. A bilateral result requires a second round with reversed roles, doubling communication and compute. +- Semi-honest by default; malicious security requires zero-knowledge proofs over the sender's polynomial evaluation. ## Example -- A regulator holds a watchlist of 10k entities. -- A bank holds 2M client account identifiers. -- The regulator (receiver) encrypts its 10k identifiers under BFV and sends ciphertexts to the bank. -- The bank (sender) homomorphically evaluates the matching polynomial over the 10k encrypted identifiers against its 2M accounts. -- The bank returns masked encrypted results. -- The regulator decrypts and discovers 47 of its watchlist entities appear among the bank's clients. -- The bank learns nothing about the remaining 9,953 watchlist entries. To learn which clients matched, the parties run a symmetric round with reversed roles. +A regulator holds a watchlist of 10k entities and a bank holds 2M client account identifiers. The regulator acts as receiver and encrypts its 10k identifiers, sending the ciphertexts to the bank. The bank homomorphically evaluates the matching polynomial over the 10k encrypted identifiers against its 2M accounts and returns masked encrypted results. The regulator decrypts and discovers 47 of its watchlist entities appear among the bank's clients. The bank learns nothing about the remaining 9,953 watchlist entries. To learn which clients matched, the parties run a symmetric round with reversed roles. ## See also -- [Private Set Intersection (DH-based)](pattern-private-set-intersection-dh.md): symmetric-set variant using ECDH, simpler for small comparable sets -- [Private Shared State (FHE)](pattern-private-shared-state-fhe.md): FHE for ongoing shared state computation, vs one-shot matching here -- [Private Shared State (co-SNARKs)](pattern-private-shared-state-cosnark.md): MPC+ZK for ongoing shared state -- [Private Set Intersection (OPRF-based)](pattern-private-set-intersection-oprf.md): OT/OPRF variant for large symmetric sets -- [Private Set Intersection (Circuit-based)](pattern-private-set-intersection-circuit.md): garbled circuit variant for computing functions over intersections -- [DvP (ERC-7573)](pattern-dvp-erc7573.md): downstream consumer, matched trade to settlement -- [Pre-trade Privacy Encryption](pattern-pretrade-privacy-encryption.md): alternative approach for pre-trade discovery -- [Microsoft APSI](https://github.com/microsoft/APSI): Asymmetric PSI library using FHE (built on Microsoft SEAL), supports labeled PSI and sender payloads -- [Microsoft SEAL](https://github.com/microsoft/SEAL): Underlying BFV/BGV homomorphic encryption library used by APSI -- [TFHE-rs](https://github.com/zama-ai/tfhe-rs): Zama's FHE library in Rust, suitable for building custom FHE-PSI protocols +- [Chen, Laine, Rindal 2017: Fast Private Set Intersection from Homomorphic Encryption](https://eprint.iacr.org/2017/299) +- [Cong et al. 2021: Labeled PSI from Homomorphic Encryption with Reduced Computation and Communication](https://eprint.iacr.org/2021/1116) +- [NIST Post-Quantum Cryptography programme](https://csrc.nist.gov/projects/post-quantum-cryptography) diff --git a/patterns/pattern-private-set-intersection-oprf.md b/patterns/pattern-private-set-intersection-oprf.md index f4b833e..20192e4 100644 --- a/patterns/pattern-private-set-intersection-oprf.md +++ b/patterns/pattern-private-set-intersection-oprf.md @@ -1,89 +1,114 @@ --- title: "Pattern: Private Set Intersection (OPRF-based)" status: draft -maturity: PoC +maturity: testnet +type: standard layer: offchain -privacy_goal: Two parties discover shared set elements without revealing non-matching entries, scaling to millions of elements -assumptions: Bilateral communication channel, OT hardness, sets contain exact-match identifiers -last_reviewed: 2026-03-18 +last_reviewed: 2026-04-22 + works-best-when: - - Sets are large (10k to millions of elements) - - Bandwidth is constrained (cuckoo hashing compresses communication) - - Elements are exact-match identifiers (addresses, LEIs, wallet hashes) + - Sets are large (10k to millions of elements). + - Bandwidth is constrained (cuckoo hashing compresses communication). + - Elements are exact-match identifiers (addresses, LEIs, wallet hashes). avoid-when: - - Sets are very small (DH-based variant is simpler and sufficient) - - Need to compute aggregates over the intersection (use circuit-based variant) - - Fuzzy or approximate matching is required -dependencies: [OPRF (RFC 9497), OT extensions, cuckoo hashing] + - Sets are very small (the DH-based variant is simpler and sufficient). + - Aggregates over the intersection are required (use the circuit-based variant). + - Fuzzy or approximate matching is required. + context: both +context_differentiation: + i2i: "Between institutions, the protocol runs bilaterally over an authenticated channel with set sizes in the hundreds of thousands or millions. Parties pre-negotiate OPRF parameters and cuckoo-hash sizing, and typically wrap the protocol in legal agreements covering fair play." + i2u: "For end users, the user runs their side on commodity hardware. Minimum-set-size policies prevent the institution from turning the protocol into a yes/no oracle for a single user-submitted identifier. The user should only submit sets they can stand behind committing to in bulk." + crops_profile: cr: high - os: yes - privacy: full - security: medium + o: yes + p: full + s: medium + +crops_context: + cr: "Both parties run the protocol directly without an intermediary that could censor or filter matches. No on-chain component is required, so chain-level censorship does not apply." + o: "Open-source implementations exist across several languages; underlying OT extensions and cuckoo-hashing routines are standard." + p: "Non-intersecting elements are computationally hidden under OT hardness. Privacy degrades from `full` to `partial` when a party submits a very small set, because intersection membership becomes attributable to specific elements." + s: "Semi-honest by default. Malicious security requires a committed OPRF with a zero-knowledge proof per element, roughly doubling computation." + +post_quantum: + risk: medium + vector: "Base OT in standard OT-extension pipelines uses elliptic-curve primitives broken by a CRQC. OPRF evaluation itself is pseudorandom and resists quantum analysis once base OT is secure." + mitigation: "Swap base OT for a lattice-based or code-based post-quantum OT construction; the OT-extension layer and cuckoo hashing carry over unchanged. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + alternative_to: [pattern-private-set-intersection-dh, pattern-private-set-intersection-circuit, pattern-private-set-intersection-fhe] + composes_with: [pattern-dvp-erc7573, pattern-pretrade-privacy-encryption] + see_also: [pattern-voprf-nullifiers, pattern-mpc-custody, pattern-private-shared-state-cosnark] + +open_source_implementations: + - url: https://github.com/microsoft/APSI + description: "Microsoft APSI: asymmetric PSI library supporting labeled and unlabeled modes with unbalanced set sizes" + language: "C++" + - url: https://github.com/OpenMined/PSI + description: "OpenMined PSI: cardinality protocol based on ECDH and Bloom filters, with bindings for several languages" + language: "C++" + - url: https://github.com/encryptogroup/PSI + description: "Encrypto Group PSI: benchmarking suite for multiple PSI protocol variants including OT-based" + language: "C++" + - url: https://github.com/osu-crypto/libOTe + description: "libOTe: OT extension library underpinning many OPRF-PSI implementations" + language: "C++" --- ## Intent -Two parties each hold a private set of identifiers and want to learn which elements they share without exposing the rest. This variant uses Oblivious Pseudorandom Functions (OPRFs) built on Oblivious Transfer extensions. Each party acts as the OPRF evaluator for the other's inputs, producing pseudorandom tags that match only when the underlying elements match. Cuckoo hashing compresses communication to O(n + m) with small constants. The protocol scales to millions of elements where the DH-based variant becomes impractical. +Two parties each hold a private set of identifiers and want to learn which elements they share without exposing the rest. This variant uses Oblivious Pseudorandom Functions built on OT extensions: each party acts as the OPRF evaluator for the other's inputs, producing pseudorandom tags that match only when the underlying elements match. Cuckoo hashing compresses communication to O(n + m) with small constants, so the protocol scales to millions of elements where the DH-based variant becomes impractical. -## Ingredients +## Components -- **Cryptography**: OPRF (RFC 9497), OT extensions (IKNP or Silent OT), cuckoo hashing -- **Infra**: Authenticated bilateral channel (TLS, Noise, or similar) -- **Off-chain**: Ephemeral computation, no persistent infrastructure required +- OPRF construction (RFC 9497 or batched-OPRF) and an OT extension library (IKNP, Silent OT, or similar). +- Cuckoo hash tables with an agreed number of hash functions and stash slots, used by both parties to pack their inputs. +- Authenticated bilateral channel for OT base setup, OPRF evaluation, and tag exchange. +- Local matcher on each side that compares received OPRF tags against locally-computed tags to surface the intersection. ## Protocol -1. **Agree**: Parties A and B fix OPRF parameters, hash functions for cuckoo hashing, and a shared PRF output length. -2. **Hash**: Each party inserts its elements into a cuckoo hash table with k hash functions, producing fixed-size tables T_A and T_B. -3. **OPRF (A evaluates for B)**: A acts as the OPRF key holder with secret key k_A. B sends its table entries through an OT-based OPRF protocol. B receives PRF(k_A, y) for each y in T_B without A learning any y values. -4. **OPRF (B evaluates for A)**: B acts as the OPRF key holder with secret key k_B. A sends its table entries through the same OPRF protocol. A receives PRF(k_B, x) for each x in T_A without B learning any x values. -5. **Tag exchange**: A computes PRF(k_A, x) for its own elements and sends these tags to B. B computes PRF(k_B, y) for its own elements and sends these tags to A. -6. **Match**: Each party compares the tags it computed in the OPRF step against the tags received from the other party. Equal tags identify the intersection. -7. **Output**: Each party maps matched tags back to its own plaintext elements. Non-matching elements are hidden behind the other party's OPRF key. +1. [counterparty] Parties A and B agree OPRF parameters, cuckoo-hash functions, and tag length. +2. [counterparty] Each party inserts its elements into a cuckoo hash table, producing fixed-size tables. +3. [counterparty] A holds OPRF key k_A; B sends its table entries through an OT-based OPRF protocol and receives PRF(k_A, y) for each y without A learning y. +4. [counterparty] Roles reverse: B holds OPRF key k_B; A sends its table entries and receives PRF(k_B, x) for each x without B learning x. +5. [counterparty] A locally computes PRF(k_A, x) for its own elements and sends these tags to B. B does the same with PRF(k_B, y) and sends its tags to A. +6. [counterparty] Each party compares the tags it computed via the OPRF step against the tags the other party sent, and maps equal tags back to its own plaintext elements. + +## Guarantees & threat model + +Guarantees: + +- Input privacy: non-intersecting elements are computationally hidden under OT hardness and PRF security. +- Bilateral: runs directly between two parties over an authenticated channel. +- Completeness: all shared elements are found, assuming cuckoo insertion succeeds (negligible failure probability with stash slots). +- Soundness: zero false positives under a collision-resistant PRF. +- Scalability: O(n + m) communication with small constants; amortises well as sets grow. -## Guarantees +Threat model: -- **Input privacy**: Non-intersecting elements are computationally hidden under OT hardness. The OPRF ensures the evaluator learns just the PRF outputs. -- **Bilateral**: Runs directly between two parties over an authenticated channel. -- **Completeness**: All shared elements are found, assuming cuckoo hashing insertion succeeds (negligible failure probability). -- **Soundness**: Zero false positives (PRF collision probability is negligible). -- **Scalability**: O(n + m) communication with small constants. Handles large sets (millions of elements) efficiently. -- **I2I**: Custodians reconcile flagged-address lists, banks deduplicate client portfolios, or counterparties match large order books. -- **I2U**: A user checks a large eligibility list without the institution learning the user's other identifiers. +- OT and PRF security; in particular, the base OT must remain secure against the network adversary. +- Honest cuckoo construction by both parties. A malicious party can skew table layout to probe specific identifiers; commit-and-prove variants mitigate. +- Authenticated transport between the parties. +- Set-size hygiene: singleton or near-singleton submissions turn the protocol into a yes/no oracle on the submitted element. ## Trade-offs -- More complex to implement than the DH-based variant. Requires OT extension libraries and cuckoo hashing. -- O(n + m) communication, but with larger per-element constants than DH-based due to OT base setup. Amortizes well as set sizes grow. -- Semi-honest security by default. Malicious security requires a committed OPRF, which adds a zero-knowledge proof per element and roughly doubles computation. -- Cuckoo hashing introduces a small failure probability (element insertion fails). Stash slots or larger tables mitigate this at minor cost. -- Privacy degrades if a party submits a singleton set (reveals whether that element is in the other's set). Mitigate with a minimum set-size policy. -- **CROPS context**: Applies to both I2I and I2U. CR is `high` because both parties run the protocol directly without an intermediary that could censor or filter matches. In I2I, institutions execute the protocol bilaterally over an authenticated channel, with set sizes in the hundreds of thousands or millions. In I2U, the user runs their side independently on commodity hardware. Privacy degrades from `full` to `partial` if either party submits a very small set, since intersection membership becomes attributable to specific elements. +- More moving parts than the DH-based variant: an OT extension library and cuckoo-hashing machinery are required. +- Larger per-element constant factor than DH-based due to OT base setup, but linear communication amortises for large sets. +- Cuckoo hashing has a small insertion-failure probability. Stash slots or larger tables mitigate at minor cost. +- Equality-only: aggregates over the intersection require the circuit-based variant. ## Example -- Custodian A holds 500k wallet addresses flagged for compliance review. -- Custodian B holds 400k wallet addresses flagged under a different jurisdiction's rules. -- Both run OPRF-PSI bilaterally. -- They discover 8,200 addresses appearing on both flagged lists. -- The remaining 491,800 and 391,800 non-overlapping addresses are not disclosed. -- Matched addresses feed into a joint investigation workflow. +Two custodians hold flagged-address lists under different jurisdictions. Custodian A holds 500k addresses and Custodian B holds 400k. Both run the bilateral OPRF intersection protocol. They discover 8,200 addresses appearing on both lists; the remaining 491,800 and 391,800 non-overlapping entries are not disclosed. Matched addresses feed into a joint investigation workflow. ## See also -- [Private Set Intersection (DH-based)](pattern-private-set-intersection-dh.md): simpler variant for smaller sets (under 10k elements) -- [Private Set Intersection (Circuit-based)](pattern-private-set-intersection-circuit.md): garbled circuit variant for computing functions over intersections -- [Private Set Intersection (FHE-based)](pattern-private-set-intersection-fhe.md): FHE variant for asymmetric set sizes with post-quantum security -- [Private Shared State (co-SNARKs)](pattern-private-shared-state-cosnark.md): MPC for ongoing shared state, vs one-shot matching here -- [VOPRF Nullifiers](pattern-voprf-nullifiers.md): OPRF as a building block for unlinkable nullifier generation -- [DvP (ERC-7573)](pattern-dvp-erc7573.md): downstream consumer, matched trade to settlement -- [Pre-trade Privacy Encryption](pattern-pretrade-privacy-encryption.md): alternative approach for pre-trade discovery -- [MPC Custody](pattern-mpc-custody.md): shares the MPC trust model family -- [Microsoft APSI](https://github.com/microsoft/APSI): asymmetric PSI library supporting labeled and unlabeled modes with unbalanced set sizes -- [OpenMined PSI](https://github.com/OpenMined/PSI): PSI cardinality protocol based on ECDH and Bloom Filters, available in C++, Go, and Rust -- [Encrypto Group PSI](https://github.com/encryptogroup/PSI): benchmarking suite for multiple PSI protocol variants including OT-based -- [libOTe](https://github.com/osu-crypto/libOTe): OT extension library underpinning many OPRF-PSI implementations -- [Kolesnikov et al. 2016](https://eprint.iacr.org/2016/799): foundational paper on efficient batched OPRF for PSI -- [Pinkas et al. 2019](https://eprint.iacr.org/2019/241): circuit-PSI and OPRF-PSI with linear communication +- [RFC 9497: Oblivious Pseudorandom Functions (OPRFs) using Prime-Order Groups](https://datatracker.ietf.org/doc/rfc9497/) +- [Kolesnikov et al. 2016: Efficient Batched Oblivious PRF with Applications to Private Set Intersection](https://eprint.iacr.org/2016/799) +- [Pinkas et al. 2019: Efficient Circuit-based PSI with Linear Communication](https://eprint.iacr.org/2019/241) diff --git a/patterns/pattern-private-shared-state-cosnark.md b/patterns/pattern-private-shared-state-cosnark.md index a8ee31d..ec3e40d 100644 --- a/patterns/pattern-private-shared-state-cosnark.md +++ b/patterns/pattern-private-shared-state-cosnark.md @@ -1,82 +1,111 @@ --- title: "Pattern: Private Shared State (MPC + ZK / co-SNARKs)" status: draft -maturity: PoC +maturity: testnet +type: standard layer: hybrid -privacy_goal: Multiple parties jointly maintain shared state via collaborative ZK proving over secret-shared inputs -assumptions: co-SNARK protocol infrastructure, MPC network with honest majority, Ethereum L1/L2 for state-root anchoring -last_reviewed: 2026-03-11 +last_reviewed: 2026-04-22 + works-best-when: - - Multiple institutions share a ledger, pool, or order book and must hide individual positions from each other - - Cryptographic privacy guarantees are required (no hardware trust acceptable) - - Regulatory audit must be possible without exposing raw data to all participants + - Multiple institutions share a ledger, pool, or order book and must hide individual positions from each other. + - Cryptographic privacy guarantees are required (no hardware trust acceptable). + - Regulatory audit must be possible without exposing raw data to all participants. avoid-when: - - Single-party privacy is sufficient (use shielding instead) - - Sub-second latency is critical (MPC rounds + proving add batch latency) - - Fully trustless client-side proving with no external infrastructure dependency is required -dependencies: [co-SNARK protocols (e.g. TACEO), threshold cryptography, Groth16/STARK verifier] + - Single-party privacy is sufficient (use shielding instead). + - Sub-second latency is critical (MPC rounds plus proving add batch latency). + - Fully trustless client-side proving with no external infrastructure dependency is required. + context: both +context_differentiation: + i2i: "Between institutions, the MPC node set is typically operated by the consortium members themselves or by a neutral third party under SLA. Honest-majority risk is bounded by bilateral agreements and audit logs; legal recourse backs any collusion claim." + i2u: "For user-facing deployments the prover and MPC node set must be operator-diverse and ideally permissionless. A user has no recourse if a coalition silently reconstructs their witness. Economic bonding with slashing and publicly auditable proving logs are required to make the guarantee meaningful." + crops_profile: cr: medium - os: yes - privacy: full - security: medium + o: yes + p: full + s: medium + +crops_context: + cr: "Reaches `high` when the MPC prover network is permissionless and bond-backed. Drops to `low` when a single proving service controls the pipeline or when participation requires consortium membership." + o: "Core co-SNARK proving frameworks are published under permissive licenses. Production deployments may bundle proprietary orchestration and share-routing." + p: "No single MPC node or the verifier sees any party's plaintext inputs under the honest-majority assumption. Metadata about who participated, timing, and which circuit was proven can still leak." + s: "Rides on the soundness of the underlying SNARK (including any trusted-setup ceremony) and on the honest-majority assumption across MPC nodes. Dishonest majority leads to witness exposure and, in some constructions, forged proofs." + +post_quantum: + risk: high + vector: "Pairing-based SNARKs (Groth16, PLONK/KZG) broken by CRQC. MPC communication inherits the underlying key-exchange assumptions; HNDL risk applies to recorded MPC transcripts." + mitigation: "co-STARK alternatives with hash-based commitments. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + requires: [pattern-co-snark, pattern-zk-proof-systems] + composes_with: [pattern-stealth-addresses, pattern-regulatory-disclosure-keys-proofs, pattern-threshold-encrypted-mempool] + alternative_to: [pattern-private-shared-state-fhe, pattern-private-shared-state-tee] + see_also: [pattern-shielding, pattern-co-snark] + +open_source_implementations: + - url: https://github.com/TaceoLabs/co-snarks + description: "co-SNARK proving framework supporting Groth16 and PLONK (research/testnet)" + language: Rust --- ## Intent -Enable **N parties to jointly read and write shared on-chain state** (balances, positions, order books, collateral pools) while keeping each party's individual data private from the others **and** from the infrastructure operator. This variant uses **MPC + collaborative ZK proving (co-SNARKs)**: parties secret-share their inputs, jointly produce a ZK proof of correct state transition, and post the proof on-chain for verification. +Enable N parties to jointly read and write shared on-chain state (balances, positions, order books, collateral pools) while keeping each party's individual data private from the others and from the infrastructure operator. This variant secret-shares each party's inputs across a distributed prover network; the nodes jointly run an MPC protocol to compute a single zero-knowledge proof of a correct state transition; the proof is posted on-chain for verification. -Unlike single-party privacy (shielding), private shared state requires computation *across* multiple parties' secrets. +Unlike single-party shielding, private shared state requires computation across multiple parties' secrets. -## Ingredients +## Components -- **Cryptography**: co-SNARK protocols (e.g. [TACEO](https://core.taceo.io/)), secret sharing, Groth16/STARK proof systems -- **Infra**: MPC network for collaborative proving; Ethereum L1/L2 for state-root anchoring and settlement finality -- **On-chain**: Commitment schemes (Pedersen, Poseidon) for state representation; ZK verifier contract -- **Off-chain**: Secret-shared state storage; regulatory disclosure mechanism (selective ZK proofs or viewing keys) +- Secret-sharing layer splits each party's inputs (additive or Shamir) and routes shares to the proving network. +- Distributed prover network jointly runs the MPC protocol to compute a zero-knowledge proof without any node reconstructing the full witness. +- Coordinator sequences MPC rounds and assembles the final proof. +- Commitment scheme (Pedersen, Poseidon) represents the shared state as commitments anchored on-chain. +- On-chain verifier contract checks the proof and advances the state root on L1 or a settlement L2. +- Regulatory disclosure path produces selective zero-knowledge proofs or scoped viewing material for auditors without revealing other participants' data. ## Protocol -1. **Setup**: Parties establish MPC key shares and agree on proving circuit. -2. **Deposit**: Parties deposit assets into PSS contract; balances converted to secret-shared representation. -3. **Request**: A party submits a secret-shared state transition (transfer, trade, margin call). -4. **Compute**: MPC nodes jointly evaluate the transition and produce a collaborative ZK proof without any single node seeing plaintext inputs. -5. **Commit**: ZK proof and new state commitment posted on-chain; verifier contract checks correctness. -6. **Audit**: Regulators access scoped disclosure via selective ZK proofs without seeing all participants' data. +1. [user] Each participating institution secret-shares its inputs across the MPC prover network. +2. [user] A party submits a secret-shared state transition request (transfer, trade, margin call). +3. [prover] MPC nodes jointly execute the co-SNARK protocol, exchanging shares across rounds to compute witness polynomials and commitments without reconstructing any plaintext. +4. [prover] The coordinator assembles the final zero-knowledge proof and the new state commitment. +5. [contract] The on-chain verifier checks the proof and advances the state root. +6. [auditor] Regulator obtains scoped disclosure via a selective zero-knowledge proof or viewing key bound to a specific position. + +## Guarantees & threat model -## Guarantees +Guarantees: -- **Input privacy**: No party or MPC node learns another's balances, positions, or trade intent (honest-majority assumption). -- **State correctness**: On-chain ZK proof ensures transitions follow protocol rules. -- **Settlement finality**: Anchored to Ethereum L1/L2 for irreversibility. -- **Auditability**: Scoped disclosure path for regulators without full-state exposure. +- Input privacy: no party or MPC node learns another party's balances, positions, or trade intent under the honest-majority assumption. +- State correctness: the on-chain zero-knowledge proof enforces that every transition follows protocol rules. +- Settlement finality anchored to Ethereum L1 or an L2 for irreversibility. +- Scoped auditability through selective zero-knowledge proofs or disclosure keys. + +Threat model: + +- Soundness of the underlying SNARK and any trusted-setup ceremony. +- Honest-majority assumption across MPC nodes. A colluding majority can recover witnesses and, in some constructions, forge proofs. +- Non-censoring coordinator. A malicious coordinator can refuse to finalize or selectively drop requests; liveness fails, not privacy. +- Authenticated and confidential channels between nodes. Metadata about participation and timing is out of scope. +- Sender and receiver addresses are not hidden by default; address unlinkability requires composition with stealth addresses. ## Trade-offs -- Requires MPC network infrastructure with honest-majority assumption; dishonest majority leads to state corruption, not privacy loss. -- Batch latency from MPC rounds + proving (~200 TPS batched). -- Does not hide sender/receiver addresses by default; combine with [stealth addresses](pattern-stealth-addresses.md) for address unlinkability. -- Testnet maturity as of March 2026; UTXO shielding is production-ready but covers single-party privacy only. -- **Liveness**: MPC halts if fewer than the required quorum of nodes respond. Degrades to unavailability, not privacy loss. -- **CROPS context**: Applies to I2I (multi-party institutional computation). CR is `medium` because participation requires MPC network access but protocol-level guarantees exist. In I2I, institutions negotiate MPC node operation among themselves. If extended to I2U, end-users would depend on institutional MPC nodes with no independent fallback. -- **Post-quantum exposure**: Groth16-based co-SNARKs rely on pairings broken by CRQC. Mitigation: co-STARK alternatives. See [Post-Quantum Threats](../domains/post-quantum.md). +- Heavy communication overhead. Round count and bandwidth scale with both the number of provers and circuit size. +- Batch latency of several hundred milliseconds to seconds per transition; batched throughput in the low hundreds of TPS in current research stacks. +- Liveness depends on all designated nodes remaining online through the proving session. Dropouts force a restart. +- New infrastructure requirements: MPC nodes, share routing, key management, and slashing if bond-backed. +- Not a fit when sub-second latency is required or when a fully client-side proof is possible. ## Example -**Consortium Collateral Pool** - -- Three banks deposit tokenised bonds into a shared collateral pool on an Ethereum L2. -- Each bank's deposit amount is secret-shared across MPC nodes. -- A margin call triggers collaborative ZK proving: the MPC network verifies sufficient aggregate collateral without revealing individual positions. -- A ZK proof and new state commitment root are posted on-chain. -- The regulator uses a selective ZK proof to audit one bank's position without learning the others'. +- Three banks share a tokenised-bond collateral pool on an Ethereum settlement L2. Each bank's deposit is secret-shared across the MPC prover network. A margin call triggers a joint co-SNARK run: the network produces one zero-knowledge proof attesting that aggregate collateral covers the exposure without revealing any individual position. The proof and the new state commitment are posted on-chain. A regulator later audits one bank's position via a scoped selective proof without learning the others. ## See also -- [co-SNARKs (Collaborative Proving)](pattern-co-snark.md): The underlying collaborative proving primitive -- [Private Shared State (FHE)](pattern-private-shared-state-fhe.md): FHE-based alternative -- [Private Shared State (TEE)](pattern-private-shared-state-tee.md): TEE-based alternative -- [Shielding](pattern-shielding.md): Single-party UTXO privacy (not shared state) -- [Threshold Encrypted Mempool](pattern-threshold-encrypted-mempool.md): Threshold encryption for transaction privacy -- Vendor: [TACEO Merces](../vendors/taceo-merces.md): PSS reference implementation (co-SNARKs) +- [TACEO Merces](../vendors/taceo-merces.md) +- [Collaborative zk-SNARKs (Ozdemir & Boneh, 2021)](https://eprint.iacr.org/2021/1530.pdf) +- [TACEO private proof delegation](https://core.taceo.io/articles/private-proof-delegation/) diff --git a/patterns/pattern-private-shared-state-fhe.md b/patterns/pattern-private-shared-state-fhe.md index 6fc6ab5..251af94 100644 --- a/patterns/pattern-private-shared-state-fhe.md +++ b/patterns/pattern-private-shared-state-fhe.md @@ -1,81 +1,112 @@ --- title: "Pattern: Private Shared State (FHE)" status: draft -maturity: PoC +maturity: testnet +type: standard layer: hybrid -privacy_goal: Multiple parties jointly maintain shared state via fully homomorphic encryption over encrypted on-chain data -assumptions: FHE coprocessor infrastructure, threshold decryption network, Ethereum L1/L2 for state-root anchoring -last_reviewed: 2026-03-11 +last_reviewed: 2026-04-22 + works-best-when: - - Multiple institutions share a ledger, pool, or order book and must hide individual positions from each other - - Computation on encrypted state must happen without decrypting (homomorphic operations) - - Higher throughput is needed compared to MPC+ZK (500-1000 TPS shared across apps) + - Multiple institutions share a ledger, pool, or order book and must hide individual positions from each other. + - Computation on encrypted state must happen without decrypting intermediate values. + - Higher batched throughput is needed than MPC-plus-ZK approaches can offer. avoid-when: - - Single-party privacy is sufficient (use shielding instead) - - Sub-second latency is critical (FHE computation overhead is high) - - No tolerance for threshold decryption committee trust -dependencies: [FHE schemes (TFHE/BFV), threshold decryption network, Ethereum L1/L2] + - Single-party privacy is sufficient (use shielding instead). + - Sub-second latency is critical (Fully Homomorphic Encryption overhead is high). + - No tolerance for a threshold decryption committee in the trust model. + context: both +context_differentiation: + i2i: "The threshold decryption committee and the Fully Homomorphic Encryption coprocessor are typically operated by consortium members or a neutral third party under SLA. Committee collusion risk is bounded by contractual controls and committee diversity; institutions can enforce geographic and legal separation." + i2u: "For user-facing deployments the threshold committee must be operator-diverse so that no coalition can decrypt user state. A user has no recourse if the committee silently releases decryption material. Committee rotation, transparent key ceremonies, and bond-backed participation matter more than in the i2i setting." + crops_profile: cr: medium - os: partial - privacy: full - security: medium + o: partial + p: full + s: medium + +crops_context: + cr: "Protocol-level participation is open but requires access to a Fully Homomorphic Encryption coprocessor and the decryption committee. Drops to `low` when a single operator controls both. Reaches `high` only when the coprocessor and committee are permissionless or bond-backed." + o: "Reference Fully Homomorphic Encryption libraries are open source under permissive licenses. Production coprocessors often bundle proprietary optimisations, orchestration, and hosted decryption services." + p: "No plaintext is exposed during computation, including to the coprocessor operator, under the threshold-committee assumption. A breach of the committee above the threshold leaks all encrypted state; metadata about callers and timing remains visible on-chain." + s: "Rides on the hardness assumptions of the Fully Homomorphic Encryption scheme (typically LWE-based), correct distributed key generation, and honest-threshold behaviour of the decryption committee." + +post_quantum: + risk: low + vector: "Lattice-based Fully Homomorphic Encryption schemes (TFHE, BFV, CKKS) rely on LWE, which is not broken by known quantum algorithms. Side-channel risk and parameter choice still matter." + mitigation: "Track NIST-selected lattice parameter sets and any quantum-side-channel guidance. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + composes_with: [pattern-stealth-addresses, pattern-regulatory-disclosure-keys-proofs, pattern-threshold-encrypted-mempool] + alternative_to: [pattern-private-shared-state-cosnark, pattern-private-shared-state-tee] + see_also: [pattern-shielding, pattern-co-snark, pattern-private-set-intersection-fhe] + +open_source_implementations: + - url: https://github.com/zama-ai/fhevm + description: "Zama fhEVM, Fully Homomorphic Encryption runtime for EVM contracts (testnet)" + language: "Solidity, Rust" + - url: https://github.com/zama-ai/tfhe-rs + description: "TFHE-rs, pure-Rust implementation of TFHE primitives used by coprocessors" + language: Rust --- ## Intent -Enable **N parties to jointly read and write shared on-chain state** (balances, positions, order books, collateral pools) while keeping each party's individual data private from the others **and** from the infrastructure operator. This variant uses **fully homomorphic encryption (FHE)**: state is stored encrypted on-chain, computation happens directly on ciphertexts via an FHE coprocessor, and a threshold decryption network controls read access. +Enable N parties to jointly read and write shared on-chain state (balances, positions, order books, collateral pools) while keeping each party's individual data private from the others and from the infrastructure operator. This variant stores state encrypted on-chain under a shared Fully Homomorphic Encryption key, runs state transitions as homomorphic operations on ciphertexts, and controls reads through a threshold decryption committee. -Unlike single-party privacy (shielding), private shared state requires computation *across* multiple parties' secrets. +Unlike single-party shielding, private shared state requires computation across multiple parties' secrets. -## Ingredients +## Components -- **Cryptography**: FHE schemes (TFHE, BFV); threshold decryption network for controlled reads -- **Infra**: FHE coprocessor (e.g. [Zama fhEVM](https://www.zama.ai/), [Fhenix](https://www.fhenix.io/)); Ethereum L1/L2 for state-root anchoring and settlement finality -- **On-chain**: Encrypted state representation; FHE computation contracts -- **Off-chain**: Threshold decryption committee; regulatory disclosure mechanism (decryption keys scoped to regulator) +- Fully Homomorphic Encryption scheme (for example TFHE or BFV) supporting the target state-transition circuit on encrypted data. +- Shared public key generated via distributed key generation by a threshold decryption committee; the matching secret is never assembled in one place. +- Fully Homomorphic Encryption coprocessor evaluates state transitions on ciphertexts and emits updated encrypted state plus a correctness proof. +- Threshold decryption committee jointly decrypts scoped read requests for participants or auditors. +- On-chain state store holds encrypted balances and commitments; a verifier contract anchors the correctness proof. +- Regulatory disclosure path issues threshold-controlled decryption keys scoped to a specific position or time window. ## Protocol -1. **Setup**: Parties establish shared threshold FHE key via distributed key generation (DKG). -2. **Deposit**: Parties deposit assets into PSS contract; balances encrypted under the shared FHE key. -3. **Request**: A party submits an encrypted state transition (transfer, trade, margin call). -4. **Compute**: FHE coprocessor processes the transition homomorphically on ciphertexts without decrypting. -5. **Commit**: Updated encrypted state and correctness proof posted on-chain. -6. **Audit**: Regulators access scoped disclosure via threshold-controlled decryption keys. +1. [user] The threshold committee runs a distributed key generation and publishes the shared Fully Homomorphic Encryption public key. +2. [user] Each party deposits assets; balances are encrypted under the shared key and posted as on-chain ciphertexts. +3. [user] A party submits an encrypted state-transition request (transfer, trade, margin call). +4. [prover] The coprocessor evaluates the transition homomorphically on ciphertexts and produces the updated encrypted state plus a correctness proof. +5. [contract] The verifier contract checks the proof and commits the new encrypted state root. +6. [auditor] Regulators or participants request scoped reads; the committee performs threshold decryption bound to the approved scope. + +## Guarantees & threat model -## Guarantees +Guarantees: -- **Input privacy**: Computations happen on encrypted data; no party or coprocessor sees plaintext. -- **State correctness**: FHE computation preserves correctness; results verifiable on-chain. -- **Settlement finality**: Anchored to Ethereum L1/L2 for irreversibility. -- **Auditability**: Threshold-controlled decryption provides scoped regulator access. +- No plaintext is exposed during computation, including to the coprocessor operator, under the threshold-committee assumption. +- State correctness is enforced by the coprocessor's correctness proof verified on-chain. +- Settlement finality anchored to Ethereum L1 or an L2. +- Scoped auditability via threshold-controlled decryption for specific positions or windows. + +Threat model: + +- Hardness of the underlying lattice assumption and correct parameter choice. +- Honest-threshold behaviour of the decryption committee. A breach above the threshold leaks all encrypted state bulk-decryption capability. +- Coprocessor correctness. A malicious coprocessor without a correctness proof could post invalid state; the proof-verifier contract mitigates this. +- Metadata about callers, contract addresses, and timing remains visible on-chain. +- Sender and receiver addresses are not hidden by default; address unlinkability requires composition with stealth addresses. ## Trade-offs -- FHE computation overhead is high (latency); batching helps throughput (500-1000 TPS shared across apps). -- Threshold decryption committee must be online for any state read; breach leads to bulk decryption of all encrypted state. -- Zama fhEVM is partially open source; FHE coprocessors have proprietary components (OS: `partial`). -- Does not hide sender/receiver addresses by default; combine with [stealth addresses](pattern-stealth-addresses.md) for address unlinkability. -- Testnet maturity as of March 2026. -- **Liveness**: FHE requires the threshold decryption committee to be online for any state read. Degrades to unavailability, not privacy loss, on liveness failure. -- **CROPS context**: Applies to I2I (multi-party institutional computation). CR is `medium` because protocol-level participation is open but requires FHE coprocessor access. In I2I, institutions negotiate coprocessor operation. If extended to I2U, end-users would depend on institutional FHE infrastructure with no independent verification of computation correctness. +- Fully Homomorphic Encryption computation overhead is high per operation; batching and coprocessor-level optimisations are required to reach useful throughput. +- The threshold committee must be online for any read; offline committee degrades to unavailability, not privacy loss. +- Ciphertext size and on-chain storage cost are larger than plaintext or commitment-only state. +- Tooling and developer experience are less mature than Solidity with plaintext state; constrained language subsets and specific coprocessor APIs apply. ## Example -**Consortium Collateral Pool** - -- Three banks deposit tokenised bonds into a shared collateral pool on an Ethereum L2 with FHE support. -- Each bank's deposit amount is encrypted under the shared FHE key. -- A margin call triggers homomorphic computation: the FHE coprocessor verifies sufficient aggregate collateral on encrypted balances. -- Updated encrypted state is posted on-chain. -- The regulator uses a threshold-controlled decryption key to audit one bank's position without learning the others'. +- Three banks share a tokenised-bond collateral pool on an Ethereum L2 with Fully Homomorphic Encryption support. Each bank's deposit is encrypted under the shared key; on-chain state is fully ciphertext. A margin call triggers the coprocessor to evaluate aggregate collateral coverage homomorphically and emit the updated encrypted state. The regulator uses a threshold-controlled decryption key to audit one bank's position without learning the others. ## See also -- [Private Shared State (co-SNARKs)](pattern-private-shared-state-cosnark.md): MPC+ZK alternative -- [Private Shared State (TEE)](pattern-private-shared-state-tee.md): TEE-based alternative -- [Shielding](pattern-shielding.md): Single-party UTXO privacy (not shared state) -- [Threshold Encrypted Mempool](pattern-threshold-encrypted-mempool.md): Threshold encryption for transaction privacy -- Vendor: [Zama](../vendors/zama.md): FHE infrastructure provider +- [Zama](../vendors/zama.md) +- [Fhenix](../vendors/fhenix.md) +- [Zama fhEVM documentation](https://docs.zama.ai/fhevm) diff --git a/patterns/pattern-private-shared-state-tee.md b/patterns/pattern-private-shared-state-tee.md index dac61ab..aeba876 100644 --- a/patterns/pattern-private-shared-state-tee.md +++ b/patterns/pattern-private-shared-state-tee.md @@ -1,82 +1,114 @@ --- title: "Pattern: Private Shared State (TEE)" status: draft -maturity: pilot +maturity: testnet +type: standard layer: hybrid -privacy_goal: Multiple parties jointly maintain shared state inside hardware enclaves with attestation-verified execution -assumptions: Attested TEE infrastructure (SGX/SEV/Nitro), Ethereum L1/L2 for state-root anchoring, participants accept hardware trust -last_reviewed: 2026-03-11 +last_reviewed: 2026-04-22 + works-best-when: - - Multiple institutions share a ledger, pool, or order book and must hide individual positions from each other - - Low latency is required (TEE execution speed comparable to native) - - Participants accept hardware trust assumptions with contractual controls + - Multiple institutions share a ledger, pool, or order book and must hide individual positions from each other. + - Low latency is required and participants accept hardware trust assumptions. + - Contractual and audit controls can bound hardware-vendor and host-operator risk. avoid-when: - - Single-party privacy is sufficient (use shielding instead) - - Threat model includes nation-state physical access or supply-chain compromise - - Full trustlessness required (prefer co-SNARKs or FHE alternatives) -dependencies: [TEE platforms (SGX/SEV-SNP/Nitro), attestation infrastructure, Ethereum L1/L2] + - Single-party privacy is sufficient (use shielding instead). + - The threat model includes nation-state physical access or supply-chain compromise. + - Full trustlessness is required; prefer the co-SNARK or Fully Homomorphic Encryption variants. + context: both +context_differentiation: + i2i: "Between institutions, hardware trust is bounded by contractual controls (NDAs, audit rights, attestation logging) and by running enclaves across diverse operators. The consortium can standardise enclave code, measurement values, and rotation policy." + i2u: "For user-facing deployments a single-operator enclave gives the user no independent verification of integrity. A coalition of host plus hardware vendor can observe plaintext. Threshold keys across multiple independent enclave operators, combined with zero-knowledge proofs of correct execution, are required to make the guarantee meaningful." + crops_profile: cr: low - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "Host controls enclave availability and can deny service. Hardware-vendor dependency on attestation roots is unavoidable; users cannot route around a vendor revocation. Remains `low` even with multiple host operators." + o: "Enclave guest code can be fully open source and reproducibly built. TEE hardware, firmware, and attestation services remain proprietary; drivers and microcode updates are vendor-controlled." + p: "Plaintext is exposed inside the enclave during execution. Privacy holds only against the host operator and co-tenants; the hardware vendor and a physical attacker with sufficient capability can observe or extract state. Side-channels (cache timing, Spectre-family) remain an active research area." + s: "Rides on enclave measurement correctness, timely firmware patching, and attestation-chain integrity. Remote attestation catches configuration drift but not silent microcode backdoors." + +post_quantum: + risk: medium + vector: "Remote attestation typically uses elliptic-curve signatures (ECDSA, EdDSA) broken by CRQC. Recorded attestation reports and sealed blobs face HNDL risk if encrypted to vendor-operated key hierarchies." + mitigation: "Migrate attestation signing and sealing keys to post-quantum signatures (ML-DSA, SLH-DSA) as vendors ship them. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + requires: [pattern-tee-based-privacy] + composes_with: [pattern-tee-zk-settlement, pattern-tee-key-manager, pattern-stealth-addresses, pattern-regulatory-disclosure-keys-proofs] + alternative_to: [pattern-private-shared-state-cosnark, pattern-private-shared-state-fhe] + see_also: [pattern-shielding, pattern-co-snark] + +open_source_implementations: + - url: https://github.com/oasisprotocol/sapphire-paratime + description: "Confidential EVM runtime running under TEE with attested execution" + language: "Rust, Solidity" + - url: https://github.com/automata-network/multi-prover-avs + description: "Attested multi-prover infrastructure usable as a TEE execution backend" + language: "Go, Rust" --- ## Intent -Enable **N parties to jointly read and write shared on-chain state** (balances, positions, order books, collateral pools) while keeping each party's individual data private from the others. This variant uses **trusted execution environments (TEEs)**: encrypted state is decrypted inside hardware enclaves, computation happens at native speed, and attestation proves correct execution. +Enable N parties to jointly read and write shared on-chain state (balances, positions, order books, collateral pools) while keeping each party's individual data private from the others. This variant stores state encrypted to an enclave public key; a Trusted Execution Environment decrypts inputs, runs the state transition at native speed, and posts updated encrypted state plus a remote-attestation report proving which code ran. -Unlike single-party privacy (shielding), private shared state requires computation *across* multiple parties' secrets. +Unlike single-party shielding, private shared state requires computation across multiple parties' secrets. -## Ingredients +## Components -- **Hardware**: TEE platforms — Intel SGX (process-level enclaves), AMD SEV-SNP (VM-level), or AWS Nitro Enclaves (hypervisor-isolated) -- **Infra**: Attestation verification service; Ethereum L1/L2 for state-root anchoring and settlement finality -- **On-chain**: Commitment schemes (Pedersen, Poseidon) for state representation; optional ZK verifier for TEE+ZK hybrid -- **Off-chain**: Encrypted state blobs; enclave-mediated regulatory access +- Trusted execution environment: Intel SGX (process-level), AMD SEV-SNP (VM-level), or AWS Nitro Enclaves (hypervisor-isolated). Each imposes a different threat model and attestation chain. +- Enclave guest code implements the state-transition logic and holds the decrypted state only for the duration of a transition. +- Remote attestation service binds the enclave's measurement (code hash plus configuration) to a signed attestation report that participants and the on-chain verifier can check. +- Commitment scheme (Pedersen, Poseidon) represents state on-chain; an optional zero-knowledge proof hybrid proves correct execution beyond attestation. +- On-chain state store and verifier contract anchor attested state updates; a fallback hybrid path verifies a zero-knowledge proof of execution. +- Regulatory disclosure path uses enclave-mediated decryption scoped to specific positions or time windows. ## Protocol -1. **Setup**: Parties deploy attested TEE cluster; verify enclave measurements and platform configuration. -2. **Deposit**: Parties deposit assets into PSS contract; balances encrypted to enclave public key. -3. **Request**: A party submits an encrypted state transition (transfer, trade, margin call) to the enclave. -4. **Compute**: TEE decrypts inputs, processes the transition at native speed, produces encrypted outputs. -5. **Commit**: State commitment and optional correctness proof posted on-chain. -6. **Audit**: Regulators access scoped disclosure via enclave-mediated decryption. +1. [operator] Deploy the attested enclave cluster; publish enclave measurements and attestation public keys. +2. [user] Each party verifies attestation, then deposits assets; balances are encrypted to the enclave public key. +3. [user] A party submits an encrypted state-transition request to the enclave. +4. [operator] The enclave decrypts inputs, executes the transition at native speed, and emits the updated encrypted state plus an attestation report. +5. [contract] The on-chain verifier checks the attestation (and, in the hybrid variant, a zero-knowledge proof of correct execution) and updates the state root. +6. [auditor] Regulator requests scoped disclosure; the enclave decrypts only the approved scope and emits a signed disclosure record. + +## Guarantees & threat model -## Guarantees +Guarantees: -- **Input privacy**: Data confidential from other parties and from the host operator (under TEE assumptions). Hardware vendor holds potential access via master keys. -- **State correctness**: Attestation proves code and configuration match expectations. For stronger guarantees, combine with ZK proofs ([TEE+ZK Settlement](pattern-tee-zk-settlement.md)). -- **Settlement finality**: Anchored to Ethereum L1/L2 for irreversibility. -- **Auditability**: Enclave-mediated scoped disclosure for regulators. +- Inputs and intermediate state remain confidential from other parties and from the host operator, subject to the enclave assumptions. +- Remote attestation binds every state transition to a specific code measurement and configuration. +- Settlement finality anchored to Ethereum L1 or an L2. +- Enclave-mediated scoped disclosure for regulators. + +Threat model: + +- Enclave integrity, including resistance to cache-timing and transient-execution side-channels. Constant-time code and timely firmware patching are required mitigations. +- Hardware-vendor trust: vendor master keys and attestation-chain integrity are unavoidable roots of trust. +- Host-operator availability: the host can schedule or refuse to schedule the enclave; privacy is unaffected, liveness is not. +- Physical access and supply-chain compromise are out of scope for the bare TEE variant; combine with a zero-knowledge execution proof for stronger guarantees. +- Sender and receiver addresses are not hidden by default; address unlinkability requires composition with stealth addresses. ## Trade-offs -- Host/operator controls enclave availability; can deny service. Hardware vendor dependency for attestation roots (CR: `low`). -- Privacy depends on TEE integrity; hardware vendor can observe plaintext during execution (privacy: `partial`). Contractual controls (NDA, audit rights) mitigate this in institutional settings. -- Fastest to deploy (pilot maturity); lowest latency of the three PSS variants. -- Enclave code can be open source, but TEE hardware and firmware are proprietary (OS: `partial`). -- Side-channel attacks (cache timing, Spectre) are documented risks; constant-time code and firmware patching mitigate. -- Does not hide sender/receiver addresses by default; combine with [stealth addresses](pattern-stealth-addresses.md) for address unlinkability. -- **Liveness**: TEE depends on the host continuing to schedule the enclave. Degrades to unavailability, not privacy loss, on liveness failure. -- **CROPS context**: Applies to I2I (multi-party institutional computation). In I2U, CR drops further — institution operates the TEE and end-user has no independent verification of enclave integrity, making privacy dependent on institutional trust. Security improves with TEE+ZK combination or threshold keys across multiple independent TEE instances. +- Lowest latency of the private-shared-state variants; execution runs at near-native speed inside the enclave. +- Hardware trust is a hard dependency. Contractual controls and enclave-operator diversity mitigate but do not remove it. +- Attestation-verification gas cost on-chain is non-trivial and varies by platform. +- Side-channel exposure is a moving target; assume ongoing firmware maintenance and code hardening. +- Hybrid designs that add a zero-knowledge proof of correct execution reduce hardware dependence at the cost of proving overhead. ## Example -**Consortium Collateral Pool** - -- Three banks deposit tokenised bonds into a shared collateral pool on an Ethereum L2. -- Each bank's deposit amount is encrypted to the TEE cluster's public key. -- A margin call triggers enclave computation: the TEE decrypts balances, verifies sufficient aggregate collateral, and produces encrypted results. -- A state commitment is posted on-chain; attestation logs prove correct execution. -- The regulator uses enclave-mediated access to audit one bank's position without learning the others'. +- Three banks share a tokenised-bond collateral pool on an Ethereum settlement L2. Each bank's deposit is encrypted to the enclave cluster's public key. A margin call triggers enclave computation: the enclave decrypts inputs, evaluates aggregate collateral coverage at native speed, and emits the updated encrypted state with an attestation report. The regulator uses enclave-mediated disclosure to audit one bank's position without learning the others. ## See also -- [Private Shared State (co-SNARKs)](pattern-private-shared-state-cosnark.md): MPC+ZK alternative (cryptographic trust) -- [Private Shared State (FHE)](pattern-private-shared-state-fhe.md): FHE alternative (cryptographic trust) -- [TEE-Based Privacy](pattern-tee-based-privacy.md): Foundational TEE trust model and failure modes -- [Hybrid TEE + ZK Settlement](pattern-tee-zk-settlement.md): TEE execution with ZK verification for stronger guarantees -- [Shielding](pattern-shielding.md): Single-party UTXO privacy (not shared state) +- [Oasis Sapphire ParaTime](https://oasisprotocol.org/sapphire) +- [Intel SGX documentation](https://www.intel.com/content/www/us/en/developer/tools/software-guard-extensions/overview.html) +- [AWS Nitro Enclaves documentation](https://docs.aws.amazon.com/enclaves/latest/user/nitro-enclave.html) diff --git a/patterns/pattern-private-stablecoin-shielded-payments.md b/patterns/pattern-private-stablecoin-shielded-payments.md index 5bf9693..8da434b 100644 --- a/patterns/pattern-private-stablecoin-shielded-payments.md +++ b/patterns/pattern-private-stablecoin-shielded-payments.md @@ -1,64 +1,121 @@ --- title: "Pattern: Private Stablecoin Shielded Payments" status: ready -maturity: pilot +maturity: testnet +type: standard layer: L2 -privacy_goal: Stakeholder-only stablecoin transfers with view-key/proof-based disclosure for regulators -assumptions: Privacy L2 (Aztec/Zama/Fhenix), wallet/KMS integration, optional L1 anchoring -last_reviewed: 2026-01-14 +last_reviewed: 2026-04-22 + works-best-when: - - Cash leg must be private (amounts + counterparties) with selective disclosure. - - You need Ethereum‑native tooling (L2/app‑chain) and interop with PvP or DvP. + - The cash leg must be private in both amounts and counterparties, with selective disclosure available to auditors. + - Ethereum-native tooling on an L2 or app-chain is preferred, with composability into PvP or DvP flows. avoid-when: - - Public transparency is required by design, or batch netting off‑chain suffices. -dependencies: [ERC-20, ERC-3643, ERC-7573, Attestations] + - Public transparency of the cash leg is required by policy. + - Off-chain netting already satisfies the confidentiality requirement. + context: both +context_differentiation: + i2i: "Between institutions the issuer and both counterparties are KYC-aligned with legal recourse. Permissioned shielded pools and ERC-3643 gating preserve unlinkability within the consortium while viewing keys cover audit. Issuer-level controls (freeze, blacklist) are negotiated contractually and bounded by governance." + i2u: "For end users the cash leg must not depend on an issuer who can freeze balances unilaterally or on an operator who can block withdrawals. Forced withdrawal and user-controlled viewing keys are required to make the privacy guarantee meaningful; without them, censorship resistance collapses to `low`." + crops_profile: cr: medium - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "Reaches `medium` when the privacy L2 has a permissionless exit path and no single issuer can freeze balances without governance. Drops to `low` when issuer controls (freeze, blacklist) are unconstrained or when the L2 has operator-controlled exit." + o: "Shielded-pool contracts and zero-knowledge circuits are typically open source. Fully Homomorphic Encryption coprocessors and hosted issuer tooling often include proprietary components." + p: "Amounts, counterparties, and memos are hidden from non-participants. Viewing keys and selective disclosure proofs cover auditors. Network-layer metadata (timing, gas payer, IP) remains visible unless combined with a network-anonymity pattern." + s: "Rides on the soundness of the underlying proof system or Fully Homomorphic Encryption scheme, the honesty of any threshold decryption committee, and the integrity of the L2 state root anchored to L1." + +post_quantum: + risk: high + vector: "Pairing-based shielded pools (Groth16, PLONK/KZG) broken by CRQC. HNDL risk applies to encrypted notes and any long-lived audit log encrypted under classical asymmetric keys." + mitigation: "Migrate to STARK-based shielded pools with hash commitments; re-encrypt long-lived audit logs under post-quantum key encapsulation. See [Post-Quantum Threats](../domains/post-quantum.md)." + +visibility: + counterparty: [amounts, identities, memos] + chain: [commitments, nullifiers] + regulator: [full_tx with viewing key] + public: [] + +standards: [ERC-20, ERC-3643, ERC-7573, EIP-5564] + +related_patterns: + requires: [pattern-shielding] + composes_with: [pattern-stealth-addresses, pattern-dvp-erc7573, pattern-private-pvp-stablecoins-erc7573, pattern-erc3643-rwa, pattern-regulatory-disclosure-keys-proofs, pattern-verifiable-attestation, pattern-user-controlled-viewing-keys] + see_also: [pattern-privacy-l2s, pattern-l2-encrypted-offchain-audit, pattern-forced-withdrawal, pattern-network-anonymity] + +open_source_implementations: + - url: https://github.com/AztecProtocol/aztec-packages + description: "Privacy L2 with private notes and viewing keys for programmable confidential tokens" + language: Noir + - url: https://github.com/zama-ai/fhevm + description: "Confidential ERC-20 reference implementations running on a Fully Homomorphic Encryption coprocessor" + language: "Solidity, Rust" --- ## Intent -Provide **stakeholder‑only** stablecoin transfers on Ethereum (L2/app‑chain acceptable) with **view‑key/proof‑based disclosure** for regulators and auditors, and the ability to compose atomically with asset legs (DvP) or other cash legs (PvP). - -## Ingredients -- **Standards:** [ERC‑20](https://eips.ethereum.org/EIPS/eip-20) (cash), optional [ERC‑3643](https://eips.ethereum.org/EIPS/eip-3643) (holder gating), [ERC‑7573](https://ercs.ethereum.org/ERCS/erc-7573) (atomic settlement triggers), [Attestations](pattern-verifiable-attestation.md) (audit/compliance). -- **Infra:** Privacy L2/app‑chain: - - **Programmable privacy (ZK):** [Aztec](https://docs.aztec.network/) — private notes + view keys. - - **FHE approaches:** [Zama fhEVM](https://www.zama.ai/post/confidential-erc-20-tokens-using-homomorphic-encryption), [Fhenix L2/coFHE](https://www.fhenix.io/) (encrypted balances/amounts). Note that FHE alone doesn't provide sender/receiver anonymity, needs to be paired with with **[ERC-5564 Stealth Addresses](https://eips.ethereum.org/EIPS/eip-5564)** (or equivalent) to hide payer/payee identities. -- **Wallet/KMS:** Custodial or MPC; issuer admin keys for freeze/blacklist if mandated. -- **Optional:** L1 anchoring of encrypted audit log; oracles for cutoffs. - -## Protocol (concise) -1. **Gate access (optional):** KYC issuers/custodians attest allow‑listed participants via [attestations](pattern-verifiable-attestation.md) and/or enforce via [ERC‑3643](https://eips.ethereum.org/EIPS/eip-3643). -2. **Mint/Wrap:** Issuer mints native private‑mode stablecoin or wraps ERC‑20 into confidential form (ZK/FHE). -3. **Shielded transfer:** Payer creates a private transfer (encrypted note); only payer, payee (and permitted auditor) can view **amount + counterparty**. -4. **Selective disclosure:** Auditor/regulator obtains scoped view via viewing key or ZK proof; access is logged via [attestations](pattern-verifiable-attestation.md). -5. **(Optional) Atomicity:** Couple with asset leg via [ERC‑7573](https://ercs.ethereum.org/ERCS/erc-7573) for DvP, or with other cash leg for PvP. -6. **(Optional) Anchor & archive:** Post commitment roots/hashes to L1; store encrypted append‑only audit trail off‑chain. - -## Guarantees -- **Hides:** amounts, counterparties, and memos from non‑participants; reveals only to stakeholders. -- **Atomicity:** DvP (cash↔asset) or PvP (cash↔cash) when combined with ERC‑7573. -- **Auditability:** Verifiable access events via EAS; issuer controls for policy enforcement. + +Provide stakeholder-only stablecoin transfers on an L2 or app-chain, with viewing-key or zero-knowledge-proof-based disclosure to regulators and auditors, and the ability to compose atomically with asset legs (DvP) or other cash legs (PvP). Hide amounts, counterparties, and memos from non-participants while still enforcing any issuer-level or regulatory policy bound to the stablecoin. + +## Components + +- Confidential cash token: either a native private-mode stablecoin or a wrapped form of a public ERC-20 held inside a shielded pool or under encrypted balances. +- Privacy L2 or app-chain: programmable-privacy zero-knowledge L2 (private notes plus viewing keys) or a Fully Homomorphic Encryption runtime (encrypted balances and amounts). +- Stealth-address layer (ERC-5564) to hide payer and payee identities in the Fully Homomorphic Encryption case, since encrypted balances alone do not anonymise counterparties. +- Issuer controls bound to ERC-3643 or equivalent gating: allow-listing, freeze, blacklist where mandated by policy. +- Atomic-settlement hook via ERC-7573 to compose the cash leg with an asset leg (DvP) or another cash leg (PvP). +- Audit and disclosure layer: viewing keys, selective zero-knowledge disclosure proofs, or threshold-decryption keys for regulators; on-chain attestations (EAS) log access events. +- Wallet or custody module, optionally MPC-based; issuer admin keys where policy requires. +- Optional L1 anchor of the encrypted audit log and cutoff oracles. + +## Protocol + +1. [operator] Optional gating: KYC issuers or custodians attest allow-listed participants via verifiable attestations and enforce ERC-3643 eligibility at mint and transfer. +2. [operator] Mint a native private-mode stablecoin or wrap a public ERC-20 into confidential form (shielded pool or encrypted-balance token). +3. [user] Construct a shielded transfer: generate an encrypted note or ciphertext so that only the payer, payee, and any permitted auditor can view amount and counterparty. +4. [contract] Verify the transfer (zero-knowledge proof or homomorphic evaluation), update commitments or encrypted balances, and record any nullifiers. +5. [auditor] Obtain a scoped view via the payee's viewing key or a selective zero-knowledge disclosure proof; access is logged via attestations. +6. [contract] Optional atomic leg: compose with ERC-7573 to settle DvP against a tokenised asset leg or PvP against another cash leg. +7. [operator] Optional: post commitment roots and encrypted audit log hashes to L1 and archive the append-only audit trail off-chain. + +## Guarantees & threat model + +Guarantees: + +- Hides amounts, counterparties, and memos from non-participants; reveals only to stakeholders in the transfer and any permitted auditor. +- Atomic DvP (cash against asset) or PvP (cash against cash) when composed with ERC-7573. +- Verifiable audit trail via attestations; issuer controls enforce policy without exposing transfer contents. + +Threat model: + +- Soundness of the underlying proof system or Fully Homomorphic Encryption scheme. +- Honesty of the L2 sequencer or prover and of any threshold decryption committee. +- Non-compromised relayer and paymaster. A colluding relayer can link user IPs to shielded activity; a colluding paymaster can selectively censor. +- Unconstrained issuer controls (freeze, blacklist without governance) break the guarantee for users; address at the policy layer. +- Network-layer metadata (timing, gas payer, IP) is out of scope and must be covered by a network-anonymity pattern. ## Trade-offs -- **Cost/latency:** Private proofs (ZK/FHE) add overhead; choose L2/app‑chain accordingly. -- **DX:** Non‑EVM L2s (e.g., Aztec) require new tooling (Noir); FHE stacks may rely on co‑processors/oracles. -- **Leakage:** Timing/ordering metadata may persist; mitigate with batching/delayed anchors. -- **Non‑fit:** **Stealth addresses** ([ERC‑5564](https://eips.ethereum.org/EIPS/eip-5564)) hide recipients but **do not** provide issuer‑level policy or full cash‑flow privacy alone. -- **CROPS context (both)**: In I2U, CR drops to `low` if issuer freeze/blacklist is unconstrained and user has no L1 exit path. Privacy reaches `full` if regulator disclosure is opt-in (user controls viewing keys) rather than mandatory. In I2I, banks negotiate issuer controls contractually. + +- Zero-knowledge or Fully Homomorphic Encryption proofs add per-transfer cost and latency compared with a public ERC-20 transfer. +- Developer experience varies: non-EVM privacy L2s require circuit DSLs; Fully Homomorphic Encryption stacks depend on coprocessors and oracles. +- Timing and ordering metadata can persist even when contents are hidden; mitigate with batching or delayed anchors. +- Stealth addresses alone do not provide issuer-level policy or full cash-flow privacy; they complement, rather than replace, a shielded cash token. +- Monotonic on-chain growth: commitments or ciphertexts accumulate indefinitely; prover or coprocessor costs drift up over time. ## Example -- A dealer pays weekend margin in a **private USDC‑like** token on a privacy L2; the venue receives funds without public leakage; the regulator gets read‑only access via a time‑bound viewing key; the payment leg participates in an **ERC‑7573** PvP with EUR stablecoin or DvP with tokenized UST collateral. + +- A dealer pays weekend margin in a confidential stablecoin on a privacy L2. The venue receives funds without public leakage. The regulator gets read-only access via a time-bound viewing key. The payment leg participates in an ERC-7573 PvP against another stablecoin or a DvP against tokenised collateral. ## See also -- `pattern-dvp-erc7573.md` · `pattern-l2-encrypted-offchain-audit.md` · `pattern-aztec-privacy-l2-erc7573.md` · `pattern-confidential-erc20-fhe-l2-erc7573.md` -## Prior art / references -- Canton weekend repo (USDC cash leg, atomic settlement): [press](https://www.canton.network/canton-network-press-releases/digital-asset-complete-on-chain-us-treasury-financing) -- Aztec programmable privacy: [docs](https://docs.aztec.network/) -- Zama confidential ERC‑20: [post](https://www.zama.ai/post/confidential-erc-20-tokens-using-homomorphic-encryption) -- Fhenix encrypted computation (coFHE): [overview](https://blog.arbitrum.io/fhenix-private-computation/) \ No newline at end of file +- [Aztec](../vendors/aztec.md) +- [Zama](../vendors/zama.md) +- [Fhenix](../vendors/fhenix.md) +- [Canton Network press release on weekend USDC cash leg](https://www.canton.network/canton-network-press-releases/digital-asset-complete-on-chain-us-treasury-financing) +- [Aztec programmable-privacy documentation](https://docs.aztec.network/) +- [Zama confidential ERC-20 overview](https://www.zama.ai/post/confidential-erc-20-tokens-using-homomorphic-encryption) +- [Fhenix encrypted computation overview](https://blog.arbitrum.io/fhenix-private-computation/) diff --git a/patterns/pattern-private-transaction-broadcasting.md b/patterns/pattern-private-transaction-broadcasting.md index eff0fcb..cd4bd4a 100644 --- a/patterns/pattern-private-transaction-broadcasting.md +++ b/patterns/pattern-private-transaction-broadcasting.md @@ -1,124 +1,125 @@ --- title: "Pattern: Private Transaction Broadcasting" status: draft -maturity: pilot +maturity: production +type: standard layer: hybrid -privacy_goal: Prevent MEV extraction and intent leakage during transaction submission -assumptions: Private relay/builder infrastructure or threshold encryption committee available -last_reviewed: 2026-01-14 +last_reviewed: 2026-04-22 + works-best-when: - - Transaction content must not leak before block inclusion - - MEV protection is required for large institutional trades - - Competitive intelligence exposure is a concern + - Transaction content must stay hidden from the public mempool until block inclusion to prevent MEV extraction. + - Large institutional trades must not signal intent to competitors before settlement. + - A block-inclusion latency overhead of tens to low hundreds of milliseconds is acceptable. avoid-when: - - Public transparency is required by policy or regulation - - Immediate inclusion guarantees are critical (private routes may have lower priority) -dependencies: [Flashbots Protect, Shutter Network, SUAVE] + - Public transparency of the pending transaction is required by policy or regulation. + - Hard real-time inclusion guarantees are required and fallback to the public mempool is unacceptable. + context: both +context_differentiation: + i2i: "Between institutions the relay or threshold committee can be contracted under SLA with diverse operators, audit logging, and an escalation path. Reputational and legal recourse bound the risk of a relay that peeks at or reorders transactions." + i2u: "For end users the relay or threshold committee is operated by parties the user cannot audit. Protection strength depends on cryptographic enforcement (threshold decryption) rather than reputation, and on the availability of a fallback path that does not silently leak the transaction to the public mempool." + crops_profile: cr: medium - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "Private relays can refuse individual transactions; censorship resistance depends on relay diversity and on a fallback path. Threshold-encrypted mempools reach `high` once a wide validator set enforces inclusion of encrypted payloads." + o: "Core relay and threshold-decryption software is typically open source. Builder and relay operations often include proprietary orchestration and commercial MEV-capture logic." + p: "Content is hidden from public mempool observers until inclusion. A compromised relay or a threshold committee above the threshold can reveal content early. Sender address and gas payer are typically visible even during the pending phase." + s: "Relay-based variants rely on reputational and contractual enforcement. Threshold-encrypted variants rely on the honest-threshold assumption of the decryption committee and on timely decryption after inclusion." + +post_quantum: + risk: medium + vector: "Threshold-encryption schemes built on pairings or elliptic-curve key agreement are broken by CRQC; recorded encrypted transactions face HNDL risk. Relay authentication channels typically use TLS with classical key exchange." + mitigation: "Migrate threshold-encryption and relay authentication to post-quantum primitives (lattice-based KEMs and signatures) as the ecosystem ships them. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + composes_with: [pattern-threshold-encrypted-mempool, pattern-pretrade-privacy-encryption, pattern-focil-eip7805, pattern-mixnet-anonymity, pattern-onion-routing] + alternative_to: [pattern-shielding] + see_also: [pattern-modular-privacy-stack, pattern-network-anonymity] + +open_source_implementations: + - url: https://github.com/flashbots/mev-boost + description: "MEV-Boost relay infrastructure used by the majority of Ethereum validators" + language: Go + - url: https://github.com/shutter-network/rolling-shutter + description: "Threshold-encrypted mempool reference stack (production on Gnosis Chain)" + language: Go --- ## Intent -Hide transaction content from the public mempool to prevent front-running, sandwich attacks, and competitive intelligence extraction. Transactions are submitted through private channels and only become visible after block inclusion, eliminating the window where adversaries can observe and exploit pending trades. +Hide transaction content from the public mempool before inclusion so that front-runners, sandwich bots, and competitors cannot observe or exploit pending trades. Transactions are routed through private relays or published as ciphertexts decrypted only after ordering, so adversaries see the transaction only once it is committed to a block. -## Ingredients +## Components -- **Standards**: None required (infrastructure-level pattern) -- **Infra**: - - Private transaction relays (Flashbots Protect, MEV Blocker) - - Encrypted mempools with threshold decryption (Shutter Network) - - Intent-based execution pools (SUAVE) -- **Off-chain**: - - RPC endpoint configuration for private submission - - Optional: bundle submission for atomic multi-tx execution - - Wallet/custody integration for private RPC routing +- Private relay network that accepts signed transactions from users and forwards them to participating block builders under contractual or protocol rules. +- Builder set that includes privately-routed transactions in blocks without republishing them to the public mempool. +- Threshold decryption committee (for encrypted-mempool variants) that reveals transaction content only after the block containing it is committed. +- Client-side encryption library for threshold-encrypted submissions. +- RPC or wallet integration that routes traffic to the private endpoint with a configurable fallback policy. +- Optional MEV-redistribution mechanism that returns part of any extracted value to the originator. -## Protocol (concise) +## Protocol -### Variant A: Private Relay (Flashbots Protect) +### Variant A: Private relay -1. User signs transaction locally with standard tooling. -2. Submit transaction to private RPC endpoint instead of public mempool. -3. Relay forwards to participating block builders under NDA/protocol rules. -4. Builder includes transaction in block without broadcasting to public mempool. -5. Transaction appears on-chain only after block confirmation. -6. Optional: MEV-Share returns portion of extracted value to user if MEV occurred. +1. [user] Sign the transaction locally with standard tooling. +2. [user] Submit the signed transaction to a private RPC endpoint instead of the public mempool. +3. [relayer] Forward the transaction to participating block builders under the relay's operating rules. +4. [validator] Include the transaction in a block without re-broadcasting to the public mempool. +5. [contract] Execute the transaction; its content becomes visible only after on-chain inclusion. +6. [relayer] Optionally return a share of extracted MEV to the originator via an MEV-sharing mechanism. -### Variant B: Encrypted Mempool (Shutter) +### Variant B: Threshold-encrypted mempool -1. User encrypts transaction payload using threshold public key. -2. Encrypted transaction submitted to mempool (content hidden, metadata visible). -3. Transaction included in block by builder/proposer. -4. After inclusion commitment, threshold committee decrypts transaction. -5. Decrypted transaction executed; content revealed only post-inclusion. -6. Front-running prevented as content was hidden during ordering phase. +1. [user] Encrypt the transaction payload under the committee's threshold public key. +2. [user] Submit the ciphertext to the mempool; metadata (sender, gas, size) is visible but content is not. +3. [validator] Include the ciphertext in a block to commit its ordering. +4. [operator] After inclusion commitment, the threshold committee publishes decryption shares. +5. [validator] Validators reconstruct the plaintext and execute the transaction. +6. [contract] Execution proceeds with ordering already fixed, so front-running based on observed content is impossible. -## Guarantees +## Guarantees & threat model -- **Hides**: Transaction content (to, value, calldata) from public mempool observers during pending phase. -- **Prevents**: Front-running, sandwich attacks, just-in-time liquidity attacks, intent signaling to competitors. -- **Does not hide**: Transaction details after on-chain inclusion; sender address may still be visible depending on implementation. -- **Atomicity**: Same as underlying L1/L2; private submission does not change execution semantics. -- **Censorship**: Private relays may refuse transactions; fallback to public mempool available. +Guarantees: -## Trade-offs - -- **Trust model**: - - Flashbots: Trust that relay/builders honor privacy commitments (reputational + contractual enforcement). - - Shutter: Trust threshold committee (cryptographic enforcement, k-of-n threshold security). -- **Latency**: May add 10-100ms for relay routing; encrypted mempool adds decryption step. -- **Inclusion priority**: Private transactions may have lower priority than direct builder submissions. -- **Coverage**: MEV-Boost covers ~90% of Ethereum blocks; Flashbots relay handles ~70% of MEV-Boost blocks. -- **Failure mode**: If private relay unavailable, transaction can fallback to public mempool (losing privacy) or fail (losing liveness). -- **Cost**: Some private relay services charge fees or take MEV share; Shutter requires threshold committee infrastructure. -- **CROPS context (both)**: In I2U, end-users depend on relay operators they cannot audit. In I2I, institutions can contractually bind relay operators and run their own relay infrastructure. +- Transaction content (target, value, calldata) is hidden from public mempool observers during the pending phase. +- Front-running, sandwiching, and just-in-time-liquidity attacks based on pre-inclusion observation are prevented. +- In the threshold-encrypted variant, ordering is committed before content is revealed, so ordering cannot depend on the plaintext. +- Execution semantics are unchanged from direct submission; the pattern is a transport change, not an execution change. -## Example +Threat model: -**Institutional Stablecoin Transfer** +- In the relay variant: a colluding relay or builder can observe content; protection reduces to contractual and reputational enforcement. +- In the threshold variant: a committee above the decryption threshold can reveal content before inclusion, defeating the guarantee. +- Sender address and gas payer are typically visible during the pending phase. +- A fallback to the public mempool on relay unavailability can silently leak the transaction; the fallback policy must be explicit. +- Post-inclusion transaction details are fully public; this pattern does not provide shielded amounts or counterparties. -1. Bank A needs to transfer $50M USDC to Bank B for settlement. -2. Submitting to public mempool would signal large transfer intent to competitors and MEV searchers. -3. Bank A configures custody system to route through Flashbots Protect RPC. -4. Transaction submitted privately; not visible in any public mempool explorer. -5. Block builder includes transaction in next block. -6. Competitors and MEV bots see the transfer only after on-chain confirmation. -7. Result: No front-running, no sandwich attacks, no advance warning to market. - -**RFQ Settlement with Encrypted Mempool** +## Trade-offs -1. Dealer wins RFQ to sell 1000 ETH to institutional buyer. -2. Settlement transaction encrypted using Shutter threshold key. -3. Encrypted payload submitted to Gnosis Chain mempool. -4. Validators include encrypted transaction in block. -5. After block finalization, threshold committee decrypts and executes. -6. Competing dealers cannot front-run or copy trade. +- Block-inclusion latency overhead in the tens to low hundreds of milliseconds, plus a decryption step for the threshold variant. +- Inclusion priority depends on the relay's agreements with builders; private routes may see higher variance in inclusion time than direct builder submissions. +- Relay coverage varies over time; users should monitor live coverage metrics rather than assume a fixed figure. +- The threshold variant requires a decryption committee infrastructure and adds a liveness dependency. +- Cost model varies: some relay services are free, others take a share of MEV or charge fees. -## Performance Characteristics +## Example -- **Network**: Ethereum L1, Gnosis Chain (Shutter), L2s with private mempool support -- **Latency**: +10-100ms vs public mempool submission -- **Cost**: Varies by provider; Flashbots Protect is free, MEV-Share takes percentage -- **Coverage**: ~90% of Ethereum blocks use MEV-Boost relays; Shutter live on Gnosis -- **Failure rate**: <1% relay unavailability; fallback paths available +- A bank settles a large institutional stablecoin transfer by routing through a private relay so the transfer does not appear in any public mempool explorer. The block builder includes the transaction; competitors and MEV bots observe it only after confirmation. +- A dealer wins an RFQ and submits the settlement transaction encrypted under a threshold key. Validators commit the ciphertext to a block. Only after inclusion does the committee publish decryption shares, after which the transaction executes. Competing dealers cannot front-run or copy-trade the order. ## See also -- [Pre-trade Privacy (Shutter/SUAVE)](pattern-pretrade-privacy-encryption.md) -- [FOCIL Inclusion Lists](pattern-focil-eip7805.md) - Censorship resistance complement -- [Vendor: Flashbots](../vendors/flashbots.md) -- [Vendor: Shutter](../vendors/shutter.md) -- [Approach: Private Broadcasting](../approaches/approach-private-broadcasting.md) - -## See also (external) - -- Flashbots Protect: https://docs.flashbots.net/flashbots-protect/overview -- Flashbots MEV-Share: https://docs.flashbots.net/flashbots-mev-share/overview -- Shutter Network: https://docs.shutter.network/ -- MEV Blocker: https://mevblocker.io/ -- SUAVE: https://writings.flashbots.net/the-future-of-mev-is-suave +- [Flashbots](../vendors/flashbots.md) +- [Shutter](../vendors/shutter.md) +- [Flashbots Protect documentation](https://docs.flashbots.net/flashbots-protect/overview) +- [Flashbots MEV-Share documentation](https://docs.flashbots.net/flashbots-mev-share/overview) +- [Shutter Network documentation](https://docs.shutter.network/) +- [MEV Blocker](https://mevblocker.io/) diff --git a/patterns/pattern-private-vaults.md b/patterns/pattern-private-vaults.md index 7b6a989..9aa5f96 100644 --- a/patterns/pattern-private-vaults.md +++ b/patterns/pattern-private-vaults.md @@ -1,68 +1,111 @@ --- title: "Pattern: Private Intent-Based Vaults" status: draft -maturity: PoC +maturity: testnet +type: standard layer: hybrid -privacy_goal: Hide strategy parameters and order flow while keeping deposited assets auditable -assumptions: FHE-enabled chain or privacy L2, intent relayers/solvers, compliance oracles -last_reviewed: 2026-01-14 +last_reviewed: 2026-04-22 + works-best-when: - - Institutions or funds need private strategy execution while assets remain transparently custodied. - - Strategies are automated or intent-driven and should not leak parameters to competitors. + - Institutions or funds need private strategy execution while deposited assets remain transparently custodied. + - Strategies are intent-driven or automated and parameters must not leak to competitors. + - Auditors can be served via viewing keys or attestation logs without public disclosure of strategy details. avoid-when: - - Full on-chain transparency of strategy or yield composition is a regulatory requirement. - - Low gas environments or limited privacy infra availability. -dependencies: [ERC-20, ERC-7573, EAS, Zama FHE SDK, Oracles] + - Regulation requires full on-chain transparency of strategy composition and yield sources. + - The target chain lacks mature privacy infrastructure and low-cost confidential computation. + context: both +context_differentiation: + i2i: "Between institutions, vault operators and solvers are typically known and contractually bound. LPs can demand audit rights, independent verification of solver code, and attested execution logs. Residual risk (misrouted flow, solver front-running) is bounded by legal recourse." + i2u: "For users, vault operators are third parties the user cannot audit. Censorship resistance is low because withdrawal typically depends on operator cooperation. Permissionless entry, open-source solver code, a forced-exit path, and multiple competing solvers are required to raise the guarantee above `low`." + crops_profile: cr: low - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "Stays `low` as long as entry, exit, or solver selection depend on a single operator. Rises when vault entry is permissionless, multiple independent solvers compete, and a forced-exit path allows redemption without operator cooperation." + o: "Vault contracts are typically open source. Solver logic and strategy engines may be proprietary; the confidential-computation substrate (Fully Homomorphic Encryption coprocessor, enclave, or privacy L2) varies in openness." + p: "Strategy parameters, intent content, and order flow are hidden from the public. Aggregate on-chain state (AUM, performance) remains visible. A breach at the solver, key manager, or privacy substrate can expose strategy data wholesale." + s: "Rides on the confidentiality of the substrate (Fully Homomorphic Encryption, enclave, or shielded execution), correct solver key management, and intent signature verification. Misconfigured access control is a common failure mode." + +post_quantum: + risk: medium + vector: "Elliptic-curve signatures on intents (ECDSA, EdDSA) broken by CRQC. Encrypted intents and solver key hierarchies built on classical public-key encryption face HNDL risk." + mitigation: "Migrate intent signatures to post-quantum signatures and encrypt long-lived intent archives under post-quantum KEMs as the ecosystem ships them. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [ERC-20, ERC-7573] + +related_patterns: + requires: [pattern-verifiable-attestation] + composes_with: [pattern-private-shared-state-fhe, pattern-private-shared-state-tee, pattern-privacy-l2s, pattern-pretrade-privacy-encryption, pattern-dvp-erc7573, pattern-regulatory-disclosure-keys-proofs] + see_also: [pattern-shielding, pattern-forced-withdrawal, pattern-private-transaction-broadcasting] + +open_source_implementations: + - url: https://github.com/zama-ai/fhevm + description: "Fully Homomorphic Encryption runtime suitable as a private-vault substrate (testnet)" + language: "Solidity, Rust" + - url: https://github.com/AztecProtocol/aztec-packages + description: "Privacy L2 usable as a programmable-privacy substrate for confidential strategy execution" + language: Noir --- ## Intent -Enable institutional or DeFi actors to **express trading or allocation intents** that are executed by a vault **privately** — hiding strategy parameters, order flow, and risk exposure while keeping deposited assets auditable and redeemable. +Allow institutional and DeFi actors to express trading or allocation intents that a vault executes privately: strategy parameters, order flow, and risk exposure stay hidden while deposited assets remain transparently custodied and redeemable. Auditors receive scoped disclosure; the public sees only aggregate state. -## Ingredients +## Components -- **Standards:** ERC-20 (underlying asset), optional ERC-7573 (atomic execution), EAS (attestations / audit proofs). -- **Infra:** Private L2 or FHE-enabled chain (e.g., Zama, Fhenix). -- **Off-chain Services:** Intent relayers / solvers, strategy engine, compliance oracles, and KMS for encrypted strategy data. +- Vault contract (ERC-20 wrapper) holds deposits transparently and exposes a redeem path for LPs and auditors. +- Encrypted intent: signed envelope containing target allocation, yield strategy, or hedging goal. Encrypted to the solver or to a confidential-computation substrate. +- Solver or strategy engine runs off-chain or inside a confidential runtime, converting intents into an execution plan. +- Confidential-computation substrate provides the privacy guarantee for the strategy. Options: Fully Homomorphic Encryption coprocessor, Trusted Execution Environment, or a privacy L2 with private notes. +- Execution layer: trades and allocations run on a privacy L2 or on a Fully Homomorphic Encryption runtime so order flow does not appear publicly. +- Audit and disclosure layer: viewing keys and attestation-logged scoped disclosure (EAS) let regulators and LPs verify execution authenticity without revealing strategy composition. +- Optional key-management module for encrypted strategy data and for solver credentials. ## Protocol -1. **Deposit:** User or institution deposits assets into an intent-based vault (ERC-20 wrapper). -2. **Intent submission:** Depositor submits an **encrypted intent** (target allocation, yield strategy, or hedging goal). -3. **Solver/engine:** Off-chain or enclave executor decrypts or partially computes the intent to generate an execution plan. -4. **Execution:** Vault executes trades or allocations privately on a privacy L2 or FHE runtime. -5. **Settlement:** Results (profits/losses) are reflected on-chain; only aggregate state is public. -6. **Audit:** Regulator or auditor can verify correctness via viewing key or EAS-logged disclosure. +1. [user] Deposit assets into the vault; on-chain state records the deposit transparently. +2. [user] Submit a signed encrypted intent (for example, a target allocation or hedging rule) to the solver or substrate. +3. [prover] Solver or confidential runtime decrypts or partially computes the intent and produces an execution plan without exposing parameters. +4. [operator] Vault executes the plan privately on a privacy L2 or a Fully Homomorphic Encryption runtime; order flow stays hidden. +5. [contract] Settlement updates aggregate vault state on-chain; individual positions and strategy details remain private. +6. [auditor] Regulator or LP verifies correctness via a viewing key or an attestation-logged disclosure, without seeing strategy composition. + +## Guarantees & threat model + +Guarantees: + +- Strategy logic, parameters, and order flow stay hidden from the public and from competitors. +- Vault asset balances and aggregate performance remain auditable on-chain. +- Intents are cryptographically signed; solvers cannot alter user intent without detection. +- Scoped disclosure lets regulators verify execution authenticity without revealing strategy composition. -## Guarantees +Threat model: -- **Privacy:** Strategy logic and parameters remain hidden; vault asset balances visible. -- **Integrity:** Intents are cryptographically signed and cannot be altered by solvers. -- **Auditability:** Regulator or LP can verify execution authenticity without revealing details. +- Confidentiality of the chosen substrate (Fully Homomorphic Encryption, enclave, privacy L2). A substrate breach exposes strategy data in bulk. +- Solver correctness and key hygiene. A compromised solver can leak intent content or front-run the execution plan. +- Misconfigured access control on viewing keys or attestation logs can turn scoped disclosure into public disclosure. +- Solver liveness. A single solver becomes a censorship chokepoint; multiple competing solvers mitigate. +- Timing and ordering metadata at the execution layer can leak strategy signals even when content is hidden; compose with private transaction broadcasting. ## Trade-offs -- **Performance:** FHE or privacy L2 introduces latency and higher gas cost. -- **Complexity:** Requires secure off-chain computation and intent relayer coordination. -- **Risk:** Misconfigured access control or key leakage may expose strategy data. -- **CROPS context (both)**: In I2U, CR is especially low -- end-user depends entirely on vault operator for strategy execution and redemption. OS improves if solver is open source and auditable. CR improves with permissionless vault entry and multiple competing solvers. +- Confidential computation adds latency and cost compared with transparent vault execution. +- Operational complexity: off-chain solver, encrypted intent pipeline, and privacy substrate together create a larger attack surface than a transparent vault. +- Auditor onboarding requires careful viewing-key or attestation scope design to avoid over-disclosure. +- Composability with public DeFi is limited while assets sit inside the privacy substrate; an exit step is required for public venues. ## Example -- A fund deposits USDC into a private intent-based vault. -- It submits an encrypted intent: _“allocate 60% to ETH yield strategy, 40% to staked T-Bills.”_ -- The vault solver computes trades privately via Zama FHE and executes them. -- On-chain, only total AUM and performance metrics are visible. -- Auditor verifies correctness via an EAS-logged proof without seeing strategy composition. +- A fund deposits a stablecoin into a private vault. It submits a signed encrypted intent: "allocate 60 per cent to an ETH yield strategy and 40 per cent to staked T-Bills." The solver decrypts the intent inside a Fully Homomorphic Encryption runtime, produces an execution plan, and the vault executes trades privately on a privacy L2. On-chain, only total AUM and aggregate performance are visible. An auditor later verifies correctness via an attestation-logged disclosure without seeing strategy composition. ## See also -- [Pattern: Private Stablecoin Payments on Private L2s](./pattern-privacy-l2s.md) -- [Vendor: Orion Finance](https://www.orionfinance.ai/) -- [Vendor: Zama](https://www.zama.ai/) +- [Zama](../vendors/zama.md) +- [Fhenix](../vendors/fhenix.md) +- [Orion Finance](../vendors/orion-finance.md) +- [Aztec](../vendors/aztec.md) diff --git a/patterns/pattern-proof-of-innocence.md b/patterns/pattern-proof-of-innocence.md index 2f0e956..012a2af 100644 --- a/patterns/pattern-proof-of-innocence.md +++ b/patterns/pattern-proof-of-innocence.md @@ -1,98 +1,124 @@ --- title: "Pattern: Proof of Innocence (Association Set Proofs)" status: draft -maturity: PoC +maturity: production +type: standard layer: L1 -privacy_goal: Prove funds are not associated with illicit activity without revealing transaction history -assumptions: Shielded pool with commitment/nullifier model, Association Set Providers, zk-SNARKs -last_reviewed: 2026-04-08 +last_reviewed: 2026-04-22 + works-best-when: - - Users need to prove compliance (clean funds) to an institution or exchange - - Privacy within a compliant population is acceptable - - Association sets can be maintained by credible, independent providers + - Users need to prove compliance (clean funds) to an institution or exchange. + - Privacy within a compliant population is acceptable. + - Association sets can be maintained by credible, independent providers. avoid-when: - - Full transaction transparency is required by regulation - - The anonymity set is too small for meaningful privacy - - No credible ASP exists for the relevant jurisdiction -dependencies: - - zk-SNARKs (Groth16 or equivalent) - - Shielded pool contract (commitment/nullifier model) - - Association Set Providers (ASPs) + - Full transaction transparency is required by regulation. + - The anonymity set is too small for meaningful privacy. + - No credible association-set provider exists for the relevant jurisdiction. + context: both +context_differentiation: + i2i: "Between institutions, the compliance signal is an artefact of bilateral reporting obligations. Counterparties typically agree on a shared set of providers whose jurisdictional coverage matches their obligations, and disagreements are resolved through contract. Opinionated curation is tolerated as long as the selection criteria are disclosed." + i2u: "For end users, provider neutrality and plurality are non-negotiable. A single institution mandating one provider collapses CR to `low` because that provider can exclude a user from settlement. User-side privacy requires that the chosen set does not itself become a de facto allowlist." + crops_profile: cr: medium - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "L1 deposit and withdrawal remain permissionless, but set providers can effectively exclude users by refusing to include their deposits in a set. Reaches `high` when multiple competing providers are routinely accepted by relying parties. Drops to `low` when an institution mandates a single provider." + o: "Shielded-pool contracts and proof circuits are typically open source. Set-curation logic and blocklist-provider data pipelines are often proprietary, which limits independent reproduction of the compliance signal." + p: "The compliance signal is a structured disclosure; the verifier learns `clean` or `not proven clean` against a specific set but not the deposit, the transaction history, or counterparties. Set choice itself leaks coarse information about the user's jurisdictional context." + s: "Rides on the soundness of the zero-knowledge proof system and on the integrity of the set root commitment. Stale or adversarial set updates can cause false positives or false negatives." + +post_quantum: + risk: high + vector: "Groth16 and PLONK/KZG Merkle-branch proofs rely on elliptic-curve pairings broken by a CRQC. HNDL risk applies if historical proofs are later reused to infer deposit-withdrawal linkages." + mitigation: "Migrate proof systems to STARKs with hash-based commitments. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + requires: [pattern-shielding, pattern-zk-proof-systems] + composes_with: [pattern-compliance-monitoring, pattern-regulatory-disclosure-keys-proofs] + alternative_to: [pattern-zk-promises] + see_also: [pattern-user-controlled-viewing-keys] + +open_source_implementations: + - url: https://github.com/ameensol/privacy-pools + description: "Privacy Pools reference implementation with association-set proofs at withdrawal" + language: "Solidity, Circom" + - url: https://github.com/Railgun-Privacy/contract + description: "Railgun shielded pool with PPOI exclusion proofs at deposit and proof inheritance" + language: "Solidity, Circom" --- ## Intent -Allow users to prove their funds are not associated with illicit activity, without revealing their deposit, transaction history, or counterparties. Two protocol variants exist: prove at withdrawal (Privacy Pools) or prove at deposit with proof propagation (Railgun PPOI). Both use Merkle tree membership/exclusion proofs with zk-SNARKs; they differ in timing, proof direction, and set management. +Let users prove their funds are not associated with illicit activity without revealing the deposit, transaction history, or counterparties. Two protocol variants exist: prove at withdrawal against a curated set root, or prove at deposit with proof propagation through subsequent transfers. Both rely on Merkle tree membership or exclusion proofs with zero-knowledge proofs and differ in timing, proof direction, and set management. -Introduced in [Buterin et al. (2023)](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4563364) and deployed in [Privacy Pools](../vendors/privacypools.md). [Railgun](../vendors/railgun.md) implements a separate proof-of-innocence mechanism (PPOI) with a different set-management model. +## Components -## Ingredients - -- **Cryptography**: zk-SNARKs (Groth16) for Merkle-branch proofs; commitments + nullifiers for deposit unlinkability; proof inheritance tracking for intermediate transfers (Railgun variant) -- **On-chain**: shielded pool contract storing deposit commitments and nullifier sets; proof verifier contract -- **Off-chain**: set providers that define and publish curated lists. Two models: - - **Association Set Providers (ASPs)** (Privacy Pools): flexible, jurisdiction-specific sets. Sets can be inclusion-based ("low-risk deposits permitted"), exclusion-based ("all except sanctioned"), or hybrid. - - **Blocklist providers** (Railgun PPOI): Chainalysis Sanctions Oracle, Elliptic, SlowMist, ScamSniffer, PureFi. Exclusion-based lists of flagged addresses/transactions. -- **Data availability**: commitments and proofs on-chain; full set data on IPFS or off-chain with integrity anchoring +- Shielded pool contract that stores deposit commitments and nullifier sets. +- Zero-knowledge proof verifier that checks Merkle-branch statements against set roots. +- Set providers that publish curated set roots. Two models: + - Association-set providers publish flexible, jurisdiction-specific sets. Sets can be inclusion-based ("low-risk deposits permitted"), exclusion-based ("all except sanctioned"), or hybrid. + - Blocklist providers publish exclusion-based lists of flagged addresses and transactions (for example, sanctions-oracle feeds). +- Data-availability path for the full set data (IPFS or off-chain storage with on-chain integrity anchors). +- Proof-inheritance tracker (deposit-side variant) that carries forward the proof status of a commitment through intermediate transfers. ## Protocol -Two variants share the same primitive but differ in protocol flow: +Two variants share the same primitive but differ in flow. + +Variant A, prove at withdrawal: -**Variant A: prove at withdrawal (Privacy Pools)** +1. [user] Deposit tokens into a shielded pool; the contract stores a commitment in the global Merkle tree. +2. [operator] Set providers publish curated association sets, each defined by a Merkle root over a subset of deposits. +3. [user] Select a set and generate a zero-knowledge proof that the deposit is in the global tree and is a member of the chosen set root, or that the deposit is not in an exclusion set. +4. [contract] Verify the proof against the pool root and the set root; the verifier learns neither which deposit nor when it was made. +5. [user] Complete the withdrawal carrying a clean compliance signal. -1. User deposits tokens into a shielded pool. The contract stores a commitment in a global Merkle tree. -2. ASPs publish curated association sets, each defined by a Merkle root `R_A` over a subset of deposits. Different ASPs may serve different jurisdictions or risk models. -3. On withdrawal, the user selects an ASP set and generates a zk-SNARK proof: "my deposit is in the global tree AND is a member of set `R_A`" (membership) or "my deposit is NOT in illicit set `R_B`" (exclusion). -4. The verifier checks the proof against the on-chain pool root and the ASP's set root. The verifier does not learn which deposit, when it was made, or any linked transaction. -5. User completes the withdrawal with a clean compliance signal. +Variant B, prove at deposit with proof inheritance: -**Variant B: prove at deposit with proof inheritance (Railgun PPOI)** +1. [user] Shield tokens into the pool contract. +2. [prover] Auto-generate an exclusion proof that the deposited tokens are not present in any blocklist provider's dataset. +3. [contract] Enforce a standby window during which the deposit may only be unshielded back to the original address; this gives list providers time to update. +4. [user] Subsequent shielded transfers inherit the proof status of their inputs; the tracking service records which commitments have been checked. +5. [user] On unshield, any external verifier can reconstruct the proof chain from initial deposit through intermediate transfers. -1. User shields (deposits) tokens into the Railgun contract. -2. A Groth16 exclusion proof is auto-generated: "these tokens are not part of any blocklist provider's dataset." -3. A 1-hour standby period follows, during which tokens can be unshielded exclusively back to the original wallet. This gives list providers time to update their datasets. -4. After standby, the proof status carries forward through intermediate 0zk transfers. Recipients inherit valid proof status without regenerating proofs; the PPOI node tracks which UTXOs have been checked. -5. On unshield (withdrawal), the proof chain from initial deposit through intermediate transfers is verifiable by any external party. +## Guarantees & threat model -## Guarantees +Guarantees: -- **Compliance signal without surveillance**: the verifier gets "clean" or "not proven clean," never the transaction graph. -- **Deposit unlinkability**: the proof does not reveal which deposit belongs to the user. -- **Voluntary disclosure**: the user chooses which set to prove against. No mandatory global allowlist. -- **Separating equilibrium**: honest users benefit from proving (lower friction at exchanges). Dishonest users cannot produce valid proofs against well-curated sets. +- Compliance signal without surveillance: the verifier learns `clean` or `not proven clean` for a specified set, never the transaction graph. +- Deposit unlinkability: the proof does not reveal which deposit belongs to the user. +- Voluntary disclosure: the user chooses which set to prove against, avoiding a single mandatory global allowlist. +- Separating equilibrium: honest users benefit from proving; users excluded from credible sets cannot produce valid proofs against them. + +Threat model: + +- Set-provider integrity. A malicious or compromised provider can include or exclude specific deposits, effectively censoring users or diluting the compliance signal. +- Soundness of the zero-knowledge proof system and its trusted setup if applicable. +- Stale sets. Between set updates, newly flagged deposits still produce valid proofs. +- Small anonymity sets. Even a valid proof conveys little privacy when the set is tiny. +- Metadata such as relayer IPs, timing, and gas payer is out of scope for this pattern. ## Trade-offs -- **Set provider trust**: whoever curates the sets controls who is "clean." Mitigation: multiple competing providers; user choice; on-chain governance. -- **Set freshness**: stale sets miss recent sanctions. Railgun's 1-hour standby mitigates this at deposit time; Privacy Pools depend on ASP update cadence. -- **Assumed guilty by default**: non-provers are treated as non-compliant, penalizing users with limited compute or connectivity. -- **Anonymity set size**: small sets provide weak privacy even with valid proofs. -- **Regulatory acceptance**: ZK exclusion proofs are not yet universally accepted as equivalent to traditional KYC/AML. Varies by jurisdiction. -- **CROPS context (both)**: CR `medium` because L1 deposit/withdrawal is permissionless, but set providers can effectively exclude users. In I2U, CR drops if the institution mandates a single provider. Privacy `partial`: compliance signal is structured disclosure. OS `partial`: pool contracts are open source; set curation logic may be proprietary. -- **Post-quantum exposure**: Groth16 relies on EC pairings broken by CRQC. Mitigation: STARK-based pool. See [Post-Quantum Threats](../domains/post-quantum.md). +- Multiple providers introduce governance and coordination overhead for relying parties that accept proofs. +- Non-provers may be treated as non-compliant, penalising users with limited compute or connectivity. +- Regulatory acceptance of exclusion proofs as equivalent to traditional screening varies by jurisdiction and is still evolving. +- Set-update cadence trades off freshness against availability: standby windows delay usable funds, while long refresh intervals widen the window in which newly flagged deposits remain provable as clean. ## Example -A user withdraws from a shielded pool to an institutional exchange. The exchange requires proof of non-association with OFAC-sanctioned addresses. The user generates a ZK exclusion proof against the relevant set and submits it with the withdrawal. The exchange verifies the proof, accepts the deposit, and never learns which deposit the user made or when. +A user withdraws from a shielded pool to an institutional exchange. The exchange requires proof of non-association with sanctioned addresses. The user generates a zero-knowledge exclusion proof against the relevant set and submits it with the withdrawal. The exchange verifies the proof, accepts the deposit, and never learns which deposit the user made or when. ## See also -- [Shielded ERC-20 Transfers](pattern-shielding.md): the underlying shielded pool mechanism -- [Compliance Monitoring](pattern-compliance-monitoring.md): institutional screening logic (this pattern provides the user-side compliance signal) -- [zk-promises](pattern-zk-promises.md): stateful anonymous credentials with async enforcement -- [Selective Disclosure](pattern-regulatory-disclosure-keys-proofs.md): viewing-key-based disclosure for regulators -- [Vendor: Privacy Pools](../vendors/privacypools.md) -- [Vendor: Railgun](../vendors/railgun.md) - -## See also (external) - - [Privacy Pools paper (Buterin et al. 2023)](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4563364) - [Vitalik on Privacy Pools](https://vitalik.eth.limo/general/2023/09/06/privacy.html) -- [Privacy Pools GitHub](https://github.com/ameensol/privacy-pools) +- [Privacy Pools](../vendors/privacypools.md) +- [Railgun](../vendors/railgun.md) diff --git a/patterns/pattern-regulatory-disclosure-keys-proofs.md b/patterns/pattern-regulatory-disclosure-keys-proofs.md index ef3ce99..428ddb2 100644 --- a/patterns/pattern-regulatory-disclosure-keys-proofs.md +++ b/patterns/pattern-regulatory-disclosure-keys-proofs.md @@ -1,59 +1,102 @@ --- -title: "Pattern: Selective disclosure (viewing keys + ZK proofs)" +title: "Pattern: Selective disclosure (viewing keys + zero-knowledge proofs)" status: ready -maturity: pilot +maturity: testnet +type: standard layer: hybrid -privacy_goal: Provide on-demand scoped visibility into confidential trades via threshold keys or ZK proofs -assumptions: Threshold KMS, EAS for access logging, ZK predicate circuits -last_reviewed: 2026-01-14 +last_reviewed: 2026-04-22 + works-best-when: - - Regulator needs targeted visibility without blanket transparency. + - A regulator needs targeted visibility into specific trades or accounts without blanket transparency. + - The workflow can require an approval step that is logged and revocable. + - Zero-knowledge predicates can answer most regulator questions without releasing raw data. avoid-when: - - Policy requires full public plaintext. -dependencies: - - EAS - - Threshold-crypto/KMS - - ZK predicate circuits + - Policy requires fully public plaintext of all transactions. + - The organisation cannot support the operational complexity of threshold key custody and audit storage. + context: both +context_differentiation: + i2i: "Between institutions, regulator-initiated disclosure is a normal part of compliance. Both the subject and requester have audit obligations and legal recourse, and the approval workflow sits inside established supervisory channels." + i2u: "For end users, disclosure should remain user-controlled wherever possible; see `pattern-user-controlled-viewing-keys`. When disclosure is imposed on users without their consent or knowledge the pattern collapses to `cr: low` because the institution can reveal user activity unilaterally." + crops_profile: cr: medium - os: partial - privacy: partial - security: medium + o: partial + p: full + s: medium + +crops_context: + cr: "Regulator-mandated disclosure is normal institutional operation and does not block transaction flow, so CR stays `medium`. Drops to `low` when disclosure is imposed on end users outside the institution's governance boundary. Threshold custody with independent operators can push CR toward `high` by preventing any single party from forcing a reveal." + o: "Openness depends on the implementation. Pool-native viewing keys and open predicate circuits are inspectable; proprietary threshold KMS deployments are not. Disclosure policy code, mandate verification logic, and revocation flows should be auditable for the pattern to remain interoperable." + p: "Disclosure is scoped: the regulator learns only what the mandate authorises. Zero-knowledge predicate responses leak no raw data. Viewing-key responses leak everything inside the key's scope, so key segmentation and time-boxing are important." + s: "Rides on threshold key custody, hardware-rooted policy engines, correct mandate parsing, and tamper-evident audit storage. Key compromise yields retroactive loss of privacy across the key's scope." + +post_quantum: + risk: high + vector: "Viewing keys typically derive from EC-based key exchange and are stored as long-lived secrets; HNDL risk is high since ciphertexts and proofs can be archived now and broken later. Predicate circuits built on pairing-based proof systems are also affected." + mitigation: "Migrate key-encapsulation to post-quantum KEMs (for example, ML-KEM) and move predicate circuits to STARK-based systems with hash commitments. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + composes_with: [pattern-shielding, pattern-user-controlled-viewing-keys, pattern-compliance-monitoring] + alternative_to: [pattern-proof-of-innocence] + see_also: [pattern-l2-encrypted-offchain-audit, pattern-private-pvp-stablecoins-erc7573] + +open_source_implementations: + - url: https://github.com/ethereum-attestation-service/eas-contracts + description: "Ethereum Attestation Service contracts, useful for logging disclosure grants" + language: "Solidity" --- ## Intent -Provide **on-demand, scoped visibility** into confidential trades/positions via **threshold-controlled viewing keys** and/or **ZK proofs** answering regulator questions. -## Ingredients -- **Standards**: EAS for access logging -- **Infra**: Threshold KMS, policy engine -- **Off-chain**: Request/approval workflow; audit storage +Provide on-demand, scoped visibility into confidential trades and positions via threshold-controlled viewing keys or zero-knowledge predicate proofs that answer specific regulator questions. The institution keeps plaintext private by default and releases only the minimum information required to satisfy a specific, logged mandate. + +## Components -## Protocol (concise) -1. Regulator requests scope (account/ISIN/time). -2. Policy engine checks mandate; emits EAS access-grant. -3. Assemble **time-limited viewing key** or produce **zero-knowledge proof**. -4. Deliver result; log disclosure (hash + who/when). +- Threshold key management that holds viewing-key shares across independent operators and releases material only under policy. +- Policy engine that checks each request against the active mandate (jurisdiction, scope, time window, requester identity) before assembling a response. +- Predicate circuit library that can answer common regulator questions ("total volume in ISIN X on date Y"; "no trades with sanctioned parties in quarter Q") without releasing raw data. +- Attestation log that records every access grant as a signed, hashed entry; a public registry can anchor these hashes for tamper-evidence without revealing content. +- Approval workflow used by the institution's compliance team to review and sign off on requests before the policy engine acts. -## Guarantees -- Least-privilege, revocable access; full audit trail. -- Zero-knowledge responses when raw data isn’t needed. +## Protocol + +1. [regulator] Submit a scoped request specifying account, instrument, time window, and mandate. +2. [operator] The policy engine checks the request against the active mandate and approvals; an attestation logs the grant. +3. [operator] Assemble the response: either a time-limited viewing key reconstituted from threshold shares, or a zero-knowledge proof generated by the predicate circuit over the relevant private state. +4. [operator] Deliver the response to the regulator over an authenticated channel. +5. [auditor] Verify the disclosure record against the anchored hash to confirm that the response matches the approved mandate. + +## Guarantees & threat model + +Guarantees: + +- Least-privilege, revocable access: viewing keys are time-boxed; predicate proofs leak no raw data. +- Full audit trail: every grant is recorded, signed, and anchored. +- Predicate proofs can answer common compliance questions without exposing transaction content. + +Threat model: + +- Threshold key custody integrity. A coalition of operators above the threshold can forge responses or leak keys. +- Mandate parsing correctness. A bug in the policy engine can widen scope beyond what the mandate authorises. +- Attestation log availability. If the log is rewritable or unobserved, disclosures can be retroactively denied. +- Predicate circuit soundness and input binding. A misbound predicate may answer a different question than the one logged. +- Side channels in custody infrastructure are out of scope for this pattern. ## Trade-offs -- Operational complexity (key custody/rotation). -- Proof authoring/UX requires discipline. -- **CROPS context (both)**: Regulator-mandated disclosure is normal institutional operation and protects end-users (CR `medium`). In I2U, CR drops to `low` when disclosure is imposed on users without their control. OS depends on whether the viewing key implementation is open and composable (e.g. Aztec viewing keys are open) vs proprietary KMS. Security varies by implementation — audited threshold KMS could reach `high`. + +- Operational complexity: threshold key custody, rotation, and incident response need dedicated runbooks. +- Predicate authoring requires discipline: circuits must mirror mandate semantics exactly, and changes need auditable version control. +- Response latency increases with threshold reconstitution or proof generation time; batch workflows absorb this better than real-time supervisory queries. +- Regulator tooling maturity varies: some supervisory authorities still require raw data formats, limiting applicable use cases. ## Example -- BaFin asks for Jan-15 trades in ISIN X. -- System issues 24-hour read token; EAS logs event; auto-revokes. + +A supervisory authority asks for trades on a given date in a specific instrument. The policy engine matches the request against the institution's active mandate, an approval record is logged, and a 24-hour viewing key reconstituted from threshold shares is issued. The regulator reviews the trades during the window; at expiry the key is revoked automatically, and the attestation log retains a hashed record for future audit. ## See also -- [User-Controlled Viewing Keys](pattern-user-controlled-viewing-keys.md): user-held key custody for I2U privacy sovereignty; this pattern covers the institution-side workflow once keys are shared -- pattern-confidential-erc20-fhe-l2-erc7573.md -- [Low-cost L2 + Off-chain Encrypted Audit Log](pattern-l2-encrypted-offchain-audit.md) -## See also (external) -- EAS docs: https://easscan.org/docs -- EAS contracts: https://github.com/ethereum-attestation-service/eas-contracts +- [EAS documentation](https://easscan.org/docs) +- [Aztec](../vendors/aztec.md) diff --git a/patterns/pattern-safe-proof-delegation.md b/patterns/pattern-safe-proof-delegation.md index 30a7bcb..ebca4fe 100644 --- a/patterns/pattern-safe-proof-delegation.md +++ b/patterns/pattern-safe-proof-delegation.md @@ -1,72 +1,104 @@ --- title: "Pattern: Safe Proof Delegation" status: draft -maturity: PoC +maturity: testnet +type: standard layer: L1 -privacy_goal: Delegate proof generation to an untrusted prover without trusting it with funds -assumptions: Intent-based authorization, ZK proof system, nullifierKey + rotatable outputSecret -last_reviewed: 2026-03-16 +last_reviewed: 2026-04-22 + +works-best-when: + - Users cannot generate zero-knowledge proofs locally (mobile wallets, hardware wallets, constrained devices). + - A server-side prover or privacy-aware RPC bridges the gap before native wallet support. + - Delegation must be revocable without moving funds to new notes or a new address. +avoid-when: + - Client-side proving is already available and performant for the target workload. + - The prover seeing transaction details is unacceptable even temporarily; prefer a distributed or TEE-hosted prover instead. + context: both +context_differentiation: + i2i: "Between institutions, proof delegation typically happens under bilateral contracts with SLAs and audit rights. The authorising institution can demand operational logs and, through legal recourse, punish deviation even though deviation cannot be prevented cryptographically." + i2u: "For users, the prover is usually an external service. The pattern must assume the prover can be adversarial at any moment: output-secret rotation and short-lived intents are how the user retains the ability to unplug a compromised prover without moving funds." + crops_profile: cr: low - os: yes - privacy: partial - security: high -works-best-when: - - Users cannot generate ZK proofs locally (mobile, hardware wallets). - - A server-side prover or Privacy RPC bridges the gap before native wallet support. - - Delegation must be revocable without moving funds. -avoid-when: - - Client-side proving is already available and performant. - - The prover seeing transaction details is unacceptable even temporarily. -dependencies: - - ZK proof system (commitments/nullifiers) - - Poseidon hash (intent digest) - - EIP-8182 (draft) + o: yes + p: partial + s: high + +crops_context: + cr: "Depends on prover liveness. A single prover service is a censorship surface; CR approaches `medium` when multiple interchangeable provers accept the same intent format and the user can switch without re-sealing state." + o: "Intent schema, circuits, and verifier contracts are open source; provers can be hosted by anyone implementing the schema." + p: "The prover sees transaction plaintext (amount, recipient, token). The verifier and the chain see only the proof. Combining with a TEE-hosted or MPC-based prover can hide plaintext from the prover operator as well." + s: "Funds cannot be stolen or redirected: the signed intent binds every material parameter. Security rides on the soundness of the zero-knowledge proof system, correct intent-schema binding, and rotatable output secrets that unlink future transactions from a past prover." + +post_quantum: + risk: high + vector: "Pairing-based proof systems and ECDSA/Schnorr intent signatures are broken by a CRQC. HNDL risk applies: an attacker recording today's intent signatures could forge future spends once quantum capability is available." + mitigation: "Post-quantum signature schemes (ML-DSA, SLH-DSA) for the intent layer and STARK-based circuits for the proof system. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [EIP-8182] + +related_patterns: + requires: [pattern-shielding, pattern-zk-proof-systems] + composes_with: [pattern-permissionless-spend-auth, pattern-co-snark, pattern-tee-based-privacy] + alternative_to: [pattern-co-snark] + see_also: [pattern-user-controlled-viewing-keys] + +open_source_implementations: + - url: https://github.com/ethereum/EIPs/pull/11373 + description: "EIP-8182 draft: canonical intent digest and rotatable output-secret protocol" + language: "specification" --- ## Intent -Let a user delegate ZK proof generation to an external prover — a Privacy RPC, a hardware accelerator, or a third-party service — without giving that prover the ability to forge, redirect, or overspend. The user signs a **canonical intent digest** that binds every material parameter; the prover can produce a valid proof that executes exactly that intent, nothing else. +Let a user delegate zero-knowledge proof generation to an external prover (a privacy RPC, a hardware accelerator, or a third-party service) without giving that prover the ability to forge, redirect, or overspend. The user signs a canonical intent digest that binds every material parameter; the prover can produce a valid proof that executes exactly that intent and nothing else. + +## Components + +- Canonical intent digest that binds operation kind, token, recipient, amount, nonce, expiry, chain identifier, and any required additional fields such as policy version and pool address. +- Two protocol secrets: an immutable spending key that controls nullifier derivation, and a rotatable output secret that controls deterministic output randomness. Note-delivery encryption is handled by companion standards. +- Intent nullifier set, distinct from the note nullifier set, that prevents replay of a signed intent. +- Zero-knowledge circuit that checks the signature against the authorising address, verifies that every public input matches the intent digest, validates note openings and Merkle paths, and enforces value conservation. + +## Protocol -## Ingredients +1. [user] Compute the canonical intent digest and sign it inside the wallet; the signed intent is never broadcast. +2. [user] Send the signed intent plus witness data (note openings, Merkle paths, keys) to the prover over an encrypted channel. +3. [prover] Run the circuit to produce a proof that binds the witness to the signed intent. +4. [prover] Submit the proof and public inputs to the pool contract. +5. [contract] Verify the proof, consume note nullifiers, and record the intent nullifier to prevent replay. +6. [user] When switching provers, rotate the output secret so the former prover can no longer derive output randomness for future transactions; existing notes remain spendable because the spending key is unchanged. -- **Canonical intent digest**: Poseidon hash binding all material parameters (operation kind, token, recipient, amount, nonce, expiry, chain ID, and additional fields like policy version and pool address per the current EIP-8182 draft) -- **Two protocol secrets**: immutable `nullifierKey` (controls spending and nullifier derivation) + rotatable `outputSecret` (controls deterministic output randomness). Note-delivery encryption is handled by companion standards, not the base protocol. -- **Intent nullifier set**: separate on-chain nullifier set preventing intent replay -- **ZK circuit**: verifies the signed intent and witness data, outputs a spend proof +## Guarantees & threat model -## Protocol (concise) +Guarantees: -1. **User signs intent.** Wallet computes the canonical intent digest and signs it. The digest binds all material parameters (see Ingredients). This is never broadcast. -2. **User sends to prover.** The signed intent plus witness data (note openings, Merkle paths, keys) are transmitted to the prover over an encrypted channel. -3. **Prover generates proof.** The prover runs the ZK circuit. The circuit checks: signature matches `authorizingAddress`, all parameters match the intent digest, notes are valid, and value is conserved. -4. **Prover submits on-chain.** The proof and public inputs go to the pool contract. The contract verifies the proof, consumes note nullifiers, and records the intent nullifier to prevent replay. -5. **Prover boundaries enforced.** The prover **cannot** change the recipient, amount, or token — any deviation invalidates the proof. The prover **can** see transaction details, choose submission timing, and choose the note-delivery payloads attached to the transaction. The protocol does not validate payload contents, so a malicious prover can emit unusable delivery data for that transaction. Expiry limits the prover's timing window. -6. **Revoke forward derivation.** User rotates `outputSecret`. After stale user roots expire, the former prover can no longer derive output randomness for future transactions. The immutable `nullifierKey` means existing notes remain spendable without migration. +- No custody: the prover never holds keys that can unilaterally spend. Every spend requires a user-signed intent. +- Tamper-proof intents: modifying any bound parameter invalidates the proof. +- Replay prevention: each signed intent can execute exactly once via the intent nullifier set. +- Revocable delegation: rotating the output secret cuts off a former prover's ability to derive future output randomness without moving funds. -## Guarantees +Threat model: -- **No fund custody.** The prover never holds keys that can unilaterally spend. Every spend requires a user-signed intent. -- **Tamper-proof intents.** Modifying any parameter (recipient, amount, token) breaks the proof. -- **Replay prevention.** Intent nullifiers form a separate set; each signed intent can execute exactly once. -- **Revocable delegation.** Rotating `outputSecret` cuts off a former prover's ability to derive future output randomness without affecting spendability. +- Soundness of the underlying proof system. +- Correctness of the intent-digest schema and domain separation; a bug that lets the prover substitute a public input breaks the tamper-proof guarantee. +- Confidentiality of the note-delivery channel. A malicious prover can emit unusable delivery payloads, rendering outputs unrecoverable by the recipient (funds are not lost for the sender, but the recipient cannot claim them). +- Liveness of at least one prover; a single offline prover stalls the user until they switch. +- Microarchitectural or supply-chain attacks on the prover that leak plaintext are in scope for this pattern but are mitigated by combining with a TEE-hosted or MPC-based prover. ## Trade-offs -- **Prover sees plaintext.** The prover learns transaction details (amount, recipient, token). Mitigable via TEE-hosted provers or MPC proving, at higher complexity. -- **Liveness dependency.** If the prover is offline, the user cannot transact until they switch provers or generate proofs locally. -- **Expiry tuning.** Too short and transactions fail before submission; too long and a compromised prover has a wider replay-like window (though still bound to the exact intent parameters). -- **Note-delivery risk.** The prover chooses note-delivery payloads. A malicious prover can emit unusable data, making the in-flight transfer's output notes unrecoverable by the recipient. The prover cannot steal or redirect funds. -- **Output secret rotation cost.** After rotation, the user must retain the prior `outputSecret` until the stale-root window expires and any authorized transactions have settled. -- **Post-quantum exposure**: recursive ZK verification relies on EC-based proof systems broken by CRQC. Mitigation: STARK-based recursive proving. See [Post-Quantum Threats](../domains/post-quantum.md). +- The prover sees transaction plaintext. Privacy from the prover operator itself requires a TEE-based or distributed prover, at the cost of more infrastructure. +- Liveness depends on the prover. If the prover is offline, the user must switch or move to client-side proving. +- Expiry tuning matters: too short and transactions fail before submission, too long and a compromised prover has more room to manoeuvre within the fixed intent. +- Output-secret rotation has an operational cost: the user must retain the prior secret until the stale-root window expires and authorised transactions have settled. ## Example -- Alice uses a mobile wallet that cannot generate ZK proofs. She signs an intent to send 100 USDC to Bob, with a 10-minute expiry. Her Privacy RPC generates the proof and submits it on-chain within 3 minutes. The RPC sees the transfer details but cannot redirect funds. When Alice later switches to a different RPC provider, she rotates her `outputSecret` — the old provider can no longer derive output randomness for her future transactions. +A user holds shielded balances in a mobile wallet that cannot generate zero-knowledge proofs. The wallet signs an intent to send 100 units to a specific recipient with a ten-minute expiry and forwards the signed intent plus witness data to a privacy RPC. The RPC generates the proof and submits it on-chain within three minutes. The RPC sees the transfer details but cannot redirect funds. When the user later switches RPC providers, they rotate the output secret; the former RPC can no longer derive output randomness for future transactions, and existing notes remain spendable. ## See also -- [Shielding](pattern-shielding.md) - the pool contract this delegation targets -- [Permissionless Spend Auth](pattern-permissionless-spend-auth.md) - inner/outer circuit split this delegation composes with -- [EIP-8182 (draft)](https://github.com/ethereum/EIPs/pull/11373) +- [EIP-8182 draft](https://github.com/ethereum/EIPs/pull/11373) +- [Railgun](../vendors/railgun.md) diff --git a/patterns/pattern-stealth-addresses.md b/patterns/pattern-stealth-addresses.md index ab29f04..1299b0c 100644 --- a/patterns/pattern-stealth-addresses.md +++ b/patterns/pattern-stealth-addresses.md @@ -1,90 +1,103 @@ --- title: "Pattern: Stealth Addresses" status: draft -maturity: PoC +maturity: production +type: standard layer: L1 -privacy_goal: Hide address linkages via one-time destination addresses; amounts remain visible -assumptions: EIP-5564 support, wallet view/spend key management, optional registry for public view keys -last_reviewed: 2026-01-14 +last_reviewed: 2026-04-22 + works-best-when: - - Sender and receiver want to hide address linkages on a public chain. - - Amount privacy is less critical than unlinkability of counterparties. + - Sender and receiver want to hide the link between their public identities on a transparent chain. + - Counterparty unlinkability matters more than amount confidentiality. + - Wallets or directory services can publish and manage view-key material for recipients. avoid-when: - - Strong amount confidentiality is required (use shielded pools or confidential tokens). - - Institutions require regulator keys / scoped audit by default. -dependencies: - - ERC-20 - - ERC-4337 (optional, account abstraction for wallet UX) - - EIP-5564 (Ethereum Stealth Addresses draft) + - Strong amount confidentiality is required; use a shielded pool or confidential token instead. + - The deployment requires scoped regulator access by default; stealth addresses only support voluntary disclosure. + context: both +context_differentiation: + i2i: "Between institutions, recipients can maintain directory entries that publish view keys. Disclosure to regulators happens by the recipient voluntarily sharing the private view key for a time window or a specific stealth address." + i2u: "For end users, self-relaying from the stealth address is necessary to preserve unlinkability; otherwise the gas-paying address re-links the stealth address to a known identity. CR drops to `low` when relayers are mandatory and centralised, which is often the case before account-abstraction paymasters are routinely available." + crops_profile: cr: medium - os: yes - privacy: partial - security: high + o: yes + p: partial + s: high + +crops_context: + cr: "Reaches `high` when the user can self-relay and pay gas from the stealth address without a shared paymaster; in practice this requires account-abstraction support for fresh addresses. Drops to `low` when a central relayer is unavoidable." + o: "The stealth-address derivation is open and standardised; wallets implementing EIP-5564 can interoperate. Registry components may be open-source or proprietary depending on the deployment." + p: "Counterparty linkage on-chain is hidden; amounts and token type remain visible, and network-layer metadata (IP, timing, relayer identity) is out of scope." + s: "Rides on the hardness of the Diffie-Hellman problem used to derive shared secrets and on correct implementation of view and spend keys in wallets." + +post_quantum: + risk: high + vector: "Elliptic-curve Diffie-Hellman underpins the shared-secret derivation and is broken by a CRQC. HNDL risk is acute: address linkages recorded now are retroactively compromised once a quantum adversary can recover view keys." + mitigation: "Post-quantum key-encapsulation such as ML-KEM for the shared-secret step, combined with oblivious message retrieval as an off-chain scanning aid. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [ERC-20, EIP-5564, ERC-4337] + +related_patterns: + composes_with: [pattern-shielding, pattern-erc3643-rwa, pattern-user-controlled-viewing-keys] + see_also: [pattern-private-iso20022, pattern-network-anonymity] + +open_source_implementations: + - url: https://github.com/nerolation/eip-stealth-address-erc-5564 + description: "Reference implementation of EIP-5564 stealth-address scheme" + language: "Solidity" --- ## Intent -Enable unlinkable transfers by deriving a **one-time destination address per transaction** using cryptographic Diffie–Hellman (shared secret) between sender and receiver keys. -Observers see the transfer to a fresh address, but only the receiver can detect and spend from it. +Enable unlinkable transfers on a transparent chain by deriving a one-time destination address per transaction using a Diffie-Hellman shared secret between sender and receiver keys. Observers see a transfer to a fresh address; only the recipient can detect and spend the funds. ---- - -## Ingredients +## Components -- **Standards**: ERC-20 (token transfers), optional EIP-5564 for standardized stealth addresses. -- **Infra**: base L1/L2 chain; compatible wallets implementing view keys and spend keys. -- **Off-chain services**: none required, but directory/registry may help with publishing public view keys. +- Stealth keypair held by the recipient: a view key used to scan the chain and a spend key used to control funds. +- Ephemeral sender key generated per transaction; combined with the recipient view key to produce a shared secret. +- Derivation function that converts the shared secret into a stealth address and an optional view tag for fast scanning. +- Optional registry or directory that publishes recipient view keys so senders can discover them. +- Wallet or account-abstraction stack that can fund and operate the stealth address without re-linking it to the recipient's primary address. ---- +## Protocol -## Protocol (concise) +1. [user] The recipient publishes a public view key via a directory or shares it with the sender directly. +2. [user] The sender generates an ephemeral key and computes the Diffie-Hellman shared secret with the recipient view key. +3. [user] The sender derives the one-time stealth address from the shared secret and transfers tokens to it. +4. [user] The recipient scans new transactions using the private view key and detects transfers destined to their stealth addresses. +5. [user] The recipient uses the spend key to authorise spending from the stealth address when needed. +6. [auditor] The recipient can optionally share the private view key with an auditor for a specific scope or time window. -1. Receiver publishes a **public view key** (part of a stealth keypair). -2. Sender generates an **ephemeral key**, computes shared secret with receiver’s view key. -3. Derive a one-time **stealth address** from the secret. -4. Sender transfers ERC-20 tokens (or ETH) to the stealth address. -5. Receiver scans chain with their **private view key**, detects funds destined for them. -6. Receiver uses their **spend key** to access/control funds. -7. Optionally: receiver can disclose full transaction set to auditors via view key export. +## Guarantees & threat model ---- +Guarantees: -## Guarantees +- On-chain observers do not see a direct link between sender and recipient identities. +- The recipient can scan and spend without the sender needing further interaction. +- Retrospective disclosure is possible by voluntarily sharing the view key with a specific auditor. -- **Hides**: direct link between sender and receiver; on-chain observers see only fresh addresses. -- **Does not hide**: transfer amounts or token type. -- **Audit**: receiver can share view keys for retrospective audit; no mandatory regulator path. -- **Finality**: same as base L1/L2 ERC-20 transfer finality. +Threat model: ---- +- The hardness of elliptic-curve Diffie-Hellman; key compromise reveals all past and future stealth addresses derived from the same view key. +- Wallet implementation correctness in handling view and spend keys and in funding the stealth address without re-linking it. +- Metadata at the network layer (RPC provider logs, relayer identity, IP addresses) and repeated address reuse by the recipient are out of scope. +- Amount and token type are visible on-chain by design. ## Trade-offs -- **Performance/UX**: requires wallets to manage extra key material (view/spend keys, stealth derivations). -- **Scanning cost**: receivers must scan chain for potential stealth addresses (mitigated with view tags). -- **Amount leakage**: visible amounts still expose competitive data. -- **Regulatory fit**: no built-in scoped regulator access; relies on voluntary disclosure. -- **Interoperability**: limited unless EIP-5564 or similar standards are widely adopted. -- **CROPS context (both)**: CR reaches `high` if user can self-relay and pay own gas from stealth address — could become practical after EIP-8141. Drops to `low` if relayer/paymaster dependency is unavoidable and centralized. In I2U, end-users are more likely to depend on relayers provided by institutions. -- **Post-quantum exposure**: ECDH key derivation is broken by CRQC; HNDL risk is high — address linkages recorded now are retroactively compromised. Mitigation: ML-KEM + OMR sidecar for off-chain note discovery. See [Post-Quantum Threats](../domains/post-quantum.md). - ---- +- Amount leakage: transfer values remain visible and can expose competitive information. +- Scanning cost: recipients must scan all transactions, or use view tags and prefiltering to reduce load. +- Funding the stealth address to cover gas can re-link the stealth address to a known source unless account abstraction or dedicated gas-payer flows are in place. +- Interoperability depends on EIP-5564 adoption across wallets and on registry availability. +- Regulator workflows require voluntary view-key sharing; there is no scoped access path by default. ## Example -- Bank A owes Bank B €10m (tokenized ERC-20 stablecoin). -- Bank B publishes a public view key in its directory entry. -- Bank A derives a stealth address for Bank B using the shared secret, transfers 10m EURC to it. -- On-chain: looks like a transfer to a random fresh address. -- Bank B’s wallet detects the funds via its view key, then moves them to a custodian wallet. -- For audit, Bank B can later disclose the view key to regulators. - ---- +An institution owes a counterparty tokenised stablecoin. The recipient publishes a public view key in its directory entry. The sender derives a stealth address using the shared secret and transfers the stablecoin to that address. On-chain, the transfer looks like a payment to a fresh address. The recipient's wallet detects the funds via the private view key, then moves them to a custodian wallet. For audit, the recipient can later disclose the view key to a regulator for the relevant window. ## See also -- [pattern-private-iso20022.md](pattern-private-iso20022.md) (messaging integration with stealth/hidden settlement) -- pattern-aztec-privacy-l2-erc7573.md (shielded pool settlement) -- pattern-confidential-erc20-fhe-l2-erc7573.md (amount-hiding tokens) +- [EIP-5564 specification](https://eips.ethereum.org/EIPS/eip-5564) +- [Vitalik on stealth addresses](https://vitalik.eth.limo/general/2023/01/20/stealth.html) +- [Curvy](../vendors/curvy.md) diff --git a/patterns/pattern-tee-based-privacy.md b/patterns/pattern-tee-based-privacy.md index ffedb95..c4dc287 100644 --- a/patterns/pattern-tee-based-privacy.md +++ b/patterns/pattern-tee-based-privacy.md @@ -1,178 +1,139 @@ --- title: "Pattern: TEE-Based Privacy" status: draft -maturity: pilot +maturity: production +type: standard layer: offchain -privacy_goal: Protect computation and data confidentiality via hardware-isolated execution -assumptions: Hardware vendor trust, attestation infrastructure, physical security of deployment environment -last_reviewed: 2026-02-13 +last_reviewed: 2026-04-22 + works-best-when: - - Confidential computation needed with lower latency than ZK proofs - - Parties accept hardware trust assumptions over cryptographic-only solutions - - Institutional-grade infrastructure with known operators and vendors + - Confidential computation is needed with lower latency than zero-knowledge proofs or multi-party computation can deliver. + - The deployment can accept hardware and vendor trust anchors in exchange for performance. + - Operators and hardware vendors are known and contractually bound. avoid-when: - - Threat model includes nation-state physical access or supply-chain compromise - - Full trustlessness required (prefer ZK or MPC alternatives) - - Long-term secrets that outlive hardware security lifecycle -dependencies: - [Intel SGX, AMD SEV-SNP, AWS Nitro Enclaves, Azure Confidential Computing] + - The threat model includes nation-state physical access or supply-chain compromise. + - Full trust minimisation is required; prefer zero-knowledge or multi-party computation instead. + - Secrets must outlive the security lifecycle of the hardware platform. + context: both +context_differentiation: + i2i: "Between institutions, Trusted Execution Environments are operated under bilateral contracts with physical-security controls, audit rights, and SLAs. Threshold distribution across operators and vendors reduces the blast radius of any single compromise. Attestation logs and measurement registries become shared compliance artefacts." + i2u: "For end users, the institution typically operates the enclave. The user has no independent way to verify the hardware state or the operator's integrity, so any privacy claim rests on institutional trust. Multi-operator or multi-vendor deployments and, where applicable, zero-knowledge proofs of execution, are needed before the user-facing privacy claim has technical substance." + crops_profile: cr: low - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "A single operator that controls scheduling and I/O can deny service at any time; CR is structurally bounded. Multi-operator threshold setups and public measurement registries lift the floor by requiring coordinated action to censor." + o: "Attestation formats and open-source enclave runtimes are available, but full platform stacks (microcode, vendor attestation services) are closed. Deployment openness depends on how much of the stack the operator publishes." + p: "Plaintext inside the enclave is hidden from the host operating system and hypervisor under the vendor's trust assumptions. I/O metadata, timing, and microarchitectural side channels remain observable and must be mitigated at the application layer." + s: "Rides on hardware-vendor key integrity, firmware and microcode patch discipline, and correct enclave code. Documented side channels and firmware vulnerabilities mean the security floor moves with every disclosed CVE." + +post_quantum: + risk: high + vector: "Attestation chains depend on vendor ECDSA signing keys (for example, Intel DCAP) that a CRQC can forge, invalidating remote attestation. Any long-lived keys sealed inside the enclave using elliptic-curve primitives are similarly exposed." + mitigation: "Adopt post-quantum signature schemes (ML-DSA, SLH-DSA) for attestation and sealing keys; track vendor roadmaps for post-quantum DCAP. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + composes_with: [pattern-tee-key-manager, pattern-tee-zk-settlement, pattern-tee-network-anonymity, pattern-verifiable-attestation, pattern-private-shared-state-tee] + alternative_to: [pattern-co-snark, pattern-mpc-custody, pattern-private-shared-state-fhe] + see_also: [pattern-modular-privacy-stack] + +open_source_implementations: + - url: https://github.com/openenclave/openenclave + description: "Open Enclave SDK supporting Intel SGX and similar hardware TEEs" + language: "C, C++" + - url: https://github.com/AMDESE/AMDSEV + description: "AMD SEV-SNP reference tooling for VM-level attested confidential computing" + language: "C, Shell" --- ## Intent -Use Trusted Execution Environments (TEEs) to isolate sensitive computation from the host operating system, hypervisor, and operator. TEEs provide hardware-enforced confidentiality and integrity for code and data during execution, enabling privacy-preserving operations without exposing plaintext to infrastructure providers. - -This is a foundational pattern describing TEE trust models and failure modes. Specific applications (key management, settlement, matching) build on this foundation. - -## Ingredients - -- **Hardware Platforms** (two categories with different trust models): - - _CPU-encrypted (hardware TEEs)_: Memory encrypted by the CPU itself; protects data even from the host OS and hypervisor - - **[Intel SGX](https://www.intel.com/content/www/us/en/architecture-and-technology/software-guard-extensions.html)**: Process-level enclaves, 90–128 MB encrypted memory (EPC). Attestation rooted in Intel signing keys - - **[AMD SEV-SNP](https://www.amd.com/en/developer/sev.html)**: VM-level isolation with full memory encryption and integrity. Attestation rooted in AMD signing keys - - _Hypervisor-isolated (VM TEEs)_: Isolation enforced by a minimal hypervisor; no CPU-level memory encryption - - **[AWS Nitro Enclaves](https://aws.amazon.com/ec2/nitro/nitro-enclaves/)**: Isolated VMs with no persistent storage, no network access. Attestation signed by AWS root CA - - **[Azure Confidential Computing](https://azure.microsoft.com/en-us/solutions/confidential-compute/)**: Offers both SGX and SEV-SNP; also provides attestation-as-a-service - - **ARM TrustZone**: Mobile/embedded TEE (less common in institutional settings) - -- **Attestation Infrastructure**: - - Remote attestation services (Intel IAS/DCAP, AMD KDS, AWS Nitro attestation) - - Attestation verification logic (on-chain or off-chain) - - Measurement registries for approved code/configurations - -- **Operational Requirements**: - - Secure provisioning and sealing key management - - Firmware/TCB update policies - - Physical security of hosting environment - - Incident response runbooks - -## Trust Model - -### Who Must Be Trusted +Use hardware-isolated execution environments to protect sensitive computation from the host operating system, hypervisor, and operator. The pattern provides hardware-enforced confidentiality and integrity for code and data while running, so privacy-preserving operations can be performed without exposing plaintext to infrastructure providers. This is a foundational pattern; specific applications (key management, settlement, matching) compose on top. -| Entity | Trust Requirement | Mitigation | -| ---------------------- | ------------------------------------- | ------------------------------------------------------------ | -| **Hardware Vendor** | Correct implementation, no backdoors | Vendor reputation, third-party audits, multi-vendor strategy | -| **Firmware/Microcode** | No vulnerabilities, timely patches | TCB recovery, update policies, attestation checks | -| **Cloud Provider** | Physical security, correct hypervisor | Contractual obligations, attestation, multi-cloud | -| **Operator** | Correct deployment, no tampering | Remote attestation, sealed secrets, audit logs | -| **Code Author** | Correct enclave logic | Open source, audits, formal verification | +## Components -### Platform Threat Model Comparison +- CPU-encrypted enclaves (for example, Intel SGX, AMD SEV-SNP) where memory is encrypted by the processor so the host operating system and hypervisor cannot read plaintext. +- Hypervisor-isolated enclaves (for example, AWS Nitro Enclaves) where isolation is enforced by a minimal hypervisor without CPU-level memory encryption. +- Remote attestation services that sign measurement reports rooted in hardware-vendor or cloud-provider keys. +- Measurement registry that records approved code and configuration hashes so verifiers know what "correct" looks like. +- Operational stack: secure provisioning, sealing-key management, firmware and microcode update policy, physical security controls, and incident-response runbooks. -| | CPU-encrypted (SGX, SEV) | Hypervisor-isolated (Nitro) | -| ------------------------- | --------------------------------------------------------- | ------------------------------------ | -| **Protects from** | Host OS, hypervisor, cloud provider | Parent instance, other tenants | -| **Does NOT protect from** | CPU manufacturer (holds master keys) | Cloud provider (controls hypervisor) | -| **Memory encryption** | CPU silicon | None (hypervisor boundary only) | -| **Attestation root** | CPU manufacturer signing keys | Cloud provider root CA | -| **Side-channel exposure** | High (CPU-level: Spectre, cache timing) | Lower (VM boundary) | -| **Institutional analogy** | "Programmable enclave" (weaker than HSM — see note below) | "Locked-down VM you can't SSH into" | +Hardware TEEs differ from Hardware Security Modules. HSMs provide physical tamper resistance (EAL5 to 7), dedicated silicon, and a minimal firmware surface; TEEs offer general-purpose computation with logical isolation but share the CPU die, lack physical tamper resistance (EAL2 to 4), and have a larger attack surface with documented side-channel history. Contractual controls partially mitigate this gap but do not close it; treat TEEs as complementary to HSMs, not replacements. -For institutions already trusting a cloud provider with their infrastructure, hypervisor-isolated TEEs are operationally simpler. When protection _from_ the cloud provider is needed, CPU-encrypted TEEs are required. +The two platform families differ in threat coverage: -> **TEE ≠ HSM.** HSMs provide physical tamper resistance (EAL5–7), dedicated silicon, and minimal firmware surface. TEEs offer general-purpose computation with logical isolation but share the CPU die, lack physical tamper resistance (EAL2–4), and have a larger attack surface with documented side-channel history. Contractual controls (NDA, audit rights, SLAs) partially mitigate this gap but do not close it. Treat TEEs as complementary to HSMs, not replacements. +| | CPU-encrypted (SGX, SEV-SNP) | Hypervisor-isolated (Nitro Enclaves) | +| ------------------------- | --------------------------------------- | ------------------------------------ | +| Protects from | Host OS, hypervisor, cloud provider | Parent instance, other tenants | +| Does not protect from | CPU manufacturer holding master keys | Cloud provider controlling hypervisor | +| Memory encryption | CPU silicon | None (hypervisor boundary only) | +| Attestation root | CPU-manufacturer signing keys | Cloud-provider root CA | +| Side-channel exposure | High (Spectre, cache timing) | Lower (VM boundary) | -### What TEEs Protect +## Protocol -- **Confidentiality**: Data and code encrypted in memory; inaccessible to host OS/hypervisor -- **Integrity**: Tamper detection via hardware measurements and attestation -- **Isolation**: Execution separated from other processes and privileged software +1. [operator] Deploy the workload with a measured code image, generate or import secrets, and configure attestation expectations. +2. [operator] The enclave produces an attestation report containing the code measurement and platform configuration. +3. [verifier] Check the report against the expected measurement and the vendor's certificate chain; bind a session key to a successful attestation. +4. [user] Establish an authenticated channel to the enclave using the bound session key and submit confidential inputs. +5. [enclave] Execute the computation, encrypt outputs before they leave the enclave, and return them over the authenticated channel. +6. [operator] Log attestation events and operations; seal state for persistence with anti-rollback controls. +7. [operator] Rotate code or firmware as required; re-attest and migrate sealed state under a controlled procedure. -### What TEEs Do NOT Protect +## Guarantees & threat model -- **Availability**: Host can deny service, power off, or refuse to schedule enclave -- **I/O Channel Control**: Host operator controls all enclave communication (e.g., vsock) and can intercept, reorder, drop, replay, and inject messages — even without reading enclave memory -- **Communication Metadata**: Packet sizes, processing duration, and connection patterns remain visible even with encrypted payloads, leaking operation types -- **Side Channels**: Timing, cache, power, and speculative execution leaks remain possible without constant-time cryptography and platform-specific mitigations -- **Physical Attacks**: Sophisticated attackers with hardware access may extract secrets -- **Supply Chain**: Compromised hardware from manufacturing may have backdoors +Guarantees: -## Protocol (concise) +- Confidentiality of data and code in memory from the host operating system and hypervisor, under the stated vendor trust assumptions. +- Integrity: attestation proves that the running code and configuration match the approved measurement. +- Auditability: attestation logs create a verifiable execution history. +- Portability: sealed state can be migrated between attested enclaves of the same family. -1. **Provision**: Deploy TEE workload with measured code image; generate or import secrets. -2. **Attest**: TEE produces attestation report; verifier checks measurement against expected values. -3. **Establish Trust**: Clients verify attestation before sending sensitive data. -4. **Execute**: TEE processes confidential data; results encrypted before leaving enclave. -5. **Audit**: Log attestation events and operations for compliance; seal state for persistence. -6. **Rotate/Upgrade**: Update code or firmware; re-attest; migrate sealed state if needed. +Threat model: -## Failure Modes +- Hardware-vendor and microcode correctness, including the attestation-signing key hierarchy. +- Firmware vulnerabilities; exposure is bounded by TCB recovery cadence and update policy. +- Microarchitectural side channels (cache, speculative execution, timing). Constant-time implementations and platform-specific mitigations are required; absence is a live risk. +- I/O-channel control. The host operator controls every byte crossing the enclave boundary and can intercept, reorder, drop, replay, or inject messages even without reading enclave memory. +- Metadata: packet sizes, processing time, and connection patterns remain observable even with encrypted payloads. +- Physical attacks with hardware access, supply-chain compromise, and denial of service (the host can simply refuse to run the enclave). -| Failure Mode | Description | Impact | Mitigation | -| --------------------------------------- | --------------------------------------------------------------------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -| **Supply Chain Compromise** | Backdoored hardware from manufacturing | Complete confidentiality loss | Multi-vendor, hardware audits, attestation checks | -| **Firmware Vulnerability** | Exploitable bugs in microcode/firmware | Enclave escape, secret extraction | TCB recovery, rapid patching, version policies | -| **Side-Channel Attack** | Cache timing, Spectre/Meltdown variants | Partial secret leakage | Constant-time code, partitioning, updates | -| **Rollback Attack** | Replay of old sealed state | Policy bypass, double-spend | Monotonic counters, external anchoring | -| **Denial of Service** | Host refuses to run enclave | Availability loss | Redundancy, fallback procedures, SLAs | -| **I/O Manipulation** | Operator intercepts, reorders, or injects messages on the channel | Data corruption, front-running, censorship | Authenticated channels with sequence numbers, ZK proofs of execution, multi-operator setups | -| **Incomplete Attestation Verification** | Client skips certificate chain or platform register validation | Code substitution while attestation appears valid | Validate full certificate chain to vendor root CA, check all platform registers, use nonce freshness | -| **Key Exfiltration** | Bug in enclave code leaks secrets | Complete compromise | Audits, formal verification, minimal TCB | +Failure modes and mitigations: -## Guarantees - -- **Confidentiality**: Protected from host/operator under stated trust assumptions -- **Integrity**: Attestation proves code and configuration match expectations -- **Auditability**: Attestation logs provide verifiable execution history -- **Portability**: Secrets can be sealed and migrated between attested enclaves +| Failure mode | Impact | Mitigation | +| -------------------------------------- | ----------------------------------------------------- | -------------------------------------------------------------------- | +| Supply-chain compromise | Full confidentiality loss | Multi-vendor, hardware audits, attestation checks | +| Firmware vulnerability | Enclave escape, secret extraction | TCB recovery, rapid patching, version policies | +| Side-channel attack | Partial secret leakage | Constant-time code, partitioning, platform mitigations, updates | +| Rollback attack | Policy bypass, double-spend | Monotonic counters, external anchoring | +| Denial of service | Availability loss | Redundancy, fallback procedures, SLAs | +| I/O manipulation | Data corruption, front-running, censorship | Authenticated channels with sequence numbers, proofs of execution, multi-operator setups | +| Incomplete attestation verification | Code substitution while attestation appears valid | Validate full vendor certificate chain, check platform registers, nonce freshness | +| Key exfiltration from enclave bug | Full compromise | Audits, formal verification, minimal trusted-computing base | ## Trade-offs -- **Hardware Dependency**: Locked to specific vendors; supply constraints possible -- **Trust Surface**: Larger than pure cryptographic solutions; hardware/firmware vulnerabilities affect all deployments -- **Performance**: Fast execution but limited memory (SGX); context switches have overhead -- **Lifecycle**: Hardware security erodes over time as attacks improve; plan for migration -- **Regulatory Uncertainty**: Some regulators may not accept "black box" execution for audit purposes -- **CROPS context (both)**: In I2U, the institution operates the TEE — user has no independent verification of enclave integrity, making privacy dependent on institutional trust. CR improves with multi-operator/multi-vendor TEE setups. Security improves with TEE+ZK combination (removes attestation dependency for verifiability). - -## When TEEs Are Appropriate - -| Use Case | TEE Fit | Notes | -| ------------------------- | ---------- | ------------------------------------------------------ | -| Hot key management | Good | Faster than MPC; acceptable trust for operational keys | -| Private matching engine | Good | Real-time performance; ZK too slow for orderbooks | -| Bridge/oracle relayer | Acceptable | Defense in depth with other controls | -| Long-term custody | Poor | Prefer MPC or cold storage for years-long secrets | -| Regulatory-critical audit | Uncertain | Depends on regulator acceptance | - -## Defense Layers - -A TEE alone is insufficient for high-value production workloads. Each layer reduces the trust surface: - -| Layer | Composition | What it adds | -| ------------------------ | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **TEE only** | Single enclave, single operator | Memory isolation. Vulnerable to operator I/O manipulation, side-channels, single point of compromise. Suitable for pilots and low-value operations only | -| **TEE + Threshold Keys** | Key material distributed across multiple TEE instances operated by independent parties | No single compromise yields full key. Minimum viable for production custody and coordination | -| **TEE + ZK** | TEE executes, produces ZK proof verified on-chain | Mitigates operator I/O manipulation: even if the operator tampers with inputs/outputs, the ZK proof will not verify unless execution was correct. Removes dependency on attestation infrastructure for verifiability (see [Hybrid TEE + ZK Settlement](pattern-tee-zk-settlement.md)) | -| **TEE + Threshold + ZK** | Full defense in depth | Threshold trust, cryptographic verifiability, hardware isolation as complementary layers | +- Hardware dependency: platforms are tied to specific vendors and subject to supply constraints. +- Trust surface is larger than pure cryptographic solutions; hardware or firmware vulnerabilities can affect all deployments simultaneously. +- Performance: execution is fast but memory is limited in some platforms; context switches add overhead. +- Lifecycle: hardware security erodes as attacks improve, so migration paths must be planned in advance. +- Regulatory acceptance varies; some regulators still treat hardware-isolated execution as opaque for audit purposes. +- Defense layering is usually required: TEE-only deployments are acceptable only for pilots or low-value operations. Production-grade custody and coordination typically combine the TEE with threshold keys and, where verifiability is needed, zero-knowledge proofs of execution. ## Example -**Confidential Order Matching** - -1. Exchange deploys matching engine inside AWS Nitro Enclave. -2. Traders verify attestation showing approved matching code. -3. Orders submitted encrypted; decrypted only inside enclave. -4. Matching occurs privately; only fills are published. -5. Attestation logs prove matching logic was not tampered with. -6. Auditors can verify code measurements without seeing order flow. +A bank deploys a confidential matching engine for block trades inside a hardware-isolated enclave. Traders verify the attestation before submitting encrypted orders; matching runs inside the enclave and only fills are published. Attestation logs record that the approved matching code was executed for each batch, while auditors can verify the code measurement without seeing order flow. Threshold key shares and a zero-knowledge proof of execution are added in a later phase to reduce the blast radius of any single compromise. ## See also -- [TEE Key Manager](pattern-tee-key-manager.md) - Specific application for custody -- [Hybrid TEE + ZK Settlement](pattern-tee-zk-settlement.md) - TEE execution with ZK verification -- [MPC Custody](pattern-mpc-custody.md) - Cryptographic alternative to TEE key management -- [Verifiable Attestation](pattern-verifiable-attestation.md) - On-chain attestation verification - -## See also (external) - -- Bluethroat Labs TEE Security Handbook: https://docs.bluethroatlabs.com/ -- Confidential Computing Consortium: https://confidentialcomputing.io/ -- awesome-tee-blockchain: https://github.com/dineshpinto/awesome-tee-blockchain +- [Confidential Computing Consortium](https://confidentialcomputing.io/) +- [awesome-tee-blockchain](https://github.com/dineshpinto/awesome-tee-blockchain) +- [Fhenix](../vendors/fhenix.md) +- [iExec](../vendors/iexec.md) diff --git a/patterns/pattern-tee-key-manager.md b/patterns/pattern-tee-key-manager.md index 2b8ab55..5ed66e8 100644 --- a/patterns/pattern-tee-key-manager.md +++ b/patterns/pattern-tee-key-manager.md @@ -1,133 +1,118 @@ --- -title: "Pattern: TEE key manager" +title: "Pattern: TEE Key Manager" status: draft -maturity: pilot +maturity: testnet +type: standard layer: offchain -privacy_goal: Isolate private keys in TEE with policy-bound signing; no on-chain transaction privacy -assumptions: Attested TEE hardware (SGX/SEV), attestation verification service, KMS for bootstrapping -last_reviewed: 2026-01-14 +last_reviewed: 2026-04-22 + works-best-when: - - Institutions need hot or warm keys with stronger isolation than software-only wallets. - - TEE operator and hardware vendor are known and contractually bound. + - An institution needs hot or warm key custody with stronger isolation than a software-only wallet. + - The hardware vendor and operator are known, contractually bound, and operationally mature. + - Signing workloads are moderate in throughput and can tolerate attestation and policy-check latency. avoid-when: - Key security must not depend on specific hardware vendors or cloud operators. - - The threat model includes strong physical or microarchitectural side-channel attackers against the TEE. -dependencies: - - Attested TEEs (Intel SGX/AMD SEV) + - The threat model includes strong physical or microarchitectural side-channel attackers. + - Custody duration exceeds the security lifecycle of the underlying hardware platform. + context: both +context_differentiation: + i2i: "Between institutions, TEE key managers operate under bilateral agreements covering physical security, attestation verification, TCB recovery, and incident response. Threshold distribution across operators and vendors is expected for anything above pilot value, and attestation measurements become shared artefacts in compliance reviews." + i2u: "For user-facing keys, a single-operator TEE is insufficient: the user has no independent way to verify enclave integrity, and the operator alone can halt signing. Multi-operator threshold deployments and publishable attestation measurements are required before the custody claim translates to a meaningful user-side guarantee." + crops_profile: cr: low - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "The host operator can refuse to schedule the enclave or drop messages on the I/O channel, so single-operator deployments are structurally censorable. Threshold custody across independent operators raises the floor by requiring coordinated action to withhold signatures." + o: "Key-manager policy logic and attestation-verification code can be open-sourced, and platforms such as Open Enclave are available. Vendor attestation services and microcode remain closed." + p: "Private keys stay inside the enclave under the stated trust assumptions. Signing requests and request context are visible to the operator at the channel level unless additionally encrypted end-to-end; this is a metadata leakage concern even when plaintext never leaves the enclave." + s: "Rides on hardware-vendor key integrity, firmware and microcode discipline, correct enclave code, attestation-verifier correctness, and anti-rollback of protected state. Side-channel and supply-chain risks are active and require continuing platform hygiene." + +post_quantum: + risk: high + vector: "Signing keys stored inside the enclave (ECDSA on secp256k1, BLS for validator signing) are broken by a CRQC. Attestation chains additionally rely on vendor ECDSA keys (for example, Intel DCAP), so a CRQC invalidates remote attestation itself." + mitigation: "Post-quantum signature schemes (ML-DSA, SLH-DSA) inside the enclave for application signing, and vendor roadmaps for post-quantum attestation. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + requires: [pattern-tee-based-privacy] + composes_with: [pattern-verifiable-attestation, pattern-mpc-custody, pattern-user-controlled-viewing-keys] + alternative_to: [pattern-mpc-custody] + see_also: [pattern-tee-zk-settlement] + +open_source_implementations: + - url: https://github.com/openenclave/openenclave + description: "Open Enclave SDK used for enclave-hosted key managers on Intel SGX" + language: "C, C++" + - url: https://github.com/fortanix/rust-sgx + description: "Rust SGX toolchain suitable for building attested enclave services" + language: "Rust" --- ## Intent -Use an attested trusted execution environment (TEE) as a key manager for institutional Ethereum keys. -Keys are generated or imported inside a TEE workload (an enclave or confidential VM, depending on the platform) that enforces signing policy and produces signatures while keeping private key material isolated from the host and operator. -External systems bind the signer public key and policy hash to an approved attested measurement/configuration via an attestation verifier; on-chain registries (or EAS) may record this binding for audit, but are not themselves the verifier. - -## Ingredients - -- **Standards** - - TEE attestation formats and reports (for example, [Intel SGX DCAP / ECDSA quotes](https://www.intel.com/content/dam/develop/public/us/en/documents/intel-sgx-dcap-ecdsa-orientation.pdf), [AMD SEV-SNP attestation reports](https://www.amd.com/content/dam/amd/en/documents/developer/lss-snp-attestation.pdf)). - - Optional: [Ethereum Attestation Service (EAS)](https://docs.attest.org/) entries for measurement/config and policy hash (audit log). - - Ethereum assets or keys under custody (for example,[ERC-3643](https://www.erc3643.org/), EOAs on secp256k1, validator signing keys on BLS). - -- **Infra** - - Certified TEE hardware in secure data centres or cloud environments. - - Attestation verification service that validates attestation reports (and platform configuration policy) and registers approved signer public keys and measurements/configuration. - - Registry (on-chain or off-chain) that maps approved signer keys to institutions and policies. - -- **Off-chain** - - KMS or HSM used only for bootstrapping and controlled key migration into the TEE (if importing legacy keys is required). - - Internal approvals / policy system that feeds rules into the TEE. - - Monitoring for TEE health, firmware/TCB status, and attestation freshness. +Run an institutional key manager inside an attested hardware-isolated environment. Keys are generated or imported inside the enclave, which enforces a signing policy and produces signatures while keeping private key material isolated from the host and operator. External systems bind the signer public key and policy hash to an approved attested measurement via an attestation verifier; on-chain registries can record this binding for audit. -## Protocol (concise) +## Components -1. **Provision and attest** - - Deploy the key-manager as a TEE workload (enclave or confidential VM) with a well-defined, attested initial image and configuration (e.g., debug disabled, accepted TCB/firmware levels). - - The TEE produces an attestation report with code measurement and platform configuration. - - The attestation service verifies the report and registers the signer public key and measurement/configuration in a registry. +- Attested hardware platform (CPU-encrypted enclave or hypervisor-isolated enclave) providing remote attestation and sealed persistence. +- Key-manager workload implementing generation, import, signing policy, and rotation. +- Attestation verification service that validates attestation reports against platform configuration policy and approves signer public keys against a measurement registry. +- Registry that maps approved signer keys to institutions and active policies; can be on-chain via an attestation service or off-chain under stricter controls. +- Internal policy and approvals system feeding rules into the enclave over an authenticated channel. +- Monitoring for enclave health, firmware and TCB status, and attestation freshness. +- Bootstrap path (hardware security module or enterprise key-management service) used only for controlled key import, if legacy keys must be migrated. -2. **Generate or import keys** - - For new keys, generate key pairs inside the TEE **only if** the platform provides a cryptographically strong entropy source available to the TEE at generation time; otherwise, import keys (or derive keys from an external root under a controlled process). - - Store key material using platform-specific protected persistence (e.g., sealing or hardware-rooted encryption), with explicit anti-rollback/versioning when policy depends on mutable state. - - If the environment allows cloning or snapshot restore, treat first-boot entropy and key uniqueness as an explicit requirement (or disable keygen and require controlled import). - - For existing keys, a one-time controlled import moves keys into the TEE over an authenticated channel using key-wrapping. Decommissioning legacy storage is an operational control; true “revocation” usually requires rotating assets/permissions away from the old key. +## Protocol -3. **Configure policy** - - Institution defines signing policy (assets, destinations, limits, required approvals). - - Policy is loaded into the TEE over an authenticated channel and stored as protected state (with an explicit version number). - - A hash of the active policy can be anchored in EAS or the registry for auditability. +1. [operator] Deploy the key-manager workload with an approved initial image and configuration (debug disabled, accepted TCB levels) and obtain an attestation report from the enclave. +2. [verifier] Verify the attestation report, check platform configuration against policy, and register the signer public key and measurement in the registry. +3. [enclave] Generate new keys inside the enclave when the platform provides a strong entropy source, or accept a controlled import over an authenticated channel; store key material using platform-specific protected persistence with explicit anti-rollback. +4. [operator] Load the institution's signing policy (assets, destinations, limits, approvals) into the enclave over an authenticated channel and anchor a hash of the active policy in the registry. +5. [user] Submit signing requests with unsigned transactions or messages plus context (purpose, approvals, limits) to the enclave over an authenticated, encrypted channel. +6. [enclave] Reconstruct signing intent, check the request against policy and protected state (limits, replay, approvals), and either sign or return a rejection without exposing key material. +7. [operator] On key events (creation, import, rotation, policy change), write an append-only record signed by the TEE-held key and anchor its hash in the registry; rotate under a controlled procedure and retire old keys. -4. **Submit signing requests** - - Client systems send unsigned transactions or messages plus context (purpose, approvals, limits) to the TEE over an authenticated, encrypted channel. - - The TEE reconstructs signing intent from the request and context (e.g., chainId, to, value, calldata hash, nonce rules, validity window). +## Guarantees & threat model -5. **Enforce policy and sign** - - The TEE checks the request against stored policy and current protected state (for example, daily limits, replay protection, approval thresholds). - - If the request passes, the TEE signs with the protected key and returns the signature. - - If it fails, the TEE returns a clear rejection without exposing key material. +Guarantees: -6. **Audit and rotate** - - For key events (creation, import, rotation, policy change), write an append-only record **signed by the TEE-held key**; optionally publish its hash to EAS for audit. The linkage to a measurement/configuration is established by the attestation verifier that approved the signer key. - - Rotation generates new keys inside the TEE, updates dependent systems, and retires old keys; protected state (including versioning / anti-rollback) is updated accordingly. +- Key confidentiality under the hardware-vendor trust assumptions: the host operating system, hypervisor, and operator cannot read plaintext private keys from the protected execution context. +- Policy-bound signing: the enclave only signs requests that satisfy the attested code and protected policy, assuming correct parsing and strict domain separation (for example, EIP-155 for transactions, EIP-712 for structured messages); avoid "sign arbitrary bytes" interfaces. +- Attested signer identity: approved public keys are tied, via remote attestation, to a specific measurement and platform configuration. Without forging attestation or compromising the registry, an attacker cannot impersonate the key manager. +- Auditable lifecycle: key generation, import, rotation, and policy changes link to approved configurations through the verifier and registry without revealing private keys. -## Guarantees +Threat model: -- **Key confidentiality under TEE assumptions** - - If TEE isolation holds and attestation verification correctly excludes unsafe configurations, the host OS, hypervisor, and operator should not be able to directly read plaintext private keys from the protected execution context. - - Any key state stored outside the TEE is encrypted via platform-specific protected persistence (e.g., sealing or hardware-rooted encryption). Rollback resistance and portability depend on the platform and your anti-rollback design. - - Key confidentiality does not imply key unpredictability/uniqueness unless key generation uses a strong entropy source available to the TEE. - - Network metadata, traffic patterns, and timing remain visible; microarchitectural side-channels are not solved by default. Treat them as in-scope unless you have platform-specific mitigations and validation. - -- **Policy-bound signing** - - The TEE only signs requests that satisfy the attested code and protected policy. - - This depends on correct parsing and explicit domain separation (e.g., [EIP-155](https://eips.ethereum.org/EIPS/eip-155) for transactions, [EIP-712](https://eips.ethereum.org/EIPS/eip-712) for structured messages); avoid “sign arbitrary bytes” interfaces. - - An attacker who can submit signing requests but cannot change TEE code, configuration, or registry entries **should not** be able to cause signatures that violate configured rules, assuming correct parsing, domain separation, and policy implementation. - -- **Attested signer identity** - - Approved signer public keys are tied (by the verifier’s acceptance policy), via remote attestation, to a specific measurement and platform configuration. - - Without forging attestation or compromising the verifier/registry, an attacker cannot impersonate the key manager. - -- **Auditable lifecycle** - - Key generation, import, rotation, and policy changes can be linked to an approved configuration through the verifier/registry, supporting compliance reviews and incident response without revealing private keys. +- TEE vendor (silicon, microcode, attestation roots), the operator (physical security, I/O control, availability), and enclave code correctness (parsing, domain separation, policy logic). +- Attestation verifier and registry integrity; compromise of either allows unapproved signer keys to be accepted. +- Supply-chain or firmware compromise breaking TEE isolation or forging attestation. +- Microarchitectural and side-channel attacks leaking keys or policy state until platforms are patched. +- Rollback or snapshot attacks restoring older protected state to bypass limits; anti-rollback and external anchoring are required. +- Bugs in secure boot, attestation checks, debug controls, or policy code that cause over-broad signing while attestation appears valid. +- Key entropy: if the platform does not provide strong entropy to the enclave at generation time, generated keys may not be unique or unpredictable; import or derivation from an external root under controlled processes must be used instead. +- Key confidentiality does not equal key unpredictability. Metadata on signing requests (timing, sizes) is not hidden by this pattern. ## Trade-offs -- **Trust surface** - - Security depends on the TEE vendor (silicon, microcode, attestation roots/keys), the operator (physical security, provisioning, availability, and I/O channel control), and TEE code (correct, non-malicious policy logic), plus the attestation verifier and registry. - - These are stronger trust assumptions than fully trust-minimised custody (for example, MPC without hardware trust anchors) and must be reflected in risk assessments. - - TEE key isolation provides weaker guarantees than HSM custody (no physical tamper resistance, larger attack surface, documented side-channel history). In institutional settings, contractual controls with TEE operators partially mitigate this gap. Treat TEE key managers as complementary to HSMs, not replacements. - -- **Attack and failure modes** - - Supply-chain or firmware compromise can break TEE isolation or allow forged/meaningless attestation. - - Microarchitectural and side-channel attacks (cache, speculative execution, etc.) can leak keys or policy state until platforms are patched or mitigated. - - Rollback or snapshot attacks can restore older protected state to bypass limits or replay approvals if anti-rollback and logging are missing or misused. - - Misconfiguration of secure boot, attestation checks, or debug controls, or bugs in TEE or policy code, can lead to incorrect or over-broad signing while attestation still appears valid. - -- **Operational and performance limits** - - Secure provisioning, protected-state handling, monitoring, re-attestation, key rotation, and incident response runbooks are required; loss or corruption of protected state without a recovery plan can render keys unusable. - - TEE execution and policy checks add latency and cap throughput, making this pattern better suited to treasury, validator, and institutional flows than very high-frequency trading. - -- **Single-TEE limitation** - - A single TEE instance is a single point of compromise. For production custody, threshold key distribution across multiple TEE instances operated by independent parties is recommended. Single-TEE deployments are acceptable for pilot use or warm/operational keys with limited exposure. - - See [TEE-Based Privacy — Defense Layers](pattern-tee-based-privacy.md#defense-layers) for the layered security model. -- **CROPS context (I2I)**: Security improves to `high` with threshold keys across multiple independent TEE instances. Single-TEE is acceptable for pilot only. -- **Post-quantum exposure**: ECDSA/BLS signing keys are broken by CRQC. Mitigation: PQ signature schemes (ML-DSA, SLH-DSA) within TEE. Note: TEE attestation infrastructure also relies on CPU manufacturer ECDSA signing keys (e.g., Intel SGX DCAP); PQ attestation schemes will be needed for long-term TEE trust. See [Post-Quantum Threats](../domains/post-quantum.md). +- Trust anchors (vendor, operator, attestation verifier, registry) are stronger than fully trust-minimised custody and must be reflected in risk assessments. +- Hardware Security Modules remain the baseline for physical tamper resistance; TEE key managers are complementary, not replacements. +- Performance: attestation and policy checks add latency and cap throughput; better suited to treasury, validator, and institutional flows than very high-frequency trading. +- Operational maturity: provisioning, protected-state handling, monitoring, re-attestation, key rotation, and incident response runbooks are all required. Loss or corruption of protected state without a recovery plan can render keys unusable. +- Single-enclave deployments are a single point of compromise. Production custody typically distributes keys across multiple enclaves operated by independent parties; single-enclave deployments should be limited to pilot use or warm operational keys. ## Example -- A bank runs a TEE key manager for its Ethereum treasury and [ERC-3643](https://www.erc3643.org/) instruments. -- Keys are generated inside the TEE where the platform provides strong entropy; policy restricts transfers to approved counterparties and daily limits. -- Treasury operators use an internal system that submits unsigned transactions and approvals (e.g., signed attestations) bound to signing intent. -- The TEE checks policy, signs approved transactions, and returns signatures for broadcast without exposing private keys outside the TEE. +An institution runs a TEE-backed key manager for its treasury and tokenised-asset instruments. Keys are generated inside the enclave on a platform with a strong entropy source; policy restricts transfers to approved counterparties and daily limits. Treasury operators submit unsigned transactions and signed internal approvals over an authenticated channel. The enclave checks the request, signs approved transactions, and returns signatures for broadcast. Key events are anchored in an on-chain registry for audit. ## See also -- Pattern: [MPC Custody](./pattern-mpc-custody.md) -- Pattern: [TEE ZK Settlement](./pattern-tee-zk-settlement.md) -- Pattern: [Verifiable Attestation](./pattern-verifiable-attestation.md) \ No newline at end of file +- [Intel SGX DCAP orientation](https://www.intel.com/content/dam/develop/public/us/en/documents/intel-sgx-dcap-ecdsa-orientation.pdf) +- [AMD SEV-SNP attestation](https://www.amd.com/content/dam/amd/en/documents/developer/lss-snp-attestation.pdf) +- [Ethereum Attestation Service](https://docs.attest.org/) +- [Fireblocks](../vendors/fireblocks.md) diff --git a/patterns/pattern-tee-network-anonymity.md b/patterns/pattern-tee-network-anonymity.md index 04b611c..53d2b95 100644 --- a/patterns/pattern-tee-network-anonymity.md +++ b/patterns/pattern-tee-network-anonymity.md @@ -1,84 +1,104 @@ --- title: "Pattern: TEE-Assisted Network Anonymity" status: draft -maturity: PoC +maturity: research +type: standard layer: offchain -privacy_goal: Hide sender identity (IP, timing) for both reads and writes at the transport layer -assumptions: TEE availability on client side, semi-honest server majority -last_reviewed: 2026-02-18 +last_reviewed: 2026-04-22 + works-best-when: - - Metadata leakage (IP, timing, query patterns) is a threat - - Low latency is required (rules out Tor/mixnets) - - Both read and write privacy are needed from the same infrastructure + - Metadata leakage (IP, timing, query patterns) is a threat. + - Low latency is required so higher-latency anonymity networks are not viable. + - Both read and write privacy must come from the same infrastructure. avoid-when: - - Threat model does not include network observers - - Running own node eliminates RPC provider trust - - High-latency anonymity networks (Tor, Nym) are acceptable -dependencies: - - TEE (client-side) - - Secret sharing - - Additive homomorphic commitments + - The threat model does not include network-level observers. + - Running a local full node already removes RPC-provider exposure. + - Higher-latency anonymity networks such as onion routing or mixnets are acceptable. + context: both +context_differentiation: + i2i: "Institutions often run dedicated nodes or relays, so metadata exposure is between institutions rather than from user to institution. The TEE-assisted layer hides query patterns and transaction timing from counterparty infrastructure at latencies compatible with trading desks." + i2u: "End users typically route through institution-operated RPC endpoints that can correlate queries and transactions. The client-side TEE lets users split their payload so no single server sees the cleartext, giving institutional-grade metadata protection without the high latency of mixnets." + crops_profile: cr: medium - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "Censorship resistance reaches `medium` because submission does not depend on any one server, but the server set is still permissioned and can be pressured by jurisdiction." + o: "Core designs are published in research papers and prototypes are open, yet production-grade deployments and the server operator set may be governed by a single vendor." + p: "Sender anonymity is `partial`: the cryptographic layer preserves unlinkability even if the TEE is compromised, but metadata protection depends on a semi-honest server majority and a sufficient anonymity set during the round." + s: "Security rides on TEE attestation integrity, correct secret-sharing implementation, and an honest majority among anonymity servers. Side-channel attacks on the client TEE can degrade guarantees." + +post_quantum: + risk: medium + vector: "Additive homomorphic commitments and key exchange between client and servers rely on elliptic-curve primitives broken by a CRQC; Harvest-Now-Decrypt-Later risk applies to anyone recording the traffic." + mitigation: "Migrate the key-encapsulation and commitment layers to post-quantum primitives (ML-KEM for key exchange, lattice-based commitments). See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [] + +related_patterns: + composes_with: [pattern-private-transaction-broadcasting, pattern-threshold-encrypted-mempool, pattern-shielding] + alternative_to: [pattern-onion-routing, pattern-mixnet-anonymity] + see_also: [pattern-network-anonymity, pattern-tee-based-privacy, pattern-modular-privacy-stack] + +open_source_implementations: + - url: https://writings.flashbots.net/network-anonymized-mempools + description: "Flashnet writeup of a TEE-assisted anonymous mempool design (research)" + language: "N/A (design spec)" --- ## Intent -Hide *who* is sending transactions or querying state at the network layer. Existing privacy patterns hide *what* (transaction content, balances) but not *who* — IP addresses, timing, and query patterns still leak sender identity. This pattern provides sender anonymity for both writes (transaction submission) and reads (RPC queries) with latency suitable for DeFi. +Hide who is sending transactions or querying state at the network layer with latency low enough for interactive workloads. Content-privacy patterns hide what is in a transaction but not who submitted it; IP addresses, timing, and query patterns still leak sender identity. A client-side Trusted Execution Environment secret-shares the outbound payload across a set of servers so that no single server sees the cleartext, and the anonymity guarantee survives a compromise of the TEE at the cost of liveness. + +## Components -## Ingredients +- Client-side Trusted Execution Environment: generates and verifies the secret-sharing of the outbound message, and attests to correct construction. +- Secret-sharing layer: splits each message into shares that can only be reconstructed by the aggregate of server contributions. +- Additive homomorphic commitments: allow servers to compute aggregate outputs over encrypted shares without decrypting any individual share. +- Anonymity server set: a semi-honest majority that processes shares, computes homomorphic sums, and forwards aggregated traffic. +- Leader node: reconstructs aggregated output from server contributions and delivers it to the destination (RPC endpoint or mempool). -- Cryptographic: secret sharing, additive homomorphic commitments -- Hardware: client-side TEE (ensures correct secret sharing without revealing message) -- Infra: server network (semi-honest majority), leader node for output reconstruction +## Protocol -## Protocol (concise) +1. [user] Place the outbound message, a transaction or an RPC query, into a random slot of a fixed-size array. +2. [user] The client-side Trusted Execution Environment secret-shares the array across the anonymity servers and attests that the shares were built correctly. +3. [operator] Each server receives one share and, because no single server sees the full array, cannot recover the message on its own. +4. [operator] Servers compute additive homomorphic sums over the incoming shares from all clients in the round. +5. [operator] The leader reconstructs the aggregated output by combining the server contributions. +6. [operator] The aggregated output is delivered to the destination; the real messages appear without any binding to the clients that submitted them. -1. Client positions message (transaction or query) in a random slot of a fixed-size array. -2. Client TEE secret-shares the array across servers, verifying correct construction. -3. Servers receive encrypted shares; no single server sees the original message. -4. Servers compute homomorphic sums over all client shares. -5. Leader reconstructs aggregated output from server contributions. -6. Output reveals messages but not which client sent which message. +## Guarantees & threat model -## Guarantees +Guarantees: -- Hides sender IP, timing correlation, and query-to-identity mapping. -- TEE compromise loses liveness (system stalls), never anonymity (crypto layer preserves it). -- Same infrastructure anonymizes both transaction submission and state queries. -- Does not hide message content — pair with content-privacy patterns for full stack. +- Sender IP, timing correlation, and query-to-identity mapping are hidden from any single server and from downstream RPC or mempool infrastructure. +- The same infrastructure anonymizes transaction submission and state queries, so read-side and write-side metadata protection share a single deployment. +- A client Trusted Execution Environment compromise costs liveness, not anonymity: the cryptographic layer still prevents reconstruction of individual messages. + +Threat model: + +- Semi-honest majority among anonymity servers; a colluding majority can halt the round but still cannot reconstruct individual messages unless the TEE has also been compromised. +- Client Trusted Execution Environment integrity for liveness and for correct share construction. A compromised TEE can submit malformed shares that stall the round. +- Network-layer cover: the anonymity set is all clients active in the same round. In a low-adoption deployment, the effective guarantee degrades. +- Message content is out of scope; pair with a content-privacy pattern such as shielding or threshold encryption for a full stack. ## Trade-offs -- Anonymity trilemma: anonymity set size, latency, and bandwidth (cover traffic) are in tension. Pure-crypto approaches (Tor, Nym, DC-Nets) must sacrifice at least one. TEE-assisted designs like Flashnet relax the trilemma by offloading verification to hardware, but introduce a hardware trust assumption for liveness. -- Client TEEs required for liveness; hardware trust for availability only, not privacy. -- Requires semi-honest majority among servers; colluding majority can break liveness. -- Research-stage (Flashbots Flashnet); no production deployment as of 2026-04. -- **CROPS context (both)**: Privacy is `partial` because anonymity rests on a client-side TEE and a semi-honest server majority; a TEE compromise or majority collusion breaks liveness (the system stalls) rather than anonymity, since the cryptographic layer preserves unlinkability. Defense in depth (pairing with Tor or a mixnet) strengthens guarantees when the TEE trust assumption is weakened. In I2U, end-users leak identity to RPC providers operated by institutions without this layer. In I2I, institutions may already run their own nodes, reducing the need. +- The anonymity trilemma of anonymity-set size, latency, and bandwidth still applies. Hardware assistance relaxes it compared to pure-cryptographic designs but does not eliminate it. +- Client Trusted Execution Environments are required on the submission path, which constrains device support and adds attestation infrastructure. +- Live deployments are research-stage; there is no production service targeting Ethereum as of 2026-04, and server-operator governance is still being defined. +- Defence in depth can pair this layer with onion routing or a mixnet when the hardware trust assumption is considered weaker than the cryptographic layer. ## Example -1. Fund manager queries 50 token balances across DeFi protocols to value portfolio. -2. Without network anonymity, RPC provider sees all queried addresses — revealing holdings and strategy. -3. Queries are secret-shared via client TEE across anonymity server network. -4. Servers process shares; RPC provider sees aggregated queries from many clients, cannot attribute any query to the fund manager. -5. Result: Portfolio valued without leaking positions or identity to any infrastructure provider. +A fund manager needs to query balances for fifty tokens across decentralized-finance protocols to value a portfolio. Without network anonymity, the RPC provider sees all queried addresses and can infer holdings and strategy. Each query is placed into a random slot of a fixed-size array, secret-shared by the manager's client Trusted Execution Environment across the server set, and aggregated homomorphically. The RPC provider sees a batch of queries from many clients in the round and cannot attribute any single query to the manager. Latency is under a second per round, so the workflow remains interactive. ## See also -- [Network-Level Anonymity](pattern-network-anonymity.md) - umbrella pattern and approach comparison -- [Onion Routing](pattern-onion-routing.md) - Tor-based alternative, higher latency but no hardware trust -- [Mixnet Anonymity](pattern-mixnet-anonymity.md) - strongest anonymity, highest latency -- [Private Transaction Broadcasting](pattern-private-transaction-broadcasting.md) - content privacy for writes (complementary) -- [Threshold Encrypted Mempool](pattern-threshold-encrypted-mempool.md) - content privacy via threshold encryption -- [TEE-Based Privacy](pattern-tee-based-privacy.md) - broader TEE trust model analysis -- [RFP: Private Reads](../rfps/rfp-private-reads.md) - read-side privacy gap this pattern addresses -- [Vendor: Flashbots](../vendors/flashbots.md) - Flashnet development - -## See also (external) - -- Flashbots Flashnet: https://writings.flashbots.net/network-anonymized-mempools +- [Flashbots Flashnet writeup](https://writings.flashbots.net/network-anonymized-mempools) +- [Flashbots](../vendors/flashbots.md) +- [RFP: Private Reads](../rfps/rfp-private-reads.md) diff --git a/patterns/pattern-tee-zk-settlement.md b/patterns/pattern-tee-zk-settlement.md index 442e276..93f130f 100644 --- a/patterns/pattern-tee-zk-settlement.md +++ b/patterns/pattern-tee-zk-settlement.md @@ -1,146 +1,109 @@ --- -title: "Pattern: Hybrid TEE + ZK Settlement" +title: "Pattern: Hybrid TEE + ZK settlement" status: draft -maturity: PoC +maturity: research +type: standard layer: hybrid -privacy_goal: Private settlement coordination inside TEEs with zero-knowledge proofs for on-chain verifiability -assumptions: Attested TEE infrastructure, ZK prover backend, attestation registry, participants accept hardware trust -last_reviewed: 2026-02-13 +last_reviewed: 2026-04-22 + works-best-when: - - Counterparty risk is the primary concern and atomicity of settlement is the goal - - Privacy breach (operator/manufacturer sees trade details) is an acceptable residual risk manageable through contractual controls - - Settlement coordination requires low latency that client-side ZK cannot meet + - Counterparty risk is the primary concern and atomic settlement is the goal. + - A privacy breach (the enclave operator or hardware vendor sees trade details) is an acceptable residual risk that can be bounded by contractual controls. + - Settlement coordination requires lower latency than client-side zero-knowledge proving can achieve. avoid-when: - - Trustless guarantees are required (client-side ZK is preferable) - - Regulators reject opaque enclaves without additional compliance layers - - Simple same-chain transfers where shielded pools suffice without coordination overhead -dependencies: - - Attested TEEs (Intel SGX, AMD SEV, AWS Nitro) - - zero-knowledge proof system (Groth16/PLONK) - - Stealth address support (EIP-5564) + - Trustless guarantees are required; prefer client-side zero-knowledge proving. + - Regulators reject opaque enclave execution even with downstream compliance layers. + - A simple same-chain shielded transfer is sufficient without matching or coordination. + context: i2i + crops_profile: cr: medium - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "Censorship resistance sits at `medium` because settlement ultimately anchors on L1, but the enclave operator controls order intake and message flow, so it can delay or drop submissions before on-chain anchoring." + o: "Smart contracts and proof systems are typically open source, while the enclave binary, attestation infrastructure, and operational tooling often ship from a single vendor with limited forkability." + p: "Privacy is `partial`: counterparties, amounts, and matching logic are hidden from network observers, but the enclave operator and hardware vendor can observe plaintext during execution. The zero-knowledge proof bounds financial risk but does not hide data inside the enclave." + s: "Security rides on TEE attestation integrity, correct nonce-monotonicity enforcement inside the zero-knowledge circuit, and honest state-root anchoring on L1. Side-channel attacks on the underlying hardware are a known exposure." + +post_quantum: + risk: high + vector: "Settlement proofs based on pairing-friendly curves (Groth16, PLONK with KZG) are broken by a CRQC; encrypted state blobs held by enclave operators face Harvest-Now-Decrypt-Later risk." + mitigation: "STARK-based settlement proofs with hash commitments. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [EIP-5564, ERC-20, ERC-3643] + +related_patterns: + requires: [pattern-tee-based-privacy, pattern-zk-proof-systems] + composes_with: [pattern-stealth-addresses, pattern-shielding, pattern-dvp-erc7573] + alternative_to: [pattern-co-snark] + see_also: [pattern-tee-key-manager, pattern-cross-chain-privacy-bridge] + +open_source_implementations: [] --- ## Intent -Coordinate private settlement inside TEEs, with zero-knowledge proofs attesting correct execution to smart contracts on-chain. The TEE acts as a neutral synchronization layer between parties who do not trust each other — matching orders, managing escrow state, and producing verifiable proofs — while hiding counterparties, amounts, and matching logic from all external observers. - -The key property of this construction is the separation of financial risk from privacy risk. The ZK proof guarantees correct, atomic settlement on-chain regardless of TEE integrity: counterparty risk is eliminated by the protocol, not by trusting the hardware. If the TEE is compromised (operator or manufacturer observes plaintext), the worst case is a privacy breach — trade details are exposed — but no funds are lost and settlement correctness is unaffected. In institutional settings, this residual privacy risk is manageable through contractual controls (NDA, audit rights, penalties) with TEE operators, making it a legal/commercial matter rather than a protocol failure. - -## Ingredients +Coordinate private settlement inside a Trusted Execution Environment while anchoring correctness with a zero-knowledge proof verified on-chain. The enclave acts as a neutral synchronization layer between parties who do not trust each other: it matches orders, manages escrow state, and produces a succinct proof of correct execution. External observers see only commitments, proofs, and stealth-address outputs, while the enclave operator sees plaintext under contractual terms. -- **Standards**: EIP-5564 (stealth addresses), ERC-20/3643 assets, EAS (attestations) -- **TEE platforms**: Intel SGX (90–128 MB EPC), AMD SEV (full VM memory), AWS Nitro Enclaves -- **On-chain**: State commitment contract, zero-knowledge proof verifier, attestation registry, announcement contract (for stealth key revelation) -- **Off-chain**: Encrypted state blobs (replicated), KMS for sealed storage, multiple TEE nodes for availability +The key property is the separation of financial risk from privacy risk. The zero-knowledge proof guarantees atomic settlement and state-transition correctness on-chain regardless of enclave integrity, so counterparty risk is bounded by the protocol rather than by hardware trust. If the enclave is compromised, trade details leak but funds are not lost and settlement correctness is preserved. In institutional settings, this residual privacy exposure is managed through contractual controls (non-disclosure agreements, audit rights, penalties) with the enclave operator. -## TEE API Surface +## Components -| Function | Input | Output | Purpose | -|----------|-------|--------|---------| -| `key_gen()` | Entropy source | `(pubkey, attestation_report)` | Generate enclave keypair; report contains code hash + pubkey + hardware signature | -| `attest(measurement)` | Code measurement | `signed_report` | Prove specific code runs unmodified in genuine TEE | -| `process(encrypted_orders[], state)` | User-encrypted orders, current state | `{new_state, encrypted_results[], log}` | Decrypt orders, validate nonces, match counterparties, update state | -| `prove(execution_log)` | Internal execution trace | `zk_proof` | Generate succinct proof of correct matching and state transition | -| `settle(commitment, proof, blobs)` | State root, proof, encrypted outputs | `tx_hash` | Submit proof on-chain, reveal stealth keys via announcement contract | - -Attestation verification: check hardware signature is from known manufacturer, code hash matches expected binary, TEE model is not revoked. +- Enclave keypair and attestation report: generated inside the Trusted Execution Environment and verified by each counterparty before submission. +- Matching engine inside the enclave: decrypts orders, validates nonces against state, and matches counterparties according to settlement rules. +- Stealth-address escrow: notes are locked to per-settlement stealth addresses with dual spending conditions (stealth-derived key or original-owner timeout path) enforced by the zero-knowledge circuit. +- Zero-knowledge prover inside the enclave: generates the succinct proof of correct matching and monotonic state transition. +- On-chain state commitment contract and verifier: stores state roots and checks each settlement proof. +- Announcement contract: publishes the ephemeral stealth-address keys atomically with settlement acceptance. +- Off-chain encrypted state blobs and key management: persist state across enclave restarts; replication covers enclave-node failure. ## Protocol -1. **Setup**: TEE generates keypair inside enclave, publishes attestation report and public key. Verifiers check report against manufacturer root of trust. -2. **Order submission**: Each party encrypts their order (asset, amount, conditions, nonce) to the TEE public key and submits on-chain or via direct channel. -3. **Matching**: TEE decrypts orders, validates nonces against state (rollback protection), matches counterparties according to settlement rules. -4. **Escrow via stealth addresses**: Notes are locked to stealth addresses derived per-settlement. Each note has dual spending conditions in the zero-knowledge circuit: spendable by the stealth-derived key OR by the original owner after a timeout period. -5. **Proof generation**: TEE generates a zero-knowledge proof attesting: orders were valid, matching followed protocol rules, state transition is monotonic (no rollback), output commitments are correct. -6. **On-chain settlement**: Proof is verified on-chain. On success, the TEE atomically publishes both ephemeral keys to the announcement contract, allowing recipients to derive their spending keys. -7. **Completion or timeout**: Recipients scan the announcement contract, derive spending keys, and claim their notes. If the TEE fails before revealing keys, original owners reclaim notes after the timeout period. - -## Trust Framework - -> For the general TEE threat model, failure modes, and defense layers, see [TEE-Based Privacy](pattern-tee-based-privacy.md). This section covers only what is specific to the settlement protocol. - -**Who sees what:** - -| Actor | Sees | Does not see | -|-------|------|-------------| -| Users | Own order details, own settlement outcome | Other parties' orders, matching logic | -| TEE operator | Communication metadata (packet sizes, timing, connection patterns), I/O channel control (can reorder, delay, drop messages) | Enclave memory contents (isolated by hardware) | -| Hardware vendor | Everything during execution (master keys) | Nothing after enclave destroyed | -| Network observers | Commitments, proofs, stealth address outputs | Amounts, counterparties, order flow | -| Auditors | Selectively disclosed data via viewing keys | Full state unless explicitly granted | - -**Threat model:** - -| Threat | Impact | Mitigation | -|--------|--------|------------| -| Hardware vendor compromise | Full plaintext access during execution | Multi-vendor TEE diversity, zero-knowledge proofs limit damage to current session | -| Side-channel attacks (Spectre, cache timing) | Partial data leakage | ORAM inside enclave, constant-time algorithms, firmware patching | -| Rollback / replay attacks | Double-spend, stale state processing | Nonce monotonicity enforced in zero-knowledge proof, on-chain state root anchoring | -| Single TEE failure | Service unavailability, locked funds | Multiple TEE nodes, timeout refund escape hatch in stealth note circuits | -| Fake TEE (no attestation verification) | Operator steals all data | Mandatory attestation verification before encrypting orders | -| Operator metadata leakage | Communication metadata (packet sizes, timing) can reveal trade magnitudes and enable front-running, even though the ZK proof guarantees correct execution | Constant-size message padding, constant-time processing, multi-operator coordination | -| Operator selective delay | Operator stalls settlement to lock counterparty capital while market conditions change (timeout griefing) | Appropriate timeout calibration, operator reputation/staking, multi-operator threshold | -| Supply chain tampering | Compromised hardware from manufacturing | Attestation checks, multi-vendor sourcing | - -## Guarantees - -- **Privacy**: Counterparties, amounts, and matching logic hidden from all observers including TEE operator -- **Verifiability**: zero-knowledge proof provides on-chain verification of correct execution without TEE attestation infrastructure dependency -- **Rollback safety**: Nonce monotonicity in proofs prevents replay of old state -- **Availability**: Timeout refund ensures funds are never permanently locked, even if TEE goes offline -- **Auditability**: Selective disclosure via viewing keys for regulatory compliance - -## Trade-offs +1. [operator] The enclave generates a keypair, publishes an attestation report, and exposes the public key so counterparties can verify the report and encrypt orders. +2. [user] Each counterparty encrypts its order (asset, amount, conditions, nonce) to the enclave public key and submits it on-chain or through a direct channel. +3. [operator] The enclave decrypts orders, validates nonces against state to prevent rollback, and matches counterparties according to the settlement rules. +4. [contract] Notes are locked to per-settlement stealth addresses with the zero-knowledge circuit enforcing dual spending conditions (stealth-derived key or original-owner timeout). +5. [prover] The enclave generates a zero-knowledge proof attesting that orders were valid, matching followed the protocol, state transition is monotonic, and output commitments are correct. +6. [contract] The on-chain verifier checks the proof; on success the enclave atomically publishes the ephemeral stealth-address keys to the announcement contract. +7. [user] Recipients scan the announcement contract, derive their spending keys, and claim their notes. If the enclave fails before revealing keys, original owners reclaim after the timeout. -**Failure modes and correct approach:** +## Guarantees & threat model -| Anti-pattern | Consequence | Correct approach | -|-------------|-------------|-----------------| -| Plaintext inputs/outputs | Network sees all data | Encrypt all I/O to TEE pubkey, per-user encryption keys | -| No rollback protection | Double-spend via old state | Nonce in state, zero-knowledge proof verifies monotonicity | -| Single TEE instance | Total unavailability on failure | Multiple TEE nodes with replicated encrypted state | -| TEE without zero-knowledge proofs | No public verifiability, must trust attestation | zero-knowledge proof of execution verified on-chain | -| Shared encryption key | One compromise leaks all data | Per-user encryption, key isolation | -| In-memory state only | Crash loses all funds | Persist encrypted state blobs + on-chain commitments | +Guarantees: -**Core limitations:** +- Counterparties, amounts, and matching logic are hidden from network observers; inside the enclave the operator can see plaintext under contractual terms. +- Atomic settlement: the zero-knowledge proof guarantees correct execution on-chain regardless of enclave integrity, so financial correctness is independent of hardware trust. +- Rollback safety: nonce monotonicity is enforced inside the circuit and anchored to an on-chain state root. +- Liveness floor: the timeout refund circuit ensures original owners can reclaim locked notes if the enclave goes offline. +- Auditability: viewing keys can disclose scoped data to regulators without exposing the full state. -- **Privacy depends on TEE integrity, financial correctness does not**: The ZK proof guarantees settlement correctness on-chain regardless of TEE compromise. However, the TEE hardware vendor can observe plaintext during execution — a privacy breach, not a financial one. This separation is the core design tradeoff versus client-side ZK (which provides both). -- **Cross-chain atomicity is timeout-based, not cryptographic**: When coordinating across independent networks, one leg can succeed while the other fails. The timeout refund mechanism provides safety but not true atomicity. Same-network settlement remains the most practical path to atomic DvP. -- **Performance**: 10–50% overhead versus native execution. Enclave memory limits constrain batch sizes on SGX. +Threat model: -**When to use this pattern vs alternatives:** +- Soundness of the zero-knowledge proof system and correctness of the on-chain verifier. +- Attestation integrity: counterparties must verify the hardware signature, the code measurement, and the revocation status before encrypting orders. +- Semi-honest enclave operator: a fully malicious operator can leak plaintext, reorder, delay, or drop messages, but cannot alter settlement outcomes because the proof is verified on-chain. +- Side-channel attacks on the underlying hardware (Spectre-family, cache-timing) can leak partial data even when attestation succeeds. +- Metadata leakage: packet sizes, timing, and connection patterns can reveal trade magnitudes and enable front-running; padding and constant-time processing are required. +- Supply-chain tampering on the hardware is out of scope for the protocol and must be handled at sourcing time. -| Scenario | TEE+ZK | Client-side ZK | Pure TEE | -|----------|--------|---------------|----------| -| Simple private transfers | Overkill | Preferred | Insufficient | -| Cross-chain coordination | Good fit | Cannot coordinate | No verifiability | -| High-frequency matching | Good fit | Too slow | No auditability | -| Institutional coordination (contractual trust) | Good fit | May suffice | Acceptable with audit layers | +## Trade-offs -- **CROPS context (I2I)**: Privacy is `partial` because TEE hardware vendor can observe plaintext during execution — a privacy breach manageable through contractual controls in institutional settings. ZK proof guarantees financial correctness regardless of TEE integrity. -- **Post-quantum exposure**: Groth16/PLONK proof systems rely on pairings/EC broken by CRQC. Mitigation: STARK-based settlement proofs. See [Post-Quantum Threats](../domains/post-quantum.md). +- Privacy depends on enclave integrity while financial correctness does not; this is the core design trade-off versus client-side zero-knowledge proving, which provides both at the cost of latency. +- Cross-chain atomicity is timeout-based rather than cryptographic. One leg can succeed while the other fails, and timeout refunds provide safety but not true atomicity. Same-network settlement remains the cleanest atomic-DvP path. +- Performance overhead of roughly 10 to 50 percent versus native execution, plus enclave memory limits that constrain batch sizes on some hardware. +- Multiple enclave nodes with replicated encrypted state are required to avoid a single point of failure; otherwise one crash locks all in-flight settlements until the timeout path triggers. +- Common anti-patterns (plaintext inputs or outputs, missing nonce monotonicity, shared encryption keys, in-memory-only state) silently weaken the guarantees and must be explicitly guarded against. ## Example -**Cross-border bond DvP with stealth address settlement:** - -1. Bank A (Frankfurt) wants to sell EUR-denominated corporate bonds to Bank B (Singapore) for USDC. Both assets exist on shielded pools on the same L1. -2. Both banks verify the TEE's attestation report and encrypt their orders (Bank A: sell 500 bond notes at par; Bank B: buy with 500K USDC) to the TEE public key. -3. TEE decrypts, validates nonces, confirms KYC attestations, matches the orders. Notes are locked to stealth addresses with 24-hour timeout refund. -4. TEE generates zero-knowledge proof of correct matching and submits on-chain. Proof verifies, TEE publishes both ephemeral keys to announcement contract. -5. Bank B derives the spending key for the bond notes, Bank A derives the key for the USDC notes. Settlement complete. -6. **Failure path**: If the TEE crashes after step 3 but before step 4, both banks reclaim their original notes via the timeout circuit after 24 hours. +A bank in Frankfurt wants to sell euro-denominated corporate bonds to a bank in Singapore for stablecoins, with both assets living on shielded pools on the same L1. Both banks verify the enclave's attestation report and encrypt their orders to the enclave public key. The enclave decrypts, validates nonces, confirms the compliance attestations, and matches the orders. Notes are locked to stealth addresses with a 24-hour timeout refund. The enclave generates a zero-knowledge proof of correct matching and submits it on-chain; once the proof verifies, the enclave publishes the ephemeral keys to the announcement contract. The buying bank derives the spending key for the bond notes and the selling bank derives the key for the stablecoin notes. If the enclave crashes between matching and proof submission, both banks reclaim their original notes through the timeout circuit. ## See also -- [TEE-Based Privacy](pattern-tee-based-privacy.md) — general TEE trust model, failure modes, upgrade paths -- [TEE Key Manager](pattern-tee-key-manager.md) — key generation, entropy, lifecycle in TEEs -- [DvP ERC-7573](pattern-dvp-erc7573.md) — cross-network DvP coordination standard -- [Cross-Chain Privacy Bridge](pattern-cross-chain-privacy-bridge.md) — bridging assets between chains with privacy +- [Flashbots](../vendors/flashbots.md) +- [Renegade](../vendors/renegade.md) +- [Post-Quantum Threats](../domains/post-quantum.md) diff --git a/patterns/pattern-threshold-encrypted-mempool.md b/patterns/pattern-threshold-encrypted-mempool.md index f6c3e6c..efb5c3d 100644 --- a/patterns/pattern-threshold-encrypted-mempool.md +++ b/patterns/pattern-threshold-encrypted-mempool.md @@ -1,152 +1,115 @@ --- -title: "Pattern: Threshold Encrypted Mempool" +title: "Pattern: Threshold-encrypted mempool" status: draft -maturity: pilot +maturity: testnet +type: standard layer: L1 -privacy_goal: Hide transaction content until block inclusion via threshold encryption -assumptions: Honest threshold committee (k-of-n), timely key release, compatible block builder -last_reviewed: 2026-01-14 + works-best-when: - - MEV protection required at protocol level - - Users cannot or prefer not to trust private relays - - Censorship resistance combined with pre-trade privacy needed + - Miner Extractable Value protection is needed at the protocol level rather than through a trusted relay. + - Users cannot or do not want to trust a private relay as a single point of trust. + - Censorship resistance must be combined with pre-inclusion content privacy. avoid-when: - - Committee liveness requirements unacceptable - - Decryption latency incompatible with use case - - Single trusted party acceptable (simpler private relay) -dependencies: [Threshold cryptography, Distributed key generation, Block builder integration] + - The committee liveness dependency is unacceptable for the target use case. + - Decryption latency is incompatible with the workload. + - A single trusted operator is acceptable, in which case a private relay is simpler. + +last_reviewed: 2026-04-22 + context: both +context_differentiation: + i2i: "The protocol-level design treats every participant identically, so institutional submitters get the same guarantee as anyone else. Institutions may still prefer bilateral private-relay integrations where contractual recourse is available, but the threshold scheme removes any single-operator trust." + i2u: "End users are protected by the same k-of-n threshold as institutions, which is the main user-facing benefit: MEV protection does not require trusting a sequencer or a private-order-flow relay. The guarantee is only as strong as the committee's independence, so a committee captured by institutional interests degrades the user-side protection." + crops_profile: cr: high - os: partial - privacy: partial - security: medium + o: partial + p: partial + s: medium + +crops_context: + cr: "Censorship resistance is `high` because encrypted transactions can be included by any block builder without inspecting content, and no single relay can suppress them." + o: "Reference implementations are open source; keyper-network governance and participation criteria vary by deployment and may be gated." + p: "Content privacy is `partial`: the payload is hidden until decryption, but sender address, gas limit, and transaction size remain visible pre-inclusion, and post-decryption MEV on the resulting state is still possible." + s: "Security rides on the k-of-n honest-committee assumption, correct distributed key generation, and timely key release after block commitment. Premature decryption reduces the guarantee to that of a transparent mempool." + +post_quantum: + risk: high + vector: "Pairing-based threshold encryption schemes rely on elliptic-curve primitives broken by a CRQC; pre-inclusion ciphertext collected today has Harvest-Now-Decrypt-Later exposure." + mitigation: "Lattice-based threshold encryption schemes. See [Post-Quantum Threats](../domains/post-quantum.md)." + +standards: [ERC-20, EIP-7573] + +related_patterns: + requires: [pattern-private-transaction-broadcasting] + composes_with: [pattern-focil-eip7805, pattern-pretrade-privacy-encryption, pattern-shielding] + alternative_to: [pattern-tee-based-privacy] + see_also: [pattern-network-anonymity, pattern-modular-privacy-stack] + +open_source_implementations: + - url: https://github.com/shutter-network/shutter + description: "Shutter threshold-encryption toolkit for Ethereum-compatible chains" + language: "Go" --- ## Intent -> **Sub-pattern of [Private Transaction Broadcasting](pattern-private-transaction-broadcasting.md)** — This pattern provides detailed coverage of threshold encryption specifically. See the parent pattern for alternative approaches (private relays, TEE-based builders). - -Prevent MEV extraction by encrypting transaction content before mempool submission, with decryption occurring only after block ordering is committed. A distributed committee holds threshold key shares; no single party can decrypt prematurely. This provides cryptographic (not trust-based) protection against front-running while maintaining censorship resistance. - -## Ingredients - -- **Cryptographic Primitives**: - - **Threshold encryption**: k-of-n scheme where k committee members must cooperate to decrypt - - **Distributed Key Generation (DKG)**: Committee jointly generates threshold public key without any party knowing full private key - - **Identity-Based Encryption (IBE)** or **timelock encryption**: Optional variants for slot-based decryption - -- **Infrastructure**: - - **Keyper committee**: Distributed set of key holders (validators, independent operators, or DAOs) - - **Sequencer/proposer integration**: Block builder must support encrypted transaction inclusion - - **Decryption oracle**: Publishes decryption keys after inclusion commitment - -- **Standards**: - - No ERC standard yet; Shutter uses custom protocol - - Compatible with ERC-20, ERC-7573, and other token standards at application layer +Prevent miner-extractable-value extraction by encrypting transaction content before mempool submission and releasing the decryption key only after block ordering is committed. A distributed committee holds threshold key shares, so no single party can decrypt prematurely. The result is cryptographic protection against front-running, back-running, and sandwich attacks, without handing trust to any one relay. -## Protocol (concise) +This pattern is the cryptographic sub-pattern of [Private Transaction Broadcasting](pattern-private-transaction-broadcasting.md). See that pattern for alternative approaches (trust-based private relays, hardware-assisted builders). -### Encryption Phase +## Components -1. **Committee setup**: Keypers run DKG to generate threshold public key `PK` and individual key shares `sk_i`. -2. **Key publication**: Threshold public key `PK` published; users encrypt transactions with `PK`. -3. **Transaction encryption**: User encrypts transaction `tx` as `E(PK, tx)` and submits to mempool. -4. **Encrypted inclusion**: Block builder includes `E(PK, tx)` in block without seeing contents. +- Threshold encryption scheme: a k-of-n construction so that k committee members must cooperate to decrypt. +- Distributed key generation: the committee jointly produces the threshold public key without any party ever holding the full private key. +- Keyper committee: a distributed set of key holders drawn from validators, independent operators, or a delegated governance process. +- Block builder integration: the builder accepts encrypted payloads and includes them without inspecting contents. +- Decryption oracle: publishes decryption key shares after block commitment so execution can proceed. +- Identity-based encryption or timelock-encryption variants are optional when slot-based decryption is required without a committee round trip. -### Decryption Phase +## Protocol -5. **Inclusion commitment**: Block is proposed/finalized with encrypted transactions. -6. **Decryption key release**: After slot commitment, k-of-n keypers release decryption key shares. -7. **Key aggregation**: Shares combined to produce decryption key `DK` for that slot/block. -8. **Transaction reveal**: `DK` decrypts all transactions in block; execution proceeds with revealed content. +1. [operator] Keypers run distributed key generation to produce a threshold public key and individual key shares. +2. [operator] The threshold public key is published so users can encrypt transactions to it. +3. [user] The user encrypts a transaction under the threshold public key and submits the ciphertext to the mempool. +4. [operator] The block builder includes the ciphertext in a block without seeing its contents. +5. [contract] The block is proposed and finalized; slot commitment is now immutable. +6. [operator] At least k keypers release their decryption key shares for the slot. +7. [operator] Shares are aggregated into the slot decryption key, which reveals the transactions, and execution proceeds on the decrypted payloads. -## Committee Assumptions +## Guarantees & threat model -| Assumption | Requirement | Failure Impact | -|------------|-------------|----------------| -| **Honest threshold** | At least k of n keypers are honest |