From 470873b8a2e05bc537cafe167db6d4564ef923bd Mon Sep 17 00:00:00 2001 From: Satya Date: Sun, 11 Oct 2026 09:54:34 +0800 Subject: [PATCH 1/5] docs(site): selective disclosure section, commitments & encryption guides, confidential use cases Document the Pedersen, ElGamal, threshold DKG/HPKE and confidential-note work (ADR-0051..0055) for beginners, and help readers choose between disclosure options. - New "Selective disclosure" section: a chooser ("one salary, six ways" with a help-me-choose tree) and six option pages (reveal with BBS, prove a rule, hide a number, tell chosen readers, encrypt for an auditor, split the trust), each with short code and real-world uses. The BBS guide stays as it was, plus one pointer to the chooser. - New guides (Guides > Commitments & encryption): Pedersen commitments, ElGamal encryption, threshold decryption (DKG + HPKE share delivery), confidential notes. Complete examples were compiled and run against a pre13 build. - New Learn page "Commitments & encryption, explained" with interactive commitment and encryption explainers. - New use cases with walkthroughs: confidential payroll, sealed-bid auction, confidential loyalty points, proof of solvency with hidden balances; private voting gains the encrypted-tally section (zeroj-usecases PR #8). The demos are on open zeroj-usecases PRs #8/#9 and the pages say so. - Reference updates: status matrix, glossary, modules, API cheatsheet, AI starter pack, gadgets. - On-chain Groth16 costs re-measured at 6a89f8a after ADR-0056 (1 input: 2,052,276,435 CPU / 138,837 memory; +0.14e9 per input). - SinceNotice component marks pages whose APIs are newer than the published release; check-api-refs honours non-ZeroJ imports of a same-named type. Co-Authored-By: Claude Opus 5.5 --- www/astro.config.mjs | 9 + www/scripts/ai-artifacts.mjs | 8 + www/scripts/check-api-refs.mjs | 3 + www/site.config.mjs | 20 + www/src/components/SinceNotice.astro | 23 + .../walkthrough/AuctionWalkthrough.astro | 431 ++++++++++++++ .../walkthrough/CardanoProofWalkthrough.astro | 2 +- .../walkthrough/CommitmentExplainer.astro | 311 ++++++++++ .../DisclosureOptionsExplainer.astro | 334 +++++++++++ .../walkthrough/EncryptionExplainer.astro | 215 +++++++ .../walkthrough/NoteDeliveryExplainer.astro | 307 ++++++++++ .../walkthrough/PayrollWalkthrough.astro | 366 ++++++++++++ .../walkthrough/PointsWalkthrough.astro | 445 +++++++++++++++ .../walkthrough/SolvencyWalkthrough.astro | 532 ++++++++++++++++++ .../walkthrough/TallyWalkthrough.astro | 320 +++++++++++ .../components/walkthrough/auction-data.ts | 41 ++ .../components/walkthrough/commitment-data.ts | 13 + .../walkthrough/disclosure-options-data.ts | 151 +++++ .../components/walkthrough/encryption-data.ts | 15 + .../walkthrough/note-delivery-data.ts | 25 + .../components/walkthrough/payroll-data.ts | 16 + www/src/components/walkthrough/points-data.ts | 30 + .../walkthrough/proof-system-data.ts | 2 +- .../components/walkthrough/solvency-data.ts | 29 + www/src/components/walkthrough/tally-data.ts | 21 + www/src/content/docs/ai/starter-pack.md | 18 + .../content/docs/guides/circuits/gadgets.md | 14 +- .../confidential/confidential-notes.mdx | 249 ++++++++ .../docs/guides/confidential/elgamal.mdx | 433 ++++++++++++++ .../docs/guides/confidential/pedersen.mdx | 457 +++++++++++++++ .../guides/confidential/threshold-elgamal.mdx | 412 ++++++++++++++ .../credentials/authenticated-state.mdx | 4 +- .../content/docs/guides/credentials/bbs.mdx | 11 +- .../docs/guides/verifying/on-chain.mdx | 19 +- .../docs/learn/commitments-and-encryption.mdx | 175 ++++++ www/src/content/docs/learn/glossary.md | 68 ++- www/src/content/docs/learn/proof-systems.mdx | 4 +- www/src/content/docs/learn/zk-on-cardano.mdx | 19 +- .../content/docs/reference/api-cheatsheet.md | 31 +- www/src/content/docs/reference/faq.md | 11 +- www/src/content/docs/reference/modules.md | 2 +- .../encrypt-for-an-auditor.mdx | 116 ++++ .../selective-disclosure/hide-a-number.mdx | 115 ++++ .../docs/selective-disclosure/index.mdx | 107 ++++ .../selective-disclosure/prove-a-rule.mdx | 152 +++++ .../reveal-attributes.mdx | 88 +++ .../share-with-chosen-readers.mdx | 97 ++++ .../docs/selective-disclosure/split-trust.mdx | 104 ++++ www/src/content/docs/start/status.md | 20 + .../docs/tutorials/verify-on-cardano.mdx | 6 +- .../docs/use-cases/account-recovery.mdx | 2 +- .../docs/use-cases/confidential-payroll.mdx | 224 ++++++++ .../docs/use-cases/confidential-points.mdx | 224 ++++++++ www/src/content/docs/use-cases/overview.mdx | 63 ++- .../docs/use-cases/private-solvency.mdx | 259 +++++++++ .../content/docs/use-cases/private-voting.mdx | 167 +++++- .../docs/use-cases/proof-of-reserves.mdx | 10 + .../docs/use-cases/sealed-bid-auction.mdx | 238 ++++++++ .../docs/use-cases/selective-disclosure.mdx | 7 + 59 files changed, 7530 insertions(+), 65 deletions(-) create mode 100644 www/src/components/SinceNotice.astro create mode 100644 www/src/components/walkthrough/AuctionWalkthrough.astro create mode 100644 www/src/components/walkthrough/CommitmentExplainer.astro create mode 100644 www/src/components/walkthrough/DisclosureOptionsExplainer.astro create mode 100644 www/src/components/walkthrough/EncryptionExplainer.astro create mode 100644 www/src/components/walkthrough/NoteDeliveryExplainer.astro create mode 100644 www/src/components/walkthrough/PayrollWalkthrough.astro create mode 100644 www/src/components/walkthrough/PointsWalkthrough.astro create mode 100644 www/src/components/walkthrough/SolvencyWalkthrough.astro create mode 100644 www/src/components/walkthrough/TallyWalkthrough.astro create mode 100644 www/src/components/walkthrough/auction-data.ts create mode 100644 www/src/components/walkthrough/commitment-data.ts create mode 100644 www/src/components/walkthrough/disclosure-options-data.ts create mode 100644 www/src/components/walkthrough/encryption-data.ts create mode 100644 www/src/components/walkthrough/note-delivery-data.ts create mode 100644 www/src/components/walkthrough/payroll-data.ts create mode 100644 www/src/components/walkthrough/points-data.ts create mode 100644 www/src/components/walkthrough/solvency-data.ts create mode 100644 www/src/components/walkthrough/tally-data.ts create mode 100644 www/src/content/docs/guides/confidential/confidential-notes.mdx create mode 100644 www/src/content/docs/guides/confidential/elgamal.mdx create mode 100644 www/src/content/docs/guides/confidential/pedersen.mdx create mode 100644 www/src/content/docs/guides/confidential/threshold-elgamal.mdx create mode 100644 www/src/content/docs/learn/commitments-and-encryption.mdx create mode 100644 www/src/content/docs/selective-disclosure/encrypt-for-an-auditor.mdx create mode 100644 www/src/content/docs/selective-disclosure/hide-a-number.mdx create mode 100644 www/src/content/docs/selective-disclosure/index.mdx create mode 100644 www/src/content/docs/selective-disclosure/prove-a-rule.mdx create mode 100644 www/src/content/docs/selective-disclosure/reveal-attributes.mdx create mode 100644 www/src/content/docs/selective-disclosure/share-with-chosen-readers.mdx create mode 100644 www/src/content/docs/selective-disclosure/split-trust.mdx create mode 100644 www/src/content/docs/use-cases/confidential-payroll.mdx create mode 100644 www/src/content/docs/use-cases/confidential-points.mdx create mode 100644 www/src/content/docs/use-cases/private-solvency.mdx create mode 100644 www/src/content/docs/use-cases/sealed-bid-auction.mdx diff --git a/www/astro.config.mjs b/www/astro.config.mjs index 930bfa8d..fd4ed950 100644 --- a/www/astro.config.mjs +++ b/www/astro.config.mjs @@ -40,6 +40,11 @@ export default defineConfig({ items: [{ autogenerate: { directory: 'learn' } }], }, { label: 'Tutorials', items: [{ autogenerate: { directory: 'tutorials' } }] }, + { + label: 'Selective disclosure', + badge: { text: 'What to use when', variant: 'note' }, + items: [{ autogenerate: { directory: 'selective-disclosure' } }], + }, { label: 'Guides', items: [ @@ -50,6 +55,10 @@ export default defineConfig({ label: 'Credentials & state', items: [{ autogenerate: { directory: 'guides/credentials' } }], }, + { + label: 'Commitments & encryption', + items: [{ autogenerate: { directory: 'guides/confidential' } }], + }, ], }, { label: 'Use cases', items: [{ autogenerate: { directory: 'use-cases' } }] }, diff --git a/www/scripts/ai-artifacts.mjs b/www/scripts/ai-artifacts.mjs index 47e454aa..6e5f5ab4 100644 --- a/www/scripts/ai-artifacts.mjs +++ b/www/scripts/ai-artifacts.mjs @@ -27,6 +27,7 @@ import { ZEROJ_DEV_VERSION, ZEROJ_RELEASED, ZEROJ_VERSION, + releasedSince, replaceVersionTokens, sourceRevision, } from '../site.config.mjs'; @@ -37,10 +38,12 @@ export const SECTIONS = [ { dir: 'start', title: 'Start here' }, { dir: 'learn', title: 'Learn zero-knowledge (concepts)' }, { dir: 'tutorials', title: 'Tutorials' }, + { dir: 'selective-disclosure', title: 'Selective disclosure: what to use when' }, { dir: 'guides/circuits', title: 'Guides: circuits' }, { dir: 'guides/proving', title: 'Guides: proving' }, { dir: 'guides/verifying', title: 'Guides: verifying' }, { dir: 'guides/credentials', title: 'Guides: credentials & state' }, + { dir: 'guides/confidential', title: 'Guides: commitments & encryption' }, { dir: 'use-cases', title: 'Use cases' }, { dir: 'reference', title: 'Reference' }, { dir: 'ai', title: 'Build with AI' }, @@ -191,6 +194,11 @@ export function toPlainMarkdown(body, { mdx }) { ? '' : `> **Caution:** ZeroJ ${ZEROJ_VERSION} isn't on Maven Central yet, so these snippets won't resolve until it's published. Build from source with \`./gradlew publishToMavenLocal\` meanwhile (local versions are \`${ZEROJ_VERSION}--SNAPSHOT\`).`, ) + .replace(//g, (_, since) => + releasedSince(since) + ? '' + : `> **Note:** the APIs on this page are new in ZeroJ ${since} and not in a release on Maven Central yet (the latest is ${ZEROJ_VERSION}). Use a development snapshot (\`${since}--SNAPSHOT\`) from https://repo.bloxbean.org/maven/snapshots to try them.`, + ) .replace(/<\/?(Steps|Tabs|CardGrid|FileTree|Card|TabItem|Aside)(\s[^>]*)?>/g, ''); } text = convertDirectives(text); diff --git a/www/scripts/check-api-refs.mjs b/www/scripts/check-api-refs.mjs index cb3387ab..adc39229 100644 --- a/www/scripts/check-api-refs.mjs +++ b/www/scripts/check-api-refs.mjs @@ -165,6 +165,9 @@ for (const b of blocks) { } const entries = byName.get(type); if (!entries || docTypes.has(type) || EXTERNAL.has(type)) continue; + // The block imports a non-ZeroJ type with this simple name (java.security.Signature, say), so a + // ZeroJ type that shares the name isn't the one in use. + if (imported.has(type) && !imported.get(type).startsWith('org.zeroj.')) continue; if (member === 'class' || member === 'length') continue; if (!declares(entries, member)) { // Enum constants/nested types declared in a nested type with the same simple name are covered by diff --git a/www/site.config.mjs b/www/site.config.mjs index 7f0756dd..3670895a 100644 --- a/www/site.config.mjs +++ b/www/site.config.mjs @@ -75,6 +75,26 @@ function readRelease() { return release; } +// Orders release versions such as 0.1.0-pre12 < 0.1.0-pre13 < 0.1.0. A pre-release sorts before +// the plain release of the same x.y.z. +export function compareVersions(a, b) { + const parse = (v) => { + const [core, pre] = v.split('-'); + const pr = pre?.match(/^pre(\d+)$/); + return [...core.split('.').map(Number), pre ? (pr ? Number(pr[1]) : 0) : Infinity]; + }; + const x = parse(a); + const y = parse(b); + for (let i = 0; i < 4; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1; + return 0; +} + +// True when the published release (release.json, and only once it is on Maven Central) contains +// features first shipped in `since`. Pages use it through . +export function releasedSince(since) { + return ZEROJ_RELEASED && compareVersions(ZEROJ_VERSION, since) >= 0; +} + export const VERSION_TOKENS = { '%ZEROJ_VERSION%': ZEROJ_VERSION, '%JULC_VERSION%': JULC_VERSION, diff --git a/www/src/components/SinceNotice.astro b/www/src/components/SinceNotice.astro new file mode 100644 index 00000000..ab251b5e --- /dev/null +++ b/www/src/components/SinceNotice.astro @@ -0,0 +1,23 @@ +--- +// Shown on pages that document APIs newer than the published release in release.json. Renders +// nothing once a release at or after `since` is on Maven Central. The AI exports get the same text +// (scripts/ai-artifacts.mjs). +import { Aside } from '@astrojs/starlight/components'; +import { ZEROJ_VERSION, releasedSince } from '../../site.config.mjs'; + +interface Props { + since: string; +} +const { since } = Astro.props; +--- + +{ + !releasedSince(since) && ( + + ) +} diff --git a/www/src/components/walkthrough/AuctionWalkthrough.astro b/www/src/components/walkthrough/AuctionWalkthrough.astro new file mode 100644 index 00000000..652dfb28 --- /dev/null +++ b/www/src/components/walkthrough/AuctionWalkthrough.astro @@ -0,0 +1,431 @@ +--- +// Sealed-bid auction with enforced disclosure, step by step: +// open the lot -> sealed bids -> bidding closes -> settle with a proof -> payouts -> a cheat. +// Values follow the zeroj-usecases demo (auction-data.ts). Ciphertexts and keys are illustrative +// stand-ins (fakeHash), not curve points. Three views: Alice (a bidder), the auctioneer, the public. +import './walkthrough.css'; +import { fakeHash } from './engine'; +import { BIDDERS, BID_RANGE, DEPOSIT, ITEM, RESERVE, ada, bidOk, settle } from './auction-data'; + +const auctioneerKey = fakeHash('auctioneer-pk'); +const s = settle(BIDDERS.map((b) => b.bid)); +const winner = s.kind === 'win' ? BIDDERS[s.winner] : undefined; +const price = s.kind === 'win' ? s.price : 0; +const cheat = s.kind === 'win' ? `${BIDDERS[s.cheat.bidder].name} wins at ${ada(s.cheat.price)}` : 'someone won'; +const rings = [ + 'M116.28 43.93A56 56 0 1 1 29.76 19.69', + 'M45.87 98.53A39 39 0 1 1 94.31 39.46', + 'M55.21 43.29A22.5 22.5 0 0 1 80.18 79.63', +]; +--- + +
+
+
+ Sealed-bid auction · step 1 / 6 +
+
+ + + +
+ +
+
+ +
+ +
+
+ Bidders + each knows only its own bid +
+ {BIDDERS.map((b, i) => ( +
+ {b.name}'s bidSECRETHIDDEN + {ada(b.bid)}████████ + + {bidOk(b.bid) ? `proof: ${RESERVE} ≤ bid ≤ ${DEPOSIT}, sealed to the auctioneer` : 'no bid proof exists: refused'} + +
+ ))} +

Alice, Bob and Carol each have {ada(DEPOSIT)} ready for the deposit.

+

Nobody can withdraw a bid or refuse to reveal it: the auctioneer can already read it.

+
+ + + + +
+
+ Lot on Cardano + SealedBidAuction +
+
+ item · deposit · reservePUBLIC + {ITEM} · {ada(DEPOSIT)} · {ada(RESERVE)} +
+
+ auctioneer key (from its registry)PUBLIC + {auctioneerKey} +
+
+ Bids in the lot datum +
    + {BIDDERS.map((b, i) => ( + + ))} +
+ {ada(DEPOSIT * BIDDERS.filter((b) => bidOk(b.bid)).length)} of deposits locked +
+
+ Settle redeemer + + {winner ? `winner = ${winner.name}, price = ${ada(price)}: proof valid` : 'no bids: the seller takes the item back'} + + Only the winner and the price become public. Losing bids never do. +
+
+ Payouts, all checked by the validator +
    +
    +
    + A dishonest settle + no settlement proof exists: rejected +
    +
    + + + + +
    +
    + Auctioneer + reads every bid, can't fake the result +
    +
    + secret keySECRETHIDDEN + {fakeHash('auctioneer-sk')}████████ +
    +
    + Decrypted, privately + {BIDDERS.map((b, i) => ( + + ))} +
    + +
    + πsettlement proofover every bid +
    +
    + Tries to claim + {cheat} + the decryptions say otherwise: no proof can be made +
    +
    +
    + +
    + Try other bids + {BIDDERS.map((b, i) => ( + + ))} + Valid bids are {ada(RESERVE)} to {ada(DEPOSIT)}. Ties go to the earlier bid. +
    + +
    +
    +

    1. Open the lot

    +

    The seller locks the {ITEM} in a lot on Cardano, with a deposit of {ada(DEPOSIT)} and a reserve of {ada(RESERVE)}. The lot names the auctioneer's public key, taken from the auctioneer's on-chain key registry.

    +
    +
    +

    2. Sealed bids

    +

    Each bidder encrypts its bid so that only the auctioneer's key opens it, proves the hidden bid is between the reserve and the deposit, and locks the {ada(DEPOSIT)} deposit. Drag a bid outside that range below: no proof exists, so the bid can't be placed.

    +
    +
    +

    3. Bidding closes

    +

    After the deadline the lot accepts no more bids. Everyone can see who bid and how many deposits are locked, but not one amount. Unlike commit-and-reveal, there's no reveal phase for a losing bidder to skip.

    +
    +
    +

    4. Settle with a proof

    +

    The auctioneer decrypts every bid privately and proves, over all the bids in the lot, that {winner ? `${winner.name}'s bid of ${ada(price)}` : 'no bid'} is the earliest highest. Only the winner and the price are published.

    +
    +
    +

    5. Payouts

    +

    The validator checks every payout in the settle transaction: the seller gets the price, the winner gets the item and the rest of its deposit, and every other bidder gets its whole deposit back. If nobody settles in time, anyone can trigger a full refund.

    +
    +
    +

    6. A cheating auctioneer

    +

    The auctioneer can read the bids but can't change the result: a proof for any other winner or price doesn't exist. Copying another bidder's ciphertext fails too, because each bid proof is bound to its bidder's key.

    +
    +
    + +
    +
      +
    1. +
    2. +
    3. +
    4. +
    5. +
    6. +
    +
    + + + +
    +
    +
    + SECRET visible only in the views allowed to see it + PUBLIC on-chain for anyone + Keys and ciphertexts are illustrative. +
    +
    +
    + + + + diff --git a/www/src/components/walkthrough/CardanoProofWalkthrough.astro b/www/src/components/walkthrough/CardanoProofWalkthrough.astro index 40e911de..41b495eb 100644 --- a/www/src/components/walkthrough/CardanoProofWalkthrough.astro +++ b/www/src/components/walkthrough/CardanoProofWalkthrough.astro @@ -176,7 +176,7 @@ const spendRefB = fakeHash(`spendRef:${txB}#0`); transaction succeeds: 5 ADA unlocked the whole transaction fails: the 5 ADA stay locked -

    About 2.8 billion of the 10 billion CPU units allowed per transaction.

    +

    About 2.2 billion of the 10 billion CPU units allowed per transaction.

    What your validator checks diff --git a/www/src/components/walkthrough/CommitmentExplainer.astro b/www/src/components/walkthrough/CommitmentExplainer.astro new file mode 100644 index 00000000..c6a2020a --- /dev/null +++ b/www/src/components/walkthrough/CommitmentExplainer.astro @@ -0,0 +1,311 @@ +--- +// A Pedersen commitment, step by step: seal -> hiding -> open (binding) -> add -> prove a range. +// Commitment values are illustrative stand-ins (fakeHash), not Jubjub points. The "add" step shows +// the real rule: C(a, r) + C(b, s) is the commitment to (a + b, r + s). +import './walkthrough.css'; +import { fakeHash } from './engine'; +import { ALICE, BOB, MIN_DEPOSIT, commitLabel, fmt } from './commitment-data'; + +const cAlice = commitLabel(ALICE.amount, ALICE.blinding); +const cAliceAgain = commitLabel(ALICE.amount, ALICE.blinding2); +const cBob = commitLabel(BOB.amount, BOB.blinding); +const cSum = commitLabel(ALICE.amount + BOB.amount, ALICE.blinding + BOB.blinding); +const rings = [ + 'M116.28 43.93A56 56 0 1 1 29.76 19.69', + 'M45.87 98.53A39 39 0 1 1 94.31 39.46', + 'M55.21 43.29A22.5 22.5 0 0 1 80.18 79.63', +]; +--- + +
    +
    +
    + Commitment · step 1 / 5 +
    +
    + + +
    + +
    +
    + +
    +
    +
    + Alice + commits to an amount +
    +
    + amount vSECRETHIDDEN + {fmt(ALICE.amount)}████████ + +
    +
    + blinding r (random, 252 bits)SECRETHIDDEN + {fakeHash(`r:${ALICE.blinding}`)}████████ + +
    +
    + Proves, without opening + the amount in C is at least {fmt(MIN_DEPOSIT)} + +
    +
    + + + +
    +
    + Public ledger + anyone can read it +
    +
    + C = v·G + r·HPUBLIC + {cAlice} +
    +
    + Same amount, new blinding +
    + C′ (also {fmt(ALICE.amount)})PUBLIC + {cAliceAgain} +
    + C and C′ look unrelated: nobody can tell they hide the same amount +
    +
    + Bob commits too +
    + D (Bob)PUBLIC + {cBob} +
    +
    + C + DPUBLIC + {cSum} +
    + Anyone can add the points. Only someone who knows both openings can open the sum. +
    +
    + + + +
    +
    + Verifier + an auditor, a validator, a counterparty +
    +

    Sees only C. Learns nothing about the amount.

    +
    + Alice opens C to the verifier + + commit({fmt(ALICE.amount)}, r) = C: accepted + Try another number. No blinding makes a different amount match C. +
    +
    + Opening the total + C + D opens to {fmt(ALICE.amount + BOB.amount)} with blinding r + s + The verifier learns the total, not who put in what. +
    +
    + Checks π against C + proof valid: at least {fmt(MIN_DEPOSIT)}, amount still hidden +
    +
    +
    + +
    +
    +

    1. Seal

    +

    Alice picks an amount and a fresh random blinding and publishes one curve point, C = v·G + r·H. Think of a sealed envelope: everyone can see it, nobody can read it. Drag the amount or roll a new blinding and watch C change.

    +
    +
    +

    2. Hiding

    +

    Commit to the same amount again with a new blinding, and you get a completely different point. Because the blinding is random, C reveals nothing about the amount, not even whether two commitments hide the same one.

    +
    +
    +

    3. Open (binding)

    +

    Later, Alice can hand the opening (v, r) to someone she chooses. They recompute the point and compare it with C. She can't find a second opening for a different amount, so C locks her in. Type another amount to see it fail.

    +
    +
    +

    4. Add

    +

    Commitments add up: C + D is the commitment to the sum of the amounts, with the sum of the blindings. A ledger can total balances, or check that inputs equal outputs, without seeing any single amount.

    +
    +
    +

    5. Prove without opening

    +

    A zero-knowledge proof can show a fact about the hidden amount, such as "at least {fmt(MIN_DEPOSIT)}", while C stays sealed. Drag Alice's amount below {fmt(MIN_DEPOSIT)} and no valid proof exists.

    +
    +
    + +
    +
      +
    1. +
    2. +
    3. +
    4. +
    5. +
    +
    + + + +
    +
    +
    + SECRET only Alice knows it + PUBLIC anyone can see it + Point values are illustrative. +
    +
    +
    + + + + diff --git a/www/src/components/walkthrough/DisclosureOptionsExplainer.astro b/www/src/components/walkthrough/DisclosureOptionsExplainer.astro new file mode 100644 index 00000000..7ba7f8ac --- /dev/null +++ b/www/src/components/walkthrough/DisclosureOptionsExplainer.astro @@ -0,0 +1,334 @@ +--- +// One salary, disclosed six ways: for each option, what Carol, a landlord (a verifier), the tax +// authority and everyone else learn. A "help me choose" question tree picks an option. +// Data and wording live in disclosure-options-data.ts. +import './walkthrough.css'; +import { OPTIONS, QUESTIONS, SALARY, THRESHOLD } from './disclosure-options-data'; + +const lanes = [ + { key: 'carol', name: 'Carol', sub: 'the employee' }, + { key: 'landlord', name: 'Landlord', sub: `asks "earns at least ${THRESHOLD.toLocaleString('en-US')}?"` }, + { key: 'tax', name: 'Tax authority', sub: 'an auditor' }, + { key: 'everyone', name: 'Everyone else', sub: 'the public chain' }, +] as const; +const tagText = { value: 'SEES IT', proof: 'PROVEN', sealed: 'SEALED', none: 'NOTHING' }; +const first = OPTIONS[0]; +--- + +
    +
    + One salary, six ways · Carol earns {SALARY.toLocaleString('en-US')} a month + +
    + + + +
    + {OPTIONS.map((o, i) => ( + + ))} +
    + +
    +

    {first.summary}

    +
    + {lanes.map((l) => ( +
    +
    + {l.name} + {l.sub} +
    + {tagText[first[l.key].kind]} + {first[l.key].text} +
    + ))} +
    +
    +
    Needs
    {first.needs}
    +
    On Cardano
    {first.onchain}
    +
    Maturity
    {first.maturity}
    +
    + How to use it +
    + +
    + SEES IT learns the salary + PROVEN learns only a checked fact + SEALED sees a commitment or ciphertext +
    +
    + + + + diff --git a/www/src/components/walkthrough/EncryptionExplainer.astro b/www/src/components/walkthrough/EncryptionExplainer.astro new file mode 100644 index 00000000..bc256cf3 --- /dev/null +++ b/www/src/components/walkthrough/EncryptionExplainer.astro @@ -0,0 +1,215 @@ +--- +// Exponential ElGamal on Jubjub, step by step: key -> encrypt -> add -> decrypt -> split the key. +// Ciphertext values are illustrative stand-ins (fakeHash), not curve points. +import './walkthrough.css'; +import { fakeHash } from './engine'; +import { SENDERS, THRESHOLD, TRUSTEES, ctLabel, fmt } from './encryption-data'; + +const total = SENDERS.reduce((s, x) => s + x.amount, 0); +const pk = fakeHash('elgamal-pk'); +--- + +
    +
    +
    + Encryption · step 1 / 5 +
    +
    + + +
    + +
    +
    + +
    +
    +
    + Senders + encrypt to the public key +
    + {SENDERS.map((s, i) => ( +
    + {s.name}'s amountSECRETHIDDEN + {fmt(s.amount)}████████ +
    + ))} +

    Anyone can encrypt with the public key. Only the secret key opens the result.

    + +
    + + + +
    +
    + Public ledger + anyone can read it +
    +
    + public key PKPUBLIC + {pk} +
    + {SENDERS.map((s, i) => ( +
    + Enc({s.name}) = (A, B)PUBLIC + {ctLabel(s.amount, s.nonce)} +
    + ))} +
    + sum of ciphertextsPUBLIC + {ctLabel(total, SENDERS.reduce((s, x) => s + x.nonce, 0))} +
    +

    Adding ciphertexts adds the amounts inside. Nobody had to decrypt anything.

    +
    + + + +
    +
    + Auditor + Trustees + holds the secret key + each holds one share +
    +
    + secret key skSECRETHIDDEN + {fakeHash('elgamal-sk')}████████ +
    +
    + Decrypt the sum + B − sk·A = {fmt(total)}·G + look up {fmt(total)} in a table of small numbers + Only small amounts (up to 2³² here) can be looked up, so values are kept small or split into limbs. +
    +
    + Pick who takes part (need {THRESHOLD} of {TRUSTEES.length}) +
    + {TRUSTEES.map((t) => ( + + ))} +
    + 0 of {TRUSTEES.length}: not enough shares, nothing decrypts +
    +
    +
    + +
    +
    +

    1. Key

    +

    An auditor makes a key pair and publishes the public key. Think of a lockbox with a slot: anyone can drop something in, only the auditor has the key.

    +
    +
    +

    2. Encrypt

    +

    Alice encrypts her amount to the auditor's public key and publishes the ciphertext. Each encryption uses fresh randomness, so encrypting the same amount twice gives unrelated ciphertexts. Press "Encrypt again".

    +
    +
    +

    3. Add

    +

    Bob does the same. Because this is exponential ElGamal, adding two ciphertexts gives a ciphertext of the sum. A ledger can keep a running encrypted total that nobody can read.

    +
    +
    +

    4. Decrypt

    +

    The auditor uses the secret key to recover the total. Decryption ends in a lookup, which is why encrypted amounts must be small numbers, such as votes or 32-bit limbs.

    +
    +
    +

    5. Split the key

    +

    To stop any one party reading the ciphertexts, trustees run a distributed key generation: nobody ever holds the whole secret key. Decrypting needs {THRESHOLD} of {TRUSTEES.length} trustees to cooperate. Pick trustees to try it.

    +
    +
    + +
    +
      +
    1. +
    2. +
    3. +
    4. +
    5. +
    +
    + + + +
    +
    +
    + SECRET only its owner knows it + PUBLIC anyone can see it + Key and ciphertext values are illustrative. +
    +
    +
    + + + + diff --git a/www/src/components/walkthrough/NoteDeliveryExplainer.astro b/www/src/components/walkthrough/NoteDeliveryExplainer.astro new file mode 100644 index 00000000..6a4e3b4e --- /dev/null +++ b/www/src/components/walkthrough/NoteDeliveryExplainer.astro @@ -0,0 +1,307 @@ +--- +// A confidential note's opening delivered on-chain, step by step: +// seal -> publish -> open (owner / auditor / stranger) -> a garbage delivery -> wallet scan. +// Points and bytes are illustrative stand-ins (fakeHash), not Jubjub points or real ciphertexts. +import './walkthrough.css'; +import { fakeHash } from './engine'; +import { AMOUNT, HOLDERS, SCAN, commitment, delivery } from './note-delivery-data'; +--- + +
    +
    +
    + Confidential note · step 1 / 5 +
    +
    + + +
    + +
    +
    + +
    + +
    +
    + Sender + creates the note +
    +
    + amount vSECRETHIDDEN + {AMOUNT}████████ +
    +
    + blinding rSECRETHIDDEN + {fakeHash('note-r')}████████ +
    +
    + Seals the opening (v, r) once per reader + ✉ to the owner's reader key, fresh one-time key + ✉ to the auditor's reader key, fresh one-time key +
    +

    Done. The sender can go offline; nothing is sent privately.

    +
    + + + + +
    +
    + Cardano + the note's datum +
    +

    Waiting for the note.

    +
    + commitment CPUBLIC + {commitment} +
    +
    + delivery 0 · owner · 89 bytesPUBLIC + {delivery(0)} +
    +
    + delivery 1 · auditor · 89 bytesPUBLIC + {delivery(1)} +
    + +

    The validator can only check each delivery's length. It can't tell whether one decrypts.

    +
    + + + + +
    +
    + You hold the… + + {HOLDERS.map((h, i) => ( + + ))} + +
    +
    + owner's viewing keySECRETHIDDEN + {fakeHash('vk:owner')}████████ +
    +

    Each reader published a 32-byte reader key earlier; the viewing key never leaves the wallet.

    +
    + Opens delivery 0 (its own position) + decrypts to (v = {AMOUNT}, r) + commit({AMOUNT}, r) = C: accepted +
    +
    + Wallet scan, owner's key +
      + {SCAN.map((n, i) => ( +
    • {n.label}…
    • + ))} +
    + Notes are matched by the owner field first; only those are opened. +
    +
    +
    + +
    +
    +

    1. Seal

    +

    The sender commits to {AMOUNT} with a random blinding, then encrypts the opening (v, r) separately for each reader: the owner first, then the auditor. Each copy uses a fresh one-time key, as Zcash notes do.

    +
    +
    +

    2. Publish

    +

    The note goes on-chain: the commitment plus one 89-byte delivery per reader. The public sees a point and random-looking bytes. Switch to the public view to compare.

    +
    +
    +

    3. Open

    +

    A reader decrypts the delivery at its own position and accepts the opening only if it recomputes C. Pick the owner, the auditor or a stranger. A stranger's key opens nothing.

    +
    +
    +

    4. A bad delivery

    +

    A careless or hostile sender can write garbage into a delivery, and the ledger can't notice. The owner's wallet finds a note it owns but can't open, and reports it instead of hiding it. The auditor's copy is separate, so the auditor still reads {AMOUNT}. Untick the box to compare.

    +
    +
    +

    5. Recover from the chain

    +

    A wallet with only its viewing key can rebuild its balance by scanning the ledger: open the notes it owns, skip everyone else's, and flag owned notes that don't open. No private messages are needed.

    +
    +
    + +
    +
      +
    1. +
    2. +
    3. +
    4. +
    5. +
    +
    + + + +
    +
    +
    + SECRET only its holder knows it + PUBLIC on-chain, anyone can see it + Point and byte values are illustrative. +
    +
    +
    + + + + diff --git a/www/src/components/walkthrough/PayrollWalkthrough.astro b/www/src/components/walkthrough/PayrollWalkthrough.astro new file mode 100644 index 00000000..87355601 --- /dev/null +++ b/www/src/components/walkthrough/PayrollWalkthrough.astro @@ -0,0 +1,366 @@ +--- +// Confidential payroll, step by step: register the tax key -> proved pay run -> payslips recovered +// from chain -> transfer -> tax view -> under-report cheat. Values follow the zeroj-usecases +// payroll demo (payroll-data.ts). Hashes and ciphertexts are illustrative stand-ins (fakeHash). +// +// Three views: Carol's (an employee), the tax authority's, and the public's. Rows marked +// data-readers="employee tax" are readable only in those views; the public view masks every +// data-kind="secret" row through the shared walkthrough CSS. +import './walkthrough.css'; +import { fakeHash } from './engine'; +import { + CAROL_SALARY, + CASH_OUT, + DAVE_SALARY, + REPORTED_DEFAULT, + TRANSFER, + credits, + issueProofExists, +} from './payroll-data'; + +const taxKey = fakeHash('tax-authority-pk'); +const cCarol = fakeHash(`C:carol:${CAROL_SALARY}`); +const cDave = fakeHash(`C:dave:${DAVE_SALARY}`); +const cToDave = fakeHash(`C:dave:${TRANSFER}`); +const cChange = fakeHash(`C:carol:${CAROL_SALARY - TRANSFER}`); +const cheatOk = issueProofExists(REPORTED_DEFAULT); +--- + +
    +
    +
    + Confidential payroll · step 1 / 6 +
    +
    + + + +
    + +
    +
    + +
    + +
    +
    + Employer + pays salaries +
    +

    Waiting for the tax authority's key.

    +
    + Pay run +
    + carol's salarySECRETHIDDEN + {credits(CAROL_SALARY)}████████ +
    +
    + dave's salarySECRETHIDDEN + {credits(DAVE_SALARY)}████████ +
    + each amount also encrypted to the tax key, as two 32-bit limbs +
    + πissuance prooflimbs match each salary +
    +
    +
    + Pay carol {credits(CAROL_SALARY)}, but tell the tax authority +
    + amount in the limbsCHEAT + {credits(REPORTED_DEFAULT)} + +
    + + {cheatOk ? 'limbs match the salary: the proof can be made' : 'limbs ≠ salary: no issuance proof exists'} + +
    +
    + + + + +
    +
    + Cardano + anyone can read it +
    +
    + registry: tax key PKPUBLIC + {taxKey} +
    + key possession proved on-chain +
    + NoteLedger salary notes +
    + owner carol · CPUBLIC + {cCarol} +
    +
    + owner dave · CPUBLIC + {cDave} +
    + each note also carries: 2 limb ciphertexts for the tax key, and 2 sealed openings (payslip, tax copy) + proof valid: the limbs encrypt each committed salary +
    +
    + Transfer +
    + owner dave · CPUBLIC + {cToDave} +
    +
    + owner carol (change) · CPUBLIC + {cChange} +
    + proof valid: input = outputs, limbs match +
    +
    + + {cheatOk ? 'honest pay run accepted' : 'no proof to verify: pay run refused, nothing minted'} + +
    +
    + + + + +
    +
    +
    + Carol + employee +
    +
    + viewing keySECRETHIDDEN + {fakeHash('carol-viewing-key')}████████ +
    +
    + payslip opened from chainSECRETHIDDEN + {credits(CAROL_SALARY)}████████ +
    + opening recomputes C: the payslip is genuine +
    + sent to dave · change keptSECRETHIDDEN + {credits(TRANSFER)} · {credits(CAROL_SALARY - TRANSFER)}████████ +
    +
    + +
    +
    + Tax authority + registry auditor +
    +
    + secret keySECRETHIDDEN + {fakeHash('tax-authority-sk')}████████ +
    +
    + Every salary, decrypted from the limbs +
    + carol · pay runSECRETHIDDEN + {credits(CAROL_SALARY)}████████ +
    +
    + dave · pay runSECRETHIDDEN + {credits(DAVE_SALARY)}████████ +
    +
    + carol → daveSECRETHIDDEN + {credits(TRANSFER)}████████ +
    +
    + carol · changeSECRETHIDDEN + {credits(CAROL_SALARY - TRANSFER)}████████ +
    + every amount proof-enforced +
    +
    +
    +
    + +
    +
    +

    1. Register the tax key

    +

    The tax authority publishes an encryption key in an on-chain registry, with a proof that it holds the matching secret key. The payroll ledger reads the key from there, so the employer can't pick its own.

    +
    +
    +

    2. Pay run

    +

    The employer pays carol {credits(CAROL_SALARY)} and dave {credits(DAVE_SALARY)} in one transaction. Each salary becomes a note: a commitment that hides the amount, the amount encrypted to the tax key in two 32-bit pieces ("limbs"), and two sealed copies of the opening. A zero-knowledge proof shows that the limbs add up to the committed amount. The ledger mints nothing without that proof.

    +
    +
    +

    3. Payslip

    +

    Carol scans the chain with her viewing key, a key that only opens notes sent to her. She decrypts her payslip and checks that it recomputes the commitment. Switch views: the public sees owners and commitments, never amounts.

    +
    +
    +

    4. Spend

    +

    Carol sends {credits(TRANSFER)} to dave and keeps {credits(CAROL_SALARY - TRANSFER)} as change. The transfer proof shows the amounts balance and that the new notes' limbs are encrypted to the tax key. She could also cash out {credits(CASH_OUT)} at the employer as a public amount.

    +
    +
    +

    5. Tax view

    +

    The tax authority decrypts the limbs of every note ever minted or transferred, straight from chain data. Because every one came with a proof, these are the real amounts, not what the employer chose to report.

    +
    +
    +

    6. Try to under-report

    +

    The employer pays carol {credits(CAROL_SALARY)} but encrypts a smaller number to the tax authority. The limbs no longer match the committed salary, so no issuance proof exists and the pay run is refused. Drag the slider to {credits(CAROL_SALARY)} to make it honest again.

    +
    +
    + +
    +
      +
    1. +
    2. +
    3. +
    4. +
    5. +
    6. +
    +
    + + + +
    +
    +
    + SECRET readable in this view + HIDDEN not readable in this view + PUBLIC on-chain + Hashes are illustrative. +
    +
    +
    + + + + diff --git a/www/src/components/walkthrough/PointsWalkthrough.astro b/www/src/components/walkthrough/PointsWalkthrough.astro new file mode 100644 index 00000000..4bab1c1f --- /dev/null +++ b/www/src/components/walkthrough/PointsWalkthrough.astro @@ -0,0 +1,445 @@ +--- +// Confidential loyalty points with an auditor, step by step: +// register auditor -> issue -> transfer -> redeem -> wallets recover from chain -> auditor view. +// Values follow the pedersen-commitments demo's points tab (points-data.ts). Two cheat toggles +// switch the run: a garbage owner delivery on bob's transfer note, and an issuer that under-reports +// the issuance to the auditor. Commitments are illustrative stand-ins (fakeHash). +import './walkthrough.css'; +import { fakeHash } from './engine'; +import { ISSUED, NOTES, PRICE, TRANSFERRED, UNDER_REPORTED, commitment, pts } from './points-data'; + +const [, , n3, n4] = NOTES; +const rings = [ + 'M116.28 43.93A56 56 0 1 1 29.76 19.69', + 'M45.87 98.53A39 39 0 1 1 94.31 39.46', + 'M55.21 43.29A22.5 22.5 0 0 1 80.18 79.63', +]; +--- + +
    +
    +
    + Points · step 1 / 6 +
    +
    + + + +
    + +
    +
    + +
    + Try to cheat + + +
    + +
    + +
    +
    + Wallets + retailer · Alice · Bob +
    +
    + Retailer (issuer) + Ready to issue points. + Issued {pts(ISSUED)} to Alice. + Received Bob's {pts(PRICE)}: receipt token. + Nothing redeemed yet. + told the auditor {pts(UNDER_REPORTED)} +
    +
    + Alice's balanceSECRETHIDDEN + + + {pts(ISSUED)} + {pts(n3.amount)} + ████████ + +
    +
    + Bob's balanceSECRETHIDDEN + + + {pts(TRANSFERRED)}{pts(n4.amount)} + 0 pts spendable + ████████ + +
    + Bob owns a note he can't open: unopenable, reported + both wallets rebuilt their balances from chain data alone + Alice rebuilt hers from chain data; Bob's scan flags the bad note +
    + π + {ISSUED.toLocaleString('en-US')} = {TRANSFERRED} + {n3.amount} + Groth16 +
    +
    + π + {TRANSFERRED} = {PRICE} + {n4.amount} + Groth16 +
    + +
    + + + + +
    +
    + Cardano + NoteLedger UTxOs +
    +
    + AuditorRegistry · generation 0PUBLIC + PK {fakeHash('auditor-pk')} +
    + both possession proofs verified on-chain + {NOTES.map((n) => ( +
    + {n.id} · {n.owner} · {n.how} · spent + C{commitment(n)} + + amount{pts(n.amount)}██████ + + + owner + auditor deliveries · 2 audit limbs + +
    + ))} + N2's owner delivery is random bytes. The ledger only checks its length. +
    + + + + +
    +
    + Auditor + regulator or retailer's audit desk +
    +
    + ElGamal key + viewing keySECRETHIDDEN + {fakeHash('auditor-sk')}████████ +
    +

    Registers once. Every note that follows carries its amount encrypted to this key.

    +
    + Every note, read from chain + {NOTES.map((n) => ( +
    + {n.id} · {n.owner} + {n.origin} + + + {n.id === 'N1' ? ( + <> + {pts(n.amount)} + {pts(UNDER_REPORTED)} (delivery: {pts(n.amount)}) + + ) : ( + pts(n.amount) + )} + ████████ + +
    + ))} + N1 mismatch: the limbs and the auditor's own delivery disagree + N2 still reads {pts(TRANSFERRED)}: the limbs are what the proof enforces +
    +
    +
    + +
    +
    +

    1. Register the auditor

    +

    The auditor publishes two keys in a one-of-a-kind registry UTxO: an ElGamal key for amounts and a viewing key for deliveries. The registry validator checks a proof that the auditor really holds each key.

    +
    +
    +

    2. Issue

    +

    The retailer issues {pts(ISSUED)} to Alice as a note: a Pedersen commitment, its opening sealed for Alice and for the auditor, and the amount encrypted to the auditor. Issuance is trusted for points, so nothing proves the auditor's copy is right. Here the retailer lies and encrypts {pts(UNDER_REPORTED)}. The ledger accepts it.

    +
    +
    +

    3. Transfer

    +

    Alice sends Bob {pts(TRANSFERRED)}. Her wallet spends N1 and creates N2 for Bob and N3 as her change. The proof shows {pts(ISSUED)} = {pts(TRANSFERRED)} + {pts(n3.amount)} without showing any amount, and that each new note's encrypted limbs hold its real amount. Alice puts random bytes where Bob's delivery belongs. The ledger can't tell.

    +
    +
    +

    4. Redeem

    +

    Bob spends {pts(PRICE)} at the shop. The price is public; the rest of his note, {pts(n4.amount)}, comes back as a new hidden note.

    +

    Bob can't open N2, so he can't build a proof to spend it. The points are his on-chain but stuck.

    +
    +
    +

    5. Recover from chain

    +

    No server keeps balances. Each wallet scans the ledger's UTxOs and opens the deliveries addressed to its viewing key, keeping only notes that name it as owner and that open to their commitment. A note Bob owns but can't open is reported, not ignored: it's evidence against the sender.

    +
    +
    +

    6. Audit

    +

    The auditor decrypts every note's limbs and cross-checks its own delivery. Notes created by a transfer or redeem are proof-enforced; the issued note is issuer-claimed. The lie shows up as a mismatch, but only because the retailer's delivery told the truth; the ledger didn't stop it. Payroll uses proved issuance to close that gap.

    +
    +
    + +
    +
      +
    1. +
    2. +
    3. +
    4. +
    5. +
    6. +
    +
    + + + +
    +
    +
    + SECRET readable only with the right key + PUBLIC on the chain for anyone + "Alice & Bob" combines both wallets: each one reads only its own notes. + Commitment and key values are illustrative. +
    +
    +
    + + + + diff --git a/www/src/components/walkthrough/SolvencyWalkthrough.astro b/www/src/components/walkthrough/SolvencyWalkthrough.astro new file mode 100644 index 00000000..83ffb0a0 --- /dev/null +++ b/www/src/components/walkthrough/SolvencyWalkthrough.astro @@ -0,0 +1,532 @@ +--- +// Proof of solvency with hidden balances (Pedersen commitments, demo C in zeroj-usecases), step by +// step: book -> commit and deliver -> prove and lock -> customers check -> auditor opens the total +// -> release. Values follow solvency-data.ts. Commitments and hashes are illustrative stand-ins +// (see fakeHash), not Jubjub points or BLAKE2b outputs. +// +// Four views: the exchange's (everything), a customer's (their own balance only), the auditor's +// (the total only) and the public's (nothing secret). The client script marks each secret row +// data-masked for the current view; rows list who may see them in data-vis. +import './walkthrough.css'; +import { fakeHash } from './engine'; +import { BOOK, DEFAULT_RESERVE, GARBAGE_DEFAULT, PERIOD, RESERVE_RANGE, TOTAL, ada, customerCheck, provable } from './solvency-data'; + +const commitment = (id: string, amount: number) => fakeHash(`C:${id}:${amount}`); +const idHash = (id: string) => fakeHash(`idHash:${id}:salt-p1`); +const sumC = fakeHash(`sumC:${BOOK.map((c) => `${c.id}=${c.ada}`).join(',')}`); +const ok = provable(DEFAULT_RESERVE); +const first = BOOK[0]; +const rings = [ + 'M116.28 43.93A56 56 0 1 1 29.76 19.69', + 'M45.87 98.53A39 39 0 1 1 94.31 39.46', + 'M55.21 43.29A22.5 22.5 0 0 1 80.18 79.63', +]; +--- + +
    +
    +
    + Hidden-balance solvency · step 1 / 6 +
    +
    + + + + +
    + +
    +
    + +
    + +
    +
    + Exchange + the book of accounts +
    + {BOOK.map((c) => ( +
    + {c.name}SECRETHIDDEN + {ada(c.ada)}████████ +
    + ))} +
    + total liabilities LSECRETHIDDEN + {ada(TOTAL)}████████ +
    +

    Each customer also gets a fresh salt for this period with their statement.

    +
    + reserve R to lockPUBLIC + {ada(DEFAULT_RESERVE)} + +
    + + + {ok ? 'proof made: the hidden total fits under R' : 'no proof exists: the book exceeds R'} + + +
    + + + + +
    +
    + Cardano + this period's vault +
    +

    Nothing published yet.

    +
    + Datum, ready to publish + Attestation datum +
      + {BOOK.map((c) => ( +
    • + idHash {idHash(c.id)} + C = {commitment(c.id, c.ada)} + delivery → {c.name} 89 bytes + delivery → {c.name} 89 random bytes +
    • + ))} +
    + auditor delivery: opening of ΣC 89 bytes + The vault checks shapes and lengths. It can't check that a delivery opens. +
    +
    + SolvencyVault + {ok ? `${ada(DEFAULT_RESERVE)} locked with the proof` : 'nothing locked'} + attested before the period starts (in about {PERIOD.leadSeconds} s) + period running ({PERIOD.lengthSeconds} s): nothing added, nothing released + release inside the period: rejected + period over: reserve released, token burned +
    +
    + + + +
    + +
    +
    + Customer + checks their own entry +
    + + {BOOK.map((c, i) => ( + + ))} + + {BOOK.map((c, i) => ( + + ))} +
    + my idHash appears exactly once + {`delivery opens to ${ada(first.ada)}: matches`} + {customerCheck(first.id, null)} +
    +

    Waits for the attestation.

    +
    + + +
    +
    + Auditor + registered viewing key +
    +
    +
    + ΣC, added up from the chainPUBLIC + {sumC} +
    + its delivery opens ΣC: L = {ada(TOTAL)} + {ok ? `L ≤ ${ada(DEFAULT_RESERVE)} locked` : 'no attestation to audit'} + One total, no single balance. +
    +

    Opens only the total, at step 5.

    +
    +
    +
    + +
    +
    +

    1. The book

    +

    The exchange owes four customers {ada(TOTAL)} in total. It wants to prove it holds enough to pay everyone without publishing any balance, or even the total. Switch views to see what each party knows.

    +
    +
    +

    2. Commit and deliver

    +

    Each balance becomes a Pedersen commitment C = v·G + r·H. Next to it go a salted hash of the customer's id and the opening (v, r) encrypted to that customer's viewing key. The auditor gets the opening of the sum, encrypted to its own key.

    +
    +
    +

    3. Prove and lock

    +

    A Groth16 proof shows that the four committed balances add up to at most R. The vault verifies it and locks R before the period starts. Drag R below {ada(TOTAL)}: no proof exists, so nothing can be locked.

    +
    +
    +

    4. Customers check

    +

    During the period, each customer finds their entry by its salted id hash and opens their delivery with their own key. The opening comes from the chain, not from the exchange. Pick a customer, or tick the cheat to see what Dave finds.

    +
    +
    +

    5. Auditor opens the total

    +

    Commitments add up, so anyone can compute ΣC from the chain. Only the auditor can open it, with its delivery, and it learns the total and nothing about any one customer.

    +
    +
    +

    6. Release

    +

    After the period ends, the exchange takes the reserve back. Because every attestation in a period is locked for the whole period, the same funds can't back two attestations one after another.

    +
    +
    + +
    +
      +
    1. +
    2. +
    3. +
    4. +
    5. +
    6. +
    +
    + + + +
    +
    +
    + SECRET visible only to whoever the view belongs to + PUBLIC on-chain + Commitments and hashes are illustrative. +
    +
    +
    + + + + diff --git a/www/src/components/walkthrough/TallyWalkthrough.astro b/www/src/components/walkthrough/TallyWalkthrough.astro new file mode 100644 index 00000000..161ea3e2 --- /dev/null +++ b/www/src/components/walkthrough/TallyWalkthrough.astro @@ -0,0 +1,320 @@ +--- +// Encrypted ballots and a homomorphic tally, step by step (zeroj-usecases PR #8, ADR-0005): +// election key -> encrypted votes -> double vote refused -> encrypted sum -> decryption shares -> +// result. The demo's election key is n-of-n: every trustee must post a share. +import './walkthrough.css'; +import { fakeHash } from './engine'; +import { TRUSTEES, VOTERS, ballotLabel, nullifierLabel, shareLabel, sumLabel, yesCount } from './tally-data'; + +const votes = VOTERS.map((v) => v.vote); +const yes = yesCount(votes); +const electionKey = fakeHash('election-key:PK1+PK2+PK3'); +--- + +
    +
    +
    + Encrypted tally · step 1 / 6 +
    +
    + + +
    + +
    +
    + +
    + +
    +
    + Voters + each knows only their own vote + identities and choices hidden +
    +

    Each voter holds an eligibility secret. Its key is a leaf in the voter tree.

    + {VOTERS.map((v, i) => ( +
    + {v.id} + + + + + SECRETHIDDEN + {v.vote ? 'YES' : 'NO'}████ +
    + ))} +
    + πeligible · my nullifier · encrypts 0 or 1one per ballot +
    + voter1 votes again: same secret, same nullifier +
    + + + + +
    +
    + Cardano + ballot policy + vote list +
    +
    + election key PK = PK₁ + PK₂ + PK₃PUBLIC + {electionKey} +
    +
    + Vote list (one node per nullifier) +
      + {VOTERS.map((v, i) => ( +
    • + N = {nullifierLabel(v.id)} + (A, B) = {ballotLabel(v.id, v.vote)} +
    • + ))} +
    + each proof verified on-chain, before the deadline + nullifier already in the list: second ballot refused +
    +
    + encrypted sum (ΣA, ΣB)PUBLIC + {sumLabel(votes)} +
    +

    Adding the ciphertexts adds the votes inside them. Nobody has decrypted anything yet.

    +
    + Result + YES {yes} · NO {VOTERS.length - yes} · total {VOTERS.length} + ΣB − (D₁ + D₂ + D₃) = [YES]·G, found by a short search + anyone re-checks the shares, the ballots and the count + +
    +
    + + + + +
    +
    + Trustees + n-of-n in the demo +
    + {TRUSTEES.map((t, j) => ( +
    + {t} +
    + sk{j + 1}SECRETHIDDEN + {fakeHash(`sk:${t}`)}████ +
    + publishes PK{j + 1} with a proof it knows sk{j + 1} + + absent: no share +
    + ))} + +
    +
    + +
    +
    +

    1. Election key

    +

    Three trustees each make a key pair and publish the public half, with a proof that they know the secret behind it (this stops a trustee choosing a key that cancels the others). The election key is the sum of the three. Nobody holds its secret key.

    +
    +
    +

    2. Encrypted votes

    +

    Each voter encrypts 0 or 1 to the election key and proves, in zero knowledge, that they are on the voter list, that the nullifier is theirs, and that the ciphertext holds a 0 or a 1, nothing else. The chain sees only ciphertexts. Flip a vote in the voters' view: its ciphertext changes, and the public view stays unreadable.

    +
    +
    +

    3. Vote twice?

    +

    voter1 tries again. The same secret gives the same nullifier, which is already in the on-chain list, so the second ballot is refused, whatever it encrypts.

    +
    +
    +

    4. Add them up

    +

    Anyone can add the ciphertexts. The result is one ciphertext of the number of YES votes. No single ballot is ever decrypted, and the running total isn't decrypted before the deadline either.

    +
    +
    +

    5. Decryption shares

    +

    After the deadline, each trustee applies its secret to the sum, once, and posts the result with a proof that it used the same secret as its registered key. A wrong share fails its proof. In the demo every trustee must take part; tick the box to see what happens when one doesn't.

    +
    +
    +

    6. Result

    +

    Removing the three shares leaves the YES count as a small curve multiple, found by a quick search. Anyone can redo every check from chain data. Only the total is revealed, never who voted what.

    +
    +
    + +
    +
      +
    1. +
    2. +
    3. +
    4. +
    5. +
    6. +
    +
    + + + +
    +
    +
    + SECRET known only to its owner + PUBLIC on-chain + Key and ciphertext values are illustrative. +
    +
    +
    + + + + diff --git a/www/src/components/walkthrough/auction-data.ts b/www/src/components/walkthrough/auction-data.ts new file mode 100644 index 00000000..ffddc6a3 --- /dev/null +++ b/www/src/components/walkthrough/auction-data.ts @@ -0,0 +1,41 @@ +// Data and rules for AuctionWalkthrough, shared by its server render and its client script. +// Values follow the zeroj-usecases sealed-bid auction demo (pedersen-commitments, PR #9): lot +// "Painting", a common deposit of 100 ADA, a reserve of 10 ADA, and AuctionDevKitE2ETest's bids +// alice 40, bob 70, carol 70 (bob wins at 70 as the earlier of the two highest bids). + +export const ITEM = 'Painting'; +export const DEPOSIT = 100; +export const RESERVE = 10; +export const BID_RANGE = { min: 0, max: 120, step: 5 }; + +export type Bidder = { id: string; name: string; bid: number }; + +export const BIDDERS: Bidder[] = [ + { id: 'alice', name: 'Alice', bid: 40 }, + { id: 'bob', name: 'Bob', bid: 70 }, + { id: 'carol', name: 'Carol', bid: 70 }, +]; + +export const ada = (n: number) => `${n.toLocaleString('en-US')} ADA`; + +// BidProof: a proof exists only for reserve <= bid <= deposit, so other bids never reach the lot. +export const bidOk = (bid: number) => bid >= RESERVE && bid <= DEPOSIT; + +export type Settlement = + | { kind: 'none' } + | { kind: 'win'; winner: number; price: number; cheat: { bidder: number; price: number } }; + +// SettleProof: first price, the earliest highest bid wins. `bids` are in lot (datum) order; an +// out-of-range bid was refused at bid time, so it isn't in the lot. The cheat is a claim the +// auctioneer can't prove: the best other accepted bid at its own amount (with a tie, the later +// equal bid, as in the demo's cheat), or else a lower price. +export function settle(bids: number[]): Settlement { + const accepted = bids.map((b, i) => ({ b, i })).filter((x) => bidOk(x.b)); + if (accepted.length === 0) return { kind: 'none' }; + let best = accepted[0]; + for (const x of accepted) if (x.b > best.b) best = x; + let other: { b: number; i: number } | undefined; + for (const x of accepted) if (x.i !== best.i && (!other || x.b > other.b)) other = x; + const cheat = other ? { bidder: other.i, price: other.b } : { bidder: best.i, price: best.b - 5 }; + return { kind: 'win', winner: best.i, price: best.b, cheat }; +} diff --git a/www/src/components/walkthrough/commitment-data.ts b/www/src/components/walkthrough/commitment-data.ts new file mode 100644 index 00000000..d435d8bc --- /dev/null +++ b/www/src/components/walkthrough/commitment-data.ts @@ -0,0 +1,13 @@ +// Data for CommitmentExplainer, shared by its server render and its client script. The amounts are +// made up for the illustration; the commitment strings are FNV stand-ins (fakeHash), not points. +import { fakeHash } from './engine'; + +export const ALICE = { amount: 4_200, blinding: 7_340_113, blinding2: 7_340_113 ^ 0x5bd1e995 }; +export const BOB = { amount: 2_500, blinding: 1_928_377 }; +export const MIN_DEPOSIT = 1_000; + +export const fmt = (n: number) => `${n.toLocaleString('en-US')} ADA`; + +// The same (amount, blinding) always gives the same label, and the sum step uses (a + b, r + s), +// so "C + D" and "commit(a + b, r + s)" print the same value, as they do for real commitments. +export const commitLabel = (amount: number, blinding: number) => fakeHash(`C:${amount}:${blinding}`); diff --git a/www/src/components/walkthrough/disclosure-options-data.ts b/www/src/components/walkthrough/disclosure-options-data.ts new file mode 100644 index 00000000..04eb08c3 --- /dev/null +++ b/www/src/components/walkthrough/disclosure-options-data.ts @@ -0,0 +1,151 @@ +// Data for DisclosureOptionsExplainer: one salary disclosed six ways. Carol's salary and the +// threshold are made up for the illustration (the payroll demo pays Carol 5,000). + +export const SALARY = 5_000; +export const OTHER_SALARY = 4_200; // Dave, for the payroll total in "split trust" +export const THRESHOLD = 3_000; + +export type Seen = { kind: 'value' | 'proof' | 'sealed' | 'none'; text: string }; + +export type Option = { + id: string; + label: string; + tech: string; + href: string; + summary: string; + carol: Seen; + landlord: Seen; + tax: Seen; + everyone: Seen; + needs: string; + onchain: string; + maturity: string; +}; + +const n = (x: number) => x.toLocaleString('en-US'); + +export const OPTIONS: Option[] = [ + { + id: 'reveal', + label: 'Reveal the value', + tech: 'BBS', + href: '/selective-disclosure/reveal-attributes/', + summary: + 'The employer signs a credential once. Carol shows the landlord only the salary line and hides the rest, and the landlord checks the employer signed it.', + carol: { kind: 'value', text: `holds the signed credential (salary ${n(SALARY)}, name, role, …)` }, + landlord: { kind: 'value', text: `salary = ${n(SALARY)}, signed by the employer` }, + tax: { kind: 'none', text: 'not involved' }, + everyone: { kind: 'none', text: 'nothing; revealed values become public only if the presentation goes on-chain' }, + needs: 'An issuer with a BBS key. No circuit, no trusted setup.', + onchain: 'BbsProofVerify, one fixed credential shape', + maturity: 'Beta (IRTF draft)', + }, + { + id: 'rule', + label: 'Prove a rule', + tech: 'Groth16 predicate', + href: '/selective-disclosure/prove-a-rule/', + summary: + 'Carol proves a statement about her signed salary, such as "at least 3,000", without revealing the number. The landlord learns yes or no.', + carol: { kind: 'value', text: `knows ${n(SALARY)}; runs the circuit on her device` }, + landlord: { kind: 'proof', text: `salary ≥ ${n(THRESHOLD)}: yes` }, + tax: { kind: 'none', text: 'not involved' }, + everyone: { kind: 'proof', text: `the proof and the threshold ${n(THRESHOLD)}` }, + needs: 'A circuit per question, and a trusted setup per circuit.', + onchain: 'Groth16 verifier, about 2.1–2.5 billion steps, by public-input count', + maturity: 'Beta', + }, + { + id: 'commit', + label: 'Hide a number', + tech: 'Pedersen commitment', + href: '/selective-disclosure/hide-a-number/', + summary: + 'The salary is published as a sealed commitment. Proofs show facts about it, and commitments add up, so totals can be checked without seeing any one salary.', + carol: { kind: 'value', text: `knows ${n(SALARY)} and the blinding` }, + landlord: { kind: 'proof', text: `"the commitment hides at least ${n(THRESHOLD)}": yes` }, + tax: { kind: 'sealed', text: 'can add commitments up; learns a total only if given its opening' }, + everyone: { kind: 'sealed', text: 'a 32-byte commitment' }, + needs: 'A circuit for each statement about the value.', + onchain: 'Commitment as two public inputs to a Groth16 proof', + maturity: 'Ready (pending review) in-circuit; Experimental sums', + }, + { + id: 'readers', + label: 'Tell chosen readers', + tech: 'Confidential note', + href: '/selective-disclosure/share-with-chosen-readers/', + summary: + 'Next to the commitment, the opening is sealed on-chain for Carol and for the tax authority. Each one decrypts their own copy and checks it matches.', + carol: { kind: 'value', text: `opens her delivery: ${n(SALARY)}` }, + landlord: { kind: 'none', text: 'nothing, unless Carol shares the opening' }, + tax: { kind: 'value', text: `opens its delivery: ${n(SALARY)}, if the sender delivered honestly (not enforced)` }, + everyone: { kind: 'sealed', text: 'the commitment + 89 bytes per reader' }, + needs: 'A viewing key per reader. No circuit for delivery itself.', + onchain: 'Deliveries in the datum; only their length is checked', + maturity: 'Experimental', + }, + { + id: 'auditor', + label: 'Encrypt for an auditor', + tech: 'ElGamal + proof', + href: '/selective-disclosure/encrypt-for-an-auditor/', + summary: + "The salary is also encrypted to the tax authority's key, and a proof shows the ciphertext holds the same amount as the commitment. The employer can't under-report.", + carol: { kind: 'value', text: `knows ${n(SALARY)}` }, + landlord: { kind: 'none', text: 'not involved' }, + tax: { kind: 'value', text: `decrypts ${n(SALARY)}, guaranteed to match the commitment` }, + everyone: { kind: 'sealed', text: 'commitment, ciphertext and proof' }, + needs: 'An auditor key with a possession proof, and a circuit.', + onchain: 'Groth16 proof binds the ciphertext to the commitment', + maturity: 'Experimental', + }, + { + id: 'threshold', + label: 'Split the trust', + tech: 'Threshold ElGamal', + href: '/selective-disclosure/split-trust/', + summary: + 'Salaries are encrypted to a key no one holds. Any 2 of 3 trustees together can decrypt; by policy they decrypt only the agreed result, here the payroll total. A quorum could decrypt one salary, so pick independent trustees.', + carol: { kind: 'value', text: `knows ${n(SALARY)}` }, + landlord: { kind: 'none', text: 'not involved' }, + tax: { kind: 'proof', text: `2 of 3 trustees decrypt the total: ${n(SALARY + OTHER_SALARY)}` }, + everyone: { kind: 'sealed', text: 'ciphertexts, then the total once decrypted' }, + needs: 'A key generation ceremony among the trustees.', + onchain: 'Ciphertexts in datums; ballot-style proofs', + maturity: 'Experimental', + }, +]; + +// "Help me choose": each answer either asks another question or picks an option. +export type Choice = { text: string; next?: string; pick?: string }; +export type Question = { id: string; text: string; choices: Choice[] }; + +export const QUESTIONS: Question[] = [ + { + id: 'exact', + text: 'Does anyone need to learn the exact value?', + choices: [ + { text: 'No, a yes/no answer is enough', next: 'later' }, + { text: 'Yes', next: 'who' }, + ], + }, + { + id: 'later', + text: 'Does the value also need to live on-chain, to be added up or checked again later?', + choices: [ + { text: 'No, just answer this one question', pick: 'rule' }, + { text: 'Yes, keep it sealed on-chain', pick: 'commit' }, + ], + }, + { + id: 'who', + text: 'Who should learn it?', + choices: [ + { text: 'The verifier I am talking to', pick: 'reveal' }, + { text: 'Named parties, later, straight from the chain', pick: 'readers' }, + { text: "An authority, and the sender mustn't be able to lie", pick: 'auditor' }, + { text: 'No single party; only a group together', pick: 'threshold' }, + ], + }, +]; diff --git a/www/src/components/walkthrough/encryption-data.ts b/www/src/components/walkthrough/encryption-data.ts new file mode 100644 index 00000000..2f3128ee --- /dev/null +++ b/www/src/components/walkthrough/encryption-data.ts @@ -0,0 +1,15 @@ +// Data for EncryptionExplainer. Amounts are made up for the illustration; ciphertext strings are +// FNV stand-ins (fakeHash), not curve points. +import { fakeHash } from './engine'; + +export const SENDERS = [ + { name: 'Alice', amount: 4_200, nonce: 101 }, + { name: 'Bob', amount: 2_500, nonce: 202 }, +]; + +export const TRUSTEES = ['Trustee 1', 'Trustee 2', 'Trustee 3']; +export const THRESHOLD = 2; + +export const fmt = (n: number) => n.toLocaleString('en-US'); + +export const ctLabel = (amount: number, nonce: number) => fakeHash(`ct:${amount}:${nonce}`); diff --git a/www/src/components/walkthrough/note-delivery-data.ts b/www/src/components/walkthrough/note-delivery-data.ts new file mode 100644 index 00000000..87e85b3b --- /dev/null +++ b/www/src/components/walkthrough/note-delivery-data.ts @@ -0,0 +1,25 @@ +// Data for NoteDeliveryExplainer, shared by its server render and its client script. The amount +// matches the guide's ConfidentialNoteDemo (250). Points and bytes are FNV stand-ins (fakeHash). +import { fakeHash } from './engine'; + +export const AMOUNT = 250; + +export type Holder = 'owner' | 'auditor' | 'stranger'; + +export const HOLDERS: { id: Holder; label: string; position: number | null }[] = [ + { id: 'owner', label: 'Owner', position: 0 }, + { id: 'auditor', label: 'Auditor', position: 1 }, + { id: 'stranger', label: 'Stranger', position: null }, +]; + +export const commitment = fakeHash(`note-C:${AMOUNT}`); +export const delivery = (position: number, garbage = false) => + garbage ? fakeHash(`random-89-bytes:${position}`) : fakeHash(`delivery:${position}:${AMOUNT}`); + +// The wallet scan in step 5: notes at the ledger address, as the owner's wallet sees them. +export const SCAN = [ + { label: 'Note A', mine: true, opens: true, amount: AMOUNT }, + { label: 'Note B', mine: false, opens: false, amount: 0 }, + { label: 'Note C', mine: true, opens: true, amount: 40 }, + { label: 'Note D', mine: true, opens: false, amount: 0 }, +]; diff --git a/www/src/components/walkthrough/payroll-data.ts b/www/src/components/walkthrough/payroll-data.ts new file mode 100644 index 00000000..0f87a2e3 --- /dev/null +++ b/www/src/components/walkthrough/payroll-data.ts @@ -0,0 +1,16 @@ +// Data for PayrollWalkthrough, shared by its server render and its client script. Values follow the +// zeroj-usecases pedersen-commitments payroll tab (zeroj-usecases PR #9): the UI pays carol 5,000, +// the DevKit E2E pays carol 5,000 and dave 4,200 in one pay run and carol transfers 800 to dave; the +// UI's cash-out default is 1,000, and the under-report cheat tells the tax authority 3,000. + +export const CAROL_SALARY = 5_000; +export const DAVE_SALARY = 4_200; +export const TRANSFER = 800; +export const CASH_OUT = 1_000; +export const REPORTED_DEFAULT = 3_000; + +export const credits = (n: number) => n.toLocaleString('en-US'); + +// NoteIssueProof exists only if every note's two 32-bit limbs, encrypted to the tax authority, +// recombine to the amount the note's commitment hides. +export const issueProofExists = (reported: number) => reported === CAROL_SALARY; diff --git a/www/src/components/walkthrough/points-data.ts b/www/src/components/walkthrough/points-data.ts new file mode 100644 index 00000000..882b192a --- /dev/null +++ b/www/src/components/walkthrough/points-data.ts @@ -0,0 +1,30 @@ +// Data for PointsWalkthrough. Values follow the zeroj-usecases pedersen-commitments demo, points tab +// (PR #9, branch feat/confidential-notes-m3): the retailer issues 1,000 to alice, alice transfers +// 700 to bob, bob redeems 120 at the retailer. The under-report cheat tells the auditor 100. +// Commitment strings are FNV stand-ins (fakeHash), not Jubjub points. +import { fakeHash } from './engine'; + +export type Note = { + id: string; + owner: 'Alice' | 'Bob'; + amount: number; + createdAt: number; // step that creates the note + spentAt?: number; // step that spends it (honest run) + origin: 'issuer-claimed' | 'proof-enforced'; + how: string; +}; + +export const ISSUED = 1_000; +export const TRANSFERRED = 700; +export const PRICE = 120; +export const UNDER_REPORTED = 100; + +export const NOTES: Note[] = [ + { id: 'N1', owner: 'Alice', amount: ISSUED, createdAt: 2, spentAt: 3, origin: 'issuer-claimed', how: 'issued by the retailer' }, + { id: 'N2', owner: 'Bob', amount: TRANSFERRED, createdAt: 3, spentAt: 4, origin: 'proof-enforced', how: 'transfer output' }, + { id: 'N3', owner: 'Alice', amount: ISSUED - TRANSFERRED, createdAt: 3, origin: 'proof-enforced', how: 'transfer change' }, + { id: 'N4', owner: 'Bob', amount: TRANSFERRED - PRICE, createdAt: 4, origin: 'proof-enforced', how: 'redeem change' }, +]; + +export const pts = (n: number) => `${n.toLocaleString('en-US')} pts`; +export const commitment = (n: Note) => fakeHash(`note:${n.id}:${n.amount}`); diff --git a/www/src/components/walkthrough/proof-system-data.ts b/www/src/components/walkthrough/proof-system-data.ts index ae7e95be..8ce2b234 100644 --- a/www/src/components/walkthrough/proof-system-data.ts +++ b/www/src/components/walkthrough/proof-system-data.ts @@ -57,7 +57,7 @@ export function recommend(a: Answers): Recommendation { } if (a.where === 'cardano') { if (circuit) { - notes.push({ kind: 'ok', html: 'Groth16 on Cardano is Beta, testnet only. In ZeroJ\u2019s JuLC VM tests, a proof with two public inputs used about 2.8 billion of the 10 billion CPU units a transaction may spend.' }); + notes.push({ kind: 'ok', html: 'Groth16 on Cardano is Beta, testnet only. In ZeroJ\u2019s JuLC VM tests, a proof with two public inputs used about 2.2 billion of the 10 billion CPU units a transaction may spend.' }); } if (a.need !== 'compute') { notes.push({ kind: 'warn', html: 'On-chain BBS supports one fixed shape: a 5-attribute credential revealing indexes 2 and 3. Other shapes need a different unrolling, or a Groth16 circuit.' }); diff --git a/www/src/components/walkthrough/solvency-data.ts b/www/src/components/walkthrough/solvency-data.ts new file mode 100644 index 00000000..6a3c5634 --- /dev/null +++ b/www/src/components/walkthrough/solvency-data.ts @@ -0,0 +1,29 @@ +// Data for SolvencyWalkthrough, shared by its server render and its client script. Values follow the +// zeroj-usecases pedersen-commitments demo C (SolvencyService defaults on the +// feat/confidential-notes-m3 branch): four customers, 2,000 ADA locked, a period that starts about +// 45 s after the attestation and lasts 180 s. Commitments and hashes are fakeHash stand-ins. + +export const BOOK = [ + { id: 'alice', name: 'Alice', ada: 500 }, + { id: 'bob', name: 'Bob', ada: 1_200 }, + { id: 'carol', name: 'Carol', ada: 300 }, + { id: 'dave', name: 'Dave', ada: 0 }, +]; + +export const TOTAL = BOOK.reduce((sum, c) => sum + c.ada, 0); +export const DEFAULT_RESERVE = 2_000; +export const RESERVE_RANGE = { min: 1_000, max: 3_000, step: 100 }; +export const PERIOD = { leadSeconds: 45, lengthSeconds: 180 }; +export const GARBAGE_DEFAULT = 'dave'; + +export const ada = (n: number) => `${n.toLocaleString('en-US')} ADA`; + +// HiddenLiabilitySolvencyProof: Σ balances ≤ reserves. Below the book total no proof exists. +export const provable = (reserve: number) => TOTAL <= reserve; + +export type Check = 'LISTED_ONCE_CORRECT' | 'UNOPENABLE'; + +// SolvencyAttestation.customerCheck, for the two outcomes the walkthrough can produce: an honest +// entry, or the "garbage delivery" cheat, which the vault accepts (it only checks the length). +export const customerCheck = (id: string, garbageFor: string | null): Check => + id === garbageFor ? 'UNOPENABLE' : 'LISTED_ONCE_CORRECT'; diff --git a/www/src/components/walkthrough/tally-data.ts b/www/src/components/walkthrough/tally-data.ts new file mode 100644 index 00000000..dc040e5a --- /dev/null +++ b/www/src/components/walkthrough/tally-data.ts @@ -0,0 +1,21 @@ +// Data for TallyWalkthrough, shared by its server render and its client script. Values follow the +// private-voting demo on zeroj-usecases PR #8 (ADR-0005): 3 trustees holding an n-of-n election key, +// and the README flow voter1 YES, voter2 NO, voter3 YES, then voter1 again (refused). +// Ciphertext and key strings are FNV stand-ins (fakeHash), not Jubjub points. +import { fakeHash } from './engine'; + +export const VOTERS = [ + { id: 'voter1', vote: 1 }, + { id: 'voter2', vote: 0 }, + { id: 'voter3', vote: 1 }, +]; + +export const TRUSTEES = ['Trustee 1', 'Trustee 2', 'Trustee 3']; + +// The ciphertext label depends on the vote and a per-voter nonce, so flipping a vote changes it. +export const ballotLabel = (voter: string, vote: number) => fakeHash(`ballot:${voter}:${vote}`); +export const nullifierLabel = (voter: string) => fakeHash(`nullifier:${voter}:dao-proposal-1`); +export const sumLabel = (votes: number[]) => fakeHash(`sum:${votes.join('')}`); +export const shareLabel = (trustee: string, votes: number[]) => fakeHash(`share:${trustee}:${votes.join('')}`); + +export const yesCount = (votes: number[]) => votes.reduce((s, v) => s + v, 0); diff --git a/www/src/content/docs/ai/starter-pack.md b/www/src/content/docs/ai/starter-pack.md index 85a1b94a..54f47b79 100644 --- a/www/src/content/docs/ai/starter-pack.md +++ b/www/src/content/docs/ai/starter-pack.md @@ -184,6 +184,21 @@ The annotation processor generates `Circuit` with: `build(...)`, `sch - **Never** for Cardano: `ZkMiMC` (BN254-only), the no-params Poseidon overload, `ZkMerkle.HashType.MIMC` or `HashType.POSEIDON`. - Heavier gadgets exist for real-world cryptography: `ZkSha512`, `ZkHmacSha512`, `ZkBlake2b`, `ZkCip1852` (BIP32-Ed25519 / CIP-1852 derivation), `ZkPedersen`, `ZkJubjubPoint`, `ZkEdDSAJubjub`. Bind prover-supplied Jubjub points with `ZkJubjubPoint.witnessAffine(zk, u, v)`. See [Gadget library](/guides/circuits/gadgets/). +### Commitments and encryption (new in 0.1.0-pre13, experimental) + +Pedersen commitments, exponential ElGamal, threshold DKG and confidential notes are in `zeroj-circuit-lib` (host classes in `org.zeroj.circuit.lib.jubjub`, circuit adapters in `org.zeroj.circuit.lib.zk`). Rules: + +- **Blinding:** a Pedersen blinding is `@Secret @UInt(bits = 252)` in circuits (narrower, public or constant blindings make `build()` throw) and `PedersenCommitment.randomBlinding(new SecureRandom())` on the host — fresh every time, never derived from public data. +- **Decoding:** received commitment bytes go through `PedersenCommitment.decode` (canonical + prime-order subgroup), never `JubjubPoint.fromBytes`. The verifier rebuilds the public inputs (commitment `u`, then `v`) from data it trusts. +- **No wrap:** commitment and ciphertext sums are modulo a 252-bit order. Prove conservation with `ZkPedersen.assertBalanced` on width-bounded terms; never treat an off-circuit point sum as an integer total. +- **ElGamal widths:** message width 1–64; ciphertext bounds add up under `add`/`sum`; decryption needs `maxPlaintext ≥ bound` and only works up to about 2^43, so encrypt 64-bit amounts as two 32-bit limbs and use the narrowest width that fits. +- **Verify by type, with real proofs:** keys from others → `VerifiedKeyShare.verify(bytes, possessionProofVerifier)`; ciphertexts from others → `ElGamal.admit(raw, ctx, width, encryptionProofVerifier)`; decryption shares → `VerifiedDecryptionShare.verify(…)`. A verifier lambda that returns `true` (`s -> true`) silently removes the guarantee — only use it when a validator already checked that exact proof, and say so in a comment. +- **Threshold:** `DkgConfig.create(t, n, …)` means any `t + 1` of `n` decrypt, with `2t + 1 ≤ n ≤ 64` (2-of-3 is `create(1, 3, …)`). Never reuse an `attempt` number. Decrypt only the final total, once; decrypting running totals leaks individual values. With HPKE delivery, close round 1 only through `DkgShareDelivery.closeRound1`. +- **Notes:** reader order is fixed (owner first, then auditors); a reader opens only its own delivery position and checks the owner credential itself; report `unopenableOwned` notes, never drop them; scan only in the user's own wallet process. A viewing key can't spend. +- **Secret operations are offline/isolated only** (variable-time arithmetic): committing, encrypting, decrypting, DKG dealing, sealing and opening notes. Don't put them in a timing-observable service. +- **Not a library API:** an auditor amount enforced inside a transfer proof ("D3a") is a pattern you build in your own circuit (`ZkElGamal.encrypt` + `ZkPedersenCommitment`), and issued notes carry whatever audit data the issuer supplied. +- Guides: [Commitments & encryption, explained](/learn/commitments-and-encryption/), [Pedersen commitments](/guides/confidential/pedersen/), [ElGamal encryption](/guides/confidential/elgamal/), [Threshold decryption](/guides/confidential/threshold-elgamal/), [Confidential notes](/guides/confidential/confidential-notes/), [Choose how to disclose](/selective-disclosure/). + ### Lower-level DSL When annotations don't fit, implement `CircuitSpec` and use `SignalBuilder`/`Signal`: @@ -260,6 +275,9 @@ var p = ProverToCardano.compressProof(proof); // piA (48 B), piB (96 B) | Inventing a seeded/deterministic prover for reproducibility | Store the proof you produced | | Bare `Groth16BLS12381Verifier` (or the datum-based `Groth16BLS12381TxOutRefBindingVerifier`) guarding funds | A custom validator on `Groth16BLS12381Lib` that computes the spend binding from `ScriptContext`, binds the recipient, and enforces policy | | Trusting a prover-supplied fact ("my age is 27") | Have an issuer sign or commit to it and verify that inside the circuit or with BBS | +| A short or public Pedersen blinding, or reusing one | `@Secret @UInt(bits = 252)` and a fresh `PedersenCommitment.randomBlinding(new SecureRandom())` | +| Summing commitments or ciphertexts and calling it an integer total | `ZkPedersen.assertBalanced` with declared widths; track ElGamal bounds | +| `s -> true` as a key, share or ciphertext verifier | Verify the possession, DLEQ or encryption proof for exactly that statement | | Testing only the happy path | Invalid-witness and tampered-public-input tests for every constraint | | Claiming "secure", "audited", "production-ready" | "Experimental, not externally audited" | diff --git a/www/src/content/docs/guides/circuits/gadgets.md b/www/src/content/docs/guides/circuits/gadgets.md index d2df32a6..c79441d4 100644 --- a/www/src/content/docs/guides/circuits/gadgets.md +++ b/www/src/content/docs/guides/circuits/gadgets.md @@ -148,7 +148,8 @@ the public commitment. Sample it with `PedersenCommitment.randomBlinding(SecureR complete commitment with both coordinates bound as public inputs costs 2,410 constraints for a 64-bit value and 4,042 for a 252-bit value. A value narrower than 252 bits is canonical by its own range, so only full-width values pay for the comparator. The profile is specified in -`docs/specs/pedersen-jubjub-v1.md`. +`docs/specs/pedersen-jubjub-v1.md`. For a step-by-step introduction with runnable programs, see +[Pedersen commitments](/guides/confidential/pedersen/). **Commitments the circuit did not compute.** `ZkPedersenCommitment` is a typed commitment that records where a point came from. Use `ZkPedersenCommitment.commit(...)` for commitments @@ -248,7 +249,9 @@ affected. The normative scheme is `elgamal-jubjub-v1` is exponential ("lifted") ElGamal on Jubjub. A message `m` becomes `A = [k]·G`, `B = [m]·G + [k]·PK`. Ciphertexts under one key add up to an encryption of the sum, so you can total encrypted votes, bids or survey answers and decrypt only the total. The profile -is specified in `docs/specs/elgamal-jubjub-v1.md` (ADR-0052). It is **experimental**. +is specified in `docs/specs/elgamal-jubjub-v1.md` (ADR-0052). It is **experimental**. The +host-side guides are [ElGamal encryption](/guides/confidential/elgamal/) and +[Threshold decryption](/guides/confidential/threshold-elgamal/). **Proving a ciphertext is well formed.** The circuit side proves that a public ciphertext encrypts an in-range message under a key: @@ -273,7 +276,8 @@ void prove(ZkContext zk, (`fromVerifierFixedPublic`; the verifier checks subgroup membership), or as a witness proved in the subgroup (`witnessInSubgroup`). Both refuse the identity key. -Cost: 6,558 constraints at width 1, and 6,938 at width 64. +Cost: 6,558 constraints at width 1, 6,650 at width 16 and 6,938 at width 64 with a +verifier-fixed key; a key witnessed in the subgroup raises it to 12,105. **Trustee proofs.** `ZkElGamal.assertDiscreteLogEquality(zk, x, X…, P…, D…)` proves `P = [x]·G` and `D = [x]·X` (6,546 constraints). All six coordinates must be public inputs, so @@ -369,7 +373,7 @@ spec `docs/specs/dkg-share-delivery-hpke-v1.md`. itself, to each of its readers: the owner, and any auditors the application requires. It uses Zcash Sapling's key agreement on Jubjub, its BLAKE2b-256 KDF (with ZeroJ's personalization) and ChaCha20-Poly1305, with a fresh ephemeral key per reader. Recipients and auditors recover every -note from chain data alone. +note from chain data alone. See [Confidential notes](/guides/confidential/confidential-notes/). ```java // Sender: one delivery per reader, in the application's order (owner first, then auditors). @@ -486,5 +490,7 @@ The authoritative, detailed table is in the ## Next steps - [Test your circuits for soundness](/guides/circuits/testing-circuits/) +- [Commitments & encryption, explained](/learn/commitments-and-encryption/) and + [Choose how to disclose](/selective-disclosure/) - [Private allowlist with a Merkle tree](/tutorials/private-allowlist/) - [Prove with Groth16](/guides/proving/groth16/) diff --git a/www/src/content/docs/guides/confidential/confidential-notes.mdx b/www/src/content/docs/guides/confidential/confidential-notes.mdx new file mode 100644 index 00000000..36476a61 --- /dev/null +++ b/www/src/content/docs/guides/confidential/confidential-notes.mdx @@ -0,0 +1,249 @@ +--- +title: Confidential notes +description: 'Put a Pedersen commitment on-chain together with its opening, encrypted separately for the owner and each auditor, then recover notes by scanning the chain with a viewing key.' +sidebar: + order: 4 +--- + +import SinceNotice from '../../../../components/SinceNotice.astro'; +import NoteDeliveryExplainer from '../../../../components/walkthrough/NoteDeliveryExplainer.astro'; + +A [Pedersen commitment](/guides/confidential/pedersen/) hides an amount, but whoever owns it needs +the **opening**, the amount and the blinding `(v, r)`, to spend it or prove anything about it later. +Sending that opening over a private channel is fragile: lose the message and the money is stuck. + +A **confidential note** puts the opening on-chain too, encrypted separately for each reader. The +owner comes first, then any auditors. Each reader holds a **viewing key**: a key that can read +deliveries but can't spend anything. The rest of the world sees the commitment and a few +random-looking bytes per reader. + +That gives you two things: + +- **Recovery from the chain.** A wallet that knows only its viewing key can rebuild its balance by + scanning the ledger. No side channel, no backup of every opening. +- **Chosen readers.** The owner and the named auditors can read the amount. Nobody else can. + +ZeroJ's profile is [`confidential-note-jubjub-v1`](https://github.com/bloxbean/zeroj/blob/main/docs/specs/confidential-note-jubjub-v1.md), +designed in [ADR-0055](https://github.com/bloxbean/zeroj/blob/main/docs/adr/0055-confidential-notes-jubjub.md). + + + + + +## Status + +| Area | Status | +|---|---| +| Notes: seal, open, scan (`ConfidentialNotes`, `NoteScanner`, `NoteViewingKey`, `NoteReaderKey`, `NoteOpening`) | **Experimental**, pending review and external review | +| Secret operations (sealing, opening, viewing keys) | **Offline/isolated only**: variable-time arithmetic on secrets | +| Assumptions A1–A3 (see [below](#assumptions-in-plain-words)) | Unproved; external review is a production gate | + +The delivery format is checked against all 10 Zcash Sapling note-encryption test vectors, an +independent Python reference written from the spec, BouncyCastle's personalized BLAKE2b and the +Wycheproof ChaCha20-Poly1305 vectors. It behaves identically in a GraalVM native image. + +## How a delivery works + +The construction follows Zcash Sapling's note encryption on the Jubjub curve: + +1. For each reader, the sender picks a **fresh one-time key** `e` and publishes `E = e·G`. +2. Sender and reader agree on a shared secret from `e` and the reader's public **reader key** + (Diffie–Hellman on Jubjub). +3. A BLAKE2b-256 key-derivation step, personalized with `ZeroJ_NoteKDF_v1`, turns that secret into + a one-time encryption key. +4. ChaCha20-Poly1305 encrypts the 41-byte plaintext `0x01 ‖ v (8 bytes) ‖ r (32 bytes)` into a + 57-byte ciphertext. Because each key encrypts exactly one message, the fixed all-zero nonce is + safe. + +A delivery is `E ‖ ciphertext`, **89 bytes per reader**. A reader who decrypts it doesn't trust the +result blindly: it **accepts the opening only if `commit(v, r)` recomputes the note's commitment**. +A delivery that doesn't decrypt, or decrypts to a wrong opening, is rejected. + +## 1. Create, deliver, open, scan + +This program plays every party: an owner, an auditor and a stranger make viewing keys, a sender +creates a note for 250, and each reader tries to open it. It needs only `zeroj-circuit-lib` +(plus `zeroj-bom-core`); see [Pedersen commitments](/guides/confidential/pedersen/#add-the-dependency). + +```java title="ConfidentialNoteDemo.java" +import org.zeroj.circuit.lib.jubjub.ConfidentialNotes; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.NoteOpening; +import org.zeroj.circuit.lib.jubjub.NoteReaderKey; +import org.zeroj.circuit.lib.jubjub.NoteScanner; +import org.zeroj.circuit.lib.jubjub.NoteScanner.Candidate; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.List; +import java.util.Optional; + +/** + * A confidential note: a Pedersen commitment to an amount, plus its opening (amount, blinding) + * encrypted to each reader. The owner and an auditor can open it; nobody else can. + */ +public class ConfidentialNoteDemo { + + public static void main(String[] args) { + SecureRandom random = new SecureRandom(); + + // 1. Each reader makes a viewing key in its own wallet and publishes the reader key. + NoteViewingKey ownerKey = NoteViewingKey.generate(random); + NoteViewingKey auditorKey = NoteViewingKey.generate(random); + NoteViewingKey strangerKey = NoteViewingKey.generate(random); + byte[] ownerPublished = ownerKey.readerKey().encode(); // 32 bytes + byte[] auditorPublished = auditorKey.readerKey().encode(); + + // 2. The sender validates the received reader keys, then creates the note: + // the commitment C goes in the datum, one 89-byte delivery per reader next to it. + List readers = List.of( // order: owner, then auditors + NoteReaderKey.decode(ownerPublished), + NoteReaderKey.decode(auditorPublished)); + NoteOpening opening = NoteOpening.random(BigInteger.valueOf(250), random); + JubjubPoint c = opening.commitment(); + BigInteger u = c.affineU(); + BigInteger v = c.affineV(); + List deliveries = ConfidentialNotes.seal(opening, readers, random); + System.out.println("Deliveries: " + deliveries.size() + " x " + deliveries.get(0).length + " bytes"); + + // 3. The owner opens the delivery at its position (0) against the note's (u, v). + NoteScanner owner = NoteScanner.of(ownerKey); + Optional mine = owner.open(deliveries.get(0), u, v); + System.out.println("Owner reads amount: " + mine.map(NoteOpening::value).orElse(null)); + + // 4. The auditor opens its own delivery (position 1). + Optional audited = NoteScanner.of(auditorKey).open(deliveries.get(1), u, v); + System.out.println("Auditor reads amount: " + audited.map(NoteOpening::value).orElse(null)); + + // 5. Anyone else gets "not mine", for every delivery. + NoteScanner stranger = NoteScanner.of(strangerKey); + System.out.println("Stranger opens delivery 0? " + stranger.open(deliveries.get(0), u, v).isPresent()); + System.out.println("Stranger opens delivery 1? " + stranger.open(deliveries.get(1), u, v).isPresent()); + + // 6. A wallet scans many notes at once. `ownedByMe` is the wallet's own owner check + // (e.g. the datum's owner credential). An owned note that does not open is value the + // wallet cannot spend: report it, never drop it silently. + NoteOpening other = NoteOpening.random(BigInteger.valueOf(99), random); + JubjubPoint c2 = other.commitment(); + byte[] badDelivery = ConfidentialNotes.seal(other, List.of(readers.get(1)), random).get(0); // not to the owner + NoteScanner.Scan scan = owner.scan(List.of( + Candidate.of(deliveries.get(0), u, v, true), + Candidate.of(badDelivery, c2.affineU(), c2.affineV(), true))); + System.out.println("Scan: opened " + scan.opened().size() + + ", owned but unopenable at indices " + scan.unopenableOwned()); + } +} +``` + +```text +Deliveries: 2 x 89 bytes +Owner reads amount: 250 +Auditor reads amount: 250 +Stranger opens delivery 0? false +Stranger opens delivery 1? false +Scan: opened 1, owned but unopenable at indices [1] +``` + +A few details: + +- **Readers are positional.** The application fixes the order (owner first, then auditors) and + each reader opens only the delivery at its own position. +- **Open with the datum's coordinates.** `open` and `Candidate.of` take the commitment's affine + `(u, v)` as `BigInteger`s, exactly as they appear in the note's datum. +- **`ownedByMe` is your check, not the library's.** The scanner can't know who owns a UTxO. Your + wallet decides that from the datum's owner credential and the script address before it scans. + +## Viewing keys + +- **Generate in the wallet.** `NoteViewingKey.generate(new SecureRandom())` creates the secret; publish + only `readerKey().encode()`, 32 bytes. +- **Back it up.** `exportSecret()` and `NoteViewingKey.restore(bytes)` move the key between devices. + Call `destroy()` when you're done with an in-memory copy. +- **Verify keys you receive from a registry.** `NoteReaderKey.decode(bytes)` checks that the bytes + are a valid key. When keys come from a public registry, use + `NoteReaderKey.verified(bytes, verifier)` with a **proof of possession**, so nobody can register + a key they don't control. The proof statement carries no context, so the registry itself must + bind each key to its registrant. +- **A viewing key is only a viewing key.** It can't spend, sign or decrypt ElGamal ciphertexts. An + auditor that also receives [ElGamal-encrypted amounts](/guides/confidential/elgamal/) has a + separate ElGamal key. +- **No forward secrecy.** A leaked viewing key reads every past delivery addressed to it. + +## What a delivery does and doesn't guarantee + +**A validator can only check the length.** Plutus has no Jubjub operations, so an on-chain +validator can require "an 89-byte delivery for each reader" but can't check that it decrypts. A +careless or hostile sender can fill a delivery with random bytes. The owner's wallet then finds a +note it owns but can't open. It must **report** that note as unopenable, never drop it silently, +because it's value the owner can't spend. + +**Delivery alone doesn't make the sender honest with the auditor.** The sender writes the +auditor's delivery too, and could put a different (valid-looking) opening there. When the auditor's +view must be *enforced*, add the amount a second time as ElGamal ciphertext to the auditor's +key, and prove inside the transfer's Groth16 proof that it matches the commitment. ADR-0055 calls +this **D3a**: + +- the amount is split into two 32-bit **limbs**, so the auditor can decrypt each one quickly; +- each limb is ElGamal-encrypted to the auditor's separate key; +- the transfer circuit proves `limb0 + 2³²·limb1` is the committed amount and that both + ciphertexts are correct. + +D3a is **not a library API**. It's a pattern, with a test-only reference validator +([`AuditedConfidentialNoteValidator`](https://github.com/bloxbean/zeroj/blob/main/zeroj-integration-tests/src/test/java/org/zeroj/examples/notes/onchain/AuditedConfidentialNoteValidator.java) +and [`AuditedConfidentialNoteOnChainTest`](https://github.com/bloxbean/zeroj/blob/main/zeroj-integration-tests/src/test/java/org/zeroj/examples/notes/AuditedConfidentialNoteOnChainTest.java)). +In ZeroJ's test validator, a two-output transfer with one auditor measured 34,184 constraints and +73.4% of the per-transaction step limit in the JuLC VM, before the verifier savings in ZeroJ PRs +#85 and #86. A real ledger script does more work: the points demo's transfer, on the same circuit, +used 75.8% on Yaci DevKit. It covers only notes created by +proof-checked transitions such as transfers. Newly **issued** notes carry whatever audit data the +issuer supplied, unless issuance is proved too, as in +[confidential payroll](/use-cases/confidential-payroll/). + +## Wallet rules + +- **Open only your own position**, and only notes your owner check selected. +- **Check the owner credential and the script address yourself**, so a copied note can't pass as + one of yours. +- **Report unopenable owned notes**; never drop them. +- **Scan only in the user's own wallet process**, never as a shared or network service: a scanner + holds the viewing key and learns every amount. +- **Run sealing and opening offline or isolated.** They use variable-time arithmetic on secrets. + +## Assumptions in plain words + +The construction reuses Sapling's components, but ZeroJ's use of them has not been externally +reviewed. Three assumptions carry the security, and all three are open: + +- **A1, confidentiality.** A delivery reveals nothing about the amount to anyone without the + reader's viewing key. +- **A2, integrity.** An opening a reader accepts really opens the note's commitment, and a sender + can't make two readers accept different openings of the same note. This rests on the + commitment being binding. +- **A3, no useful multi-key partitioning.** A delivery is accepted under at most one reader key, + whatever its contents, except with negligible probability. ChaCha20-Poly1305 isn't + key-committing, so this doesn't follow from the cipher alone. If two keys accepted different + openings, A2 would be broken; the case where two keys accept the *same* opening rests on ZeroJ's + own argument about the key derivation. A3 is unproved, and that argument hasn't been reviewed. + +## Sizes and timings + +| Item | Value | Source | +|---|---|---| +| Delivery | 89 bytes per reader (32-byte `E` + 57-byte ciphertext) | spec | +| Reader key | 32 bytes | spec | +| Extra minimum ADA, owner + one auditor | about 0.8 ADA (estimate) | ADR-0055 | +| Seal for 2 readers | about 5.6 ms | [benchmark](https://github.com/bloxbean/zeroj/blob/main/docs/benchmarks/confidential-note-jubjub-2026-10-09.md) | +| Accept a delivery (decrypt + recompute C) | about 5 ms | benchmark | +| Reject a delivery that isn't yours | about 1.7 ms | benchmark | +| Scan, one thread, every delivery rejected | about 660 deliveries per second (accepting one costs more; threads scale sublinearly) | benchmark | + +Timings are from one Apple M4 Max laptop and are only a rough guide. + +## Next steps + +- Use cases: [Confidential loyalty points](/use-cases/confidential-points/), + [Confidential payroll](/use-cases/confidential-payroll/), + [Proof of solvency with hidden balances](/use-cases/private-solvency/) +- [Share a value with chosen readers](/selective-disclosure/share-with-chosen-readers/): when to use notes +- [ElGamal encryption](/guides/confidential/elgamal/) and [Pedersen commitments](/guides/confidential/pedersen/) diff --git a/www/src/content/docs/guides/confidential/elgamal.mdx b/www/src/content/docs/guides/confidential/elgamal.mdx new file mode 100644 index 00000000..c4dd1001 --- /dev/null +++ b/www/src/content/docs/guides/confidential/elgamal.mdx @@ -0,0 +1,433 @@ +--- +title: ElGamal encryption +description: Encrypt small amounts to someone's public key, add ciphertexts without decrypting them, and prove in a Groth16 circuit what a ciphertext contains, with ZeroJ's elgamal-jubjub-v1 profile. +sidebar: + order: 2 +--- + +import SinceNotice from '../../../../components/SinceNotice.astro'; +import EncryptionExplainer from '../../../../components/walkthrough/EncryptionExplainer.astro'; + +A [Pedersen commitment](/guides/confidential/pedersen/) can only be opened by someone who knows +its opening. **Encryption** solves a different problem: a value that a named party, such as an +auditor, an auctioneer or a group of election trustees, must be able to read later **without +the sender's help**. + +Think of a lockbox with a slot. Anyone can drop a value in using the public key; only the holder +of the secret key can open it. ZeroJ uses **exponential ElGamal** on the Jubjub curve, which adds +one more property: ciphertexts under the same key **add up**. A ledger can keep an encrypted +running total, and the key holder decrypts only the total. + +The trade-off is that decryption ends in a search, so it only works for **small numbers**: votes, +counters, or a large amount split into 32-bit pieces called **limbs**. The profile is +[`elgamal-jubjub-v1`](https://github.com/bloxbean/zeroj/blob/main/docs/specs/elgamal-jubjub-v1.md), +designed in [ADR-0052](https://github.com/bloxbean/zeroj/blob/main/docs/adr/0052-exponential-elgamal-jubjub.md). + + + + + +## Status + +| Area | Status | +|---|---| +| Host API: keys, encryption, homomorphic addition, decryption (`ElGamal`, `ElGamalCiphertext`, key contexts) | **Experimental**, pending review and external review | +| In-circuit encryption and DLEQ proofs (`ZkElGamal`, `ZkElGamalPublicKey`) | **Experimental**, pending review and external review | +| Secret operations (encrypting, decryption shares, decrypting) | **Offline/isolated only**: variable-time arithmetic, no constant-time claim | + +"Offline/isolated only" means: run code that touches secret keys or plaintexts on the user's own +device or in a separate process, never in a shared service an attacker can time. See +[Status & maturity](/start/status/). + +## Add the dependency + +The host API is in `zeroj-circuit-lib`: + +```groovy title="build.gradle" +dependencies { + implementation platform('org.zeroj:zeroj-bom-core:') + implementation 'org.zeroj:zeroj-circuit-lib' // ElGamal, ElGamalCiphertext, JubjubDiscreteLog, ... +} +``` + +Example 4 below also proves a circuit, so it needs the annotation, crypto, codec and verifier +modules listed in the [Pedersen guide](/guides/confidential/pedersen/#add-the-dependency). Use a +`0.1.0-pre13` snapshot for `` until the release is out. + +## 1. Encrypt, add, decrypt + +```java title="ElGamalBasics.java" +import org.zeroj.circuit.lib.jubjub.ElGamal; +import org.zeroj.circuit.lib.jubjub.ElGamalCiphertext; +import org.zeroj.circuit.lib.jubjub.ElGamalSecretKey; +import org.zeroj.circuit.lib.jubjub.JubjubDiscreteLog; +import org.zeroj.circuit.lib.jubjub.NOfNKeyContext; +import org.zeroj.circuit.lib.jubjub.RawElGamalCiphertext; + +import java.security.SecureRandom; + +/** Exponential ElGamal on Jubjub: encrypt two amounts, add the ciphertexts, decrypt only the sum. */ +public class ElGamalBasics { + + public static void main(String[] args) { + SecureRandom random = new SecureRandom(); + + // 1. A key pair. The context is "the key a ciphertext belongs to"; n-of-n with n = 1 here. + ElGamalSecretKey secretKey = ElGamalSecretKey.generate(random); + NOfNKeyContext key = NOfNKeyContext.singleKey(secretKey); + + // 2. Encrypt two amounts. The width (16 bits here) is a promise: 0 <= m < 2^16. + int width = 16; + ElGamalCiphertext a = ElGamal.encrypt(key, 1200, width, random); + ElGamalCiphertext b = ElGamal.encrypt(key, 345, width, random); + System.out.println("Ciphertext size: " + a.encode().length + " bytes"); + System.out.println("Bound of each ciphertext: " + a.bound()); + + // 3. Add without decrypting. The library tracks the bound of the sum. + ElGamalCiphertext sum = a.add(b); + System.out.println("Bound of the sum: " + sum.bound()); + + // 4. Decrypt the sum: a bounded discrete-log search over [0, bound]. + // Build the search table once and reuse it for many decryptions. + long maxPlaintext = sum.bound().longValueExact(); + JubjubDiscreteLog table = JubjubDiscreteLog.forBound(maxPlaintext); + long total = ElGamal.decryptWithSecret(sum, secretKey, maxPlaintext, table); + System.out.println("Decrypted sum: " + total); + + // What the safe API refuses: + try { + ElGamal.decryptWithSecret(sum, secretKey, 1000); // search limit below the bound + } catch (IllegalArgumentException e) { + System.out.println("Refused: " + e.getMessage()); + } + try { + ElGamalSecretKey other = ElGamalSecretKey.generate(random); + a.add(ElGamal.encrypt(NOfNKeyContext.singleKey(other), 1, 1, random)); // different keys + } catch (IllegalArgumentException e) { + System.out.println("Refused: " + e.getMessage()); + } + try { + ElGamal.encrypt(key, 70_000, width, random); // does not fit in 16 bits + } catch (IllegalArgumentException e) { + System.out.println("Refused: " + e.getMessage()); + } + + // Bytes carry no key and no bound: decoding gives a *raw* ciphertext, which has no + // decrypt method. It re-enters the safe layer only through ElGamal.admit(...) with a + // verifier that checks an encryption proof. + RawElGamalCiphertext raw = RawElGamalCiphertext.decode(sum.encode()); + System.out.println("Decoded from bytes: " + raw.getClass().getSimpleName()); + } +} +``` + +```text +Ciphertext size: 64 bytes +Bound of each ciphertext: 65535 +Bound of the sum: 131070 +Decrypted sum: 1545 +Refused: the ciphertext's plaintext bound 131070 exceeds the search limit 1000 +Refused: ciphertexts are under different key contexts; homomorphic operations need one key +Refused: message must satisfy 0 <= m < 2^16 +Decoded from bytes: RawElGamalCiphertext +``` + +What to notice: + +- **Every encryption carries a width.** `encrypt(key, 1200, 16, random)` promises that the + message fits in 16 bits. The ciphertext remembers the largest value it can hold, its **bound** + (65,535 here), and adding two ciphertexts adds their bounds. +- **Decryption is a search** over `[0, bound]`. `JubjubDiscreteLog.forBound(...)` builds a lookup + table once; reuse it for many decryptions. +- **The safe API refuses mistakes** instead of returning a wrong answer: a search limit below the + bound, ciphertexts under different keys, a message that doesn't fit its width. +- **Bytes carry no key and no bound.** `RawElGamalCiphertext.decode` gives you a *raw* ciphertext, + which has no decrypt method. Section 3 shows how it gets back in. + +## 2. Encrypt to someone else's key + +In example 1 one process owns the key, so `NOfNKeyContext.singleKey(secretKey)` is fine. A real +sender only has the recipient's **published** key, and must check a **possession proof** before +using it: a zero-knowledge proof (a DLEQ proof) that whoever published the key knows its secret. + +Why bother? Without it, an attacker can publish a "rogue" key crafted from other people's keys, +so that a combined key ends up decryptable by the attacker alone. ZeroJ makes the check part of +the type system: the only way from bytes to a usable key goes through `VerifiedKeyShare.verify`, +which hands your verifier the exact statement to check. + +```java title="Admit a published key (shape)" +import org.zeroj.circuit.lib.jubjub.DleqStatement; +import org.zeroj.circuit.lib.jubjub.ElGamalPublicKey; +import org.zeroj.circuit.lib.jubjub.NOfNKeyContext; +import org.zeroj.circuit.lib.jubjub.VerifiedKeyShare; + +import java.util.List; + +// keyBytes and proof come from the auditor's registry entry (or a trustee's announcement). +VerifiedKeyShare share = VerifiedKeyShare.verify(keyBytes, statement -> + statement.kind() == DleqStatement.Kind.POSSESSION + && verifyDleqProof(proof, statement.publicInputs())); // YOUR Groth16 check +NOfNKeyContext auditor = ElGamalPublicKey.aggregate(List.of(share)); + +// Several key holders (n-of-n): aggregate all their verified shares into one joint key. +// NOfNKeyContext trustees = ElGamalPublicKey.aggregate(List.of(share1, share2, share3)); +``` + +`verifyDleqProof` stands for your own Groth16 verification of the possession proof, over a DLEQ +circuit built with `ZkElGamal.assertDiscreteLogEquality`. The full proven flow (possession +proofs, joint key, proved ballots, proved decryption shares, tally) is the `endToEnd` test in +[`AnnotatedElGamalTest`](https://github.com/bloxbean/zeroj/blob/main/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation/AnnotatedElGamalTest.java). + +:::danger[A verifier that returns `true` disables the check] +Every `...Verifier` lambda is a promise that *you* checked a proof. `s -> true` compiles, runs and +silently turns off the protection. +::: + +## 3. Receive ciphertexts: admit them with a proof + +A ciphertext you receive could encrypt anything: a negative number, a huge number, a value under +the wrong key. Adding it to your total would corrupt the total. So received bytes start as a +`RawElGamalCiphertext`, and become a usable `ElGamalCiphertext` only through `ElGamal.admit`: + +```java title="Admit a received ciphertext" +import org.zeroj.circuit.lib.jubjub.ElGamal; +import org.zeroj.circuit.lib.jubjub.ElGamalCiphertext; +import org.zeroj.circuit.lib.jubjub.RawElGamalCiphertext; + +RawElGamalCiphertext raw = RawElGamalCiphertext.decode(ciphertextBytes); // 64 bytes +ElGamalCiphertext ballot = ElGamal.admit(raw, electionKey, 1, statement -> + statement.width() == 1 + && verifyEncryptionProof(proof, statement.publicInputs())); // YOUR Groth16 check +``` + +The statement's public inputs are exactly `PK.u, PK.v, A.u, A.v, B.u, B.v`: the key and the +ciphertext's two points. Your proof must be over those values and that width, for example a +circuit that calls `ZkElGamal.encrypt` and `assertAffineEquals`, as in example 4. + +When is `s -> true` acceptable? Only when something else already verified a proof for that exact +statement, for example a Cardano validator that refused the transaction unless the proof +verified. The [confidential points](/use-cases/confidential-points/) auditor does this for +ciphertexts it reads from validated ledger outputs, and says so in a comment. + +## 4. Prove what a ciphertext contains + +The most useful pattern combines a commitment and a ciphertext: "this ciphertext, encrypted to the +auditor, holds **the same amount** as this commitment". Then the auditor's copy can't be faked, +even by the sender. This circuit is a minimal illustration of that idea for one 32-bit amount; it +is not the reference circuit ZeroJ measured on-chain. + +```java title="AuditedAmount.java" +import org.zeroj.circuit.annotation.Prove; +import org.zeroj.circuit.annotation.Public; +import org.zeroj.circuit.annotation.Secret; +import org.zeroj.circuit.annotation.UInt; +import org.zeroj.circuit.annotation.ZKCircuit; +import org.zeroj.circuit.annotation.ZkContext; +import org.zeroj.circuit.annotation.ZkField; +import org.zeroj.circuit.annotation.ZkUInt; +import org.zeroj.circuit.lib.zk.ZkElGamal; +import org.zeroj.circuit.lib.zk.ZkElGamalPublicKey; +import org.zeroj.circuit.lib.zk.ZkPedersenCommitment; + +/** + * "The public ElGamal ciphertext encrypts, under the auditor's key, the same amount the public + * Pedersen commitment hides." One secret amount feeds both relations. + */ +@ZKCircuit(name = "audited-amount", version = 1) +public class AuditedAmount { + @Prove + void prove(ZkContext zk, + @Public ZkField commitU, @Public ZkField commitV, + @Public ZkField auditorU, @Public ZkField auditorV, + @Public ZkField handleU, @Public ZkField handleV, + @Public ZkField blindedU, @Public ZkField blindedV, + @Secret @UInt(bits = 32) ZkUInt amount, + @Secret @UInt(bits = 252) ZkUInt blinding, + @Secret @UInt(bits = 252) ZkUInt randomness) { + ZkPedersenCommitment.commit(zk, amount, blinding).assertAffineEquals(zk, commitU, commitV); + var auditor = ZkElGamalPublicKey.fromVerifierFixedPublic(zk, auditorU, auditorV); + ZkElGamal.encrypt(zk, amount, randomness, auditor) + .assertAffineEquals(zk, handleU, handleV, blindedU, blindedV); + } +} +``` + +The program commits to 250, encrypts 250 to the auditor, proves the circuit, lets the auditor admit +and decrypt the ciphertext, then plays a cheating sender who encrypts 1 instead. Run it with +`-Dzeroj.allowInsecureTrustedSetup=true` (development setup): + +```java title="AuditedAmountMain.java" +import org.zeroj.api.CurveId; +import org.zeroj.api.ProofSystemId; +import org.zeroj.api.VerificationMaterial; +import org.zeroj.circuit.lib.jubjub.ElGamal; +import org.zeroj.circuit.lib.jubjub.ElGamalCiphertext; +import org.zeroj.circuit.lib.jubjub.ElGamalEncryption; +import org.zeroj.circuit.lib.jubjub.ElGamalSecretKey; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.NOfNKeyContext; +import org.zeroj.circuit.lib.jubjub.NoteOpening; +import org.zeroj.circuit.lib.jubjub.RawElGamalCiphertext; +import org.zeroj.codec.SnarkjsJsonCodec; +import org.zeroj.crypto.groth16.Groth16Keys; +import org.zeroj.crypto.setup.PowersOfTauBLS381; +import org.zeroj.crypto.snarkjs.SnarkjsGroth16Json; +import org.zeroj.verifier.groth16.bls12381.Groth16BLS12381PureJavaVerifier; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; + +public class AuditedAmountMain { + + public static void main(String[] args) { + SecureRandom random = new SecureRandom(); + var circuit = AuditedAmountCircuit.build(); + var r1cs = circuit.compileR1CS(CurveId.BLS12_381); + System.out.println("Public inputs: " + AuditedAmountCircuit.schema().publicInputs().names()); + System.out.println("Constraints: " + r1cs.numConstraints()); + + // DEV-ONLY single-party setup. Production keys come from an MPC ceremony. + BigInteger tau = PowersOfTauBLS381.generate(6).tauScalar(); + Groth16Keys keys = Groth16Keys.setupInMemory(r1cs.constraints(), r1cs.numWires(), + r1cs.numPublicInputs(), tau); + String vkJson = SnarkjsGroth16Json.verificationKeyJson(keys); + + // The auditor's ElGamal key (a separate key from any note viewing key). + // Demo shortcut: one process plays both parties. A real sender builds this context from + // the auditor's published key and possession proof: + // ElGamalPublicKey.aggregate(List.of(VerifiedKeyShare.verify(keyBytes, proofVerifier))) + ElGamalSecretKey auditorSecret = ElGamalSecretKey.generate(random); + NOfNKeyContext auditor = NOfNKeyContext.singleKey(auditorSecret); + + // Sender: commit to 250 and encrypt the same 250 to the auditor, then prove it. + long amount = 250; + NoteOpening opening = NoteOpening.random(BigInteger.valueOf(amount), random); + JubjubPoint c = opening.commitment(); + ElGamalEncryption enc = ElGamal.encryptWithOpening(auditor, BigInteger.valueOf(amount), 32, random); + List keyAndCiphertext = enc.statement().publicInputs(); // PK.u, PK.v, A.u, A.v, B.u, B.v + var inputs = AuditedAmountCircuit.inputs() + .commitU(c.affineU()).commitV(c.affineV()) + .auditorU(keyAndCiphertext.get(0)).auditorV(keyAndCiphertext.get(1)) + .handleU(keyAndCiphertext.get(2)).handleV(keyAndCiphertext.get(3)) + .blindedU(keyAndCiphertext.get(4)).blindedV(keyAndCiphertext.get(5)) + .amount(amount).blinding(opening.blinding()).randomness(enc.randomness()); + String proofJson = SnarkjsGroth16Json.proofJson( + keys.prove(inputs.calculateWitness(circuit, CurveId.BLS12_381), r1cs.constraints())); + byte[] ciphertextBytes = enc.ciphertext().encode(); // what goes on chain, 64 bytes + + // Auditor: admit the ciphertext only if the proof verifies for exactly + // (this commitment, my key, this ciphertext, width 32), then decrypt it. + RawElGamalCiphertext raw = RawElGamalCiphertext.decode(ciphertextBytes); + ElGamalCiphertext admitted = ElGamal.admit(raw, auditor, 32, statement -> { + List pub = new ArrayList<>(List.of(c.affineU(), c.affineV())); + pub.addAll(statement.publicInputs()); + return statement.width() == 32 && verify(vkJson, proofJson, pub); + }); + System.out.println("Auditor decrypts: " + ElGamal.decryptWithSecret(admitted, auditorSecret, (1L << 32) - 1)); + + // A cheating sender: commitment hides 250, ciphertext encrypts 1. No witness exists. + ElGamalEncryption lie = ElGamal.encryptWithOpening(auditor, BigInteger.ONE, 32, random); + List liePub = lie.statement().publicInputs(); + try { + inputs.handleU(liePub.get(2)).handleV(liePub.get(3)).blindedU(liePub.get(4)).blindedV(liePub.get(5)) + .randomness(lie.randomness()).calculateWitness(circuit, CurveId.BLS12_381); + System.out.println("Cheating witness accepted?!"); + } catch (ArithmeticException e) { + System.out.println("Cheating sender: witness rejected (" + e.getMessage() + ")"); + } + } + + static boolean verify(String vkJson, String proofJson, List publicInputs) { + var circuitId = AuditedAmountCircuit.circuitId(); + String publicJson = SnarkjsGroth16Json.publicJson(publicInputs.toArray(BigInteger[]::new)); + var envelope = SnarkjsJsonCodec.toEnvelopeFromJson(proofJson, vkJson, publicJson, circuitId); + var material = VerificationMaterial.of(vkJson.getBytes(StandardCharsets.UTF_8), + ProofSystemId.GROTH16, CurveId.BLS12_381, circuitId); + return new Groth16BLS12381PureJavaVerifier().verify(envelope, material).proofValid(); + } +} +``` + +```text +Public inputs: [commitU, commitV, auditorU, auditorV, handleU, handleV, blindedU, blindedV] +Constraints: 8893 +Auditor decrypts: 250 +Cheating sender: witness rejected (Constraint violation: w30527=2541…7612 != w30513=1358…0935) +``` + +The cheating sender can't even produce a witness: no secret amount makes both the commitment and +the ciphertext check out. The circuit has 8,893 constraints. Production applications split a +64-bit amount into two 32-bit limbs and encrypt each, so the auditor can decrypt it; the +[confidential payroll](/use-cases/confidential-payroll/) and +[confidential points](/use-cases/confidential-points/) demos do exactly that, inside their +transfer and issue proofs. + +## Bounds and decryption cost + +Decryption recovers `m·G` and then searches for `m`. How far it can search decides what you can +encrypt: + +- **Widths are 1 to 64 bits**, and a message must satisfy `0 ≤ m < 2^width`. +- **Bounds add up.** A sum of 1,000 ciphertexts of width 16 has a bound of about 65 million, even + if the real total is small. Use the narrowest width that fits. +- **`maxPlaintext` must be at least the bound**, not just the value you expect, or `decrypt` + refuses. If no value in range matches, it throws `ElGamalDecryptionException` instead of + guessing. +- **The default table reaches about 2⁴³.** A width-64 ciphertext can be admitted and added, but + not decrypted. Split amounts into 32-bit limbs. + +| Operation (Apple M4 Max) | Time | +|---|---| +| Encrypt | 4.7 ms | +| Decryption share | 1.65 ms | +| Decode a ciphertext | 0.22 ms | +| Add, per ciphertext | 1.6 µs | +| Discrete log up to 2³²: build table / solve | 21 ms / 7–19 ms | +| Discrete log up to 2⁴⁰: build table / solve | 108 ms / 0.55–0.9 s | + +Source: [ElGamal benchmark](https://github.com/bloxbean/zeroj/blob/main/docs/benchmarks/elgamal-jubjub-2026-10-05.md). +These are measurements on one machine, not performance claims. + +## Rules to follow + +- **Verify every key you didn't make** with `VerifiedKeyShare.verify` and a real possession-proof + check. +- **Admit every ciphertext you didn't make** with `ElGamal.admit` and a real encryption-proof + check, for exactly that key and width. +- **Verify every decryption share you didn't make** with `VerifiedDecryptionShare.verify` and a + DLEQ proof. An unchecked share lets a key holder choose the result. +- **Keep widths small** and decrypt only bounded values. +- **Run secret operations offline or isolated.** Encrypting, decryption shares and decrypting + handle secrets with variable-time code. +- **The key holder can read everything encrypted to them.** If that's too much trust in one + party, split the key: see [Threshold decryption](/guides/confidential/threshold-elgamal/). +- **Fixed randomness is test-only.** Never pass your own encryption randomness; the API draws it + from `SecureRandom`. +- **A proof is not a permission.** Binding ciphertexts to transactions, replay and authorization + are application rules. See [Application security](/guides/verifying/application-security/). + +## Cost + +| Circuit | Constraints | +|---|---| +| Encrypt to a fixed public key, width 1 / 16 / 64 | 6,558 / 6,650 / 6,938 | +| Encrypt to a key witnessed in the circuit | 12,105 | +| DLEQ (possession or decryption-share proof) | 6,546 | +| Commitment + ciphertext of the same 32-bit amount (example 4) | 8,893 | + +A 64-byte ciphertext is two curve points. On Cardano, its four coordinates are public inputs of +an ordinary Groth16 proof; see [Verify proofs on Cardano](/guides/verifying/on-chain/). + +## Next steps + +- [Threshold decryption](/guides/confidential/threshold-elgamal/): split the key among trustees +- [Confidential notes](/guides/confidential/confidential-notes/): deliver commitment openings + on-chain +- [Encrypt for an auditor](/selective-disclosure/encrypt-for-an-auditor/): the pattern, with use + cases +- Use cases: [Sealed-bid auction](/use-cases/sealed-bid-auction/), + [Confidential payroll](/use-cases/confidential-payroll/), + [Private voting](/use-cases/private-voting/) diff --git a/www/src/content/docs/guides/confidential/pedersen.mdx b/www/src/content/docs/guides/confidential/pedersen.mdx new file mode 100644 index 00000000..e69d82b6 --- /dev/null +++ b/www/src/content/docs/guides/confidential/pedersen.mdx @@ -0,0 +1,457 @@ +--- +title: Pedersen commitments +description: Commit to a hidden number, open it later, add commitments together, and prove facts about the hidden value in a Groth16 circuit, with ZeroJ's pedersen-jubjub-v1 profile. +sidebar: + order: 1 +--- + +import SinceNotice from '../../../../components/SinceNotice.astro'; +import CommitmentExplainer from '../../../../components/walkthrough/CommitmentExplainer.astro'; + +A **Pedersen commitment** is a sealed envelope for a number. You publish the envelope, a 32-byte +curve point, and keep the number and a random **blinding** value to yourself. Later you can open +it to someone you choose, or prove facts about the number while it stays sealed: "at least 500", +"these inputs equal these outputs", "this total is covered by our reserves". + +ZeroJ implements commitments on the Jubjub curve, whose arithmetic is cheap inside BLS12-381 +circuits, so a Groth16 proof about a committed value costs a few thousand constraints. The +profile is [`pedersen-jubjub-v1`](https://github.com/bloxbean/zeroj/blob/main/docs/specs/pedersen-jubjub-v1.md), +designed in [ADR-0051](https://github.com/bloxbean/zeroj/blob/main/docs/adr/0051-pedersen-commitment-profiles.md). + +New to commitments? Read [Commitments & encryption, explained](/learn/commitments-and-encryption/) +first. Not sure a commitment is what you need? [Choose how to disclose](/selective-disclosure/) +compares it with BBS, predicates, encrypted deliveries and threshold decryption. + + + + + +## Status + +| Area | Status | +|---|---| +| In-circuit commitment (`ZkPedersen`, `ZkPedersenCommitment`) | **Ready on BLS12-381 Groth16, pending external review** | +| In-circuit homomorphic API (`ZkPedersen.assertBalanced`, `ZkPedersenCommitment.add`/`subtract`, subgroup checks) | **Experimental**, pending review and external review | +| Vector commitments (`ZkPedersenVector`, `PedersenVectorCommitment`) | **Experimental**, pending spec and external review | +| Creating commitments off-circuit (`PedersenCommitment.commit`, `randomBlinding`) | **Offline/isolated only**: variable-time arithmetic on secrets | +| Verifying a disclosed opening (`PedersenCommitment.verify`, `decode`) | Fine anywhere: the opening is no longer secret to that verifier | + +"Offline/isolated only" restricts *where* you run the secret-handling code: on the user's device or +in a separate process, never in a service an attacker can time. It doesn't weaken the commitment's +hiding or binding. + +## Add the dependency + +Every Pedersen class is in `zeroj-circuit-lib`. Add it next to the modules from the +[quickstart](/start/quickstart/): + +```groovy title="build.gradle" +dependencies { + implementation platform('org.zeroj:zeroj-bom-core:') + annotationProcessor platform('org.zeroj:zeroj-bom-core:') + + implementation 'org.zeroj:zeroj-circuit-annotation-api' + annotationProcessor 'org.zeroj:zeroj-circuit-annotation-processor' + implementation 'org.zeroj:zeroj-circuit-dsl' + implementation 'org.zeroj:zeroj-circuit-lib' // PedersenCommitment, ZkPedersen, ... + implementation 'org.zeroj:zeroj-crypto' + implementation 'org.zeroj:zeroj-codec' + implementation 'org.zeroj:zeroj-verifier-groth16' +} +``` + +Use a `0.1.0-pre13` snapshot for `` until the release is out (see the note above). + +## 1. Commit and open + +```java title="CommitAndOpen.java" +import org.zeroj.circuit.lib.jubjub.JubjubCurve; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.PedersenCommitment; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.HexFormat; + +public class CommitAndOpen { + + public static void main(String[] args) { + // --- Committer (offline) --- + BigInteger value = BigInteger.valueOf(1_000); // the secret + BigInteger blinding = PedersenCommitment.randomBlinding(new SecureRandom()); // fresh, never reused + + JubjubPoint commitment = PedersenCommitment.commit(value, blinding); + byte[] published = commitment.toBytes(); // 32 bytes + System.out.println("Commitment (32 bytes): " + HexFormat.of().formatHex(published)); + + // --- Verifier, later: receives the bytes, then the opening (value, blinding) --- + // decode() rejects non-canonical encodings and points outside the prime-order subgroup. + JubjubPoint received = PedersenCommitment.decode(published); + + System.out.println("Opens to (1000, r)? " + PedersenCommitment.verify(received, value, blinding)); + System.out.println("Opens to (1001, r)? " + + PedersenCommitment.verify(received, BigInteger.valueOf(1_001), blinding)); + System.out.println("Opens to (1000, r+1)? " + + PedersenCommitment.verify(received, value, blinding.add(BigInteger.ONE))); + + // (0, -1) is on the curve but has order 2: never a valid commitment. + BigInteger minusOne = JubjubCurve.BASE_FIELD_PRIME.subtract(BigInteger.ONE); + byte[] lowOrder = JubjubPoint.fromAffine(BigInteger.ZERO, minusOne).toBytes(); + try { + PedersenCommitment.decode(lowOrder); + } catch (IllegalArgumentException e) { + System.out.println("Low-order point rejected: " + e.getMessage()); + } + } +} +``` + +```text +Commitment (32 bytes): dd6ad5a52e940bdf5754476f42d1bab89df3391c1282fc26d37ca553d4f21291 +Opens to (1000, r)? true +Opens to (1001, r)? false +Opens to (1000, r+1)? false +Low-order point rejected: Pedersen commitment is not in the prime-order subgroup +``` + +The commitment bytes change on every run because the blinding is random. That's the point: +committing to 1,000 twice gives two unrelated envelopes. + +:::caution[Decode received commitments with `PedersenCommitment.decode`] +`JubjubPoint.fromBytes` only checks that the bytes are a point on the curve. It does **not** check +the prime-order subgroup that commitments live in. Use `PedersenCommitment.decode` for any +commitment you receive. +::: + +## 2. Add commitments + +Anyone can add two commitments: `C(30, r1) + C(12, r2) = C(42, r1 + r2)`. There's no +`PedersenCommitment.add`; you add the points with `JubjubPoint.add`. + +```java title="Homomorphic.java" +import org.zeroj.circuit.lib.jubjub.JubjubCurve; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.PedersenCommitment; + +import java.math.BigInteger; +import java.security.SecureRandom; + +public class Homomorphic { + + public static void main(String[] args) { + SecureRandom random = new SecureRandom(); + BigInteger v1 = BigInteger.valueOf(30), r1 = PedersenCommitment.randomBlinding(random); + BigInteger v2 = BigInteger.valueOf(12), r2 = PedersenCommitment.randomBlinding(random); + + JubjubPoint c1 = PedersenCommitment.commit(v1, r1); + JubjubPoint c2 = PedersenCommitment.commit(v2, r2); + + JubjubPoint sum = c1.add(c2); + System.out.println("Sum opens to (42, r1 + r2)? " + + PedersenCommitment.verify(sum, BigInteger.valueOf(42), r1.add(r2))); + + // The arithmetic is modulo the group order l, not over the integers. + BigInteger l = JubjubCurve.SUBGROUP_ORDER; + JubjubPoint wrapped = PedersenCommitment.commit(l.subtract(BigInteger.ONE), r1) + .add(PedersenCommitment.commit(BigInteger.ONE, r2)); + System.out.println("C(l-1, r1) + C(1, r2) opens to (0, r1 + r2)? " + + PedersenCommitment.verify(wrapped, BigInteger.ZERO, r1.add(r2))); + } +} +``` + +```text +Sum opens to (42, r1 + r2)? true +C(l-1, r1) + C(1, r2) opens to (0, r1 + r2)? true +``` + +The second line is the most important thing on this page. Commitment arithmetic **wraps around** +at a 252-bit number `l`. A huge "value" plus 1 can look like 0, so a cheat could hide a negative +amount inside a sum. A sum of commitments proves nothing about real-world totals unless every +value is range-bounded. That's what the circuit gadgets below do for you. + +## 3. Prove a fact without opening + +This circuit proves "the value inside this public commitment is at least the public threshold". +The commitment enters as two public inputs, its affine coordinates `(u, v)`. + +```java title="CommittedThreshold.java" +import org.zeroj.circuit.annotation.Prove; +import org.zeroj.circuit.annotation.Public; +import org.zeroj.circuit.annotation.Secret; +import org.zeroj.circuit.annotation.UInt; +import org.zeroj.circuit.annotation.ZKCircuit; +import org.zeroj.circuit.annotation.ZkBool; +import org.zeroj.circuit.annotation.ZkContext; +import org.zeroj.circuit.annotation.ZkField; +import org.zeroj.circuit.annotation.ZkUInt; +import org.zeroj.circuit.lib.zk.ZkPedersen; + +@ZKCircuit(name = "committed-threshold", version = 1) +public class CommittedThreshold { + @Prove + ZkBool prove(ZkContext zk, + @Public ZkField commitmentU, // the commitment, as affine (u, v) + @Public ZkField commitmentV, + @Public @UInt(bits = 64) ZkUInt threshold, + @Secret @UInt(bits = 64) ZkUInt value, // never revealed + @Secret @UInt(bits = 252) ZkUInt blinding) { // must be exactly 252 bits + // 1. Recompute C = [value]G + [blinding]H and pin it to the public (u, v). + ZkPedersen.commit(zk, value, blinding).assertAffineEquals(zk, commitmentU, commitmentV); + // 2. The statement about the hidden value. + return value.gte(threshold); + } +} +``` + +The program below commits to 1,000, proves "at least 500", and plays the verifier. It uses a +**development-only** setup, as the quickstart does, so run it with +`-Dzeroj.allowInsecureTrustedSetup=true`. + +```java title="ThresholdProof.java" +import org.zeroj.api.CircuitId; +import org.zeroj.api.CurveId; +import org.zeroj.api.ProofSystemId; +import org.zeroj.api.PublicInputs; +import org.zeroj.api.VerificationMaterial; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.PedersenCommitment; +import org.zeroj.codec.SnarkjsJsonCodec; +import org.zeroj.crypto.groth16.Groth16Keys; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; +import org.zeroj.crypto.setup.PowersOfTauBLS381; +import org.zeroj.crypto.snarkjs.SnarkjsGroth16Json; +import org.zeroj.verifier.groth16.bls12381.Groth16BLS12381PureJavaVerifier; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; + +public class ThresholdProof { + + public static void main(String[] args) { + // 1. Committer (offline): commit to a balance and publish the 32-byte commitment. + BigInteger balance = BigInteger.valueOf(1_000); + BigInteger blinding = PedersenCommitment.randomBlinding(new SecureRandom()); + byte[] published = PedersenCommitment.commit(balance, blinding).toBytes(); + + // 2. Compile, then a DEV-ONLY trusted setup (this process knows tau). + var circuit = CommittedThresholdCircuit.build(); + var r1cs = circuit.compileR1CS(CurveId.BLS12_381); + BigInteger tau = PowersOfTauBLS381.generate(4).tauScalar(); // only tau is used + try (var keys = Groth16Keys.setupInMemory( + r1cs.constraints(), r1cs.numWires(), r1cs.numPublicInputs(), tau)) { + String vkJson = SnarkjsGroth16Json.verificationKeyJson(keys); + + // 3. Prover: knows (balance, blinding) and proves "balance >= 500". + JubjubPoint c = PedersenCommitment.decode(published); + var inputs = CommittedThresholdCircuit.inputs() + .commitmentU(c.affineU()) + .commitmentV(c.affineV()) + .threshold(500) + .value(balance) // secret + .blinding(blinding); // secret + BigInteger[] witness = inputs.calculateWitness(circuit, CurveId.BLS12_381); + Groth16ProofBLS381 proof = keys.prove(witness, r1cs.constraints()); + String proofJson = SnarkjsGroth16Json.proofJson(proof); + String publicJson = SnarkjsGroth16Json.publicJson(inputs.publicValues().toArray(new BigInteger[0])); + + // 4. Verifier: has the published commitment and its own threshold, never the balance. + System.out.println("Accepted (balance >= 500)? " + accept(vkJson, proofJson, publicJson, published, 500)); + System.out.println("Accepted as proof of >= 900? " + accept(vkJson, proofJson, publicJson, published, 900)); + + // 5. A false claim can't even produce a witness. + try { + inputs.threshold(2_000).calculateWitness(circuit, CurveId.BLS12_381); + } catch (ArithmeticException e) { + System.out.println("Witness for balance >= 2000 refused"); + } + } + } + + /** Rebuild the statement from data the verifier trusts, then check the proof. */ + static boolean accept(String vkJson, String proofJson, String publicJson, + byte[] publishedCommitment, long requiredThreshold) { + JubjubPoint c = PedersenCommitment.decode(publishedCommitment); + PublicInputs expected = CommittedThresholdCircuit.inputs() + .commitmentU(c.affineU()) + .commitmentV(c.affineV()) + .threshold(requiredThreshold) + .toPublicInputs(); + if (!expected.equals(SnarkjsJsonCodec.parsePublicInputs(publicJson))) { + return false; // the proof is about a different commitment or threshold + } + CircuitId id = CommittedThresholdCircuit.circuitId(); + var envelope = SnarkjsJsonCodec.toEnvelopeFromJson(proofJson, vkJson, publicJson, id); + var material = VerificationMaterial.of(vkJson.getBytes(StandardCharsets.UTF_8), + ProofSystemId.GROTH16, CurveId.BLS12_381, id); + return new Groth16BLS12381PureJavaVerifier().verify(envelope, material).proofValid(); + } +} +``` + +```text +Accepted (balance >= 500)? true +Accepted as proof of >= 900? false +Witness for balance >= 2000 refused +``` + +The circuit has 2,671 constraints. Two details carry the security: + +- **The verifier rebuilds the public inputs** from the commitment it already holds and the + threshold it requires. Comparing them with the proof's public inputs is what stops a prover + from submitting a valid proof about a *different* commitment or a lower threshold. +- **The blinding is declared `@Secret @UInt(bits = 252)`.** ZeroJ refuses to build a circuit + whose blinding is narrower, public or a constant: `CommittedThresholdCircuit.build()` throws + `IllegalArgumentException`. A 16-bit blinding could be brute-forced, which would reveal the + value. The guard can't tell whether *your* blinding is random, though, so always use + `randomBlinding(new SecureRandom())`. + +## 4. Prove that amounts balance + +To move value privately, prove that the hidden inputs equal the hidden outputs plus any public +fee. `ZkPedersen.assertBalanced` does this, and it refuses layouts that could wrap around `l`. + +```java title="ConfidentialTransfer.java" +import org.zeroj.circuit.annotation.Prove; +import org.zeroj.circuit.annotation.Public; +import org.zeroj.circuit.annotation.Secret; +import org.zeroj.circuit.annotation.UInt; +import org.zeroj.circuit.annotation.ZKCircuit; +import org.zeroj.circuit.annotation.ZkContext; +import org.zeroj.circuit.annotation.ZkField; +import org.zeroj.circuit.annotation.ZkUInt; +import org.zeroj.circuit.lib.zk.ZkPedersen; +import org.zeroj.circuit.lib.zk.ZkPedersenCommitment; + +import java.util.List; + +/** "The hidden input amount equals the hidden output amount plus the public fee." */ +@ZKCircuit(name = "confidential-transfer", version = 1) +public class ConfidentialTransfer { + @Prove + void prove(ZkContext zk, + @Public ZkField inU, @Public ZkField inV, // input commitment (u, v) + @Public ZkField outU, @Public ZkField outV, // output commitment (u, v) + @Public @UInt(bits = 32) ZkUInt fee, + @Secret @UInt(bits = 64) ZkUInt inAmount, + @Secret @UInt(bits = 252) ZkUInt inBlinding, + @Secret @UInt(bits = 64) ZkUInt outAmount, + @Secret @UInt(bits = 252) ZkUInt outBlinding) { + var in = ZkPedersenCommitment.commit(zk, inAmount, inBlinding); + var out = ZkPedersenCommitment.commit(zk, outAmount, outBlinding); + in.assertAffineEquals(zk, inU, inV); + out.assertAffineEquals(zk, outU, outV); + // in = out + fee over the integers. 64 + 32-bit terms can't reach l, so nothing wraps; + // assertBalanced checks that when the circuit is built. + ZkPedersen.assertBalanced(zk, + List.of(ZkPedersen.Term.of(in)), + List.of(ZkPedersen.Term.of(out), ZkPedersen.Term.amount(fee))); + } +} +``` + +Driven the same way as the threshold example (sending 5,000 as 4,750 plus a 250 fee), it gives: + +```text +Transfer accepted (fee 250)? true +Transfer accepted (fee 200)? false +Unbalanced witness refused: Constraint violation: inAmount(w6)=5000 != w17753=5001 +Wrapping layout refused: the left side of this balance can reach 1fff…fffe (hex), which is not below +the subgroup order l. A relation mod l would not imply integer conservation; narrow the declared +widths or coefficients (ADR-0051 D3a). +``` + +The last line comes from a variant whose amounts are declared 252 bits wide. `build()` refuses it +before any proof exists. The rules `assertBalanced` enforces: + +- every term has a declared width, through `@UInt(bits = …)`; +- coefficients are positive constants (move a subtraction to the other side); +- the largest possible total on each side stays below `l`. + +The circuit has 4,886 constraints. The [confidential loyalty points](/use-cases/confidential-points/) +demo uses the same pattern for a 1-in, 2-out transfer. + +## 5. Commit to several values at once + +A **vector commitment** seals up to 16 values in one point, for example a credit profile of +income, score, birth year and country. A proof can then check a rule over some fields and keep all +of them hidden: + +```java title="CreditProfileCheck.java (core)" +import org.zeroj.circuit.lib.zk.ZkPedersenVector; + +// SCHEMA lists the fields and their widths: income/64, credit_score/16, birth_year/16, country/16. +var binding = ZkPedersenVector.bindSchema(zk, SCHEMA, schemaDigest); // schemaDigest is @Public +ZkPedersenVector.commit(zk, binding, List.of(income, creditScore, birthYear, country), blinding) + .assertAffineEquals(zk, u, v); +income.gte(minIncome).assertTrue(); +creditScore.gte(minScore).assertTrue(); +``` + +Vector commitments need two extra checks that single commitments don't: + +- **The point doesn't record its layout.** `C([a], r)` equals `C([a, 0], r)`, so every proof binds a + public **schema digest** with `bindSchema`, and the verifier checks it against a trusted + `PedersenSchemaRegistry`. +- **A commitment proves nothing about who issued it.** Accept a received commitment only with an + authenticated issuance record, and fail closed without one. + +The full worked example is `AnnotatedVectorCommitment` in +[`zeroj-integration-tests`](https://github.com/bloxbean/zeroj/tree/main/zeroj-integration-tests/src/test/java/org/zeroj/examples/annotation), +and the [credit gate](/selective-disclosure/prove-a-rule/#over-a-committed-credential) shows it on +Cardano. + +## Commitments you didn't make + +If your circuit receives a commitment whose opening it doesn't know, for example another party's +balance, there are three ways in. Pick by who checks the point: + +| Situation | API | Who checks the point | +|---|---|---| +| The circuit knows the opening | `ZkPedersenCommitment.commit(zk, value, blinding)` + `assertAffineEquals` | The circuit recomputes it | +| The opening is unknown, the point is a witness | `ZkPedersenCommitment.witnessInSubgroup(zk, u, v)` | The circuit (about 5,500 extra constraints) | +| The opening is unknown, the point is public | `ZkPedersenCommitment.fromVerifierCheckedPublic(zk, u, v)` | **Your verifier** must `PedersenCommitment.decode` it first | + +On Cardano, a validator can't run the Jubjub subgroup check, so on-chain consumers use the first +two rows. + +## Rules to follow + +- **Fresh random blinding, every time.** `PedersenCommitment.randomBlinding(new SecureRandom())`; + never reuse one, never derive it from public data. +- **Commit offline.** `commit` and `randomBlinding` use variable-time arithmetic on secrets. Run + them on the user's device or in an isolated process. +- **Decode with `PedersenCommitment.decode`**, never `JubjubPoint.fromBytes`, for received bytes. +- **Range-bound every value that means a number.** Commitments bind values *modulo* `l`: + `commit(v, r)` equals `commit(v + l, r)`. Integer meaning comes only from declared widths and + `assertBalanced`. Off-circuit point sums carry no such check. +- **Rebuild public inputs on the verifier side.** A commitment is two public inputs, `u` then `v`. +- **The identity point is a valid commitment** (to 0 with blinding 0). Check `isIdentity()` if + your application must exclude it. +- **A proof is not a permission.** Replay protection, nullifiers and binding to the spending + transaction are still your job. See [Application security](/guides/verifying/application-security/). + +## Cost + +| Circuit | Constraints | Source | +|---|---|---| +| Commitment with public `(u, v)`, 64-bit value | 2,410 | `zeroj-circuit-lib` README | +| Same, 252-bit value | 4,042 | `zeroj-circuit-lib` README | +| "At least a threshold" (example 3) | 2,671 | measured for this page | +| 1-in, 1-out transfer with a fee (example 4) | 4,886 | measured for this page | +| Vector commitment, 1 / 4 / 16 values | 2,411 / 3,581 / 8,261 | [vector benchmark](https://github.com/bloxbean/zeroj/blob/main/docs/benchmarks/pedersen-vector-2026-10-03.md) | + +Pure-Java proving for circuits this size took about 1.2 to 1.5 seconds per proof in the +[vector benchmark](https://github.com/bloxbean/zeroj/blob/main/docs/benchmarks/pedersen-vector-2026-10-03.md) +(2,400 to 8,300 constraints, one Apple M4 Max laptop), most of it fixed overhead. On Cardano, the proof is checked by ZeroJ's ordinary Groth16 verifier, and the +commitment is just two of its public inputs. See [Verify proofs on Cardano](/guides/verifying/on-chain/). + +## Next steps + +- [Confidential notes](/guides/confidential/confidential-notes/): deliver the opening on-chain to + the owner and an auditor +- [ElGamal encryption](/guides/confidential/elgamal/): encrypt an amount so an auditor can read it +- [Hide a number, prove facts about it](/selective-disclosure/hide-a-number/): the pattern, with use cases +- Use cases: [Proof of solvency with hidden balances](/use-cases/private-solvency/), + [Confidential loyalty points](/use-cases/confidential-points/) diff --git a/www/src/content/docs/guides/confidential/threshold-elgamal.mdx b/www/src/content/docs/guides/confidential/threshold-elgamal.mdx new file mode 100644 index 00000000..95d84b99 --- /dev/null +++ b/www/src/content/docs/guides/confidential/threshold-elgamal.mdx @@ -0,0 +1,412 @@ +--- +title: Threshold decryption +description: Split an ElGamal key among trustees so that no single party can decrypt, run the distributed key generation, deliver its private shares over a public board with HPKE, and decrypt only a total. +sidebar: + order: 3 +--- + +import SinceNotice from '../../../../components/SinceNotice.astro'; + +With [ElGamal encryption](/guides/confidential/elgamal/), whoever holds the secret key can read +every ciphertext. For an election, a sealed-bid market or a shared treasury, that's too much +trust in one party. **Threshold decryption** splits the key among `n` trustees so that: + +- any `t + 1` of them can decrypt together; +- any `t` or fewer learn nothing, even if they collude; +- the full secret key **never exists anywhere**, not even during setup. + +The trustees create the key together with a **distributed key generation** (DKG): each trustee +deals secret shares to the others and publishes commitments that let everyone check the shares, +so a cheating dealer is caught and excluded. Afterwards each trustee holds one share, and everyone +knows the joint public key that voters encrypt to. + +ZeroJ implements the New-DKG protocol of Gennaro, Jarecki, Krawczyk and Rabin +([J. Cryptology 2007](https://doi.org/10.1007/s00145-006-0347-3)) as the profile +[`elgamal-jubjub-threshold-v1`](https://github.com/bloxbean/zeroj/blob/main/docs/specs/elgamal-jubjub-threshold-v1.md) +([ADR-0053](https://github.com/bloxbean/zeroj/blob/main/docs/adr/0053-threshold-elgamal-jubjub-dkg.md)). +The private shares can travel over a public board, encrypted with HPKE (RFC 9180), following +[`dkg-share-delivery-hpke-v1`](https://github.com/bloxbean/zeroj/blob/main/docs/specs/dkg-share-delivery-hpke-v1.md) +([ADR-0054](https://github.com/bloxbean/zeroj/blob/main/docs/adr/0054-hpke-dkg-share-delivery.md)). + + + +## Status + +| Area | Status | +|---|---| +| Threshold key generation and decryption (`DkgParticipant`, `ThresholdKeyContext`, `ElGamal.decrypt` with shares) | **Experimental**, pending review and external review | +| Encrypted share delivery over a board (`DkgShareDelivery`, `DkgShareDeliveryKeys`, `DkgKeyDirectory`) | **Experimental**. Assumption A1 (HPKE envelopes can stand in for private channels) and the delivery contract await external review. | +| Secret operations (dealing, decryption shares) | **Offline/isolated only**: variable-time arithmetic, no constant-time claim | + +Everything is in `zeroj-circuit-lib`, the same dependency as the +[ElGamal guide](/guides/confidential/elgamal/#add-the-dependency). + +## Choose t and n + +`t` is the number of **corrupted trustees the scheme tolerates**, not the number needed to +decrypt. Decrypting needs `t + 1`. The protocol requires an honest majority, `2t + 1 ≤ n`, and +supports up to 64 trustees. + +| `DkgConfig.create(t, n, …)` | Decrypting needs | Tolerates | +|---|---|---| +| `create(1, 3, …)` | any 2 of 3 | 1 corrupted trustee | +| `create(2, 5, …)` | any 3 of 5 | 2 | +| `create(3, 7, …)` | any 4 of 7 | 3 | + +A 4-of-5 policy isn't possible: it would need `t = 3` with `n = 5`, which breaks the honest +majority. And remember the other side of the threshold: any `t + 1` trustees who collude can +decrypt **any single ciphertext**, not just the total. + +## 1. Run the key generation and decrypt a tally + +This program runs a 2-of-3 key generation in one process, encrypts five 0/1 votes to the joint +key, adds them, and has two trustees decrypt only the total. In a real deployment each trustee is +a separate, isolated machine, and the messages travel over your own channels. + +```java title="ThresholdTally.java" +import org.zeroj.circuit.lib.jubjub.DkgConfig; +import org.zeroj.circuit.lib.jubjub.DkgMessage; +import org.zeroj.circuit.lib.jubjub.DkgParticipant; +import org.zeroj.circuit.lib.jubjub.ElGamal; +import org.zeroj.circuit.lib.jubjub.ElGamalCiphertext; +import org.zeroj.circuit.lib.jubjub.ThresholdKeyContext; +import org.zeroj.circuit.lib.jubjub.ThresholdKeyShare; +import org.zeroj.circuit.lib.jubjub.VerifiedDecryptionShare; + +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; + +/** + * Three trustees run a threshold key generation (t = 1, n = 3: any 2 can decrypt), voters + * encrypt 0/1 votes, the ciphertexts are added, and two trustees decrypt only the tally. + * Everything runs in one process here; in reality each trustee is a separate, isolated host. + */ +public class ThresholdTally { + + public static void main(String[] args) { + SecureRandom random = new SecureRandom(); + + // 1. Configuration, agreed by everyone (e.g. published in an election manifest). + // t = faults tolerated; any t + 1 trustees decrypt; the rule is 2t + 1 <= n. + List roster = List.of( // each trustee's authentication key (demo bytes) + "trustee-1-auth-key".getBytes(StandardCharsets.UTF_8), + "trustee-2-auth-key".getBytes(StandardCharsets.UTF_8), + "trustee-3-auth-key".getBytes(StandardCharsets.UTF_8)); + DkgConfig config = DkgConfig.create(1, 3, roster, + "demo-election-2026".getBytes(StandardCharsets.UTF_8), 1); + + // 2. Key generation: 7 rounds. Broadcasts go to everyone (sender included); + // SHARE messages go privately to one recipient. + List trustees = new ArrayList<>(); + for (int id = 1; id <= 3; id++) trustees.add(DkgParticipant.create(config, id, random)); + List outgoing = new ArrayList<>(); + for (DkgParticipant p : trustees) outgoing.addAll(p.start()); + for (int round = 1; round <= 7; round++) { + for (DkgMessage m : outgoing) { + for (DkgParticipant p : trustees) { + if (m.kind() != DkgMessage.Kind.SHARE) p.receiveBroadcast(m.sender(), m.encode()); + else if (m.subject() == p.id()) p.receivePrivate(m.sender(), m.encode()); + } + } + outgoing = new ArrayList<>(); + for (DkgParticipant p : trustees) outgoing.addAll(p.closeRound()); // round deadline + } + List shares = new ArrayList<>(); + for (DkgParticipant p : trustees) shares.add(p.result()); // each trustee keeps its own + ThresholdKeyContext election = shares.get(0).context(); + System.out.println("Threshold t = " + election.threshold() + ", qualified trustees " + election.qual()); + System.out.println("All trustees agree on the key: " + + (election.equals(shares.get(1).context()) && election.equals(shares.get(2).context()))); + + // 3. Voters encrypt 0 or 1 (width 1) under the joint key; the ciphertexts are added. + int[] votes = {1, 0, 1, 1, 0}; + List ballots = new ArrayList<>(); + for (int vote : votes) ballots.add(ElGamal.encrypt(election, vote, 1, random)); + ElGamalCiphertext total = ElGamalCiphertext.sum(ballots); + System.out.println("Encrypted tally bound: " + total.bound()); + + // 4. Any t + 1 = 2 trustees publish decryption shares of the *total* only. + List published = List.of( + ElGamal.decryptionShare(shares.get(0), total), // trustee 1 + ElGamal.decryptionShare(shares.get(2), total)); // trustee 3 (trustee 2 is away) + long yes = ElGamal.decrypt(total, published, total.bound().longValueExact()); + System.out.println("Yes votes: " + yes + " of " + votes.length); + + // One share is not enough. + try { + ElGamal.decrypt(total, published.subList(0, 1), total.bound().longValueExact()); + } catch (IllegalArgumentException e) { + System.out.println("Refused: " + e.getMessage()); + } + } +} +``` + +```text +Threshold t = 1, qualified trustees [1, 2, 3] +All trustees agree on the key: true +Encrypted tally bound: 5 +Yes votes: 3 of 5 +Refused: threshold decryption needs at least t + 1 = 2 verified shares, got 1 +``` + +The key generation is seven rounds. In each round every trustee processes what it received and +sends its next messages. `closeRound()` is the round deadline: whatever didn't arrive in time +counts as missing, which is how a silent trustee gets excluded instead of blocking everyone. +Two rules of the in-memory loop matter in real code too: + +- **Every trustee also receives its own broadcasts**, and `SHARE` messages go only to their one + recipient, through `receivePrivate`. +- **An abort is final.** Start a new attempt with a new `attempt` number in `DkgConfig.create`; + never reuse one. + +## 2. Deliver private shares over a public board (HPKE) + +Each trustee's `SHARE` messages are secrets meant for one recipient. If you don't have private +channels between trustees, ZeroJ can encrypt them with HPKE (RFC 9180, Base mode, with X25519, +HKDF-SHA256 and ChaCha20-Poly1305) and post the encrypted **envelopes** on the same public board +as everything else. The order of posts is part of the security, so the API enforces round +barriers: + +1. **Round 0: announce.** Each trustee generates fresh delivery keys for this attempt and posts the + announcement (106 bytes). Once the round-0 window is final, every trustee builds the same + `DkgKeyDirectory` from it. +2. **Round 1: envelopes first.** `DkgShareDelivery.start` replaces `start()`. Post the envelopes + (223 bytes each, `n(n−1)` per attempt), and post the `COMMITMENTS` broadcasts only after the + envelopes are final, or atomically with them. +3. **Close round 1 only through `closeRound1`**, passing the round-1 window after its cutoff + **and** after it's final on the board. Plain `closeRound()` refuses round 1. The delivery keys + are destroyed here. +4. **Rounds 2 to 7** are plain broadcasts, as in example 1. + +This program runs the same 2-of-3 key generation as example 1, with every message on one board. +Posts are signed with each trustee's Ed25519 roster key, and the board doubles as the verifier +the API asks for. Its last step, letting an outsider admit the key, is in section 3. + +```java title="EncryptedBoardDkg.java" +import org.zeroj.circuit.lib.jubjub.AuthenticatedDkgMessage; +import org.zeroj.circuit.lib.jubjub.DkgAdmissionVerifier; +import org.zeroj.circuit.lib.jubjub.DkgConfig; +import org.zeroj.circuit.lib.jubjub.DkgKeyDirectory; +import org.zeroj.circuit.lib.jubjub.DkgMessage; +import org.zeroj.circuit.lib.jubjub.DkgParticipant; +import org.zeroj.circuit.lib.jubjub.DkgShareDelivery; +import org.zeroj.circuit.lib.jubjub.DkgShareDeliveryKeys; +import org.zeroj.circuit.lib.jubjub.DkgTranscript; +import org.zeroj.circuit.lib.jubjub.ThresholdKeyContext; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; + +/** + * The same 2-of-3 key generation as ThresholdTally, but with no private channels: every message, + * including each trustee's secret SHAREs (HPKE-encrypted), goes over one public board. Each post + * is signed with the trustee's Ed25519 roster key. Afterwards an outsider (a voter) admits the + * joint key from the board alone. + */ +public class EncryptedBoardDkg { + + /** An in-memory public board: posts per round window, each signed by its sender. */ + static final class Board implements DkgAdmissionVerifier { + final List> rounds = new ArrayList<>(); + final List signers; + + Board(List signers) { + this.signers = signers; + for (int r = 0; r <= 7; r++) rounds.add(new ArrayList<>()); + } + + void post(int round, int sender, byte[] message) throws GeneralSecurityException { + Signature s = Signature.getInstance("Ed25519"); + s.initSign(signers.get(sender - 1).getPrivate()); + s.update(message); + rounds.get(round).add(new AuthenticatedDkgMessage(message, s.sign())); + } + + @Override // authenticity: a valid Ed25519 signature under the sender's roster key + public boolean authenticate(int sender, byte[] rosterKey, byte[] message, byte[] authenticator) { + try { + Signature s = Signature.getInstance("Ed25519"); + s.initVerify(KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(rosterKey))); + s.update(message); + return s.verify(authenticator); + } catch (GeneralSecurityException | RuntimeException e) { + return false; // never throw on attacker-supplied input + } + } + + @Override // closure: this board is the agreed, complete record of each round window + public boolean roundClosed(DkgConfig config, int round, List messages, byte[] evidence) { + List expected = DkgTranscript.deliveredRound(config, round, rounds.get(round), this); + if (expected.size() != messages.size()) return false; + for (int i = 0; i < expected.size(); i++) { + if (!Arrays.equals(expected.get(i), messages.get(i))) return false; + } + return true; + } + } + + public static void main(String[] args) throws GeneralSecurityException { + SecureRandom random = new SecureRandom(); + int n = 3; + + // Roster: each trustee's long-term Ed25519 public key (X.509-encoded). + List signers = new ArrayList<>(); + List roster = new ArrayList<>(); + KeyPairGenerator ed = KeyPairGenerator.getInstance("Ed25519"); + for (int j = 1; j <= n; j++) { + KeyPair kp = ed.generateKeyPair(); + signers.add(kp); + roster.add(kp.getPublic().getEncoded()); + } + DkgConfig config = DkgConfig.create(1, n, roster, "demo-election-2026".getBytes(StandardCharsets.UTF_8), 1); + Board board = new Board(signers); + + List trustees = new ArrayList<>(); + List hpkeKeys = new ArrayList<>(); + for (int j = 1; j <= n; j++) { + trustees.add(DkgParticipant.create(config, j, random)); + hpkeKeys.add(DkgShareDeliveryKeys.generate(config, j, random)); // fresh per attempt + } + + // Round 0: each trustee announces its HPKE key. Once the window is final, everyone + // builds the same directory from it. + for (DkgShareDeliveryKeys k : hpkeKeys) board.post(0, k.id(), k.announcement()); + DkgKeyDirectory directory = DkgKeyDirectory.fromRound0(config, board.rounds.get(0), board); + + // Round 1: envelopes (encrypted SHAREs) first; COMMITMENTS only after the envelopes are final. + List dealings = new ArrayList<>(); + for (DkgParticipant p : trustees) { + DkgShareDelivery.SealedDealing d = DkgShareDelivery.start(p, directory, hpkeKeys.get(p.id() - 1), random); + dealings.add(d); + for (byte[] envelope : d.envelopes()) board.post(1, p.id(), envelope); // one per other trustee + } + for (int j = 1; j <= n; j++) { + for (DkgMessage m : dealings.get(j - 1).broadcasts()) board.post(1, j, m.encode()); + } + // Barrier: after the round-1 window is final, each trustee processes all of it at once. + List outgoing = new ArrayList<>(); + for (DkgParticipant p : trustees) { + outgoing.addAll(DkgShareDelivery.closeRound1(p, directory, hpkeKeys.get(p.id() - 1), + board.rounds.get(1), board)); + } + System.out.println("HPKE keys destroyed after round 1: " + + hpkeKeys.stream().allMatch(DkgShareDeliveryKeys::isDestroyed)); + + // Rounds 2-7: plain broadcasts, as without encryption. + for (int round = 2; round <= 7; round++) { + for (DkgMessage m : outgoing) { + board.post(round, m.sender(), m.encode()); + for (DkgParticipant p : trustees) p.receiveBroadcast(m.sender(), m.encode()); + } + outgoing = new ArrayList<>(); + for (DkgParticipant p : trustees) outgoing.addAll(p.closeRound()); + } + ThresholdKeyContext trusteeView = trustees.get(0).result().context(); + + // Section 3: an outsider admits the joint key from the board. + } +} +``` + +Output of the full program (the joint key is random): + +```text +HPKE keys destroyed after round 1: true +Board posts: 18 +Voter's admitted key equals the trustees' key: true +Joint key: 325c41c481f9e3fc49d9cc400cb51928820fa74e4dff86dd8501e8e631b1522e +``` + +Two rules for your own board verifier: `authenticate` and `roundClosed` must **return `false`, +never throw**, on bad input; and `roundClosed` must only say `true` for the agreed, complete +record of that round. A `roundClosed` that always returns `true` defeats the protection. + +HPKE here has no forward secrecy and isn't post-quantum: a delivery key that leaks before it is +destroyed exposes that trustee's shares. + +## 3. Let outsiders admit the joint key + +Voters, talliers and validators hold no secret, but they need to know that the joint key really +came out of an honest key generation. `ThresholdKeyContext.admit` replays the public record and +returns the same key context the trustees hold: + +```java title="EncryptedBoardDkg.java (end of main)" + +// A voter, who holds no secret, admits the key from the signed board (rounds 1-6 + confirmations). +List transcript = new ArrayList<>(); +for (int r = 1; r <= 6; r++) { + for (byte[] m : DkgTranscript.deliveredRound(config, r, board.rounds.get(r), board)) { + for (AuthenticatedDkgMessage post : board.rounds.get(r)) { + if (Arrays.equals(post.message(), m)) { transcript.add(post); break; } + } + } +} +Map closureEvidence = new HashMap<>(); +for (int r = 1; r <= 7; r++) closureEvidence.put(r, new byte[0]); // our Board needs none +ThresholdKeyContext voterView = ThresholdKeyContext.admit(config, transcript, closureEvidence, + board.rounds.get(7), board); +System.out.println("Board posts: " + board.rounds.stream().mapToInt(List::size).sum()); +System.out.println("Voter's admitted key equals the trustees' key: " + voterView.equals(trusteeView)); +System.out.println("Joint key: " + HexFormat.of().formatHex(voterView.jointKey().encode())); +``` + +`DkgTranscript.deliveredRound` filters each round down to the threshold protocol's own messages, +dropping the HPKE envelopes and announcements that share the board. + +## Operating rules + +The library enforces the protocol; it can't enforce how you run it. A deployment must: + +- **Isolate trustees.** Each one runs on its own machine, under its own control. +- **Fix the configuration in advance.** `t`, `n`, the roster and the application context come from + a trusted source, such as a published election manifest, never from the network mid-run. +- **Never reuse an `attempt` number** for the same context. +- **Deliver private shares on time.** A missed share triggers a complaint, and answering a + complaint publishes that share. Timely private delivery is a precondition for secrecy. +- **Decrypt once.** Decrypt only the final total, after the deadline. Decrypting running totals + and subtracting them reveals individual votes. +- **Verify every decryption share** you receive with `VerifiedDecryptionShare.verify` and a DLEQ + proof. In example 1 the shares are "verified by construction" because one process made them; a + separate tallier gets them as bytes. + +## Sizes and timings + +| Item | Size | +|---|---| +| Delivery key announcement | 106 bytes per trustee | +| Encrypted share envelope | 223 bytes, `n(n−1)` per attempt (about 0.9 MB at `n = 64`) | +| Joint key, key shares, decryption shares | 32 bytes each | + +| Key generation, whole run in one process (Apple M4 Max) | Time | +|---|---| +| `t = 1, n = 3` | 62 ms | +| `t = 2, n = 5` | 176 ms | +| `t = 10, n = 21` | 4.5 s | + +Key generation times are the plain-channel runs in the +[ElGamal benchmark](https://github.com/bloxbean/zeroj/blob/main/docs/benchmarks/elgamal-jubjub-2026-10-05.md); +sizes are from the +[share delivery benchmark](https://github.com/bloxbean/zeroj/blob/main/docs/benchmarks/dkg-share-delivery-hpke-2026-10-09.md), +which also times the HPKE-delivered runs. Network rounds, not computation, dominate a real ceremony. + +## Next steps + +- [Private voting](/use-cases/private-voting/): an encrypted tally decrypted by trustees +- [Split trust between several parties](/selective-disclosure/split-trust/): the pattern, and + when to use it +- [ElGamal encryption](/guides/confidential/elgamal/): keys, admission and proofs diff --git a/www/src/content/docs/guides/credentials/authenticated-state.mdx b/www/src/content/docs/guides/credentials/authenticated-state.mdx index 1b2a6736..20ce168d 100644 --- a/www/src/content/docs/guides/credentials/authenticated-state.mdx +++ b/www/src/content/docs/guides/credentials/authenticated-state.mdx @@ -83,8 +83,8 @@ methods (`inclusion(maxSteps)`, `valueUpdate(maxSteps)`, …) and as `ZkMpf*` / | Deletion | No physical delete yet | Tombstones only; a tombstone is **not** proof of absence | Both produce the same 192-byte compressed Groth16 proof and a 432-byte compressed VK for one public -input, so on-chain cost is the same: ZeroJ measured **2,627,770,348 CPU steps and 177,749 memory -units** in the JuLC VM. The JMT's larger native proof is private prover input and never reaches +input, so on-chain cost is the same: ZeroJ measured **2,052,276,435 CPU steps and 138,837 memory +units** in the JuLC VM (JuLC 0.1.0-pre18). The JMT's larger native proof is private prover input and never reaches the chain. The two root profiles (`zeroj-poseidon-mpf-v1`, `zeroj-poseidon-jmt-v1`) are incompatible with diff --git a/www/src/content/docs/guides/credentials/bbs.mdx b/www/src/content/docs/guides/credentials/bbs.mdx index 70a298e3..39ce33a8 100644 --- a/www/src/content/docs/guides/credentials/bbs.mdx +++ b/www/src/content/docs/guides/credentials/bbs.mdx @@ -18,6 +18,13 @@ officer can still check the government's stamp. ZeroJ implements BBS in the opt-in `zeroj-bbs` module, following the IRTF CFRG draft **`draft-irtf-cfrg-bbs-signatures-10`**. It is a draft, not yet an RFC. +:::tip[Is BBS the right tool?] +BBS reveals the exact signed values you choose. If a verifier needs only a yes/no answer, a hidden +number it can check, or a value that only an auditor may read, see +[Choose how to disclose](/selective-disclosure/), which compares BBS with predicates, commitments, +encrypted deliveries and threshold keys. +::: + ## BBS or a circuit? | You want to… | Use | @@ -239,8 +246,8 @@ validator's parameters, so the script hash pins both the issuer and the credenti :::caution[Fixed profile] `BbsProofVerify.verify` is unrolled for **one shape: a 5-message credential disclosing indexes 2 and 3** (hiding 0, 1 and 4). Plutus has no cheap dynamic loop, so other shapes need a different -unrolling. It uses the SHA-256 ciphersuite and was measured at about 2.44 billion CPU steps and -183,509 memory units in the JuLC VM. On-chain BBS is an opt-in, unaudited path for testnets. +unrolling. It uses the SHA-256 ciphersuite and was measured at about 2.43 billion CPU steps and +169,451 memory units in the JuLC VM. On-chain BBS is an opt-in, unaudited path for testnets. ::: Your validator composes `BbsProofVerify` with its own policy: check that the disclosed values match diff --git a/www/src/content/docs/guides/verifying/on-chain.mdx b/www/src/content/docs/guides/verifying/on-chain.mdx index 6202d21c..2da0addf 100644 --- a/www/src/content/docs/guides/verifying/on-chain.mdx +++ b/www/src/content/docs/guides/verifying/on-chain.mdx @@ -170,7 +170,7 @@ public inputs, and the validator computes `spendRef` from `ScriptContext` and pr checking the proof. It is the validator built and tested in [Verify your proof on Cardano](/tutorials/verify-on-cardano/), where it unlocks a real lock transaction on an in-memory ledger and rejects the same proof replayed against a second UTxO -(about 3.02 billion CPU steps and 263,000 memory units for two application inputs). +(about 2.34 billion CPU steps and 212,000 memory units for two application inputs). ```java title="SpendBoundGroth16Verifier.java" package com.example.onchain; @@ -286,9 +286,11 @@ tampered proof, a different spent UTxO, an output paying someone else. Then run A Groth16 check is four Miller loops and one final verification, plus one G1 scalar multiplication and addition per public input. ZeroJ's JuLC VM tests measured the generic `Groth16BLS12381Verifier`, evaluated as a spending validator with a full `ScriptContext`, at -**2,627,770,348 CPU steps and 177,749 memory units** for one public input, about 2.82 billion -CPU steps and 212,000 memory units for two, and about 3.02 billion and 246,000 for three. Your own -validator's policy checks come on top, and a JuLC upgrade can shift these numbers. +**2,052,276,435 CPU steps and 138,837 memory units** for one public input, about 2.19 billion +CPU steps and 168,000 memory units for two, and about 2.33 billion and 197,000 for three (JuLC +0.1.0-pre18, commit `6a89f8a`; the two- and three-input figures are from `Groth16BLS12381VerifierTest`). Each extra public input adds about 0.14 billion CPU steps. The verifier +decompresses each point once ([ADR-0056](https://github.com/bloxbean/zeroj/blob/main/docs/adr/0056-groth16-onchain-ic-single-decompression.md)), which cut about a fifth of the CPU cost. +Your own validator's policy checks come on top, and a JuLC upgrade can shift these numbers. For planning, `ScriptBudgetEstimator` gives estimates built from BLS12-381 builtin costs (they leave out the rest of the validator, so measured budgets come out higher), and @@ -342,12 +344,13 @@ correctness claim for them. Use Groth16. For completeness: `PlonkBLS12381Verifier` handles one public input, `PlonkBLS12381MultiInputVerifier` takes 1–8 public inputs from the datum, and `PlonkBLS12381MultiInputParamVerifier` takes them as script parameters, so the statement values are -pinned by the script hash. `ScriptBudgetEstimator` records roughly 4.8 billion CPU steps for the -one-input profile. +pinned by the script hash. The one-input verifier measured about 4.56 billion CPU steps and +565,000 memory units in the JuLC VM (`ScriptBudgetEstimator` still records an older estimate of +about 4.8 billion). `BbsProofVerify` verifies a BBS selective-disclosure presentation natively. It is unrolled for one -fixed shape: a **5-message credential disclosing indexes 2 and 3**, measured at about 2.44 billion -CPU steps and 183,509 memory units. Other shapes need a different unrolling. The off-chain half is +fixed shape: a **5-message credential disclosing indexes 2 and 3**, measured at about 2.43 billion +CPU steps and 169,451 memory units. Other shapes need a different unrolling. The off-chain half is `BbsToCardano` in `zeroj-bbs`; the [BBS guide](/guides/credentials/bbs/) shows both. ## Next steps diff --git a/www/src/content/docs/learn/commitments-and-encryption.mdx b/www/src/content/docs/learn/commitments-and-encryption.mdx new file mode 100644 index 00000000..cfbaf157 --- /dev/null +++ b/www/src/content/docs/learn/commitments-and-encryption.mdx @@ -0,0 +1,175 @@ +--- +title: Commitments & encryption, explained +description: 'Sealed envelopes, lockboxes and shared keys: what Pedersen commitments, ElGamal encryption, confidential notes and threshold decryption do, in plain English.' +sidebar: + order: 6 +--- + +import CommitmentExplainer from '../../../components/walkthrough/CommitmentExplainer.astro'; +import EncryptionExplainer from '../../../components/walkthrough/EncryptionExplainer.astro'; +import TextOnly from '../../../components/TextOnly.astro'; + +A zero-knowledge proof answers a question about secret data. Often that's all you need: "is this +person over 18?" But many applications also have to **keep a secret value on a public ledger**: a +balance, a salary, a bid, a vote. Somebody needs to check it now, somebody else may need to read it +later, and everyone else should see nothing. + +Four tools cover almost every case. This page explains each one with an everyday picture, and +[Choose how to disclose](/selective-disclosure/) helps you pick between them. + +| Tool | Everyday picture | What it gives you | +|---|---|---| +| **Commitment** | A sealed envelope | Publish a value without revealing it; prove facts about it; open it later | +| **Encryption to a key** | A lockbox with a slot | Anyone can put a value in; only the key holder can read it | +| **Encrypted delivery** | A letter to named readers | Hand the opening of a commitment to the owner and an auditor, on-chain | +| **Shared key (threshold)** | A safe that needs two of three keys | Nobody alone can decrypt; a quorum can | + +## Commitments: a sealed envelope + +A **commitment** lets you fix a value now and reveal it later, or never. ZeroJ uses **Pedersen +commitments**. To commit to a value `v`, you pick a large random number `r`, the **blinding**, and +publish one point on an elliptic curve: + +```text +C = v·G + r·H +``` + +`G` and `H` are two fixed public points. You don't need to follow the math to use it; three +properties matter: + +- **Hiding.** Because `r` is random, `C` reveals nothing about `v`. Two commitments to the same + amount look unrelated. +- **Binding.** Once you publish `C`, you can't later claim it held a different value. Finding a + second opening is as hard as breaking the curve. +- **Adding.** Commitments add up: `C(a, r) + C(b, s) = C(a + b, r + s)`. A ledger can total + balances, or check that inputs equal outputs, without seeing any single amount. + +Step through it. Drag the amount, roll a new blinding, and try opening the envelope to a different +number. + + + + + +```text + Alice Public ledger Verifier + v = 4,200 (secret) C = v·G + r·H sees only C + r = random (secret) ─── C ──▶ (32 bytes) + later, given (v, r): + ─── (v, r) ───────────────────────────────▶ recompute C, compare + C + D = commitment to the total + proves "v ≥ 1,000" ─── π ───────────────────────────────────▶ checks π against C +``` + + + +A commitment on its own only lets you open or not open. Its real power comes with a +zero-knowledge proof over the hidden value: "the amount in `C` is at least 1,000", "these three +commitments add up to that one", "this commitment holds a 0 or a 1". The proof reveals nothing +else, and `C` stays sealed. + +:::caution[Sums wrap around] +Commitment arithmetic wraps around at a huge number, about 2²⁵². A cheat could hide a "negative" +amount that looks like an enormous positive one, so a sum of commitments proves nothing about +real totals until every value is proven to be in range. ZeroJ's circuit gadgets check ranges and +refuse layouts that could wrap. See [Pedersen commitments](/guides/confidential/pedersen/#2-add-commitments). +::: + +## Encryption to a key: a lockbox with a slot + +A commitment can only be opened by someone who knows the opening. Sometimes a third party must be +able to read the value **without the owner's cooperation**: a tax authority reading salaries, an +auctioneer reading bids, election trustees counting votes. For that you encrypt the value to their +public key. + +ZeroJ uses **exponential ElGamal** on the same curve. A ciphertext is two points, and it has two +useful properties: + +- **Fresh randomness every time**, so the same value encrypted twice gives unrelated ciphertexts. +- **Adding.** Ciphertexts add up like commitments, so a ledger can keep an encrypted running total. + +The catch: decrypting ends with a lookup, so it only works for **small numbers**, such as votes or +amounts split into 32-bit pieces (called **limbs**). Decrypting a 64-bit amount directly would +take too long. + + + + + +```text + Senders Public ledger Auditor (holds sk) + Alice: 4,200 ── Enc ──▶ PK, Enc(4,200) + Bob: 2,500 ── Enc ──▶ Enc(2,500) + Enc(4,200) + Enc(2,500) = Enc(6,700) ──▶ decrypts 6,700 + + Split key: trustees T1, T2, T3 each hold a share; any 2 of 3 together decrypt, 1 alone can't. +``` + + + +Encryption and commitments work well together. A proof can show "this ciphertext encrypts the same +amount as this commitment", so the auditor's copy can't be faked. That's how the +[sealed-bid auction](/use-cases/sealed-bid-auction/) forces every bid to be readable by the +auctioneer, and how [confidential payroll](/use-cases/confidential-payroll/) stops an employer +from under-reporting a salary. + +## Encrypted delivery: a letter to named readers + +Suppose a payment is a commitment on-chain. Its owner needs the opening, `(v, r)`, to spend it +later, and an auditor may need it too. You could send it privately, but then a lost message means +lost money. A **confidential note** puts the opening on-chain, encrypted separately to each reader. + +- Each reader has a **viewing key**. The sender seals the opening for each reader with a fresh + one-time key, the way Zcash notes are encrypted. +- A reader scans the chain, opens the deliveries addressed to them, and **accepts a note only if + the opening recomputes the commitment**. A garbage delivery can't trick them; it shows up as + "unopenable". +- Everyone else sees the commitment and a few bytes of ciphertext per reader (89 bytes each). + +Delivery is about *convenience and recovery*: a lost wallet can rebuild its balance from the +chain. On its own it doesn't *force* the sender to tell the auditor the truth; pair it with an +encrypted amount and a proof when that matters. See [Confidential notes](/guides/confidential/confidential-notes/). + +## Shared keys: no single reader + +A single auditor or trustee is a single point of failure: they could read everything, or lose the +key. **Threshold decryption** splits the secret key among `n` trustees so that any `t + 1` of +them can decrypt together, and `t` or fewer learn nothing. + +The trustees create the key together with a **distributed key generation** (DKG): each one deals +shares to the others, and the full secret key never exists anywhere. ZeroJ implements a +well-studied DKG (Gennaro, Jarecki, Krawczyk and Rabin) and delivers the private shares over a +public board with HPKE (RFC 9180) encryption. A typical policy is: decrypt only the final total, +never a single ballot. See [Threshold decryption](/guides/confidential/threshold-elgamal/). + +## Putting them together + +Real applications combine the tools: + +| Use case | Commitment | Encryption | Delivery | Threshold | +|---|---|---|---|---| +| [Private voting with an encrypted tally](/use-cases/private-voting/) | | ✓ votes to the election key | | Shared key: the demo needs all 3 trustees (n-of-n); a t-of-n DKG is available | +| [Confidential loyalty points](/use-cases/confidential-points/) | ✓ balances | ✓ amounts to an auditor | ✓ to owner and auditor | | +| [Confidential payroll](/use-cases/confidential-payroll/) | ✓ salaries | ✓ to the tax authority, proven | ✓ to employee and tax authority | | +| [Sealed-bid auction](/use-cases/sealed-bid-auction/) | | ✓ bids to the auctioneer, proven | | | +| [Proof of solvency with hidden balances](/use-cases/private-solvency/) | ✓ customer balances | | ✓ to each customer and the auditor | | + +## What these tools don't do + +- **They don't authorize anything.** A valid opening or proof says nothing about who may spend a + UTxO. Validators still check signatures, replay and the transaction itself. See + [Application security](/guides/verifying/application-security/). +- **They don't hide the transaction graph.** Who pays whom, and when, is still visible on Cardano + unless the application hides it separately. +- **Key holders are trusted with what they can read.** An auditor who can decrypt can also leak. + Threshold keys reduce that risk; they don't remove it. + +## Next steps + +- [Choose how to disclose](/selective-disclosure/): BBS, predicates, commitments, deliveries and + threshold keys compared, with code +- Guides: [Pedersen commitments](/guides/confidential/pedersen/), + [ElGamal encryption](/guides/confidential/elgamal/), + [Confidential notes](/guides/confidential/confidential-notes/), + [Threshold decryption](/guides/confidential/threshold-elgamal/) +- [Glossary](/learn/glossary/) diff --git a/www/src/content/docs/learn/glossary.md b/www/src/content/docs/learn/glossary.md index 0a1f738c..278170a4 100644 --- a/www/src/content/docs/learn/glossary.md +++ b/www/src/content/docs/learn/glossary.md @@ -2,7 +2,7 @@ title: Glossary description: Short, plain-English definitions of the zero-knowledge, cryptography and Cardano terms used throughout the ZeroJ docs. sidebar: - order: 6 + order: 7 --- Quick definitions of the terms you'll meet in these docs, in alphabetical order. Each entry links @@ -20,8 +20,10 @@ draft-10. See [Groth16, PlonK & BBS](/learn/proof-systems/) and [BBS credentials **Blinding.** Randomness mixed into a proof or commitment so it reveals nothing about the secret. ZeroJ's Groth16 prover always blinds proofs, so two proofs of the same statement look unrelated. -In commitments, a random salt stops low-entropy values like an age from being guessed. -See [Zero-knowledge in plain English](/learn/zero-knowledge-basics/). +In commitments, a random salt stops low-entropy values like an age from being guessed. In a +Pedersen commitment the blinding is a fresh random 252-bit number, and ZeroJ refuses circuits that +declare it narrower or public. See [Zero-knowledge in plain English](/learn/zero-knowledge-basics/) +and [Pedersen commitments](/guides/confidential/pedersen/). **BLS12-381.** The pairing-friendly elliptic curve ZeroJ uses by default, and the only one Cardano can verify on-chain, through Plutus V3 builtins. See [Groth16, PlonK & BBS](/learn/proof-systems/). @@ -44,6 +46,17 @@ See [Circuits, constraints & witnesses](/learn/circuits-and-witnesses/). In circuits it's often a hash such as Poseidon(value, salt). You can later prove statements about the committed value. See [Zero-knowledge in plain English](/learn/zero-knowledge-basics/). +**Commitment (Pedersen).** A commitment that is a curve point, `C = v·G + r·H`, with a random +blinding `r`. It hides `v` completely, binds you to it, and adds up: the sum of two commitments +commits to the sum of the values. ZeroJ uses the Jubjub curve. See +[Commitments & encryption, explained](/learn/commitments-and-encryption/) and +[Pedersen commitments](/guides/confidential/pedersen/). + +**Confidential note.** A Pedersen commitment to an amount, stored on-chain together with its +opening encrypted separately to each chosen reader, such as the owner and an auditor. Readers find +their notes by scanning the chain with a viewing key. See +[Confidential notes](/guides/confidential/confidential-notes/). + **Completeness.** The guarantee that an honest prover with a true statement always convinces the verifier. See [Zero-knowledge in plain English](/learn/zero-knowledge-basics/). @@ -64,6 +77,19 @@ proof is two G1 points and one G2 point. See [Groth16, PlonK & BBS](/learn/proof **Datum.** Data attached to a UTxO locked at a script address. ZeroJ's reusable on-chain verifier reads the public inputs from it. See [ZK on Cardano](/learn/zk-on-cardano/). +**DKG (distributed key generation).** A protocol in which several trustees create one shared +public key together, each keeping only a share of the secret key. The full secret key never exists +anywhere. See [Threshold decryption](/guides/confidential/threshold-elgamal/). + +**DLEQ proof.** A proof that two points use the same secret multiplier ("discrete-log equality"). +ZeroJ uses it to prove possession of an ElGamal key and to prove that a decryption share is +correct. See [ElGamal encryption](/guides/confidential/elgamal/). + +**ElGamal (exponential).** Public-key encryption of small numbers in which ciphertexts add up: +the sum of two ciphertexts decrypts to the sum of the values. Decrypting ends in a search, so only +small values (such as votes or 32-bit limbs) can be decrypted. See +[ElGamal encryption](/guides/confidential/elgamal/). + **eUTxO.** Cardano's extended unspent-transaction-output model: funds and state live in outputs that validators guard, with a datum, a redeemer, and a ScriptContext. See [ZK on Cardano](/learn/zk-on-cardano/). @@ -84,6 +110,14 @@ comparator. ZeroJ's gadgets live in `zeroj-circuit-lib`. See [Gadgets](/guides/c **Groth16.** The zk-SNARK ZeroJ uses by default: 192-byte proofs on BLS12-381, the cheapest verification, and a trusted setup per circuit. See [Groth16, PlonK & BBS](/learn/proof-systems/). +**Homomorphic.** Describes commitments or ciphertexts you can combine without opening them: +adding two gives a commitment or ciphertext of the sum. Useful for totals and tallies. See +[Commitments & encryption, explained](/learn/commitments-and-encryption/). + +**HPKE.** Hybrid Public Key Encryption (RFC 9180). ZeroJ uses it to deliver each trustee's secret +DKG share over a public board, encrypted to that trustee. See +[Threshold decryption](/guides/confidential/threshold-elgamal/). + **JuLC.** A compiler that turns Java code into Plutus V3 validators for Cardano. ZeroJ's on-chain verifiers are written with it. See [ZK on Cardano](/learn/zk-on-cardano/). @@ -91,6 +125,12 @@ verifiers are written with it. See [ZK on Cardano](/learn/zk-on-cardano/). polynomial and later prove its value at a point. PlonK uses it with a universal SRS. See [Groth16, PlonK & BBS](/learn/proof-systems/). +## L + +**Limb.** One piece of a number split into smaller parts. An amount up to 2⁶⁴ is encrypted as two +32-bit limbs so that each limb is small enough to decrypt. See +[ElGamal encryption](/guides/confidential/elgamal/). + ## M–N **Merkle tree.** A tree of hashes whose single root commits to an entire list. A Merkle proof shows @@ -105,6 +145,12 @@ See [Trusted setup, explained](/learn/trusted-setup/). Poseidon(secret, electionId). It's the same every time the same secret is used in the same scope, so a validator can reject repeats without learning the secret. See [ZK on Cardano](/learn/zk-on-cardano/). +## O + +**Opening.** The values that unlock a commitment: for a Pedersen commitment, the value and its +blinding `(v, r)`. Whoever holds the opening can show what the commitment contains. See +[Pedersen commitments](/guides/confidential/pedersen/). + ## P **Pairing.** A special function that maps a G1 point and a G2 point to a third group, such that @@ -119,6 +165,10 @@ See [Groth16, PlonK & BBS](/learn/proof-systems/). than SHA-256. For Cardano circuits, always pass explicit BLS12-381 parameters: `PoseidonParamsBLS12_381T3.INSTANCE`. See [Gadgets](/guides/circuits/gadgets/). +**Possession proof.** A proof that whoever publishes a public key also knows its secret key. It +stops "rogue key" tricks where someone publishes a key derived from other people's keys. ZeroJ's +are DLEQ proofs. See [ElGamal encryption](/guides/confidential/elgamal/). + **Powers of tau.** The universal phase-1 setup output: curve points built from powers of a secret τ. It's stored in a `.ptau` file and reusable by every circuit up to its size. See [Trusted setup, explained](/learn/trusted-setup/). @@ -162,8 +212,9 @@ never leaves the prover. ZeroJ marks these with `@Secret`. See [Zero-knowledge in plain English](/learn/zero-knowledge-basics/). **Selective disclosure.** Revealing some attributes of a signed credential while proving the rest -are validly signed but hidden. BBS provides it natively. -See [Selective disclosure](/use-cases/selective-disclosure/). +are validly signed but hidden. BBS provides it natively; predicates, commitments and encrypted +deliveries are other ways to disclose less. See [Choose how to disclose](/selective-disclosure/) +and [Selective disclosure](/use-cases/selective-disclosure/). **SNARK.** Succinct Non-interactive ARgument of Knowledge: a short proof, checked quickly, sent in one message, showing the prover knows a valid witness. A zk-SNARK is also zero-knowledge. @@ -179,6 +230,10 @@ See [Zero-knowledge in plain English](/learn/zero-knowledge-basics/). ## T–U +**Threshold decryption.** Decryption that needs any `t + 1` of `n` key holders to cooperate; +`t` or fewer learn nothing. ZeroJ's threshold ElGamal requires `2t + 1 ≤ n`. See +[Threshold decryption](/guides/confidential/threshold-elgamal/). + **Toxic waste.** The secret randomness used in a trusted setup. Anyone who keeps it can forge proofs. See [Trusted setup, explained](/learn/trusted-setup/). @@ -205,6 +260,9 @@ See [ZK on Cardano](/learn/zk-on-cardano/). BLS12-381 with one public input it's 432 bytes compressed. On Cardano it's baked into the validator as script parameters. See [Trusted setup, explained](/learn/trusted-setup/). +**Viewing key.** A key that lets its holder find and open the confidential notes delivered to +them. It can't spend anything. See [Confidential notes](/guides/confidential/confidential-notes/). + **Wire.** A variable in a circuit. The witness gives every wire a value; wire 0 is always the constant 1. See [Circuits, constraints & witnesses](/learn/circuits-and-witnesses/). diff --git a/www/src/content/docs/learn/proof-systems.mdx b/www/src/content/docs/learn/proof-systems.mdx index 208318c5..b481c3ef 100644 --- a/www/src/content/docs/learn/proof-systems.mdx +++ b/www/src/content/docs/learn/proof-systems.mdx @@ -29,7 +29,7 @@ proofs that are tiny and cheap to verify. - **Verification:** a single *pairing check*, plus one elliptic-curve multiplication per public input. On Cardano, ZeroJ's reusable verifier does four Miller loops and one final check using Plutus V3 builtins. In ZeroJ's JuLC VM tests, a proof with two public inputs used about - 2.8 billion CPU units, against a per-transaction limit of 10 billion. + 2.2 billion CPU units, against a per-transaction limit of 10 billion. - **Setup:** Groth16 needs a **trusted setup for each circuit**. A universal "powers of tau" phase is reused, and a circuit-specific phase 2 runs for every circuit and every change to it. See [Trusted setup, explained](/learn/trusted-setup/). @@ -53,7 +53,7 @@ gates and wiring permutations instead of R1CS, and a polynomial commitment schem public and deterministic, so changing a circuit doesn't need a new ceremony. - **Proof:** larger than Groth16, about 650 bytes (roughly 3.5 times as large). - **Verification:** two pairings plus more scalar multiplications than Groth16. ZeroJ's - experimental on-chain verifier measured about 4.8 billion CPU units for one public input. + experimental on-chain verifier measured about 4.6 billion CPU units for one public input. - **Non-interactivity** comes from Fiat–Shamir: the verifier's challenges are derived by hashing the proof transcript, so transcript encoding details are security-critical. diff --git a/www/src/content/docs/learn/zk-on-cardano.mdx b/www/src/content/docs/learn/zk-on-cardano.mdx index 58cc3172..845dfa62 100644 --- a/www/src/content/docs/learn/zk-on-cardano.mdx +++ b/www/src/content/docs/learn/zk-on-cardano.mdx @@ -75,17 +75,18 @@ maximum. Groth16 is the cheapest pairing-based option because its verification w apart from one extra scalar multiplication per public input. In ZeroJ's JuLC VM tests, the reusable Groth16 verifier, run as a spending validator with a full -`ScriptContext`, measured: +`ScriptContext`, measured (JuLC 0.1.0-pre18): | Public inputs | CPU units | Memory units | |---------------|-----------|--------------| -| 1 | about 2.63 billion | about 178,000 | -| 2 | about 2.82 billion | about 212,000 | -| 3 | about 3.02 billion | about 246,000 | - -That's roughly a quarter to a third of the per-transaction CPU limit of 10 billion units under -current protocol parameters, leaving room for your own validation logic. Each extra public input -adds about 0.2 billion CPU units, and transaction fees scale with the units used, so keep public +| 1 | about 2.05 billion | about 139,000 | +| 2 | about 2.19 billion | about 168,000 | +| 3 | about 2.33 billion | about 197,000 | + +That's about a fifth to a quarter of the per-transaction CPU limit of 10 billion units under +current protocol parameters, leaving room for your own validation logic. (The figures dropped by +about a fifth when ZeroJ's verifier started decompressing each point once; see +[ADR-0056](https://github.com/bloxbean/zeroj/blob/main/docs/adr/0056-groth16-onchain-ic-single-decompression.md).) Each extra public input adds about 0.14 billion CPU units, and transaction fees scale with the units used, so keep public inputs to what the validator actually needs. Measure your own validator too: its policy checks add cost, and a JuLC compiler upgrade can shift the numbers. @@ -106,7 +107,7 @@ transaction metadata using Cardano Client Lib. |---|------------------------|-------------------------------------| | Who checks the proof | Every Cardano node, as part of consensus | Your verifier, plus anyone who re-checks later | | Can an invalid proof move funds? | No; the transaction fails | The chain doesn't check the proof at all, so your off-chain logic must | -| Cost | Plutus execution units, roughly 2.6 to 3 billion CPU units per proof | Only metadata bytes | +| Cost | Plutus execution units, roughly 2 to 2.4 billion CPU units per proof | Only metadata bytes | | Good for | Unlocking funds, minting, state transitions enforced by the ledger | Audit trails, attestations, batch results, off-chain protocols | ZeroJ's current release doesn't ship an anchoring helper. You write the metadata yourself with diff --git a/www/src/content/docs/reference/api-cheatsheet.md b/www/src/content/docs/reference/api-cheatsheet.md index d5abae9a..b27a592e 100644 --- a/www/src/content/docs/reference/api-cheatsheet.md +++ b/www/src/content/docs/reference/api-cheatsheet.md @@ -1,6 +1,6 @@ --- title: API cheat sheet -description: One page of the ZeroJ calls you use most, grouped by task, each with the class's package, from circuit definition to on-chain verification and BBS. +description: One page of the ZeroJ calls you use most, grouped by task, each with the class's package, from circuit definition to on-chain verification, BBS, commitments and encryption. sidebar: order: 2 --- @@ -137,6 +137,35 @@ bind the proof to the transaction in your own validator. | `new BbsPublicKey(bytes, BbsCiphersuite.BLS12381_SHA256)` · `pk.bytes()` | `BbsPublicKey` (`org.zeroj.bbs`) | | `BbsToCardano.verifierParams(pk, header, messageCount)` · `BbsToCardano.onChainProof(p)` | `BbsToCardano` (`org.zeroj.bbs.cardano`) | +## Commitments & encryption + +New in 0.1.0-pre13; everything here is in `zeroj-circuit-lib`, in `org.zeroj.circuit.lib.jubjub` +(host side) or `org.zeroj.circuit.lib.zk` (in circuits). Secret operations (creating commitments, +encrypting, decrypting, sealing notes, DKG) are offline/isolated only. See +[Commitments & encryption, explained](/learn/commitments-and-encryption/). + +| Call | Class (package) | +|---|---| +| `BigInteger r = PedersenCommitment.randomBlinding(new SecureRandom())` · `JubjubPoint c = PedersenCommitment.commit(v, r)` | `PedersenCommitment`, `JubjubPoint` (`…lib.jubjub`) | +| `PedersenCommitment.verify(c, v, r)` · `PedersenCommitment.decode(bytes)` (canonical + subgroup check; not `JubjubPoint.fromBytes`) | `PedersenCommitment` (`…lib.jubjub`) | +| In a circuit: `ZkPedersen.commit(zk, value, blinding).assertAffineEquals(zk, u, v)` (blinding `@Secret @UInt(bits = 252)`) | `ZkPedersen` (`…lib.zk`) | +| `ZkPedersenCommitment.commit(zk, value, blinding)` · `ZkPedersen.assertBalanced(zk, List.of(Term.of(in)), List.of(Term.of(out), Term.amount(fee)))` | `ZkPedersenCommitment`, `ZkPedersen.Term` (`…lib.zk`) | +| `ZkPedersenVector.commit(zk, ZkPedersenVector.bindSchema(zk, schema, schemaDigest), values, blinding)` | `ZkPedersenVector` (`…lib.zk`), `PedersenVectorSchema` (`…lib.jubjub`) | +| `ElGamal.encrypt(keyContext, m, width, rng)` · `ElGamal.encryptWithOpening(keyContext, m, width, rng)` (width 1–64) | `ElGamal`, `ElGamalCiphertext`, `ElGamalEncryption` (`…lib.jubjub`) | +| `ElGamalCiphertext.sum(ciphertexts)` · `ct.add(other)` (bounds add up) | `ElGamalCiphertext` (`…lib.jubjub`) | +| `ElGamal.admit(RawElGamalCiphertext.decode(bytes), keyContext, width, statement -> verifyEncryptionProof(…))` | `ElGamal`, `RawElGamalCiphertext` (`…lib.jubjub`) | +| `ElGamal.decryptWithSecret(ct, secretKey, maxPlaintext, JubjubDiscreteLog.forBound(maxPlaintext))` | `ElGamal`, `JubjubDiscreteLog` (`…lib.jubjub`) | +| `ElGamalPublicKey.aggregate(List.of(VerifiedKeyShare.verify(keyBytes, statement -> verifyPossessionProof(…))))` | `ElGamalPublicKey`, `VerifiedKeyShare`, `NOfNKeyContext` (`…lib.jubjub`) | +| `ElGamal.decryptionShare(share, total)` · `VerifiedDecryptionShare.verify(…)` · `ElGamal.decrypt(total, verifiedShares, maxPlaintext)` | `ElGamal`, `VerifiedDecryptionShare` (`…lib.jubjub`) | +| `DkgConfig.create(t, n, roster, appContext, attempt)` (any `t + 1` decrypt; `2t + 1 ≤ n ≤ 64`) | `DkgConfig` (`…lib.jubjub`) | +| `DkgParticipant.create(config, id, rng)` → `start()`, `receiveBroadcast`, `receivePrivate`, `closeRound()`, `result()` | `DkgParticipant`, `ThresholdKeyShare` (`…lib.jubjub`) | +| `ThresholdKeyContext.admit(config, transcript, roundClosure, confirmations, verifier)` (an outsider admits the joint key) | `ThresholdKeyContext` (`…lib.jubjub`) | +| `DkgShareDelivery.start(participant, directory, keys, rng)` · `DkgShareDelivery.closeRound1(participant, directory, keys, finalWindow, verifier)` | `DkgShareDelivery`, `DkgKeyDirectory`, `DkgShareDeliveryKeys` (`…lib.jubjub`) | +| `NoteViewingKey vk = NoteViewingKey.generate(rng)` · `vk.readerKey().encode()` (32 bytes to publish) | `NoteViewingKey`, `NoteReaderKey` (`…lib.jubjub`) | +| `ConfidentialNotes.seal(NoteOpening.random(v, rng), List.of(ownerReaderKey, auditorReaderKey), rng)` (89 bytes per reader; `NoteReaderKey`s, owner first) | `ConfidentialNotes`, `NoteOpening` (`…lib.jubjub`) | +| `NoteScanner.of(vk).open(delivery, u, v)` · `NoteScanner.of(vk).scan(candidates)` → `opened()`, `unopenableOwned()` | `NoteScanner` (`…lib.jubjub`) | +| In a circuit: `ZkElGamal.encrypt(zk, amount, randomness, ZkElGamalPublicKey.fromVerifierFixedPublic(zk, pkU, pkV)).assertAffineEquals(zk, aU, aV, bU, bV)` | `ZkElGamal`, `ZkElGamalPublicKey` (`…lib.zk`) | + ## PlonK (experimental) :::caution[Experimental] diff --git a/www/src/content/docs/reference/faq.md b/www/src/content/docs/reference/faq.md index f84265bd..9f102507 100644 --- a/www/src/content/docs/reference/faq.md +++ b/www/src/content/docs/reference/faq.md @@ -67,10 +67,13 @@ Numbers ZeroJ has measured and published (they depend on hardware and JVM): | Groth16 VK, compressed, one public input | 432 bytes | | Off-chain verification in the JVM | about 115 ms (113–119 ms across runs) | | Proving circuits of about 10k–74k constraints | about 2.9–4.6 s median | -| On-chain verification, generic verifier, one public input (JuLC VM, full `ScriptContext`) | 2,627,770,348 CPU steps, 177,749 memory units | +| On-chain verification, generic verifier, one public input (JuLC VM, full `ScriptContext`) | 2,052,276,435 CPU steps, 138,837 memory units | -The proving, off-chain verification and on-chain figures come from the Poseidon MPF/JMT -benchmarks. Each extra public input adds about 0.2 billion CPU steps on-chain, and your +The proving and off-chain verification figures come from the Poseidon MPF/JMT benchmarks; the +on-chain figure was re-measured at commit `6a89f8a` (JuLC 0.1.0-pre18) with the same +`PoseidonMpfCardanoArtifactTest` bundles, after the +verifier started decompressing each point once +([ADR-0056](https://github.com/bloxbean/zeroj/blob/main/docs/adr/0056-groth16-onchain-ic-single-decompression.md)). Each extra public input adds about 0.14 billion CPU steps on-chain, and your validator's own checks add more; see [Verify proofs on Cardano](/guides/verifying/on-chain/#budgets-and-script-size). Circuits with millions of constraints can be proved within commodity memory using the store-backed keys; see @@ -193,7 +196,7 @@ ZeroJ's interop tests pin snarkjs 0.7.6. See [Bring circom & snarkjs circuits](/ - Measure first: run the validator in the JuLC VM, and use `ScriptBudgetEstimator` for rough numbers (it counts only the BLS12-381 builtins, so real validators cost more). The generic - one-input Groth16 verifier measured about 2.63 billion CPU steps. + one-input Groth16 verifier measured about 2.05 billion CPU steps. - Each public input costs an extra scalar multiplication on-chain. Keep the count low. - Keep other heavy logic out of the same script execution, and compare with the network's *current* protocol parameters. diff --git a/www/src/content/docs/reference/modules.md b/www/src/content/docs/reference/modules.md index 11746f00..973ebd2c 100644 --- a/www/src/content/docs/reference/modules.md +++ b/www/src/content/docs/reference/modules.md @@ -63,7 +63,7 @@ dependencies { | `zeroj-crypto` | The pure-Java prover: Groth16 setup, proving, key stores, ceremony import, snarkjs export | Beta (Groth16); PlonK classes are experimental | `Groth16Keys`, `Groth16Pipeline`, `Groth16ProverBLS381`, `Groth16SetupBLS381`, `PowersOfTauBLS381`, `ZkeyImporterBLS381`, `ZkeyPkStoreImporter`, `SnarkjsGroth16Json` | | `zeroj-crypto-blst` | Opt-in blst MSM backend for the Groth16 prover; bit-identical proofs | Beta, opt-in | `BlstProverBackend` | | `zeroj-circuit-dsl` | Java circuit DSL; compiles to R1CS | Beta | `CircuitBuilder`, `CircuitSpec`, `SignalBuilder`, `Signal` | -| `zeroj-circuit-lib` | Gadget library: Poseidon, Merkle, comparators, binary, mux, Blake2b/SHA-512/HMAC, Ed25519/BIP32/CIP-1852… | Beta, per-gadget status | `PoseidonParamsBLS12_381T3`, see [Gadgets](/guides/circuits/gadgets/) | +| `zeroj-circuit-lib` | Gadget library: Poseidon, Merkle, comparators, binary, mux, Blake2b/SHA-512/HMAC, Ed25519/BIP32/CIP-1852…; from 0.1.0-pre13 also Pedersen commitments, exponential ElGamal, threshold DKG with HPKE share delivery, and confidential notes | Beta, per-gadget status; the commitment and encryption APIs are mostly Experimental (see [Status](/start/status/#commitments--encryption)) | `PoseidonParamsBLS12_381T3`, `PedersenCommitment`, `ElGamal`, `ConfidentialNotes`; see [Gadgets](/guides/circuits/gadgets/) and [Pedersen commitments](/guides/confidential/pedersen/) | | `zeroj-circuit-annotation-api` | `@ZKCircuit` symbolic annotations and `Zk*` types | Beta | `@ZKCircuit`, `@Prove`, `@Public`, `@Secret`, `ZkField`, `ZkBool`, `ZkContext`, `ZkInputMap` | | `zeroj-circuit-annotation-processor` | Annotation processor that generates a `Circuit` companion class | Beta | Add as `annotationProcessor` | | `zeroj-onchain-julc` | Plutus V3 validators and codecs, compiled with JuLC | Groth16: **Beta, testnet only**. PlonK validators: **Experimental**. BBS on-chain libraries: working for one fixed disclosure profile, not separately rated in the support matrix | `groth16.validator.Groth16BLS12381Verifier`, `Groth16BLS12381TxOutRefBindingVerifier` (reference example only), `Groth16BLS12381Lib`, `ProverToCardano`, `SnarkjsToCardano`, `ScriptBudgetEstimator` | diff --git a/www/src/content/docs/selective-disclosure/encrypt-for-an-auditor.mdx b/www/src/content/docs/selective-disclosure/encrypt-for-an-auditor.mdx new file mode 100644 index 00000000..4a988aaa --- /dev/null +++ b/www/src/content/docs/selective-disclosure/encrypt-for-an-auditor.mdx @@ -0,0 +1,116 @@ +--- +title: Encrypt for an auditor (ElGamal + proof) +description: Encrypt a value to an auditor's key and prove the ciphertext matches the hidden amount, so the auditor can always read the real value and the sender can't under-report. +sidebar: + order: 6 +--- + +import EncryptionExplainer from '../../../components/walkthrough/EncryptionExplainer.astro'; +import SinceNotice from '../../../components/SinceNotice.astro'; + +**Use this when an authority must be able to read a value, and the sender must not be able to lie +about it**: a tax authority reading salaries, an auctioneer reading bids, a regulator reading +transfer amounts. + +The sender encrypts the value to the auditor's public key with **exponential ElGamal**, and a +Groth16 proof shows the ciphertext holds the same value as the public commitment (or satisfies a +rule, such as "a bid between the reserve and the deposit"). A validator checks the proof, so a +transaction with a fake auditor copy never lands on-chain. + + + + + +## Who learns what + +| Party | Learns | +|---|---| +| Sender | The value | +| Auditor | The value, by decrypting; guaranteed to match the commitment | +| Everyone else | A 64-byte ciphertext and a proof; never the value | + +## In code + +The circuit ties one secret amount to both the public commitment and the public ciphertext: + +```java title="AuditedAmount.java" +import org.zeroj.circuit.annotation.*; +import org.zeroj.circuit.lib.zk.ZkElGamal; +import org.zeroj.circuit.lib.zk.ZkElGamalPublicKey; +import org.zeroj.circuit.lib.zk.ZkPedersenCommitment; + +/** "The ciphertext encrypts, under the auditor's key, the amount the commitment hides." */ +@ZKCircuit(name = "audited-amount", version = 1) +public class AuditedAmount { + @Prove + void prove(ZkContext zk, + @Public ZkField commitU, @Public ZkField commitV, + @Public ZkField auditorU, @Public ZkField auditorV, + @Public ZkField handleU, @Public ZkField handleV, + @Public ZkField blindedU, @Public ZkField blindedV, + @Secret @UInt(bits = 32) ZkUInt amount, + @Secret @UInt(bits = 252) ZkUInt blinding, + @Secret @UInt(bits = 252) ZkUInt randomness) { + ZkPedersenCommitment.commit(zk, amount, blinding).assertAffineEquals(zk, commitU, commitV); + var auditor = ZkElGamalPublicKey.fromVerifierFixedPublic(zk, auditorU, auditorV); + ZkElGamal.encrypt(zk, amount, randomness, auditor) + .assertAffineEquals(zk, handleU, handleV, blindedU, blindedV); + } +} +``` + +On the host, the sender encrypts with `ElGamal.encryptWithOpening`, and the auditor admits the +ciphertext only after checking that exact proof, then decrypts: + +```java title="AuditorSide.java (core)" +import org.zeroj.circuit.lib.jubjub.ElGamal; +import org.zeroj.circuit.lib.jubjub.ElGamalCiphertext; +import org.zeroj.circuit.lib.jubjub.ElGamalEncryption; +import org.zeroj.circuit.lib.jubjub.RawElGamalCiphertext; + +// Sender: encrypt the same 250 to the auditor's key (its key context, built from a verified key), +// declaring a 32-bit message width +ElGamalEncryption enc = ElGamal.encryptWithOpening(auditor, BigInteger.valueOf(250), 32, random); + +// Auditor: bytes from the chain re-enter the safe API only with a verified proof +RawElGamalCiphertext raw = RawElGamalCiphertext.decode(enc.ciphertext().encode()); +ElGamalCiphertext admitted = ElGamal.admit(raw, auditor, 32, + statement -> statement.width() == 32 && proofVerifies(commitment, statement.publicInputs())); +long amount = ElGamal.decryptWithSecret(admitted, auditorSecret, (1L << 32) - 1); // 250 +``` + +If the sender encrypts 1 instead of 250, no proof can be made. The full program, which shows that +refusal, is in the [ElGamal guide](/guides/confidential/elgamal/). + +## Real-world uses + +- **Confidential payroll.** The tax authority reads every salary from the chain, and the employer + can't under-report one. ([use case](/use-cases/confidential-payroll/)) +- **Sealed-bid auctions.** Each bid is encrypted to the auctioneer with a proof that it's between + the reserve and the deposit, so no bidder can back out by refusing to reveal. + ([use case](/use-cases/sealed-bid-auction/)) +- **Audited transfers.** Every confidential transfer carries the amount for a regulator, enforced + by the transfer proof. ([use case](/use-cases/confidential-points/)) + +## When not to use it + +- **No single party should read individual values.** Use [split trust](/selective-disclosure/split-trust/). +- **The value is a large number.** Decryption ends in a search that only works for small values + (up to about 2⁴³). Split amounts into 32-bit pieces (limbs) and encrypt each one, as the payroll + and points demos do. + +## Watch out for + +- **Verify the auditor's key.** Encrypt only to a key that came with a proof its owner knows the + secret (`VerifiedKeyShare.verify`), or a rogue key could lock the auditor out. +- **Never admit ciphertexts with `s -> true`** unless the ledger already verified that exact + statement. The verifier lambda is what makes the guarantee. +- **The auditor can leak.** Anyone who can decrypt can also share. Rotate keys, and consider a + threshold key for high-value data. +- **Maturity.** Experimental. Secret operations are offline/isolated only. + +## Next steps + +- [ElGamal encryption guide](/guides/confidential/elgamal/) +- [Split the trust](/selective-disclosure/split-trust/) +- [Choose how to disclose](/selective-disclosure/) diff --git a/www/src/content/docs/selective-disclosure/hide-a-number.mdx b/www/src/content/docs/selective-disclosure/hide-a-number.mdx new file mode 100644 index 00000000..02b9b826 --- /dev/null +++ b/www/src/content/docs/selective-disclosure/hide-a-number.mdx @@ -0,0 +1,115 @@ +--- +title: Hide a number (Pedersen commitments) +description: Publish a number as a sealed commitment, prove facts about it, add commitments together and open them later, so balances, bids and totals stay private on a public ledger. +sidebar: + order: 4 +--- + +import CommitmentExplainer from '../../../components/walkthrough/CommitmentExplainer.astro'; +import SinceNotice from '../../../components/SinceNotice.astro'; + +**Use this when a number has to live on a public ledger but stay private**: a balance, a salary, a +customer's deposit. People can still check facts about it ("at least 1,000", "inputs equal outputs") +and add many of them up, without ever seeing one. + +A **Pedersen commitment** is a sealed envelope: a 32-byte curve point made from the value and a +random **blinding**. It hides the value completely, it can't be reopened as a different value, and +commitments add up. A Groth16 proof can show facts about the hidden value. + + + + + +## Who learns what + +| Party | Learns | +|---|---| +| The committer | The value and its blinding (the **opening**) | +| A verifier given a proof | Only the proven fact, such as "at least 1,000" | +| Someone given the opening | The value; they can check it matches the commitment | +| Everyone else | A 32-byte commitment that reveals nothing | + +## In code + +Commit, publish 32 bytes, and open later: + +```java title="CommitAndOpen.java (core)" +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.PedersenCommitment; + +// Committer (offline): a fresh random blinding for every commitment +BigInteger value = BigInteger.valueOf(1_000); +BigInteger blinding = PedersenCommitment.randomBlinding(new SecureRandom()); +byte[] published = PedersenCommitment.commit(value, blinding).toBytes(); // 32 bytes + +// Verifier, later, given the opening (value, blinding) +JubjubPoint received = PedersenCommitment.decode(published); // checks the point +boolean opens = PedersenCommitment.verify(received, value, blinding); // true +boolean lies = PedersenCommitment.verify(received, BigInteger.valueOf(1_001), blinding); // false +``` + +Prove a fact without opening. This circuit proves "the committed value is at least the threshold": + +```java title="CommittedThreshold.java" +import org.zeroj.circuit.annotation.*; +import org.zeroj.circuit.lib.zk.ZkPedersen; + +@ZKCircuit(name = "committed-threshold", version = 1) +public class CommittedThreshold { + @Prove + ZkBool prove(ZkContext zk, + @Public ZkField commitmentU, // the commitment, as affine (u, v) + @Public ZkField commitmentV, + @Public @UInt(bits = 64) ZkUInt threshold, + @Secret @UInt(bits = 64) ZkUInt value, // never revealed + @Secret @UInt(bits = 252) ZkUInt blinding) { // must be exactly 252 bits + ZkPedersen.commit(zk, value, blinding).assertAffineEquals(zk, commitmentU, commitmentV); + return value.gte(threshold); + } +} +``` + +The [Pedersen guide](/guides/confidential/pedersen/) has both as complete, runnable programs, plus +adding commitments and proving that amounts balance. + +## Real-world uses + +- **Proof of solvency.** An exchange commits to every customer balance, proves the hidden total is + covered by locked reserves, and each customer checks their own entry. + ([use case](/use-cases/private-solvency/)) +- **Confidential balances and transfers.** Loyalty points or tokens move between holders, and a + proof shows inputs equal outputs, with no amounts on the ledger. + ([use case](/use-cases/confidential-points/)) +- **Commit now, reveal later.** Lock in a prediction, a price quote or a design hash today; open it + after the deadline, and nobody can claim you changed it. +- **Committed credentials.** A bureau commits to a credit profile; the holder proves "income ≥ + 50,000" from it. ([Prove a rule](/selective-disclosure/prove-a-rule/#over-a-committed-credential)) + +## When not to use it + +- **Someone else has to read the value without the owner's help.** A commitment opens only with + the opening. Add [chosen readers](/selective-disclosure/share-with-chosen-readers/) or + [encrypt for an auditor](/selective-disclosure/encrypt-for-an-auditor/). +- **The value is a one-off answer.** If nothing is stored on-chain, a plain + [predicate](/selective-disclosure/prove-a-rule/) is simpler. + +## Watch out for + +- **Sums wrap around.** Commitment arithmetic is modulo a 252-bit number, so an unchecked sum can + hide a "negative" amount. Prove every value's range, and use `ZkPedersen.assertBalanced`, which + refuses layouts that could wrap. +- **The blinding must be fresh, random and 252 bits.** ZeroJ refuses circuits whose blinding is + narrower, public or constant, but it can't check that yours is random. +- **Create commitments offline.** `commit` and `randomBlinding` run variable-time arithmetic on + secrets; keep them on the user's device or in an isolated process. +- **Decode received commitments with `PedersenCommitment.decode`**, which checks the point is in + the right subgroup. +- **Maturity.** In-circuit commitments are *ready, pending external review*; sums and vector + commitments are *experimental*. + +## Next steps + +- [Pedersen commitments guide](/guides/confidential/pedersen/) +- [Tell chosen readers](/selective-disclosure/share-with-chosen-readers/): deliver the opening + on-chain +- [Choose how to disclose](/selective-disclosure/) diff --git a/www/src/content/docs/selective-disclosure/index.mdx b/www/src/content/docs/selective-disclosure/index.mdx new file mode 100644 index 00000000..06baa571 --- /dev/null +++ b/www/src/content/docs/selective-disclosure/index.mdx @@ -0,0 +1,107 @@ +--- +title: Choose how to disclose +description: 'Six ways to share private data on Cardano with ZeroJ, and what each party learns: reveal signed values, prove a rule, hide a number, tell chosen readers, encrypt for an auditor, or split the trust.' +sidebar: + order: 1 + label: Choose how to disclose +--- + +import { CardGrid, LinkCard } from '@astrojs/starlight/components'; +import DisclosureOptionsExplainer from '../../../components/walkthrough/DisclosureOptionsExplainer.astro'; +import TextOnly from '../../../components/TextOnly.astro'; +import SinceNotice from '../../../components/SinceNotice.astro'; + +**Selective disclosure** means showing each party exactly what it needs and nothing more. A +landlord needs to know you earn enough, not your payslip. A tax authority needs every salary, but +the public needs none. An election needs the total, and nobody should see a single ballot. + +ZeroJ gives you six tools for this. They differ in **who learns what**, what they need (an +issuer, a circuit, a key) and how mature they are. This page compares them on one example. Each +option has its own page with simple code and real use cases. + +## One salary, six ways + +Carol earns 5,000 a month. Pick an option to see what Carol, a landlord, the tax authority and +everyone else learn. Not sure where to start? Press **Help me choose**. + + + + + +| Option | Landlord learns | Tax authority learns | Everyone else sees | +|---|---|---|---| +| Reveal the value (BBS) | salary = 5,000, signed by the employer | — | nothing | +| Prove a rule (Groth16) | "salary ≥ 3,000": yes | — | the proof and the threshold | +| Hide a number (Pedersen) | "the commitment hides ≥ 3,000": yes | can add commitments up; learns a total only if given its opening | a 32-byte commitment | +| Tell chosen readers (confidential note) | nothing unless Carol shares | 5,000 from its own delivery, if the sender delivered honestly (not enforced) | commitment + 89 bytes per reader | +| Encrypt for an auditor (ElGamal + proof) | — | 5,000, guaranteed to match | commitment, ciphertext, proof | +| Split the trust (threshold ElGamal) | — | only what 2 of 3 trustees agree to decrypt (by policy, the total) | ciphertexts, then the total | + + + +## Which one do I need? + +Start from the question "does anyone need the exact value?" + +| You need… | Use | Needs | Maturity | +|---|---|---|---| +| The verifier to see **some signed attributes exactly** ("country = NZ") and nothing else | [Reveal the value](/selective-disclosure/reveal-attributes/) with **BBS** | An issuer; no circuit, no trusted setup | Beta (IRTF draft) | +| A **yes/no answer** about private data ("over 21", "income ≥ 50,000") | [Prove a rule](/selective-disclosure/prove-a-rule/) with a **Groth16 predicate** | A circuit and a trusted setup | Beta | +| A **number kept sealed on-chain** that can be checked, added up or opened later | [Hide a number](/selective-disclosure/hide-a-number/) with a **Pedersen commitment** | A circuit for each statement | Ready (pending external review) in-circuit; sums experimental | +| **Named parties** (the owner, an auditor) to read the value from the chain | [Tell chosen readers](/selective-disclosure/share-with-chosen-readers/) with a **confidential note** | A viewing key per reader | Experimental | +| An **authority to read it, with no way for the sender to lie** | [Encrypt for an auditor](/selective-disclosure/encrypt-for-an-auditor/) with **ElGamal plus a proof** | An auditor key and a circuit | Experimental | +| **No single party** to see individual values; a quorum decrypts only the agreed result (a policy, not a guarantee) | [Split the trust](/selective-disclosure/split-trust/) with **threshold ElGamal** | A key-generation ceremony among trustees | Experimental | + +Two quick rules of thumb: + +- **BBS reveals, circuits compute.** If the verifier only needs a fact *about* a value, don't reveal + the value: prove the fact. +- **Commitments are for the owner, encryption is for someone else.** Only the person holding the + **opening** (the value and its random blinding) can open a commitment. If a third party must read the value without the owner's help, + encrypt it to them. + +:::caution[Experimental and new] +Everything except BBS and Groth16 predicates is new in ZeroJ 0.1.0-pre13 and is either +**experimental** or **pending external review**. None of it has been externally audited. See +[Status & maturity](/start/status/). +::: + + + +## They combine + +Real applications use several options at once: + +- **Confidential payroll** hides each salary in a commitment, delivers it to the employee and the + tax authority, and encrypts it to the tax authority with a proof so the employer can't + under-report. ([use case](/use-cases/confidential-payroll/)) +- **A private vote** encrypts each ballot to a key shared by trustees, proves each ballot is a 0 + or a 1, and decrypts only the total. The demo needs all three trustees (n-of-n); threshold + key generation is the t-of-n upgrade. ([use case](/use-cases/private-voting/)) +- **KYC** could reveal a country with BBS and prove an age rule with a small circuit; the two demos + show each half. ([use case](/use-cases/selective-disclosure/)) + +## What disclosure doesn't cover + +Choosing what to reveal is half the job. Every option above also needs the usual application +checks: + +- **Replay.** A presentation or proof can be copied. Bind it to a fresh challenge or to the UTxO + being spent. +- **Authorization.** A valid proof says nothing about who may spend or receive funds. +- **Metadata.** Transaction graphs, timing and fees can reveal more than the data you hid. + +See [Application security](/guides/verifying/application-security/). + +## The options + + + + + + + + + + +New to the underlying ideas? Read [Commitments & encryption, explained](/learn/commitments-and-encryption/). diff --git a/www/src/content/docs/selective-disclosure/prove-a-rule.mdx b/www/src/content/docs/selective-disclosure/prove-a-rule.mdx new file mode 100644 index 00000000..c9a133da --- /dev/null +++ b/www/src/content/docs/selective-disclosure/prove-a-rule.mdx @@ -0,0 +1,152 @@ +--- +title: Prove a rule (Groth16 predicates) +description: Prove a yes/no fact about private data, such as an age, income or score threshold, from a signed or committed credential, without revealing the data. The verifier learns only the answer. +sidebar: + order: 3 +--- + +import DisclosureWalkthrough from '../../../components/walkthrough/DisclosureWalkthrough.astro'; +import SinceNotice from '../../../components/SinceNotice.astro'; + +**Use this when the verifier needs an answer, not the data**: "over 21", "income at least 50,000", +"credit score at least 650", "resident of an approved country". + +The holder runs a small circuit on their own device. It checks that the data came from a trusted +issuer, then checks the rule, and outputs a Groth16 proof. The verifier, an app or a Cardano +validator, checks the proof against the issuer's key and its own policy values. It learns that the +rule holds, and nothing else. + + + +## Who learns what + +| Party | Learns | +|---|---| +| Issuer | The data, once, at issuance | +| Holder | Their own data | +| Verifier | The rule's answer, plus the public policy values it chose (the threshold, the current year) | +| Everyone else | The same as the verifier, if the proof goes on-chain | + +## Over a signed credential + +The issuer signs a Poseidon hash of all the fields with EdDSA on Jubjub. The circuit recomputes +the hash, checks the signature against the issuer's public key, then applies the rule. This one, +from the `selective-disclosure` demo, answers "a doctor, born at least 30 years before +`currentYear`?" in its public `eligible` output and reveals nothing else. The verifier must +require `eligible = 1`; a proof with `eligible = 0` is a valid proof of "no". + +```java title="SeniorDoctorProof.java" +import org.zeroj.circuit.annotation.*; +import org.zeroj.circuit.lib.poseidon.PoseidonParams; +import org.zeroj.circuit.lib.poseidon.PoseidonParamsBLS12_381T3; +import org.zeroj.circuit.lib.zk.ZkEdDSAJubjub; +import org.zeroj.circuit.lib.zk.ZkPoseidonN; + +@ZKCircuit(name = "senior-doctor", version = 1) +public class SeniorDoctorProof { + private static final PoseidonParams POSEIDON = PoseidonParamsBLS12_381T3.INSTANCE; + private static final int MIN_AGE = 30; + private static final long DOCTOR_ROLE_ID = 1001L; + + @Prove + ZkBool prove(ZkContext zk, + @Public ZkField pkU, + @Public ZkField pkV, + @Public @UInt(bits = 16) ZkUInt currentYear, + @Public ZkBool eligible, + @Secret @UInt(bits = 16) ZkUInt dobYear, + @Secret @UInt(bits = 16) ZkUInt country, + @Secret ZkField roleId, + @Secret @UInt(bits = 8) ZkUInt salaryBracket, + @Secret ZkField nameHash, + @Secret ZkField sigRU, + @Secret ZkField sigRV, + @Secret @UInt(bits = 252) ZkUInt sigS, + @Secret @UInt(bits = 252) ZkUInt kModL, + @Secret @UInt(bits = 4) ZkUInt kQuotient) { + + // Every predicate recomputes the same signed message over all five fields + var claims = ZkPoseidonN.hash(zk, POSEIDON, dobYear.asField(), country.asField(), + roleId, salaryBracket.asField(), nameHash); + ZkEdDSAJubjub.verifyWithRegisteredKey(zk, pkU, pkV, claims, sigRU, sigRV, sigS, kModL, kQuotient); + + // The predicate: role == doctor AND born no later than currentYear - 30 + var maxDobYear = ZkUInt.wrap(zk, currentYear.asField().sub(zk.constant(MIN_AGE)).signal(), 16); + var roleOk = roleId.isEqual(zk.constant(DOCTOR_ROLE_ID)); + return roleOk.and(eligible.isEqual(dobYear.lte(maxDobYear))); + } +} +``` + +This is the pattern of the [age and KYC](/use-cases/age-and-kyc/) and +[selective disclosure](/use-cases/selective-disclosure/) demos. The tutorial +[Prove you're over 18](/tutorials/age-check/) builds one step by step, including setup, proving and +verification. + +## Over a committed credential + + + +Instead of a signature, an issuer can publish a **Pedersen vector commitment** to a whole profile: +income, score, birth year and country in one 32-byte point. The holder gets the opening. A proof can +then check a rule over any of the fields while all of them stay sealed: + +```java title="CreditProfileCheck.java (core)" +import org.zeroj.circuit.lib.zk.ZkPedersenVector; + +// SCHEMA: income/64, credit_score/16, birth_year/16, country/16 bits +var binding = ZkPedersenVector.bindSchema(zk, SCHEMA, schemaDigest); // schemaDigest is @Public +ZkPedersenVector.commit(zk, binding, List.of(income, creditScore, birthYear, country), blinding) + .assertAffineEquals(zk, u, v); // (u, v) is the public commitment +income.gte(minIncome).assertTrue(); +creditScore.gte(minScore).assertTrue(); +``` + +The pedersen-commitments demo in [zeroj-usecases PR #8](https://github.com/bloxbean/zeroj-usecases/pull/8) +uses this as a **credit gate**: a bureau commits to Alice's profile (income 85,000, score 720), and +she proves "income ≥ 50,000 and score ≥ 650" to a lender, who mints her a badge on-chain. If Mallory +copies Alice's commitment and proof, the validator refuses, because the bureau's issuance record +names Alice, and Alice has to sign. + +Two rules come with vector commitments: bind the public **schema digest** in every proof, and +accept a commitment only with an authenticated **issuance record**. See +[Pedersen commitments](/guides/confidential/pedersen/#5-commit-to-several-values-at-once). + +| | Signed credential | Committed credential | +|---|---|---| +| Issuer publishes | A signature, held by the holder | A commitment, often on-chain | +| Unlinkable across verifiers | Yes, if the proof hides the signature | No: the same commitment is reused | +| Circuit size | Signature check plus the rule | About 3,000 constraints for the credit gate | +| Maturity | Beta | Experimental | + +## Real-world uses + +- **Age-restricted services.** "Over 18" for a game, "over 21" for a venue. + ([use case](/use-cases/age-and-kyc/)) +- **Lending.** "Income at least 50,000 and score at least 650" without a payslip or a credit + report. +- **Professional access.** "A doctor, licensed for 10 years or more", from a medical board's + credential. +- **Allowlists.** "My key is in this approved set", with a Merkle proof. + ([tutorial](/tutorials/private-allowlist/)) + +## When not to use it + +- **The verifier must see the value itself.** Use [Reveal the value](/selective-disclosure/reveal-attributes/). +- **The value has to stay on-chain and be added up.** Use [Hide a number](/selective-disclosure/hide-a-number/). +- **You can't run a trusted setup per circuit.** Every new rule is a new circuit; consider BBS if + revealing is acceptable. + +## Watch out for + +- **Pin the policy values.** The verifier, not the prover, chooses the threshold and the current + year. On Cardano, make them script parameters. +- **Replay.** These proofs carry no nonce. Bind them to the UTxO being spent or to a session. +- **Trusted setup.** Production keys come from a multi-party ceremony. See + [Trusted setup, explained](/learn/trusted-setup/). + +## Next steps + +- [Prove you're over 18](/tutorials/age-check/) (tutorial) +- [Hide a number](/selective-disclosure/hide-a-number/) +- [Choose how to disclose](/selective-disclosure/) diff --git a/www/src/content/docs/selective-disclosure/reveal-attributes.mdx b/www/src/content/docs/selective-disclosure/reveal-attributes.mdx new file mode 100644 index 00000000..95d1323f --- /dev/null +++ b/www/src/content/docs/selective-disclosure/reveal-attributes.mdx @@ -0,0 +1,88 @@ +--- +title: Reveal the value (BBS) +description: Show a verifier some attributes of an issuer-signed credential exactly as issued, and hide the rest, with BBS signatures. No circuit, no trusted setup. +sidebar: + order: 2 +--- + +import DisclosureWalkthrough from '../../../components/walkthrough/DisclosureWalkthrough.astro'; + +**Use this when the verifier needs to see a value exactly as an issuer signed it**, such as "country += NZ" or "licence class = B", and should learn nothing about the other attributes. + +An issuer signs a list of attributes once with **BBS**, a signature scheme built for credentials. +The holder can then show any subset of the attributes, together with a proof that the issuer +signed the whole list. Hidden attributes stay hidden, and two presentations of the same credential +can't be linked by the proof alone. + + + +## Who learns what + +| Party | Learns | +|---|---| +| Issuer | Everything, once, at issuance | +| Holder | Their own credential | +| Verifier | The revealed attributes, and that the issuer signed them | +| Everyone else | Nothing, unless the presentation is published (for example in a Cardano transaction, where revealed values become public) | + +## In code + +```java title="RevealCountry.java (core)" +import org.zeroj.bbs.BbsKeyPair; +import org.zeroj.bbs.BbsPresentation; +import org.zeroj.bbs.BbsService; +import org.zeroj.bbs.BbsSignature; + +BbsService bbs = BbsService.pureJava(); + +// Issuer: sign five attributes once (keyMaterial: at least 32 secret random bytes) +BbsKeyPair issuer = bbs.keyPair(keyMaterial, keyInfo); +List attributes = List.of(name, dob, country, kycLevel, docId); +BbsSignature signature = bbs.sign(issuer.secretKey(), issuer.publicKey(), attributes, header); + +// Holder: reveal country (2) and kycLevel (3), bound to the verifier's fresh challenge +BbsPresentation presentation = bbs.derivePresentation( + issuer.publicKey(), signature, attributes, header, challenge, new int[] {2, 3}); + +// Verifier: check the proof, then that the challenge is the one it issued, then its policy +boolean valid = bbs.verifyPresentation(issuer.publicKey(), presentation); +``` + +The complete, runnable program, plus key handling, headers and on-chain verification, is in the +[BBS guide](/guides/credentials/bbs/). + +## Real-world uses + +- **Reusable KYC.** Do identity checks once; show each service only the country and KYC level. + ([use case](/use-cases/selective-disclosure/), demo `reusable-kyc`) +- **Professional licences.** A doctor shows "licensed physician, valid until 2027" to a pharmacy + portal, without a home address or registration number. +- **Event and membership passes.** A member shows "tier = gold" to get in, and nothing else. +- **Supply-chain certificates.** A shipper reveals "origin = EU" and "certified organic" from an + auditor-signed product credential. + +## When not to use it + +- **The verifier needs a fact, not the value.** "Over 21" shouldn't reveal a birth date. Use + [Prove a rule](/selective-disclosure/prove-a-rule/). +- **The value lives on-chain and changes**, like a balance. BBS signs a fixed credential; use + [Hide a number](/selective-disclosure/hide-a-number/). +- **A rare revealed value identifies the person.** A unique combination of attributes can + re-identify someone; reveal the minimum. + +## Watch out for + +- **Replay.** A presentation stays valid forever. The verifier must pick a fresh challenge and + mark it used, or derive it from the UTxO being spent on-chain. +- **On-chain shape.** ZeroJ's on-chain BBS verifier supports one fixed shape: a five-attribute + credential revealing positions 2 and 3, at about 2.43 billion CPU steps. +- **Maturity.** BBS is **Beta** and follows an IRTF draft, not yet an RFC. The default pure-Java + provider isn't constant-time, so prefer the blst provider for issuer keys. + +## Next steps + +- [BBS credentials guide](/guides/credentials/bbs/) +- [Prove a rule](/selective-disclosure/prove-a-rule/): combine with a small circuit when one + attribute needs a range check +- [Choose how to disclose](/selective-disclosure/) diff --git a/www/src/content/docs/selective-disclosure/share-with-chosen-readers.mdx b/www/src/content/docs/selective-disclosure/share-with-chosen-readers.mdx new file mode 100644 index 00000000..e4b6cd04 --- /dev/null +++ b/www/src/content/docs/selective-disclosure/share-with-chosen-readers.mdx @@ -0,0 +1,97 @@ +--- +title: Tell chosen readers (confidential notes) +description: Put a hidden amount on-chain and seal its opening separately for each reader, such as the owner and an auditor, so they can read it straight from the chain and nobody else can. +sidebar: + order: 5 +--- + +import NoteDeliveryExplainer from '../../../components/walkthrough/NoteDeliveryExplainer.astro'; +import SinceNotice from '../../../components/SinceNotice.astro'; + +**Use this when named parties must be able to read a hidden value from the chain**: the owner of a +balance, so a lost wallet can recover it, and an auditor, so oversight doesn't depend on a side +channel. + +A **confidential note** is a [Pedersen commitment](/selective-disclosure/hide-a-number/) plus its +opening, encrypted separately for each reader, in the same transaction output. Each reader has a +**viewing key**. Their wallet scans the chain, opens the delivery addressed to them, and accepts +the value only if it recomputes the commitment. To everyone else, a note is a commitment and 89 +bytes of ciphertext per reader. + + + + + +## Who learns what + +| Party | Learns | +|---|---| +| Sender | The amount (they created the note) | +| Owner | The amount, from delivery 0 | +| Each auditor | The amount, from its own delivery | +| Everyone else | The commitment and that deliveries exist; never the amount | + +## In code + +```java title="ConfidentialNote.java (core)" +import org.zeroj.circuit.lib.jubjub.ConfidentialNotes; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.NoteOpening; +import org.zeroj.circuit.lib.jubjub.NoteReaderKey; +import org.zeroj.circuit.lib.jubjub.NoteScanner; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; + +// Each reader creates a viewing key in its own wallet and publishes the 32-byte reader key +NoteViewingKey ownerKey = NoteViewingKey.generate(random); +NoteViewingKey auditorKey = NoteViewingKey.generate(random); + +// Sender: commit to 250 and seal the opening for the owner (first) and the auditor +List readers = List.of( + NoteReaderKey.decode(ownerKey.readerKey().encode()), + NoteReaderKey.decode(auditorKey.readerKey().encode())); +NoteOpening opening = NoteOpening.random(BigInteger.valueOf(250), random); +JubjubPoint c = opening.commitment(); // goes in the datum +List deliveries = ConfidentialNotes.seal(opening, readers, random); // 2 x 89 bytes + +// Owner and auditor each open their own position against the note's (u, v) +Optional mine = NoteScanner.of(ownerKey).open(deliveries.get(0), c.affineU(), c.affineV()); +Optional audited = NoteScanner.of(auditorKey).open(deliveries.get(1), c.affineU(), c.affineV()); +// both hold 250; anyone else's key gets Optional.empty() +``` + +The complete program, wallet scanning and the rules for wallets are in the +[Confidential notes guide](/guides/confidential/confidential-notes/). + +## Real-world uses + +- **Confidential loyalty points.** Holders recover their balances from the chain; an auditor reads + every amount. ([use case](/use-cases/confidential-points/)) +- **Payroll.** Each payslip is readable by the employee and the tax authority, nobody else. + ([use case](/use-cases/confidential-payroll/)) +- **Proof of solvency.** Each customer opens their own committed balance from the attestation, and + the auditor opens only the total. ([use case](/use-cases/private-solvency/)) +- **Escrow and invoicing.** A buyer, a seller and an arbitrator can each read a confidential + invoice amount. + +## When not to use it + +- **The sender must not be able to lie to the auditor.** On-chain, a validator can only check that + a delivery of the right length exists, not that it opens. A dishonest sender can deliver garbage. + The reader notices ("unopenable"), but if the auditor's copy has to be *guaranteed*, also + [encrypt for the auditor with a proof](/selective-disclosure/encrypt-for-an-auditor/). +- **The reader should only see a total.** Use [split trust](/selective-disclosure/split-trust/). + +## Watch out for + +- **Report unopenable notes.** A note you own but can't open is value you can't spend. Wallets must + show it, never drop it. +- **Scan in your own process.** The viewing key reads every past delivery to it, so never hand it to + a shared scanning service. There's no forward secrecy. +- **Open only your own position**, and check the note's owner field and script address yourself. +- **Maturity.** Experimental. The delivery's security assumptions (A1–A3) await external review. + +## Next steps + +- [Confidential notes guide](/guides/confidential/confidential-notes/) +- [Encrypt for an auditor](/selective-disclosure/encrypt-for-an-auditor/) +- [Choose how to disclose](/selective-disclosure/) diff --git a/www/src/content/docs/selective-disclosure/split-trust.mdx b/www/src/content/docs/selective-disclosure/split-trust.mdx new file mode 100644 index 00000000..45a6c262 --- /dev/null +++ b/www/src/content/docs/selective-disclosure/split-trust.mdx @@ -0,0 +1,104 @@ +--- +title: Split the trust (threshold decryption) +description: Encrypt values to a key that no single party holds, so only a quorum of trustees can decrypt, and agree to decrypt only the result, such as an election tally. +sidebar: + order: 7 +--- + +import EncryptionExplainer from '../../../components/walkthrough/EncryptionExplainer.astro'; +import SinceNotice from '../../../components/SinceNotice.astro'; + +**Use this when nobody should be able to see individual values on their own**, but a group must be +able to reveal an agreed result: an election tally, a total of private bids, an aggregate statistic. + +Trustees run a **distributed key generation** (DKG) together. It produces one public key, and each +trustee keeps a share of the secret key; the full secret key never exists anywhere. Values are +encrypted to the public key and added up while still encrypted. At the end, any `t + 1` of the `n` +trustees publish decryption shares of the **total**, each with a proof it was computed honestly, +and the total comes out. Fewer than `t + 1` learn nothing. + + + + + +Step 5 of the illustration is this page's idea: pick trustees and see when the total decrypts. + +## Who learns what + +| Party | Learns | +|---|---| +| Each sender | Their own value | +| Any single trustee | Nothing beyond the public data | +| `t + 1` trustees together | Whatever they agree to decrypt; the policy is to decrypt only the total | +| Everyone else | Ciphertexts, then the total once decrypted | + +## In code + +A 2-of-3 setup (`t = 1`, `n = 3`) with an in-process key generation and a five-vote tally: + +```java title="ThresholdTally.java (core)" +import org.zeroj.circuit.lib.jubjub.DkgConfig; +import org.zeroj.circuit.lib.jubjub.ElGamal; +import org.zeroj.circuit.lib.jubjub.ElGamalCiphertext; +import org.zeroj.circuit.lib.jubjub.ThresholdKeyContext; +import org.zeroj.circuit.lib.jubjub.VerifiedDecryptionShare; + +// Agreed by everyone, e.g. in an election manifest: tolerate t = 1 fault, so any 2 of 3 decrypt +DkgConfig config = DkgConfig.create(1, 3, roster, "demo-election-2026".getBytes(UTF_8), 1); +// ... the trustees run the 7-round key generation (see the guide) and each keeps its share ... +ThresholdKeyContext election = shares.get(0).context(); + +// Voters encrypt 0 or 1 (width 1); anyone adds the ciphertexts +List ballots = new ArrayList<>(); +for (int vote : new int[] {1, 0, 1, 1, 0}) ballots.add(ElGamal.encrypt(election, vote, 1, random)); +ElGamalCiphertext total = ElGamalCiphertext.sum(ballots); + +// After the deadline, trustees 1 and 3 publish decryption shares of the total only +List published = List.of( + ElGamal.decryptionShare(shares.get(0), total), + ElGamal.decryptionShare(shares.get(2), total)); +long yes = ElGamal.decrypt(total, published, total.bound().longValueExact()); // 3 +``` + +The full program, including the key generation and the HPKE-encrypted delivery of trustee shares +over a public board, is in the [Threshold decryption guide](/guides/confidential/threshold-elgamal/). + +## Real-world uses + +- **Private voting.** Each ballot is encrypted to the election key with a proof it's a 0 or a 1; + trustees decrypt only the final count. The demo shares the key n-of-n among three trustees, so + all three must take part; the threshold key generation here is the t-of-n upgrade. + ([use case](/use-cases/private-voting/)) +- **Sealed-bid totals and statistics.** A consortium learns the total or average of private + submissions, and no member sees another's. +- **Key escrow with a quorum.** Recovery data is readable only when, say, 3 of 5 custodians agree. + +## Choose `t` and `n` + +| Policy | `t` | `n` | +|---|---|---| +| Any 2 of 3 | 1 | 3 | +| Any 3 of 5 | 2 | 5 | +| Any 4 of 7 | 3 | 7 | + +Any `t + 1` trustees decrypt. The rule `2t + 1 ≤ n ≤ 64` is about faults, not the quorum: at most +`t` trustees may misbehave during key generation, so the honest ones must outnumber them. It allows +"2 of 5" (`t = 1`, `n = 5`) but not "4 of 5", which would need `n ≥ 7`. + +## Watch out for + +- **A quorum can read anything.** `t + 1` colluding trustees can decrypt any single ciphertext, not + just the total. The "decrypt only the total" rule is a policy the library can't enforce; publish + it, and pick independent trustees. +- **Decrypt once.** Decrypting a running total twice and subtracting reveals the values in between. +- **Verify every share.** Accept decryption shares only with `VerifiedDecryptionShare.verify` and a + DLEQ proof (a proof that the share was made with the trustee's real key share); an unverified share lets a trustee choose the result. +- **Small results reveal.** A unanimous vote, or a total of one, reveals the individual values. +- **Maturity.** Experimental. Secret operations are offline/isolated only, and the encrypted share + delivery's assumption A1 awaits external review. + +## Next steps + +- [Threshold decryption guide](/guides/confidential/threshold-elgamal/) +- [ElGamal encryption guide](/guides/confidential/elgamal/) +- [Choose how to disclose](/selective-disclosure/) diff --git a/www/src/content/docs/start/status.md b/www/src/content/docs/start/status.md index 21f9a0a0..22f2439c 100644 --- a/www/src/content/docs/start/status.md +++ b/www/src/content/docs/start/status.md @@ -68,6 +68,24 @@ alternative to Groth16, and these docs make no correctness or readiness claims f | BBS (IRTF CFRG draft-10): verification | `zeroj-bbs` | **Beta**. The spec is an IRTF draft, not yet an RFC. | | BBS: issuance and proof generation | `zeroj-bbs` | **Beta with caveat**. The default pure-Java provider is not constant-time; prefer the blst provider for issuer keys. | +### Commitments & encryption + +New in 0.1.0-pre13 (before that release is on Maven Central, use a [snapshot](/start/installation/#snapshots)). All of +these live in `zeroj-circuit-lib`. + +| Area | Modules | Status | +|------|---------|--------| +| Pedersen commitments in circuits (`ZkPedersen`, `ZkPedersenCommitment`) | `zeroj-circuit-lib` | **Ready on BLS12-381 Groth16, pending external review**. Creating commitments off-circuit is offline/isolated only. | +| Pedersen homomorphic API and vector commitments | `zeroj-circuit-lib` | **Experimental**, pending review and external review | +| Exponential ElGamal and threshold DKG | `zeroj-circuit-lib` | **Experimental**. Secret operations are offline/isolated only. | +| Encrypted DKG share delivery (HPKE, RFC 9180) | `zeroj-circuit-lib` | **Experimental**. Its assumption A1 (HPKE in place of private channels) awaits external review. | +| Confidential notes (encrypted opening delivery) | `zeroj-circuit-lib` | **Experimental**. Assumptions A1–A3 await external review; secret operations are offline/isolated only. | + +"Offline/isolated only" means the code that handles secrets uses variable-time arithmetic: run it on +the user's device or in an isolated process, never in a service an attacker can time. See +[Commitments & encryption, explained](/learn/commitments-and-encryption/) and the guides under +[Pedersen commitments](/guides/confidential/pedersen/). + ### Authenticated state | Area | Modules | Status | @@ -122,6 +140,8 @@ possible, expected values come from somewhere other than the code under test. | Differential tests against independent implementations | zkcrypto BLS12-381 and zkryptium BBS compiled to WASM and run as oracles in a dedicated assurance CI job; Poseidon checked against published circomlibjs vectors (BN254) and an independent SageMath implementation of the Poseidon paper spec (BLS12-381) | | Cross-provider equivalence | The same BBS vectors run against the pure-Java, blst, and WASM providers; the blst prover backend is tested for bit-identical Groth16 output against the pure-Java prover | | Interop with other toolchains | A CI job where the pinned snarkjs 0.7.6 CLI verifies ZeroJ-produced proofs and keys, ZeroJ verifies live snarkjs proofs, and tampered proofs must be rejected; PlonK transcript checks against fixtures generated by gnark v0.14.0 | +| Independent references written from the specs | Python reproductions of the Pedersen, ElGamal, threshold DKG, HPKE share-delivery and confidential-note specs, written without reading the Java code; their vectors are replayed in Java | +| Official vectors for commitments and encryption | All 10 Zcash Sapling note-encryption vectors; the RFC 9180 A.2.1 HPKE known-answer test; Wycheproof X25519 and ChaCha20-Poly1305 vectors; differential checks against BouncyCastle's HPKE and personalized BLAKE2b | | End-to-end on-chain runs | Groth16 proofs generated in pure Java and verified by a Plutus V3 validator in lock-and-unlock transactions on Yaci DevKit | :::caution[Passing tests is not security] diff --git a/www/src/content/docs/tutorials/verify-on-cardano.mdx b/www/src/content/docs/tutorials/verify-on-cardano.mdx index f0187948..a0e818ea 100644 --- a/www/src/content/docs/tutorials/verify-on-cardano.mdx +++ b/www/src/content/docs/tutorials/verify-on-cardano.mdx @@ -371,8 +371,8 @@ bigger picture. deprecated in favour of the same operations on `Tx`; this tutorial uses `ScriptTx` because it's the path ZeroJ's end-to-end tests run against Yaci DevKit. -Verifying this two-input proof inside the validator costs roughly 2.8 billion CPU steps and -212,000 memory units, measured in the JuLC VM. More public inputs cost more, because each one +Verifying this two-input proof inside the validator costs roughly 2.2 billion CPU steps and +168,000 memory units, measured in the JuLC VM. More public inputs cost more, because each one adds a scalar multiplication. ## A valid proof is not authorization @@ -738,7 +738,7 @@ validator below computes `spendRef` instead of reading it. -Checking the proof costs about 3.0 billion CPU steps and 263,000 memory units in the JuLC VM, +Checking the proof costs about 2.34 billion CPU steps and 212,000 memory units in the JuLC VM, a little more than the bare verifier because of the extra public input and the hash. Test a validator like this with failing cases as well as the happy path. For this one we checked, in the JuLC VM, that each of these is rejected: the same proof on another UTxO, a tampered datum diff --git a/www/src/content/docs/use-cases/account-recovery.mdx b/www/src/content/docs/use-cases/account-recovery.mdx index 03fc1fa3..c77708cc 100644 --- a/www/src/content/docs/use-cases/account-recovery.mdx +++ b/www/src/content/docs/use-cases/account-recovery.mdx @@ -125,7 +125,7 @@ on-chain check affordable. | Local dev setup | About 6 min on a 12-core, 128 GB machine; about 9.6 GB key bundle on disk | | Prove | About 1.5 min on that machine; about 2.6 min on an ordinary 16 GB machine | | Verify off-chain | Under 1 s | -| Verify on-chain | About 2.8×10⁹ CPU steps, under the 10×10⁹ per-transaction limit | +| Verify on-chain | About 2.2×10⁹ CPU steps, under the 10×10⁹ per-transaction limit | These figures come from the demo's CLI documentation and ZeroJ's prover-memory work, and they depend on hardware. Proving a circuit this size in commodity memory relies on the memory-mapped proving key diff --git a/www/src/content/docs/use-cases/confidential-payroll.mdx b/www/src/content/docs/use-cases/confidential-payroll.mdx new file mode 100644 index 00000000..ed8103bd --- /dev/null +++ b/www/src/content/docs/use-cases/confidential-payroll.mdx @@ -0,0 +1,224 @@ +--- +title: Confidential payroll +description: Pay salaries on Cardano without publishing them, while the tax authority reads every salary from the chain and the employer can't under-report one. +sidebar: + order: 11 +--- + +import SinceNotice from '../../../components/SinceNotice.astro'; +import PayrollWalkthrough from '../../../components/walkthrough/PayrollWalkthrough.astro'; + +Paying salaries on a public ledger is fast and cheap, but it publishes everyone's pay to everyone: +colleagues, competitors and anyone curious. Hiding the amounts fixes that, and creates a new +problem. The tax authority, and often an auditor or a regulator, must still see every salary, and +they shouldn't have to take the employer's word for it. An employer that reports a smaller number +than it paid shouldn't be able to. + +This demo pays salaries as **confidential notes**: the chain stores the amount sealed, the employee +can open their own payslip, and the tax authority can read every salary. A zero-knowledge proof +makes the tax authority's copy match the real amount. + + + + + +## The zero-knowledge idea + +**With each pay run the employer proves "every salary note I'm creating hides some amount, and the +copy of that amount encrypted to the tax authority's registered key is the same amount", without +revealing any salary.** + +A salary note has three parts: + +- **A commitment.** A Pedersen commitment is a single curve point that hides a number, like a sealed + envelope. Everyone can see it, nobody can read it, and nobody can later claim it held a different + number. See [Commitments & encryption](/learn/commitments-and-encryption/). +- **The amount for the tax authority.** The amount is encrypted with exponential ElGamal to the tax + authority's public key. Decrypting ElGamal ends in a search over small numbers, so the 64-bit + amount is split into two 32-bit pieces, called **limbs**: `amount = limb0 + 2³²·limb1`. Each limb + is encrypted separately. +- **Sealed openings.** The opening is the amount plus the random blinding that hides it. It is + encrypted once for the employee and once for the tax authority. Each reader decrypts their copy + with a **viewing key**, a key that only reads notes and can't spend them. + +The proof ties the first two together. Without it, an employer could commit to 5,000 and encrypt +3,000 for the tax authority. With it, the ledger refuses to mint a salary note unless the limbs +recombine to the committed amount. The openings are a convenience for readers: anyone who opens one +checks it against the commitment, so a wrong opening is detected, not trusted. + +## What stays private, what's public + +| Value | Employer | Employee | Tax authority | Public | +|---|---|---|---|---| +| Each salary amount | Knows it | Their own, from their payslip | Every one, from the limbs | Hidden | +| Blinding (the random part of the commitment) | Knows it | Their own, from their payslip | From its copy of the opening | Hidden | +| Employee's viewing key | No | Yes | No | No | +| Tax authority's secret key | No | No | Yes | No | +| Note owner (the employee's key hash) | Yes | Yes | Yes | **Public** | +| Commitment, limb ciphertexts, sealed openings | Yes | Yes | Yes | **Public**, but unreadable | +| Issuance proof | Yes | Yes | Yes | **Public** | +| Tax authority's public key | Yes | Yes | Yes | **Public**, in the registry | + +Owners are public in this demo, so the transfer graph (who paid whom) is visible. The amounts are +not. + +## How it works + +1. **Register the tax key.** The tax authority publishes its keys in an on-chain registry, with + zero-knowledge proofs that it holds the matching secret keys. The payroll ledger reads the key + from the registry, so the employer can't substitute one it controls. +2. **Pay run.** The employer builds one note per salary, one or two salaries per transaction, and + proves the limb relation for each. The ledger validator verifies the proof against the + commitments and limbs in the new notes' datums and the key in the registry. +3. **Payslips.** Each employee scans the chain with their viewing key, opens their note and checks + that the opening recomputes the commitment. A note that is theirs but won't open is reported, not + ignored. +4. **Spend.** An employee can transfer part of a salary to a colleague, or cash out at the employer + for a public amount. Both are proved: the amounts balance, and every new note's limbs are + encrypted to the current tax key. +5. **Tax view.** The tax authority decrypts the limbs of every note in the ledger's mint history, + including notes already spent, and totals them per employee. Each amount is + **proof-enforced**. + +## The circuit + +This is the demo's `NoteIssueProof` simplified to a single salary. The demo version handles one or +two notes per pay run with `@CircuitParam` arrays, and keeps the limb relation in a shared +`AuditLimbs` helper. + +```java title="SalaryNoteProof.java" +import org.zeroj.circuit.annotation.*; +import org.zeroj.circuit.lib.zk.ZkElGamal; +import org.zeroj.circuit.lib.zk.ZkElGamalPublicKey; +import org.zeroj.circuit.lib.zk.ZkPedersenCommitment; + +import java.math.BigInteger; + +@ZKCircuit(name = "salary-note", version = 1) +public class SalaryNoteProof { + private static final BigInteger TWO_32 = BigInteger.ONE.shiftLeft(32); + + @Prove + void prove(ZkContext zk, + @Public ZkField noteU, @Public ZkField noteV, // the note's commitment + @Public ZkField pkU, @Public ZkField pkV, // the tax key, from the registry + @Public @FixedSize(8) ZkArray audit, // limb 0 then limb 1: A.u, A.v, B.u, B.v + @Secret @UInt(bits = 64) ZkUInt amount, + @Secret @UInt(bits = 252) ZkUInt blinding, + @Secret @UInt(bits = 32) ZkUInt limb0, + @Secret @UInt(bits = 32) ZkUInt limb1, + @Secret @UInt(bits = 252) ZkUInt k0, + @Secret @UInt(bits = 252) ZkUInt k1) { + // The note's commitment opens to (amount, blinding) + ZkPedersenCommitment.commit(zk, amount, blinding).assertAffineEquals(zk, noteU, noteV); + + // The two 32-bit limbs recombine to the same amount + limb0.asField().add(limb1.asField().mul(zk.constant(TWO_32))).assertEqual(amount.asField()); + + // Each limb is an ElGamal encryption to the tax key, matching the public ciphertexts + var taxKey = ZkElGamalPublicKey.fromVerifierFixedPublic(zk, pkU, pkV); + ZkElGamal.encrypt(zk, limb0, k0, taxKey) + .assertAffineEquals(zk, audit.get(0), audit.get(1), audit.get(2), audit.get(3)); + ZkElGamal.encrypt(zk, limb1, k1, taxKey) + .assertAffineEquals(zk, audit.get(4), audit.get(5), audit.get(6), audit.get(7)); + } +} +``` + +Every public input comes from data the validator can see: the commitment and the limbs from the new +note's datum, and the key from the registry entry. The blinding is a full 252-bit secret, and each +limb uses its own fresh 252-bit randomness, as the ElGamal profile requires. + +The demo's transfer proof (`note-transfer`) adds the balance rule, input = output 1 + output 2, with +`ZkPedersen.assertBalanced`, and the same limb relation for both new notes. + +## On Cardano + +The demo deploys one `NoteLedger` multi-validator for payroll, with token `SAL` and proved issuance +switched on. In this mode the plain `Issue` redeemer is refused, so `SAL` can't be minted without +a proof. A `ProvedIssue` must: + +- carry a `NoteIssueProof` that verifies over the new notes' commitments, the registry key and their + limbs, taken from the transaction itself; +- use pairwise-distinct handles `A` across every limb ciphertext in the transaction, which catches + exact reuse of encryption randomness within the transaction (reused randomness would reveal the + difference between two limbs); +- place each note at the ledger's exact address, with the exact datum shape and exactly one token; +- be signed by the employer. + +Transfers and cash-outs use the same ledger's `Transfer` and `Redeem` paths, also proved, and require +the note owner's signature. + +| Transaction (demo) | Circuit size | Script budget (steps) | Fee | +|---|---|---|---| +| Pay run, one salary | 15,890 constraints | 50.5% (JuLC VM) | — | +| Pay run, two salaries | 31,773 constraints | 71.3% (Yaci DevKit) | 1.111 ADA | +| Transfer | 34,184 constraints | 75.8% (Yaci DevKit) | 1.163 ADA | +| Cash-out | 18,366 constraints | 57.8% (Yaci DevKit) | 0.984 ADA | + +Budgets are shares of the per-transaction step limit, from zeroj-usecases ADR-0007 (r3). Fees were +measured on Yaci DevKit with mainnet protocol parameters after the demo's fee optimization (commit +`814b2f0`). The demo is pinned to a ZeroJ snapshot from before ZeroJ PRs #85 and #86, which lowered +the cost of the on-chain Groth16 verifier, so current ZeroJ should come in somewhat lower. + +A valid proof is not authorization. The ledger also checks the employer's signature, the owner's +signature on spends, the registry reference input and the exact output shape. See +[Application security](/guides/verifying/application-security/). + +## Security considerations + +- **Supply is still trusted.** The proof stops the employer under-reporting what it pays. It doesn't + stop the employer paying salaries that don't exist, or paying nobody. Payroll truth outside the + chain is still the employer's. +- **Openings are only length-checked on-chain.** A validator can't decrypt a sealed opening, so a + garbage payslip is accepted. The employee sees an unopenable note, and should treat that as + evidence against the sender. The tax authority's amount comes from the proved limbs, so it is + unaffected. +- **The tax key is trusted for confidentiality.** Whoever holds the tax authority's secret key reads + every salary, past and future. Key rotation stops new notes using a retired key, but doesn't hide + old ones. +- **Demo custody.** The demo server holds every wallet's spending and viewing keys and the tax + authority's secrets, and scans the chain for everyone. A real deployment scans inside each user's + own wallet and never ships viewing keys to a server. +- **Unreviewed assumptions.** The confidential-note profile's assumptions A1–A3 (ZeroJ ADR-0055) + and the demo's protocol haven't had external review. +- **Trusted setup.** The demo uses a single-party development setup, so whoever ran it could forge + proofs. Production keys need a multi-party ceremony + ([Trusted setup, explained](/learn/trusted-setup/)). +- **Not audited.** This is a blueprint of a protocol pattern, not a production payroll system. + +## Try it + +:::note[The demo isn't merged yet] +The payroll demo is in zeroj-usecases +[PR #9](https://github.com/bloxbean/zeroj-usecases/pull/9), which is still open. Until it is merged, +use the branch +[`feat/confidential-notes-m3`](https://github.com/bloxbean/zeroj-usecases/tree/feat/confidential-notes-m3/pedersen-commitments). +It builds against a ZeroJ development snapshot. +::: + +With Yaci DevKit running (see [Run the demos](/use-cases/overview/#run-the-demos)) and Java 25: + +```bash +git clone -b feat/confidential-notes-m3 https://github.com/bloxbean/zeroj-usecases +cd zeroj-usecases +./gradlew -p pedersen-commitments bootRun -PwithFrontend +# open http://localhost:8093 and choose "Confidential payroll" +``` + +The first start runs development setups for every circuit and takes several minutes; later starts +reuse the cached keys. In the payroll tab, pay a salary, open payslips, transfer and cash out, and +watch the tax authority's table fill in. Then try the cheats: under-report a salary (no proof +exists), send a garbage payslip (unopenable for the employee, still readable by the tax authority) +and use the tax authority's key after a rotation (refused). + +## Related + +- [Commitments & encryption, explained](/learn/commitments-and-encryption/) +- [Choose how to disclose](/selective-disclosure/): payroll is one point on the map +- [Share with chosen readers](/selective-disclosure/share-with-chosen-readers/) and + [Encrypt for an auditor](/selective-disclosure/encrypt-for-an-auditor/) +- [Confidential notes guide](/guides/confidential/confidential-notes/) and + [ElGamal guide](/guides/confidential/elgamal/) +- [Confidential loyalty points](/use-cases/confidential-points/): the same ledger with *trusted* + issuance, where the under-report succeeds and is only flagged diff --git a/www/src/content/docs/use-cases/confidential-points.mdx b/www/src/content/docs/use-cases/confidential-points.mdx new file mode 100644 index 00000000..cc02a432 --- /dev/null +++ b/www/src/content/docs/use-cases/confidential-points.mdx @@ -0,0 +1,224 @@ +--- +title: Confidential loyalty points +description: Customers hold and move loyalty points with hidden amounts on Cardano, wallets recover their balances from chain data, and an auditor can still read every amount. +sidebar: + order: 13 +--- + +import PointsWalkthrough from '../../../components/walkthrough/PointsWalkthrough.astro'; +import SinceNotice from '../../../components/SinceNotice.astro'; + +Put a loyalty programme on a public chain and every customer's balance, every gift to a friend and +every purchase becomes public. Anyone can see that Alice holds 1,000 points, sent 700 to Bob and +that Bob spent 120 at the shop. Hiding the amounts fixes that, but it creates a new problem. The +retailer still has to account for the points it owes, and a regulator or auditor may need to see +every amount. Nobody should have to trust a database that the retailer runs. + +This page follows a demo in which amounts are hidden from the public. Holders recover their own +balances from the chain, and a designated auditor reads every amount. For notes created by a +transfer or a redemption, a proof guarantees that what the auditor reads is the real amount. + + + + + +## The zero-knowledge idea + +**Each holding is a _note_ on-chain: a sealed amount that the owner and the auditor can open, and +that a proof keeps honest when it moves.** + +A note has three parts: + +- **A Pedersen commitment** `C = v·G + r·H` to the amount `v` with a random blinding `r`. It hides + the amount, and the owner can't later claim a different one. Commitments add up, so a proof can + show that a spent note equals the notes it creates. See + [Commitments & encryption](/learn/commitments-and-encryption/). +- **Sealed openings.** The opening `(v, r)` is encrypted on-chain twice: once to the owner's + viewing key and once to the auditor's. Each sealed copy is an 89-byte *delivery*. A reader accepts + an opening only if it recomputes the commitment. +- **Audit limbs.** The amount is also split into two 32-bit halves, and each half is encrypted to the + auditor's ElGamal key. The transfer proof shows that these limbs encrypt exactly the committed + amount, so the auditor's view is enforced, not just delivered. + +Moving points is a proof: "the note I spend holds exactly as much as the two notes I create, and +each new note's limbs encrypt its amount". The verifier sees only commitments and ciphertexts. + +## What stays private, what's public + +| Value | Who can see it | Why | +|---|---|---| +| Amount of each note | Owner and auditor | Hidden from the public by the commitment | +| Blinding `r` | Owner and auditor | Part of the opening; inside the deliveries | +| Viewing keys and spending keys | Their holder only | Open deliveries; sign spends | +| Auditor's ElGamal secret key | Auditor only | Decrypts the limbs | +| Commitment `(u, v)` | Public | Stored in the note datum | +| Owner (key hash) | Public | The ledger checks the owner's signature on a spend | +| Deliveries and audit limbs | Public, but unreadable without a key | Stored in the note datum | +| Redemption price | Public | The shop is paid a visible amount | +| Auditor's public keys and generation | Public | Published in the registry | + +Amounts are hidden; the transfer graph is not. Anyone can see that Alice's note was spent in the +same transaction that created a note owned by Bob. + +## How it works + +1. **Register the auditor.** The auditor publishes an ElGamal public key and a viewing key in a + registry UTxO that holds a one-of-a-kind token. The registry validator verifies a proof that the + auditor holds each secret key. Rotating the keys bumps a generation number. +2. **Issue.** The retailer creates a note for Alice: a commitment to 1,000, deliveries for Alice + and the auditor, and the auditor limbs. For points, issuance is *trusted*: nothing proves that + the limbs match the commitment. +3. **Transfer.** Alice sends Bob 700. Her wallet spends her note and creates a 700 note for Bob and + a 300 note for herself, with a proof that `1,000 = 700 + 300` and that each new note's limbs + encrypt its amount under the current auditor key. +4. **Redeem.** Bob spends 120 at the shop. The price is public; a proof shows his note covers it + and returns 580 as a new hidden note. +5. **Recover.** Each wallet scans the ledger's UTxOs and opens the deliveries meant for it. No + server keeps balances. +6. **Audit.** The auditor decrypts every note's limbs, cross-checks its own delivery, and labels + each note *proof-enforced* (created by a transfer or redemption) or *issuer-claimed* (issued). + +## The circuit + +This is the core of the demo's `NoteTransferProof` (one note in, two out), with the audit-limb +helper inlined for the first output. Amounts are 64-bit, blindings and ElGamal randomness are +252-bit, and limbs are 32-bit. + +```java title="NoteTransferProof.java (core)" +// Each note's opening must produce its public commitment (u, v). +var in = ZkPedersenCommitment.commit(zk, inAmount, inBlinding); +var out1 = ZkPedersenCommitment.commit(zk, o1Amount, o1Blinding); +var out2 = ZkPedersenCommitment.commit(zk, o2Amount, o2Blinding); +in.assertAffineEquals(zk, inU, inV); +out1.assertAffineEquals(zk, o1U, o1V); +out2.assertAffineEquals(zk, o2U, o2V); + +// in = out1 + out2 as whole numbers (the gadget refuses layouts that could wrap around). +ZkPedersen.assertBalanced(zk, + List.of(ZkPedersen.Term.of(in)), + List.of(ZkPedersen.Term.of(out1), ZkPedersen.Term.of(out2))); + +// The auditor's key is a public input that the validator takes from the registry. +var key = ZkElGamalPublicKey.fromVerifierFixedPublic(zk, pkU, pkV); + +// amount = L0 + 2^32·L1, and each limb is encrypted to the auditor's key (repeated for out2). +o1L0.asField().add(o1L1.asField().mul(zk.constant(TWO_32))).assertEqual(o1Amount.asField()); +ZkElGamal.encrypt(zk, o1L0, o1K0, key).assertAffineEquals(zk, o1a0u, o1a0v, o1b0u, o1b0v); +ZkElGamal.encrypt(zk, o1L1, o1K1, key).assertAffineEquals(zk, o1a1u, o1a1v, o1b1u, o1b1v); +``` + +The full circuit has 24 public inputs: the three commitments, the auditor's key and the 16 +coordinates of the four limb ciphertexts. It compiles to 34,184 constraints. The redeem circuit, +with a public price, has 18,366. + +Why two 32-bit limbs instead of one 64-bit ciphertext? Decrypting exponential ElGamal ends in a +search for a small number. The auditor can search 2³² values quickly with a lookup table; 2⁶⁴ is out +of reach. + +## Recovering notes from the chain + +A wallet doesn't need a server to know its balance. It reads the note UTxOs at the ledger address +and hands the owner deliveries to ZeroJ's `NoteScanner` with its viewing key: + +```java title="Wallet scan" +List candidates = new ArrayList<>(); +for (var note : ledgerNotes) { // read from the chain: datum fields of each note UTxO + boolean mine = Arrays.equals(note.owner(), myKeyHash); + candidates.add(NoteScanner.Candidate.of(note.ownerDelivery(), note.u(), note.v(), mine)); +} +NoteScanner.Scan scan = NoteScanner.of(myViewingKey).scan(candidates); + +scan.opened(); // openings that recompute their commitment: spendable if the note names you +scan.unopenableOwned(); // notes that name you as owner but don't open: report these +``` + +A note counts as yours only if it names your key hash as owner **and** its delivery opens to its +commitment. A note you own but can't open is reported rather than skipped. On-chain the ledger can +only check a delivery's length, so a sender could put random bytes there; the unopenable note is +your evidence. + +The auditor works from the same chain data. It decrypts the two limbs of each note with its +ElGamal key and opens its own delivery with its viewing key, then compares the two. For a +proof-enforced note the limbs are guaranteed. For an issued note they are only the issuer's claim, +and a disagreement with the delivery is flagged. + +Scanning decrypts data that anyone can put on-chain. Run it in the user's own wallet process, not on +a shared server. The demo's server scans on its wallets' behalf for convenience. + +## On Cardano + +- **`NoteLedger`** is one JuLC multi-validator: it mints the note tokens (issue, split, receipt) and + guards the note UTxOs (transfer, redeem). It verifies the Groth16 proofs and requires the owner's + signature on a spend. It also reads the auditor key from exactly one registry reference input and + rejects limbs encrypted to a retired key. +- **Exact-address policy.** Every output under the ledger's payment credential must sit at the + ledger's exact enterprise address and hold only ADA and one note token. A note sent to a variant of + the address with a stake credential is rejected. +- **`AuditorRegistry`** holds the auditor's keys under a one-shot token, so there is only ever one + current entry. Registration and rotation verify two key-possession proofs on-chain. +- **Datum size.** A note's datum is about 0.6 KB (commitment, generation, eight limb coordinates and + two 89-byte deliveries), so each note UTxO holds about 3.5 ADA. + +Measured on Yaci DevKit for the complete transaction (zeroj-usecases ADR-0007 r3, fee figures with +mainnet protocol parameters after commit `814b2f0`): + +| Transaction | CPU steps (of per-tx limit) | Memory | Fee | +|---|---|---|---| +| Transfer (one note in, two out) | 75.8% | 13.8% | about 1.16 ADA | +| Redeem | 57.8% | 11.5% | about 0.98 ADA | +| Trusted issue (one note) | 2.1% | 4.3% | about 0.47 ADA | +| Registry init / rotate | 76.8% / 77.2% | 6.2% / 6.9% | about 1.22 / 1.23 ADA | + +The demo builds against a ZeroJ snapshot from before ZeroJ PRs #85 and #86, which reduced the +on-chain Groth16 verifier's decompression cost. These figures haven't been re-measured since. + +## Security considerations + +- **Points issuance is trusted.** The retailer chooses what to encrypt for the auditor when it + issues, and the ledger can't check it. The auditor labels such notes *issuer-claimed*. The + [confidential payroll](/use-cases/confidential-payroll/) demo uses proved issuance instead, so an + employer can't under-report a salary. +- **Deliveries are only length-checked on-chain.** A sender can give the recipient a delivery that + doesn't open. The recipient's wallet reports the note as unopenable, but the points are stuck. + The auditor's limbs are the part a proof enforces. +- **The transfer graph is public.** Owners are key hashes in the datum, so who paid whom is visible + even though the amounts aren't. +- **Key custody in the demo.** The demo server holds every wallet's keys and the auditor's keys, + and scans on their behalf. A real deployment keeps viewing keys and scanning in each user's + wallet, and the auditor's keys with the auditor. +- **Development trusted setup.** The demo's Groth16 keys come from a single-party setup. Whoever + ran it could forge proofs. See [Trusted setup, explained](/learn/trusted-setup/). +- **Unreviewed assumptions.** ZeroJ's confidential-note profile rests on assumptions (A1–A3 in + ADR-0055) about delivering the same opening to several readers, which still await external + review. Nothing here is audited. + +## Try it + +The demo is the **Confidential points** tab of the `pedersen-commitments` app in +[zeroj-usecases PR #9](https://github.com/bloxbean/zeroj-usecases/pull/9), which isn't merged yet. +The source is on the branch +[`feat/confidential-notes-m3`](https://github.com/bloxbean/zeroj-usecases/tree/feat/confidential-notes-m3/pedersen-commitments). +With Yaci DevKit running (see [Run the demos](/use-cases/overview/#run-the-demos)) and Java 25: + +```bash +git clone -b feat/confidential-notes-m3 https://github.com/bloxbean/zeroj-usecases +cd zeroj-usecases +./gradlew -p pedersen-commitments bootRun -PwithFrontend +# open http://localhost:8093 once the status shows ready +``` + +The first start compiles the circuits and runs development setups, which takes a few minutes; +later starts reuse the cached keys. In the tab, issue points to Alice, transfer to Bob and redeem. +Then try the cheats: transfer more than a note holds (no proof exists), send a garbage delivery, +under-report an issuance, encrypt limbs to a retired auditor key, or send a note to a stake-variant +address. The ledger evaluates rejected transactions locally and doesn't submit them. + +## Related + +- [Commitments & encryption, explained](/learn/commitments-and-encryption/) +- [Choose how to disclose](/selective-disclosure/) +- [Share with chosen readers](/selective-disclosure/share-with-chosen-readers/) and + [Hide a number](/selective-disclosure/hide-a-number/) +- [Confidential notes guide](/guides/confidential/confidential-notes/) and + [Pedersen commitments guide](/guides/confidential/pedersen/) +- [Confidential payroll](/use-cases/confidential-payroll/): the same ledger with proved issuance diff --git a/www/src/content/docs/use-cases/overview.mdx b/www/src/content/docs/use-cases/overview.mdx index df6ec3cb..e104af64 100644 --- a/www/src/content/docs/use-cases/overview.mdx +++ b/www/src/content/docs/use-cases/overview.mdx @@ -1,6 +1,6 @@ --- title: Use cases -description: What zero-knowledge proofs unlock on Cardano — nine worked use cases, the building block behind each, and runnable demos. +description: What zero-knowledge proofs, commitments and encryption unlock on Cardano — thirteen worked use cases, the building block behind each, and runnable demos. sidebar: order: 1 label: Overview @@ -54,12 +54,41 @@ Treat them as blueprints to learn from, not as systems for real identities, vote /> +## Confidential values + +Balances, salaries and bids kept private on a public ledger, with Pedersen commitments, ElGamal +encryption and confidential notes. These demos are new in ZeroJ 0.1.0-pre13 and live on open +[zeroj-usecases](https://github.com/bloxbean/zeroj-usecases) pull requests until they merge. + + + + + + + + ## Governance & communities