From f9d6f7fa7c60571404892becddca2efcdb63c049 Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 10 Oct 2026 15:28:38 +0800 Subject: [PATCH 01/12] build: pin ZeroJ 0.1.0-pre13-1e78c6f-SNAPSHOT (ADR-0055 merged) Local publishToMavenLocal of bloxbean/zeroj main at 1e78c6f, which adds confidential-note-jubjub-v1 (ADR-0055). Existing pedersen-commitments and private-voting tests pass unchanged. Move to the public release before merge. Co-Authored-By: Claude Opus 5.5 --- version.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.properties b/version.properties index 1dd23b2..16f7f72 100644 --- a/version.properties +++ b/version.properties @@ -11,6 +11,6 @@ version=0.1.0-pre7 # --- dependency versions --- -zerojVersion=0.1.0-pre13-8a5078a-SNAPSHOT +zerojVersion=0.1.0-pre13-1e78c6f-SNAPSHOT julcVersion=0.1.0-pre18 cclVersion=0.8.0-pre5 From 7ca179e14e5dd281106b26483ab51fca569ddfa3 Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 10 Oct 2026 15:28:38 +0800 Subject: [PATCH 02/12] docs(adr): ADR-0007 confidential notes in the Pedersen demos, ADR-0008 sealed-bid auction ADR-0007 is ZeroJ ADR-0055's milestone M3: on-chain opening delivery and D3a enforced auditor amounts for the points demo (NoteLedger), an auditor registry with on-chain-verified, context-bound possession proofs, an exact-address policy, wallets and auditors that recover notes from chain data, solvency entries with deliveries, and a confidential payroll with proof-enforced issuance (ADR-0055 Q9 (b)). ADR-0008 is a sealed-bid auction whose bids are encrypted to the auctioneer under elgamal-jubjub-v1 with a bid proof, and settled with a proof that names the earliest highest bid without publishing the losing ones. r2 of both responds to a design review (adversarial Claude reviewer F1-F17, Codex C1-C10; no P0). ADR-0006 gains an r4 note pointing to both. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0006-pedersen-commitment-demos.md | 13 +- ...07-confidential-notes-in-pedersen-demos.md | 490 ++++++++++++++++++ ...-sealed-bid-auction-enforced-disclosure.md | 273 ++++++++++ 3 files changed, 773 insertions(+), 3 deletions(-) create mode 100644 docs/adr/0007-confidential-notes-in-pedersen-demos.md create mode 100644 docs/adr/0008-sealed-bid-auction-enforced-disclosure.md diff --git a/docs/adr/0006-pedersen-commitment-demos.md b/docs/adr/0006-pedersen-commitment-demos.md index a40ef12..1e9e5a4 100644 --- a/docs/adr/0006-pedersen-commitment-demos.md +++ b/docs/adr/0006-pedersen-commitment-demos.md @@ -2,7 +2,11 @@ - **Status:** Proposed. Implementation is on `feat/pedersen-private-ballot-and-demos`. - **Date:** 2026-10-04 (r2: amended after the design review; r3: after the implementation review — - demo C is bound to an attestation period) + demo C is bound to an attestation period; r4, 2026-10-10: demo A's notes and demo C's entries + carry on-chain deliveries, see [ADR-0007](0007-confidential-notes-in-pedersen-demos.md)) +- **Superseded in part (r4):** demo A's ledger, datums and circuits are now ADR-0007's + `NoteLedger` (ZeroJ ADR-0055 M3). Demo C's attestation datum gains deliveries (ADR-0007 N6). + The rest of this ADR stands. - **Related:** - ZeroJ ADR-0051 and its specs, `pedersen-jubjub-v1` and `pedersen-jubjub-vector-v1`. - ZeroJ's reference validators `ConfidentialNoteValidator` and @@ -130,7 +134,8 @@ should re-split its note. - the number of notes. Points cannot be burned, so zero-value notes, and the min-ADA they hold, accumulate. Openings are -given to recipients off-chain; that delivery channel is out of scope. +given to recipients off-chain; that delivery channel is out of scope. (r4: openings are now +delivered on-chain; see ADR-0007.) --- @@ -305,7 +310,9 @@ exchange's process runs the single-party dev setup, which is acceptable only as binding. They deliberately have no issuance control and no business rules. Demos A and B add those. - **A sealed-bid auction.** Making it complete needs either an auctioneer who sees every bid, or - an on-chain auction state machine. It was deferred as larger than a demo. + an on-chain auction state machine. It was deferred as larger than a demo. (r4: built in + [ADR-0008](0008-sealed-bid-auction-enforced-disclosure.md), with bids encrypted to the + auctioneer under `elgamal-jubjub-v1`.) - **Demo C as a mint-only attestation, with the token at the exchange's own address.** Rejected in review. The exchange could move the token and swap the datum after proving, and it could reuse the same reserves for several attestations. diff --git a/docs/adr/0007-confidential-notes-in-pedersen-demos.md b/docs/adr/0007-confidential-notes-in-pedersen-demos.md new file mode 100644 index 0000000..97d1653 --- /dev/null +++ b/docs/adr/0007-confidential-notes-in-pedersen-demos.md @@ -0,0 +1,490 @@ +# ADR-0007: Confidential notes in the Pedersen demos — on-chain opening delivery, enforced auditor amounts, proof-enforced payroll + +- **Status:** Proposed. Implementation is on `feat/confidential-notes-m3`, stacked on + `feat/pedersen-private-ballot-and-demos` (PR #8). +- **Date:** 2026-10-10 (r2, 2026-10-10: amended after the design review; see "Revision history") +- **Related:** + - ZeroJ ADR-0055 (`confidential-note-jubjub-v1`). Its design is accepted, and milestones M0–M2, + M4 and M5a are merged (bloxbean/zeroj#82, `1e78c6f`). **This ADR is its milestone M3**, the + usecase migration. + - ZeroJ specs `confidential-note-jubjub-v1`, `elgamal-jubjub-v1` and `pedersen-jubjub-v1`, at + `1e78c6f`. + - [ADR-0006](0006-pedersen-commitment-demos.md): demos A (points) and C (solvency), which this + ADR changes. + - [ADR-0005](0005-private-ballot-homomorphic-tally.md): the DLEQ possession proof pattern. + - [ADR-0008](0008-sealed-bid-auction-enforced-disclosure.md): the sealed-bid auction, which + reuses this ADR's registry and wallet pieces. +- **Risk:** R2. These are application protocols, validators and circuit compositions over + profiles ZeroJ has already accepted and implemented. No primitive is implemented here. Every + secret operation goes through ZeroJ's public API. + +## Context + +ADR-0006 hides amounts as `pedersen-jubjub-v1` commitments, but its openings never leave the +process that made them. A recipient or auditor cannot recover a note from chain data, and the web +demo's server keeps every wallet's openings. ZeroJ ADR-0055 closes that gap with **notes**: the +commitment plus its opening encrypted on-chain to each reader (Zcash Sapling's KA, KDF and +ChaCha20-Poly1305). Its D3a additionally gives an auditor the **amount** of every note that a +proof-enforced transition creates. It does this with `elgamal-jubjub-v1` limb ciphertexts that +the transition's Groth16 proof binds to the commitment. + +ADR-0055's M3 exit criteria, which this ADR must meet: +1. On Yaci DevKit: issue, transfer and redeem, with recovery from chain data by the owner and by + the auditor. +2. Validator mutation tests: a missing auditor delivery, wrong lengths, extra deliveries. +3. A garbage delivery is reported as unopenable. +4. **(a)** The demo defines and enforces its address policy: how continuing outputs are matched + (payment credential and stake credential) and how notes are authenticated. The mutations + include an extra output under the script's payment credential with another stake credential. +5. **(b)** The wallet's prover encrypts limbs with `ElGamal.encryptWithOpening`, under a key + context built from a possession-verified registry key. It never uses the reference test's + variable-time fixture. +6. ADR-0055 note 8: the gate check runs on the application's **complete** transaction (spending + plus minting purposes), at most 80% of the per-transaction step and memory limits. + +This ADR also adds two uses of the same pieces, as the maintainer asked: +- **solvency** (demo C) with on-chain delivery of each customer's entry, which ADR-0055 lists as + optional; +- a new **confidential payroll** demo, whose issuance is proof-enforced (ADR-0055 Q9 (b)). + +## Threat model and trust assumptions + +ADR-0006's model stands. This ADR adds the following. + +| Party | Trusted for | Not trusted for | May try | +|---|---|---|---| +| Sender of a note (transfer, redeem) | Nothing | The owner's delivery, the auditor's limbs, randomness | Garbage or wrong deliveries; limbs of another amount; limbs under a retired or foreign key; reused limb randomness; an extra note at a stake-variant address | +| Points issuer | Supply (ADR-0006), **and** the audit data of issued notes (Q9 (a)) | Anything else | Issuing notes whose limbs understate the amount. This succeeds, and the auditor labels it as issuer-trusted. | +| Payroll employer (issuer) | Supply only | The audit data of issued notes (Q9 (b)) | Paying a salary while under-reporting it to the tax authority. This is refused, because no proof exists. | +| Auditor or tax authority | Its own registry entry; honest-but-curious | — | Reads every amount, which is the point. It never receives spending authority. It can stop auditing (by losing its keys), but it cannot freeze notes: a registered ElGamal key is checked on-chain to be a valid subgroup key (N1), so every spend circuit stays satisfiable. | +| Registry operator (the auditor) | Which keys it registers | — | Registering a key it does not hold, such as someone else's published key with that key's published proofs. Possession proofs are bound to the registrant, the registry and the key type (N7), so a copied proof does not verify. | +| Demo server | Everything (demo custody) | — | It holds every wallet's viewing key and scans on their behalf. **This is demo-only** and contradicts ADR-0055 D9, under which scanning runs in the user's own wallet process. The UI says so. | + +**Secret:** the viewing keys, the auditor's ElGamal secret, every opening `(v, r)`, the limb +values and their randomness `k`. + +**Untrusted inputs:** every datum, every delivery, every registry entry until its possession +proofs verify, and every reference input. + +**Assumptions:** ADR-0055's A1–A3, which are unproved and gated on external review. The demos +make no claim beyond them. + +## Decision + +### N1 — Auditor registry (`AuditorRegistry`) + +Each audited application has one registry instance: a Julc multi-validator whose hash is both +the registry token's policy and the registry's address. This follows spec §8.1's first option, +a **singleton** registry token that the registry's own script moves forward on rotation. + +- **Init (mint).** The parameter is a seed, `txId ‖ I2OSP2(index)`, as in `VoteListLib`. The + policy mints exactly one `REG` token, and only in a transaction that spends the seed. The token + goes into exactly one output, at the registry's exact enterprise address, with a well-formed + entry with `generation = 0`. The auditor named in the entry signs, and `pkProof` verifies + on-chain (below). No input under the registry's own payment credential is spent. The seed can + be spent once, so the token is unique forever. +- **Entry datum.** `Entry(auditor: B28, generation: I, pkU: I, pkV: I, pkEnc: B32, viewKey: B32, + pkProof: B192, viewProof: B192)`: + - `pkU`, `pkV`: the auditor's `elgamal-jubjub-v1` key `PK_a` as canonical affine coordinates, + which validators read; + - `pkEnc`: the same key's 32-byte encoding (spec §7.3), which wallets decode strictly; + - `viewKey`: the auditor's `confidential-note-jubjub-v1` reader key, encoded; + - `pkProof`, `viewProof`: compressed Groth16 possession proofs (`piA ‖ piB ‖ piC`) for the two + keys, under the demo's `KeyPossessionProof` circuit (N7). Each proof is bound to its key type, + to this registry's policy id and to the entry's `auditor`. +- **Rotate (spend).** All of these must hold: + - exactly one input under the registry's payment credential; + - the old entry's auditor signs, and so does the new entry's; + - exactly one output holds the token; + - that output is at the exact enterprise address, with value exactly lovelace plus the token; + - its datum has the exact shape, canonical coordinates, lengths 28/32/32/192/192, + `pkEnc ≠ viewKey`, and `generation = old + 1`; + - the new entry's `pkProof` verifies on-chain; + - no mint under the registry policy; + - the spent input holds the registry token (so a token-less output at the address cannot be + "rotated"). + + The token is never burned or duplicated, so no older entry stays unspent. That is what makes + the current generation enforceable (ADR-0055 Q7, implementation note 11). +- **Possession (Q6).** + - **The ElGamal key is checked on-chain** at Init and Rotate. The registry verifies `pkProof` + (one Groth16 verification, 7 public inputs, about 3.5e9 steps; rotation is rare) over + `[ctx(0x01), G.u, G.v, pkU, pkV, pkU, pkV]`. This discharges `R_enc`'s `PK ∈ 𝔾` obligation + on-chain (spec §9.3). It also means an auditor cannot register an identity, off-curve or + out-of-subgroup key, which would make every spend circuit unsatisfiable and freeze every note. + - **The viewing key is checked off-chain** by every sender before delivering to it (N5). A bad + viewing key costs the auditor its own D5 deliveries, nothing else. + - **Binding.** The context `ctx(type)` (N7) is computed on-chain from the key type, the + registry's own policy id and the entry's `auditor`. A proof copied from another registry, from + another registrant or from the other key type does not verify. Together with the registrant's + own signature on Init and Rotate, this binds each registration to its registrant, its registry + and this profile (ADR-0055 D2, spec §2.2). +- **Pinning.** A ledger takes the registry's policy id and token name as parameters. Which + auditor an application uses is therefore the operator's choice, fixed in the ledger's hash. The + auditor checks that the ledger names its registry. + +### N2 — The note ledger (`NoteLedger`, replacing `PointsLedger`) + +`PointsLedger` (ADR-0006 A) becomes `NoteLedger`, which has two instances: + +| Instance | Token | Issuance | Auditor | +|---|---|---|---| +| Confidential points | `PTS` | **Trusted** (ADR-0055 Q9 (a)) | Points auditor registry | +| Confidential payroll | `SAL` | **Proof-enforced** (Q9 (b)) | Tax-authority registry | + +The parameters are: +- the issuer's pkh, the token name and the issuance mode; +- the registry policy and token; +- the verification keys: transfer, redeem, and proved issuance for one and for two notes. + +**Datum:** `Note(owner: B28, u: I, v: I, generation: I, audit: [I × 8], deliveries: [B89 × 2])`. +- `audit` holds the two `elgamal-jubjub-v1` limb ciphertexts at width 32, `A.u, A.v, B.u, B.v` + for limb 0 and then limb 1 (spec §8.1). +- `deliveries` holds the owner's delivery, then the auditor's (spec §3.2). The auditor's delivery + goes to the registry entry's `viewKey`. +- `generation` is the registry generation the note was created under. Every path (Issue, + ProvedIssue, Transfer, Redeem) requires every created note's `generation` to equal the current + entry's (read from the registry reference input). The auditor uses it to pick the right + generation's keys (N5). +- The output's value is exactly lovelace plus one note token (no other asset). Its lovelace is + computed from the serialized output and the protocol's `coinsPerUTxOByte`, not hard-coded + (ADR-0055 D8). The datum is about 0.6 KB, so a note needs about 3.5 ADA. + +A validator checks the shape, the counts (8 and 2), the lengths (28, and 89 for each delivery) +and that every integer is canonical. It cannot check that a delivery decrypts (ADR-0055 D8). + +**Address policy (M3 criterion (a)):** +- A **note output** is any output whose payment credential is the ledger's script. +- In every ledger transaction (issue, transfer, redeem), **every** such output must: + - be at the ledger's **exact enterprise address**, with no stake credential; + - hold exactly lovelace and one note token, and nothing else; + - have a well-formed note datum of the current generation. + + Otherwise the transaction is refused. +- An output at a stake-variant address is therefore never silently ignored, unlike ZeroJ's + reference validator (ADR-0055 implementation note 12). It makes the whole transaction fail. +- Script inputs are counted by payment credential, as in ADR-0006, so one note is spent per + transaction under any stake variant. + +**Note authentication.** +- The note token is minted only by Issue (by the issuer, or with a proof in payroll mode) and by + Split (alongside a proved transfer). +- Every path places every token in a note at the exact address. +- A wallet therefore treats a UTxO as a note only if: + - it is at the exact ledger address; + - it holds exactly one note token of the ledger's policy; + - its datum parses. + + Anything else paid to the address is ignored (ADR-0006 P6). + +### N3 — Enforced auditor amount on transfer and redeem (ADR-0055 D3a) + +Both circuits get a new version (`NoteTransferProof` and `NoteRedeemProof`, version 2). Each +created note `o` gets: +- two secret 32-bit limbs with `L_{o,0} + 2^32·L_{o,1} = amount_o`, where `amount_o` is the + witness that opens `C_o`; +- for each limb, `ZkElGamal.encrypt(limb, k, key)` under + `ZkElGamalPublicKey.fromVerifierFixedPublic(pkU, pkV)`, with `assertAffineEquals` against the + public coordinates. + +The public inputs, in spec §8.2 order after the application's own: +- **transfer:** `in.u, in.v, o1.u, o1.v, o2.u, o2.v, PK.u, PK.v`, then o1's 8 coordinates, then + o2's. That is 24 inputs. +- **redeem:** `in.u, in.v, change.u, change.v, price, PK.u, PK.v`, then the change note's 8 + coordinates. That is 15 inputs. + +The validator fixes every one of them: +- the commitments and coordinates from the datums; +- the price from the redeemer, as in ADR-0006; +- `PK` from **exactly one** reference input holding exactly one registry token. The datum must + be an `Entry` of the exact shape; a second entry, another quantity or another shape is refused. + +**Fresh randomness.** All limb handles `A` in the transaction must be pairwise distinct (spec +§8.1). This catches exact reuse, an honest wallet's accident. Related or cross-transaction reuse +cannot be detected; it rests on the prover's random generator. + +**Layout gate.** +- The direct layout (spec §8.2) is used if and only if the complete transaction measures at most + 80% of both limits. The complete transaction is the spend plus the `Split` or `Receipt` mint. + It is measured in the Julc VM (protocol version 11 cost model) and confirmed on DevKit from the + evaluator's execution units. +- The reference validator measured 73.4% for the transfer spend alone. If the complete + transaction exceeds 80%, that transaction uses the hash-compressed layout (spec §8.3) instead. + Its public inputs are then the application's inputs, `PK.u, PK.v`, `digest_hi`, `digest_lo` + (transfer: `in, o1, o2, PK, digest_hi, digest_lo`, 10 inputs). +- The measured table goes into "Measurements" below. Until it is filled in, this decision is + open. + +### N4 — Issuance + +- **Trusted (points).** ADR-0006's `Issue` rules apply, plus N2's datum shape and address policy. + The issuer supplies the limbs and deliveries, and the auditor relies on the issuer for them. + The auditor's view labels such notes **issuer-trusted**, and flags it when the limb amount + differs from the auditor's own D5 opening. +- **Both modes** require: the issuer's signature; no input under the ledger's payment + credential (`ownInputs = 0`, which the auditor's origin label relies on); the mint entry exactly + `{token: n}`; exactly `n` note outputs, each satisfying N2 (exact address, exact value, datum + shape, current generation); and exactly one registry reference input (N3's rule). +- **Proved (payroll).** A `ProvedIssue(piA, piB, piC)` redeemer replaces `Issue`. In this mode + `Issue` is refused, and in trusted mode `ProvedIssue` is refused. In addition: + - `n ∈ {1, 2}`; + - every limb handle of every issued note is pairwise distinct (spec §8.1); + - `NoteIssueProof(n)` verifies over `u_1 … u_n`, `v_1 … v_n` (the issued commitments in + output order), `PK.u, PK.v` **from the registry reference input**, and then each note's 8 + coordinates **from its datum**, in output order. That is `2n + 2 + 8n` inputs: 12 for one + note, 22 for two. No public input comes from the redeemer. + + The circuit proves, for every issued note, the same limb relation as N3. So an employer that + supplies a wrong audit ciphertext has no proof, and its transaction is refused. That is + ADR-0055 M5a's Q9 (b) obligation. The same gate applies: a size `n` whose complete transaction + exceeds 80% is not offered. + +### N5 — Wallets, senders and auditors (host side) + +All of this uses ZeroJ's public API only. + +**Admitting a registry entry.** A sender or auditor admits an entry only if every check passes, +and fails closed otherwise: +1. `VerifiedKeyShare.verify(pkEnc, s -> s.kind() == POSSESSION && possession.verify(pkProof, + s.publicInputs()))`. This decodes strictly: canonical, in the subgroup, not the identity. +2. `ElGamalPublicKey.aggregate(List.of(share))`, giving an `NOfNKeyContext` with one key. +3. The context's key equals the datum's `(pkU, pkV)`, which is what the validator feeds the + proof. +4. `NoteReaderKey.verified(viewKey, …)` with `viewProof`. + +**Limbs.** +- Only `ElGamal.encryptWithOpening(context, limb, 32, rng)` is used (M3 criterion (b)). It draws + `k` and runs every secret multiplication on the blinded best-effort schedule, which is + ADR-0039's compatibility/offline class. +- Main code never builds limbs with variable-time `scalarMul`. +- Deliveries come from `ConfidentialNotes.seal(opening, [ownerKey, auditorViewKey], rng)`, with + `NoteOpening.random`. + +**Wallet scan.** +- For each note UTxO (N2's authentication), the wallet builds `Candidate.of(deliveries[0], u, v, + owner == myPkh)` and runs `NoteScanner.of(myViewingKey).scan(...)`. The result is the opened + notes and the **unopenable owned** notes (ADR-0055 I9). +- A note counts as the wallet's, and is offered for spending, only if it **both** opened **and** + names the wallet's own key hash as `owner`. Opening alone is not ownership: `Scan.opened()` + also lists notes whose delivery opens but whose `owner` is someone else (spec §5, "the + application's step"). Those are shown as "readable, not yours". An owned note that does not + open is shown as value the user owns but cannot spend, which is evidence of a misbehaving + sender. + +**Auditor.** For each note: +- **keys:** the auditor keeps every generation's ElGamal secret and viewing key (ADR-0055 D2, + "Rotation"), and uses the generation the note's datum records. That field is checked against + the registry when the note is created (N2). +- **which notes:** only authenticated notes (N2: exact address, exactly one note token of this + ledger). Anything else paid to the address is never admitted or decrypted. +- **amount:** `RawElGamalCiphertext.fromAffine` (strict), then `ElGamal.admit(raw, context, 32, + s -> true)`, then `decryptWithSecret` with one reusable `JubjubDiscreteLog` table at + `2^32 − 1`. The amount is `L0 + 2^32·L1`. + - The delegated verifier `s -> true` is legitimate (spec §10.1) only because the ledger verified + the transaction proof when an authenticated **proof-enforced** note was created. + - For an **issuer-trusted** note no proof was verified. Its decrypted amount is reported as + "issuer-claimed", never as enforced. This is a deliberate, labelled use of the admitted API + outside its delegated-verifier premise. +- **origin:** + - **proof-enforced** if the creating transaction spent a ledger input, or was a `ProvedIssue` + (payroll); + - **issuer-trusted** otherwise (points issuance). + + It is derived from chain data: the creating transaction's inputs, through Yaci Store. +- **cross-check:** the auditor also opens its D5 delivery. A delivery that does not open, or + whose value differs from the limb amount, is shown as a sender fault. For an issuer-trusted + note it is shown as "issuer data inconsistent". + +**Keys.** +- Viewing keys and auditor secrets are generated with `NoteViewingKey.generate` and + `ElGamalSecretKey.generate`, then kept in the server's demo custody. +- Possession proofs come from `NoteViewingKey.provePossession` and + `ElGamalSecretKey.possessionStatement()`. + +### N6 — Solvency entries carry deliveries (demo C) + +- **Datum.** `Attestation([Entry(idHash: B32, u, v, delivery: B89)] × N, auditorDelivery: B89)`. + - Each entry's `delivery` goes to the customer's viewing key. The customer gives that key to + the exchange when opening an account; it encrypts to the customer, so it needs no possession + proof. + - `auditorDelivery` delivers the **aggregate** opening `(L, Σ r_i mod l)` of `Σ C_i` to the + auditor's possession-verified viewing key. It needs `L < 2^64`, which the exchange checks + before attesting. +- **Validator.** `SolvencyVault` additionally checks each delivery's length (89) and the datum's + shape. The circuit, its verification key and its public inputs are unchanged, because + deliveries are not public inputs. +- **Customer check.** + 1. The customer scans the period's live entries and opens the delivery of the entry under its + `idHash`. + 2. It compares the opened balance with its own account record. + 3. The `idHash` "exactly once" rule (ADR-0006) is unchanged. The per-period salt still reaches + the customer off-chain, with its account statement. + + An entry under its `idHash` that does not open is reported. The opening now comes from the + chain, not from the exchange's say-so. +- **Auditor check.** The auditor computes `Σ C_i` from the chain and opens `auditorDelivery` + against it, which gives `L` with no off-chain hand-over. +- **What the auditor learns.** One aggregate per **attestation**, not per period. With several + attestations in a period the auditor learns each one's subtotal, and an attestation holding one + real customer plus zero-padding would reveal that customer's balance. The demo therefore makes + exactly one attestation per period, and the exchange must not split a period into sparse + attestations. +- **The auditor's key.** The exchange admits the auditor's registry entry (N1, N5) and encrypts + `auditorDelivery` to its `viewKey`. The vault does not read the registry. `L < 2^64` follows from + `Σ b_i ≤ R < 2^64`. + +### N7 — Key possession circuit (`KeyPossessionProof`) + +This is `elgamal-jubjub-v1` §9.2 `R_dleq` (`ZkElGamal.assertDiscreteLogEquality`) with one +application input in front, as spec §8 allows ("application circuits may embed these groups among +their own inputs"): +- **Public, in order:** `ctx`, then `DleqStatement.publicInputs()` (`X.u, X.v, P.u, P.v, D.u, + D.v`). +- `ctx(type) = OS2IP(blake2b_256(ASCII("zeroj.usecases.key-possession.v1") ‖ type ‖ registryPolicy + ‖ auditor)[0..30])`, 31 bytes, so `ctx < 2^248 < p`. `type` is one byte: `0x01` for the + `elgamal-jubjub-v1` key, `0x02` for the viewing key. `registryPolicy` is 28 bytes and `auditor` + 28 bytes. +- The circuit constrains `ctx² = sq` with `sq` a witness, so `ctx` enters a constraint and the + proof is bound to it. A public input in no constraint would not affect Groth16 verification, + and ZeroJ's native setup refuses unbound public wires. +- It is used for the possession statement `(X = G, P = D = key)` of both key types. The key + types stay distinct (ADR-0055 I6): the statement's form is shared, but `type` makes a proof for + one type useless for the other. +- A `DleqStatementVerifier` built on it verifies the proof over `[ctx] ‖ statement.publicInputs()`, + with `ctx` computed by the verifier, never taken from the prover. + +### N8 — Payroll demo + +- The employer is the payroll `NoteLedger` issuer, and the tax authority is its registry auditor. +- **Employer's pay run:** one `ProvedIssue` transaction for one or two employees. +- **Employees:** read their payslips from the chain by scanning, and transfer or cash out ("redeem + at the employer", which mints a receipt as in ADR-0006) through N3. +- **Tax authority:** reads every salary from chain data, every one proof-enforced, with totals per + employee. +- **Cheats:** + - under-report a salary to the tax authority: no proof exists; + - a garbage payslip delivery: the employee sees an unopenable note, and the tax authority still + reads the amount; + - limbs encrypted to a retired key: refused, because only the current registry entry exists. + +## Revision history + +- **r1** (2026-10-10): initial proposal. +- **r2** (2026-10-10; design review by an adversarial Claude reviewer, F1–F17, and Codex, + C1–C10; no P0): + - F1: a registered ElGamal key could be the identity or off-curve, freezing every note → its + possession proof is verified on-chain at Init and Rotate (N1). + - F7, C7: possession proofs were replayable across registrants, registries and key types → + `KeyPossessionProof` takes a bound context `ctx(type)` (N7). + - F2: proved issuance did not pin `PK`'s source and lacked distinct handles and `ownInputs = 0` + → N4 lists every rule. + - C6: decryptability was treated as ownership → the wallet also requires `owner` = its key + (N5, N-I7). + - F6: the auditor ignored generations → notes record `generation`, checked against the + registry; the auditor keeps every generation's keys (N2, N5). + - F8: delegated admission obligations stated; issuer-trusted amounts are "issuer-claimed" (N5). + - F5: the solvency auditor learns per-attestation subtotals → stated; one attestation per + period in the demo (N6). + - F17: notes hold exactly lovelace plus the token; min-ADA computed; per-path compressed + inputs listed; the source-scan pattern scoped. + - F10 (script size) stays a measurement at M3a. + +## Invariants + +| ID | Invariant | Enforced by | +|---|---|---| +| N-I1 | Every note output of every ledger transaction is at the exact ledger address, holding exactly lovelace and one note token, with the current registry generation, 8 canonical audit coordinates, and exactly 2 deliveries of 89 bytes. | `NoteLedger` (all paths) | +| N-I2 | No ledger transaction has an output under the ledger's payment credential with a stake credential. | `NoteLedger` | +| N-I3 | `PK_a` comes from exactly one registry reference input. The registry token is a singleton, and rotation increments the generation under both auditors' signatures. Every registered ElGamal key has an on-chain-verified possession proof bound to its registrant, registry and key type, so it is a valid subgroup key. | `NoteLedger`, `AuditorRegistry` | +| N-I4 | Transfer and redeem: the limbs of every created note encrypt, under `PK_a`, the amount that opens its commitment. Every public input comes from the ledger. Handles are pairwise distinct. | Circuit + `NoteLedger` | +| N-I5 | Payroll: no `SAL` is minted without a proof, over the registry's key and the datums' limbs, binding every issued note's limbs to its amount, with distinct handles. Points: no `PTS` is minted without the issuer's signature. | Circuit + `NoteLedger` | +| N-I6 | Senders encrypt limbs only with `encryptWithOpening`, and deliver only to keys of an admitted registry entry (N5). | Host code; a test checks that main code has no `scalarMul` call | +| N-I7 | A wallet counts a note as its own only after the profile's acceptance (spec §5 steps 1–7), N2's authentication **and** `owner` = its key hash. Owned notes that do not open are reported, not dropped. | `NoteScanner` + wallet | +| N-I8 | The auditor decrypts only authenticated notes, with the keys of the note's generation, and reports an amount as enforced only for proof-enforced notes. | Auditor view | +| N-I9 | Solvency entries and the attestation carry deliveries of the right length. Customers and the auditor recover from the chain. | `SolvencyVault` + host code | +| P1–P8, S1–S7 | ADR-0006's invariants, unchanged. | As in ADR-0006 | + +## Alternatives considered + +- **Possession proofs verified on-chain at registration.** Two Groth16 verifications would cost + about 8e9 steps, and Q6 allows off-chain checking. Rejected for the demo; anyone can still + verify the proofs, which are stored in the entry. +- **The issuer governs the registry.** The auditee would then control the auditor's key. + Rejected: the auditor rotates its own entry, and the operator only pins which registry a + ledger uses. +- **Notes identified by payment credential under any stake credential.** Wallets would have to + scan an open set of addresses, and stake-variant outputs could carry unchecked notes (ADR-0055 + note 12). Rejected in favour of N2's exact-address rule. +- **The hash-compressed layout everywhere.** It costs about 3.5×10^5 constraints and tens of + seconds per proof. It is used only where the direct layout fails the gate (N3). +- **Deliveries in transaction metadata.** Invisible to Plutus (ADR-0055 D8). +- **A separate payroll validator.** It would duplicate the ledger. A mode parameter on + `NoteLedger` shows Q9 (a) against Q9 (b) side by side instead. + +## Milestones + +| ID | Scope | +|---|---| +| M0 | ZeroJ snapshot `0.1.0-pre13-1e78c6f-SNAPSHOT`; the existing tests stay green. | +| M1 | This ADR and ADR-0008. | +| M2 | `AuditorRegistry`, `KeyPossessionProof`, and the key, wallet and auditor helpers. | +| M3a | `NoteLedger`, the version 2 circuits, the points migration, and the layout gate. | +| M3b | The points service and UI. | +| M4 | Payroll: issuance circuits, proved issuance, service and UI. | +| M5 | Solvency deliveries: vault, service and UI. | +| M6 | The auction (ADR-0008). | +| M7 | README, `demo.sh`, final reviews. | + +## Verification + +- **Circuit invalid witnesses** (ADR-0055 I12), mirroring ZeroJ's reference test: + - a wrong limb, or a limb at `2^32`; + - limbs swapped, or swapped between notes; + - another key; + - limbs of another amount; + - for proved issuance, an issued note with a wrong audit ciphertext. +- **Plutus VM mutations** (Julc testkit): + - ADR-0006's P1–P8; + - the audit data absent, wrong (either output), swapped between outputs, limbs swapped, not + canonical, or 7 entries; + - a delivery missing, short (88 bytes), or extra (3 deliveries); + - the registry missing, another key, a second entry, quantity 2, an extra field, the wrong + token; + - reused handles (within a note and across notes); + - **an extra output at a stake-variant script address** (criterion (a)); + - a tampered proof; + - for the registry: a second mint, a mint without the seed, rotation without either signature, + a generation not incremented, an extra token, a stake address, the wrong shape, + `pkEnc = viewKey`, a `pkProof` for another key, another registrant, another registry or the + other key type, and an identity or off-curve key; + - a created note of a stale generation, an extra asset in a note, and for proved issuance: + `PK` not from the registry, datum limbs other than the proved ones, reused handles, `n` + different from the number of note outputs, and a ledger input spent. +- **Host:** + - registry admission refuses a wrong possession proof, mismatched coordinates, a swapped proof, + and a proof copied from another registrant or registry; + - a source-scan test shows that main code calls no variable-time `JubjubPoint.scalarMul(` + (the blinded `scalarMulSecretBlindedBestEffort` is not matched); + - a note readable by the wallet but owned by someone else is not counted as the wallet's; + - the owner, the auditor and the sender recover the same amount (a differential check). +- **DevKit end to end** (`ZEROJ_YACI_E2E=true`): + - points: issue, transfer and redeem, with recovery by the owner and the auditor; a garbage + delivery is unopenable; a key rotation, after which stale limbs are refused; + - payroll: a pay run, payslips, the tax view, and the under-report refused; + - solvency: customers and the auditor recover from the chain. +- **UI:** each tab is driven through the Playwright MCP, covering the honest flows and every + cheat. + +## Measurements + +To be filled in at M3a and M4: constraints, prover time, and the Julc VM cost of the complete +transaction as a percentage of `maxTxExecutionUnits` (10e9 steps, 16.5e6 memory), for transfer, +redeem, and proved issuance with n = 1 and n = 2. + +## Production gates (not met by this demo) + +- ADR-0055's gates: external review of D2, D5–D7 and A1–A3, a scanning deployment model under + ADR-0039, and the registry design. +- Scanning inside the user's own wallet process, not on a server (ADR-0055 D9). +- Keys from an MPC ceremony, not the single-party development setup. +- Registry governance beyond "the auditor signs": key escrow, recovery and revocation policy. diff --git a/docs/adr/0008-sealed-bid-auction-enforced-disclosure.md b/docs/adr/0008-sealed-bid-auction-enforced-disclosure.md new file mode 100644 index 0000000..5b552d6 --- /dev/null +++ b/docs/adr/0008-sealed-bid-auction-enforced-disclosure.md @@ -0,0 +1,273 @@ +# ADR-0008: Sealed-bid auction with enforced bid disclosure to the auctioneer + +- **Status:** Proposed. Implementation is on `feat/confidential-notes-m3`. +- **Date:** 2026-10-10 (r2, 2026-10-10: amended after the design review; see "Revision history") +- **Related:** + - [ADR-0007](0007-confidential-notes-in-pedersen-demos.md): its `AuditorRegistry`, + `KeyPossessionProof` and key admission (N1, N5, N7) are reused here, through an auctioneer + registry instance of its own. + - ZeroJ `elgamal-jubjub-v1` (§6.1 decryption, §8 public inputs, §9.1 `R_enc`, §10.1 + admission) and ADR-0052. + - [ADR-0006](0006-pedersen-commitment-demos.md), whose "Alternatives considered" deferred this + auction as larger than a demo. +- **Risk:** R2. This is a new application protocol and a new circuit composition (the + settlement relation, D4) over the accepted `elgamal-jubjub-v1` relation. No primitive is + implemented. **D4's decryption argument is this repository's own and needs review.** See + "Escalation". + +## Context + +A commit–reveal sealed-bid auction has a known weakness: a bidder who sees it is losing, or who +regrets its bid, simply does not reveal. ADR-0006 deferred an auction because a complete one +needs either an auctioneer who sees every bid or an on-chain state machine. + +`elgamal-jubjub-v1` gives a third way. Each bid is encrypted to the auctioneer's key, and the +bid transaction's Groth16 proof shows that the ciphertext encrypts the very amount the bid is +checked against. Disclosure to the auctioneer is therefore **enforced at bid time**, and there is +no reveal phase to abandon. At settlement, the auctioneer proves who won and at what price +without publishing the losing bids. + +## Threat model and trust assumptions + +| Party | Trusted for | May try | +|---|---|---| +| Bidder | Nothing | Bid above its deposit; bid below the reserve; copy another bidder's ciphertext or proof; bid after the deadline; bid twice; withdraw its bid; fill every bid slot with sybil keys | +| Seller | Nothing beyond listing its own item | Bid on its own lot (directly, or through other keys); take the item back after a sale | +| Auctioneer | **Confidentiality of bids**: it sees every bid and is honest-but-curious. It could leak bids to a colluding bidder during bidding; this ADR does not prevent that. | Name a wrong winner or price; omit or reorder bids; settle early; never settle; bid itself | +| Anyone | — | Pay a fake lot to the address; settle or refund a lot at the wrong time; steal deposits; make one output satisfy two lots' payouts | + +**Secret:** each bid amount (from everyone except the bidder and the auctioneer), each bid's +encryption randomness, and the auctioneer's ElGamal secret. + +**Public by design:** the bidders, the bid count, the common deposit, the reserve, the +deadlines, the winner and the winning price. Payment is in ADA, so the price is public anyway. + +## Decision + +### D1 — The lot: one state UTxO (`SealedBidAuction`) + +A Julc multi-validator whose hash is both the lot-token policy and the lot address. + +**Parameters:** +- `registryPolicy`, `registryToken`: the **auctioneer's** registry instance (ADR-0007 N1). It is + separate from any note ledger's auditor registry. +- `minWindow`: the minimum `settleBy − biddingEnds`, in milliseconds; +- `minLotAda`: the minimum ADA a lot output carries, in lovelace; +- the verification keys: one for the bid relation (D3), and one each for settlement with 1, 2 + and 3 bids (D4). + +**Datum:** `Lot(seller: B28, auctioneer: B28, itemPolicy: B28, itemName: B, lotAda: I, +deposit: I, reserve: I, biddingEnds: I, settleBy: I, pkU: I, pkV: I, generation: I, +bids: [Bid(bidder: B28, A.u: I, A.v: I, B.u: I, B.v: I)])`. +- `deposit` and `reserve` are whole ADA, with `2 ≤ reserve ≤ deposit < 2^32`. `lotAda` is in + lovelace, `lotAda ≥ minLotAda`. +- `biddingEnds` and `settleBy` are POSIX milliseconds, with `settleBy − biddingEnds ≥ minWindow`. +- `(pkU, pkV, generation)` is the auctioneer's key and registry generation, copied from the + registry at Open and fixed for the lot's lifetime. +- `bids` holds at most **3** bids. That fixes the settlement circuits and the budget. + +**An authentic lot** is an output at the script's exact enterprise address whose value is +exactly: +- lovelace; +- one unit of `itemPolicy.itemName`; +- exactly one token under the script's policy, the **lot token** `T`, with quantity 1. + +Wallets and the auctioneer consider only authentic lots. Every spending action requires the +spent input to be authentic, and every action burns or carries forward that same `T`. + +**Payout outputs.** Every payout goes to the recipient's **exact enterprise address**, +`(PubKeyCredential(pkh), no stake)`. It carries the inline datum `Payout(T)`. `T` is unique to +one lot (below), so one output can never satisfy two lots' payouts, even across differently +parameterized auction scripts in one transaction. Within one lot the recipients are distinct +(seller, auctioneer and bidders, below). + +**Time.** A rule "ends at or before t" requires a **finite** upper bound `≤ t`, and "starts at or +after t" a **finite** lower bound `≥ t`. An infinite bound fails. + +| Action | Purpose | Conditions | +|---|---|---| +| **Open** | mint |
  • No input under the script's payment credential.
  • The mint entry under the policy is exactly `{T: 1}`, where `T = blake2b_256(refBytes(i))` for some input `i` the transaction spends. So `T` is one-shot and globally unique.
  • Exactly one output under the script's credential. It is an authentic lot holding `T`, with exactly `lotAda` lovelace and `bids = []`.
  • `seller` signs. `seller`, `auctioneer` and `itemPolicy` are 28 bytes; `itemPolicy` is not the script's policy; `itemName` is at most 32 bytes.
  • The parameter ranges above hold.
  • The transaction ends at or before `biddingEnds`.
  • Exactly one registry reference input (ADR-0007 N3's rule). Its entry's `auditor`, `pkU`, `pkV` and `generation` equal the datum's `auctioneer`, `pkU`, `pkV` and `generation`.
| +| **Bid** | spend |
  • The spent input is an authentic lot, and the only input under the script's credential.
  • No mint under the policy.
  • The transaction ends at or before `biddingEnds`.
  • The appended bid's `bidder` signs. It is 28 bytes and differs from `seller`, `auctioneer` and every earlier bidder.
  • Fewer than 3 bids before this one.
  • Exactly one output under the script's credential: an authentic lot with the same `T`, the same item, and lovelace exactly `deposit · 10^6` more.
  • Its datum equals the old datum with exactly this `Bid` appended. It is rebuilt and compared.
  • Coordinates are canonical, `A.u ≠ 0`, and `A` differs from every earlier bid's `A`.
  • `BidProof` verifies over `[OS2IP(bidder), deposit, reserve, pkU, pkV, A.u, A.v, B.u, B.v]` (D3).
| +| **Settle** | spend + burn |
  • The spent input is an authentic lot, and the only script input.
  • The mint entry is exactly `{T: −1}`, and there is no output under the script's credential.
  • The transaction starts at or after `biddingEnds` and ends at or before `settleBy`.
  • `n = len(bids) ≥ 1`, with `w` and `p` from the redeemer, `1 ≤ w ≤ n` and `reserve ≤ p ≤ deposit`.
  • `SettleProof(n)` verifies over `[w, p, pkU, pkV, A_1, B_1, …, A_n, B_n]` from the datum (D4).
  • Payouts, each tagged `Payout(T)`: to `bids[w].bidder` the item and at least `lotAda + (deposit − p) · 10^6` lovelace; to `seller` at least `p · 10^6`; to every other bidder at least `deposit · 10^6`.
| +| **NoBids** | spend + burn |
  • The spent input is authentic and the only script input.
  • The mint entry is `{T: −1}`, and there is no script output.
  • The transaction starts at or after `biddingEnds`, and `bids = []`.
  • `seller` signs.
  • A payout to `seller` with the item and at least `lotAda`.
| +| **Refund** | spend + burn |
  • The spent input is authentic and the only script input.
  • The mint entry is `{T: −1}`, and there is no script output.
  • The transaction starts at or after `settleBy`.
  • A payout to `seller` with the item and at least `lotAda`.
  • A payout to every bidder of at least `deposit · 10^6`.
  • Anyone may submit it.
| + +**Why the payouts are sound:** +- `T` is unique, and every payout output carries `Payout(T)` at an exact address. +- The lot's recipients are distinct. +- So each required payout is a different output, and none is shared with another lot. +- The payouts sum to the lot's value: `lotAda + n · deposit` against + `(lotAda + deposit − p) + p + (n − 1) · deposit`. The transaction fee comes from the + submitter's own inputs. +- `lotAda` travels with the item, so the output holding the item always has enough ADA. + +### D2 — Notation and encodings + +- Bids are `elgamal-jubjub-v1` ciphertexts at width 32 under `PK = (pkU, pkV)`. +- `OS2IP(bidder)` is the 28-byte key hash as an integer, below `2^224 < p`. It is computed on-chain + with `byteStringToInteger` (big-endian). +- All coordinates are canonical (`< p`). The validator checks this before any proof. + +### D3 — Bid relation (`BidProof`) + +- **Public, in order:** `bidderInt, deposit, reserve, PK.u, PK.v, A.u, A.v, B.u, B.v`. The + application's inputs come first, then the key group and the ciphertext group in + `elgamal-jubjub-v1` §8 order. +- **Witness:** `bid` (32 bits) and `k` (252 bits). +- **Constraints:** + - `ZkElGamal.encrypt(bid, k, fromVerifierFixedPublic(PK))` equals `(A, B)` (`R_enc(32)`); + - `reserve ≤ bid ≤ deposit`; + - `bidderInt² = sq`, with `sq` a witness. + + The last constraint puts `bidderInt` into a constraint so that the proof is bound to it. A + public input that appears in no constraint does not affect Groth16 verification, and ZeroJ's + native setup refuses such a wire. Without the binding, another bidder could copy a ciphertext + together with its proof. +- **Verifier obligations** (spec §9.3): + - `PK ∈ 𝔾`: the auctioneer registry verifies the key's possession proof on-chain (ADR-0007 N1), + and Open takes the key from the registry; + - every coordinate is canonical. +- **What it guarantees:** + - `A = [k]·G`, so `A ∈ 𝔾`. With `A.u ≠ 0`, `A` is not the identity: a bid with `k ≡ 0` would + otherwise make the lot unsettleable, because D4's key rule needs `u ≠ 0`. + - The auctioneer can decrypt every accepted bid, and the bid lies in `[reserve, deposit]`. + +### D4 — Settlement relation (`SettleProof(n)`, `n ∈ {1, 2, 3}`) + +- **Public, in order:** `w, p, PK.u, PK.v`, then for each bid `i = 1 … n` in datum order: + `A_i.u, A_i.v, B_i.u, B_i.v`. That is `4 + 4n` inputs. These are a key group and `n` + ciphertext groups (spec §8), not `R_enc` statements. +- **Witness:** `sk` (252 bits) and `m_1 … m_n` (32 bits each). +- **Constraints:** + 1. **Decryption.** For each `i`, `ZkElGamal.encrypt(m_i, sk, fromVerifierFixedPublic(A_i))` + is asserted equal to `(PK, B_i)`. The `ZkUInt` decomposition of `sk` is minted once and + cached, so one decomposition drives every multiplication. By `R_enc`'s definition (spec + §9.1, with key `A_i` and randomness `sk`) this states exactly: + - `[sk]·G = PK`, so `sk` is the auctioneer's secret mod `l`. `sk ≥ l` is harmless, because + `A_i ∈ 𝔾`; + - `[m_i]·G + [sk]·A_i = B_i`, that is, `B_i − [sk]·A_i = [m_i]·G`; + - `m_i < 2^32`. + + That is ElGamal decryption (spec §6.1, `M = B − [sk]·A`) of bid `i` to `m_i`. `m_i` is + unique given `(A_i, B_i)`, because `G` has prime order `l > 2^32`. + 2. **Winner.** `w ∈ {1, …, n}`, as a one-hot selection, and `m_w = p`. + 3. **First price, earliest bid wins ties.** `m_i < p` for `i < w`, and `m_i ≤ p` for `i > w`. +- **Verifier obligations:** + - each `A_i ∈ 𝔾 ∖ {𝒪}`, from D3 and the Bid check; + - `PK ∈ 𝔾`, from the registry; + - canonical coordinates. +- **What it guarantees:** + - the winner holds the highest bid, and the earliest one on a tie; + - `p` is that bid. + - The proof itself discloses only `w` and `p`. The order rule implies `m_i < p` for earlier + bids and `m_i ≤ p` for later ones. +- **Cost estimate.** Each bid needs one `R_enc` instance, about 6.6k–6.9k rows, so about 22k + constraints at `n = 3`. On-chain, 16 public inputs at `n = 3`; the cost is measured in M6. + +### D5 — Wallets and the auctioneer (host side) + +- **Authentication first.** Wallets and the auctioneer read only authentic lots (D1). Anything + else at the address, such as a token-less "lot" with chosen ciphertexts, is never decrypted or + settled. `ElGamal.admit(…, s -> true)` (delegated admission, spec §10.1) is legitimate only for + the bids of an authentic lot: the validator verified each bid's proof when the bid was + appended. +- **Seller and bidders.** + - They admit the auctioneer's registry entry exactly as ADR-0007 N5 does. They require the + lot's `(auctioneer, pkU, pkV, generation)` to equal the current entry's. + - If the auctioneer has rotated since Open, wallets refuse to bid: they fail closed. + - **Operational rule:** the auctioneer does not rotate while it has open lots. +- **Bidder.** Encrypts its bid with `ElGamal.encryptWithOpening(context, bid, 32, rng)`. It never + uses the variable-time `scalarMul`. +- **Auctioneer.** + - Keeps the secret for every generation, and uses the one the lot records. + - For each bid it runs `admit`, then `decryptWithSecret` with `maxPlaintext = 2^32 − 1` and one + reusable `JubjubDiscreteLog` table. An admitted width-32 ciphertext carries that bound, and + `ElGamal` refuses any smaller one. It then checks `reserve ≤ m ≤ deposit`. + - It computes the winner and the price, and proves D4. + +## Invariants + +| ID | Invariant | +|---|---| +| A-I1 | Each lot is one authentic UTxO with a one-shot, globally unique token `T`, at the exact enterprise address, from Open until `T` is burned. | +| A-I2 | A bid is accepted only before `biddingEnds`, signed by a new bidder (not the seller or the auctioneer), with exactly `deposit` ADA added and the datum extended by exactly that bid. | +| A-I3 | Every accepted bid encrypts, under the lot's key, an amount in `[reserve, deposit]`, bound to its bidder (D3). | +| A-I4 | Settlement happens only in `[biddingEnds, settleBy]`, covers **every** bid in the datum, names the earliest highest bid and its amount, and pays the seller, the winner and every loser through outputs tagged with `T`. | +| A-I5 | If there is no settlement by `settleBy`, anyone can return every deposit and the item. | +| A-I6 | No transaction discloses a losing bid amount; settlement discloses only `w` and `p`. The bid ciphertexts are permanent: whoever holds the lot's auctioneer secret, now or later, can read every bid. There is no forward secrecy. | +| A-I7 | One lot per transaction; payouts are tagged with the lot's unique token; within a lot, recipients are distinct. | + +## Limitations (stated, not prevented) + +- **Auctioneer trust.** It sees all bids during bidding and could leak them. Removing that trust + needs threshold decryption (ZeroJ ADR-0053) or a timed release, which is out of scope. Together + with the seller, it has a free option not to settle: bidders then wait until `settleBy` for + Refund. +- **Bid capacity and sybils.** The first three distinct keys fill a lot. One party with three keys + can occupy every slot at the reserve, and a seller or auctioneer can bid through keys other + than its own. Real use would need an allowlist or a bid bond. The demo states this. +- **Rotation freezes open lots** for compliant wallets (D5). + +## Escalation (external review) + +- **D4 composes `R_enc`'s gadget with the auctioneer's secret as the randomness and a bid handle + as the key.** This is algebraically the decryption relation, and both design reviewers verified + that the gadget supports it: the key path, the shared cached decomposition, and the `u ≠ 0` + rule. ZeroJ's specs define no named decryption relation (ADR-0052 D8 put on-chain decryption + shares out of scope). The argument is this repository's own and needs external review. + +## Alternatives considered + +- **Commit–reveal with forfeited deposits.** A bidder can still refuse to reveal, at the cost of + its deposit, and the auction then ends with a wrong price. +- **Bids as Pedersen commitments with D5 deliveries.** Deliveries cannot be enforced (ADR-0055 + D3 is deferred), so a bidder could post an unreadable bid. +- **Publishing decryption shares at settlement.** Simple, but it reveals every losing bid. +- **A Vickrey (second-price) auction.** It needs `p = ` the second-highest bid. That is a small + change to D4, deferred to keep the demo small. +- **Payouts matched by payment credential only.** Rejected (review C1, F14): the submitter could + pick the stake credential, and one output could satisfy two lots. + +## Revision history + +- **r1** (2026-10-10): initial proposal. +- **r2** (2026-10-10; design review by an adversarial Claude reviewer, F1–F17, and Codex, + C1–C10; no P0; both verified D4): + - C1, F14: payouts are tagged with `Payout(T)` and paid to exact enterprise addresses. + - C2, F9: lot authentication and the per-action rules are written out. + - C3: Open spends no script input. + - C4, F4: decryption uses the `2^32 − 1` bound. + - C5, F3: `lotAda`, computed from the serialized output, replaces the fixed 2 ADA. + - C8, F6: the generation is pinned; the operational rule against rotation is added. + - C9, F11: finite bounds and `minWindow`. + - C10, F13: the auctioneer is refused as a bidder; sybil capacity is listed under limitations. + - F12: on-chain range checks for `w` and `p`. + - F15: A-I6 reworded. + - F16: the auctioneer has its own registry instance. + - F1: the registry key is verified on-chain (ADR-0007 r2). + +## Verification + +- **Circuits:** + - bid: a bid above the deposit or below the reserve; a ciphertext of another amount; another + key; a proof for one bidder checked against another (the binding test); + - settle: a wrong winner, a wrong price, a later equal bid named as winner (the tie order), a + wrong `sk`, a bid omitted. +- **Plutus VM mutations:** + - Open: no consumed input matching `T`, a script input spent, two tokens, a wrong item, too + little `lotAda`, the key or generation not from the registry, the auctioneer not the entry's, + `minWindow` not met, the transaction after `biddingEnds`, bad ranges; + - Bid: late; an infinite upper bound; unsigned; by the seller; by the auctioneer; a repeated + bidder; a fourth bid; the deposit off by one lovelace; the datum not appended exactly (a + reordered or modified earlier bid); a copied handle; `A` the identity; a stake-variant + output; a token-less input; an extra asset; + - Settle: early; late; a missing, underpaid or untagged payout; a payout at a stake address; the + token not burned; `w` or `p` out of range; a proof over a subset of the bids; two lots in one + transaction; + - Refund: early, or underpaid; NoBids with bids present, or unsigned. +- **DevKit end to end:** open, three bids, settle (with the winner and price checked, and the + losers refunded); the refund path; a bid over the deposit refused (no proof); a late bid + refused. +- **UI** through the Playwright MCP. +- **Measurements**, filled in at M6: constraints, prover time, and the Julc VM cost of Bid and of + Settle (`n = 1, 2, 3`) against the 80% gate. From 3654128c8cdf6c8edeb5f7f9d410018f739fffc7 Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 10 Oct 2026 15:56:42 +0800 Subject: [PATCH 03/12] pedersen-commitments: auditor registry with on-chain possession proofs (ADR-0007 M2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AuditorRegistry is a singleton key registry: a one-shot REG token minted by spending a seed, moved forward on rotation under the old and the new auditor's signatures, so a ledger always reads the current generation (ZeroJ ADR-0055 spec §8.1). Each entry holds the auditor's elgamal-jubjub-v1 key and confidential-note viewing key, as coordinates bound on-chain to their encodings, with u != 0. Both Groth16 DLEQ possession proofs are verified on-chain at Init and Rotate (about 7.8e9 steps), bound to the key type, the registry and the registrant, so no registered key can freeze notes or be refused by honest senders, and a copied proof never registers. Host side: KeyPossession (context-bound proofs, 192-byte compressed codec), AuditorKeys, RegistryEntry, AdmittedAuditor (the only way to obtain a key context for limb encryption: ADR-0055 M3 criterion (b)), Registry (Init, Rotate, current entry), and a minimum-ADA helper. Tests: VM mutations for every shape, signature, generation, address, token, encoding and possession rule (each guard checked by reverting it), with a positive control for the identity key's valid proof; admission refusals including key-type binding in isolation and cross-registry replay. Reviewed by Claude and Codex (no P0/P1; findings fixed). Co-Authored-By: Claude Opus 5.5 --- ...07-confidential-notes-in-pedersen-demos.md | 57 ++- pedersen-commitments/build.gradle | 1 + .../usecases/pedersen/common/Plutus.java | 36 ++ .../usecases/pedersen/common/ProofBytes.java | 58 +++ .../pedersen/notes/AdmittedAuditor.java | 82 ++++ .../usecases/pedersen/notes/AuditorKeys.java | 56 +++ .../pedersen/notes/KeyPossession.java | 96 +++++ .../usecases/pedersen/notes/Registry.java | 203 ++++++++++ .../pedersen/notes/RegistryEntry.java | 75 ++++ .../notes/circuit/KeyPossessionProof.java | 41 ++ .../notes/onchain/AuditorRegistry.java | 177 +++++++++ .../pedersen/notes/onchain/ChainLib.java | 146 ++++++++ .../pedersen/notes/onchain/RegistryLib.java | 149 ++++++++ .../pedersen/notes/AuditorRegistryVmTest.java | 350 ++++++++++++++++++ .../pedersen/notes/RegistryAdmissionTest.java | 111 ++++++ 15 files changed, 1618 insertions(+), 20 deletions(-) create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/ProofBytes.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AdmittedAuditor.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorKeys.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/KeyPossession.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/Registry.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryEntry.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/circuit/KeyPossessionProof.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/AuditorRegistry.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/ChainLib.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/RegistryLib.java create mode 100644 pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorRegistryVmTest.java create mode 100644 pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryAdmissionTest.java diff --git a/docs/adr/0007-confidential-notes-in-pedersen-demos.md b/docs/adr/0007-confidential-notes-in-pedersen-demos.md index 97d1653..a6e0d73 100644 --- a/docs/adr/0007-confidential-notes-in-pedersen-demos.md +++ b/docs/adr/0007-confidential-notes-in-pedersen-demos.md @@ -80,40 +80,48 @@ a **singleton** registry token that the registry's own script moves forward on r - **Init (mint).** The parameter is a seed, `txId ‖ I2OSP2(index)`, as in `VoteListLib`. The policy mints exactly one `REG` token, and only in a transaction that spends the seed. The token goes into exactly one output, at the registry's exact enterprise address, with a well-formed - entry with `generation = 0`. The auditor named in the entry signs, and `pkProof` verifies - on-chain (below). No input under the registry's own payment credential is spent. The seed can + entry with `generation = 0`. The auditor named in the entry signs, and both possession proofs + verify on-chain (below). No input under the registry's own payment credential is spent. The seed can be spent once, so the token is unique forever. -- **Entry datum.** `Entry(auditor: B28, generation: I, pkU: I, pkV: I, pkEnc: B32, viewKey: B32, - pkProof: B192, viewProof: B192)`: +- **Entry datum.** `Entry(auditor: B28, generation: I, pkU: I, pkV: I, pkEnc: B32, viewU: I, + viewV: I, viewKey: B32, pkProof: B192, viewProof: B192)`: - `pkU`, `pkV`: the auditor's `elgamal-jubjub-v1` key `PK_a` as canonical affine coordinates, which validators read; - - `pkEnc`: the same key's 32-byte encoding (spec §7.3), which wallets decode strictly; - - `viewKey`: the auditor's `confidential-note-jubjub-v1` reader key, encoded; + - `pkEnc`: the same key's 32-byte encoding, which wallets decode strictly; + - `viewU`, `viewV`, `viewKey`: the auditor's `confidential-note-jubjub-v1` reader key, as + coordinates and encoded; + - the registry checks on-chain that each encoding is exactly its coordinates' + `pedersen-jubjub-v1` §4 encoding (`v` little-endian, top bit the parity of `u`), that both keys + have `u ≠ 0`, and that the two keys differ; - `pkProof`, `viewProof`: compressed Groth16 possession proofs (`piA ‖ piB ‖ piC`) for the two keys, under the demo's `KeyPossessionProof` circuit (N7). Each proof is bound to its key type, to this registry's policy id and to the entry's `auditor`. - **Rotate (spend).** All of these must hold: - exactly one input under the registry's payment credential; - the old entry's auditor signs, and so does the new entry's; - - exactly one output holds the token; + - exactly one output under the registry's payment credential, and it holds the token; - that output is at the exact enterprise address, with value exactly lovelace plus the token; - its datum has the exact shape, canonical coordinates, lengths 28/32/32/192/192, `pkEnc ≠ viewKey`, and `generation = old + 1`; - - the new entry's `pkProof` verifies on-chain; + - the new entry's two possession proofs verify on-chain; - no mint under the registry policy; - the spent input holds the registry token (so a token-less output at the address cannot be "rotated"). The token is never burned or duplicated, so no older entry stays unspent. That is what makes the current generation enforceable (ADR-0055 Q7, implementation note 11). -- **Possession (Q6).** - - **The ElGamal key is checked on-chain** at Init and Rotate. The registry verifies `pkProof` - (one Groth16 verification, 7 public inputs, about 3.5e9 steps; rotation is rare) over - `[ctx(0x01), G.u, G.v, pkU, pkV, pkU, pkV]`. This discharges `R_enc`'s `PK ∈ 𝔾` obligation - on-chain (spec §9.3). It also means an auditor cannot register an identity, off-curve or - out-of-subgroup key, which would make every spend circuit unsatisfiable and freeze every note. - - **The viewing key is checked off-chain** by every sender before delivering to it (N5). A bad - viewing key costs the auditor its own D5 deliveries, nothing else. +- **Possession (Q6), checked on-chain for both keys** at Init and Rotate. The registry verifies + `pkProof` over `[ctx(0x01), G.u, G.v, pkU, pkV, pkU, pkV]` and `viewProof` over + `[ctx(0x02), G.u, G.v, viewU, viewV, viewU, viewV]`. Two Groth16 verifications measure about + 7.8e9 steps and 1.5e6 memory (78% and 9% of the limits). Registry transactions are rare, and the + ADR-0055 80% gate is for note transactions. + - This discharges `R_enc`'s `PK ∈ 𝔾` obligation on-chain (spec §9.3). + - An auditor cannot register an identity, off-curve or out-of-subgroup key, which would make + every spend circuit unsatisfiable and freeze every note. A possession proof with secret 0 does + verify for the identity, so `u ≠ 0` is checked separately. + - It cannot register an entry that honest senders then refuse to admit (N5): an encoding that + is not its coordinates', a viewing key it does not hold, or a malformed proof. Such an entry + would otherwise stop every honest transfer. - **Binding.** The context `ctx(type)` (N7) is computed on-chain from the key type, the registry's own policy id and the entry's `auditor`. A proof copied from another registry, from another registrant or from the other key type does not verify. Together with the registrant's @@ -135,7 +143,7 @@ a **singleton** registry token that the registry's own script moves forward on r The parameters are: - the issuer's pkh, the token name and the issuance mode; - the registry policy and token; -- the verification keys: transfer, redeem, and proved issuance for one and for two notes. +- the `blake2b_256(serialiseData(vk))` hashes of the verification keys: transfer, redeem, and proved issuance for one and for two notes (each redeemer carries its key; see the r2 note on script size). **Datum:** `Note(owner: B28, u: I, v: I, generation: I, audit: [I × 8], deliveries: [B89 × 2])`. - `audit` holds the two `elgamal-jubjub-v1` limb ciphertexts at width 32, `A.u, A.v, B.u, B.v` @@ -387,6 +395,15 @@ their own inputs"): period in the demo (N6). - F17: notes hold exactly lovelace plus the token; min-ADA computed; per-path compressed inputs listed; the source-scan pattern scoped. + - M2 implementation review (Claude R1–R6, Codex C1–C2): the entry gains the viewing key's + coordinates; both encodings are bound and both proofs verified on-chain (R1); key-type + binding tested in isolation (R2, C2); `AdmittedAuditor` has no public constructor (C1); + host builders check their preconditions (R5). + - Verification keys are pinned by hash: a script embedding four verification keys measured + 18.1–18.9 KB, beyond the 16 KB transaction limit even for deploying a reference script. + `NoteLedger` takes `blake2b_256(serialiseData(vk))` per key, and each proof's redeemer + carries its key (on-chain `VkLib`). The ledger is deployed once as a reference script into an + output at its own address that holds no note token, so it can never be spent. - F10 (script size) stays a measurement at M3a. ## Invariants @@ -406,9 +423,9 @@ their own inputs"): ## Alternatives considered -- **Possession proofs verified on-chain at registration.** Two Groth16 verifications would cost - about 8e9 steps, and Q6 allows off-chain checking. Rejected for the demo; anyone can still - verify the proofs, which are stored in the entry. +- **Possession proofs verified off-chain only.** Q6 allows it, and it saves about 7.8e9 steps per + registry transaction. Rejected in r2 (design review F1, implementation review R1): an auditor + could then register an entry that freezes every note or that every honest sender refuses. - **The issuer governs the registry.** The auditee would then control the auditor's key. Rejected: the auditor rotates its own entry, and the operator only pins which registry a ledger uses. diff --git a/pedersen-commitments/build.gradle b/pedersen-commitments/build.gradle index 646054d..648008e 100644 --- a/pedersen-commitments/build.gradle +++ b/pedersen-commitments/build.gradle @@ -59,6 +59,7 @@ dependencies { implementation "org.zeroj:zeroj-circuit-annotation-api:${zerojVersion}" annotationProcessor "org.zeroj:zeroj-circuit-annotation-processor:${zerojVersion}" implementation "org.zeroj:zeroj-crypto:${zerojVersion}" + implementation "org.zeroj:zeroj-bls12381:${zerojVersion}" implementation "org.zeroj:zeroj-codec:${zerojVersion}" implementation "org.zeroj:zeroj-verifier-groth16:${zerojVersion}" implementation "org.zeroj:zeroj-onchain-julc:${zerojVersion}" diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Plutus.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Plutus.java index 5f24703..0d8583e 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Plutus.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Plutus.java @@ -1,6 +1,13 @@ package com.bloxbean.cardano.zeroj.usecases.pedersen.common; +import com.bloxbean.cardano.client.api.MinAdaCalculator; +import com.bloxbean.cardano.client.api.model.Amount; +import com.bloxbean.cardano.client.backend.api.BackendService; import com.bloxbean.cardano.client.exception.CborSerializationException; +import com.bloxbean.cardano.client.transaction.spec.Asset; +import com.bloxbean.cardano.client.transaction.spec.MultiAsset; +import com.bloxbean.cardano.client.transaction.spec.TransactionOutput; +import com.bloxbean.cardano.client.transaction.spec.Value; import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; import com.bloxbean.cardano.client.plutus.spec.ConstrPlutusData; import com.bloxbean.cardano.client.plutus.spec.ListPlutusData; @@ -10,6 +17,8 @@ import org.zeroj.crypto.groth16.Groth16ProofBLS381; import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; +import java.math.BigInteger; +import java.util.ArrayList; import java.util.List; /** Off-chain Plutus data encodings shared by the demos. */ @@ -39,4 +48,31 @@ public static ConstrPlutusData proofRedeemer(Groth16ProofBLS381 proof) { return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()))).build(); } + + /** + * The lovelace an output needs: the ledger minimum for its serialized size at the current + * {@code coinsPerUTxOByte}, plus a 10% margin, rounded up to whole ADA. {@code tokens} are + * {@code policyHex + nameHex} units with quantities (no lovelace). + */ + public static BigInteger minAda(BackendService backend, String address, List tokens, PlutusData inlineDatum) { + try { + var params = backend.getEpochService().getProtocolParameters().getValue(); + List multiAssets = new ArrayList<>(); + for (Amount a : tokens) { + String policy = a.getUnit().substring(0, 56); + String name = "0x" + a.getUnit().substring(56); + multiAssets.add(MultiAsset.builder().policyId(policy) + .assets(List.of(new Asset(name, a.getQuantity()))).build()); + } + TransactionOutput output = TransactionOutput.builder().address(address) + .value(Value.builder().coin(BigInteger.valueOf(10_000_000_000L)).multiAssets(multiAssets).build()) + .inlineDatum(inlineDatum).build(); + BigInteger min = new MinAdaCalculator(params).calculateMinAda(output); + BigInteger padded = min.multiply(BigInteger.valueOf(11)).divide(BigInteger.TEN); + BigInteger ada = BigInteger.valueOf(1_000_000); + return padded.add(ada.subtract(BigInteger.ONE)).divide(ada).multiply(ada); + } catch (Exception e) { + throw new IllegalStateException("could not compute the minimum ADA: " + e.getMessage(), e); + } + } } diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/ProofBytes.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/ProofBytes.java new file mode 100644 index 0000000..220ebd6 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/ProofBytes.java @@ -0,0 +1,58 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.common; + +import org.zeroj.bls12381.Bls12381Codecs; +import org.zeroj.bls12381.ec.G1Point; +import org.zeroj.bls12381.ec.G2Point; +import org.zeroj.bls12381.ec.JacobianG1BLS381.AffineG1; +import org.zeroj.bls12381.ec.JacobianG2BLS381.AffineG2; +import org.zeroj.bls12381.field.MontFp2_381; +import org.zeroj.bls12381.field.MontFp381; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; +import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; + +import java.util.Arrays; + +/** + * A Groth16 proof as the 192 bytes {@code piA (48) ‖ piB (96) ‖ piC (48)}, the compressed form + * the on-chain verifier takes, and back. Used to store proofs in datums (the registry's + * possession proofs) and to verify them off-chain. + */ +public final class ProofBytes { + + public static final int LENGTH = 192; + + private ProofBytes() {} + + public static byte[] encode(Groth16ProofBLS381 proof) { + var p = ProverToCardano.compressProof(proof); + return Fields.concat(p.piA(), p.piB(), p.piC()); + } + + /** + * Decodes and validates (on the curve, in the subgroup, not infinity) the three points. + * + * @throws IllegalArgumentException for any other length or an invalid point + */ + public static Groth16ProofBLS381 decode(byte[] bytes) { + if (bytes == null || bytes.length != LENGTH) { + throw new IllegalArgumentException("a compressed Groth16 proof is " + LENGTH + " bytes"); + } + G1Point a = Bls12381Codecs.g1FromCompressed(Arrays.copyOfRange(bytes, 0, 48)); + G2Point b = Bls12381Codecs.g2FromCompressed(Arrays.copyOfRange(bytes, 48, 144)); + G1Point c = Bls12381Codecs.g1FromCompressed(Arrays.copyOfRange(bytes, 144, 192)); + if (a.isInfinity() || b.isInfinity() || c.isInfinity()) { + throw new IllegalArgumentException("a proof point is the point at infinity"); + } + return new Groth16ProofBLS381(g1(a), g2(b), g1(c)); + } + + private static AffineG1 g1(G1Point p) { + return new AffineG1(MontFp381.fromBigInteger(p.x().value()), MontFp381.fromBigInteger(p.y().value())); + } + + private static AffineG2 g2(G2Point p) { + return new AffineG2( + MontFp2_381.of(p.x().c0().value(), p.x().c1().value()), + MontFp2_381.of(p.y().c0().value(), p.y().c1().value())); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AdmittedAuditor.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AdmittedAuditor.java new file mode 100644 index 0000000..f92fec5 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AdmittedAuditor.java @@ -0,0 +1,82 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import org.zeroj.circuit.lib.jubjub.ElGamalPublicKey; +import org.zeroj.circuit.lib.jubjub.NOfNKeyContext; +import org.zeroj.circuit.lib.jubjub.NoteReaderKey; +import org.zeroj.circuit.lib.jubjub.VerifiedKeyShare; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; + +/** + * A registry entry a sender has admitted (ADR-0007 N5): both keys decoded strictly, their + * possession proofs verified under this registry's and this auditor's context (N7), and each key + * equal to the coordinates the validator reads. This is the only source of a key context for limb + * encryption and of the auditor's reader key for deliveries (ZeroJ ADR-0055 M3 criterion (b)), so + * it has no public constructor: {@link #admit} is the only way in. + */ +public final class AdmittedAuditor { + + private final byte[] auditor; + private final long generation; + private final NOfNKeyContext context; + private final NoteReaderKey viewKey; + + private AdmittedAuditor(byte[] auditor, long generation, NOfNKeyContext context, NoteReaderKey viewKey) { + this.auditor = auditor; + this.generation = generation; + this.context = context; + this.viewKey = viewKey; + } + + /** + * @throws IllegalArgumentException if a key does not decode to a valid subgroup point, a + * possession proof does not verify under this registry and auditor, coordinates do not + * match an encoding, or the two keys are equal + */ + public static AdmittedAuditor admit(byte[] registryPolicy, RegistryEntry entry, KeyPossession possession) { + if (Arrays.equals(entry.pkEnc(), entry.viewKey())) { + throw new IllegalArgumentException("the ElGamal key and the viewing key must differ"); + } + var pkCtx = KeyPossession.ctx(KeyPossession.KeyType.ELGAMAL, registryPolicy, entry.auditor()); + var viewCtx = KeyPossession.ctx(KeyPossession.KeyType.VIEWING, registryPolicy, entry.auditor()); + VerifiedKeyShare share = VerifiedKeyShare.verify(entry.pkEnc(), + statement -> possession.verifyPossession(pkCtx, statement, entry.pkProof())); + NOfNKeyContext context = ElGamalPublicKey.aggregate(List.of(share)); + ElGamalPublicKey key = context.jointKey(); + if (!key.affineU().equals(entry.pkU()) || !key.affineV().equals(entry.pkV())) { + throw new IllegalArgumentException("registry coordinates do not match the ElGamal key's encoding"); + } + NoteReaderKey view = NoteReaderKey.verified(entry.viewKey(), + statement -> possession.verifyPossession(viewCtx, statement, entry.viewProof())); + if (!view.affineU().equals(entry.viewU()) || !view.affineV().equals(entry.viewV())) { + throw new IllegalArgumentException("registry coordinates do not match the viewing key's encoding"); + } + return new AdmittedAuditor(entry.auditor().clone(), entry.generation(), context, view); + } + + public byte[] auditor() { + return auditor.clone(); + } + + public long generation() { + return generation; + } + + public NOfNKeyContext context() { + return context; + } + + public NoteReaderKey viewKey() { + return viewKey; + } + + public BigInteger pkU() { + return context.jointKey().affineU(); + } + + public BigInteger pkV() { + return context.jointKey().affineV(); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorKeys.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorKeys.java new file mode 100644 index 0000000..2995f6d --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorKeys.java @@ -0,0 +1,56 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import org.zeroj.circuit.lib.jubjub.ElGamalPublicKey; +import org.zeroj.circuit.lib.jubjub.ElGamalSecretKey; +import org.zeroj.circuit.lib.jubjub.NOfNKeyContext; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; + +import java.security.SecureRandom; + +/** + * An auditor's two secret keys (ZeroJ ADR-0055 D2): an {@code elgamal-jubjub-v1} key that + * receives D3a limb ciphertexts, and a separate {@code confidential-note-jubjub-v1} viewing key + * that receives D5 deliveries. Neither is derived from the other. One pair per generation. + */ +public final class AuditorKeys { + + private final ElGamalSecretKey elgamal; + private final NoteViewingKey viewing; + + private AuditorKeys(ElGamalSecretKey elgamal, NoteViewingKey viewing) { + this.elgamal = elgamal; + this.viewing = viewing; + } + + public static AuditorKeys generate(SecureRandom random) { + return new AuditorKeys(ElGamalSecretKey.generate(random), NoteViewingKey.generate(random)); + } + + /** + * The registry entry for these keys in the registry {@code registryPolicy}: both public keys + * and a possession proof of each (ADR-0055 Q6), bound to the key type, the registry and + * {@code auditorPkh} (ADR-0007 N7), at {@code generation}. + */ + public RegistryEntry entry(byte[] registryPolicy, byte[] auditorPkh, long generation, KeyPossession possession) { + byte[] pkProof = possession.prove(KeyPossession.ctx(KeyPossession.KeyType.ELGAMAL, registryPolicy, auditorPkh), + elgamal.possessionStatement(), elgamal.secretScalar()); + var viewCtx = KeyPossession.ctx(KeyPossession.KeyType.VIEWING, registryPolicy, auditorPkh); + byte[] viewProof = viewing.provePossession((statement, secret) -> possession.prove(viewCtx, statement, secret)); + ElGamalPublicKey pk = elgamal.publicKey(); + var reader = viewing.readerKey(); + return new RegistryEntry(auditorPkh.clone(), generation, pk.affineU(), pk.affineV(), pk.encode(), + reader.affineU(), reader.affineV(), reader.encode(), pkProof, viewProof); + } + + public ElGamalSecretKey elgamal() { + return elgamal; + } + + public NOfNKeyContext context() { + return NOfNKeyContext.singleKey(elgamal); + } + + public NoteViewingKey viewing() { + return viewing; + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/KeyPossession.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/KeyPossession.java new file mode 100644 index 0000000..db7c6a7 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/KeyPossession.java @@ -0,0 +1,96 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.KeyedCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.ProofBytes; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit.KeyPossessionProofCircuit; +import org.zeroj.circuit.lib.jubjub.DleqStatement; + +import com.bloxbean.cardano.client.crypto.Blake2bUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Proofs of possession for registry keys (ADR-0007 N7): Groth16 over {@code R_dleq} for a + * library-built {@link DleqStatement}, bound to a context {@link #ctx}, stored as 192 compressed + * bytes. + */ +public final class KeyPossession { + + /** The key types a registry entry holds. */ + public enum KeyType { + ELGAMAL((byte) 0x01), VIEWING((byte) 0x02); + + final byte tag; + + KeyType(byte tag) { + this.tag = tag; + } + } + + private static final byte[] DOMAIN = "zeroj.usecases.key-possession.v1".getBytes(StandardCharsets.US_ASCII); + + private final KeyedCircuit circuit; + + public KeyPossession() { + circuit = KeyedCircuit.compile("key-possession", KeyPossessionProofCircuit.build()); + } + + /** {@code DOMAIN ‖ type}: the prefix the registry hashes with its policy and the auditor. */ + public static byte[] ctxPrefix(KeyType type) { + return Fields.concat(DOMAIN, new byte[]{type.tag}); + } + + /** + * {@code ctx(type) = OS2IP(blake2b_256(DOMAIN ‖ type ‖ registryPolicy ‖ auditor)[0..30])}, 31 + * bytes, so below {@code p}. The registry validator computes the same value on-chain. + */ + public static BigInteger ctx(KeyType type, byte[] registryPolicy, byte[] auditor) { + if (registryPolicy.length != 28 || auditor.length != 28) { + throw new IllegalArgumentException("policy and auditor are 28-byte hashes"); + } + byte[] digest = Blake2bUtil.blake2bHash256(Fields.concat(ctxPrefix(type), registryPolicy, auditor)); + return new BigInteger(1, Arrays.copyOf(digest, 31)); + } + + /** The proof's public inputs: {@code ctx} then the statement's six, in order. */ + public static List publicInputs(BigInteger ctx, DleqStatement statement) { + List out = new ArrayList<>(7); + out.add(ctx); + out.addAll(statement.publicInputs()); + return out; + } + + /** Proves {@code statement} with its secret under {@code ctx}; the statement's inputs are used verbatim. */ + public byte[] prove(BigInteger ctx, DleqStatement statement, BigInteger secret) { + List pub = statement.publicInputs(); + var inputs = KeyPossessionProofCircuit.inputs() + .ctx(ctx).ctxSquared(ctx.multiply(ctx).mod(Fields.FR)) + .baseU(pub.get(0)).baseV(pub.get(1)) + .keyU(pub.get(2)).keyV(pub.get(3)) + .shareU(pub.get(4)).shareV(pub.get(5)) + .secret(secret); + return ProofBytes.encode(circuit.prove(inputs.toWitnessMap())); + } + + /** + * Verifies a stored proof for exactly the possession statement the library built, under the + * verifier's own {@code ctx}. A malformed proof is a failed verification, never an exception. + */ + public boolean verifyPossession(BigInteger ctx, DleqStatement statement, byte[] proof) { + if (statement == null || statement.kind() != DleqStatement.Kind.POSSESSION) return false; + try { + return circuit.verify(ProofBytes.decode(proof), publicInputs(ctx, statement)); + } catch (RuntimeException e) { + return false; + } + } + + public KeyedCircuit circuit() { + return circuit; + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/Registry.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/Registry.java new file mode 100644 index 0000000..88ba73c --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/Registry.java @@ -0,0 +1,203 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.address.AddressProvider; +import com.bloxbean.cardano.client.api.model.Amount; +import com.bloxbean.cardano.client.api.model.Result; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.common.model.Networks; +import com.bloxbean.cardano.client.function.helper.SignerProviders; +import com.bloxbean.cardano.client.plutus.spec.BigIntPlutusData; +import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusScript; +import com.bloxbean.cardano.client.quicktx.QuickTxBuilder; +import com.bloxbean.cardano.client.quicktx.ScriptTx; +import com.bloxbean.cardano.client.transaction.spec.Asset; +import com.bloxbean.cardano.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain.AuditorRegistry; +import org.julclang.clientlib.JulcScriptLoader; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * One auditor registry instance (ADR-0007 N1): its script, address and policy, the Init and + * Rotate transactions, and the current entry read from the chain. + * + *

The instance is fixed by its seed output, which Init must spend. Its policy id is what a + * ledger (or an auction) pins as {@code registryPolicy}. + */ +public final class Registry { + + public static final byte[] TOKEN = "REG".getBytes(StandardCharsets.UTF_8); + private final PlutusScript script; + private final KeyPossession possession; + private final String seedTxHash; + private final int seedIndex; + private final byte[] policy; + private final String address; + + private Registry(PlutusScript script, KeyPossession possession, String seedTxHash, int seedIndex) { + this.script = script; + this.possession = possession; + this.seedTxHash = seedTxHash; + this.seedIndex = seedIndex; + this.policy = HexUtil.decodeHexString(Plutus.policyId(script)); + try { + this.address = AddressProvider.getEntAddress(script, Networks.testnet()).toBech32(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + /** The registry whose Init must spend {@code seedTxHash#seedIndex}. */ + public static Registry forSeed(String seedTxHash, int seedIndex, KeyPossession possession) { + var vk = possession.circuit().compressedVk(); + // The base X = G of every possession statement (elgamal-jubjub-v1 §3.3). + JubjubPoint g = JubjubPoint.SUBGROUP_GENERATOR.normalized(); + PlutusScript script = JulcScriptLoader.load(AuditorRegistry.class, + new BytesPlutusData(seedRef(seedTxHash, seedIndex)), + new BytesPlutusData(TOKEN), + new BytesPlutusData(KeyPossession.ctxPrefix(KeyPossession.KeyType.ELGAMAL)), + new BytesPlutusData(KeyPossession.ctxPrefix(KeyPossession.KeyType.VIEWING)), + BigIntPlutusData.of(g.affineU()), BigIntPlutusData.of(g.affineV()), + new BytesPlutusData(vk.alpha()), new BytesPlutusData(vk.beta()), + new BytesPlutusData(vk.gamma()), new BytesPlutusData(vk.delta()), Plutus.icData(vk.ic())); + return new Registry(script, possession, seedTxHash, seedIndex); + } + + /** {@code txId ‖ I2OSP2(index)}, as {@code ValuesLib.refBytes}. */ + public static byte[] seedRef(String txHash, int index) { + return Fields.concat(HexUtil.decodeHexString(txHash), Fields.i2osp(BigInteger.valueOf(index), 2)); + } + + public PlutusScript script() { return script; } + + public byte[] policy() { return policy.clone(); } + + public String policyHex() { return HexUtil.encodeHexString(policy); } + + public String address() { return address; } + + public String unit() { return policyHex() + HexUtil.encodeHexString(TOKEN); } + + public KeyPossession possession() { return possession; } + + // ------------------------------------------------------------------ transactions + + /** Creates the registry with generation 0, spending {@code seed} and signed by the auditor. */ + public Result init(BackendService backend, Account auditor, Utxo seed, RegistryEntry entry) { + if (entry.generation() != 0) throw new IllegalArgumentException("Init creates generation 0"); + if (!seed.getTxHash().equals(seedTxHash) || seed.getOutputIndex() != seedIndex) { + throw new IllegalArgumentException("this registry's Init must spend " + seedTxHash + "#" + seedIndex); + } + requireKey(auditor, entry.auditor(), "the auditor"); + AdmittedAuditor.admit(policy, entry, possession); // fail before submitting what the script would refuse + List held = entryValue(backend, entry); + var tx = new ScriptTx() + .collectFrom(seed) + .mintAsset(script, List.of(new Asset("0x" + HexUtil.encodeHexString(TOKEN), BigInteger.ONE)), + PlutusData.unit()) + .payToContract(address, held, entry.toPlutusData()); + return submit(backend, tx, List.of(auditor), auditor); + } + + /** Moves the entry forward one generation, signed by the old and the new auditor. */ + public Result rotate(BackendService backend, Account oldAuditor, Account newAuditor, RegistryEntry next) { + RegistryEntry old = current(backend); + requireKey(oldAuditor, old.auditor(), "the current auditor"); + requireKey(newAuditor, next.auditor(), "the new auditor"); + if (next.generation() != old.generation() + 1) { + throw new IllegalArgumentException("a rotation moves to generation " + (old.generation() + 1)); + } + AdmittedAuditor.admit(policy, next, possession); + Utxo current = currentUtxo(backend); + var tx = new ScriptTx() + .collectFrom(current, PlutusData.unit()) + .payToContract(address, entryValue(backend, next), next.toPlutusData()) + .attachSpendingValidator(script); + List signers = Arrays.equals(keyHash(oldAuditor), keyHash(newAuditor)) + ? List.of(oldAuditor) : List.of(oldAuditor, newAuditor); + return submit(backend, tx, signers, oldAuditor); + } + + private static byte[] keyHash(Account account) { + return account.hdKeyPair().getPublicKey().getKeyHash(); + } + + private static void requireKey(Account account, byte[] expected, String who) { + if (!Arrays.equals(keyHash(account), expected)) { + throw new IllegalArgumentException(who + "'s key hash is not the entry's auditor"); + } + } + + private List entryValue(BackendService backend, RegistryEntry entry) { + List token = List.of(new Amount(unit(), BigInteger.ONE)); + List held = new ArrayList<>(); + held.add(new Amount("lovelace", Plutus.minAda(backend, address, token, entry.toPlutusData()))); + held.addAll(token); + return held; + } + + private static Result submit(BackendService backend, ScriptTx tx, List signers, Account payer) { + try { + var builder = new QuickTxBuilder(backend).compose(tx) + .withTxEvaluator(DevKit.evaluator(backend)) + .feePayer(payer.baseAddress()) + .collateralPayer(payer.baseAddress()); + var signer = SignerProviders.signerFrom(signers.getFirst()); + List required = new ArrayList<>(); + for (Account a : signers) required.add(a.hdKeyPair().getPublicKey().getKeyHash()); + for (int i = 1; i < signers.size(); i++) signer = signer.andThen(SignerProviders.signerFrom(signers.get(i))); + return builder.withSigner(signer).withRequiredSigners(required.toArray(new byte[0][])).complete(); + } catch (RuntimeException e) { + return Result.error(e.getMessage()); + } + } + + // ------------------------------------------------------------------ reading + + /** The one UTxO holding the registry token, at the exact registry address. */ + public Utxo currentUtxo(BackendService backend) { + try { + for (int page = 1; ; page++) { + var r = backend.getUtxoService().getUtxos(address, 100, page); + if (!r.isSuccessful() || r.getValue() == null || r.getValue().isEmpty()) break; + for (Utxo u : r.getValue()) { + if (u.getAmount().stream().anyMatch(a -> a.getUnit().equals(unit()) + && a.getQuantity().equals(BigInteger.ONE))) { + return u; + } + } + if (r.getValue().size() < 100) break; + } + } catch (Exception e) { + throw new IllegalStateException("could not read the registry: " + e.getMessage(), e); + } + throw new IllegalStateException("no registry entry at " + address); + } + + /** The current entry, parsed strictly (shape only; admission is {@link AdmittedAuditor#admit}). */ + public RegistryEntry current(BackendService backend) { + Utxo u = currentUtxo(backend); + try { + return RegistryEntry.fromPlutusData(PlutusData.deserialize(HexUtil.decodeHexString(u.getInlineDatum()))); + } catch (Exception e) { + throw new IllegalStateException("registry datum unreadable: " + e.getMessage(), e); + } + } + + /** The current entry, admitted: possession proofs verified under this registry (ADR-0007 N5). */ + public AdmittedAuditor admitted(BackendService backend) { + return AdmittedAuditor.admit(policy, current(backend), possession); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryEntry.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryEntry.java new file mode 100644 index 0000000..b44846c --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryEntry.java @@ -0,0 +1,75 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import com.bloxbean.cardano.client.plutus.spec.BigIntPlutusData; +import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ConstrPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ListPlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusData; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; + +import java.math.BigInteger; +import java.util.List; + +/** + * An auditor registry entry (ADR-0007 N1), as {@code AuditorRegistry} stores it: + * {@code Entry(auditor, generation, pkU, pkV, pkEnc, viewU, viewV, viewKey, pkProof, viewProof)}. + * + *

{@link #fromPlutusData} checks the shape and lengths only. Whether the keys are valid and + * possessed is {@link AdmittedAuditor#admit}'s job (and, for entries on chain, the registry's). + */ +public record RegistryEntry(byte[] auditor, long generation, BigInteger pkU, BigInteger pkV, byte[] pkEnc, + BigInteger viewU, BigInteger viewV, byte[] viewKey, byte[] pkProof, byte[] viewProof) { + + public ConstrPlutusData toPlutusData() { + return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(auditor), + BigIntPlutusData.of(generation), + BigIntPlutusData.of(pkU), + BigIntPlutusData.of(pkV), + new BytesPlutusData(pkEnc), + BigIntPlutusData.of(viewU), + BigIntPlutusData.of(viewV), + new BytesPlutusData(viewKey), + new BytesPlutusData(pkProof), + new BytesPlutusData(viewProof))).build(); + } + + /** @throws IllegalArgumentException if {@code data} is not exactly an entry */ + public static RegistryEntry fromPlutusData(PlutusData data) { + if (!(data instanceof ConstrPlutusData c) || c.getAlternative() != 0) { + throw new IllegalArgumentException("not a registry entry"); + } + List f = c.getData().getPlutusDataList(); + if (f.size() != 10) throw new IllegalArgumentException("a registry entry has 10 fields"); + var entry = new RegistryEntry(bytes(f.get(0), 28), integer(f.get(1)).longValueExact(), + integer(f.get(2)), integer(f.get(3)), bytes(f.get(4), 32), + integer(f.get(5)), integer(f.get(6)), bytes(f.get(7), 32), + bytes(f.get(8), 192), bytes(f.get(9), 192)); + if (entry.generation < 0 || !canonical(entry.pkU) || !canonical(entry.pkV) + || !canonical(entry.viewU) || !canonical(entry.viewV)) { + throw new IllegalArgumentException("registry entry out of range"); + } + return entry; + } + + /** The same entry with another possession proof for the ElGamal key (tests and cheats). */ + public RegistryEntry withPkProof(byte[] proof) { + return new RegistryEntry(auditor, generation, pkU, pkV, pkEnc, viewU, viewV, viewKey, proof, viewProof); + } + + private static boolean canonical(BigInteger x) { + return x.signum() >= 0 && x.compareTo(Fields.FR) < 0; + } + + private static byte[] bytes(PlutusData d, int length) { + if (!(d instanceof BytesPlutusData b) || b.getValue().length != length) { + throw new IllegalArgumentException("expected " + length + " bytes"); + } + return b.getValue(); + } + + private static BigInteger integer(PlutusData d) { + if (!(d instanceof BigIntPlutusData i)) throw new IllegalArgumentException("expected an integer"); + return i.getValue(); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/circuit/KeyPossessionProof.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/circuit/KeyPossessionProof.java new file mode 100644 index 0000000..c87730b --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/circuit/KeyPossessionProof.java @@ -0,0 +1,41 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit; + +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; + +/** + * Proof of possession of a Jubjub key (ADR-0007 N7): ZeroJ's {@code elgamal-jubjub-v1} DLEQ + * relation {@code R_dleq} (spec §9.2), as ADR-0005's trustee proof uses it. + * + *

Public, in order: {@code ctx}, then {@code X.u, X.v, P.u, P.v, D.u, D.v}, exactly a + * {@code DleqStatement}'s public inputs (spec §8 lets an application put its own inputs around + * the group). The prover knows {@code x} with {@code P = [x]·G} and {@code D = [x]·X}. For a + * possession statement the library builds {@code X = G} and {@code D = P = key}. + * + *

{@code ctx} binds the proof to a key type, a registry and a registrant (ADR-0007 N7), so a + * published proof cannot be replayed to register the same key elsewhere, by someone else or as the + * other key type. {@code ctx² = sq} puts it into a constraint: a public input in no constraint would + * not affect verification. + */ +@ZKCircuit(name = "key-possession", version = 2) +public class KeyPossessionProof { + + @Prove + void prove(ZkContext zk, + @Public ZkField ctx, + @Public ZkField baseU, @Public ZkField baseV, + @Public ZkField keyU, @Public ZkField keyV, + @Public ZkField shareU, @Public ZkField shareV, + @Secret @UInt(bits = 252) ZkUInt secret, + @Secret ZkField ctxSquared) { + ctx.mul(ctx).assertEqual(ctxSquared); + ZkElGamal.assertDiscreteLogEquality(zk, secret, baseU, baseV, keyU, keyV, shareU, shareV); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/AuditorRegistry.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/AuditorRegistry.java new file mode 100644 index 0000000..c9d6935 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/AuditorRegistry.java @@ -0,0 +1,177 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain; + +import org.julclang.core.PlutusData; +import org.julclang.ledger.Address; +import org.julclang.ledger.Credential; +import org.julclang.ledger.ScriptContext; +import org.julclang.ledger.ScriptHash; +import org.julclang.ledger.ScriptInfo; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxInfo; +import org.julclang.ledger.TxOut; +import org.julclang.stdlib.Builtins; +import org.julclang.stdlib.annotation.Entrypoint; +import org.julclang.stdlib.annotation.MultiValidator; +import org.julclang.stdlib.annotation.Param; +import org.julclang.stdlib.annotation.Purpose; +import org.julclang.stdlib.lib.ContextsLib; +import org.julclang.stdlib.lib.ValuesLib; +import org.zeroj.onchain.julc.groth16.lib.Groth16BLS12381Lib; + +import java.math.BigInteger; +import java.util.Optional; + +/** + * An auditor's key registry (ADR-0007 N1; ZeroJ ADR-0055 spec §8.1, singleton option). One script + * is the registry token's policy and the registry address. + * + *

The registry holds exactly one entry, ever: a single {@code registryToken} minted once (the + * transaction must spend the seed output {@code seedRef = txId ‖ I2OSP2(index)}), and moved + * forward on every rotation by spending the entry and recreating it. The token is never burned or + * duplicated, so no older entry stays unspent and a ledger that reads the registry always sees the + * current generation. + * + *

Entry datum, exactly {@code Constr 0 [auditor B28, generation I, pkU, pkV, pkEnc B32, viewU, + * viewV, viewKey B32, pkProof B192, viewProof B192]}: both keys as canonical coordinates and as + * the encoding of exactly those coordinates, and different from each other ({@link RegistryLib#isEntry}). + * + *

Possession (ADR-0055 Q6). Every Init and Rotate verifies both Groth16 possession + * proofs, each over {@code [ctx, G.u, G.v, u, v, u, v]} with + * {@code ctx = OS2IP(blake2b_256(prefix ‖ type ‖ policy ‖ auditor)[0..30])} (ADR-0007 N7). So + * every registered key is a valid subgroup key its registrant holds: no ledger's spend circuits can + * be made unsatisfiable through it, honest senders can always admit it, and a proof copied from + * another registry, registrant or key type fails. + * + *

    + *
  • Init (mint): spends the seed; mints exactly one {@code registryToken}; exactly one + * output under the registry credential, at the exact enterprise address, holding lovelace + * and the token only, with a well-formed entry of generation 0; the entry's auditor signs.
  • + *
  • Rotate (spend): the spent entry holds the token; exactly one registry input; no + * mint under the policy; exactly one output under the registry credential, as for Init, + * with generation {@code old + 1}; the old and the new auditor both sign.
  • + *
+ */ +@MultiValidator +public class AuditorRegistry { + + @Param static byte[] seedRef; + @Param static byte[] registryToken; + @Param static byte[] elgamalCtxPrefix; // ASCII("zeroj.usecases.key-possession.v1") ‖ 0x01 + @Param static byte[] viewCtxPrefix; // ASCII("zeroj.usecases.key-possession.v1") ‖ 0x02 + @Param static BigInteger genU; // the Jubjub generator G (pedersen-jubjub-v1 §2) + @Param static BigInteger genV; + @Param static byte[] possAlpha; + @Param static byte[] possBeta; + @Param static byte[] possGamma; + @Param static byte[] possDelta; + @Param static PlutusData possIc; + + @Entrypoint(purpose = Purpose.MINT) + public static boolean mint(PlutusData redeemer, ScriptContext ctx) { + TxInfo txInfo = ctx.txInfo(); + ScriptInfo.MintingScript mintInfo = (ScriptInfo.MintingScript) ctx.scriptInfo(); + byte[] policy = PlutusData.cast(mintInfo.policyId(), byte[].class); + Credential own = new Credential.ScriptCredential(PlutusData.cast(policy, ScriptHash.class)); + Address exact = new Address(own, Optional.empty()); + + boolean seedConsumed = false; + for (TxInInfo input : txInfo.inputs()) { + seedConsumed = seedConsumed + || Builtins.equalsByteString(ValuesLib.refBytes(input.outRef()), seedRef); + } + if (!seedConsumed + || ChainLib.policyEntryCount(txInfo.mint(), policy) != 1 + || ValuesLib.assetOf(txInfo.mint(), policy, registryToken).compareTo(BigInteger.ONE) != 0 + || ChainLib.countInputs(txInfo.inputs(), own) != 0) { + return false; + } + TxOut entry = onlyEntryOutput(txInfo, own, exact, policy); + PlutusData datum = ChainLib.inlineDatum(entry); + return RegistryLib.isEntry(datum) + && RegistryLib.entryGeneration(datum).compareTo(BigInteger.ZERO) == 0 + && ChainLib.signedBy(txInfo, RegistryLib.entryAuditor(datum)) + && possessed(datum, policy); + } + + @Entrypoint(purpose = Purpose.SPEND) + public static boolean spend(PlutusData datum, PlutusData redeemer, ScriptContext ctx) { + TxInfo txInfo = ctx.txInfo(); + byte[] policy = ContextsLib.ownHash(ctx); + Credential own = new Credential.ScriptCredential(PlutusData.cast(policy, ScriptHash.class)); + Address exact = new Address(own, Optional.empty()); + var ownInputOptional = ContextsLib.findOwnInput(ctx); + if (ownInputOptional.isEmpty()) return false; + TxInInfo ownInput = ownInputOptional.get(); + if (ValuesLib.assetOf(ownInput.resolved().value(), policy, registryToken).compareTo(BigInteger.ONE) != 0 + || ChainLib.countInputs(txInfo.inputs(), own) != 1 + || ChainLib.policyEntryCount(txInfo.mint(), policy) != 0 + || !RegistryLib.isEntry(datum)) { + return false; + } + TxOut entry = onlyEntryOutput(txInfo, own, exact, policy); + PlutusData next = ChainLib.inlineDatum(entry); + return RegistryLib.isEntry(next) + && RegistryLib.entryGeneration(next).compareTo(RegistryLib.entryGeneration(datum).add(BigInteger.ONE)) == 0 + && ChainLib.signedBy(txInfo, RegistryLib.entryAuditor(datum)) + && ChainLib.signedBy(txInfo, RegistryLib.entryAuditor(next)) + && possessed(next, policy); + } + + /** + * Both possession proofs verify under this registry and the entry's auditor: {@code pkProof} + * for {@code (pkU, pkV)} with type {@code 0x01} and {@code viewProof} for {@code (viewU, viewV)} + * with type {@code 0x02}. With the encodings bound to the coordinates ({@code isEntry}), every + * registered key is a valid subgroup key the auditor holds, and honest senders can admit it. + */ + private static boolean possessed(PlutusData entry, byte[] policy) { + byte[] auditor = RegistryLib.entryAuditor(entry); + return possession(elgamalCtxPrefix, policy, auditor, RegistryLib.entryPkU(entry), RegistryLib.entryPkV(entry), + RegistryLib.entryPkProof(entry)) + && possession(viewCtxPrefix, policy, auditor, RegistryLib.entryViewU(entry), RegistryLib.entryViewV(entry), + RegistryLib.entryViewProof(entry)); + } + + /** One possession proof over {@code [ctx, G.u, G.v, u, v, u, v]} (ADR-0007 N7). */ + private static boolean possession(byte[] prefix, byte[] policy, byte[] auditor, BigInteger u, BigInteger v, + byte[] proof) { + byte[] digest = Builtins.blake2b_256(Builtins.appendByteString(prefix, Builtins.appendByteString(policy, auditor))); + BigInteger ctx = Builtins.byteStringToInteger(true, Builtins.sliceByteString(0, 31, digest)); + PlutusData publicInputs = Builtins.listData( + Builtins.mkCons(Builtins.iData(ctx), + Builtins.mkCons(Builtins.iData(genU), + Builtins.mkCons(Builtins.iData(genV), + Builtins.mkCons(Builtins.iData(u), + Builtins.mkCons(Builtins.iData(v), + Builtins.mkCons(Builtins.iData(u), + Builtins.mkCons(Builtins.iData(v), + Builtins.mkNilData())))))))); + return Groth16BLS12381Lib.verify(publicInputs, + Builtins.sliceByteString(0, 48, proof), + Builtins.sliceByteString(48, 96, proof), + Builtins.sliceByteString(144, 48, proof), + possAlpha, possBeta, possGamma, possDelta, possIc); + } + + /** + * The one output under the registry credential: it must be the only one, sit at the exact + * address and hold lovelace plus exactly one registry token. Anything else fails the script. + */ + private static TxOut onlyEntryOutput(TxInfo txInfo, Credential own, Address exact, byte[] policy) { + if (ChainLib.countOutputs(txInfo.outputs(), own) != 1) Builtins.error(); + TxOut found = txInfo.outputs().get(0); + for (TxOut output : txInfo.outputs()) { + if (Builtins.equalsData(output.address().credential(), own)) { + found = output; + } else { + found = found; + } + } + if (!Builtins.equalsData(found.address(), exact) + || ChainLib.outerEntryCount(found.value()) != 2 + || ChainLib.policyEntryCount(found.value(), policy) != 1 + || ValuesLib.assetOf(found.value(), policy, registryToken).compareTo(BigInteger.ONE) != 0) { + Builtins.error(); + } + return found; + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/ChainLib.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/ChainLib.java new file mode 100644 index 0000000..2ef0118 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/ChainLib.java @@ -0,0 +1,146 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain; + +import org.julclang.core.PlutusData; +import org.julclang.core.types.JulcList; +import org.julclang.ledger.Address; +import org.julclang.ledger.Credential; +import org.julclang.ledger.OutputDatum; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxInfo; +import org.julclang.ledger.TxOut; +import org.julclang.ledger.Value; +import org.julclang.stdlib.Builtins; +import org.julclang.stdlib.annotation.OnchainLibrary; + +import java.math.BigInteger; + +/** + * On-chain helpers shared by the confidential-note validators (ADR-0007, ADR-0008): counting + * inputs and outputs under a payment credential, exact value shapes, signatures, inline datums + * and canonical field elements. + */ +@OnchainLibrary +public class ChainLib { + + /** Script inputs counted by payment credential, so every stake variant counts. */ + public static int countInputs(JulcList inputs, Credential own) { + int n = 0; + for (TxInInfo input : inputs) { + if (Builtins.equalsData(input.resolved().address().credential(), own)) { + n = n + 1; + } else { + n = n; + } + } + return n; + } + + /** Outputs counted by payment credential. */ + public static int countOutputs(JulcList outputs, Credential own) { + int n = 0; + for (TxOut output : outputs) { + if (Builtins.equalsData(output.address().credential(), own)) { + n = n + 1; + } else { + n = n; + } + } + return n; + } + + /** + * Every output under the payment credential {@code own} is at exactly {@code exact} (the + * enterprise address, no stake credential). The address policy of ADR-0007 N2. + */ + public static boolean allAtExactAddress(JulcList outputs, Credential own, Address exact) { + boolean ok = true; + for (TxOut output : outputs) { + if (Builtins.equalsData(output.address().credential(), own)) { + ok = ok && Builtins.equalsData(output.address(), exact); + } else { + ok = ok; + } + } + return ok; + } + + public static boolean signedBy(TxInfo txInfo, byte[] pkh) { + boolean found = false; + for (var signer : txInfo.signatories()) { + found = found || Builtins.equalsByteString(signer.hash(), pkh); + } + return found; + } + + /** The number of policies (lovelace included) in a value. */ + public static int outerEntryCount(Value value) { + int count = 0; + PlutusData current = Builtins.unMapData(value); + while (!Builtins.nullList(current)) { + count = count + 1; + current = Builtins.tailList(current); + } + return count; + } + + /** The number of token names (any quantity) under {@code policy}. */ + public static int policyEntryCount(Value value, byte[] policy) { + PlutusData target = Builtins.bData(policy); + int count = 0; + PlutusData current = Builtins.unMapData(value); + while (!Builtins.nullList(current)) { + var pair = Builtins.headList(current); + if (Builtins.equalsData(Builtins.fstPair(pair), target)) { + count = innerEntryCount((PlutusData.MapData) Builtins.sndPair(pair)); + current = Builtins.mkNilPairData(); + } else { + current = Builtins.tailList(current); + } + } + return count; + } + + private static int innerEntryCount(PlutusData.MapData innerPairs) { + int count = 0; + PlutusData current = Builtins.unMapData(innerPairs); + while (!Builtins.nullList(current)) { + count = count + 1; + current = Builtins.tailList(current); + } + return count; + } + + /** The inline datum; a missing or hashed datum yields an integer, which no shape check accepts. */ + public static PlutusData inlineDatum(TxOut output) { + return switch (output.datum()) { + case OutputDatum.OutputDatumInline inline -> inline.datum(); + case OutputDatum.OutputDatumHash ignored -> Builtins.iData(BigInteger.ZERO); + case OutputDatum.NoOutputDatum ignored -> Builtins.iData(BigInteger.ZERO); + }; + } + + /** The length of a list datum, or -1 for anything else (a builtin failure fails closed). */ + public static int listLength(PlutusData list) { + int n = 0; + PlutusData rest = Builtins.unListData(list); + while (!Builtins.nullList(rest)) { + n = n + 1; + rest = Builtins.tailList(rest); + } + return n; + } + + /** {@code 0 ≤ value < p}, the BLS12-381 scalar field. */ + public static boolean canonicalField(BigInteger value) { + return value.compareTo(BigInteger.ZERO) >= 0 && value.compareTo(fr()) < 0; + } + + public static BigInteger fr() { + BigInteger base = BigInteger.valueOf(1000000000000000000L); + return BigInteger.valueOf(52435L).multiply(base) + .add(BigInteger.valueOf(875175126190479447L)).multiply(base) + .add(BigInteger.valueOf(740508185965837690L)).multiply(base) + .add(BigInteger.valueOf(552500527637822603L)).multiply(base) + .add(BigInteger.valueOf(658699938581184513L)); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/RegistryLib.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/RegistryLib.java new file mode 100644 index 0000000..d3cbaea --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/RegistryLib.java @@ -0,0 +1,149 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain; + +import org.julclang.core.PlutusData; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxInfo; +import org.julclang.ledger.TxOut; +import org.julclang.stdlib.Builtins; +import org.julclang.stdlib.annotation.OnchainLibrary; +import org.julclang.stdlib.lib.ValuesLib; + +import java.math.BigInteger; + +/** + * The auditor registry entry (ADR-0007 N1) as validators read it: its shape, its fields, and the + * one entry a transaction supplies as a reference input. + */ +@OnchainLibrary +public class RegistryLib { + + /** + * Exactly {@code Constr 0 [auditor B28, generation I ≥ 0, pkU, pkV, pkEnc B32, viewU, viewV, + * viewKey B32, pkProof B192, viewProof B192]}, where both keys' coordinates are canonical with + * {@code u ≠ 0}, each encoding is exactly its coordinates' {@code pedersen-jubjub-v1} §4 + * encoding ({@link #encode}), and the two keys differ. A wrong field type makes a builtin fail + * (fail closed). + * + *

{@code u ≠ 0} excludes the identity {@code (0, 1)} and the order-2 point {@code (0, −1)}: + * a possession proof with secret 0 is valid for the identity, so the proof alone would not. + */ + public static boolean isEntry(PlutusData value) { + if (Builtins.constrTag(value) != 0) return false; + PlutusData f0 = Builtins.constrFields(value); + PlutusData f1 = Builtins.tailList(f0); + PlutusData f2 = Builtins.tailList(f1); + PlutusData f3 = Builtins.tailList(f2); + PlutusData f4 = Builtins.tailList(f3); + PlutusData f5 = Builtins.tailList(f4); + PlutusData f6 = Builtins.tailList(f5); + PlutusData f7 = Builtins.tailList(f6); + PlutusData f8 = Builtins.tailList(f7); + PlutusData f9 = Builtins.tailList(f8); + if (!Builtins.nullList(Builtins.tailList(f9))) return false; + BigInteger pkU = Builtins.unIData(Builtins.headList(f2)); + BigInteger pkV = Builtins.unIData(Builtins.headList(f3)); + byte[] pkEnc = Builtins.unBData(Builtins.headList(f4)); + BigInteger viewU = Builtins.unIData(Builtins.headList(f5)); + BigInteger viewV = Builtins.unIData(Builtins.headList(f6)); + byte[] viewKey = Builtins.unBData(Builtins.headList(f7)); + return Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(f0))) == 28 + && Builtins.unIData(Builtins.headList(f1)).compareTo(BigInteger.ZERO) >= 0 + && validKeyCoordinates(pkU, pkV) + && validKeyCoordinates(viewU, viewV) + && Builtins.equalsByteString(pkEnc, encode(pkU, pkV)) + && Builtins.equalsByteString(viewKey, encode(viewU, viewV)) + && !Builtins.equalsByteString(pkEnc, viewKey) + && Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(f8))) == 192 + && Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(f9))) == 192; + } + + private static boolean validKeyCoordinates(BigInteger u, BigInteger v) { + return ChainLib.canonicalField(u) && ChainLib.canonicalField(v) && u.compareTo(BigInteger.ZERO) != 0; + } + + /** + * The 32-byte {@code pedersen-jubjub-v1} §4 encoding of the affine point {@code (u, v)}: + * {@code v} little-endian with the top bit set iff {@code u} is odd. For canonical + * coordinates of a curve point this is the unique encoding. + */ + public static byte[] encode(BigInteger u, BigInteger v) { + BigInteger sign = u.mod(BigInteger.valueOf(2)); + return Builtins.integerToByteString(false, 32, v.add(sign.multiply(twoTo255()))); + } + + private static BigInteger twoTo255() { + BigInteger b62 = BigInteger.valueOf(4611686018427387904L); + return b62.multiply(b62).multiply(b62).multiply(b62).multiply(BigInteger.valueOf(128)); + } + + public static byte[] entryAuditor(PlutusData entry) { + return Builtins.unBData(Builtins.headList(Builtins.constrFields(entry))); + } + + public static BigInteger entryGeneration(PlutusData entry) { + return Builtins.unIData(field(entry, 1)); + } + + public static BigInteger entryPkU(PlutusData entry) { + return Builtins.unIData(field(entry, 2)); + } + + public static BigInteger entryPkV(PlutusData entry) { + return Builtins.unIData(field(entry, 3)); + } + + public static BigInteger entryViewU(PlutusData entry) { + return Builtins.unIData(field(entry, 5)); + } + + public static BigInteger entryViewV(PlutusData entry) { + return Builtins.unIData(field(entry, 6)); + } + + public static byte[] entryPkProof(PlutusData entry) { + return Builtins.unBData(field(entry, 8)); + } + + public static byte[] entryViewProof(PlutusData entry) { + return Builtins.unBData(field(entry, 9)); + } + + /** Field {@code index} of a constructor. */ + private static PlutusData field(PlutusData entry, int index) { + PlutusData rest = Builtins.constrFields(entry); + int i = 0; + while (i < index) { + rest = Builtins.tailList(rest); + i = i + 1; + } + return Builtins.headList(rest); + } + + /** + * The entry of the exactly one reference input that holds the registry token + * ({@code registryPolicy}/{@code registryToken}): quantity exactly 1 and a well-formed entry + * datum (spec §8.1). No entry, a second entry, another quantity or another shape fails the + * script. The registry's own script keeps the token a singleton, so this is the current + * generation. + */ + public static PlutusData currentEntry(TxInfo txInfo, byte[] registryPolicy, byte[] registryToken) { + int entries = 0; + boolean single = true; + PlutusData found = Builtins.iData(BigInteger.ZERO); + for (TxInInfo reference : txInfo.referenceInputs()) { + TxOut resolved = reference.resolved(); + BigInteger quantity = ValuesLib.assetOf(resolved.value(), registryPolicy, registryToken); + if (quantity.compareTo(BigInteger.ZERO) > 0) { + entries = entries + 1; + single = single && quantity.compareTo(BigInteger.ONE) == 0; + found = ChainLib.inlineDatum(resolved); + } else { + entries = entries; + single = single; + found = found; + } + } + if (entries != 1 || !single || !isEntry(found)) Builtins.error(); + return found; + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorRegistryVmTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorRegistryVmTest.java new file mode 100644 index 0000000..82c7167 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorRegistryVmTest.java @@ -0,0 +1,350 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.ProofBytes; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit.KeyPossessionProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain.AuditorRegistry; +import org.julclang.core.PlutusData; +import org.julclang.core.Program; +import org.julclang.ledger.Address; +import org.julclang.ledger.Credential; +import org.julclang.ledger.DatumHash; +import org.julclang.ledger.OutputDatum; +import org.julclang.ledger.PolicyId; +import org.julclang.ledger.PubKeyHash; +import org.julclang.ledger.ScriptHash; +import org.julclang.ledger.StakingCredential; +import org.julclang.ledger.TokenName; +import org.julclang.ledger.TxId; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxOut; +import org.julclang.ledger.TxOutRef; +import org.julclang.ledger.Value; +import org.julclang.testkit.ContractTest; +import org.julclang.testkit.ScriptContextTestBuilder; +import org.julclang.testkit.TestDataBuilder; +import org.julclang.vm.EvalResult; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.zeroj.circuit.lib.jubjub.JubjubCurve; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * {@code AuditorRegistry} in the Plutus VM (ADR-0007 N1): the one-shot Init and the rotation are + * accepted; every mutation that would duplicate the token, let it leave the exact address, skip a + * signature, break the generation count, change the entry's shape, register an encoding other than + * its coordinates' or register a key without a possession proof bound to this registry, this + * registrant and its key type is rejected. That includes the identity key, for which a possession + * proof with secret 0 does verify. + */ +class AuditorRegistryVmTest extends ContractTest { + + static final byte[] POLICY = filled(28, (byte) 0x3e); + static final byte[] OTHER_REGISTRY = filled(28, (byte) 0x3f); + static final byte[] TOKEN = "REG".getBytes(StandardCharsets.UTF_8); + static final byte[] AUDITOR = filled(28, (byte) 0xa1); + static final byte[] NEW_AUDITOR = filled(28, (byte) 0xa2); + static final TxOutRef SEED = new TxOutRef(TxId.of(filled(32, (byte) 0x5e)), BigInteger.valueOf(3)); + static final Address REGISTRY = new Address(new Credential.ScriptCredential(ScriptHash.of(POLICY)), Optional.empty()); + static final Address WALLET = new Address(new Credential.PubKeyCredential(PubKeyHash.of(AUDITOR)), Optional.empty()); + static final SecureRandom RANDOM = new SecureRandom(); + + private static Program program; + private static KeyPossession possession; + private static AuditorKeys keys0; + private static RegistryEntry gen0; + private static RegistryEntry gen5; + private static RegistryEntry otherRegistrant; + private static RegistryEntry otherRegistry; + private static RegistryEntry otherKey; + + @BeforeAll + static void setup() { + possession = new KeyPossession(); + byte[] seedRef = Arrays.copyOf(SEED.txId().hash(), 34); + seedRef[33] = 3; + var vk = possession.circuit().compressedVk(); + JubjubPoint g = JubjubPoint.SUBGROUP_GENERATOR.normalized(); + PlutusData[] ic = vk.ic().stream().map(PlutusData::bytes).toArray(PlutusData[]::new); + program = new AuditorRegistryVmTest().compileValidator(AuditorRegistry.class, Path.of("src/main/java")) + .program().applyParams(PlutusData.bytes(seedRef), PlutusData.bytes(TOKEN), + PlutusData.bytes(KeyPossession.ctxPrefix(KeyPossession.KeyType.ELGAMAL)), + PlutusData.bytes(KeyPossession.ctxPrefix(KeyPossession.KeyType.VIEWING)), + PlutusData.integer(g.affineU()), PlutusData.integer(g.affineV()), + PlutusData.bytes(vk.alpha()), PlutusData.bytes(vk.beta()), PlutusData.bytes(vk.gamma()), + PlutusData.bytes(vk.delta()), PlutusData.list(ic)); + keys0 = AuditorKeys.generate(RANDOM); + gen0 = keys0.entry(POLICY, AUDITOR, 0, possession); + gen5 = AuditorKeys.generate(RANDOM).entry(POLICY, NEW_AUDITOR, 5, possession); + otherRegistrant = AuditorKeys.generate(RANDOM).entry(POLICY, NEW_AUDITOR, 0, possession); + otherRegistry = AuditorKeys.generate(RANDOM).entry(OTHER_REGISTRY, AUDITOR, 0, possession); + otherKey = AuditorKeys.generate(RANDOM).entry(POLICY, AUDITOR, 0, possession); + } + + // ------------------------------------------------------------------ entries + + /** The 10 fields of an entry, to mutate one at a time. */ + static List fields(RegistryEntry e) { + return new ArrayList<>(List.of(PlutusData.bytes(e.auditor()), PlutusData.integer(BigInteger.valueOf(e.generation())), + PlutusData.integer(e.pkU()), PlutusData.integer(e.pkV()), PlutusData.bytes(e.pkEnc()), + PlutusData.integer(e.viewU()), PlutusData.integer(e.viewV()), PlutusData.bytes(e.viewKey()), + PlutusData.bytes(e.pkProof()), PlutusData.bytes(e.viewProof()))); + } + + static PlutusData constr(List fields) { + return PlutusData.constr(0, fields.toArray(new PlutusData[0])); + } + + static PlutusData datum(RegistryEntry e) { + return constr(fields(e)); + } + + static RegistryEntry atGeneration(RegistryEntry e, long generation) { + return new RegistryEntry(e.auditor(), generation, e.pkU(), e.pkV(), e.pkEnc(), e.viewU(), e.viewV(), + e.viewKey(), e.pkProof(), e.viewProof()); + } + + /** A valid possession proof for the identity key bound to {@code auditor}: secret 0, P = D = O = (0, 1). */ + static byte[] identityProof(byte[] auditor) { + BigInteger ctx = KeyPossession.ctx(KeyPossession.KeyType.ELGAMAL, POLICY, auditor); + JubjubPoint g = JubjubPoint.SUBGROUP_GENERATOR.normalized(); + var identity = KeyPossessionProofCircuit.inputs().ctx(ctx).ctxSquared(ctx.multiply(ctx).mod(Fields.FR)) + .baseU(g.affineU()).baseV(g.affineV()).keyU(BigInteger.ZERO).keyV(BigInteger.ONE) + .shareU(BigInteger.ZERO).shareV(BigInteger.ONE).secret(BigInteger.ZERO); + byte[] proof = ProofBytes.encode(possession.circuit().prove(identity.toWitnessMap())); + // Positive control: the proof really verifies, so only the u ≠ 0 rule can refuse the entry. + assertTrue(possession.circuit().verify(ProofBytes.decode(proof), List.of(ctx, g.affineU(), g.affineV(), + BigInteger.ZERO, BigInteger.ONE, BigInteger.ZERO, BigInteger.ONE)), "the identity's possession proof verifies"); + return proof; + } + + enum EntryMutation { + NONE, + // shape + WRONG_TAG, NINE_FIELDS, ELEVEN_FIELDS, AUDITOR_27, AUDITOR_29, NEGATIVE_GENERATION, + NON_CANONICAL_PK_U, NON_CANONICAL_PK_V, NON_CANONICAL_VIEW_V, SHORT_PROOF, SAME_KEYS, + // encodings + PK_ENC_OF_OTHER_KEY, VIEW_KEY_OF_OTHER_KEY, + // possession + PROOF_OF_OTHER_REGISTRANT, PROOF_FROM_OTHER_REGISTRY, PK_PROOF_OF_OTHER_KEY, GARBAGE_VIEW_PROOF, + PK_PROOF_UNDER_VIEW_TYPE, VIEW_PROOF_UNDER_ELGAMAL_TYPE, IDENTITY_KEY_WITH_VALID_PROOF + } + + /** Entry {@code e} with mutation {@code m}. Type-swap mutations need the secrets, so they apply to gen0 only. */ + static PlutusData entry(RegistryEntry e, EntryMutation m) { + List f = fields(e); + switch (m) { + case WRONG_TAG -> { return PlutusData.constr(1, f.toArray(new PlutusData[0])); } + case NINE_FIELDS -> f.remove(9); + case ELEVEN_FIELDS -> f.add(PlutusData.integer(BigInteger.ONE)); + case AUDITOR_27 -> f.set(0, PlutusData.bytes(Arrays.copyOf(e.auditor(), 27))); + case AUDITOR_29 -> f.set(0, PlutusData.bytes(Arrays.copyOf(e.auditor(), 29))); + case NEGATIVE_GENERATION -> f.set(1, PlutusData.integer(BigInteger.valueOf(-1))); + case NON_CANONICAL_PK_U -> f.set(2, PlutusData.integer(e.pkU().add(JubjubCurve.BASE_FIELD_PRIME))); + case NON_CANONICAL_PK_V -> f.set(3, PlutusData.integer(e.pkV().add(JubjubCurve.BASE_FIELD_PRIME))); + case NON_CANONICAL_VIEW_V -> f.set(6, PlutusData.integer(e.viewV().add(JubjubCurve.BASE_FIELD_PRIME))); + case SHORT_PROOF -> f.set(8, PlutusData.bytes(Arrays.copyOf(e.pkProof(), 191))); + case SAME_KEYS -> { + f.set(5, PlutusData.integer(e.pkU())); + f.set(6, PlutusData.integer(e.pkV())); + f.set(7, PlutusData.bytes(e.pkEnc())); + f.set(9, PlutusData.bytes(e.pkProof())); + } + case PK_ENC_OF_OTHER_KEY -> f.set(4, PlutusData.bytes(otherKey.pkEnc())); + case VIEW_KEY_OF_OTHER_KEY -> f.set(7, PlutusData.bytes(otherKey.viewKey())); + // Another registrant's keys and proofs (bound to NEW_AUDITOR), claimed by e's auditor. + case PROOF_OF_OTHER_REGISTRANT -> { + List o = fields(otherRegistrant); + o.set(0, PlutusData.bytes(e.auditor())); + o.set(1, PlutusData.integer(BigInteger.valueOf(e.generation()))); + return constr(o); + } + // Keys and proofs copied from another registry's entry by the same auditor key hash. + case PROOF_FROM_OTHER_REGISTRY -> { + List o = fields(otherRegistry); + o.set(1, PlutusData.integer(BigInteger.valueOf(e.generation()))); + return constr(o); + } + case PK_PROOF_OF_OTHER_KEY -> f.set(8, PlutusData.bytes(otherKey.pkProof())); + case GARBAGE_VIEW_PROOF -> f.set(9, PlutusData.bytes(new byte[192])); + // The same key's own statement, proved under the other key type's context. + case PK_PROOF_UNDER_VIEW_TYPE -> f.set(8, PlutusData.bytes(possession.prove( + KeyPossession.ctx(KeyPossession.KeyType.VIEWING, POLICY, e.auditor()), + keys0.elgamal().possessionStatement(), keys0.elgamal().secretScalar()))); + case VIEW_PROOF_UNDER_ELGAMAL_TYPE -> f.set(9, PlutusData.bytes(keys0.viewing().provePossession( + (s, x) -> possession.prove(KeyPossession.ctx(KeyPossession.KeyType.ELGAMAL, POLICY, e.auditor()), s, x)))); + case IDENTITY_KEY_WITH_VALID_PROOF -> { + f.set(2, PlutusData.integer(BigInteger.ZERO)); + f.set(3, PlutusData.integer(BigInteger.ONE)); + f.set(4, PlutusData.bytes(JubjubPoint.IDENTITY.toBytes())); + f.set(8, PlutusData.bytes(identityProof(e.auditor()))); + } + default -> { } + } + return constr(f); + } + + // ------------------------------------------------------------------ Init + + enum InitMutation { + NONE, NO_SEED, MINT_TWO, EXTRA_MINT_NAME, OTHER_NAME_ONLY, NO_SIGNER, GENERATION_ONE, STAKED_OUTPUT, + TWO_OUTPUTS, EXTRA_ASSET, REGISTRY_INPUT_SPENT, NO_OUTPUT, HASHED_DATUM, NO_DATUM + } + + @Test + @DisplayName("Init: the seed-bound singleton is minted once into a well-formed, possession-verified entry; every mutation is rejected") + void init() { + var honest = evaluate(program, initContext(InitMutation.NONE, EntryMutation.NONE)); + assertInstanceOf(EvalResult.Success.class, honest); + System.out.println("[AuditorRegistry init] budget: " + honest.budgetConsumed()); + for (InitMutation m : InitMutation.values()) { + if (m != InitMutation.NONE && evaluate(program, initContext(m, EntryMutation.NONE)) instanceof EvalResult.Success) { + fail("Init accepted " + m); + } + } + for (EntryMutation m : EntryMutation.values()) { + if (m != EntryMutation.NONE && evaluate(program, initContext(InitMutation.NONE, m)) instanceof EvalResult.Success) { + fail("Init accepted entry " + m); + } + } + } + + private PlutusData initContext(InitMutation m, EntryMutation e) { + Value mint = switch (m) { + case MINT_TWO -> token(2); + case EXTRA_MINT_NAME -> token(1).merge(Value.singleton(PolicyId.of(POLICY), TokenName.of("X".getBytes()), BigInteger.ONE)); + case OTHER_NAME_ONLY -> Value.singleton(PolicyId.of(POLICY), TokenName.of("X".getBytes()), BigInteger.ONE); + default -> token(1); + }; + var b = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).mint(mint).redeemer(PlutusData.integer(0)); + if (m != InitMutation.NO_SIGNER) b.signer(AUDITOR); + TxOutRef seed = m == InitMutation.NO_SEED ? TestDataBuilder.randomTxOutRef_typed() : SEED; + b.input(new TxInInfo(seed, new TxOut(WALLET, ada(10), new OutputDatum.NoOutputDatum(), Optional.empty()))); + if (m == InitMutation.REGISTRY_INPUT_SPENT) { + b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(REGISTRY, ada(5), + new OutputDatum.OutputDatumInline(PlutusData.integer(0)), Optional.empty()))); + } + PlutusData datum = m == InitMutation.GENERATION_ONE ? datum(atGeneration(gen0, 1)) : entry(gen0, e); + Address at = m == InitMutation.STAKED_OUTPUT ? staked() : REGISTRY; + Value value = ada(5).merge(m == InitMutation.MINT_TWO ? token(2) : token(1)); + if (m == InitMutation.EXTRA_ASSET) value = value.merge(foreignAsset()); + OutputDatum od = switch (m) { + case HASHED_DATUM -> new OutputDatum.OutputDatumHash(DatumHash.of(filled(32, (byte) 9))); + case NO_DATUM -> new OutputDatum.NoOutputDatum(); + default -> new OutputDatum.OutputDatumInline(datum); + }; + if (m != InitMutation.NO_OUTPUT) b.output(new TxOut(at, value, od, Optional.empty())); + if (m == InitMutation.TWO_OUTPUTS) { + b.output(new TxOut(REGISTRY, ada(5), new OutputDatum.OutputDatumInline(datum(gen0)), Optional.empty())); + } + return b.buildPlutusData(); + } + + // ------------------------------------------------------------------ Rotate + + enum RotateMutation { + NONE, NO_OLD_SIGNER, NO_NEW_SIGNER, SAME_GENERATION, GENERATION_PLUS_TWO, STAKED_OUTPUT, TOKEN_TO_WALLET, + TWO_OUTPUTS, MINT_DURING_ROTATE, BURN_DURING_ROTATE, INPUT_WITHOUT_TOKEN, SECOND_REGISTRY_INPUT, EXTRA_ASSET, + NEW_ENTRY_OF_OTHER_REGISTRANT + } + + @Test + @DisplayName("Rotate: the entry moves forward one generation under both auditors' signatures; every mutation is rejected") + void rotate() { + var honest = evaluate(program, rotateContext(RotateMutation.NONE, EntryMutation.NONE)); + assertInstanceOf(EvalResult.Success.class, honest); + System.out.println("[AuditorRegistry rotate] budget: " + honest.budgetConsumed()); + for (RotateMutation m : RotateMutation.values()) { + if (m != RotateMutation.NONE && evaluate(program, rotateContext(m, EntryMutation.NONE)) instanceof EvalResult.Success) { + fail("Rotate accepted " + m); + } + } + for (EntryMutation m : List.of(EntryMutation.NINE_FIELDS, EntryMutation.PK_ENC_OF_OTHER_KEY, + EntryMutation.VIEW_KEY_OF_OTHER_KEY, EntryMutation.GARBAGE_VIEW_PROOF, + EntryMutation.PROOF_FROM_OTHER_REGISTRY, EntryMutation.IDENTITY_KEY_WITH_VALID_PROOF, + EntryMutation.NON_CANONICAL_PK_V)) { + if (evaluate(program, rotateContext(RotateMutation.NONE, m)) instanceof EvalResult.Success) { + fail("Rotate accepted new entry " + m); + } + } + } + + private PlutusData rotateContext(RotateMutation m, EntryMutation e) { + TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x61)), BigInteger.ZERO); + PlutusData old = datum(atGeneration(gen0, 4)); + var b = ScriptContextTestBuilder.spending(ownRef, old).redeemer(PlutusData.integer(0)); + Value held = m == RotateMutation.INPUT_WITHOUT_TOKEN ? ada(5) : ada(5).merge(token(1)); + b.input(new TxInInfo(ownRef, new TxOut(REGISTRY, held, new OutputDatum.OutputDatumInline(old), Optional.empty()))); + if (m == RotateMutation.SECOND_REGISTRY_INPUT) { + b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(staked(), ada(5), + new OutputDatum.OutputDatumInline(PlutusData.integer(0)), Optional.empty()))); + } + if (m != RotateMutation.NO_OLD_SIGNER) b.signer(AUDITOR); + if (m != RotateMutation.NO_NEW_SIGNER) b.signer(NEW_AUDITOR); + if (m == RotateMutation.MINT_DURING_ROTATE) { + b.mint(Value.singleton(PolicyId.of(POLICY), TokenName.of("X".getBytes()), BigInteger.ONE)); + } + if (m == RotateMutation.BURN_DURING_ROTATE) b.mint(token(-1)); + long generation = switch (m) { + case SAME_GENERATION -> 4; + case GENERATION_PLUS_TWO -> 6; + default -> 5; + }; + PlutusData next = m == RotateMutation.NEW_ENTRY_OF_OTHER_REGISTRANT + // gen0's keys and proofs (bound to AUDITOR) claimed by NEW_AUDITOR. + ? datum(new RegistryEntry(NEW_AUDITOR, 5, gen0.pkU(), gen0.pkV(), gen0.pkEnc(), gen0.viewU(), gen0.viewV(), + gen0.viewKey(), gen0.pkProof(), gen0.viewProof())) + : entry(atGeneration(gen5, generation), e); + Value value = ada(5).merge(token(1)); + if (m == RotateMutation.EXTRA_ASSET) value = value.merge(foreignAsset()); + Address at = switch (m) { + case STAKED_OUTPUT -> staked(); + case TOKEN_TO_WALLET -> WALLET; + default -> REGISTRY; + }; + b.output(new TxOut(at, value, new OutputDatum.OutputDatumInline(next), Optional.empty())); + if (m == RotateMutation.TWO_OUTPUTS) { + b.output(new TxOut(REGISTRY, ada(5), new OutputDatum.OutputDatumInline(datum(gen5)), Optional.empty())); + } + return b.buildPlutusData(); + } + + // ------------------------------------------------------------------ + + static Address staked() { + return new Address(REGISTRY.credential(), Optional.of(new StakingCredential.StakingHash( + new Credential.PubKeyCredential(PubKeyHash.of(filled(28, (byte) 0x5a)))))); + } + + static Value token(long qty) { + return Value.singleton(PolicyId.of(POLICY), TokenName.of(TOKEN), BigInteger.valueOf(qty)); + } + + static Value foreignAsset() { + return Value.singleton(PolicyId.of(filled(28, (byte) 0x77)), TokenName.of("Z".getBytes()), BigInteger.ONE); + } + + static Value ada(long ada) { + return Value.lovelace(BigInteger.valueOf(ada * 1_000_000)); + } + + static byte[] filled(int length, byte value) { + byte[] out = new byte[length]; + Arrays.fill(out, value); + return out; + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryAdmissionTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryAdmissionTest.java new file mode 100644 index 0000000..aff6e9b --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryAdmissionTest.java @@ -0,0 +1,111 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import com.bloxbean.cardano.client.plutus.spec.PlutusData; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.function.UnaryOperator; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * Registry admission (ADR-0007 N5; ZeroJ ADR-0055 M3 criterion (b)): an entry is admitted only + * with both possession proofs verifying for exactly its keys under this registry, this auditor and + * each key's own type, and with coordinates equal to each key's encoding. + */ +class RegistryAdmissionTest { + + private static final SecureRandom RANDOM = new SecureRandom(); + private static final byte[] AUDITOR = filled(28, (byte) 0xa1); + private static final byte[] POLICY = filled(28, (byte) 0x3e); + private static KeyPossession possession; + private static AuditorKeys keys; + private static RegistryEntry entry; + private static RegistryEntry other; + + @BeforeAll + static void setup() { + possession = new KeyPossession(); + keys = AuditorKeys.generate(RANDOM); + entry = keys.entry(POLICY, AUDITOR, 0, possession); + other = AuditorKeys.generate(RANDOM).entry(POLICY, AUDITOR, 0, possession); + } + + @Test + @DisplayName("An honest entry is admitted, and survives a round trip through its datum") + void honest() throws Exception { + AdmittedAuditor admitted = AdmittedAuditor.admit(POLICY, entry, possession); + assertEquals(keys.elgamal().publicKey().affineU(), admitted.pkU()); + assertEquals(keys.viewing().readerKey(), admitted.viewKey()); + RegistryEntry back = RegistryEntry.fromPlutusData(PlutusData.deserialize(entry.toPlutusData().serializeToBytes())); + assertArrayEquals(entry.pkProof(), back.pkProof()); + assertEquals(entry.viewU(), back.viewU()); + AdmittedAuditor.admit(POLICY, back, possession); + // The possession statements' base is the generator the registry script is built with. + JubjubPoint g = JubjubPoint.SUBGROUP_GENERATOR.normalized(); + assertEquals(g.affineU(), keys.elgamal().possessionStatement().publicInputs().get(0)); + assertEquals(g.affineV(), keys.elgamal().possessionStatement().publicInputs().get(1)); + } + + @Test + @DisplayName("Refused: swapped or foreign proofs, the wrong key type, mismatched coordinates, equal keys, replay") + void refusals() { + refused(e -> with(e, 8, e.viewProof()), "the viewing key's proof for the ElGamal key"); + refused(e -> with(e, 9, e.pkProof()), "the ElGamal key's proof for the viewing key"); + refused(e -> with(e, 8, other.pkProof()), "another key's ElGamal proof"); + refused(e -> with(e, 9, other.viewProof()), "another key's viewing-key proof"); + byte[] corrupt = entry.pkProof().clone(); + corrupt[10] ^= 1; + refused(e -> with(e, 8, corrupt), "a corrupted proof"); + refused(e -> with(e, 8, Arrays.copyOf(e.pkProof(), 191)), "a short proof"); + refused(e -> new RegistryEntry(e.auditor(), 0, e.pkU().add(BigInteger.ONE), e.pkV(), e.pkEnc(), e.viewU(), + e.viewV(), e.viewKey(), e.pkProof(), e.viewProof()), "ElGamal coordinates that are not its encoding"); + refused(e -> new RegistryEntry(e.auditor(), 0, e.pkU(), e.pkV(), e.pkEnc(), e.viewU().add(BigInteger.ONE), + e.viewV(), e.viewKey(), e.pkProof(), e.viewProof()), "viewing coordinates that are not its encoding"); + refused(e -> new RegistryEntry(e.auditor(), 0, other.pkU(), other.pkV(), other.pkEnc(), e.viewU(), e.viewV(), + e.viewKey(), e.pkProof(), e.viewProof()), "another key with this entry's proof"); + refused(e -> new RegistryEntry(e.auditor(), 0, e.pkU(), e.pkV(), e.pkEnc(), e.pkU(), e.pkV(), e.pkEnc(), + e.pkProof(), e.pkProof()), "the same key as both"); + + // Key-type binding in isolation: each key's own statement, proved under the other type. + byte[] pkUnderView = possession.prove(KeyPossession.ctx(KeyPossession.KeyType.VIEWING, POLICY, AUDITOR), + keys.elgamal().possessionStatement(), keys.elgamal().secretScalar()); + refused(e -> with(e, 8, pkUnderView), "the ElGamal key proved under the viewing type"); + byte[] viewUnderPk = keys.viewing().provePossession((s, x) -> possession.prove( + KeyPossession.ctx(KeyPossession.KeyType.ELGAMAL, POLICY, AUDITOR), s, x)); + refused(e -> with(e, 9, viewUnderPk), "the viewing key proved under the ElGamal type"); + + // Replay: this entry's keys and proofs, claimed in another registry or by another registrant. + assertThrows(IllegalArgumentException.class, () -> AdmittedAuditor.admit(filled(28, (byte) 0x3f), entry, possession), + "proofs bound to another registry"); + refused(e -> new RegistryEntry(filled(28, (byte) 1), 0, e.pkU(), e.pkV(), e.pkEnc(), e.viewU(), e.viewV(), + e.viewKey(), e.pkProof(), e.viewProof()), "proofs bound to another registrant"); + } + + private static void refused(UnaryOperator mutate, String what) { + RegistryEntry mutated = mutate.apply(entry); + assertThrows(IllegalArgumentException.class, () -> AdmittedAuditor.admit(POLICY, mutated, possession), what); + } + + /** {@code e} with proof field 8 ({@code pkProof}) or 9 ({@code viewProof}) replaced. */ + private static RegistryEntry with(RegistryEntry e, int field, byte[] proof) { + return field == 8 + ? new RegistryEntry(e.auditor(), e.generation(), e.pkU(), e.pkV(), e.pkEnc(), e.viewU(), e.viewV(), + e.viewKey(), proof, e.viewProof()) + : new RegistryEntry(e.auditor(), e.generation(), e.pkU(), e.pkV(), e.pkEnc(), e.viewU(), e.viewV(), + e.viewKey(), e.pkProof(), proof); + } + + static byte[] filled(int length, byte value) { + byte[] out = new byte[length]; + Arrays.fill(out, value); + return out; + } +} From 74206090ff6136abfc05abfef2cca98a9dd4ec0e Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 10 Oct 2026 16:47:38 +0800 Subject: [PATCH 04/12] pedersen-commitments: confidential notes for points, payroll and solvency (ADR-0007 M3a-M5; ZeroJ ADR-0055 M3) NoteLedger replaces PointsLedger. A note is Note(owner, u, v, generation, audit, deliveries): the Pedersen commitment, the registry generation, two elgamal-jubjub-v1 limb ciphertexts of the amount to the auditor (D3a) and confidential-note-jubjub-v1 deliveries to the owner and the auditor. - Address policy (ADR-0055 M3 criterion (a)): every output under the ledger's payment credential must be a note at the exact enterprise address, holding exactly lovelace and one note token, of the current generation. - D3a direct layout (spec 8.2): transfer and redeem prove each created note's limbs encrypt the amount that opens its commitment, PK_a from exactly one registry reference input, distinct handles. Complete transactions in the Julc VM: transfer 76.5% of the step limit, redeem 58.0% (DevKit: 76.8%, 58.3%), within the 80% gate; circuits equal ZeroJ's reference (34,184 and 18,366 constraints). - Payroll: proof-enforced issuance (Q9 (b)), NoteIssueProof for one or two notes (50.8% / 71.8%); an employer that under-reports has no proof. - Verification keys are pinned by blake2b(serialiseData(vk)) and carried in the redeemer (VkLib); the ledger is deployed as a reference script. - Wallets (NoteWallet) recover notes from chain data with their viewing key; owned-but-unopenable notes are reported, notes readable but owned by others are not counted. The auditor (AuditorView) reads every amount with the keys of the note's generation and labels it proof-enforced or issuer-claimed. Senders encrypt limbs only with ElGamal.encryptWithOpening under an admitted registry key (M3 criterion (b)). - Solvency: each entry carries its customer's delivery and the attestation the auditor's aggregate delivery; customers and the auditor check from chain. - UI: points tab reworked (chain-scanned wallets, auditor panel, rotation, garbage-delivery / under-report / retired-key / stake-variant cheats), new payroll tab, solvency tab with on-chain openings. CLI walkthrough updated. Tests: NoteLedger VM mutations (every ADR-0006 P1-P8 and ADR-0055 D3a/D8 case, stake-variant output, reused handles, stale generation, registry mutations, under-reported proved issuance), guards checked by reverting them; I12 invalid witnesses; DevKit E2E for points (issue, transfer, redeem, recovery by owner and auditor, unopenable garbage delivery, rotation with stale limbs refused); solvency VM and unit tests for deliveries. Co-Authored-By: Claude Opus 5.5 --- ...07-confidential-notes-in-pedersen-demos.md | 21 +- pedersen-commitments/frontend/src/App.svelte | 8 +- .../frontend/src/lib/NoteLedgerView.svelte | 85 +++ .../frontend/src/tabs/Payroll.svelte | 101 +++ .../frontend/src/tabs/Points.svelte | 97 ++- .../frontend/src/tabs/Solvency.svelte | 23 +- .../usecases/pedersen/PedersenDemos.java | 118 ++-- .../usecases/pedersen/common/DevKit.java | 23 +- .../usecases/pedersen/notes/AuditedNote.java | 102 ++++ .../usecases/pedersen/notes/AuditorView.java | 118 ++++ .../usecases/pedersen/notes/ChainNote.java | 84 +++ .../pedersen/notes/NoteLedgerScript.java | 264 ++++++++ .../usecases/pedersen/notes/NoteProofs.java | 151 +++++ .../usecases/pedersen/notes/NoteWallet.java | 64 ++ .../pedersen/notes/VerificationKeys.java | 42 ++ .../pedersen/notes/circuit/AuditLimbs.java | 33 + .../notes/circuit/NoteIssueProof.java | 62 ++ .../circuit/NoteRedeemProof.java} | 29 +- .../notes/circuit/NoteTransferProof.java | 65 ++ .../pedersen/notes/onchain/NoteLedger.java | 312 ++++++++++ .../pedersen/notes/onchain/NoteLib.java | 141 +++++ .../pedersen/notes/onchain/VkLib.java | 33 + .../pedersen/points/ConfidentialPoints.java | 245 -------- .../points/circuit/PointsTransferProof.java | 46 -- .../pedersen/points/onchain/PointsLedger.java | 370 ----------- .../solvency/SolvencyAttestation.java | 131 +++- .../solvency/onchain/SolvencyVault.java | 24 +- .../usecases/pedersen/web/DemoController.java | 54 +- .../usecases/pedersen/web/DemoErrors.java | 14 + .../zeroj/usecases/pedersen/web/NoteDemo.java | 356 +++++++++++ .../usecases/pedersen/web/PayrollService.java | 56 ++ .../usecases/pedersen/web/PointsService.java | 297 ++------- .../pedersen/web/SolvencyService.java | 99 ++- .../pedersen/notes/NoteCircuitTest.java | 174 ++++++ .../pedersen/notes/NoteLedgerVmTest.java | 578 ++++++++++++++++++ .../notes/PointsNotesDevKitE2ETest.java | 161 +++++ .../pedersen/points/PointsCircuitTest.java | 101 --- .../pedersen/points/PointsDevKitE2ETest.java | 87 --- .../pedersen/points/PointsLedgerVmTest.java | 336 ---------- .../solvency/SolvencyCircuitTest.java | 62 +- .../solvency/SolvencyDevKitE2ETest.java | 33 +- .../solvency/SolvencyVaultVmTest.java | 40 +- 42 files changed, 3587 insertions(+), 1653 deletions(-) create mode 100644 pedersen-commitments/frontend/src/lib/NoteLedgerView.svelte create mode 100644 pedersen-commitments/frontend/src/tabs/Payroll.svelte create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditedNote.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorView.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/ChainNote.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerScript.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteProofs.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteWallet.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/VerificationKeys.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/circuit/AuditLimbs.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/circuit/NoteIssueProof.java rename pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/{points/circuit/PointsRedeemProof.java => notes/circuit/NoteRedeemProof.java} (50%) create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/circuit/NoteTransferProof.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLedger.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLib.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/VkLib.java delete mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/ConfidentialPoints.java delete mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/circuit/PointsTransferProof.java delete mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/onchain/PointsLedger.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/NoteDemo.java create mode 100644 pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/PayrollService.java create mode 100644 pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteCircuitTest.java create mode 100644 pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerVmTest.java create mode 100644 pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/PointsNotesDevKitE2ETest.java delete mode 100644 pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsCircuitTest.java delete mode 100644 pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsDevKitE2ETest.java delete mode 100644 pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsLedgerVmTest.java diff --git a/docs/adr/0007-confidential-notes-in-pedersen-demos.md b/docs/adr/0007-confidential-notes-in-pedersen-demos.md index a6e0d73..f688d1c 100644 --- a/docs/adr/0007-confidential-notes-in-pedersen-demos.md +++ b/docs/adr/0007-confidential-notes-in-pedersen-demos.md @@ -494,9 +494,24 @@ their own inputs"): ## Measurements -To be filled in at M3a and M4: constraints, prover time, and the Julc VM cost of the complete -transaction as a percentage of `maxTxExecutionUnits` (10e9 steps, 16.5e6 memory), for transfer, -redeem, and proved issuance with n = 1 and n = 2. +Julc VM, Plutus V3 cost model (protocol version 11), against `maxTxExecutionUnits` (10e9 steps, +16.5e6 memory). Each figure is the **complete** transaction: every script purpose it runs, added up. +Verification keys are pinned by hash and carried in the redeemer (r2). + +| Transaction | Circuit constraints | Public inputs | Steps | Memory | +|---|---|---|---|---| +| Transfer (spend + Split mint), direct layout | 34,184 | 24 | 7.65e9 (76.5%) | 2.59e6 (15.7%) | +| Redeem (spend + Receipt mint), direct layout | 18,366 | 15 | 5.80e9 (58.0%) | 2.02e6 (12.2%) | +| Proved issue, one note (mint) | 15,890 | 12 | 5.08e9 (50.8%) | 1.49e6 (9.0%) | +| Proved issue, two notes (mint) | 31,773 | 22 | 7.18e9 (71.8%) | 2.26e6 (13.7%) | +| Trusted issue, two notes (mint) | — | — | 0.37e9 (3.7%) | 1.29e6 (7.8%) | +| Registry Init / Rotate (two possession proofs) | 2 × 7 inputs | — | 7.77e9 / 7.82e9 | 1.41e6 / 1.55e6 | + +**Gate outcome:** every note transaction is within ADR-0055's 80% gate with the **direct layout** +(spec §8.2), so the hash-compressed layout is not used. The transfer leaves 3.5 points of margin. +The transfer and redeem circuits are exactly the size of ZeroJ's reference D3a circuits (34,184 +and 18,366 constraints), an independent cross-check of the composition. The on-DevKit figures +(from the Julc evaluator on the real transactions) are recorded at M3a's end-to-end run. ## Production gates (not met by this demo) diff --git a/pedersen-commitments/frontend/src/App.svelte b/pedersen-commitments/frontend/src/App.svelte index 1abdb09..4a0efc7 100644 --- a/pedersen-commitments/frontend/src/App.svelte +++ b/pedersen-commitments/frontend/src/App.svelte @@ -3,6 +3,7 @@ import Points from './tabs/Points.svelte'; import Credit from './tabs/Credit.svelte'; import Solvency from './tabs/Solvency.svelte'; + import Payroll from './tabs/Payroll.svelte'; let tab = $state('points'); let status = $state(null); @@ -21,8 +22,9 @@

Hiding, binding and additive commitments with zero-knowledge proofs, verified by Plutus V3 on Yaci DevKit

- Demo server. This server creates every wallet and holds every opening (amounts, blindings, - profiles, customer balances) and key on the users' behalf; real users would each keep their own. + Demo server. This server creates every wallet and holds every key on the users' behalf — spending + keys, note viewing keys, the auditor's keys — and scans the chain for them; real users would each keep their own and + scan in their own wallet (ZeroJ ADR-0055 D9). Note balances are recovered from the chain, not kept in memory. The On-chain panels show what anyone can read from the ledger.
@@ -42,12 +44,14 @@ {#if status?.demos?.[tab] === 'ready'} {#if tab === 'points'}{/if} + {#if tab === 'payroll'}{/if} {#if tab === 'credit'}{/if} {#if tab === 'solvency'}{/if} {:else if status} diff --git a/pedersen-commitments/frontend/src/lib/NoteLedgerView.svelte b/pedersen-commitments/frontend/src/lib/NoteLedgerView.svelte new file mode 100644 index 0000000..b404c32 --- /dev/null +++ b/pedersen-commitments/frontend/src/lib/NoteLedgerView.svelte @@ -0,0 +1,85 @@ + + +
+
+

Wallets — recovered from the chain with each viewing key

+ {#each Object.entries(state.wallets) as [label, w]} +

{label}: balance {w.balance} {unit} + {#if w.unopenable.length > 0}{w.unopenable.length} unopenable owned note{w.unopenable.length > 1 ? 's' : ''}{/if} + {#if w.readableNotMine > 0}{w.readableNotMine} readable, not owned{/if} +

+ {#if w.notes.length > 0} + + + + {#each w.notes as n}{/each} + +
amountcommitment (u)gennote UTxO
{n.amount}{n.commitment}{n.generation}{n.utxo}
+ {/if} + {#each w.unopenable as u}

Owned but unopenable: {u} — the sender's delivery does not open to the commitment.

{/each} + {/each} +
+ +
+

On-chain — what anyone can see

+

Notes at {state.ledgerAddress.substring(0, 34)}…: owner, commitment, generation, two limb + ciphertexts and two encrypted openings — never the amount.

+ + + + {#each state.onChain as n}{/each} + +
note UTxOownercommitment ugenlimb A.udeliveries
{n.utxo}{n.owner}{n.u}{n.generation}{n.limbHandle}{n.deliveries} × 89 B
+ {#if state.receipts.length > 0} +

Receipts held by the issuer

+ + + + {#each state.receipts as r}{/each} + +
receipt UTxOspenderprice
{r.utxo}{r.spender}{r.price}
+ {/if} +
+
+ +
+

{state.auditor.label} — reads every amount from the chain

+

Registry generation {state.registry.generation} · ElGamal key {state.registry.elgamalKey} + · viewing key {state.registry.viewingKey}. Amounts come from the limb ciphertexts (keys of the note's generation); + each is cross-checked against the auditor's own encrypted opening.

+ + + + {#each state.auditor.notes as a} + + + + + + {/each} + +
note UTxOowneramountorigingencheck
{a.utxo}{a.owner}{a.amount}{a.origin}{a.generation}{a.status}
+

Totals by owner: + {#each Object.entries(state.auditor.totals) as [owner, total], i}{i > 0 ? ' · ' : ''}{owner} {total}{/each}

+
+ +{#if state.history.length > 0} +

Transactions

+ + + {#each state.history as h}{/each} + +
{h.summary}{h.cost ?? ''}{h.txHash.substring(0, 20)}…
+{/if} + + diff --git a/pedersen-commitments/frontend/src/tabs/Payroll.svelte b/pedersen-commitments/frontend/src/tabs/Payroll.svelte new file mode 100644 index 0000000..a16f7af --- /dev/null +++ b/pedersen-commitments/frontend/src/tabs/Payroll.svelte @@ -0,0 +1,101 @@ + + +
+

Confidential payroll

+

The employer pays salaries as confidential notes. Unlike the points demo, issuance is + proof-enforced (ADR-0055 Q9 (b)): every pay run carries a Groth16 proof that each salary note's limbs encrypt + its committed amount to the tax authority's registered key. So the tax authority reads every salary from the chain, + and the employer cannot under-report one. Employees read their payslips from the chain with their viewing keys. + Circuits: pay {state?.constraints?.issue ?? '…'} constraints, transfer {state?.constraints?.transfer ?? '…'}, + cash-out {state?.constraints?.redeem ?? '…'}.

+ +
+
+

Pay a salary (employer)

+ + + +
+
+

Transfer between employees

+ + + + +
+
+

Cash out at the employer

+ + + +
+
+

Tax authority key rotation

+

Registry generation {state?.registry?.generation ?? '…'}.

+ +
+
+ +

Try to cheat

+
+
+

Under-report a salary to the tax authority

+ +

The employer pays {salary} but encrypts {reported} to the tax authority. The issuance proof cannot be + produced — compare the points tab, where trusted issuance lets the issuer do this.

+ +
+
+

Garbage payslip

+

{from} sends {amount} to {to} with a garbage encrypted opening: {to} sees an unopenable payslip, while + the tax authority still reads the amount.

+ +
+
+

Limbs to the retired key

+

After a rotation, the amounts are encrypted to the tax authority's previous key: refused.

+ +
+
+ + {#if busy}

{busy}… (proving and waiting for the block)

{/if} + + + {#if state} + + {/if} +
diff --git a/pedersen-commitments/frontend/src/tabs/Points.svelte b/pedersen-commitments/frontend/src/tabs/Points.svelte index 058109b..9df2dae 100644 --- a/pedersen-commitments/frontend/src/tabs/Points.svelte +++ b/pedersen-commitments/frontend/src/tabs/Points.svelte @@ -1,6 +1,7 @@ + +
+

Sealed-bid auction

+

Each bid is encrypted to the auctioneer (elgamal-jubjub-v1) with a Groth16 proof that it + lies between the reserve and the deposit, so a bidder cannot refuse to reveal its bid — there is no + reveal phase. Everyone locks the same public deposit. After the bidding window the auctioneer decrypts every bid and + proves, in zero knowledge, who placed the earliest highest bid and its amount, without publishing the losing bids. + If it never settles, anyone can return the deposits and the item. Circuits: bid {state?.constraints?.bid ?? '…'} + constraints, settlement of 3 bids {state?.constraints?.settle3 ?? '…'}.

+ +
+
+

1. Seller lists an item

+ + + + +
+
+

2. Sealed bid

+ + + +

Cheat: bid above the deposit or below the reserve — no proof exists.

+
+
+

3. Auctioneer settles

+ + + +
+
+ +

Try to cheat

+
+
+

Copy another bid

+ + +

The copier submits a bid proof made for {copied}. The proof is bound to its bidder's key hash, so the + lot refuses it.

+ +
+
+

Auctioneer names another winner

+ +

The settlement proof shows the named bid is the earliest highest one; for any other bid no proof exists.

+ +
+
+ + {#if busy}

{busy}… (proving and waiting for the block)

{/if} + + + {#if state} + {#if state.lot} +
+ Lot {state.lot.item} · deposit {state.lot.deposit} ADA · reserve {state.lot.reserve} ADA · + {#if phase === 'bidding'}bidding closes in {seconds(state.lot.biddingEnds)} s{/if} + {#if phase === 'settling'}bidding closed; the auctioneer may settle for {seconds(state.lot.settleBy)} s{/if} + {#if phase === 'expired'}settlement deadline passed: anyone can refund{/if} +
+ {:else if state.closed} +
The last lot is closed (settled or refunded). Open a new one.
+ {/if} +
+
+

On-chain — what anyone can see

+ {#if state.lot} +

Lot UTxO holding the item, {state.lot.lockedAda} ADA (deposits + lot ADA) and the lot token. + Auctioneer key generation {state.lot.generation}.

+ + + + {#each state.lot.bids as b, i}{/each} + +
#bidderhandle A.uciphertext B.u
{i + 1}{b.bidder}{b.handle}{b.ciphertext}
+ {:else}

No open lot.

{/if} +

Balances

+ + {#each state.wallets as w}{/each} +
{w.wallet}{w.ada} ADA
+
+
+

Auctioneer's private view — decrypted bids

+ {#if state.auctioneerView && state.auctioneerView.length > 0} + + + + {#each state.auctioneerView as b, i}{/each} + +
#bidderbid
{i + 1}{b.bidder}{b.amount} ADA
+

Only the auctioneer can decrypt these; they never appear on-chain. (This demo server holds the auctioneer's key and shows its view to anyone, for the demo.) The auctioneer is trusted for confidentiality, not for the outcome.

+ {:else}

No bids yet.

{/if} +
+
+ {#if state.history.length > 0} +

Transactions

+ + + {#each state.history as h}{/each} + +
{h.summary}{h.cost ?? ''}{h.txHash.substring(0, 20)}…
+ {/if} + {/if} +
diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionProofs.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionProofs.java new file mode 100644 index 0000000..21c02ef --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionProofs.java @@ -0,0 +1,76 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.auction; + +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.circuit.BidProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.circuit.SettleProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.KeyedCircuit; +import org.zeroj.circuit.lib.jubjub.ElGamalCiphertext; +import org.zeroj.circuit.lib.jubjub.ElGamalEncryption; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +/** + * The auction circuits with their keys (ADR-0008 D3, D4): the bid relation and the settlement + * relation for 1, 2 and 3 bids. + */ +public final class AuctionProofs { + + private final KeyedCircuit bid; + private final List settle; + + public AuctionProofs() { + bid = KeyedCircuit.compile("sealed-bid", BidProofCircuit.build()); + settle = List.of( + KeyedCircuit.compile("sealed-bid-settle-n1", SettleProofCircuit.build(1, 4)), + KeyedCircuit.compile("sealed-bid-settle-n2", SettleProofCircuit.build(2, 8)), + KeyedCircuit.compile("sealed-bid-settle-n3", SettleProofCircuit.build(3, 12))); + } + + public KeyedCircuit bid() { return bid; } + + public KeyedCircuit settle(int bids) { + if (bids < 1 || bids > 3) throw new IllegalArgumentException("1 to 3 bids"); + return settle.get(bids - 1); + } + + /** {@code OS2IP(bidder)}: the 28-byte key hash as the bid proof's first public input. */ + public static BigInteger bidderInt(byte[] bidder) { + return new BigInteger(1, bidder); + } + + public static BidProofCircuit.Inputs bidInputs(byte[] bidder, long deposit, long reserve, BigInteger pkU, BigInteger pkV, + ElGamalEncryption bid) { + ElGamalCiphertext ct = bid.ciphertext(); + BigInteger b = bidderInt(bidder); + return BidProofCircuit.inputs() + .bidderInt(b).deposit(deposit).reserve(reserve) + .pkU(pkU).pkV(pkV) + .aU(ct.handle().affineU()).aV(ct.handle().affineV()) + .bU(ct.blinded().affineU()).bV(ct.blinded().affineV()) + .bid(bid.message()).k(bid.randomness()) + .bidderSquared(b.multiply(b).mod(Fields.FR)); + } + + /** Proves the bid; throws if it is above the deposit or below the reserve. */ + public Groth16ProofBLS381 proveBid(byte[] bidder, long deposit, long reserve, BigInteger pkU, BigInteger pkV, + ElGamalEncryption bidEncryption) { + return bid.prove(bidInputs(bidder, deposit, reserve, pkU, pkV, bidEncryption).toWitnessMap()); + } + + public static SettleProofCircuit.Inputs settleInputs(Lot lot, int w, long p, BigInteger sk, List bids) { + int n = lot.bids().size(); + List cts = new ArrayList<>(); + for (Lot.Bid b : lot.bids()) cts.addAll(List.of(b.aU(), b.aV(), b.bU(), b.bV())); + return SettleProofCircuit.inputs(n, 4 * n) + .w(w).p(p).pkU(lot.pkU()).pkV(lot.pkV()).cts(cts) + .sk(sk).m(bids.stream().map(BigInteger::valueOf).toList()); + } + + /** Proves the settlement with the auctioneer's secret and the decrypted bids; throws if it does not hold. */ + public Groth16ProofBLS381 proveSettle(Lot lot, int w, long p, BigInteger sk, List bids) { + return settle(lot.bids().size()).prove(settleInputs(lot, w, p, sk, bids).toWitnessMap()); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java new file mode 100644 index 0000000..1f56c09 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java @@ -0,0 +1,338 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.auction; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.address.AddressProvider; +import com.bloxbean.cardano.client.address.Credential; +import com.bloxbean.cardano.client.api.model.Amount; +import com.bloxbean.cardano.client.api.model.Result; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.common.model.Networks; +import com.bloxbean.cardano.client.crypto.Blake2bUtil; +import com.bloxbean.cardano.client.crypto.VerificationKey; +import com.bloxbean.cardano.client.function.helper.SignerProviders; +import com.bloxbean.cardano.client.plutus.spec.BigIntPlutusData; +import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ConstrPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ListPlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusScript; +import com.bloxbean.cardano.client.quicktx.QuickTxBuilder; +import com.bloxbean.cardano.client.quicktx.ScriptTx; +import com.bloxbean.cardano.client.quicktx.Tx; +import com.bloxbean.cardano.client.transaction.spec.Asset; +import com.bloxbean.cardano.client.transaction.spec.script.ScriptPubkey; +import com.bloxbean.cardano.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.onchain.SealedBidAuction; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.AdmittedAuditor; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.Registry; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.VerificationKeys; +import org.julclang.clientlib.JulcScriptLoader; +import org.zeroj.circuit.lib.jubjub.ElGamalCiphertext; +import org.zeroj.circuit.lib.jubjub.ElGamalEncryption; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; +import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * One {@code SealedBidAuction} instance (ADR-0008) and its transactions. Like the note ledger, it + * is deployed once as a reference script at its own address, in an output that is not an + * authentic lot and so can never be spent. + */ +public final class AuctionScript { + + private static final BigInteger LOVELACE = BigInteger.valueOf(1_000_000); + + private final AuctionProofs proofs; + private final Registry registry; + private final long minWindow; + private final long minLotLovelace; + private final PlutusScript script; + private final String policyId; + private final String address; + private Utxo reference; + + public AuctionScript(AuctionProofs proofs, Registry registry, long minWindowMillis, long minLotLovelace) { + this.proofs = proofs; + this.registry = registry; + this.minWindow = minWindowMillis; + this.minLotLovelace = minLotLovelace; + this.script = JulcScriptLoader.load(SealedBidAuction.class, + new BytesPlutusData(registry.policy()), + new BytesPlutusData(Registry.TOKEN), + BigIntPlutusData.of(minWindowMillis), + BigIntPlutusData.of(minLotLovelace), + new BytesPlutusData(VerificationKeys.hash(proofs.bid().compressedVk())), + new BytesPlutusData(VerificationKeys.hash(proofs.settle(1).compressedVk())), + new BytesPlutusData(VerificationKeys.hash(proofs.settle(2).compressedVk())), + new BytesPlutusData(VerificationKeys.hash(proofs.settle(3).compressedVk()))); + this.policyId = Plutus.policyId(script); + try { + this.address = AddressProvider.getEntAddress(script, Networks.testnet()).toBech32(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + public String policyId() { return policyId; } + + public String address() { return address; } + + public AuctionProofs proofs() { return proofs; } + + public Registry registry() { return registry; } + + public long minWindow() { return minWindow; } + + public Result deploy(BackendService backend, Account payer) { + try { + var tx = new Tx().payToContract(address, List.of(Amount.ada(30)), PlutusData.unit(), script).from(payer.baseAddress()); + var result = new QuickTxBuilder(backend).compose(tx).withSigner(SignerProviders.signerFrom(payer)).complete(); + if (result.isSuccessful()) { + DevKit.waitForTx(backend, result.getValue()); + reference = DevKit.utxosOf(backend, address, result.getValue()).getFirst(); + } + return result; + } catch (Exception e) { + return Result.error(e.getMessage()); + } + } + + // ------------------------------------------------------------------ reading + + /** Every authentic lot at the auction's address. */ + public List lots(BackendService backend) { + List out = new ArrayList<>(); + try { + for (int page = 1; ; page++) { + var r = backend.getUtxoService().getUtxos(address, 100, page); + if (!r.isSuccessful() || r.getValue() == null || r.getValue().isEmpty()) break; + for (Utxo u : r.getValue()) Lot.parse(u, policyId, address).ifPresent(out::add); + if (r.getValue().size() < 100) break; + } + } catch (Exception e) { + throw new IllegalStateException("could not read lots: " + e.getMessage(), e); + } + return out; + } + + public Optional lot(BackendService backend, String token) { + return lots(backend).stream().filter(l -> l.token().equals(token)).findFirst(); + } + + // ------------------------------------------------------------------ the item + + /** A demo item: one NFT under the seller's own native-script policy. Returns its unit. */ + public static Result mintItem(BackendService backend, Account seller, String name) { + try { + ScriptPubkey policy = ScriptPubkey.create(VerificationKey.create(seller.publicKeyBytes())); + var tx = new Tx() + .mintAssets(policy, new Asset("0x" + HexUtil.encodeHexString(name.getBytes(StandardCharsets.UTF_8)), BigInteger.ONE), + seller.baseAddress()) + .from(seller.baseAddress()); + return new QuickTxBuilder(backend).compose(tx).withSigner(SignerProviders.signerFrom(seller)).complete(); + } catch (Exception e) { + return Result.error(e.getMessage()); + } + } + + public static String itemUnit(Account seller, String name) { + try { + return ScriptPubkey.create(VerificationKey.create(seller.publicKeyBytes())).getPolicyId() + + HexUtil.encodeHexString(name.getBytes(StandardCharsets.UTF_8)); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + // ------------------------------------------------------------------ transactions + + /** + * Opens a lot: mints its one-shot token (named after a seller UTxO this transaction spends), + * locks the item with {@code lotAda}, copies the auctioneer's current key and generation. + */ + public Result open(BackendService backend, Account seller, String itemUnit, long deposit, long reserve, + long biddingEnds, long settleBy, AdmittedAuditor auctioneer) { + try { + List utxos = backend.getUtxoService().getUtxos(seller.baseAddress(), 100, 1).getValue(); + Utxo seed = utxos.stream().filter(u -> u.getAmount().size() == 1).findFirst() + .orElseThrow(() -> new IllegalStateException("the seller has no plain ADA UTxO to name the lot")); + // The fee payer's balancing adds ADA only, so the UTxO holding the item is spent explicitly. + Utxo holding = utxos.stream().filter(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().equals(itemUnit))) + .findFirst().orElseThrow(() -> new IllegalStateException("the seller does not hold " + itemUnit)); + byte[] token = Blake2bUtil.blake2bHash256(Fields.concat(HexUtil.decodeHexString(seed.getTxHash()), + Fields.i2osp(BigInteger.valueOf(seed.getOutputIndex()), 2))); + byte[] itemPolicy = HexUtil.decodeHexString(itemUnit.substring(0, 56)); + byte[] itemName = HexUtil.decodeHexString(itemUnit.substring(56)); + var datumFull = Lot.datum(pkh(seller), auctioneer.auditor(), itemPolicy, itemName, 10_000_000L, deposit, reserve, + biddingEnds, settleBy, auctioneer.pkU(), auctioneer.pkV(), auctioneer.generation(), fullBids()); + String tokenUnit = policyId + HexUtil.encodeHexString(token); + // lotAda covers the lot output at its largest (three bids), and travels with the item. + BigInteger lotAda = Plutus.minAda(backend, address, + List.of(new Amount(itemUnit, BigInteger.ONE), new Amount(tokenUnit, BigInteger.ONE)), datumFull) + .max(BigInteger.valueOf(minLotLovelace)); + var datum = Lot.datum(pkh(seller), auctioneer.auditor(), itemPolicy, itemName, lotAda.longValueExact(), deposit, + reserve, biddingEnds, settleBy, auctioneer.pkU(), auctioneer.pkV(), auctioneer.generation(), List.of()); + var tx = new ScriptTx() + .collectFrom(List.of(seed, holding)) + .mintAsset(policyId, List.of(new Asset("0x" + HexUtil.encodeHexString(token), BigInteger.ONE)), + ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of(BigIntPlutusData.of(0))).build()) + .readFrom(registry.currentUtxo(backend)) + .payToContract(address, List.of(new Amount("lovelace", lotAda), new Amount(itemUnit, BigInteger.ONE), + new Amount(tokenUnit, BigInteger.ONE)), datum); + return submit(backend, tx, seller, null, DevKit.slotAt(backend, biddingEnds) - 1); + } catch (Exception e) { + return Result.error(e.getMessage()); + } + } + + /** Places a sealed bid: appends it to the lot and adds the deposit. */ + public Result bid(BackendService backend, Account bidder, Lot lot, ElGamalEncryption encryption, + Groth16ProofBLS381 proof) { + return bid(backend, bidder, lot, encryption, proof, DevKit.slotAt(backend, lot.biddingEnds()) - 1); + } + + /** A bid whose transaction is valid until {@code validToSlot} (a later slot is the late-bid cheat). */ + public Result bid(BackendService backend, Account bidder, Lot lot, ElGamalEncryption encryption, + Groth16ProofBLS381 proof, long validToSlot) { + ElGamalCiphertext ct = encryption.ciphertext(); + var bid = new Lot.Bid(pkh(bidder), ct.handle().affineU(), ct.handle().affineV(), ct.blinded().affineU(), + ct.blinded().affineV()); + List bids = new ArrayList<>(lot.bids()); + bids.add(bid); + var p = ProverToCardano.compressProof(proof); + var redeemer = ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(bid.bidder()), BigIntPlutusData.of(bid.aU()), BigIntPlutusData.of(bid.aV()), + BigIntPlutusData.of(bid.bU()), BigIntPlutusData.of(bid.bV()), + new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()), + VerificationKeys.data(proofs.bid().compressedVk()))).build(); + List value = new ArrayList<>(); + for (Amount a : lot.utxo().getAmount()) { + value.add(a.getUnit().equals("lovelace") + ? new Amount("lovelace", a.getQuantity().add(BigInteger.valueOf(lot.deposit()).multiply(LOVELACE))) : a); + } + var tx = new ScriptTx() + .collectFrom(lot.utxo(), redeemer) + .payToContract(address, value, lot.datum(bids)); + return submit(backend, tx, bidder, null, validToSlot); + } + + /** Settles the lot with the auctioneer's proof: the winner, the seller and every loser are paid. */ + public Result settle(BackendService backend, Account submitter, Lot lot, int w, long price, Groth16ProofBLS381 proof) { + var p = ProverToCardano.compressProof(proof); + var redeemer = ConstrPlutusData.builder().alternative(1).data(ListPlutusData.of( + BigIntPlutusData.of(w), BigIntPlutusData.of(price), + new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()), + VerificationKeys.data(proofs.settle(lot.bids().size()).compressedVk()))).build(); + var tx = closing(lot, redeemer); + BigInteger deposit = BigInteger.valueOf(lot.deposit()).multiply(LOVELACE); + tx = tx.payToContract(enterprise(lot.seller()), List.of(new Amount("lovelace", BigInteger.valueOf(price).multiply(LOVELACE))), + payout(lot)); + for (int i = 0; i < lot.bids().size(); i++) { + byte[] bidder = lot.bids().get(i).bidder(); + if (i + 1 == w) { + tx = tx.payToContract(enterprise(bidder), List.of( + new Amount("lovelace", BigInteger.valueOf(lot.lotAda()).add(deposit).subtract(BigInteger.valueOf(price).multiply(LOVELACE))), + new Amount(lot.itemUnit(), BigInteger.ONE)), payout(lot)); + } else { + tx = tx.payToContract(enterprise(bidder), List.of(new Amount("lovelace", deposit)), payout(lot)); + } + } + return submit(backend, tx, submitter, DevKit.slotAt(backend, lot.biddingEnds()) + 1, + DevKit.slotAt(backend, lot.settleBy()) - 1); + } + + /** After {@code settleBy} without a settlement: anyone returns the item and every deposit. */ + public Result refund(BackendService backend, Account submitter, Lot lot) { + var tx = closing(lot, ConstrPlutusData.builder().alternative(3).data(ListPlutusData.of(BigIntPlutusData.of(0))).build()) + .payToContract(enterprise(lot.seller()), List.of(new Amount("lovelace", BigInteger.valueOf(lot.lotAda())), + new Amount(lot.itemUnit(), BigInteger.ONE)), payout(lot)); + BigInteger deposit = BigInteger.valueOf(lot.deposit()).multiply(LOVELACE); + for (Lot.Bid b : lot.bids()) tx = tx.payToContract(enterprise(b.bidder()), List.of(new Amount("lovelace", deposit)), payout(lot)); + return submit(backend, tx, submitter, DevKit.slotAt(backend, lot.settleBy()) + 1, null); + } + + /** After {@code biddingEnds} with no bids: the seller takes the item back. */ + public Result noBids(BackendService backend, Account seller, Lot lot) { + var tx = closing(lot, ConstrPlutusData.builder().alternative(2).data(ListPlutusData.of(BigIntPlutusData.of(0))).build()) + .payToContract(enterprise(lot.seller()), List.of(new Amount("lovelace", BigInteger.valueOf(lot.lotAda())), + new Amount(lot.itemUnit(), BigInteger.ONE)), payout(lot)); + return submit(backend, tx, seller, DevKit.slotAt(backend, lot.biddingEnds()) + 1, null); + } + + private ScriptTx closing(Lot lot, PlutusData redeemer) { + return new ScriptTx() + .collectFrom(lot.utxo(), redeemer) + .mintAsset(policyId, List.of(new Asset("0x" + lot.token(), BigInteger.ONE.negate())), + ConstrPlutusData.builder().alternative(1).data(ListPlutusData.of(BigIntPlutusData.of(0))).build()); + } + + /** {@code Payout(policy, T)}: tags a payout with the lot token's full asset identity. */ + private PlutusData payout(Lot lot) { + return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(HexUtil.decodeHexString(policyId)), + new BytesPlutusData(HexUtil.decodeHexString(lot.token())))).build(); + } + + /** + * Moves everything a wallet holds at its enterprise address (payouts and refunds land there) + * back to its base address, so the wallet can spend it again. Empty result if there is nothing. + */ + public static Result sweep(BackendService backend, Account wallet) { + try { + String ent = enterprise(pkh(wallet)); + var r = backend.getUtxoService().getUtxos(ent, 100, 1); + if (!r.isSuccessful() || r.getValue() == null || r.getValue().isEmpty()) return Result.success(null); + // Spend every enterprise UTxO; the change, which is all of it less the fee, goes to the base address. + var tx = new Tx().collectFrom(r.getValue()) + .payToAddress(wallet.baseAddress(), Amount.ada(1)) + .from(ent) + .withChangeAddress(wallet.baseAddress()); + return new QuickTxBuilder(backend).compose(tx) + .withSigner(SignerProviders.signerFrom(wallet)) + .complete(); + } catch (Exception e) { + return Result.error(e.getMessage()); + } + } + + static String enterprise(byte[] pkh) { + return AddressProvider.getEntAddress(Credential.fromKey(pkh), Networks.testnet()).toBech32(); + } + + private static List fullBids() { + BigInteger big = BigInteger.ONE.shiftLeft(254); + List out = new ArrayList<>(); + for (int i = 0; i < 3; i++) out.add(new Lot.Bid(new byte[28], big, big, big, big)); + return out; + } + + private Result submit(BackendService backend, ScriptTx tx, Account signer, Long validFrom, Long validTo) { + try { + var ctx = new QuickTxBuilder(backend).compose(tx.readFrom(reference)) + .withReferenceScripts(script) + .withTxEvaluator(DevKit.evaluator(backend)) + .withSigner(SignerProviders.signerFrom(signer)) + .withRequiredSigners(pkh(signer)) + .feePayer(signer.baseAddress()) + .collateralPayer(signer.baseAddress()); + if (validFrom != null) ctx = ctx.validFrom(validFrom); + if (validTo != null) ctx = ctx.validTo(validTo); + return ctx.complete(); + } catch (RuntimeException e) { + return Result.error(e.getMessage()); + } + } + + static byte[] pkh(Account a) { + return a.hdKeyPair().getPublicKey().getKeyHash(); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/Lot.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/Lot.java new file mode 100644 index 0000000..4fbf59d --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/Lot.java @@ -0,0 +1,102 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.auction; + +import com.bloxbean.cardano.client.api.model.Amount; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.plutus.spec.BigIntPlutusData; +import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ConstrPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ListPlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusData; +import com.bloxbean.cardano.client.util.HexUtil; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * A sealed-bid lot (ADR-0008 D1): {@code Lot(seller, auctioneer, itemPolicy, itemName, lotAda, + * deposit, reserve, biddingEnds, settleBy, pkU, pkV, generation, bids)}, and the UTxO holding it. + */ +public record Lot(Utxo utxo, String token, byte[] seller, byte[] auctioneer, byte[] itemPolicy, byte[] itemName, + long lotAda, long deposit, long reserve, long biddingEnds, long settleBy, BigInteger pkU, + BigInteger pkV, long generation, List bids) { + + /** One sealed bid: the bidder and the {@code elgamal-jubjub-v1} ciphertext of its amount. */ + public record Bid(byte[] bidder, BigInteger aU, BigInteger aV, BigInteger bU, BigInteger bV) { + PlutusData data() { + return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of(new BytesPlutusData(bidder), + BigIntPlutusData.of(aU), BigIntPlutusData.of(aV), BigIntPlutusData.of(bU), BigIntPlutusData.of(bV))).build(); + } + } + + public String itemUnit() { + return HexUtil.encodeHexString(itemPolicy) + HexUtil.encodeHexString(itemName); + } + + /** The datum with {@code bids}. */ + public ConstrPlutusData datum(List withBids) { + return datum(seller, auctioneer, itemPolicy, itemName, lotAda, deposit, reserve, biddingEnds, settleBy, pkU, pkV, + generation, withBids); + } + + public static ConstrPlutusData datum(byte[] seller, byte[] auctioneer, byte[] itemPolicy, byte[] itemName, long lotAda, + long deposit, long reserve, long biddingEnds, long settleBy, BigInteger pkU, + BigInteger pkV, long generation, List bids) { + List b = new ArrayList<>(); + for (Bid bid : bids) b.add(bid.data()); + return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(seller), new BytesPlutusData(auctioneer), new BytesPlutusData(itemPolicy), + new BytesPlutusData(itemName), BigIntPlutusData.of(lotAda), BigIntPlutusData.of(deposit), + BigIntPlutusData.of(reserve), BigIntPlutusData.of(biddingEnds), BigIntPlutusData.of(settleBy), + BigIntPlutusData.of(pkU), BigIntPlutusData.of(pkV), BigIntPlutusData.of(generation), + ListPlutusData.of(b.toArray(new PlutusData[0])))).build(); + } + + /** + * The lot in {@code utxo} if it is authentic for the auction whose policy is {@code policyId} + * and address {@code address}: exactly lovelace, the item and one lot token, and a datum of + * the lot shape. Anything else at the address is ignored. + */ + public static Optional parse(Utxo utxo, String policyId, String address) { + if (!address.equals(utxo.getAddress()) || utxo.getInlineDatum() == null) return Optional.empty(); + try { + var d = (ConstrPlutusData) PlutusData.deserialize(HexUtil.decodeHexString(utxo.getInlineDatum())); + var f = d.getData().getPlutusDataList(); + if (d.getAlternative() != 0 || f.size() != 13) return Optional.empty(); + byte[] itemPolicy = bytes(f.get(2)); + byte[] itemName = bytes(f.get(3)); + String itemUnit = HexUtil.encodeHexString(itemPolicy) + HexUtil.encodeHexString(itemName); + String token = null; + int assets = 0; + boolean item = false; + for (Amount a : utxo.getAmount()) { + if (a.getUnit().equals("lovelace")) continue; + assets++; + if (a.getUnit().equals(itemUnit) && a.getQuantity().equals(BigInteger.ONE)) item = true; + else if (a.getUnit().startsWith(policyId) && a.getUnit().length() == policyId.length() + 64 + && a.getQuantity().equals(BigInteger.ONE)) token = a.getUnit().substring(policyId.length()); + } + if (token == null || !item || assets != 2) return Optional.empty(); + List bids = new ArrayList<>(); + for (PlutusData x : ((ListPlutusData) f.get(12)).getPlutusDataList()) { + var bf = ((ConstrPlutusData) x).getData().getPlutusDataList(); + bids.add(new Bid(bytes(bf.get(0)), integer(bf.get(1)), integer(bf.get(2)), integer(bf.get(3)), integer(bf.get(4)))); + } + return Optional.of(new Lot(utxo, token, bytes(f.get(0)), bytes(f.get(1)), itemPolicy, itemName, + integer(f.get(4)).longValueExact(), integer(f.get(5)).longValueExact(), integer(f.get(6)).longValueExact(), + integer(f.get(7)).longValueExact(), integer(f.get(8)).longValueExact(), integer(f.get(9)), integer(f.get(10)), + integer(f.get(11)).longValueExact(), bids)); + } catch (Exception e) { + return Optional.empty(); + } + } + + private static byte[] bytes(PlutusData d) { + return ((BytesPlutusData) d).getValue(); + } + + private static BigInteger integer(PlutusData d) { + return ((BigIntPlutusData) d).getValue(); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/circuit/BidProof.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/circuit/BidProof.java new file mode 100644 index 0000000..c7bdedf --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/circuit/BidProof.java @@ -0,0 +1,45 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.auction.circuit; + +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; + +/** + * A sealed bid (ADR-0008 D3): the bid is encrypted to the auctioneer, and the ciphertext is + * proved to encrypt an amount between the reserve and the deposit. + * + *

Public, in order: {@code bidderInt, deposit, reserve} (the application's inputs), then + * {@code PK.u, PK.v} and {@code A.u, A.v, B.u, B.v} ({@code elgamal-jubjub-v1} §8 groups). The + * prover knows {@code bid} (32 bits) and {@code k} (252 bits) with {@code (A, B) = R_enc(32)} of + * {@code bid} under {@code PK} and {@code reserve ≤ bid ≤ deposit}. + * + *

{@code bidderInt² = sq} binds the proof to the bidder: a public input in no constraint would + * not affect Groth16 verification, so another bidder could copy a ciphertext with its proof. + */ +@ZKCircuit(name = "sealed-bid", version = 1) +public class BidProof { + + @Prove + void prove(ZkContext zk, + @Public ZkField bidderInt, + @Public @UInt(bits = 32) ZkUInt deposit, + @Public @UInt(bits = 32) ZkUInt reserve, + @Public ZkField pkU, @Public ZkField pkV, + @Public ZkField aU, @Public ZkField aV, @Public ZkField bU, @Public ZkField bV, + @Secret @UInt(bits = 32) ZkUInt bid, + @Secret @UInt(bits = 252) ZkUInt k, + @Secret ZkField bidderSquared) { + bidderInt.mul(bidderInt).assertEqual(bidderSquared); + var key = ZkElGamalPublicKey.fromVerifierFixedPublic(zk, pkU, pkV); + ZkElGamal.encrypt(zk, bid, k, key).assertAffineEquals(zk, aU, aV, bU, bV); + bid.lte(deposit).assertTrue(); + bid.gte(reserve).assertTrue(); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/circuit/SettleProof.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/circuit/SettleProof.java new file mode 100644 index 0000000..57d723e --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/circuit/SettleProof.java @@ -0,0 +1,81 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.auction.circuit; + +import org.zeroj.circuit.annotation.CircuitParam; +import org.zeroj.circuit.annotation.FixedSize; +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.ZkArray; +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.ZkElGamal; +import org.zeroj.circuit.lib.zk.ZkElGamalPublicKey; + +/** + * Settlement of a sealed-bid auction with {@code n} bids (ADR-0008 D4): the auctioneer proves who + * won and at what price without publishing the losing bids. + * + *

Public, in order: {@code w, p, PK.u, PK.v}, then for each bid {@code i = 1 … n} in datum + * order {@code A_i.u, A_i.v, B_i.u, B_i.v} (the {@code cts} array, interleaved per bid). + * + *

Witness: the auctioneer's secret {@code sk} (252 bits, one decomposition shared by every + * bid) and the decrypted bids {@code m_i} (32 bits). + *

    + *
  1. Decryption. For each bid, {@code R_enc(32)} with key {@code A_i} and randomness + * {@code sk}, asserted equal to {@code (PK, B_i)}: that is {@code [sk]·G = PK} and + * {@code [m_i]·G + [sk]·A_i = B_i}, so {@code m_i} is the ElGamal decryption of bid {@code i} + * ({@code elgamal-jubjub-v1} §6.1), unique since {@code m_i < 2^32 < l}. {@code A_i ∈ 𝔾} + * and {@code A_i ≠ 𝒪} are established by each bid's proof and the validator.
  2. + *
  3. Winner. {@code w ∈ {1, …, n}} as a one-hot selection, and {@code m_w = p}.
  4. + *
  5. First price, earliest wins ties. {@code m_i < p} for {@code i < w} and + * {@code m_i ≤ p} for every {@code i}.
  6. + *
+ */ +@ZKCircuit(name = "sealed-bid-settle", nameTemplate = "sealed-bid-settle-n{bids}-c{cts}", version = 1) +public class SettleProof { + + private final int bids; + + /** {@code cts = 4·bids}: the ciphertext coordinates, which must agree. */ + public SettleProof(@CircuitParam("bids") int bids, @CircuitParam("cts") int cts) { + if (bids < 1 || bids > 3) throw new IllegalArgumentException("bids must be 1, 2 or 3"); + if (cts != 4 * bids) throw new IllegalArgumentException("cts must be 4·bids"); + this.bids = bids; + } + + @Prove + void prove(ZkContext zk, + @Public ZkField w, + @Public @UInt(bits = 32) ZkUInt p, + @Public ZkField pkU, @Public ZkField pkV, + @Public @FixedSize(param = "cts") ZkArray cts, + @Secret @UInt(bits = 252) ZkUInt sk, + @Secret @UInt(bits = 32) @FixedSize(param = "bids") ZkArray m) { + ZkField one = zk.constant(1); + ZkField zero = zk.constant(0); + ZkField selected = zero; + ZkField price = zero; + ZkBool[] isWinner = new ZkBool[bids]; + for (int i = 0; i < bids; i++) { + // Decryption of bid i under the auctioneer's key. + var handle = ZkElGamalPublicKey.fromVerifierFixedPublic(zk, cts.get(4 * i), cts.get(4 * i + 1)); + ZkElGamal.encrypt(zk, m.get(i), sk, handle).assertAffineEquals(zk, pkU, pkV, cts.get(4 * i + 2), cts.get(4 * i + 3)); + isWinner[i] = w.isEqual(zk.constant(i + 1)); + selected = selected.add(isWinner[i].asField()); + price = price.add(isWinner[i].asField().mul(m.get(i).asField())); + } + selected.assertEqual(one); + price.assertEqual(p.asField()); + for (int i = 0; i < bids; i++) { + m.get(i).lte(p).assertTrue(); + // Bid i comes before the winner when some later index is the winner. + ZkField beforeWinner = zero; + for (int j = i + 1; j < bids; j++) beforeWinner = beforeWinner.add(isWinner[j].asField()); + beforeWinner.mul(one.sub(m.get(i).lt(p).asField())).assertEqual(zero); + } + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/onchain/SealedBidAuction.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/onchain/SealedBidAuction.java new file mode 100644 index 0000000..b6fa33b --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/onchain/SealedBidAuction.java @@ -0,0 +1,416 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.auction.onchain; + +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain.ChainLib; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain.RegistryLib; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain.VkLib; +import org.julclang.core.PlutusData; +import org.julclang.ledger.Address; +import org.julclang.ledger.Credential; +import org.julclang.ledger.PubKeyHash; +import org.julclang.ledger.ScriptContext; +import org.julclang.ledger.ScriptHash; +import org.julclang.ledger.ScriptInfo; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxInfo; +import org.julclang.ledger.TxOut; +import org.julclang.ledger.Value; +import org.julclang.stdlib.Builtins; +import org.julclang.stdlib.annotation.Entrypoint; +import org.julclang.stdlib.annotation.MultiValidator; +import org.julclang.stdlib.annotation.Param; +import org.julclang.stdlib.annotation.Purpose; +import org.julclang.stdlib.lib.ContextsLib; +import org.julclang.stdlib.lib.IntervalLib; +import org.julclang.stdlib.lib.ValuesLib; + +import java.math.BigInteger; +import java.util.Optional; + +/** + * A sealed-bid auction lot (ADR-0008): one state UTxO per lot, whose bids are + * {@code elgamal-jubjub-v1} ciphertexts to the auctioneer, each proved to encrypt an amount in + * {@code [reserve, deposit]}, and settled with a proof that names the earliest highest bid. + * + *

Datum {@code Lot(seller, auctioneer, itemPolicy, itemName, lotAda, deposit, reserve, + * biddingEnds, settleBy, pkU, pkV, generation, bids)} with {@code bids = [Bid(bidder, A.u, A.v, + * B.u, B.v)]}, at most 3. An authentic lot is an output at the script's exact enterprise + * address holding exactly lovelace, one unit of the item and one lot token {@code T} (quantity 1). + * Every payout goes to the recipient's exact enterprise address with inline datum + * {@code Payout(policy, T)}: the lot token's full asset identity, so one output can never satisfy + * two lots, even of differently parameterized auction scripts in one transaction. + */ +@MultiValidator +public class SealedBidAuction { + + @Param static byte[] registryPolicy; + @Param static byte[] registryToken; + @Param static BigInteger minWindow; // ms + @Param static BigInteger minLotAda; // lovelace + @Param static byte[] bidVkHash; + @Param static byte[] settle1VkHash; + @Param static byte[] settle2VkHash; + @Param static byte[] settle3VkHash; + + sealed interface LotMint permits Open, Burn {} + record Open(BigInteger unused) implements LotMint {} + record Burn(BigInteger unused) implements LotMint {} + + sealed interface LotSpend permits PlaceBid, Settle, NoBids, Refund {} + record PlaceBid(byte[] bidder, BigInteger aU, BigInteger aV, BigInteger bU, BigInteger bV, + byte[] piA, byte[] piB, byte[] piC, PlutusData vk) implements LotSpend {} + record Settle(BigInteger w, BigInteger p, byte[] piA, byte[] piB, byte[] piC, PlutusData vk) implements LotSpend {} + record NoBids(BigInteger unused) implements LotSpend {} + record Refund(BigInteger unused) implements LotSpend {} + + // ------------------------------------------------------------------ + // Minting: Open (one-shot lot token) and Burn + // ------------------------------------------------------------------ + + @Entrypoint(purpose = Purpose.MINT) + public static boolean mint(LotMint redeemer, ScriptContext ctx) { + TxInfo txInfo = ctx.txInfo(); + ScriptInfo.MintingScript mintInfo = (ScriptInfo.MintingScript) ctx.scriptInfo(); + byte[] policy = PlutusData.cast(mintInfo.policyId(), byte[].class); + Credential own = new Credential.ScriptCredential(PlutusData.cast(policy, ScriptHash.class)); + if (ChainLib.policyEntryCount(txInfo.mint(), policy) != 1) return false; + return switch (redeemer) { + case Open open -> open(txInfo, own, policy); + // The burned lot's spending purpose (Settle, NoBids, Refund) checks everything else. + case Burn burn -> ChainLib.countInputs(txInfo.inputs(), own) == 1 + && Builtins.lengthOfByteString(ValuesLib.findTokenName(txInfo.mint(), policy, BigInteger.valueOf(-1))) == 32; + }; + } + + private static boolean open(TxInfo txInfo, Credential own, byte[] policy) { + byte[] token = ValuesLib.findTokenName(txInfo.mint(), policy, BigInteger.ONE); + boolean derived = false; + for (TxInInfo input : txInfo.inputs()) { + derived = derived || Builtins.equalsByteString(ValuesLib.uniqueTokenName(input.outRef()), token); + } + if (!derived || ChainLib.countInputs(txInfo.inputs(), own) != 0 + || ChainLib.countOutputs(txInfo.outputs(), own) != 1) { + return false; + } + TxOut lot = onlyOwnOutput(txInfo, own); + PlutusData d = ChainLib.inlineDatum(lot); + if (!isLot(d) || !Builtins.nullList(Builtins.unListData(field(d, 12)))) return false; + if (!authentic(lot, new Address(own, Optional.empty()), policy, token, d) + || ValuesLib.lovelaceOf(lot.value()).compareTo(Builtins.unIData(field(d, 4))) != 0) { + return false; + } + BigInteger lotAda = Builtins.unIData(field(d, 4)); + BigInteger deposit = Builtins.unIData(field(d, 5)); + BigInteger reserve = Builtins.unIData(field(d, 6)); + BigInteger biddingEnds = Builtins.unIData(field(d, 7)); + BigInteger settleBy = Builtins.unIData(field(d, 8)); + BigInteger upper = IntervalLib.finiteUpperBound(txInfo.validRange()); + PlutusData entry = RegistryLib.currentEntry(txInfo, registryPolicy, registryToken); + return ChainLib.signedBy(txInfo, Builtins.unBData(field(d, 0))) + && !Builtins.equalsByteString(Builtins.unBData(field(d, 2)), policy) + && lotAda.compareTo(minLotAda) >= 0 + && reserve.compareTo(BigInteger.TWO) >= 0 && reserve.compareTo(deposit) <= 0 + && deposit.compareTo(BigInteger.valueOf(4294967296L)) < 0 + && settleBy.subtract(biddingEnds).compareTo(minWindow) >= 0 + && upper.compareTo(BigInteger.ZERO) >= 0 && upper.compareTo(biddingEnds) <= 0 + && Builtins.equalsByteString(RegistryLib.entryAuditor(entry), Builtins.unBData(field(d, 1))) + && RegistryLib.entryPkU(entry).compareTo(Builtins.unIData(field(d, 9))) == 0 + && RegistryLib.entryPkV(entry).compareTo(Builtins.unIData(field(d, 10))) == 0 + && RegistryLib.entryGeneration(entry).compareTo(Builtins.unIData(field(d, 11))) == 0; + } + + // ------------------------------------------------------------------ + // Spending the lot + // ------------------------------------------------------------------ + + @Entrypoint(purpose = Purpose.SPEND) + public static boolean spend(PlutusData datum, LotSpend redeemer, ScriptContext ctx) { + TxInfo txInfo = ctx.txInfo(); + byte[] policy = ContextsLib.ownHash(ctx); + Credential own = new Credential.ScriptCredential(PlutusData.cast(policy, ScriptHash.class)); + Address exact = new Address(own, Optional.empty()); + var ownInputOptional = ContextsLib.findOwnInput(ctx); + if (ownInputOptional.isEmpty()) return false; + TxOut lotIn = ownInputOptional.get().resolved(); + if (ChainLib.countInputs(txInfo.inputs(), own) != 1 || !isLot(datum)) return false; + byte[] token = ValuesLib.findTokenName(lotIn.value(), policy, BigInteger.ONE); + if (!authentic(lotIn, exact, policy, token, datum)) return false; + return switch (redeemer) { + case PlaceBid bid -> placeBid(bid, datum, lotIn, txInfo, own, exact, policy, token); + case Settle settle -> settle(settle, datum, txInfo, own, policy, token); + case NoBids noBids -> closing(txInfo, own, policy, token, datum) + && lowerAtLeast(txInfo, field(datum, 7)) + && Builtins.nullList(Builtins.unListData(field(datum, 12))) + && ChainLib.signedBy(txInfo, Builtins.unBData(field(datum, 0))) + && paid(txInfo, Builtins.unBData(field(datum, 0)), Builtins.unIData(field(datum, 4)), true, datum, policy, token); + case Refund refund -> closing(txInfo, own, policy, token, datum) + && lowerAtLeast(txInfo, field(datum, 8)) + && paid(txInfo, Builtins.unBData(field(datum, 0)), Builtins.unIData(field(datum, 4)), true, datum, policy, token) + && refunded(txInfo, Builtins.unListData(field(datum, 12)), deposit(datum), BigInteger.ZERO, datum, policy, token); + }; + } + + private static boolean placeBid(PlaceBid b, PlutusData d, TxOut lotIn, TxInfo txInfo, Credential own, + Address exact, byte[] policy, byte[] token) { + PlutusData bids = Builtins.unListData(field(d, 12)); + BigInteger upper = IntervalLib.finiteUpperBound(txInfo.validRange()); + if (upper.compareTo(BigInteger.ZERO) < 0 || upper.compareTo(Builtins.unIData(field(d, 7))) > 0 + || ChainLib.policyEntryCount(txInfo.mint(), policy) != 0 + || Builtins.lengthOfByteString(b.bidder()) != 28 + || !ChainLib.signedBy(txInfo, b.bidder()) + || Builtins.equalsByteString(b.bidder(), Builtins.unBData(field(d, 0))) + || Builtins.equalsByteString(b.bidder(), Builtins.unBData(field(d, 1))) + || ChainLib.countOutputs(txInfo.outputs(), own) != 1 + || !ChainLib.canonicalField(b.aU()) || !ChainLib.canonicalField(b.aV()) + || !ChainLib.canonicalField(b.bU()) || !ChainLib.canonicalField(b.bV()) + || b.aU().compareTo(BigInteger.ZERO) == 0) { + return false; + } + int count = 0; + boolean fresh = true; + PlutusData rest = bids; + while (!Builtins.nullList(rest)) { + PlutusData earlier = Builtins.headList(rest); + PlutusData f = Builtins.constrFields(earlier); + fresh = fresh && !Builtins.equalsByteString(Builtins.unBData(Builtins.headList(f)), b.bidder()) + && !(Builtins.unIData(Builtins.headList(Builtins.tailList(f))).compareTo(b.aU()) == 0 + && Builtins.unIData(Builtins.headList(Builtins.tailList(Builtins.tailList(f)))).compareTo(b.aV()) == 0); + count = count + 1; + rest = Builtins.tailList(rest); + } + if (!fresh || count >= 3) return false; + + TxOut lotOut = onlyOwnOutput(txInfo, own); + PlutusData newBid = Builtins.constrData(0, + Builtins.mkCons(Builtins.bData(b.bidder()), + Builtins.mkCons(Builtins.iData(b.aU()), + Builtins.mkCons(Builtins.iData(b.aV()), + Builtins.mkCons(Builtins.iData(b.bU()), + Builtins.mkCons(Builtins.iData(b.bV()), + Builtins.mkNilData())))))); + if (!Builtins.equalsData(ChainLib.inlineDatum(lotOut), withBids(d, appendBid(bids, newBid))) + || !authentic(lotOut, exact, policy, token, d) + || ValuesLib.lovelaceOf(lotOut.value()).compareTo( + ValuesLib.lovelaceOf(lotIn.value()).add(deposit(d).multiply(BigInteger.valueOf(1000000)))) != 0) { + return false; + } + PlutusData publicInputs = Builtins.listData( + Builtins.mkCons(Builtins.iData(Builtins.byteStringToInteger(true, b.bidder())), + Builtins.mkCons(field(d, 5), + Builtins.mkCons(field(d, 6), + Builtins.mkCons(field(d, 9), + Builtins.mkCons(field(d, 10), + Builtins.mkCons(Builtins.iData(b.aU()), + Builtins.mkCons(Builtins.iData(b.aV()), + Builtins.mkCons(Builtins.iData(b.bU()), + Builtins.mkCons(Builtins.iData(b.bV()), + Builtins.mkNilData())))))))))); + return VkLib.verify(publicInputs, b.piA(), b.piB(), b.piC(), b.vk(), bidVkHash); + } + + private static boolean settle(Settle s, PlutusData d, TxInfo txInfo, Credential own, byte[] policy, byte[] token) { + PlutusData bids = Builtins.unListData(field(d, 12)); + int n = 0; + PlutusData rest = bids; + while (!Builtins.nullList(rest)) { + n = n + 1; + rest = Builtins.tailList(rest); + } + BigInteger upper = IntervalLib.finiteUpperBound(txInfo.validRange()); + BigInteger reserve = Builtins.unIData(field(d, 6)); + if (n < 1 || !closing(txInfo, own, policy, token, d) + || !lowerAtLeast(txInfo, field(d, 7)) + || upper.compareTo(BigInteger.ZERO) < 0 || upper.compareTo(Builtins.unIData(field(d, 8))) > 0 + || s.w().compareTo(BigInteger.ONE) < 0 || s.w().compareTo(BigInteger.valueOf(n)) > 0 + || s.p().compareTo(reserve) < 0 || s.p().compareTo(deposit(d)) > 0) { + return false; + } + byte[] vkHash = n == 1 ? settle1VkHash : n == 2 ? settle2VkHash : settle3VkHash; + PlutusData publicInputs = Builtins.listData( + Builtins.mkCons(Builtins.iData(s.w()), + Builtins.mkCons(Builtins.iData(s.p()), + Builtins.mkCons(field(d, 9), + Builtins.mkCons(field(d, 10), + ciphertexts(bids)))))); + if (!VkLib.verify(publicInputs, s.piA(), s.piB(), s.piC(), s.vk(), vkHash)) return false; + byte[] seller = Builtins.unBData(field(d, 0)); + BigInteger lovelace = BigInteger.valueOf(1000000); + return paid(txInfo, seller, s.p().multiply(lovelace), false, d, policy, token) + && refunded(txInfo, bids, deposit(d), s.w(), d, policy, token) + && paid(txInfo, bidder(bids, s.w()), + Builtins.unIData(field(d, 4)).add(deposit(d).subtract(s.p()).multiply(lovelace)), true, d, policy, token); + } + + // ------------------------------------------------------------------ + // Helpers + // ------------------------------------------------------------------ + + /** Settle, NoBids, Refund: the lot token {@code T} is burned and no output stays at the script. */ + private static boolean closing(TxInfo txInfo, Credential own, byte[] policy, byte[] token, PlutusData d) { + return ChainLib.policyEntryCount(txInfo.mint(), policy) == 1 + && ValuesLib.assetOf(txInfo.mint(), policy, token).compareTo(BigInteger.valueOf(-1)) == 0 + && ChainLib.countOutputs(txInfo.outputs(), own) == 0; + } + + /** The transaction's validity range starts at or after {@code bound} (finite). */ + private static boolean lowerAtLeast(TxInfo txInfo, PlutusData bound) { + BigInteger lower = IntervalLib.finiteLowerBound(txInfo.validRange()); + return lower.compareTo(BigInteger.ZERO) >= 0 && lower.compareTo(Builtins.unIData(bound)) >= 0; + } + + /** + * Some output pays {@code pkh} at its exact enterprise address at least {@code lovelace}, + * with the item if {@code withItem}, tagged {@code Payout(policy, T)}. + */ + private static boolean paid(TxInfo txInfo, byte[] pkh, BigInteger lovelace, boolean withItem, PlutusData d, + byte[] policy, byte[] token) { + Address to = new Address(new Credential.PubKeyCredential(PlutusData.cast(pkh, PubKeyHash.class)), Optional.empty()); + PlutusData tag = Builtins.constrData(0, Builtins.mkCons(Builtins.bData(policy), + Builtins.mkCons(Builtins.bData(token), Builtins.mkNilData()))); + byte[] itemPolicy = Builtins.unBData(field(d, 2)); + byte[] itemName = Builtins.unBData(field(d, 3)); + boolean found = false; + for (TxOut output : txInfo.outputs()) { + found = found || (Builtins.equalsData(output.address(), to) + && Builtins.equalsData(ChainLib.inlineDatum(output), tag) + && ValuesLib.lovelaceOf(output.value()).compareTo(lovelace) >= 0 + && (!withItem || ValuesLib.assetOf(output.value(), itemPolicy, itemName).compareTo(BigInteger.ONE) == 0)); + } + return found; + } + + /** Every bidder but the winner {@code w} (1-based; 0 for none) is paid at least its deposit. */ + private static boolean refunded(TxInfo txInfo, PlutusData bids, BigInteger deposit, BigInteger w, PlutusData d, + byte[] policy, byte[] token) { + boolean ok = true; + int i = 0; + PlutusData rest = bids; + while (!Builtins.nullList(rest)) { + i = i + 1; + byte[] bidder = Builtins.unBData(Builtins.headList(Builtins.constrFields(Builtins.headList(rest)))); + boolean winner = BigInteger.valueOf(i).compareTo(w) == 0; + ok = ok && (winner || paid(txInfo, bidder, deposit.multiply(BigInteger.valueOf(1000000)), false, d, policy, token)); + rest = Builtins.tailList(rest); + } + return ok; + } + + /** The bidder of bid {@code w} (1-based). */ + private static byte[] bidder(PlutusData bids, BigInteger w) { + PlutusData rest = bids; + BigInteger i = BigInteger.ONE; + while (i.compareTo(w) < 0) { + rest = Builtins.tailList(rest); + i = i.add(BigInteger.ONE); + } + return Builtins.unBData(Builtins.headList(Builtins.constrFields(Builtins.headList(rest)))); + } + + /** {@code A_1.u, A_1.v, B_1.u, B_1.v, …} of the bids, in datum order. */ + private static PlutusData ciphertexts(PlutusData bids) { + if (Builtins.nullList(bids)) return Builtins.mkNilData(); + PlutusData f = Builtins.tailList(Builtins.constrFields(Builtins.headList(bids))); + PlutusData f2 = Builtins.tailList(f); + PlutusData f3 = Builtins.tailList(f2); + PlutusData f4 = Builtins.tailList(f3); + return Builtins.mkCons(Builtins.headList(f), + Builtins.mkCons(Builtins.headList(f2), + Builtins.mkCons(Builtins.headList(f3), + Builtins.mkCons(Builtins.headList(f4), + ciphertexts(Builtins.tailList(bids)))))); + } + + /** {@code list ++ [item]}. */ + private static PlutusData appendBid(PlutusData list, PlutusData item) { + if (Builtins.nullList(list)) return Builtins.mkCons(item, Builtins.mkNilData()); + return Builtins.mkCons(Builtins.headList(list), appendBid(Builtins.tailList(list), item)); + } + + /** The lot datum {@code d} with its bids replaced by {@code bids}. */ + private static PlutusData withBids(PlutusData d, PlutusData bids) { + return Builtins.constrData(0, replaceLast(Builtins.constrFields(d), Builtins.listData(bids))); + } + + private static PlutusData replaceLast(PlutusData fields, PlutusData last) { + if (Builtins.nullList(Builtins.tailList(fields))) return Builtins.mkCons(last, Builtins.mkNilData()); + return Builtins.mkCons(Builtins.headList(fields), replaceLast(Builtins.tailList(fields), last)); + } + + /** + * An authentic lot output: at {@code exact}, without a reference script, holding exactly + * lovelace, one unit of the item and one {@code token} under {@code policy}. + */ + private static boolean authentic(TxOut out, Address exact, byte[] policy, byte[] token, PlutusData d) { + Value v = out.value(); + // No reference script on a lot: it would make later spenders pay its reference-script fee. + return out.referenceScript().isEmpty() + && Builtins.equalsData(out.address(), exact) + && Builtins.lengthOfByteString(token) == 32 + && ChainLib.outerEntryCount(v) == 3 + && ChainLib.policyEntryCount(v, policy) == 1 + && ValuesLib.assetOf(v, policy, token).compareTo(BigInteger.ONE) == 0 + && ChainLib.policyEntryCount(v, Builtins.unBData(field(d, 2))) == 1 + && ValuesLib.assetOf(v, Builtins.unBData(field(d, 2)), Builtins.unBData(field(d, 3))).compareTo(BigInteger.ONE) == 0; + } + + /** The one output under the script's credential. */ + private static TxOut onlyOwnOutput(TxInfo txInfo, Credential own) { + TxOut found = txInfo.outputs().get(0); + for (TxOut output : txInfo.outputs()) { + if (Builtins.equalsData(output.address().credential(), own)) { + found = output; + } else { + found = found; + } + } + return found; + } + + /** + * Exactly 13 fields: three 28-byte hashes, an item name of at most 32 bytes, eight integers + * (coordinates canonical) and a list of well-formed bids. Anything else fails. + */ + private static boolean isLot(PlutusData d) { + if (Builtins.constrTag(d) != 0) return false; + PlutusData f = Builtins.constrFields(d); + int count = 0; + PlutusData rest = f; + while (!Builtins.nullList(rest)) { + count = count + 1; + rest = Builtins.tailList(rest); + } + if (count != 13) return false; + boolean bidsOk = true; + PlutusData each = Builtins.unListData(field(d, 12)); + while (!Builtins.nullList(each)) { + PlutusData bid = Builtins.headList(each); + PlutusData bf = Builtins.constrFields(bid); + bidsOk = bidsOk && Builtins.constrTag(bid) == 0 + && Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(bf))) == 28 + && ChainLib.canonicalField(Builtins.unIData(Builtins.headList(Builtins.tailList(bf)))); + each = Builtins.tailList(each); + } + return bidsOk + && Builtins.lengthOfByteString(Builtins.unBData(field(d, 0))) == 28 + && Builtins.lengthOfByteString(Builtins.unBData(field(d, 1))) == 28 + && Builtins.lengthOfByteString(Builtins.unBData(field(d, 2))) == 28 + && Builtins.lengthOfByteString(Builtins.unBData(field(d, 3))) <= 32 + && Builtins.unIData(field(d, 4)).compareTo(BigInteger.ZERO) > 0 + && ChainLib.canonicalField(Builtins.unIData(field(d, 9))) + && ChainLib.canonicalField(Builtins.unIData(field(d, 10))) + && Builtins.unIData(field(d, 11)).compareTo(BigInteger.ZERO) >= 0; + } + + private static BigInteger deposit(PlutusData d) { + return Builtins.unIData(field(d, 5)); + } + + private static PlutusData field(PlutusData d, int index) { + PlutusData rest = Builtins.constrFields(d); + int i = 0; + while (i < index) { + rest = Builtins.tailList(rest); + i = i + 1; + } + return Builtins.headList(rest); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/AuctionService.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/AuctionService.java new file mode 100644 index 0000000..9f3778e --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/AuctionService.java @@ -0,0 +1,317 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.web; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.address.AddressProvider; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.common.model.Networks; +import com.bloxbean.cardano.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.AuctionProofs; +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.AuctionScript; +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.Lot; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.AdmittedAuditor; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.AuditorKeys; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.KeyPossession; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.Registry; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +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.JubjubDiscreteLog; +import org.zeroj.circuit.lib.jubjub.RawElGamalCiphertext; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The sealed-bid auction for the UI (ADR-0008). A seller lists an item; bidders encrypt their bids + * to the auctioneer with a proof that each bid lies between the reserve and the deposit; after the + * bidding window the auctioneer decrypts every bid and proves who won and at what price, without + * publishing the losing bids. The server holds every wallet and the auctioneer's keys (demo custody). + */ +@Service +public class AuctionService { + + static final List BIDDERS = List.of("alice", "bob", "carol"); + private static final SecureRandom RANDOM = new SecureRandom(); + private static final long MAX_BID = (1L << 32) - 1; + + @Value("${auction.bidding-seconds:120}") + private long biddingSeconds = 120; + + @Value("${auction.settle-seconds:180}") + private long settleSeconds = 180; + + private final BackendService backend; + private final Funding funding; + private final Map wallets = new LinkedHashMap<>(); + private final Map auctioneerKeys = new LinkedHashMap<>(); + private final List> history = new ArrayList<>(); + private Account auctioneer; + private AuctionScript auction; + private JubjubDiscreteLog table; + private String currentLot; + private int itemCounter; + + public AuctionService(BackendService backend, Funding funding) { + this.backend = backend; + this.funding = funding; + } + + synchronized void ensureReady() throws Exception { + if (auction != null) return; + var proofs = new AuctionProofs(); + var possession = new KeyPossession(); + wallets.put("seller", funding.newWallet("auction/seller", 200)); + for (String b : BIDDERS) wallets.put(b, funding.newWallet("auction/" + b, 2_000)); + auctioneer = funding.newWallet("auction/auctioneer", 300); + Utxo seed = backend.getUtxoService().getUtxos(auctioneer.baseAddress(), 10, 1).getValue().getFirst(); + Registry registry = Registry.forSeed(seed.getTxHash(), seed.getOutputIndex(), possession); + AuditorKeys keys = AuditorKeys.generate(RANDOM); + String init = DemoErrors.require(registry.init(backend, auctioneer, seed, + keys.entry(registry.policy(), NoteDemo.pkh(auctioneer), 0, possession)), "Registering the auctioneer"); + DevKit.waitForTx(backend, init); + auctioneerKeys.put(0L, keys); + var a = new AuctionScript(proofs, registry, 60_000, 2_000_000); + DemoErrors.require(a.deploy(backend, auctioneer), "Deploying the auction script"); + table = JubjubDiscreteLog.forBound(MAX_BID); + auction = a; + } + + // ------------------------------------------------------------------ actions + + /** The seller mints a demo item and opens a lot for it. */ + public synchronized Map open(String item, long deposit, long reserve) throws Exception { + ensureReady(); + if (deposit < 2 || reserve < 2 || reserve > deposit || deposit > 1_000) { + throw new IllegalArgumentException("need 2 ≤ reserve ≤ deposit ≤ 1000 ADA"); + } + if (currentLot != null && auction.lot(backend, currentLot).isPresent()) { + throw new IllegalStateException("the current lot is still open: settle it, refund it or close it first"); + } + Account seller = wallets.get("seller"); + sweep(seller); + String name = (item == null || item.isBlank() ? "Lot" : item.replaceAll("[^A-Za-z0-9]", "")) + "#" + (++itemCounter); + String minted = DemoErrors.require(AuctionScript.mintItem(backend, seller, name), "Minting the item"); + DevKit.waitForTx(backend, minted); + long now = DevKit.chainTimeMillis(backend); + long biddingEnds = now + biddingSeconds * 1000; + long settleBy = biddingEnds + settleSeconds * 1000; + AdmittedAuditor key = auction.registry().admitted(backend); + String tx = DemoErrors.require(auction.open(backend, seller, AuctionScript.itemUnit(seller, name), deposit, reserve, + biddingEnds, settleBy, key), "Opening the lot"); + DevKit.waitForTx(backend, tx); + currentLot = auction.lots(backend).stream().filter(l -> l.utxo().getTxHash().equals(tx)).findFirst() + .orElseThrow(() -> new IllegalStateException("the new lot is not visible")).token(); + return record("open", "Seller listed " + name + " (deposit " + deposit + " ADA, reserve " + reserve + + " ADA); bidding closes in " + biddingSeconds + " s", tx); + } + + /** + * {@code bidder} places a sealed bid of {@code amount} ADA. With {@code copyFrom}, it instead + * re-submits another bidder's ciphertext and proof (the copy cheat). + */ + public synchronized Map bid(String bidder, long amount, String copyFrom) throws Exception { + ensureReady(); + Lot lot = current(); + Account wallet = requireBidder(bidder); + AdmittedAuditor key = auction.registry().admitted(backend); + // ADR-0008 D5: the lot's pinned auctioneer, generation and key must be the current entry's. + if (!Arrays.equals(key.auditor(), lot.auctioneer()) || key.generation() != lot.generation() + || !key.pkU().equals(lot.pkU()) || !key.pkV().equals(lot.pkV())) { + throw new IllegalStateException("the auctioneer's registry entry has changed since this lot opened; refusing to bid"); + } + sweep(wallet); + if (amount < 0 || amount > MAX_BID) throw new IllegalArgumentException("bid out of range"); + ElGamalEncryption enc = ElGamal.encryptWithOpening(key.context(), BigInteger.valueOf(amount), 32, RANDOM); + var proof = DemoErrors.prove(() -> auction.proofs().proveBid(NoteDemo.pkh(wallet), lot.deposit(), lot.reserve(), + lot.pkU(), lot.pkV(), enc), "A bid of " + amount + " ADA is outside [reserve " + lot.reserve() + + ", deposit " + lot.deposit() + "]: no bid proof exists"); + String what = "Bid"; + if (copyFrom != null && !copyFrom.isBlank()) { + // The copy cheat: a bid proof made for another bidder (bound to that bidder's key hash), + // submitted by this one. The lot verifies the proof against the submitter and refuses it. + if (copyFrom.equals(bidder)) throw new IllegalArgumentException("pick another bidder to copy from"); + what = bidder + " copying " + copyFrom + "'s bid"; + Account original = requireBidder(copyFrom); + var copied = DemoErrors.prove(() -> auction.proofs().proveBid(NoteDemo.pkh(original), lot.deposit(), + lot.reserve(), lot.pkU(), lot.pkV(), enc), "no proof"); + DemoErrors.require(auction.bid(backend, wallet, lot, enc, copied), what); + throw new IllegalStateException("unexpected: the lot accepted a proof made for another bidder"); + } + String tx = DemoErrors.require(auction.bid(backend, wallet, lot, enc, proof), what); + DevKit.waitForTx(backend, tx); + return record("bid", bidder + " placed a sealed bid (amount encrypted to the auctioneer; deposit " + + lot.deposit() + " ADA locked)", tx); + } + + /** + * The auctioneer decrypts every bid and settles. With {@code claimWinner} (1-based), it tries + * to name another winner: no proof exists. + */ + public synchronized Map settle(Integer claimWinner) throws Exception { + ensureReady(); + Lot lot = current(); + if (lot.bids().isEmpty()) throw new IllegalStateException("no bids; the seller can take the item back after the window"); + List amounts = decrypt(lot); + if (claimWinner != null && (claimWinner < 1 || claimWinner > amounts.size())) { + throw new IllegalArgumentException("the winner must be a bid number from 1 to " + amounts.size()); + } + int w = 1; + for (int i = 1; i < amounts.size(); i++) if (amounts.get(i) > amounts.get(w - 1)) w = i + 1; + long price = amounts.get(w - 1); + int claimed = claimWinner == null ? w : claimWinner; + long claimedPrice = claimWinner == null ? price : amounts.get(Math.max(0, Math.min(claimed, amounts.size()) - 1)); + AuditorKeys keys = auctioneerKeys.get(lot.generation()); + int fw = claimed; + var proof = DemoErrors.prove(() -> auction.proofs().proveSettle(lot, fw, claimedPrice, + keys.elgamal().secretScalar(), amounts), "Bid " + claimed + " is not the earliest highest bid: no settlement proof exists"); + String tx = DemoErrors.require(auction.settle(backend, auctioneer, lot, claimed, claimedPrice, proof), "Settlement"); + DevKit.waitForTx(backend, tx); + String winner = labelOf(lot.bids().get(claimed - 1).bidder()); + return record("settle", winner + " won at " + claimedPrice + " ADA; losing bids were never published", tx); + } + + /** After {@code settleBy}: anyone returns the item and every deposit. */ + public synchronized Map refund() throws Exception { + ensureReady(); + Lot lot = current(); + String tx = DemoErrors.require(auction.refund(backend, wallets.get("seller"), lot), "Refund"); + DevKit.waitForTx(backend, tx); + return record("refund", "No settlement in time: item returned to the seller, deposits to the bidders", tx); + } + + /** After the window with no bids: the seller takes the item back. */ + public synchronized Map noBids() throws Exception { + ensureReady(); + Lot lot = current(); + String tx = DemoErrors.require(auction.noBids(backend, wallets.get("seller"), lot), "Closing without bids"); + DevKit.waitForTx(backend, tx); + return record("noBids", "No bids: the seller took the item back", tx); + } + + // ------------------------------------------------------------------ state + + public synchronized Map state() throws Exception { + ensureReady(); + Map body = new LinkedHashMap<>(); + body.put("chainTime", DevKit.chainTimeMillis(backend)); + body.put("address", auction.address()); + body.put("constraints", Map.of("bid", auction.proofs().bid().numConstraints(), + "settle3", auction.proofs().settle(3).numConstraints())); + List> balances = new ArrayList<>(); + for (var e : wallets.entrySet()) balances.add(Map.of("wallet", e.getKey(), "ada", lovelace(e.getValue()) / 1_000_000)); + body.put("wallets", balances); + if (currentLot != null) { + var lotOpt = auction.lot(backend, currentLot); + if (lotOpt.isPresent()) { + Lot lot = lotOpt.get(); + List> publicBids = new ArrayList<>(); + List> privateBids = new ArrayList<>(); + List amounts = decrypt(lot); + for (int i = 0; i < lot.bids().size(); i++) { + Lot.Bid b = lot.bids().get(i); + publicBids.add(Map.of("bidder", labelOf(b.bidder()), "handle", NoteDemo.shortHex(b.aU()), + "ciphertext", NoteDemo.shortHex(b.bU()))); + privateBids.add(Map.of("bidder", labelOf(b.bidder()), "amount", amounts.get(i))); + } + body.put("lot", Map.of("token", lot.token().substring(0, 12) + "…", "item", new String(lot.itemName()), + "deposit", lot.deposit(), "reserve", lot.reserve(), "biddingEnds", lot.biddingEnds(), + "settleBy", lot.settleBy(), "generation", lot.generation(), "bids", publicBids, + "lockedAda", lot.utxo().getAmount().stream().filter(x -> x.getUnit().equals("lovelace")) + .findFirst().orElseThrow().getQuantity().longValueExact() / 1_000_000)); + body.put("auctioneerView", privateBids); + } else { + body.put("closed", true); + } + } + body.put("history", List.copyOf(history)); + return body; + } + + // ------------------------------------------------------------------ helpers + + /** + * The auctioneer decrypts every bid of an authentic lot with the key of the lot's generation. + * Delegated admission (elgamal-jubjub-v1 §10.1) needs the context's key to be the one the + * validator verified the bids against, the lot's pinned key. + */ + private List decrypt(Lot lot) { + AuditorKeys keys = auctioneerKeys.get(lot.generation()); + if (keys == null) throw new IllegalStateException("no auctioneer keys for generation " + lot.generation()); + var key = keys.context().jointKey(); + if (!key.affineU().equals(lot.pkU()) || !key.affineV().equals(lot.pkV())) { + throw new IllegalStateException("the lot's key is not this auctioneer's key for generation " + lot.generation()); + } + List out = new ArrayList<>(); + for (Lot.Bid b : lot.bids()) { + RawElGamalCiphertext raw = RawElGamalCiphertext.fromAffine(b.aU(), b.aV(), b.bU(), b.bV()); + // The lot is authentic, so its validator verified this bid's proof under the lot's key. + ElGamalCiphertext ct = ElGamal.admit(raw, keys.context(), 32, statement -> true); + long m = ElGamal.decryptWithSecret(ct, keys.elgamal(), MAX_BID, table); + if (m < lot.reserve() || m > lot.deposit()) { + throw new IllegalStateException("a bid decrypted outside [reserve, deposit]: the lot is not authentic"); + } + out.add(m); + } + return out; + } + + /** Refunds and payouts land at a wallet's enterprise address; move them back so it can spend them. */ + private void sweep(Account wallet) throws Exception { + var swept = AuctionScript.sweep(backend, wallet); + if (swept.isSuccessful() && swept.getValue() != null) DevKit.waitForTx(backend, swept.getValue()); + } + + private Lot current() { + if (currentLot == null) throw new IllegalStateException("open a lot first"); + return auction.lot(backend, currentLot).orElseThrow(() -> new IllegalStateException("the lot is closed; open a new one")); + } + + private Account requireBidder(String label) { + if (!BIDDERS.contains(label)) throw new IllegalArgumentException("unknown bidder: " + label); + return wallets.get(label); + } + + /** The wallet's lovelace at its base address and its enterprise address (where payouts land). */ + private long lovelace(Account a) throws Exception { + String enterprise = AddressProvider.getEntAddress(a.hdKeyPair().getPublicKey(), Networks.testnet()).toBech32(); + return lovelaceAt(a.baseAddress()) + lovelaceAt(enterprise); + } + + private long lovelaceAt(String address) throws Exception { + long sum = 0; + for (int page = 1; ; page++) { + var r = backend.getUtxoService().getUtxos(address, 100, page); + if (!r.isSuccessful() || r.getValue() == null || r.getValue().isEmpty()) break; + for (Utxo u : r.getValue()) { + for (var amt : u.getAmount()) if (amt.getUnit().equals("lovelace")) sum += amt.getQuantity().longValueExact(); + } + if (r.getValue().size() < 100) break; + } + return sum; + } + + private String labelOf(byte[] pkh) { + for (var e : wallets.entrySet()) if (Arrays.equals(NoteDemo.pkh(e.getValue()), pkh)) return e.getKey(); + return HexUtil.encodeHexString(pkh).substring(0, 10) + "…"; + } + + private Map record(String action, String summary, String tx) { + Map entry = new LinkedHashMap<>(); + entry.put("action", action); + entry.put("summary", summary); + entry.put("txHash", tx); + var budget = DevKit.lastBudget(); + if (budget.steps() > 0) entry.put("cost", String.format("%.1f%% of the step limit", budget.stepsPercent())); + history.add(0, entry); + return entry; + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoController.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoController.java index 38f1afd..6e1d3c3 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoController.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoController.java @@ -25,14 +25,18 @@ public class DemoController { private final PointsService points; private final PayrollService payroll; + private final AuctionService auction; private final CreditService credit; private final SolvencyService solvency; private final Map readiness = new ConcurrentHashMap<>( - Map.of("points", "starting", "payroll", "starting", "credit", "starting", "solvency", "starting")); + Map.of("points", "starting", "payroll", "starting", "auction", "starting", "credit", "starting", + "solvency", "starting")); - public DemoController(PointsService points, PayrollService payroll, CreditService credit, SolvencyService solvency) { + public DemoController(PointsService points, PayrollService payroll, AuctionService auction, CreditService credit, + SolvencyService solvency) { this.points = points; this.payroll = payroll; + this.auction = auction; this.credit = credit; this.solvency = solvency; } @@ -42,6 +46,7 @@ public DemoController(PointsService points, PayrollService payroll, CreditServic public void warmUp() { warm("points", () -> points.ensureReady()); warm("payroll", () -> payroll.ensureReady()); + warm("auction", () -> auction.ensureReady()); warm("credit", () -> credit.ensureReady()); warm("solvency", () -> solvency.ensureReady()); } @@ -132,6 +137,41 @@ public Map rotatePayroll() throws Exception { return payroll.rotate(); } + // --- Sealed-bid auction ------------------------------------------------------------------ + + @GetMapping("/auction") + public Map auctionState() throws Exception { + return auction.state(); + } + + @PostMapping("/auction/open") + public Map openLot(@RequestBody Map r) throws Exception { + return auction.open((String) r.get("item"), num(r, "deposit"), num(r, "reserve")); + } + + /** A sealed bid; an optional {@code copyFrom} bidder is the copy cheat. */ + @PostMapping("/auction/bid") + public Map bid(@RequestBody Map r) throws Exception { + return auction.bid(str(r, "bidder"), num(r, "amount"), (String) r.get("copyFrom")); + } + + /** Settles; an optional {@code claimWinner} (1-based) is the auctioneer naming another winner. */ + @PostMapping("/auction/settle") + public Map settle(@RequestBody Map r) throws Exception { + Long claim = optionalNum(r, "claimWinner"); + return auction.settle(claim == null ? null : claim.intValue()); + } + + @PostMapping("/auction/refund") + public Map refund() throws Exception { + return auction.refund(); + } + + @PostMapping("/auction/no-bids") + public Map noBids() throws Exception { + return auction.noBids(); + } + // --- B. Committed credential ------------------------------------------------------------ @GetMapping("/credit") diff --git a/pedersen-commitments/src/main/resources/static/assets/index-BXu4aSBw.css b/pedersen-commitments/src/main/resources/static/assets/index-BXu4aSBw.css new file mode 100644 index 0000000..924c121 --- /dev/null +++ b/pedersen-commitments/src/main/resources/static/assets/index-BXu4aSBw.css @@ -0,0 +1 @@ +.ok.svelte-wzlqy7{background:#12261a;border:1px solid #238636;border-radius:8px;padding:10px 14px;margin:12px 0;color:#7ee787}.noproof.svelte-wzlqy7{background:#2b2111;border:1px solid #d29922;border-radius:8px;padding:10px 14px;margin:12px 0}.noproof.svelte-wzlqy7 h4:where(.svelte-wzlqy7){color:#e3b341;margin:0 0 6px}.rejected.svelte-wzlqy7{background:#2d1214;border:1px solid #da3633;border-radius:8px;padding:10px 14px;margin:12px 0}.rejected.svelte-wzlqy7 h4:where(.svelte-wzlqy7){color:#f85149;margin:0 0 6px}pre.svelte-wzlqy7{white-space:pre-wrap;overflow-wrap:anywhere;max-height:200px;overflow-y:auto;background:#161b22;padding:8px;border-radius:6px;color:#ffb4ad;font-size:.8em}p.svelte-wzlqy7{margin:4px 0}.hint.svelte-wzlqy7{color:#8b949e;font-size:.9em}code.svelte-wzlqy7{font-size:.85em;color:#79c0ff;overflow-wrap:anywhere}.auditor.svelte-euwoin{margin-top:1rem}.pill.svelte-euwoin{display:inline-block;padding:0 .4rem;border-radius:.6rem;background:#e5e7eb;font-size:.8rem;margin-left:.3rem}.pill.ok.svelte-euwoin{background:#d1fae5}.pill.bad.svelte-euwoin,tr.bad.svelte-euwoin td:where(.svelte-euwoin){color:#b91c1c}p.bad.svelte-euwoin{color:#b91c1c}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;max-width:1180px;margin:0 auto;padding:20px;background:#0d1117;color:#c9d1d9}h2{color:#c9d1d9;margin:8px 0}h3{color:#58a6ff;margin:12px 0 6px;font-size:1em}.card{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:14px;margin:12px 0}.columns{display:grid;grid-template-columns:1fr 1fr;gap:16px}.panel{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:12px 14px}.panel.private{border-color:#8957e5}.panel.private h3{color:#d2a8ff}.panel.public{border-color:#1f6feb}table{width:100%;border-collapse:collapse;margin:6px 0;font-size:.9em}th,td{padding:5px 8px;text-align:left;border-bottom:1px solid #21262d}th{color:#8b949e;font-weight:400}code{font-size:.85em;color:#79c0ff}.hint{color:#8b949e;font-size:.9em}.actions{display:flex;flex-wrap:wrap;gap:12px}.action{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:10px 12px;flex:1 1 250px}.action h4{margin:0 0 8px;color:#c9d1d9}.action.cheat{border-color:#da3633}.action.cheat h4{color:#f85149}label{display:block;font-size:.85em;color:#8b949e;margin:4px 0}input,select{background:#0d1117;color:#c9d1d9;border:1px solid #30363d;border-radius:6px;padding:5px 7px;width:100%;box-sizing:border-box}button.primary,button.danger{margin-top:8px;padding:7px 14px;border:none;border-radius:6px;color:#fff;font-weight:700;cursor:pointer}button.primary{background:#238636}button.danger{background:#da3633}button:disabled{opacity:.5;cursor:not-allowed}.busy{color:#58a6ff;margin:8px 0}h1.svelte-1n46o8q{color:#58a6ff;margin-bottom:4px}.subtitle.svelte-1n46o8q{color:#8b949e;margin-top:0}.notice.svelte-1n46o8q{background:#1c1f26;border:1px solid #d29922;border-radius:8px;padding:10px 14px;color:#e3b341;font-size:.92em}nav.svelte-1n46o8q{display:flex;gap:8px;margin:18px 0 8px;flex-wrap:wrap}nav.svelte-1n46o8q button:where(.svelte-1n46o8q){padding:8px 18px;border:1px solid #30363d;background:#21262d;color:#c9d1d9;border-radius:6px;cursor:pointer}nav.svelte-1n46o8q button.active:where(.svelte-1n46o8q){background:#1f6feb;border-color:#1f6feb;color:#fff}.pill.svelte-1n46o8q{display:inline-block;padding:2px 10px;margin:2px;border-radius:12px;background:#30363d;font-size:.85em}.pill.ready.svelte-1n46o8q{background:#238636;color:#fff} diff --git a/pedersen-commitments/src/main/resources/static/assets/index-D7BFeZ31.js b/pedersen-commitments/src/main/resources/static/assets/index-D7BFeZ31.js new file mode 100644 index 0000000..70a6250 --- /dev/null +++ b/pedersen-commitments/src/main/resources/static/assets/index-D7BFeZ31.js @@ -0,0 +1,43 @@ +var qi=Object.defineProperty;var Ta=e=>{throw TypeError(e)};var Li=(e,t,r)=>t in e?qi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var gt=(e,t,r)=>Li(e,typeof t!="symbol"?t+"":t,r),Yn=(e,t,r)=>t.has(e)||Ta("Cannot "+r);var c=(e,t,r)=>(Yn(e,t,"read from private field"),r?r.call(e):t.get(e)),W=(e,t,r)=>t.has(e)?Ta("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),Y=(e,t,r,a)=>(Yn(e,t,"write to private field"),a?a.call(e,r):t.set(e,r),r),ae=(e,t,r)=>(Yn(e,t,"access private method"),r);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))a(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function r(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(s){if(s.ep)return;s.ep=!0;const o=r(s);fetch(s.href,o)}})();const ji="5";var ja;typeof window<"u"&&((ja=window.__svelte??(window.__svelte={})).v??(ja.v=new Set)).add(ji);const zi=1,Bi=2,Ba=4,Hi=8,Ui=16,Vi=1,Yi=2,Ze=Symbol("uninitialized"),Ha=!1;var Bn=Array.isArray,Gi=Array.prototype.indexOf,Dn=Array.prototype.includes,Hn=Array.from,Ua=Object.defineProperty,sn=Object.getOwnPropertyDescriptor,Ki=Object.prototype,Wi=Array.prototype,Ji=Object.getPrototypeOf,Sa=Object.isExtensible;const Zi=()=>{};function Qi(e){for(var t=0;t{e=a,t=s});return{promise:r,resolve:e,reject:t}}function Nn(e,t){if(Array.isArray(e))return e;if(!(Symbol.iterator in e))return Array.from(e);const r=[];for(const a of e)if(r.push(a),r.length===t)break;return r}const ot=2,jr=4,Un=8,Ya=1<<24,Ft=16,Nt=32,tr=64,ta=128,pa=256,Lt=512,Qe=1024,Ue=2048,Dt=4096,ut=8192,_t=16384,Yr=32768,ra=1<<25,zr=65536,Rn=1<<17,Xi=1<<18,Gr=1<<19,es=1<<20,Gt=1<<25,Pn=1<<21,Dr=1<<22,cr=1<<23,on=Symbol("$state"),Ga=Symbol("component"),ts=Symbol("attributes"),na=Symbol("class"),rs=Symbol("style"),Xr=Symbol("text"),Sn=Symbol("form reset"),gn=new class extends Error{constructor(){super(...arguments);gt(this,"name","StaleReactionError");gt(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};function ns(){console.warn("https://svelte.dev/e/derived_inert")}function as(){console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function is(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}function Ka(e){return e===this.v}function ss(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function Wa(e){return!ss(e,this.v)}function os(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function ls(e,t,r){throw new Error("https://svelte.dev/e/each_key_duplicate")}function ds(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function us(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function vs(e){throw new Error("https://svelte.dev/e/effect_orphan")}function cs(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function fs(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function hs(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function _s(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function ps(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}let bs=!1,pt=null;function Br(e){pt=e}function rr(e,t=!1,r){pt={p:pt,i:!1,c:null,e:null,s:e,x:null,r:ye,l:null}}function nr(e){var t=pt,r=t.e;if(r!==null){t.e=null;for(var a of r)bi(a)}return t.i=!0,pt=t.p,Ja(e)}function Ja(e={}){return Ua(e,Ga,{value:!0}),e}function Za(){return!0}let _r=[];function Qa(){var e=_r;_r=[],Qi(e)}function ur(e){if(_r.length===0&&!dn){var t=_r;queueMicrotask(()=>{t===_r&&Qa()})}_r.push(e)}function ms(){for(;_r.length>0;)Qa()}const gs=-7169;function Be(e,t){e.f=e.f&gs|t}function ba(e){(e.f&Lt)!==0||e.deps===null?Be(e,Qe):Be(e,Dt)}function Xa(e,t,r){(e.f&Ue)!==0?t.add(e):(e.f&Dt)!==0&&r.add(e),Be(e,Qe)}let Ca=!1;function ys(){Ca||(Ca=!0,document.addEventListener("reset",e=>{Promise.resolve().then(()=>{var t;if(!e.defaultPrevented)for(const r of e.target.elements)(t=r[Sn])==null||t.call(r)})},{capture:!0}))}function yn(e){var t=ie,r=ye;Rt(null),Jt(null);try{return e()}finally{Rt(t),Jt(r)}}function ei(e,t,r,a=r){e.addEventListener(t,()=>yn(r));const s=e[Sn];s?e[Sn]=()=>{s(),a(!0)}:e[Sn]=()=>a(!0),ys()}function ws(e,t,r,a){const s=ma;var o=e.filter(_=>!_.settled),l=t.map(s);if(r.length===0&&o.length===0){a(l);return}var u=ye,v=xs(),f=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(_=>_.promise)):null;function p(_){if((u.f&_t)===0){v();try{a([...l,..._])}catch(m){Yt(m,u)}Mn()}}var y=ti();if(r.length===0){f.then(()=>p([])).finally(y);return}function w(){Promise.all(r.map(_=>ks(_))).then(p).catch(_=>Yt(_,u)).finally(y)}f?f.then(()=>{v(),w(),Mn()}):w()}function xs(){var e=ye,t=ie,r=pt,a=q;return function(o=!0){Jt(e),Rt(t),Br(r),o&&(e.f&_t)===0&&(a==null||a.activate(),a==null||a.apply())}}function Mn(e=!0){Jt(null),Rt(null),Br(null),e&&(q==null||q.deactivate())}function ti(){var e=ye,t=e.b,r=q,a=!!(t!=null&&t.is_rendered());return t==null||t.update_pending_count(1,r),r.increment(a,e),()=>{t==null||t.update_pending_count(-1,r),r.decrement(a,e)}}function ma(e){var t=ot|Ue;return ye!==null&&(ye.f|=Gr),{ctx:pt,deps:null,effects:null,equals:Ka,f:t,fn:e,reactions:null,rv:0,v:Ze,wv:0,parent:ye,ac:null}}const en=Symbol("obsolete");function ks(e,t,r){let a=ye;a===null&&os();var s=void 0,o=Sr(Ze),l=!ie,u=new Set;return zs(()=>{var _,m;var v=ye,f=Va();s=f.promise;try{Promise.resolve(e()).then(f.resolve,k=>{k!==gn&&f.reject(k)}).finally(Mn)}catch(k){f.reject(k),Mn()}var p=q;if(l){if((v.f&Yr)!==0)var y=ti();if((_=a.b)!=null&&_.is_rendered())(m=p.async_deriveds.get(v))==null||m.reject(en);else for(const k of u.values())k.reject(en);u.add(f),p.async_deriveds.set(v,f)}const w=(k,g=void 0)=>{y==null||y(),u.delete(f),g!==en&&(p.activate(),g?(o.f|=cr,Ur(o,g)):((o.f&cr)!==0&&(o.f^=cr),Ur(o,k)),p.deactivate())};f.promise.then(w,k=>w(null,k||"unknown"))}),pi(()=>{for(const v of u)v.reject(en)}),new Promise(v=>{function f(p){function y(){p===s?v(o):f(s)}p.then(y,y)}f(s)})}function Hr(e){const t=ma(e);return ki(t),t}function As(e){const t=ma(e);return t.equals=Wa,t}function Es(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r{r.ac.abort(gn),r.ac=null}),r.fn!==null&&(r.teardown=Zi),fn(r,0),Aa(r))}function ni(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&t.fn!==null&&Vr(t)}let Gn=null,Cr=null,q=null,ln=null,rt=null,aa=null,dn=!1,Kn=!1,un=null,Cn=null;var $a=0;let Ss=1;var Rr,lr,mr,Pr,Mr,Ir,Zt,Fr,yt,hn,Qt,Mt,Ht,qr,gr,_e,ia,sa,tn,oa,ai,ii,Or,Cs,rn;const Ln=class Ln{constructor(){W(this,_e);gt(this,"id",Ss++);W(this,Rr,!1);gt(this,"linked",!0);W(this,lr,null);W(this,mr,null);gt(this,"async_deriveds",new Map);gt(this,"current",new Map);gt(this,"previous",new Map);W(this,Pr,new Set);W(this,Mr,new Set);W(this,Ir,0);W(this,Zt,new Map);W(this,Fr,null);W(this,yt,[]);W(this,hn,[]);W(this,Qt,new Set);W(this,Mt,new Set);W(this,Ht,new Map);W(this,qr,new Set);gt(this,"is_fork",!1);W(this,gr,!1);Cr===null?Gn=Cr=this:(Y(Cr,mr,this),Y(this,lr,Cr)),Cr=this}skip_effect(t){c(this,Ht).has(t)||c(this,Ht).set(t,{d:[],m:[]}),c(this,qr).delete(t)}unskip_effect(t,r=a=>this.schedule(a)){var a=c(this,Ht).get(t);if(a){c(this,Ht).delete(t);for(var s of a.d)Be(s,Ue),r(s);for(s of a.m)Be(s,Dt),r(s)}c(this,qr).add(t)}capture(t,r,a=!1){t.v!==Ze&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&cr)===0&&(this.current.set(t,[r,a]),rt==null||rt.set(t,r)),this.is_fork||(t.v=r)}activate(){q=this}deactivate(){q=null,rt=null}flush(){try{Kn=!0,q=this,ae(this,_e,tn).call(this)}finally{$a=0,aa=null,un=null,Cn=null,Kn=!1,q=null,rt=null,Kt.clear()}}discard(){var t;for(const r of c(this,Mr))r(this);c(this,Mr).clear();for(const r of this.async_deriveds.values())r.reject(en);ae(this,_e,rn).call(this),(t=c(this,Fr))==null||t.resolve()}register_created_effect(t){c(this,hn).push(t)}increment(t,r){if(Y(this,Ir,c(this,Ir)+1),t){let a=c(this,Zt).get(r)??0;c(this,Zt).set(r,a+1)}}decrement(t,r){if(Y(this,Ir,c(this,Ir)-1),t){let a=c(this,Zt).get(r)??0;a===1?c(this,Zt).delete(r):c(this,Zt).set(r,a-1)}c(this,gr)||(Y(this,gr,!0),ur(()=>{Y(this,gr,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(const a of t)c(this,Qt).add(a);for(const a of r)c(this,Mt).add(a);t.clear(),r.clear()}oncommit(t){c(this,Pr).add(t)}ondiscard(t){c(this,Mr).add(t)}settled(){return(c(this,Fr)??Y(this,Fr,Va())).promise}static ensure(){if(q===null){const t=q=new Ln;!Kn&&!dn&&ur(()=>{c(t,Rr)||t.flush()})}return q}apply(){{rt=null;return}}schedule(t){var r;if(aa=t,(r=t.b)!=null&&r.is_pending&&(t.f&(jr|Un|Ya))!==0&&(t.f&Yr)===0){t.b.defer_effect(t);return}c(this,yt).push(t)}};Rr=new WeakMap,lr=new WeakMap,mr=new WeakMap,Pr=new WeakMap,Mr=new WeakMap,Ir=new WeakMap,Zt=new WeakMap,Fr=new WeakMap,yt=new WeakMap,hn=new WeakMap,Qt=new WeakMap,Mt=new WeakMap,Ht=new WeakMap,qr=new WeakMap,gr=new WeakMap,_e=new WeakSet,ia=function(){if(this.is_fork)return!0;for(const a of c(this,Zt).keys()){for(var t=a,r=!1;t.parent!==null;){if(c(this,Ht).has(t)){r=!0;break}t=t.parent}if(!r)return!0}return!1},sa=function(){var t=[];for(const o of c(this,yt))if(!((o.f&_t)!==0||(o.f&(Ue|Dt))===0)){for(var r=o,a=!1;r.parent!==null;){r=r.parent;var s=r.f;if((s&(tr|Nt))!==0){if((s&Qe)===0){a=!0;break}r.f^=Qe}}a||t.push(r)}return Y(this,yt,[]),t},tn=function(){var u,v,f,p;Y(this,Rr,!0);for(const y of c(this,Qt))c(this,Mt).delete(y),Be(y,Ue),this.schedule(y);for(const y of c(this,Mt))Be(y,Dt),this.schedule(y);this.apply();for(var t=un=[],r=[],a=Cn=[];c(this,yt).length>0;){$a++>1e3&&(ae(this,_e,rn).call(this),Os());for(const y of ae(this,_e,sa).call(this))try{ae(this,_e,oa).call(this,y,t,r)}catch(w){throw li(y),ae(this,_e,ia).call(this)||this.discard(),w}}if(q=null,a.length>0){var s=Ln.ensure();for(const y of a)s.schedule(y)}if(un=null,Cn=null,ae(this,_e,ia).call(this)){ae(this,_e,Or).call(this,r),ae(this,_e,Or).call(this,t);for(const[y,w]of c(this,Ht))oi(y,w);a.length>0&&ae(u=q,_e,tn).call(u);return}const o=ae(this,_e,ai).call(this);if(o){ae(this,_e,Or).call(this,r),ae(this,_e,Or).call(this,t),ae(v=o,_e,ii).call(v,this);return}c(this,Qt).clear(),c(this,Mt).clear();for(const y of c(this,Pr))y(this);c(this,Pr).clear(),ln=this,Oa(r),Oa(t),ln=null,(f=c(this,Fr))==null||f.resolve();var l=q;if(c(this,Ir)===0&&(c(this,yt).length===0||l!==null)&&ae(this,_e,rn).call(this),c(this,yt).length>0)if(l!==null){for(const y of c(this,yt))c(l,yt).push(y);Y(this,yt,[])}else l=this;l!==null&&(Kt.clear(),ae(p=l,_e,tn).call(p))},oa=function(t,r,a){t.f^=Qe;for(var s=t.first;s!==null;){var o=s.f,l=(o&(Nt|tr))!==0,u=l&&(o&Qe)!==0,v=u||(o&ut)!==0||c(this,Ht).has(s);if(!v&&s.fn!==null){l?s.f^=Qe:(o&jr)!==0?r.push(s):xn(s)&&((o&Ft)!==0&&c(this,Mt).add(s),Vr(s));var f=s.first;if(f!==null){s=f;continue}}for(;s!==null;){var p=s.next;if(p!==null){s=p;break}s=s.parent}}},ai=function(){for(var t=c(this,lr);t!==null;){if(!t.is_fork){for(const[r,[,a]]of this.current)if(t.current.has(r)&&!a)return t}t=c(t,lr)}return null},ii=function(t){var a;for(const[s,o]of t.current)!this.previous.has(s)&&t.previous.has(s)&&this.previous.set(s,t.previous.get(s)),this.current.set(s,o);for(const[s,o]of t.async_deriveds){const l=this.async_deriveds.get(s);l&&o.promise.then(l.resolve).catch(l.reject)}t.async_deriveds.clear(),this.transfer_effects(c(t,Qt),c(t,Mt));const r=s=>{var o=s.reactions;if(o!==null&&!((s.f&ot)!==0&&(s.f&(Ue|Dt))===0))for(const v of o){var l=v.f;if((l&ot)!==0)r(v);else{var u=v;l&(Dr|Ft)&&!this.async_deriveds.has(u)&&(c(this,Mt).delete(u),Be(u,Ue),this.schedule(u))}}};for(const s of this.current.keys())r(s);this.oncommit(()=>t.discard()),ae(a=t,_e,rn).call(a),q=this,ae(this,_e,tn).call(this)},Or=function(t){for(var r=0;r!_.current.get(m)[1]);if(!(!c(_,Rr)||s.length===0)){var o=s.filter(m=>!this.current.has(m));if(o.length===0)t&&_.discard();else if(r.length>0){if(t)for(const m of c(this,qr))_.unskip_effect(m,k=>{var g;(k.f&(Ft|Dr))!==0?_.schedule(k):ae(g=_,_e,Or).call(g,[k])});_.activate();var l=new Set,u=new Map;for(var v of r)si(v,o,l,u);u=new Map;var f=[..._.current].filter(([m,k])=>{const g=this.current.get(m);return g?g[0]!==k[0]||g[1]!==k[1]:!0}).map(([m])=>m);if(f.length>0)for(const m of c(this,hn))(m.f&(_t|ut|Rn))===0&&ya(m,f,u)&&((m.f&(Dr|Ft))!==0?(Be(m,Ue),_.schedule(m)):c(_,Qt).add(m));if(c(_,yt).length>0&&!c(_,gr)){_.apply();for(var p of ae(y=_,_e,sa).call(y))ae(w=_,_e,oa).call(w,p,[],[])}_.deactivate()}}}},rn=function(){if(this.linked){var t=c(this,lr),r=c(this,mr);t===null?Gn=r:Y(t,mr,r),r===null?Cr=t:Y(r,lr,t),this.linked=!1}};let Tr=Ln;function $s(e){var t=dn;dn=!0;try{for(var r;;){if(ms(),q===null)return r;q.flush()}}finally{dn=t}}function Os(){try{cs()}catch(e){Yt(e,aa)}}let Pt=null;function Oa(e){var t=e.length;if(t!==0){for(var r=0;r0)){Kt.clear();for(const s of Pt){if((s.f&(_t|ut))!==0)continue;const o=[s];let l=s.parent;for(;l!==null;)Pt.has(l)&&(Pt.delete(l),o.push(l)),l=l.parent;for(let u=o.length-1;u>=0;u--){const v=o[u];(v.f&(_t|ut))===0&&Vr(v)}}Pt.clear()}}Pt=null}}function si(e,t,r,a){if(!r.has(e)&&(r.add(e),e.reactions!==null))for(const s of e.reactions){const o=s.f;(o&ot)!==0?si(s,t,r,a):(o&(Dr|Ft))!==0&&(o&Ue)===0&&ya(s,t,a)&&(Be(s,Ue),wa(s))}}function ya(e,t,r){const a=r.get(e);if(a!==void 0)return a;if(e.deps!==null)for(const s of e.deps){if(Dn.call(t,s))return!0;if((s.f&ot)!==0&&ya(s,t,r))return r.set(s,!0),!0}return r.set(e,!1),!1}function wa(e){q.schedule(e)}function oi(e,t){if(!((e.f&Nt)!==0&&(e.f&Qe)!==0)){(e.f&Ue)!==0?t.d.push(e):(e.f&Dt)!==0&&t.m.push(e),Be(e,Qe);for(var r=e.first;r!==null;)oi(r,t),r=r.next}}function li(e){Be(e,Qe);for(var t=e.first;t!==null;)li(t),t=t.next}let In=new Set;const Kt=new Map;let di=!1;function Sr(e,t){var r={f:0,v:e,reactions:null,equals:Ka,rv:0,wv:0};return r}function R(e,t){const r=Sr(e);return ki(r),r}function Ds(e,t=!1,r=!0){const a=Sr(e);return t||(a.equals=Wa),a}function T(e,t,r=!1){ie!==null&&(!qt||(ie.f&Rn)!==0)&&Za()&&(ie.f&(ot|Ft|Dr|Rn))!==0&&(Wt===null||!Wt.has(e))&&_s();let a=r?vr(t):t;return Ur(e,a,Cn)}var hr=null,la=0;function Ur(e,t,r=null){if(!e.equals(t)){fr?Kt.set(e,t):Kt.has(e)||Kt.set(e,e.v);var a=Tr.ensure();if(a.capture(e,t),(e.f&ot)!==0){const s=e;(e.f&Ue)!==0&&ga(s),rt===null&&ba(s)}e.wv=Ei(),hr=null,la=0,ui(e,Ue,r),hr=null,ye!==null&&(ye.f&Qe)!==0&&(ye.f&(Nt|tr))===0&&(St===null?Us([e]):St.push(e)),!a.is_fork&&In.size>0&&!di&&Ns()}return t}function Ns(){di=!1;for(const e of In){(e.f&Qe)!==0&&Be(e,Dt);let t;try{t=xn(e)}catch{t=!0}t&&Vr(e)}In.clear()}function vn(e){T(e,e.v+1)}function ui(e,t,r){var a=e.reactions;if(a!==null){var s=a.length;if(la+=s,la>1e5&&hr===null&&(hr=new Set),hr!==null){if(hr.has(e))return;hr.add(e)}for(var o=0;o{if(Ar===o)return u();var v=ie,f=Ar;Rt(null),Pa(o);var p=u();return Rt(v),Pa(f),p};return a&&r.set("length",R(e.length)),new Proxy(e,{defineProperty(u,v,f){(!("value"in f)||f.configurable===!1||f.enumerable===!1||f.writable===!1)&&fs();var p=r.get(v);return p===void 0?l(()=>{var y=R(f.value);return r.set(v,y),y}):T(p,f.value,!0),!0},deleteProperty(u,v){var f=r.get(v);if(f===void 0){if(v in u){const p=l(()=>R(Ze));r.set(v,p),vn(s)}}else T(f,Ze),vn(s);return!0},get(u,v,f){var _;if(v===on)return e;var p=r.get(v),y=v in u;if(p===void 0&&(!y||(_=sn(u,v))!=null&&_.writable)&&(p=l(()=>{var m=vr(y?u[v]:Ze),k=R(m);return k}),r.set(v,p)),p!==void 0){var w=n(p);return w===Ze?void 0:w}return Reflect.get(u,v,f)},getOwnPropertyDescriptor(u,v){var w;(w=this.has)==null||w.call(this,u,v);var f=Reflect.getOwnPropertyDescriptor(u,v),p=r.get(v);if(p!==void 0){var y=n(p);if(y===Ze)return;if(f&&"value"in f)f.value=y;else return{enumerable:!0,configurable:!0,value:y,writable:!0}}return f},has(u,v){var w;if(v===on)return!0;var f=r.get(v),p=f!==void 0&&f.v!==Ze||Reflect.has(u,v);if(f!==void 0||ye!==null&&(!p||(w=sn(u,v))!=null&&w.writable)){f===void 0&&(f=l(()=>{var _=p?vr(u[v]):Ze,m=R(_);return m}),r.set(v,f));var y=n(f);if(y===Ze)return!1}return p},set(u,v,f,p){var P;var y=r.get(v),w=v in u;if(a&&v==="length")for(var _=f;_R(Ze)),r.set(_+"",m))}if(y===void 0)(!w||(P=sn(u,v))!=null&&P.writable)&&(y=l(()=>R(void 0)),T(y,vr(f)),r.set(v,y));else{w=y.v!==Ze;var k=l(()=>vr(f));T(y,k)}var g=Reflect.getOwnPropertyDescriptor(u,v);if(g!=null&&g.set&&g.set.call(p,f),!w){if(a&&typeof v=="string"){var E=r.get("length"),J=Number(v);Number.isInteger(J)&&J>=E.v&&T(E,J+1)}vn(s)}return!0},ownKeys(u){n(s);var v=Reflect.ownKeys(u).filter(y=>{var w=r.get(y);return w===void 0||w.v!==Ze});for(var[f,p]of r)p.v!==Ze&&!(f in u)&&v.push(f);return v},setPrototypeOf(){hs()}})}function Da(e){try{if(e!==null&&typeof e=="object"&&on in e)return e[on]}catch{}return e}function vi(e,t){return Object.is(Da(e),Da(t))}var Na,ci,fi,hi;function Rs(){if(Na===void 0){Na=window,ci=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;fi=sn(t,"firstChild").get,hi=sn(t,"nextSibling").get,Sa(e)&&(e[na]=void 0,e[ts]=null,e[rs]=void 0,e.__e=void 0),Sa(r)&&(r[Xr]=void 0)}}function er(e=""){return document.createTextNode(e)}function cn(e){return fi.call(e)}function wn(e){return hi.call(e)}function d(e,t){return cn(e)}function nt(e,t=!1){{var r=cn(e);return r instanceof Comment&&r.data===""?wn(r):r}}function b(e,t=!1){return cn(e)}function i(e,t=1,r=!1){let a=e;for(;t--;)a=wn(a);return a}function Ps(e){e.textContent=""}function _i(){return!1}function Ms(e,t,r){return r?document.createElement(e,{is:r}):document.createElement(e)}function Is(e){var t=ye;if(t===null)return ie.f|=cr,e;if((t.f&Yr)===0&&(t.f&jr)===0)throw e;Yt(e,t)}function Yt(e,t){if(!(t!==null&&(t.f&_t)!==0)){for(;t!==null;){if((t.f&ta)!==0&&(t.f&(_t|ra))===0){if((t.f&Yr)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}function Fs(e){ye===null&&(ie===null&&vs(),us()),fr&&ds()}function qs(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function ar(e,t){var r=ye;r!==null&&(r.f&ut)!==0&&(e|=ut);var a={ctx:pt,deps:null,nodes:null,f:e|Ue|Lt,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};q==null||q.register_created_effect(a);var s=a;if((e&jr)!==0)un!==null?un.push(a):Tr.ensure().schedule(a);else if(t!==null){try{Vr(a)}catch(l){throw bt(a),l}s.deps===null&&s.teardown===null&&s.nodes===null&&s.first===s.last&&(s.f&Gr)===0&&(s=s.first,(e&Ft)!==0&&(e&zr)!==0&&s!==null&&(s.f|=zr))}if(s!==null&&(s.parent=r,r!==null&&qs(s,r),ie!==null&&(ie.f&ot)!==0&&(e&tr)===0)){var o=ie;(o.effects??(o.effects=[])).push(s)}return a}function xa(){return ie!==null&&!qt}function pi(e){const t=ar(Un,null);return Be(t,Qe),t.teardown=e,t}function Kr(e){Fs();var t=ye.f,r=!ie&&(t&Nt)!==0&&pt!==null&&!pt.i;if(r){var a=pt;(a.e??(a.e=[])).push(e)}else return bi(e)}function bi(e){return ar(jr|es,e)}function Ls(e){Tr.ensure();const t=ar(tr|Gr,e);return(r={})=>new Promise(a=>{r.outro?kr(t,()=>{bt(t),a(void 0)}):(bt(t),a(void 0))})}function js(e){return ar(jr,e)}function zs(e){return ar(Dr|Gr,e)}function mi(e,t=0){return ar(Un|t,e)}function D(e,t=[],r=[],a=[]){ws(a,t,r,s=>{ar(Un,()=>{e(...s.map(n))})})}function ka(e,t=0){var r=ar(Ft|t,e);return r}function Ot(e){return ar(Nt|Gr,e)}function gi(e){var t=e.teardown;if(t!==null){const r=fr,a=ie;Ra(!0),Rt(null);try{t.call(null)}catch(s){Yt(s,e.parent)}finally{Ra(r),Rt(a)}}}function Aa(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){const s=r.ac;s!==null&&yn(()=>{s.abort(gn)});var a=r.next;(r.f&tr)!==0?r.parent=null:bt(r,t),r=a}}function Bs(e){for(var t=e.first;t!==null;){var r=t.next;(t.f&Nt)===0&&bt(t),t=r}}function bt(e,t=!0){var r=!1;(t||(e.f&Xi)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(Hs(e.nodes.start,e.nodes.end),r=!0),e.f|=ra,Aa(e,t&&!r),fn(e,0);var a=e.nodes&&e.nodes.t;if(a!==null)for(const o of a)o.stop();gi(e),e.f^=ra,e.f|=_t;var s=e.parent;s!==null&&s.first!==null&&yi(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function Hs(e,t){for(;e!==null;){var r=e===t?null:wn(e);e.remove(),e=r}}function yi(e){var t=e.parent,r=e.prev,a=e.next;r!==null&&(r.next=a),a!==null&&(a.prev=r),t!==null&&(t.first===e&&(t.first=a),t.last===e&&(t.last=r))}function kr(e,t,r=!0){var a=[];e.f|=pa,wi(e,a,!0);var s=()=>{r&&bt(e),t&&t()},o=a.length;if(o>0){var l=()=>--o||s();for(var u of a)u.out(l)}else s()}function wi(e,t,r){if((e.f&ut)===0){e.f^=ut;var a=e.nodes&&e.nodes.t;if(a!==null)for(const u of a)(u.is_global||r)&&t.push(u);for(var s=e.first;s!==null;){var o=s.next;if((s.f&tr)===0){var l=(s.f&zr)!==0||(s.f&Nt)!==0&&(e.f&Ft)!==0;wi(s,t,l?r:!1)}s=o}}}function Fn(e){e.f&=~pa,xi(e,!0)}function xi(e,t){if((e.f&pa)===0&&(e.f&ut)!==0){e.f^=ut,(e.f&Qe)===0&&(Be(e,Ue),Tr.ensure().schedule(e));for(var r=e.first;r!==null;){var a=r.next,s=(r.f&zr)!==0||(r.f&Nt)!==0;xi(r,s?t:!1),r=a}var o=e.nodes&&e.nodes.t;if(o!==null)for(const l of o)(l.is_global||t)&&l.in()}}function Ea(e,t){if(e.nodes)for(var r=e.nodes.start,a=e.nodes.end;r!==null;){var s=r===a?null:wn(r);t.append(r),r=s}}let $n=!1,fr=!1;function Ra(e){fr=e}let ie=null,qt=!1;function Rt(e){ie=e}let ye=null;function Jt(e){ye=e}let Wt=null;function ki(e){ie!==null&&((ie.f&Pn)!==0||(ie.f&ot)!==0)&&(Wt??(Wt=new Set)).add(e)}let ht=null,At=0,St=null;function Us(e){St=e}let Ai=1,pr=0,Ar=pr;function Pa(e){Ar=e}function Ei(){return++Ai}function xn(e){var t=e.f;if((t&Ue)!==0)return!0;if((t&Dt)!==0){for(var r=e.deps,a=r.length,s=0;se.wv)return!0}(t&Lt)!==0&&rt===null&&Be(e,Qe)}return!1}function Ti(e,t,r=!0){var a=e.reactions;if(a!==null&&!(Wt!==null&&Wt.has(e)))for(var s=0;s{e.ac.abort(gn)}),e.ac=null);try{e.f|=Pn;var p=e.fn,y=p();e.f|=Yr;var w=Ma(e);if(Za()&&St!==null&&!qt&&w!==null&&(e.f&(ot|Dt|Ue))===0)for(var _=0;_0)for(t.length=At+ht.length,a=0;a{o.ac.abort(gn),o.ac=null,Be(o,Ue)}),Ts(o),fn(o,0)}}function fn(e,t){var r=e.deps;if(r!==null)for(var a=t;a{Jn=!1,Wn=null}));var l=0,u=Wn===e&&e[br];if(u){var v=s.indexOf(u);if(v!==-1&&(t===document||t===window)){e[br]=t;return}var f=s.indexOf(t);if(f===-1)return;v<=f&&(l=v)}if(o=s[l]||e.target,o!==t){Ua(e,"currentTarget",{configurable:!0,get(){return o||r}});var p=ie,y=ye;Rt(null),Jt(null);try{for(var w,_=[];o!==null&&o!==t;){try{var m=(g=o[br])==null?void 0:g[a];m!=null&&(!o.disabled||e.target===o)&&m.call(o,e)}catch(E){w?_.push(E):w=E}if(e.cancelBubble)break;l++,o=l{throw E});throw w}}finally{e[br]=t,delete e.currentTarget,Rt(p),Jt(y)}}}var za;const Zn=((za=globalThis==null?void 0:globalThis.window)==null?void 0:za.trustedTypes)&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function Gs(e){return(Zn==null?void 0:Zn.createHTML(e))??e}function Ks(e){var t=Ms("template");return t.innerHTML=Gs(e.replaceAll("","")),t.content}function qn(e,t){var r=ye;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function $(e,t){var r=(t&Vi)!==0,a=(t&Yi)!==0,s,o=!e.startsWith("");return()=>{s===void 0&&(s=Ks(o?e:""+e),r||(s=cn(s)));var l=a||ci?document.importNode(s,!0):s.cloneNode(!0);if(r){var u=cn(l),v=l.lastChild;qn(u,v)}else qn(l,l);return l}}function Er(e=""){{var t=er(e+"");return qn(t,t),t}}function Fa(){var e=document.createDocumentFragment(),t=document.createComment(""),r=er();return e.append(t,r),qn(t,r),e}function x(e,t){e!==null&&e.before(t)}const Ws=["touchstart","touchmove"];function Js(e){return Ws.includes(e)}function Zs(e){let t=0,r=Sr(0),a;return()=>{xa()&&(n(r),mi(()=>(t===0&&(a=Oi(()=>e(()=>vn(r)))),t+=1,()=>{ur(()=>{t-=1,t===0&&(a==null||a(),a=void 0,vn(r))})})))}}var Qs=zr|Gr;function Xs(e,t,r,a){new eo(e,t,r,a)}var Ct,_a,$t,yr,lt,wt,dt,xt,Ut,wr,dr,Lr,_n,pn,Xt,jn,Pe,to,ro,ua,no,va,nn,On,ca,fa;class eo{constructor(t,r,a,s){W(this,Pe);gt(this,"parent");gt(this,"is_pending",!1);gt(this,"transform_error");W(this,Ct);W(this,_a,null);W(this,$t);W(this,yr);W(this,lt);W(this,wt,null);W(this,dt,null);W(this,xt,null);W(this,Ut,null);W(this,wr,0);W(this,dr,0);W(this,Lr,!1);W(this,_n,new Set);W(this,pn,new Set);W(this,Xt,null);W(this,jn,Zs(()=>(Y(this,Xt,Sr(c(this,wr))),()=>{Y(this,Xt,null)})));var o;Y(this,Ct,t),Y(this,$t,r),Y(this,yr,l=>{var u=ye;u.b=this,u.f|=ta,a(l)}),this.parent=ye.b,this.transform_error=s??((o=this.parent)==null?void 0:o.transform_error)??(l=>l),Y(this,lt,ka(()=>{ae(this,Pe,va).call(this)},Qs))}defer_effect(t){Xa(t,c(this,_n),c(this,pn))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!c(this,$t).pending}update_pending_count(t,r){ae(this,Pe,ca).call(this,t,r),Y(this,wr,c(this,wr)+t),!(!c(this,Xt)||c(this,Lr))&&(Y(this,Lr,!0),ur(()=>{Y(this,Lr,!1),c(this,Xt)&&Ur(c(this,Xt),c(this,wr))}))}get_effect_pending(){return c(this,jn).call(this),n(c(this,Xt))}error(t){if(!c(this,$t).onerror&&!c(this,$t).failed)throw t;q!=null&&q.is_fork?(c(this,wt)&&q.skip_effect(c(this,wt)),c(this,dt)&&q.skip_effect(c(this,dt)),c(this,xt)&&q.skip_effect(c(this,xt)),q.oncommit(()=>{ae(this,Pe,fa).call(this,t)})):ae(this,Pe,fa).call(this,t)}}Ct=new WeakMap,_a=new WeakMap,$t=new WeakMap,yr=new WeakMap,lt=new WeakMap,wt=new WeakMap,dt=new WeakMap,xt=new WeakMap,Ut=new WeakMap,wr=new WeakMap,dr=new WeakMap,Lr=new WeakMap,_n=new WeakMap,pn=new WeakMap,Xt=new WeakMap,jn=new WeakMap,Pe=new WeakSet,to=function(){try{Y(this,wt,Ot(()=>c(this,yr).call(this,c(this,Ct))))}catch(t){this.error(t)}},ro=function(t){const r=c(this,$t).failed,{reset:a,invoke_onerror:s}=ae(this,Pe,ua).call(this,t);ur(s),r&&Y(this,xt,Ot(()=>{r(c(this,Ct),()=>t,()=>a)}))},ua=function(t){var r=!1,a=!1;const s=()=>{if(r){is();return}r=!0,a&&ps(),c(this,xt)!==null&&kr(c(this,xt),()=>{Y(this,xt,null)}),ae(this,Pe,On).call(this,()=>{ae(this,Pe,va).call(this)})};return{reset:s,invoke_onerror:()=>{var l,u;try{a=!0,(u=(l=c(this,$t)).onerror)==null||u.call(l,t,s),a=!1}catch(v){Yt(v,c(this,lt)&&c(this,lt).parent)}}}},no=function(){const t=c(this,$t).pending;t&&(this.is_pending=!0,Y(this,dt,Ot(()=>t(c(this,Ct)))),ur(()=>{var r=Y(this,Ut,document.createDocumentFragment()),a=er(),s=!1;if(r.append(a),Y(this,wt,ae(this,Pe,On).call(this,()=>{try{return Ot(()=>c(this,yr).call(this,a))}catch(o){try{this.error(o),s=!0}catch(l){Yt(l,c(this,lt).parent)}return null}})),c(this,wt)===null){Y(this,Ut,null),s&&ae(this,Pe,nn).call(this,q);return}c(this,dr)===0&&(c(this,Ct).before(r),Y(this,Ut,null),kr(c(this,dt),()=>{Y(this,dt,null)}),ae(this,Pe,nn).call(this,q))}))},va=function(){try{if(this.is_pending=this.has_pending_snippet(),Y(this,dr,0),Y(this,wr,0),Y(this,wt,Ot(()=>{c(this,yr).call(this,c(this,Ct))})),c(this,dr)>0){var t=Y(this,Ut,document.createDocumentFragment());Ea(c(this,wt),t);const r=c(this,$t).pending;Y(this,dt,Ot(()=>r(c(this,Ct))))}else ae(this,Pe,nn).call(this,q)}catch(r){this.error(r)}},nn=function(t){this.is_pending=!1,t.transfer_effects(c(this,_n),c(this,pn))},On=function(t){var r=ye,a=ie,s=pt;Jt(c(this,lt)),Rt(c(this,lt)),Br(c(this,lt).ctx);try{return Tr.ensure(),t()}finally{Jt(r),Rt(a),Br(s)}},ca=function(t,r){var a;if(!this.has_pending_snippet()){this.parent&&ae(a=this.parent,Pe,ca).call(a,t,r);return}Y(this,dr,c(this,dr)+t),c(this,dr)===0&&(ae(this,Pe,nn).call(this,r),c(this,dt)&&kr(c(this,dt),()=>{Y(this,dt,null)}),c(this,Ut)&&(c(this,Ct).before(c(this,Ut)),Y(this,Ut,null)))},fa=function(t){c(this,wt)&&(bt(c(this,wt)),Y(this,wt,null)),c(this,dt)&&(bt(c(this,dt)),Y(this,dt,null)),c(this,xt)&&(bt(c(this,xt)),Y(this,xt,null));let r=c(this,$t).failed;const a=s=>{const{reset:o,invoke_onerror:l}=ae(this,Pe,ua).call(this,s);l(),r&&Y(this,xt,ae(this,Pe,On).call(this,()=>{try{return Ot(()=>{var u=ye;u.b=this,u.f|=ta,r(c(this,Ct),()=>s,()=>o)})}catch(u){return Yt(u,c(this,lt).parent),null}}))};ur(()=>{var s;try{s=this.transform_error(t)}catch(o){Yt(o,c(this,lt)&&c(this,lt).parent);return}s!==null&&typeof s=="object"&&typeof s.then=="function"?s.then(a,o=>Yt(o,c(this,lt)&&c(this,lt).parent)):a(s)})};function h(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[Xr]??(e[Xr]=e.nodeValue))&&(e[Xr]=r,e.nodeValue=`${r}`)}function ao(e,t){return io(e,t)}const En=new Map;function io(e,{target:t,anchor:r,props:a={},events:s,context:o,intro:l=!0,transformError:u}){Rs();var v=void 0,f=Ls(()=>{var p=r??t.appendChild(er());Xs(p,{pending:()=>{}},_=>{rr({});var m=pt;o&&(m.c=o),s&&(a.$$events=s),v=e(_,a)||Ja(),nr()},u);var y=new Set,w=_=>{for(var m=0;m<_.length;m++){var k=_[m];if(!y.has(k)){y.add(k);var g=Js(k);for(const P of[t,document]){var E=En.get(P);E===void 0&&(E=new Map,En.set(P,E));var J=E.get(k);J===void 0?(P.addEventListener(k,Ia,{passive:g}),E.set(k,1)):E.set(k,J+1)}}}};return w(Hn(Di)),da.add(w),()=>{var g;for(var _ of y)for(const E of[t,document]){var m=En.get(E),k=m.get(_);--k==0?(E.removeEventListener(_,Ia),m.delete(_),m.size===0&&En.delete(E)):m.set(_,k)}da.delete(w),p!==r&&((g=p.parentNode)==null||g.removeChild(p))}});return so.set(v,f),v}let so=new WeakMap;var It,Vt,kt,xr,bn,mn,zn;class oo{constructor(t,r=!0){gt(this,"anchor");W(this,It,new Map);W(this,Vt,new Map);W(this,kt,new Map);W(this,xr,new Set);W(this,bn,!0);W(this,mn,t=>{if(c(this,It).has(t)){var r=c(this,It).get(t),a=c(this,Vt).get(r);if(a)Fn(a),c(this,xr).delete(r);else{var s=c(this,kt).get(r);s&&(Fn(s.effect),c(this,Vt).set(r,s.effect),c(this,kt).delete(r),s.fragment.lastChild.remove(),this.anchor.before(s.fragment),a=s.effect)}for(const[o,l]of c(this,It)){if(c(this,It).delete(o),o===t)break;const u=c(this,kt).get(l);u&&(bt(u.effect),c(this,kt).delete(l))}for(const[o,l]of c(this,Vt)){if(o===r||c(this,xr).has(o))continue;const u=()=>{if(Array.from(c(this,It).values()).includes(o)){var f=document.createDocumentFragment();Ea(l,f),f.append(er()),c(this,kt).set(o,{effect:l,fragment:f})}else bt(l);c(this,xr).delete(o),c(this,Vt).delete(o)};c(this,bn)||!a?(c(this,xr).add(o),kr(l,u,!1)):u()}}});W(this,zn,t=>{c(this,It).delete(t);const r=Array.from(c(this,It).values());for(const[a,s]of c(this,kt))r.includes(a)||(bt(s.effect),c(this,kt).delete(a))});this.anchor=t,Y(this,bn,r)}ensure(t,r){var a=q,s=_i();if(r&&!c(this,Vt).has(t)&&!c(this,kt).has(t))if(s){var o=document.createDocumentFragment(),l=er();o.append(l),c(this,kt).set(t,{effect:Ot(()=>r(l)),fragment:o})}else c(this,Vt).set(t,Ot(()=>r(this.anchor)));if(c(this,It).set(a,t),s){for(const[u,v]of c(this,Vt))u===t?a.unskip_effect(v):a.skip_effect(v);for(const[u,v]of c(this,kt))u===t?a.unskip_effect(v.effect):a.skip_effect(v.effect);a.oncommit(c(this,mn)),a.ondiscard(c(this,zn))}else c(this,mn).call(this,a)}}It=new WeakMap,Vt=new WeakMap,kt=new WeakMap,xr=new WeakMap,bn=new WeakMap,mn=new WeakMap,zn=new WeakMap;function G(e,t,r=!1){var a=new oo(e),s=r?zr:0;function o(l,u){a.ensure(l,u)}ka(()=>{var l=!1;t((u,v=0)=>{l=!0,o(v,u)}),l||o(-1,null)},s)}function de(e,t){return t}function lo(e,t,r){for(var a=[],s=t.length,o,l=t.length,u=0;u{if(o){if(o.pending.delete(y),o.done.add(y),o.pending.size===0){var w=e.outrogroups;ha(e,Hn(o.done)),w.delete(o),w.size===0&&(e.outrogroups=null)}}else l-=1},!1)}if(l===0){var v=a.length===0&&r!==null&&e.pending.size===0;if(v){var f=r,p=f.parentNode;Ps(p),p.append(f),e.items.clear()}ha(e,t,!v)}else o={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(o)}function ha(e,t,r=!0){var a;if(e.pending.size>0){a=new Set;for(const l of e.pending.values())for(const u of l)a.add(e.items.get(u).e)}for(var s=0;s{var P=r();return Bn(P)?P:P==null?[]:Hn(P)}),w,_=new Map,m=!0;function k(P){(J.effect.f&_t)===0&&(J.pending.delete(P),J.fallback=p,uo(J,w,l,t,a),p!==null&&(w.length===0?(p.f&Gt)===0?Fn(p):(p.f^=Gt,an(p,null,l)):kr(p,()=>{p=null})))}function g(P){J.pending.delete(P)}var E=ka(()=>{w=n(y);for(var P=w.length,fe=new Set,Ae=q,se=_i(),z=0;zo(l)):(p=Ot(()=>o(qa??(qa=er()))),p.f|=Gt)),P>fe.size&&ls(),!m)if(_.set(Ae,fe),se){for(const[Ee,Ce]of u)fe.has(Ee)||Ae.skip_effect(Ce.e);Ae.oncommit(k),Ae.ondiscard(g)}else k(Ae);n(y)}),J={effect:E,items:u,pending:_,outrogroups:null,fallback:p};m=!1}function Qr(e){for(;e!==null&&(e.f&Nt)===0;)e=e.next;return e}function uo(e,t,r,a,s){var ee,Ee,Ce,je,$e,Z,L,te,I;var o=(a&Hi)!==0,l=t.length,u=e.items,v=Qr(e.effect.first),f,p=null,y,w=[],_=[],m,k,g,E;if(o)for(E=0;E0){var we=(a&Ba)!==0&&l===0?r:null;if(o){for(E=0;E{var H,oe;if(y!==void 0)for(g of y)(oe=(H=g.nodes)==null?void 0:H.a)==null||oe.apply()})}function vo(e,t,r,a,s,o,l,u){var v=(l&zi)!==0?(l&Ui)===0?Ds(r,!1,!1):Sr(r):null,f=(l&Bi)!==0?Sr(s):null;return{v,i:f,e:Ot(()=>(o(t,v??r,f??s,u),()=>{e.delete(a)}))}}function an(e,t,r){if(e.nodes)for(var a=e.nodes.start,s=e.nodes.end,o=t&&(t.f&Gt)===0?t.nodes.start:r;a!==null;){var l=wn(a);if(o.before(a),a===s)return;a=l}}function sr(e,t,r){t===null?e.effect.first=r:t.next=r,r===null?e.effect.last=t:r.prev=t}const La=[...` +\r\f \v\uFEFF`];function co(e,t,r){var a=e==null?"":""+e;if(r){for(var s of Object.keys(r))if(r[s])a=a?a+" "+s:s;else if(a.length)for(var o=s.length,l=0;(l=a.indexOf(s,l))>=0;){var u=l+o;(l===0||La.includes(a[l-1]))&&(u===a.length||La.includes(a[u]))?a=(l===0?"":a.substring(0,l))+a.substring(u+1):l=u}}return a===""?null:a}function or(e,t,r,a,s,o){var l=e[na];if(l!==r||l===void 0){var u=co(r,a,o);u==null?e.removeAttribute("class"):e.className=u,e[na]=r}else if(o&&s!==o)for(var v in o){var f=!!o[v];(s==null||f!==!!s[v])&&e.classList.toggle(v,f)}return o}function fo(e,t){t?e.hasAttribute("selected")||e.setAttribute("selected",""):e.removeAttribute("selected")}function ho(e,t){var r=e.__defaultValue,a=e.multiple,s=a?r??[]:null;if(!(a&&!Bn(s))){e.selectedIndex;for(var o of e.options){var l=Nr(o);fo(o,a?s.includes(l):vi(l,r))}}}function Ni(e,t,r=!1){if(e.multiple){if(t==null)return;if(!Bn(t))return as();for(var a of e.options)a.selected=t.includes(Nr(a));return}for(a of e.options){var s=Nr(a);if(vi(s,t)){a.selected=!0;return}}(!r||t!==void 0)&&(e.selectedIndex=-1)}function ct(e){var t=new MutationObserver(r=>{r.every(_o)||("__defaultValue"in e&&ho(e),"__value"in e&&Ni(e,e.__value))});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),pi(()=>{t.disconnect()})}function ft(e,t,r=t){var a=new WeakSet,s=!0;ei(e,"change",o=>{var l=o?"[selected]":":checked",u;if(e.multiple)u=[].map.call(e.querySelectorAll(l),Nr);else{var v=e.querySelector(l)??e.querySelector("option:not([disabled])");u=v&&Nr(v)}r(u),e.__value=u,q!==null&&a.add(q)}),js(()=>{var o=t();if(e===document.activeElement){var l=q;if(a.has(l))return}if(Ni(e,o,s),s&&o===void 0){var u=e.querySelector(":checked");u!==null&&(o=Nr(u),r(o))}e.__value=o,s=!1})}function Nr(e){return"__value"in e?e.__value:e.value}function _o(e){if(e.target.closest("selectedcontent")!==null)return!0;if(e.type==="childList"){var t=[...e.addedNodes,...e.removedNodes];return t.length>0&&t.every(r=>r.nodeName==="SELECTEDCONTENT")}return!1}function He(e,t,r=t){var a=new WeakSet;ei(e,"input",async s=>{var o=s?e.defaultValue:e.value;if(o=Qn(e)?Xn(o):o,r(o),q!==null&&a.add(q),await Ys(),o!==(o=t())){var l=e.selectionStart,u=e.selectionEnd,v=e.value.length;if(e.value=o??"",u!==null){var f=e.value.length;l===u&&u===v&&f>v?(e.selectionStart=f,e.selectionEnd=f):(e.selectionStart=l,e.selectionEnd=Math.min(u,f))}}}),Oi(t)==null&&e.value&&(r(Qn(e)?Xn(e.value):e.value),q!==null&&a.add(q)),mi(()=>{var s=t();if(e===document.activeElement){var o=q;if(a.has(o))return}Qn(e)&&s===Xn(e.value)||e.type==="date"&&!s&&!e.value||s!==e.value&&(e.value=s??"")})}function Qn(e){var t=e.type;return t==="number"||t==="range"}function Xn(e){return e===""?null:+e}function po(e,t,r,a){var s=a,o=!0,l=()=>(o&&(o=!1,s=a),s),u;u=e[t],u===void 0&&a!==void 0&&(u=l());var v;return v=()=>{var f=e[t];return f===void 0?l():(o=!0,f)},v}async function Ri(e,t,r){try{const a=await fetch(`/api${t}`,{method:e,headers:r===void 0?void 0:{"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),s=await a.json().catch(()=>({error:a.statusText}));return{ok:a.ok,data:s}}catch(a){return{ok:!1,data:{error:(a==null?void 0:a.message)??String(a)}}}}const Jr=e=>Ri("GET",e),kn=(e,t={})=>Ri("POST",e,t);var bo=$('
',1),mo=$('

'),go=$('

No proof possible

The statement is false, so the prover cannot produce a proof. Nothing reaches the chain.

'),yo=$('

 
'),wo=$('

');function An(e,t){rr(t,!0);var r=Fa(),a=nt(r);{var s=o=>{var l=Fa(),u=nt(l);{var v=w=>{var _=mo(),m=d(_),k=i(m);{var g=E=>{var J=bo(),P=i(nt(J)),fe=b(P);D(()=>h(fe,`tx ${t.result.data.txHash??""}`)),x(E,J)};G(k,E=>{t.result.data.txHash&&E(g)})}D(()=>h(m,`✓ ${t.result.data.summary??t.result.data.verdict??t.result.data.lenderLearns??"Done"??""} `)),x(w,_)},f=w=>{var _=go(),m=i(d(_),2),k=b(m,!0);D(()=>h(k,t.result.data.error)),x(w,_)},p=w=>{var _=yo(),m=d(_),k=b(m,!0),g=i(m,2),E=b(g,!0),J=i(g,2),P=b(J,!0);D(()=>{h(k,t.result.data.onChainValidation.title),h(E,t.result.data.onChainValidation.summary),h(P,t.result.data.onChainValidation.detail)}),x(w,_)},y=w=>{var _=wo(),m=d(_),k=b(m,!0);D(()=>{var g;return h(k,((g=t.result.data)==null?void 0:g.error)??"Failed")}),x(w,_)};G(u,w=>{var _,m;t.result.ok?w(v):(_=t.result.data)!=null&&_.noProof?w(f,1):(m=t.result.data)!=null&&m.onChainValidation?w(p,2):w(y,-1)})}x(o,l)};G(a,o=>{t.result&&o(s)})}x(e,r),nr()}var xo=$(' '),ko=$(' '),Ao=$(" "),Eo=$("
amountcommitment (u)gennote UTxO
"),To=$(`

Owned but unopenable: — the sender's delivery does not open to the commitment.

`),So=$("

: balance

",1),Co=$(" "),$o=$(" "),Oo=$("

Receipts held by the issuer

receipt UTxOspenderprice
",1),Do=$(' '),No=$(" "),Ro=$("

Transactions

",1),Po=$(`

Wallets — recovered from the chain with each viewing key

On-chain — what anyone can see

Notes at : owner, commitment, generation, two limb + ciphertexts and two encrypted openings — never the amount.

note UTxOownercommitment ugenlimb A.udeliveries

Registry generation · ElGamal key · viewing key . Amounts come from the limb ciphertexts (keys of the note's generation); + each is cross-checked against the auditor's own encrypted opening.

note UTxOowneramountorigingencheck

Totals by owner:

`,1);function Pi(e,t){rr(t,!0);let r=po(t,"unit",3,"points");var a=Po(),s=nt(a),o=d(s),l=i(d(o),2);ue(l,17,()=>Object.entries(t.state.wallets),de,(Z,L)=>{var te=Hr(()=>Nn(n(L),2));let I=()=>n(te)[0],H=()=>n(te)[1];var oe=So(),pe=nt(oe),Oe=d(pe),Me=b(Oe,!0),Ie=i(Oe,2),Le=b(Ie,!0),j=i(Ie),ve=i(j);{var be=he=>{var Fe=xo(),qe=b(Fe);D(()=>h(qe,`${H().unopenable.length??""} unopenable owned note${H().unopenable.length>1?"s":""}`)),x(he,Fe)};G(ve,he=>{H().unopenable.length>0&&he(be)})}var O=i(ve,2);{var M=he=>{var Fe=ko(),qe=b(Fe);D(()=>h(qe,`${H().readableNotMine??""} readable, not owned`)),x(he,Fe)};G(O,he=>{H().readableNotMine>0&&he(M)})}var U=i(pe,2);{var xe=he=>{var Fe=Eo(),qe=i(d(Fe));ue(qe,21,()=>H().notes,de,(et,Ve)=>{var Et=Ao(),ce=d(Et),Te=b(ce,!0),Ge=i(ce),Ke=d(Ge),Se=b(Ke,!0),S=i(Ge),A=b(S,!0),N=i(S),F=d(N),V=b(F,!0);D(()=>{h(Te,n(Ve).amount),h(Se,n(Ve).commitment),h(A,n(Ve).generation),h(V,n(Ve).utxo)}),x(et,Et)}),x(he,Fe)};G(U,he=>{H().notes.length>0&&he(xe)})}var De=i(U,2);ue(De,17,()=>H().unopenable,de,(he,Fe)=>{var qe=To(),et=i(d(qe)),Ve=b(et,!0);D(()=>h(Ve,n(Fe))),x(he,qe)}),D(()=>{h(Me,I()),h(Le,H().balance),h(j,` ${r()??""} `)}),x(Z,oe)});var u=i(o,2),v=i(d(u),2),f=i(d(v)),p=b(f),y=i(v,2),w=i(d(y));ue(w,21,()=>t.state.onChain,de,(Z,L)=>{var te=Co(),I=d(te),H=d(I),oe=b(H,!0),pe=i(I),Oe=b(pe,!0),Me=i(pe),Ie=d(Me),Le=b(Ie,!0),j=i(Me),ve=b(j,!0),be=i(j),O=d(be),M=b(O,!0),U=i(be),xe=b(U);D(()=>{h(oe,n(L).utxo),h(Oe,n(L).owner),h(Le,n(L).u),h(ve,n(L).generation),h(M,n(L).limbHandle),h(xe,`${n(L).deliveries??""} × 89 B`)}),x(Z,te)});var _=i(y,2);{var m=Z=>{var L=Oo(),te=i(nt(L),2),I=i(d(te));ue(I,21,()=>t.state.receipts,de,(H,oe)=>{var pe=$o(),Oe=d(pe),Me=d(Oe),Ie=b(Me,!0),Le=i(Oe),j=b(Le,!0),ve=i(Le),be=b(ve,!0);D(()=>{h(Ie,n(oe).utxo),h(j,n(oe).spender),h(be,n(oe).price)}),x(H,pe)}),x(Z,L)};G(_,Z=>{t.state.receipts.length>0&&Z(m)})}var k=i(s,2),g=d(k),E=b(g),J=i(g,2),P=i(d(J)),fe=b(P,!0),Ae=i(P,2),se=b(Ae,!0),z=i(Ae,2),le=b(z,!0),we=i(J,2),ee=i(d(we));ue(ee,21,()=>t.state.auditor.notes,de,(Z,L)=>{var te=Do();let I;var H=d(te),oe=d(H),pe=b(oe,!0),Oe=i(H),Me=b(Oe,!0),Ie=i(Oe),Le=d(Ie),j=b(Le,!0),ve=i(Ie),be=d(ve);let O;var M=b(be,!0),U=i(ve),xe=b(U,!0),De=i(U),he=b(De,!0);D(()=>{I=or(te,1,"svelte-euwoin",null,I,{bad:!n(L).consistent}),h(pe,n(L).utxo),h(Me,n(L).owner),h(j,n(L).amount),O=or(be,1,"pill svelte-euwoin",null,O,{ok:n(L).origin==="proof-enforced"}),h(M,n(L).origin),h(xe,n(L).generation),h(he,n(L).status)}),x(Z,te)});var Ee=i(we,2),Ce=i(d(Ee));ue(Ce,17,()=>Object.entries(t.state.auditor.totals),de,(Z,L,te)=>{var I=Hr(()=>Nn(n(L),2));let H=()=>n(I)[0],oe=()=>n(I)[1];var pe=Er();D(()=>h(pe,`${te>0?" · ":""}${H()??""} ${oe()??""}`)),x(Z,pe)});var je=i(k,2);{var $e=Z=>{var L=Ro(),te=i(nt(L),2),I=d(te);ue(I,21,()=>t.state.history,de,(H,oe)=>{var pe=No(),Oe=d(pe),Me=b(Oe,!0),Ie=i(Oe),Le=b(Ie,!0),j=i(Ie),ve=d(j),be=b(ve);D(O=>{h(Me,n(oe).summary),h(Le,n(oe).cost??""),h(be,`${O??""}…`)},[()=>n(oe).txHash.substring(0,20)]),x(H,pe)}),x(Z,L)};G(je,Z=>{t.state.history.length>0&&Z($e)})}D(Z=>{h(p,`${Z??""}…`),h(E,`${t.state.auditor.label??""} — reads every amount from the chain`),h(fe,t.state.registry.generation),h(se,t.state.registry.elgamalKey),h(le,t.state.registry.viewingKey)},[()=>t.state.ledgerAddress.substring(0,34)]),x(e,a),nr()}var $r=$(""),Mo=$('

'),Io=$(`

A. Confidential points

Loyalty points are notes: a Pedersen commitment, the opening encrypted on-chain to the + owner and the auditor (confidential-note-jubjub-v1), and the amount encrypted to the auditor as two + 32-bit ElGamal limbs that the transfer proof binds to the commitment (ADR-0055 D3a). Wallets recover their notes by + scanning the chain with their viewing key; the auditor reads every amount from the chain. Issuance is trusted

Issue (retailer)

Transfer

Cheat: ask for more than the sender's largest note holds — no proof exists.

Redeem at the retailer

Auditor key rotation

Try to cheat

Garbage delivery

unopenable note, while the auditor + still reads the amount (D3a).

Under-report an issuance

issuer-claimed and a mismatch with its own delivery. (Payroll's proved issuance refuses this.)

Limbs to the retired key

Note under another stake key

An honest transfer plus a copy of a note paid to the ledger's script with another stake credential. + The address policy refuses every output under the script that is not at its exact address (M3 criterion (a)).

Spend someone else's note

`);function Fo(e,t){rr(t,!0);let r=R(null),a=R(""),s=R(null),o=R("alice"),l=R(1e3),u=R(100),v=R("alice"),f=R("bob"),p=R(700),y=R("bob"),w=R(120),_=R("bob"),m=R("alice");const k=["alice","bob"];async function g(){const C=await Jr("/points");C.ok&&T(r,C.data,!0)}async function E(C,K,B){T(a,C,!0),T(s,null),T(s,await kn(K,B),!0),T(a,""),await g()}Kr(()=>{g()});var J=Io(),P=i(d(J),2),fe=i(d(P),6),Ae=i(P,2),se=d(Ae),z=i(d(se),2),le=i(d(z));ue(le,21,()=>k,de,(C,K)=>{var B=$r(),Re=b(B,!0),ne={};D(()=>{h(Re,n(K)),ne!==(ne=n(K))&&(B.__value=ne)}),x(C,B)}),ct(le);var we=i(z,2),ee=i(d(we)),Ee=i(we,2),Ce=i(se,2),je=i(d(Ce),2),$e=i(d(je));ue($e,21,()=>k,de,(C,K)=>{var B=$r(),Re=b(B,!0),ne={};D(()=>{h(Re,n(K)),ne!==(ne=n(K))&&(B.__value=ne)}),x(C,B)}),ct($e);var Z=i(je,2),L=i(d(Z));ue(L,21,()=>k,de,(C,K)=>{var B=$r(),Re=b(B,!0),ne={};D(()=>{h(Re,n(K)),ne!==(ne=n(K))&&(B.__value=ne)}),x(C,B)}),ct(L);var te=i(Z,2),I=i(d(te)),H=i(te,2),oe=i(Ce,2),pe=i(d(oe),2),Oe=i(d(pe));ue(Oe,21,()=>k,de,(C,K)=>{var B=$r(),Re=b(B,!0),ne={};D(()=>{h(Re,n(K)),ne!==(ne=n(K))&&(B.__value=ne)}),x(C,B)}),ct(Oe);var Me=i(pe,2),Ie=i(d(Me)),Le=i(Me,2),j=i(oe,2),ve=i(d(j),2),be=b(ve),O=i(ve,2),M=i(Ae,4),U=d(M),xe=i(d(U),2),De=d(xe),he=i(xe,2),Fe=i(U,2),qe=i(d(Fe),2),et=i(d(qe)),Ve=i(qe,2),Et=d(Ve),ce=i(Ve,2),Te=i(Fe,2),Ge=i(d(Te),2),Ke=b(Ge),Se=i(Ge,2),S=i(Te,2),A=i(d(S),4),N=i(S,2),F=i(d(N),2),V=i(d(F));ue(V,21,()=>k,de,(C,K)=>{var B=$r(),Re=b(B,!0),ne={};D(()=>{h(Re,n(K)),ne!==(ne=n(K))&&(B.__value=ne)}),x(C,B)}),ct(V);var re=i(F,2),Ne=i(d(re));ue(Ne,21,()=>k,de,(C,K)=>{var B=$r(),Re=b(B,!0),ne={};D(()=>{h(Re,n(K)),ne!==(ne=n(K))&&(B.__value=ne)}),x(C,B)}),ct(Ne);var ze=i(re,2),Ye=i(M,2);{var We=C=>{var K=Mo(),B=b(K);D(()=>h(B,`${n(a)??""}… (proving and waiting for the block)`)),x(C,K)};G(Ye,C=>{n(a)&&C(We)})}var tt=i(Ye,2);An(tt,{get result(){return n(s)}});var me=i(tt,2);{var ge=C=>{Pi(C,{get state(){return n(r)},unit:"points"})};G(me,C=>{n(r)&&C(ge)})}D(()=>{var C,K,B,Re,ne,Q,ke;h(fe,`: the retailer supplies the issued notes' audit data. Circuits: transfer + ${((K=(C=n(r))==null?void 0:C.constraints)==null?void 0:K.transfer)??"…"??""} constraints, redeem ${((Re=(B=n(r))==null?void 0:B.constraints)==null?void 0:Re.redeem)??"…"??""}.`),Ee.disabled=!!n(a),H.disabled=!!n(a),Le.disabled=!!n(a),h(be,`Registry generation ${((Q=(ne=n(r))==null?void 0:ne.registry)==null?void 0:Q.generation)??"…"??""}. Both possession proofs are verified on-chain.`),O.disabled=!!n(a),h(De,`${n(v)??""} sends ${n(p)??""} to ${n(f)??""}, but the recipient's encrypted opening is random bytes. The ledger + can only check its length, so it is accepted: ${n(f)??""}'s wallet reports an `),he.disabled=!!n(a),h(Et,`The retailer issues ${n(l)??""} but encrypts ${n(u)??""} to the auditor. Trusted issuance accepts it; + the auditor sees `),ce.disabled=!!n(a),h(Ke,`After a rotation, ${n(v)??""} encrypts the amounts to the auditor's previous key. The ledger reads the key + from the current registry entry, so the proof does not verify.`),Se.disabled=!!n(a)||!((ke=n(r))!=null&&ke.canUseRetiredKey),A.disabled=!!n(a),ze.disabled=!!n(a)}),ft(le,()=>n(o),C=>T(o,C)),He(ee,()=>n(l),C=>T(l,C)),X("click",Ee,()=>E("Issuing","/points/issue",{to:n(o),amount:n(l)})),ft($e,()=>n(v),C=>T(v,C)),ft(L,()=>n(f),C=>T(f,C)),He(I,()=>n(p),C=>T(p,C)),X("click",H,()=>E("Proving and submitting the transfer","/points/transfer",{from:n(v),to:n(f),amount:n(p)})),ft(Oe,()=>n(y),C=>T(y,C)),He(Ie,()=>n(w),C=>T(w,C)),X("click",Le,()=>E("Proving and submitting the redemption","/points/redeem",{from:n(y),price:n(w)})),X("click",O,()=>E("Rotating the auditor keys","/points/rotate",{})),X("click",he,()=>E("Submitting a transfer with a garbage delivery","/points/transfer",{from:n(v),to:n(f),amount:n(p),cheat:"garbageDelivery"})),He(et,()=>n(u),C=>T(u,C)),X("click",ce,()=>E("Issuing with under-reported audit data","/points/issue",{to:n(o),amount:n(l),reported:n(u)})),X("click",Se,()=>E("Submitting a transfer to the retired key","/points/transfer",{from:n(v),to:n(f),amount:n(p),cheat:"retiredKey"})),X("click",A,()=>E("Submitting a transfer with a stake-variant note","/points/transfer",{from:n(v),to:n(f),amount:n(p),cheat:"stakeVariant"})),ft(V,()=>n(_),C=>T(_,C)),ft(Ne,()=>n(m),C=>T(m,C)),X("click",ze,()=>E("Submitting the theft","/points/steal",{thief:n(_),victim:n(m)})),x(e,J),nr()}Wr(["click"]);var qo=$('

'),Lo=$("
income
credit score
birth year
country
blinding
"),jo=$('

No profile issued yet.

'),zo=$("
commitment u
commitment v
schema digest σ
holder
record token
record tx
"),Bo=$('

Nothing recorded yet.

'),Ho=$('

No badge claimed yet.

'),Uo=$(" "),Vo=$(`

Private — Alice's opening

On-chain — the issuance record

What the lender learns

`),Yo=$(`

B. Committed credential

A credit bureau commits to four attributes of Alice's profile in one vector commitment + (schema ) and records the issuance on-chain. Alice then + proves income ≥ X ∧ credit_score ≥ Y

1. Bureau issues Alice's profile

2. Alice claims a badge from the lender

Raise a threshold above her profile to see that no proof exists.

Try to cheat: Mallory presents Alice's credential

Suppose Alice's opening leaked: Mallory has a valid proof for Alice's commitment. The issuance + record names Alice, and the gate requires the named holder's signature.

`);function Go(e,t){rr(t,!0);let r=R(null),a=R(""),s=R(null),o=R(85e3),l=R(720),u=R(1990),v=R(356),f=R(5e4),p=R(650);async function y(){const j=await Jr("/credit");j.ok&&T(r,j.data,!0)}async function w(j,ve,be){T(a,j,!0),T(s,null),T(s,await kn(ve,be),!0),T(a,""),await y()}Kr(()=>{y()});var _=Yo(),m=i(d(_),2),k=i(d(m),3),g=b(k),E=i(k,3),J=i(m,2),P=d(J),fe=i(d(P),2),Ae=i(d(fe)),se=i(fe,2),z=i(d(se)),le=i(se,2),we=i(d(le)),ee=i(le,2),Ee=i(d(ee)),Ce=i(ee,2),je=i(P,2),$e=i(d(je),2),Z=i(d($e)),L=i($e,2),te=i(d(L)),I=i(L,2),H=i(je,2),oe=i(d(H),4),pe=i(J,2);{var Oe=j=>{var ve=qo(),be=b(ve);D(()=>h(be,`${n(a)??""}… (proving and waiting for the block)`)),x(j,ve)};G(pe,j=>{n(a)&&j(Oe)})}var Me=i(pe,2);An(Me,{get result(){return n(s)}});var Ie=i(Me,2);{var Le=j=>{var ve=Vo(),be=d(ve),O=i(d(be),2);{var M=ce=>{var Te=Lo(),Ge=d(Te),Ke=d(Ge),Se=i(d(Ke)),S=b(Se,!0),A=i(Ke),N=i(d(A)),F=b(N,!0),V=i(A),re=i(d(V)),Ne=b(re,!0),ze=i(V),Ye=i(d(ze)),We=b(Ye,!0),tt=i(ze),me=i(d(tt)),ge=d(me),C=b(ge,!0);D(()=>{h(S,n(r).private.income),h(F,n(r).private.creditScore),h(Ne,n(r).private.birthYear),h(We,n(r).private.country),h(C,n(r).private.blinding)}),x(ce,Te)},U=ce=>{var Te=jo();x(ce,Te)};G(O,ce=>{n(r).private?ce(M):ce(U,-1)})}var xe=i(be,2),De=i(d(xe),2);{var he=ce=>{var Te=zo(),Ge=d(Te),Ke=d(Ge),Se=i(d(Ke)),S=d(Se),A=b(S,!0),N=i(Ke),F=i(d(N)),V=d(F),re=b(V,!0),Ne=i(N),ze=i(d(Ne)),Ye=d(ze),We=b(Ye,!0),tt=i(Ne),me=i(d(tt)),ge=d(me),C=b(ge,!0),K=i(tt),B=i(d(K)),Re=d(B),ne=b(Re,!0),Q=i(K),ke=i(d(Q)),Je=d(ke),at=b(Je);D(it=>{h(A,n(r).onChain.u),h(re,n(r).onChain.v),h(We,n(r).schema.digest),h(C,n(r).onChain.holder),h(ne,n(r).onChain.recordToken),h(at,`${it??""}…`)},[()=>n(r).onChain.recordTx.substring(0,20)]),x(ce,Te)},Fe=ce=>{var Te=Bo();x(ce,Te)};G(De,ce=>{n(r).onChain?ce(he):ce(Fe,-1)})}var qe=i(De,4);{var et=ce=>{var Te=Ho();x(ce,Te)};G(qe,ce=>{n(r).claims.length===0&&ce(et)})}var Ve=i(qe,2),Et=d(Ve);ue(Et,21,()=>n(r).claims,de,(ce,Te)=>{var Ge=Uo(),Ke=d(Ge),Se=b(Ke),S=i(Ke),A=d(S),N=b(A);D(F=>{h(Se,`${n(Te).claimant??""}: ${n(Te).lenderLearns??""}`),h(N,`${F??""}…`)},[()=>n(Te).txHash.substring(0,16)]),x(ce,Ge)}),x(j,ve)};G(Ie,j=>{n(r)&&j(Le)})}D(()=>{var j,ve,be,O,M,U,xe;h(g,`${((ve=(j=n(r))==null?void 0:j.schema)==null?void 0:ve.id)??""} v${((O=(be=n(r))==null?void 0:be.schema)==null?void 0:O.version)??""}`),h(E,` to a lender's gate and receives a badge. The lender learns that + she qualifies — not her income, score, birth year or country. Circuit: ${((M=n(r))==null?void 0:M.constraints)??"…"??""} constraints.`),Ce.disabled=!!n(a),I.disabled=!!n(a)||!((U=n(r))!=null&&U.private),oe.disabled=!!n(a)||!((xe=n(r))!=null&&xe.private)}),He(Ae,()=>n(o),j=>T(o,j)),He(z,()=>n(l),j=>T(l,j)),He(we,()=>n(u),j=>T(u,j)),He(Ee,()=>n(v),j=>T(v,j)),X("click",Ce,()=>w("Committing and recording the issuance","/credit/issue",{income:n(o),creditScore:n(l),birthYear:n(u),country:n(v)})),He(Z,()=>n(f),j=>T(f,j)),He(te,()=>n(p),j=>T(p,j)),X("click",I,()=>w("Proving Alice's predicate and claiming","/credit/claim",{who:"alice",minIncome:n(f),minScore:n(p)})),X("click",oe,()=>w("Submitting Mallory's claim","/credit/claim",{who:"mallory",minIncome:n(f),minScore:n(p)})),x(e,_),nr()}Wr(["click"]);var Ko=$(''),Wo=$(''),Jo=$(""),Zo=$('

'),Qo=$('
Auditor: its on-chain delivery opens, against the sum of all on-chain commitments, to total liabilities of
'),Xo=$("— reserve released, tx ",1),el=$('
Period: phase
'),tl=$(" "),rl=$(" "),nl=$('

Reserve locked: at

id hashcommitment uencrypted opening

Attestation tx

',1),al=$('

No attestation yet.

'),il=$(`

Private — the exchange's book (customers recover their own opening from the chain)

Total liabilities: (never published)

customerbalancesaltblindingid hashlast check

On-chain — the period's vault

`,1),sl=$(`

C. Hidden-liability solvency

The exchange publishes one Pedersen commitment per customer balance and proves Σ balances ≤ reserves while hiding every balance and the total. The reserve is locked in a vault for a + public attestation period: attestations only before it starts, release only after it ends, so the same funds + cannot back attestations one after another. Each entry carries its customer's opening encrypted on-chain to the customer's viewing key, and the attestation carries the total's opening encrypted to the auditor's registered + viewing key (confidential-note-jubjub-v1

1. The book (balances in ADA)

2. Attest for a new period

Lock less than the book's total to see that no proof exists.

3. Check (during the period)

Attest with a garbage delivery

Try to cheat inside the period

Before the period ends the vault rejects a release; after it ends the release succeeds.

`);function ol(e,t){rr(t,!0);let r=R(null),a=R(""),s=R(null),o=R(2e3),l=R("dave"),u=R(vr([])),v=0,f=R(vr(Date.now()));async function p(){const O=await Jr("/solvency");O.ok&&(T(r,O.data,!0),v=O.data.chainTime-Date.now(),n(u).length===0&&T(u,O.data.book.map(M=>({id:M.id,balance:M.balance})),!0))}async function y(O,M,U={}){T(a,O,!0),T(s,null),T(s,await kn(M,U),!0),T(a,""),await p()}function w(O){return Math.max(0,Math.round((O-(n(f)+v))/1e3))}Kr(()=>{p();const O=setInterval(()=>{T(f,Date.now(),!0)},1e3),M=setInterval(()=>{var U;!n(a)&&((U=n(r))!=null&&U.period)&&p()},5e3);return()=>{clearInterval(O),clearInterval(M)}});let _=Hr(()=>{var O,M;return((O=n(r))==null?void 0:O.period)&&!((M=n(r))!=null&&M.releaseTx)});var m=sl(),k=i(d(m),2),g=i(d(k),8),E=i(k,2),J=d(E),P=i(d(J),2),fe=d(P);ue(fe,21,()=>n(u),de,(O,M,U)=>{var xe=Ko(),De=d(xe),he=d(De),Fe=i(De),qe=d(Fe);D(()=>{he.disabled=n(_),qe.disabled=n(_)}),He(he,()=>n(M).id,et=>n(M).id=et),He(qe,()=>n(M).balance,et=>n(M).balance=et),x(O,xe)});var Ae=i(P,2),se=i(J,2),z=i(d(se),2),le=i(d(z)),we=i(z,2),ee=i(se,2),Ee=i(d(ee),2);ue(Ee,17,()=>{var O;return((O=n(r))==null?void 0:O.book)??[]},de,(O,M)=>{var U=Wo(),xe=b(U);D(()=>{var De;U.disabled=!!n(a)||!((De=n(r))!=null&&De.period),h(xe,`${n(M).id??""} checks`)}),X("click",U,()=>y(`${n(M).id} checks the attestations`,"/solvency/check",{id:n(M).id})),x(O,U)});var Ce=i(Ee,2),je=i(ee,2),$e=i(d(je),2),Z=i(d($e));ue(Z,21,()=>{var O;return((O=n(r))==null?void 0:O.book)??[]},de,(O,M)=>{var U=Jo(),xe=b(U,!0),De={};D(()=>{h(xe,n(M).id),De!==(De=n(M).id)&&(U.__value=De)}),x(O,U)}),ct(Z);var L=i($e,2),te=b(L),I=i(L,2),H=i(je,2),oe=i(d(H),2),pe=i(oe,2),Oe=i(E,2);{var Me=O=>{var M=Zo(),U=b(M);D(()=>h(U,`${n(a)??""}… (proving and waiting for the block)`)),x(O,M)};G(Oe,O=>{n(a)&&O(Me)})}var Ie=i(Oe,2);An(Ie,{get result(){return n(s)}});var Le=i(Ie,2);{var j=O=>{var M=Qo(),U=i(d(M)),xe=b(U),De=i(U);D(()=>{h(xe,`${n(s).data.liabilitiesAda??""} ADA`),h(De,` against ${n(s).data.reservesAda??""} ADA locked — + ${n(s).data.ok?"verified":"NOT verified"}. No single balance is revealed.`)}),x(O,M)};G(Le,O=>{var M;(M=n(s))!=null&&M.ok&&n(s).data.liabilitiesAda!==void 0&&O(j)})}var ve=i(Le,2);{var be=O=>{var M=il(),U=nt(M);{var xe=Se=>{var S=el(),A=i(d(S),2),N=b(A,!0),F=i(A,2);{var V=me=>{var ge=Er();D(C=>h(ge,`— starts in ${C??""} s (attestations allowed until then)`),[()=>w(n(r).period.start)]),x(me,ge)};G(F,me=>{n(r).phase==="before"&&me(V)})}var re=i(F,2);{var Ne=me=>{var ge=Er();D(C=>h(ge,`— ends in ${C??""} s (nothing can be added or released)`),[()=>w(n(r).period.end)]),x(me,ge)};G(re,me=>{n(r).phase==="during"&&me(Ne)})}var ze=i(re,2);{var Ye=me=>{var ge=Er("— ended; the reserve can be released");x(me,ge)};G(ze,me=>{n(r).phase==="after"&&me(Ye)})}var We=i(ze,2);{var tt=me=>{var ge=Xo(),C=i(nt(ge)),K=b(C);D(B=>h(K,`${B??""}…`),[()=>n(r).releaseTx.substring(0,20)]),x(me,ge)};G(We,me=>{n(r).phase==="released"&&me(tt)})}D(()=>h(N,n(r).phase)),x(Se,S)};G(U,Se=>{n(r).period&&Se(xe)})}var De=i(U,2),he=d(De),Fe=i(d(he),2),qe=i(d(Fe)),et=b(qe),Ve=i(Fe,2),Et=i(d(Ve));ue(Et,21,()=>n(r).book,de,(Se,S)=>{var A=tl(),N=d(A),F=b(N,!0),V=i(N),re=b(V,!0),Ne=i(V),ze=d(Ne),Ye=b(ze,!0),We=i(Ne),tt=d(We),me=b(tt,!0),ge=i(We),C=d(ge),K=b(C,!0),B=i(ge),Re=b(B,!0);D(()=>{h(F,n(S).id),h(re,n(S).balance),h(Ye,n(S).salt),h(me,n(S).blinding),h(K,n(S).idHash),h(Re,n(S).check)}),x(Se,A)});var ce=i(he,2),Te=i(d(ce),2);{var Ge=Se=>{var S=nl(),A=nt(S),N=i(d(A)),F=b(N),V=i(N,2),re=b(V),Ne=i(A,2),ze=i(d(Ne));ue(ze,21,()=>n(r).onChain??[],de,(me,ge)=>{var C=rl(),K=d(C),B=d(K),Re=b(B,!0),ne=i(K),Q=d(ne),ke=b(Q,!0),Je=i(ne),at=d(Je),it=b(at,!0);D(()=>{h(Re,n(ge).idHash),h(ke,n(ge).u),h(it,n(ge).delivery)}),x(me,C)});var Ye=i(Ne,2),We=i(d(Ye)),tt=b(We);D((me,ge)=>{h(F,`${n(r).reservesAda??""} ADA`),h(re,`${me??""}…`),h(tt,`${ge??""}…`)},[()=>n(r).vaultAddress.substring(0,30),()=>n(r).attestTx.substring(0,20)]),x(Se,S)},Ke=Se=>{var S=al();x(Se,S)};G(Te,Se=>{n(r).period?Se(Ge):Se(Ke,-1)})}D(()=>h(et,`${n(r).liabilitiesAda??""} ADA`)),x(O,M)};G(ve,O=>{n(r)&&O(be)})}D(()=>{var O,M;h(g,`): customers and the auditor check from the chain alone, and an + entry the customer cannot open is on-chain evidence against the exchange. Circuit: ${((O=n(r))==null?void 0:O.constraints)??"…"??""} + constraints (4 customers).`),Ae.disabled=!!n(a)||n(_),le.disabled=n(_),we.disabled=!!n(a)||n(_),Ce.disabled=!!n(a)||!((M=n(r))!=null&&M.period),h(te,`The exchange attests honestly but gives ${n(l)??""} an encrypted opening that does not open. The vault can + only check its length; ${n(l)??""}'s check reports it as unopenable.`),I.disabled=!!n(a)||n(_),oe.disabled=!!n(a)||!n(_),pe.disabled=!!n(a)||!n(_)}),X("click",Ae,()=>y("Saving the book","/solvency/book",{customers:n(u)})),He(le,()=>n(o),O=>T(o,O)),X("click",we,()=>y("Proving solvency and locking the reserve","/solvency/attest",{reservesAda:n(o)})),X("click",Ce,()=>y("Auditor opens the total","/solvency/audit")),ft(Z,()=>n(l),O=>T(l,O)),X("click",I,()=>y("Proving solvency and attesting with a garbage delivery","/solvency/attest",{reservesAda:n(o),garbageFor:n(l)})),X("click",oe,()=>y("Submitting another attestation","/solvency/attest-again")),X("click",pe,()=>y("Releasing the reserve","/solvency/release")),x(e,m),nr()}Wr(["click"]);var Tn=$(""),ll=$('

'),dl=$(" "),ul=$(`

Tax authority — every salary ever paid (from the chain's mint history)

Each pay run's notes, including ones already transferred or cashed out, read from the limb ciphertexts. + Every one is proof-enforced: the employer could not have under-reported it.

payslip UTxOemployeesalaryorigincheck

Salary totals:

`),vl=$(" ",1),cl=$(`

Confidential payroll

The employer pays salaries as confidential notes. Unlike the points demo, issuance is + proof-enforced

Pay a salary (employer)

Transfer between employees

Cash out at the employer

Tax authority key rotation

Try to cheat

Under-report a salary to the tax authority

Garbage payslip

Limbs to the retired key

After a rotation, the amounts are encrypted to the tax authority's previous key: refused.

`);function fl(e,t){rr(t,!0);let r=R(null),a=R(""),s=R(null),o=R("carol"),l=R(5e3),u=R(3e3),v=R("carol"),f=R("dave"),p=R(800),y=R("carol"),w=R(1e3);const _=["carol","dave"];async function m(){const A=await Jr("/payroll");A.ok&&T(r,A.data,!0)}async function k(A,N,F){T(a,A,!0),T(s,null),T(s,await kn(N,F),!0),T(a,""),await m()}Kr(()=>{m()});var g=cl(),E=i(d(g),2),J=i(d(E),2),P=i(E,2),fe=d(P),Ae=i(d(fe),2),se=i(d(Ae));ue(se,21,()=>_,de,(A,N)=>{var F=Tn(),V=b(F,!0),re={};D(()=>{h(V,n(N)),re!==(re=n(N))&&(F.__value=re)}),x(A,F)}),ct(se);var z=i(Ae,2),le=i(d(z)),we=i(z,2),ee=i(fe,2),Ee=i(d(ee),2),Ce=i(d(Ee));ue(Ce,21,()=>_,de,(A,N)=>{var F=Tn(),V=b(F,!0),re={};D(()=>{h(V,n(N)),re!==(re=n(N))&&(F.__value=re)}),x(A,F)}),ct(Ce);var je=i(Ee,2),$e=i(d(je));ue($e,21,()=>_,de,(A,N)=>{var F=Tn(),V=b(F,!0),re={};D(()=>{h(V,n(N)),re!==(re=n(N))&&(F.__value=re)}),x(A,F)}),ct($e);var Z=i(je,2),L=i(d(Z)),te=i(Z,2),I=i(ee,2),H=i(d(I),2),oe=i(d(H));ue(oe,21,()=>_,de,(A,N)=>{var F=Tn(),V=b(F,!0),re={};D(()=>{h(V,n(N)),re!==(re=n(N))&&(F.__value=re)}),x(A,F)}),ct(oe);var pe=i(H,2),Oe=i(d(pe)),Me=i(pe,2),Ie=i(I,2),Le=i(d(Ie),2),j=b(Le),ve=i(Le,2),be=i(P,4),O=d(be),M=i(d(O),2),U=i(d(M)),xe=i(M,2),De=b(xe),he=i(xe,2),Fe=i(O,2),qe=i(d(Fe),2),et=b(qe),Ve=i(qe,2),Et=i(Fe,2),ce=i(d(Et),4),Te=i(be,2);{var Ge=A=>{var N=ll(),F=b(N);D(()=>h(F,`${n(a)??""}… (proving and waiting for the block)`)),x(A,N)};G(Te,A=>{n(a)&&A(Ge)})}var Ke=i(Te,2);An(Ke,{get result(){return n(s)}});var Se=i(Ke,2);{var S=A=>{var N=vl(),F=nt(N);{var V=Ne=>{var ze=ul(),Ye=i(d(ze),4),We=i(d(Ye));ue(We,21,()=>n(r).auditor.payslips,de,(ge,C)=>{var K=dl(),B=d(K),Re=d(B),ne=b(Re,!0),Q=i(B),ke=b(Q,!0),Je=i(Q),at=d(Je),it=b(at,!0),st=i(Je),Tt=b(st,!0),vt=i(st),jt=b(vt,!0);D(()=>{h(ne,n(C).utxo),h(ke,n(C).owner),h(it,n(C).amount),h(Tt,n(C).origin),h(jt,n(C).status)}),x(ge,K)});var tt=i(Ye,2),me=i(d(tt));ue(me,17,()=>Object.entries(n(r).auditor.paidTotals),de,(ge,C,K)=>{var B=Hr(()=>Nn(n(C),2));let Re=()=>n(B)[0],ne=()=>n(B)[1];var Q=Er();D(()=>h(Q,`${K>0?" · ":""}${Re()??""} ${ne()??""}`)),x(ge,Q)}),x(Ne,ze)};G(F,Ne=>{n(r).auditor.payslips&&Ne(V)})}var re=i(F,2);Pi(re,{get state(){return n(r)},unit:"credits"}),x(A,N)};G(Se,A=>{n(r)&&A(S)})}D(()=>{var A,N,F,V,re,Ne,ze,Ye,We;h(J,` (ADR-0055 Q9 (b)): every pay run carries a Groth16 proof that each salary note's limbs encrypt + its committed amount to the tax authority's registered key. So the tax authority reads every salary from the chain, + and the employer cannot under-report one. Employees read their payslips from the chain with their viewing keys. + Circuits: pay ${((N=(A=n(r))==null?void 0:A.constraints)==null?void 0:N.issue)??"…"??""} constraints, transfer ${((V=(F=n(r))==null?void 0:F.constraints)==null?void 0:V.transfer)??"…"??""}, + cash-out ${((Ne=(re=n(r))==null?void 0:re.constraints)==null?void 0:Ne.redeem)??"…"??""}.`),we.disabled=!!n(a),te.disabled=!!n(a),Me.disabled=!!n(a),h(j,`Registry generation ${((Ye=(ze=n(r))==null?void 0:ze.registry)==null?void 0:Ye.generation)??"…"??""}.`),ve.disabled=!!n(a),h(De,`The employer pays ${n(l)??""} but encrypts ${n(u)??""} to the tax authority. The issuance proof cannot be + produced — compare the points tab, where trusted issuance lets the issuer do this.`),he.disabled=!!n(a),h(et,`${n(v)??""} sends ${n(p)??""} to ${n(f)??""} with a garbage encrypted opening: ${n(f)??""} sees an unopenable payslip, while + the tax authority still reads the amount.`),Ve.disabled=!!n(a),ce.disabled=!!n(a)||!((We=n(r))!=null&&We.canUseRetiredKey)}),ft(se,()=>n(o),A=>T(o,A)),He(le,()=>n(l),A=>T(l,A)),X("click",we,()=>k("Proving and submitting the pay run","/payroll/pay",{to:n(o),amount:n(l)})),ft(Ce,()=>n(v),A=>T(v,A)),ft($e,()=>n(f),A=>T(f,A)),He(L,()=>n(p),A=>T(p,A)),X("click",te,()=>k("Proving and submitting the transfer","/payroll/transfer",{from:n(v),to:n(f),amount:n(p)})),ft(oe,()=>n(y),A=>T(y,A)),He(Oe,()=>n(w),A=>T(w,A)),X("click",Me,()=>k("Proving and submitting the cash-out","/payroll/cash-out",{from:n(y),amount:n(w)})),X("click",ve,()=>k("Rotating the tax authority keys","/payroll/rotate",{})),He(U,()=>n(u),A=>T(u,A)),X("click",he,()=>k("Proving an under-reported pay run","/payroll/pay",{to:n(o),amount:n(l),reported:n(u)})),X("click",Ve,()=>k("Submitting a garbage payslip","/payroll/transfer",{from:n(v),to:n(f),amount:n(p),cheat:"garbageDelivery"})),X("click",ce,()=>k("Submitting a transfer to the retired key","/payroll/transfer",{from:n(v),to:n(f),amount:n(p),cheat:"retiredKey"})),x(e,g),nr()}Wr(["click"]);var ea=$(""),hl=$('

'),_l=$("bidding closes in ",1),pl=$('
'),bl=$('
The last lot is closed (settled or refunded). Open a new one.
'),ml=$(" "),gl=$('

#bidderhandle A.uciphertext B.u
',1),yl=$('

No open lot.

'),wl=$(" "),xl=$(" ADA"),kl=$(`
#bidderbid

Only the auctioneer can decrypt these; they never appear on-chain. (This demo server holds the auctioneer's key and shows its view to anyone, for the demo.) The auctioneer is trusted for confidentiality, not for the outcome.

`,1),Al=$('

No bids yet.

'),El=$(" "),Tl=$("

Transactions

",1),Sl=$(`

On-chain — what anyone can see

Balances

Auctioneer's private view — decrypted bids

`,1),Cl=$(`

Sealed-bid auction

Each bid is encrypted to the auctioneer (elgamal-jubjub-v1) with a Groth16 proof that it + lies between the reserve and the deposit, so a bidder cannot refuse to reveal

1. Seller lists an item

2. Sealed bid

Cheat: bid above the deposit or below the reserve — no proof exists.

3. Auctioneer settles

Try to cheat

Copy another bid

Auctioneer names another winner

The settlement proof shows the named bid is the earliest highest one; for any other bid no proof exists.

`);function $l(e,t){rr(t,!0);let r=R(null),a=R(""),s=R(null),o=0,l=R(vr(Date.now())),u=R("Painting"),v=R(100),f=R(10),p=R("alice"),y=R(40),w=R("carol"),_=R("alice"),m=R(1);const k=["alice","bob","carol"];async function g(){const S=await Jr("/auction");S.ok&&(T(r,S.data,!0),o=S.data.chainTime-Date.now())}async function E(S,A,N={}){T(a,S,!0),T(s,null),T(s,await kn(A,N),!0),T(a,""),await g()}function J(S){return Math.max(0,Math.round((S-(n(l)+o))/1e3))}Kr(()=>{g();const S=setInterval(()=>{T(l,Date.now(),!0)},1e3),A=setInterval(()=>{var N;!n(a)&&((N=n(r))!=null&&N.lot)&&g()},6e3);return()=>{clearInterval(S),clearInterval(A)}});let P=Hr(()=>{var S;return(S=n(r))!=null&&S.lot?n(l)+ok,de,(S,A)=>{var N=ea(),F=b(N,!0),V={};D(()=>{h(F,n(A)),V!==(V=n(A))&&(N.__value=V)}),x(S,N)}),ct(I);var H=i(te,2),oe=i(d(H)),pe=i(H,2),Oe=i(L,2),Me=i(d(Oe),2),Ie=i(Me,2),Le=i(Ie,2),j=i(z,4),ve=d(j),be=i(d(ve),2),O=i(d(be));ue(O,21,()=>k,de,(S,A)=>{var N=ea(),F=b(N,!0),V={};D(()=>{h(F,n(A)),V!==(V=n(A))&&(N.__value=V)}),x(S,N)}),ct(O);var M=i(be,2),U=i(d(M));ue(U,21,()=>k,de,(S,A)=>{var N=ea(),F=b(N,!0),V={};D(()=>{h(F,n(A)),V!==(V=n(A))&&(N.__value=V)}),x(S,N)}),ct(U);var xe=i(M,2),De=b(xe),he=i(xe,2),Fe=i(ve,2),qe=i(d(Fe),2),et=i(d(qe)),Ve=i(qe,4),Et=b(Ve),ce=i(j,2);{var Te=S=>{var A=hl(),N=b(A);D(()=>h(N,`${n(a)??""}… (proving and waiting for the block)`)),x(S,A)};G(ce,S=>{n(a)&&S(Te)})}var Ge=i(ce,2);An(Ge,{get result(){return n(s)}});var Ke=i(Ge,2);{var Se=S=>{var A=Sl(),N=nt(A);{var F=Q=>{var ke=pl(),Je=d(ke),at=b(Je),it=i(Je),st=i(it);{var Tt=Xe=>{var mt=_l(),Bt=i(nt(mt)),Zr=b(Bt);D(Vn=>h(Zr,`${Vn??""} s`),[()=>J(n(r).lot.biddingEnds)]),x(Xe,mt)};G(st,Xe=>{n(P)==="bidding"&&Xe(Tt)})}var vt=i(st,2);{var jt=Xe=>{var mt=Er();D(Bt=>h(mt,`bidding closed; the auctioneer may settle for ${Bt??""} s`),[()=>J(n(r).lot.settleBy)]),x(Xe,mt)};G(vt,Xe=>{n(P)==="settling"&&Xe(jt)})}var zt=i(vt,2);{var ir=Xe=>{var mt=Er("settlement deadline passed: anyone can refund");x(Xe,mt)};G(zt,Xe=>{n(P)==="expired"&&Xe(ir)})}D(()=>{h(at,`Lot ${n(r).lot.item??""}`),h(it,` · deposit ${n(r).lot.deposit??""} ADA · reserve ${n(r).lot.reserve??""} ADA · `)}),x(Q,ke)},V=Q=>{var ke=bl();x(Q,ke)};G(N,Q=>{n(r).lot?Q(F):n(r).closed&&Q(V,1)})}var re=i(N,2),Ne=d(re),ze=i(d(Ne),2);{var Ye=Q=>{var ke=gl(),Je=nt(ke),at=b(Je),it=i(Je,2),st=i(d(it));ue(st,21,()=>n(r).lot.bids,de,(Tt,vt,jt)=>{var zt=ml(),ir=d(zt);ir.textContent=jt+1;var Xe=i(ir),mt=b(Xe,!0),Bt=i(Xe),Zr=d(Bt),Vn=b(Zr,!0),Mi=i(Bt),Ii=d(Mi),Fi=b(Ii,!0);D(()=>{h(mt,n(vt).bidder),h(Vn,n(vt).handle),h(Fi,n(vt).ciphertext)}),x(Tt,zt)}),D(()=>h(at,`Lot UTxO holding the item, ${n(r).lot.lockedAda??""} ADA (deposits + lot ADA) and the lot token. + Auctioneer key generation ${n(r).lot.generation??""}.`)),x(Q,ke)},We=Q=>{var ke=yl();x(Q,ke)};G(ze,Q=>{n(r).lot?Q(Ye):Q(We,-1)})}var tt=i(ze,4),me=d(tt);ue(me,21,()=>n(r).wallets,de,(Q,ke)=>{var Je=wl(),at=d(Je),it=b(at,!0),st=i(at),Tt=b(st);D(()=>{h(it,n(ke).wallet),h(Tt,`${n(ke).ada??""} ADA`)}),x(Q,Je)});var ge=i(Ne,2),C=i(d(ge),2);{var K=Q=>{var ke=kl(),Je=nt(ke),at=i(d(Je));ue(at,21,()=>n(r).auctioneerView,de,(it,st,Tt)=>{var vt=xl(),jt=d(vt);jt.textContent=Tt+1;var zt=i(jt),ir=b(zt,!0),Xe=i(zt),mt=d(Xe),Bt=b(mt,!0);D(()=>{h(ir,n(st).bidder),h(Bt,n(st).amount)}),x(it,vt)}),x(Q,ke)},B=Q=>{var ke=Al();x(Q,ke)};G(C,Q=>{n(r).auctioneerView&&n(r).auctioneerView.length>0?Q(K):Q(B,-1)})}var Re=i(re,2);{var ne=Q=>{var ke=Tl(),Je=i(nt(ke),2),at=d(Je);ue(at,21,()=>n(r).history,de,(it,st)=>{var Tt=El(),vt=d(Tt),jt=b(vt,!0),zt=i(vt),ir=b(zt,!0),Xe=i(zt),mt=d(Xe),Bt=b(mt);D(Zr=>{h(jt,n(st).summary),h(ir,n(st).cost??""),h(Bt,`${Zr??""}…`)},[()=>n(st).txHash.substring(0,20)]),x(it,Tt)}),x(Q,ke)};G(Re,Q=>{n(r).history.length>0&&Q(ne)})}x(S,A)};G(Ke,S=>{n(r)&&S(Se)})}D(()=>{var S,A,N,F;h(se,` its bid — there is no + reveal phase. Everyone locks the same public deposit. After the bidding window the auctioneer decrypts every bid and + proves, in zero knowledge, who placed the earliest highest bid and its amount, without publishing the losing bids. + If it never settles, anyone can return the deposits and the item. Circuits: bid ${((A=(S=n(r))==null?void 0:S.constraints)==null?void 0:A.bid)??"…"??""} + constraints, settlement of 3 bids ${((F=(N=n(r))==null?void 0:N.constraints)==null?void 0:F.settle3)??"…"??""}.`),Z.disabled=!!n(a)||n(P)==="bidding"||n(P)==="settling",pe.disabled=!!n(a)||n(P)!=="bidding",Me.disabled=!!n(a)||n(P)!=="settling",Ie.disabled=!!n(a)||n(P)!=="expired",Le.disabled=!!n(a)||n(P)==="bidding"||n(P)==="none",h(De,`The copier submits a bid proof made for ${n(_)??""}. The proof is bound to its bidder's key hash, so the + lot refuses it.`),he.disabled=!!n(a)||n(P)!=="bidding",Ve.disabled=!!n(a)||n(P)!=="settling",h(Et,`Settle for bid #${n(m)??""}`)}),He(ee,()=>n(u),S=>T(u,S)),He(Ce,()=>n(v),S=>T(v,S)),He($e,()=>n(f),S=>T(f,S)),X("click",Z,()=>E("Opening the lot","/auction/open",{item:n(u),deposit:n(v),reserve:n(f)})),ft(I,()=>n(p),S=>T(p,S)),He(oe,()=>n(y),S=>T(y,S)),X("click",pe,()=>E("Proving and placing the bid","/auction/bid",{bidder:n(p),amount:n(y)})),X("click",Me,()=>E("Decrypting the bids and proving the settlement","/auction/settle",{})),X("click",Ie,()=>E("Refunding after the deadline","/auction/refund",{})),X("click",Le,()=>E("Closing without bids","/auction/no-bids",{})),ft(O,()=>n(w),S=>T(w,S)),ft(U,()=>n(_),S=>T(_,S)),X("click",he,()=>E("Submitting a copied bid","/auction/bid",{bidder:n(w),amount:n(y),copyFrom:n(_)})),He(et,()=>n(m),S=>T(m,S)),X("click",Ve,()=>E("Proving a wrong settlement","/auction/settle",{claimWinner:n(m)})),x(e,fe),nr()}Wr(["click"]);var Ol=$(" "),Dl=$("

"),Nl=$(`

Starting… compiling circuits, loading or generating development keys and funding demo wallets. + The first start takes a few minutes; later starts reuse the cached keys.

`),Rl=$(" ",1),Pl=$('

'),Ml=$(`

Pedersen Commitments on Cardano

Hiding, binding and additive commitments with zero-knowledge proofs, verified by Plutus V3 on Yaci DevKit

Demo server. This server creates every wallet and holds every key on the users' behalf — spending + keys, note viewing keys, the auditor's keys — and scans the chain for them; real users would each keep their own and + scan in their own wallet (ZeroJ ADR-0055 D9). Note balances are recovered from the chain, not kept in memory. + The On-chain panels show what anyone can read from the ledger.
`);function Il(e,t){rr(t,!0);let r=R("points"),a=R(null);async function s(){var z;const se=await Jr("/status");T(a,se.data,!0),(z=n(a))!=null&&z.ready||setTimeout(s,3e3)}Kr(()=>{s()});var o=Ml(),l=i(d(o),6);{var u=se=>{var z=Nl(),le=i(d(z),2);{var we=ee=>{var Ee=Dl();ue(Ee,21,()=>Object.entries(n(a).demos),de,(Ce,je)=>{var $e=Hr(()=>Nn(n(je),2));let Z=()=>n($e)[0],L=()=>n($e)[1];var te=Ol();let I;var H=b(te);D(()=>{I=or(te,1,"pill svelte-1n46o8q",null,I,{ready:L()==="ready"}),h(H,`${Z()??""}: ${L()??""}`)}),x(Ce,te)}),x(ee,Ee)};G(le,ee=>{var Ee;(Ee=n(a))!=null&&Ee.demos&&ee(we)})}x(se,z)};G(l,se=>{var z;(z=n(a))!=null&&z.ready||se(u)})}var v=i(l,2),f=d(v);let p;var y=i(f,2);let w;var _=i(y,2);let m;var k=i(_,2);let g;var E=i(k,2);let J;var P=i(v,2);{var fe=se=>{var z=Rl(),le=nt(z);{var we=I=>{Fo(I,{})};G(le,I=>{n(r)==="points"&&I(we)})}var ee=i(le,2);{var Ee=I=>{fl(I,{})};G(ee,I=>{n(r)==="payroll"&&I(Ee)})}var Ce=i(ee,2);{var je=I=>{$l(I,{})};G(Ce,I=>{n(r)==="auction"&&I(je)})}var $e=i(Ce,2);{var Z=I=>{Go(I,{})};G($e,I=>{n(r)==="credit"&&I(Z)})}var L=i($e,2);{var te=I=>{ol(I,{})};G(L,I=>{n(r)==="solvency"&&I(te)})}x(se,z)},Ae=se=>{var z=Pl(),le=b(z);D(()=>{var we,ee;return h(le,`This demo is ${((ee=(we=n(a))==null?void 0:we.demos)==null?void 0:ee[n(r)])??"starting"??""}…`)}),x(se,z)};G(P,se=>{var z,le;((le=(z=n(a))==null?void 0:z.demos)==null?void 0:le[n(r)])==="ready"?se(fe):n(a)&&se(Ae,1)})}D(()=>{p=or(f,1,"svelte-1n46o8q",null,p,{active:n(r)==="points"}),w=or(y,1,"svelte-1n46o8q",null,w,{active:n(r)==="payroll"}),m=or(_,1,"svelte-1n46o8q",null,m,{active:n(r)==="auction"}),g=or(k,1,"svelte-1n46o8q",null,g,{active:n(r)==="credit"}),J=or(E,1,"svelte-1n46o8q",null,J,{active:n(r)==="solvency"})}),X("click",f,()=>T(r,"points")),X("click",y,()=>T(r,"payroll")),X("click",_,()=>T(r,"auction")),X("click",k,()=>T(r,"credit")),X("click",E,()=>T(r,"solvency")),x(e,o),nr()}Wr(["click"]);ao(Il,{target:document.getElementById("app")}); diff --git a/pedersen-commitments/src/main/resources/static/assets/index-DTT4oLQg.js b/pedersen-commitments/src/main/resources/static/assets/index-DTT4oLQg.js deleted file mode 100644 index 3296d08..0000000 --- a/pedersen-commitments/src/main/resources/static/assets/index-DTT4oLQg.js +++ /dev/null @@ -1,15 +0,0 @@ -var Ia=Object.defineProperty;var bi=e=>{throw TypeError(e)};var qa=(e,t,r)=>t in e?Ia(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ye=(e,t,r)=>qa(e,typeof t!="symbol"?t+"":t,r),Pn=(e,t,r)=>t.has(e)||bi("Cannot "+r);var o=(e,t,r)=>(Pn(e,t,"read from private field"),r?r.call(e):t.get(e)),q=(e,t,r)=>t.has(e)?bi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),P=(e,t,r,n)=>(Pn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),z=(e,t,r)=>(Pn(e,t,"access private method"),r);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(i){if(i.ep)return;i.ep=!0;const a=r(i);fetch(i.href,a)}})();const Fa="5";var Ri;typeof window<"u"&&((Ri=window.__svelte??(window.__svelte={})).v??(Ri.v=new Set)).add(Fa);const $a=1,La=2,Di=4,za=8,ja=16,Ha=1,Va=2,ue=Symbol("uninitialized"),Ii=!1;var En=Array.isArray,Ba=Array.prototype.indexOf,hn=Array.prototype.includes,An=Array.from,qi=Object.defineProperty,Br=Object.getOwnPropertyDescriptor,Ya=Object.prototype,Ua=Array.prototype,Ga=Object.getPrototypeOf,gi=Object.isExtensible;const Ka=()=>{};function Wa(e){for(var t=0;t{e=n,t=i});return{promise:r,resolve:e,reject:t}}function $i(e,t){if(Array.isArray(e))return e;if(!(Symbol.iterator in e))return Array.from(e);const r=[];for(const n of e)if(r.push(n),r.length===t)break;return r}const Ee=2,Ar=4,Sn=8,Li=1<<24,ht=16,at=32,Ft=64,zn=128,ti=256,pt=512,fe=1024,se=2048,it=4096,Ne=8192,Ie=16384,Nr=32768,jn=1<<25,Sr=65536,_n=1<<17,Ja=1<<18,Pr=1<<19,Xa=1<<20,Et=1<<25,pn=1<<21,pr=1<<22,Yt=1<<23,Yr=Symbol("$state"),zi=Symbol("component"),Za=Symbol("attributes"),Hn=Symbol("class"),Qa=Symbol("style"),$r=Symbol("text"),fn=Symbol("form reset"),nn=new class extends Error{constructor(){super(...arguments);Ye(this,"name","StaleReactionError");Ye(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};function es(){console.warn("https://svelte.dev/e/derived_inert")}function ts(){console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function rs(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}function ji(e){return e===this.v}function ns(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function Hi(e){return!ns(e,this.v)}function is(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function as(e,t,r){throw new Error("https://svelte.dev/e/each_key_duplicate")}function ss(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function ls(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function os(e){throw new Error("https://svelte.dev/e/effect_orphan")}function us(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function fs(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function cs(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function ds(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function vs(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}let hs=!1,qe=null;function Tr(e){qe=e}function Rr(e,t=!1,r){qe={p:qe,i:!1,c:null,e:null,s:e,x:null,r:U,l:null}}function Mr(e){var t=qe,r=t.e;if(r!==null){t.e=null;for(var n of r)fa(n)}return t.i=!0,qe=t.p,Vi(e)}function Vi(e={}){return qi(e,zi,{value:!0}),e}function Bi(){return!0}let Zt=[];function Yi(){var e=Zt;Zt=[],Wa(e)}function Bt(e){if(Zt.length===0&&!Gr){var t=Zt;queueMicrotask(()=>{t===Zt&&Yi()})}Zt.push(e)}function _s(){for(;Zt.length>0;)Yi()}const ps=-7169;function ae(e,t){e.f=e.f&ps|t}function ri(e){(e.f&pt)!==0||e.deps===null?ae(e,fe):ae(e,it)}function Ui(e,t,r){(e.f&se)!==0?t.add(e):(e.f&it)!==0&&r.add(e),ae(e,fe)}let yi=!1;function ms(){yi||(yi=!0,document.addEventListener("reset",e=>{Promise.resolve().then(()=>{var t;if(!e.defaultPrevented)for(const r of e.target.elements)(t=r[fn])==null||t.call(r)})},{capture:!0}))}function an(e){var t=j,r=U;st(null),Ct(null);try{return e()}finally{st(t),Ct(r)}}function Gi(e,t,r,n=r){e.addEventListener(t,()=>an(r));const i=e[fn];i?e[fn]=()=>{i(),n(!0)}:e[fn]=()=>n(!0),ms()}function bs(e,t,r,n){const i=ni;var a=e.filter(_=>!_.settled),l=t.map(i);if(r.length===0&&a.length===0){n(l);return}var f=U,c=gs(),d=a.length===1?a[0].promise:a.length>1?Promise.all(a.map(_=>_.promise)):null;function h(_){if((f.f&Ie)===0){c();try{n([...l,..._])}catch(p){kt(p,f)}mn()}}var g=Ki();if(r.length===0){d.then(()=>h([])).finally(g);return}function b(){Promise.all(r.map(_=>ys(_))).then(h).catch(_=>kt(_,f)).finally(g)}d?d.then(()=>{c(),b(),mn()}):b()}function gs(){var e=U,t=j,r=qe,n=A;return function(a=!0){Ct(e),st(t),Tr(r),a&&(e.f&Ie)===0&&(n==null||n.activate(),n==null||n.apply())}}function mn(e=!0){Ct(null),st(null),Tr(null),e&&(A==null||A.deactivate())}function Ki(){var e=U,t=e.b,r=A,n=!!(t!=null&&t.is_rendered());return t==null||t.update_pending_count(1,r),r.increment(n,e),()=>{t==null||t.update_pending_count(-1,r),r.decrement(n,e)}}function ni(e){var t=Ee|se;return U!==null&&(U.f|=Pr),{ctx:qe,deps:null,effects:null,equals:ji,f:t,fn:e,reactions:null,rv:0,v:ue,wv:0,parent:U,ac:null}}const Lr=Symbol("obsolete");function ys(e,t,r){let n=U;n===null&&is();var i=void 0,a=fr(ue),l=!j,f=new Set;return $s(()=>{var _,p;var c=U,d=Fi();i=d.promise;try{Promise.resolve(e()).then(d.resolve,w=>{w!==nn&&d.reject(w)}).finally(mn)}catch(w){d.reject(w),mn()}var h=A;if(l){if((c.f&Nr)!==0)var g=Ki();if((_=n.b)!=null&&_.is_rendered())(p=h.async_deriveds.get(c))==null||p.reject(Lr);else for(const w of f.values())w.reject(Lr);f.add(d),h.async_deriveds.set(c,d)}const b=(w,m=void 0)=>{g==null||g(),f.delete(d),m!==Lr&&(h.activate(),m?(a.f|=Yt,Cr(a,m)):((a.f&Yt)!==0&&(a.f^=Yt),Cr(a,w)),h.deactivate())};d.promise.then(b,w=>b(null,w||"unknown"))}),ua(()=>{for(const c of f)c.reject(Lr)}),new Promise(c=>{function d(h){function g(){h===i?c(a):d(i)}h.then(g,g)}d(i)})}function ii(e){const t=ni(e);return pa(t),t}function ws(e){const t=ni(e);return t.equals=Hi,t}function xs(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r{r.ac.abort(nn),r.ac=null}),r.fn!==null&&(r.teardown=Ka),Xr(r,0),fi(r))}function Ji(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&t.fn!==null&&Or(t)}let Rn=null,cr=null,A=null,Ur=null,be=null,Vn=null,Gr=!1,Mn=!1,Kr=null,cn=null;var wi=0;let Es=1;var br,Ht,rr,gr,yr,wr,Mt,xr,Ue,Zr,Dt,dt,yt,kr,nr,Y,Bn,Yn,zr,Un,Xi,Zi,_r,As,jr;const wn=class wn{constructor(){q(this,Y);Ye(this,"id",Es++);q(this,br,!1);Ye(this,"linked",!0);q(this,Ht,null);q(this,rr,null);Ye(this,"async_deriveds",new Map);Ye(this,"current",new Map);Ye(this,"previous",new Map);q(this,gr,new Set);q(this,yr,new Set);q(this,wr,0);q(this,Mt,new Map);q(this,xr,null);q(this,Ue,[]);q(this,Zr,[]);q(this,Dt,new Set);q(this,dt,new Set);q(this,yt,new Map);q(this,kr,new Set);Ye(this,"is_fork",!1);q(this,nr,!1);cr===null?Rn=cr=this:(P(cr,rr,this),P(this,Ht,cr)),cr=this}skip_effect(t){o(this,yt).has(t)||o(this,yt).set(t,{d:[],m:[]}),o(this,kr).delete(t)}unskip_effect(t,r=n=>this.schedule(n)){var n=o(this,yt).get(t);if(n){o(this,yt).delete(t);for(var i of n.d)ae(i,se),r(i);for(i of n.m)ae(i,it),r(i)}o(this,kr).add(t)}capture(t,r,n=!1){t.v!==ue&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&Yt)===0&&(this.current.set(t,[r,n]),be==null||be.set(t,r)),this.is_fork||(t.v=r)}activate(){A=this}deactivate(){A=null,be=null}flush(){try{Mn=!0,A=this,z(this,Y,zr).call(this)}finally{wi=0,Vn=null,Kr=null,cn=null,Mn=!1,A=null,be=null,At.clear()}}discard(){var t;for(const r of o(this,yr))r(this);o(this,yr).clear();for(const r of this.async_deriveds.values())r.reject(Lr);z(this,Y,jr).call(this),(t=o(this,xr))==null||t.resolve()}register_created_effect(t){o(this,Zr).push(t)}increment(t,r){if(P(this,wr,o(this,wr)+1),t){let n=o(this,Mt).get(r)??0;o(this,Mt).set(r,n+1)}}decrement(t,r){if(P(this,wr,o(this,wr)-1),t){let n=o(this,Mt).get(r)??0;n===1?o(this,Mt).delete(r):o(this,Mt).set(r,n-1)}o(this,nr)||(P(this,nr,!0),Bt(()=>{P(this,nr,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(const n of t)o(this,Dt).add(n);for(const n of r)o(this,dt).add(n);t.clear(),r.clear()}oncommit(t){o(this,gr).add(t)}ondiscard(t){o(this,yr).add(t)}settled(){return(o(this,xr)??P(this,xr,Fi())).promise}static ensure(){if(A===null){const t=A=new wn;!Mn&&!Gr&&Bt(()=>{o(t,br)||t.flush()})}return A}apply(){{be=null;return}}schedule(t){var r;if(Vn=t,(r=t.b)!=null&&r.is_pending&&(t.f&(Ar|Sn|Li))!==0&&(t.f&Nr)===0){t.b.defer_effect(t);return}o(this,Ue).push(t)}};br=new WeakMap,Ht=new WeakMap,rr=new WeakMap,gr=new WeakMap,yr=new WeakMap,wr=new WeakMap,Mt=new WeakMap,xr=new WeakMap,Ue=new WeakMap,Zr=new WeakMap,Dt=new WeakMap,dt=new WeakMap,yt=new WeakMap,kr=new WeakMap,nr=new WeakMap,Y=new WeakSet,Bn=function(){if(this.is_fork)return!0;for(const n of o(this,Mt).keys()){for(var t=n,r=!1;t.parent!==null;){if(o(this,yt).has(t)){r=!0;break}t=t.parent}if(!r)return!0}return!1},Yn=function(){var t=[];for(const a of o(this,Ue))if(!((a.f&Ie)!==0||(a.f&(se|it))===0)){for(var r=a,n=!1;r.parent!==null;){r=r.parent;var i=r.f;if((i&(Ft|at))!==0){if((i&fe)===0){n=!0;break}r.f^=fe}}n||t.push(r)}return P(this,Ue,[]),t},zr=function(){var f,c,d,h;P(this,br,!0);for(const g of o(this,Dt))o(this,dt).delete(g),ae(g,se),this.schedule(g);for(const g of o(this,dt))ae(g,it),this.schedule(g);this.apply();for(var t=Kr=[],r=[],n=cn=[];o(this,Ue).length>0;){wi++>1e3&&(z(this,Y,jr).call(this),Ts());for(const g of z(this,Y,Yn).call(this))try{z(this,Y,Un).call(this,g,t,r)}catch(b){throw ta(g),z(this,Y,Bn).call(this)||this.discard(),b}}if(A=null,n.length>0){var i=wn.ensure();for(const g of n)i.schedule(g)}if(Kr=null,cn=null,z(this,Y,Bn).call(this)){z(this,Y,_r).call(this,r),z(this,Y,_r).call(this,t);for(const[g,b]of o(this,yt))ea(g,b);n.length>0&&z(f=A,Y,zr).call(f);return}const a=z(this,Y,Xi).call(this);if(a){z(this,Y,_r).call(this,r),z(this,Y,_r).call(this,t),z(c=a,Y,Zi).call(c,this);return}o(this,Dt).clear(),o(this,dt).clear();for(const g of o(this,gr))g(this);o(this,gr).clear(),Ur=this,xi(r),xi(t),Ur=null,(d=o(this,xr))==null||d.resolve();var l=A;if(o(this,wr)===0&&(o(this,Ue).length===0||l!==null)&&z(this,Y,jr).call(this),o(this,Ue).length>0)if(l!==null){for(const g of o(this,Ue))o(l,Ue).push(g);P(this,Ue,[])}else l=this;l!==null&&(At.clear(),z(h=l,Y,zr).call(h))},Un=function(t,r,n){t.f^=fe;for(var i=t.first;i!==null;){var a=i.f,l=(a&(at|Ft))!==0,f=l&&(a&fe)!==0,c=f||(a&Ne)!==0||o(this,yt).has(i);if(!c&&i.fn!==null){l?i.f^=fe:(a&Ar)!==0?r.push(i):ln(i)&&((a&ht)!==0&&o(this,dt).add(i),Or(i));var d=i.first;if(d!==null){i=d;continue}}for(;i!==null;){var h=i.next;if(h!==null){i=h;break}i=i.parent}}},Xi=function(){for(var t=o(this,Ht);t!==null;){if(!t.is_fork){for(const[r,[,n]]of this.current)if(t.current.has(r)&&!n)return t}t=o(t,Ht)}return null},Zi=function(t){var n;for(const[i,a]of t.current)!this.previous.has(i)&&t.previous.has(i)&&this.previous.set(i,t.previous.get(i)),this.current.set(i,a);for(const[i,a]of t.async_deriveds){const l=this.async_deriveds.get(i);l&&a.promise.then(l.resolve).catch(l.reject)}t.async_deriveds.clear(),this.transfer_effects(o(t,Dt),o(t,dt));const r=i=>{var a=i.reactions;if(a!==null&&!((i.f&Ee)!==0&&(i.f&(se|it))===0))for(const c of a){var l=c.f;if((l&Ee)!==0)r(c);else{var f=c;l&(pr|ht)&&!this.async_deriveds.has(f)&&(o(this,dt).delete(f),ae(f,se),this.schedule(f))}}};for(const i of this.current.keys())r(i);this.oncommit(()=>t.discard()),z(n=t,Y,jr).call(n),A=this,z(this,Y,zr).call(this)},_r=function(t){for(var r=0;r!_.current.get(p)[1]);if(!(!o(_,br)||i.length===0)){var a=i.filter(p=>!this.current.has(p));if(a.length===0)t&&_.discard();else if(r.length>0){if(t)for(const p of o(this,kr))_.unskip_effect(p,w=>{var m;(w.f&(ht|pr))!==0?_.schedule(w):z(m=_,Y,_r).call(m,[w])});_.activate();var l=new Set,f=new Map;for(var c of r)Qi(c,a,l,f);f=new Map;var d=[..._.current].filter(([p,w])=>{const m=this.current.get(p);return m?m[0]!==w[0]||m[1]!==w[1]:!0}).map(([p])=>p);if(d.length>0)for(const p of o(this,Zr))(p.f&(Ie|Ne|_n))===0&&si(p,d,f)&&((p.f&(pr|ht))!==0?(ae(p,se),_.schedule(p)):o(_,Dt).add(p));if(o(_,Ue).length>0&&!o(_,nr)){_.apply();for(var h of z(g=_,Y,Yn).call(g))z(b=_,Y,Un).call(b,h,[],[])}_.deactivate()}}}},jr=function(){if(this.linked){var t=o(this,Ht),r=o(this,rr);t===null?Rn=r:P(t,rr,r),r===null?cr=t:P(r,Ht,t),this.linked=!1}};let ur=wn;function Ss(e){var t=Gr;Gr=!0;try{for(var r;;){if(_s(),A===null)return r;A.flush()}}finally{Gr=t}}function Ts(){try{us()}catch(e){kt(e,Vn)}}let ct=null;function xi(e){var t=e.length;if(t!==0){for(var r=0;r0)){At.clear();for(const i of ct){if((i.f&(Ie|Ne))!==0)continue;const a=[i];let l=i.parent;for(;l!==null;)ct.has(l)&&(ct.delete(l),a.push(l)),l=l.parent;for(let f=a.length-1;f>=0;f--){const c=a[f];(c.f&(Ie|Ne))===0&&Or(c)}}ct.clear()}}ct=null}}function Qi(e,t,r,n){if(!r.has(e)&&(r.add(e),e.reactions!==null))for(const i of e.reactions){const a=i.f;(a&Ee)!==0?Qi(i,t,r,n):(a&(pr|ht))!==0&&(a&se)===0&&si(i,t,n)&&(ae(i,se),li(i))}}function si(e,t,r){const n=r.get(e);if(n!==void 0)return n;if(e.deps!==null)for(const i of e.deps){if(hn.call(t,i))return!0;if((i.f&Ee)!==0&&si(i,t,r))return r.set(i,!0),!0}return r.set(e,!1),!1}function li(e){A.schedule(e)}function ea(e,t){if(!((e.f&at)!==0&&(e.f&fe)!==0)){(e.f&se)!==0?t.d.push(e):(e.f&it)!==0&&t.m.push(e),ae(e,fe);for(var r=e.first;r!==null;)ea(r,t),r=r.next}}function ta(e){ae(e,fe);for(var t=e.first;t!==null;)ta(t),t=t.next}let bn=new Set;const At=new Map;let ra=!1;function fr(e,t){var r={f:0,v:e,reactions:null,equals:ji,rv:0,wv:0};return r}function H(e,t){const r=fr(e);return pa(r),r}function Cs(e,t=!1,r=!0){const n=fr(e);return t||(n.equals=Hi),n}function R(e,t,r=!1){j!==null&&(!_t||(j.f&_n)!==0)&&Bi()&&(j.f&(Ee|ht|pr|_n))!==0&&(Tt===null||!Tt.has(e))&&ds();let n=r?Qt(t):t;return Cr(e,n,cn)}var Xt=null,Gn=0;function Cr(e,t,r=null){if(!e.equals(t)){Ut?At.set(e,t):At.has(e)||At.set(e,e.v);var n=ur.ensure();if(n.capture(e,t),(e.f&Ee)!==0){const i=e;(e.f&se)!==0&&ai(i),be===null&&ri(i)}e.wv=ba(),Xt=null,Gn=0,na(e,se,r),Xt=null,U!==null&&(U.f&fe)!==0&&(U.f&(at|Ft))===0&&(Qe===null?js([e]):Qe.push(e)),!n.is_fork&&bn.size>0&&!ra&&Os()}return t}function Os(){ra=!1;for(const e of bn){(e.f&fe)!==0&&ae(e,it);let t;try{t=ln(e)}catch{t=!0}t&&Or(e)}bn.clear()}function Wr(e){R(e,e.v+1)}function na(e,t,r){var n=e.reactions;if(n!==null){var i=n.length;if(Gn+=i,Gn>1e5&&Xt===null&&(Xt=new Set),Xt!==null){if(Xt.has(e))return;Xt.add(e)}for(var a=0;a{if(or===a)return f();var c=j,d=or;st(null),Si(a);var h=f();return st(c),Si(d),h};return n&&r.set("length",H(e.length)),new Proxy(e,{defineProperty(f,c,d){(!("value"in d)||d.configurable===!1||d.enumerable===!1||d.writable===!1)&&fs();var h=r.get(c);return h===void 0?l(()=>{var g=H(d.value);return r.set(c,g),g}):R(h,d.value,!0),!0},deleteProperty(f,c){var d=r.get(c);if(d===void 0){if(c in f){const h=l(()=>H(ue));r.set(c,h),Wr(i)}}else R(d,ue),Wr(i);return!0},get(f,c,d){var _;if(c===Yr)return e;var h=r.get(c),g=c in f;if(h===void 0&&(!g||(_=Br(f,c))!=null&&_.writable)&&(h=l(()=>{var p=Qt(g?f[c]:ue),w=H(p);return w}),r.set(c,h)),h!==void 0){var b=s(h);return b===ue?void 0:b}return Reflect.get(f,c,d)},getOwnPropertyDescriptor(f,c){var b;(b=this.has)==null||b.call(this,f,c);var d=Reflect.getOwnPropertyDescriptor(f,c),h=r.get(c);if(h!==void 0){var g=s(h);if(g===ue)return;if(d&&"value"in d)d.value=g;else return{enumerable:!0,configurable:!0,value:g,writable:!0}}return d},has(f,c){var b;if(c===Yr)return!0;var d=r.get(c),h=d!==void 0&&d.v!==ue||Reflect.has(f,c);if(d!==void 0||U!==null&&(!h||(b=Br(f,c))!=null&&b.writable)){d===void 0&&(d=l(()=>{var _=h?Qt(f[c]):ue,p=H(_);return p}),r.set(c,d));var g=s(d);if(g===ue)return!1}return h},set(f,c,d,h){var S;var g=r.get(c),b=c in f;if(n&&c==="length")for(var _=d;_H(ue)),r.set(_+"",p))}if(g===void 0)(!b||(S=Br(f,c))!=null&&S.writable)&&(g=l(()=>H(void 0)),R(g,Qt(d)),r.set(c,g));else{b=g.v!==ue;var w=l(()=>Qt(d));R(g,w)}var m=Reflect.getOwnPropertyDescriptor(f,c);if(m!=null&&m.set&&m.set.call(h,d),!b){if(n&&typeof c=="string"){var k=r.get("length"),D=Number(c);Number.isInteger(D)&&D>=k.v&&R(k,D+1)}Wr(i)}return!0},ownKeys(f){s(i);var c=Reflect.ownKeys(f).filter(g=>{var b=r.get(g);return b===void 0||b.v!==ue});for(var[d,h]of r)h.v!==ue&&!(d in f)&&c.push(d);return c},setPrototypeOf(){cs()}})}function ki(e){try{if(e!==null&&typeof e=="object"&&Yr in e)return e[Yr]}catch{}return e}function ia(e,t){return Object.is(ki(e),ki(t))}var Ei,aa,sa,la;function Ns(){if(Ei===void 0){Ei=window,aa=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;sa=Br(t,"firstChild").get,la=Br(t,"nextSibling").get,gi(e)&&(e[Hn]=void 0,e[Za]=null,e[Qa]=void 0,e.__e=void 0),gi(r)&&(r[$r]=void 0)}}function qt(e=""){return document.createTextNode(e)}function Jr(e){return sa.call(e)}function sn(e){return la.call(e)}function v(e,t){return Jr(e)}function St(e,t=!1){{var r=Jr(e);return r instanceof Comment&&r.data===""?sn(r):r}}function x(e,t=!1){return Jr(e)}function u(e,t=1,r=!1){let n=e;for(;t--;)n=sn(n);return n}function Ps(e){e.textContent=""}function oa(){return!1}function Rs(e,t,r){return r?document.createElement(e,{is:r}):document.createElement(e)}function Ms(e){var t=U;if(t===null)return j.f|=Yt,e;if((t.f&Nr)===0&&(t.f&Ar)===0)throw e;kt(e,t)}function kt(e,t){if(!(t!==null&&(t.f&Ie)!==0)){for(;t!==null;){if((t.f&zn)!==0&&(t.f&(Ie|jn))===0){if((t.f&Nr)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}function Ds(e){U===null&&(j===null&&os(),ls()),Ut&&ss()}function Is(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function $t(e,t){var r=U;r!==null&&(r.f&Ne)!==0&&(e|=Ne);var n={ctx:qe,deps:null,nodes:null,f:e|se|pt,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};A==null||A.register_created_effect(n);var i=n;if((e&Ar)!==0)Kr!==null?Kr.push(n):ur.ensure().schedule(n);else if(t!==null){try{Or(n)}catch(l){throw Fe(n),l}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&Pr)===0&&(i=i.first,(e&ht)!==0&&(e&Sr)!==0&&i!==null&&(i.f|=Sr))}if(i!==null&&(i.parent=r,r!==null&&Is(i,r),j!==null&&(j.f&Ee)!==0&&(e&Ft)===0)){var a=j;(a.effects??(a.effects=[])).push(i)}return n}function oi(){return j!==null&&!_t}function ua(e){const t=$t(Sn,null);return ae(t,fe),t.teardown=e,t}function Tn(e){Ds();var t=U.f,r=!j&&(t&at)!==0&&qe!==null&&!qe.i;if(r){var n=qe;(n.e??(n.e=[])).push(e)}else return fa(e)}function fa(e){return $t(Ar|Xa,e)}function qs(e){ur.ensure();const t=$t(Ft|Pr,e);return(r={})=>new Promise(n=>{r.outro?lr(t,()=>{Fe(t),n(void 0)}):(Fe(t),n(void 0))})}function Fs(e){return $t(Ar,e)}function $s(e){return $t(pr|Pr,e)}function ca(e,t=0){return $t(Sn|t,e)}function $(e,t=[],r=[],n=[]){bs(n,t,r,i=>{$t(Sn,()=>{e(...i.map(s))})})}function ui(e,t=0){var r=$t(ht|t,e);return r}function rt(e){return $t(at|Pr,e)}function da(e){var t=e.teardown;if(t!==null){const r=Ut,n=j;Ai(!0),st(null);try{t.call(null)}catch(i){kt(i,e.parent)}finally{Ai(r),st(n)}}}function fi(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){const i=r.ac;i!==null&&an(()=>{i.abort(nn)});var n=r.next;(r.f&Ft)!==0?r.parent=null:Fe(r,t),r=n}}function Ls(e){for(var t=e.first;t!==null;){var r=t.next;(t.f&at)===0&&Fe(t),t=r}}function Fe(e,t=!0){var r=!1;(t||(e.f&Ja)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(zs(e.nodes.start,e.nodes.end),r=!0),e.f|=jn,fi(e,t&&!r),Xr(e,0);var n=e.nodes&&e.nodes.t;if(n!==null)for(const a of n)a.stop();da(e),e.f^=jn,e.f|=Ie;var i=e.parent;i!==null&&i.first!==null&&va(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function zs(e,t){for(;e!==null;){var r=e===t?null:sn(e);e.remove(),e=r}}function va(e){var t=e.parent,r=e.prev,n=e.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function lr(e,t,r=!0){var n=[];e.f|=ti,ha(e,n,!0);var i=()=>{r&&Fe(e),t&&t()},a=n.length;if(a>0){var l=()=>--a||i();for(var f of n)f.out(l)}else i()}function ha(e,t,r){if((e.f&Ne)===0){e.f^=Ne;var n=e.nodes&&e.nodes.t;if(n!==null)for(const f of n)(f.is_global||r)&&t.push(f);for(var i=e.first;i!==null;){var a=i.next;if((i.f&Ft)===0){var l=(i.f&Sr)!==0||(i.f&at)!==0&&(e.f&ht)!==0;ha(i,t,l?r:!1)}i=a}}}function gn(e){e.f&=~ti,_a(e,!0)}function _a(e,t){if((e.f&ti)===0&&(e.f&Ne)!==0){e.f^=Ne,(e.f&fe)===0&&(ae(e,se),ur.ensure().schedule(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&Sr)!==0||(r.f&at)!==0;_a(r,i?t:!1),r=n}var a=e.nodes&&e.nodes.t;if(a!==null)for(const l of a)(l.is_global||t)&&l.in()}}function ci(e,t){if(e.nodes)for(var r=e.nodes.start,n=e.nodes.end;r!==null;){var i=r===n?null:sn(r);t.append(r),r=i}}let dn=!1,Ut=!1;function Ai(e){Ut=e}let j=null,_t=!1;function st(e){j=e}let U=null;function Ct(e){U=e}let Tt=null;function pa(e){j!==null&&((j.f&pn)!==0||(j.f&Ee)!==0)&&(Tt??(Tt=new Set)).add(e)}let De=null,Je=0,Qe=null;function js(e){Qe=e}let ma=1,er=0,or=er;function Si(e){or=e}function ba(){return++ma}function ln(e){var t=e.f;if((t&se)!==0)return!0;if((t&it)!==0){for(var r=e.deps,n=r.length,i=0;ie.wv)return!0}(t&pt)!==0&&be===null&&ae(e,fe)}return!1}function ga(e,t,r=!0){var n=e.reactions;if(n!==null&&!(Tt!==null&&Tt.has(e)))for(var i=0;i{e.ac.abort(nn)}),e.ac=null);try{e.f|=pn;var h=e.fn,g=h();e.f|=Nr;var b=Ti(e);if(Bi()&&Qe!==null&&!_t&&b!==null&&(e.f&(Ee|it|se))===0)for(var _=0;_0)for(t.length=Je+De.length,n=0;n{a.ac.abort(nn),a.ac=null,ae(a,se)}),ks(a),Xr(a,0)}}function Xr(e,t){var r=e.deps;if(r!==null)for(var n=t;n{In=!1,Dn=null}));var l=0,f=Dn===e&&e[tr];if(f){var c=i.indexOf(f);if(c!==-1&&(t===document||t===window)){e[tr]=t;return}var d=i.indexOf(t);if(d===-1)return;c<=d&&(l=c)}if(a=i[l]||e.target,a!==t){qi(e,"currentTarget",{configurable:!0,get(){return a||r}});var h=j,g=U;st(null),Ct(null);try{for(var b,_=[];a!==null&&a!==t;){try{var p=(m=a[tr])==null?void 0:m[n];p!=null&&(!a.disabled||e.target===a)&&p.call(a,e)}catch(k){b?_.push(k):b=k}if(e.cancelBubble)break;l++,a=l{throw k});throw b}}finally{e[tr]=t,delete e.currentTarget,st(h),Ct(g)}}}var Mi;const qn=((Mi=globalThis==null?void 0:globalThis.window)==null?void 0:Mi.trustedTypes)&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function Bs(e){return(qn==null?void 0:qn.createHTML(e))??e}function Ys(e){var t=Rs("template");return t.innerHTML=Bs(e.replaceAll("","")),t.content}function yn(e,t){var r=U;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function N(e,t){var r=(t&Ha)!==0,n=(t&Va)!==0,i,a=!e.startsWith("");return()=>{i===void 0&&(i=Ys(a?e:""+e),r||(i=Jr(i)));var l=n||aa?document.importNode(i,!0):i.cloneNode(!0);if(r){var f=Jr(l),c=l.lastChild;yn(f,c)}else yn(l,l);return l}}function Fn(e=""){{var t=qt(e+"");return yn(t,t),t}}function Oi(){var e=document.createDocumentFragment(),t=document.createComment(""),r=qt();return e.append(t,r),yn(t,r),e}function E(e,t){e!==null&&e.before(t)}const Us=["touchstart","touchmove"];function Gs(e){return Us.includes(e)}function Ks(e){let t=0,r=fr(0),n;return()=>{oi()&&(s(r),ca(()=>(t===0&&(n=ka(()=>e(()=>Wr(r)))),t+=1,()=>{Bt(()=>{t-=1,t===0&&(n==null||n(),n=void 0,Wr(r))})})))}}var Ws=Sr|Pr;function Js(e,t,r,n){new Xs(e,t,r,n)}var et,ei,tt,ir,Ce,Ge,Oe,Ke,wt,ar,Vt,Er,Qr,en,It,xn,Z,Zs,Qs,Wn,el,Jn,Hr,vn,Xn,Zn;class Xs{constructor(t,r,n,i){q(this,Z);Ye(this,"parent");Ye(this,"is_pending",!1);Ye(this,"transform_error");q(this,et);q(this,ei,null);q(this,tt);q(this,ir);q(this,Ce);q(this,Ge,null);q(this,Oe,null);q(this,Ke,null);q(this,wt,null);q(this,ar,0);q(this,Vt,0);q(this,Er,!1);q(this,Qr,new Set);q(this,en,new Set);q(this,It,null);q(this,xn,Ks(()=>(P(this,It,fr(o(this,ar))),()=>{P(this,It,null)})));var a;P(this,et,t),P(this,tt,r),P(this,ir,l=>{var f=U;f.b=this,f.f|=zn,n(l)}),this.parent=U.b,this.transform_error=i??((a=this.parent)==null?void 0:a.transform_error)??(l=>l),P(this,Ce,ui(()=>{z(this,Z,Jn).call(this)},Ws))}defer_effect(t){Ui(t,o(this,Qr),o(this,en))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!o(this,tt).pending}update_pending_count(t,r){z(this,Z,Xn).call(this,t,r),P(this,ar,o(this,ar)+t),!(!o(this,It)||o(this,Er))&&(P(this,Er,!0),Bt(()=>{P(this,Er,!1),o(this,It)&&Cr(o(this,It),o(this,ar))}))}get_effect_pending(){return o(this,xn).call(this),s(o(this,It))}error(t){if(!o(this,tt).onerror&&!o(this,tt).failed)throw t;A!=null&&A.is_fork?(o(this,Ge)&&A.skip_effect(o(this,Ge)),o(this,Oe)&&A.skip_effect(o(this,Oe)),o(this,Ke)&&A.skip_effect(o(this,Ke)),A.oncommit(()=>{z(this,Z,Zn).call(this,t)})):z(this,Z,Zn).call(this,t)}}et=new WeakMap,ei=new WeakMap,tt=new WeakMap,ir=new WeakMap,Ce=new WeakMap,Ge=new WeakMap,Oe=new WeakMap,Ke=new WeakMap,wt=new WeakMap,ar=new WeakMap,Vt=new WeakMap,Er=new WeakMap,Qr=new WeakMap,en=new WeakMap,It=new WeakMap,xn=new WeakMap,Z=new WeakSet,Zs=function(){try{P(this,Ge,rt(()=>o(this,ir).call(this,o(this,et))))}catch(t){this.error(t)}},Qs=function(t){const r=o(this,tt).failed,{reset:n,invoke_onerror:i}=z(this,Z,Wn).call(this,t);Bt(i),r&&P(this,Ke,rt(()=>{r(o(this,et),()=>t,()=>n)}))},Wn=function(t){var r=!1,n=!1;const i=()=>{if(r){rs();return}r=!0,n&&vs(),o(this,Ke)!==null&&lr(o(this,Ke),()=>{P(this,Ke,null)}),z(this,Z,vn).call(this,()=>{z(this,Z,Jn).call(this)})};return{reset:i,invoke_onerror:()=>{var l,f;try{n=!0,(f=(l=o(this,tt)).onerror)==null||f.call(l,t,i),n=!1}catch(c){kt(c,o(this,Ce)&&o(this,Ce).parent)}}}},el=function(){const t=o(this,tt).pending;t&&(this.is_pending=!0,P(this,Oe,rt(()=>t(o(this,et)))),Bt(()=>{var r=P(this,wt,document.createDocumentFragment()),n=qt(),i=!1;if(r.append(n),P(this,Ge,z(this,Z,vn).call(this,()=>{try{return rt(()=>o(this,ir).call(this,n))}catch(a){try{this.error(a),i=!0}catch(l){kt(l,o(this,Ce).parent)}return null}})),o(this,Ge)===null){P(this,wt,null),i&&z(this,Z,Hr).call(this,A);return}o(this,Vt)===0&&(o(this,et).before(r),P(this,wt,null),lr(o(this,Oe),()=>{P(this,Oe,null)}),z(this,Z,Hr).call(this,A))}))},Jn=function(){try{if(this.is_pending=this.has_pending_snippet(),P(this,Vt,0),P(this,ar,0),P(this,Ge,rt(()=>{o(this,ir).call(this,o(this,et))})),o(this,Vt)>0){var t=P(this,wt,document.createDocumentFragment());ci(o(this,Ge),t);const r=o(this,tt).pending;P(this,Oe,rt(()=>r(o(this,et))))}else z(this,Z,Hr).call(this,A)}catch(r){this.error(r)}},Hr=function(t){this.is_pending=!1,t.transfer_effects(o(this,Qr),o(this,en))},vn=function(t){var r=U,n=j,i=qe;Ct(o(this,Ce)),st(o(this,Ce)),Tr(o(this,Ce).ctx);try{return ur.ensure(),t()}finally{Ct(r),st(n),Tr(i)}},Xn=function(t,r){var n;if(!this.has_pending_snippet()){this.parent&&z(n=this.parent,Z,Xn).call(n,t,r);return}P(this,Vt,o(this,Vt)+t),o(this,Vt)===0&&(z(this,Z,Hr).call(this,r),o(this,Oe)&&lr(o(this,Oe),()=>{P(this,Oe,null)}),o(this,wt)&&(o(this,et).before(o(this,wt)),P(this,wt,null)))},Zn=function(t){o(this,Ge)&&(Fe(o(this,Ge)),P(this,Ge,null)),o(this,Oe)&&(Fe(o(this,Oe)),P(this,Oe,null)),o(this,Ke)&&(Fe(o(this,Ke)),P(this,Ke,null));let r=o(this,tt).failed;const n=i=>{const{reset:a,invoke_onerror:l}=z(this,Z,Wn).call(this,i);l(),r&&P(this,Ke,z(this,Z,vn).call(this,()=>{try{return rt(()=>{var f=U;f.b=this,f.f|=zn,r(o(this,et),()=>i,()=>a)})}catch(f){return kt(f,o(this,Ce).parent),null}}))};Bt(()=>{var i;try{i=this.transform_error(t)}catch(a){kt(a,o(this,Ce)&&o(this,Ce).parent);return}i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(n,a=>kt(a,o(this,Ce)&&o(this,Ce).parent)):n(i)})};function y(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[$r]??(e[$r]=e.nodeValue))&&(e[$r]=r,e.nodeValue=`${r}`)}function tl(e,t){return rl(e,t)}const on=new Map;function rl(e,{target:t,anchor:r,props:n={},events:i,context:a,intro:l=!0,transformError:f}){Ns();var c=void 0,d=qs(()=>{var h=r??t.appendChild(qt());Js(h,{pending:()=>{}},_=>{Rr({});var p=qe;a&&(p.c=a),i&&(n.$$events=i),c=e(_,n)||Vi(),Mr()},f);var g=new Set,b=_=>{for(var p=0;p<_.length;p++){var w=_[p];if(!g.has(w)){g.add(w);var m=Gs(w);for(const S of[t,document]){var k=on.get(S);k===void 0&&(k=new Map,on.set(S,k));var D=k.get(w);D===void 0?(S.addEventListener(w,Ci,{passive:m}),k.set(w,1)):k.set(w,D+1)}}}};return b(An(Ea)),Kn.add(b),()=>{var m;for(var _ of g)for(const k of[t,document]){var p=on.get(k),w=p.get(_);--w==0?(k.removeEventListener(_,Ci),p.delete(_),p.size===0&&on.delete(k)):p.set(_,w)}Kn.delete(b),h!==r&&((m=h.parentNode)==null||m.removeChild(h))}});return nl.set(c,d),c}let nl=new WeakMap;var vt,xt,We,sr,tn,rn,kn;class il{constructor(t,r=!0){Ye(this,"anchor");q(this,vt,new Map);q(this,xt,new Map);q(this,We,new Map);q(this,sr,new Set);q(this,tn,!0);q(this,rn,t=>{if(o(this,vt).has(t)){var r=o(this,vt).get(t),n=o(this,xt).get(r);if(n)gn(n),o(this,sr).delete(r);else{var i=o(this,We).get(r);i&&(gn(i.effect),o(this,xt).set(r,i.effect),o(this,We).delete(r),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),n=i.effect)}for(const[a,l]of o(this,vt)){if(o(this,vt).delete(a),a===t)break;const f=o(this,We).get(l);f&&(Fe(f.effect),o(this,We).delete(l))}for(const[a,l]of o(this,xt)){if(a===r||o(this,sr).has(a))continue;const f=()=>{if(Array.from(o(this,vt).values()).includes(a)){var d=document.createDocumentFragment();ci(l,d),d.append(qt()),o(this,We).set(a,{effect:l,fragment:d})}else Fe(l);o(this,sr).delete(a),o(this,xt).delete(a)};o(this,tn)||!n?(o(this,sr).add(a),lr(l,f,!1)):f()}}});q(this,kn,t=>{o(this,vt).delete(t);const r=Array.from(o(this,vt).values());for(const[n,i]of o(this,We))r.includes(n)||(Fe(i.effect),o(this,We).delete(n))});this.anchor=t,P(this,tn,r)}ensure(t,r){var n=A,i=oa();if(r&&!o(this,xt).has(t)&&!o(this,We).has(t))if(i){var a=document.createDocumentFragment(),l=qt();a.append(l),o(this,We).set(t,{effect:rt(()=>r(l)),fragment:a})}else o(this,xt).set(t,rt(()=>r(this.anchor)));if(o(this,vt).set(n,t),i){for(const[f,c]of o(this,xt))f===t?n.unskip_effect(c):n.skip_effect(c);for(const[f,c]of o(this,We))f===t?n.unskip_effect(c.effect):n.skip_effect(c.effect);n.oncommit(o(this,rn)),n.ondiscard(o(this,kn))}else o(this,rn).call(this,n)}}vt=new WeakMap,xt=new WeakMap,We=new WeakMap,sr=new WeakMap,tn=new WeakMap,rn=new WeakMap,kn=new WeakMap;function K(e,t,r=!1){var n=new il(e),i=r?Sr:0;function a(l,f){n.ensure(l,f)}ui(()=>{var l=!1;t((f,c=0)=>{l=!0,a(c,f)}),l||a(-1,null)},i)}function pe(e,t){return t}function al(e,t,r){for(var n=[],i=t.length,a,l=t.length,f=0;f{if(a){if(a.pending.delete(g),a.done.add(g),a.pending.size===0){var b=e.outrogroups;Qn(e,An(a.done)),b.delete(a),b.size===0&&(e.outrogroups=null)}}else l-=1},!1)}if(l===0){var c=n.length===0&&r!==null&&e.pending.size===0;if(c){var d=r,h=d.parentNode;Ps(h),h.append(d),e.items.clear()}Qn(e,t,!c)}else a={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(a)}function Qn(e,t,r=!0){var n;if(e.pending.size>0){n=new Set;for(const l of e.pending.values())for(const f of l)n.add(e.items.get(f).e)}for(var i=0;i{var S=r();return En(S)?S:S==null?[]:An(S)}),b,_=new Map,p=!0;function w(S){(D.effect.f&Ie)===0&&(D.pending.delete(S),D.fallback=h,sl(D,b,l,t,n),h!==null&&(b.length===0?(h.f&Et)===0?gn(h):(h.f^=Et,Vr(h,null,l)):lr(h,()=>{h=null})))}function m(S){D.pending.delete(S)}var k=ui(()=>{b=s(g);for(var S=b.length,B=new Set,te=A,Q=oa(),G=0;Ga(l)):(h=rt(()=>a(Ni??(Ni=qt()))),h.f|=Et)),S>B.size&&as(),!p)if(_.set(te,B),Q){for(const[Pe,Ae]of f)B.has(Pe)||te.skip_effect(Ae.e);te.oncommit(w),te.ondiscard(m)}else w(te);s(g)}),D={effect:k,items:f,pending:_,outrogroups:null,fallback:h};p=!1}function Fr(e){for(;e!==null&&(e.f&at)===0;)e=e.next;return e}function sl(e,t,r,n,i){var V,Pe,Ae,de,Re,$e,mt,Ot,lt;var a=(n&za)!==0,l=t.length,f=e.items,c=Fr(e.effect.first),d,h=null,g,b=[],_=[],p,w,m,k;if(a)for(k=0;k0){var ce=(n&Di)!==0&&l===0?r:null;if(a){for(k=0;k{var ge,bt;if(g!==void 0)for(m of g)(bt=(ge=m.nodes)==null?void 0:ge.a)==null||bt.apply()})}function ll(e,t,r,n,i,a,l,f){var c=(l&$a)!==0?(l&ja)===0?Cs(r,!1,!1):fr(r):null,d=(l&La)!==0?fr(i):null;return{v:c,i:d,e:rt(()=>(a(t,c??r,d??i,f),()=>{e.delete(n)}))}}function Vr(e,t,r){if(e.nodes)for(var n=e.nodes.start,i=e.nodes.end,a=t&&(t.f&Et)===0?t.nodes.start:r;n!==null;){var l=sn(n);if(a.before(n),n===i)return;n=l}}function jt(e,t,r){t===null?e.effect.first=r:t.next=r,r===null?e.effect.last=t:r.prev=t}const Pi=[...` -\r\f \v\uFEFF`];function ol(e,t,r){var n=e==null?"":""+e;if(r){for(var i of Object.keys(r))if(r[i])n=n?n+" "+i:i;else if(n.length)for(var a=i.length,l=0;(l=n.indexOf(i,l))>=0;){var f=l+a;(l===0||Pi.includes(n[l-1]))&&(f===n.length||Pi.includes(n[f]))?n=(l===0?"":n.substring(0,l))+n.substring(f+1):l=f}}return n===""?null:n}function un(e,t,r,n,i,a){var l=e[Hn];if(l!==r||l===void 0){var f=ol(r,n,a);f==null?e.removeAttribute("class"):e.className=f,e[Hn]=r}else if(a&&i!==a)for(var c in a){var d=!!a[c];(i==null||d!==!!i[c])&&e.classList.toggle(c,d)}return a}function ul(e,t){t?e.hasAttribute("selected")||e.setAttribute("selected",""):e.removeAttribute("selected")}function fl(e,t){var r=e.__defaultValue,n=e.multiple,i=n?r??[]:null;if(!(n&&!En(i))){e.selectedIndex;for(var a of e.options){var l=mr(a);ul(a,n?i.includes(l):ia(l,r))}}}function Aa(e,t,r=!1){if(e.multiple){if(t==null)return;if(!En(t))return ts();for(var n of e.options)n.selected=t.includes(mr(n));return}for(n of e.options){var i=mr(n);if(ia(i,t)){n.selected=!0;return}}(!r||t!==void 0)&&(e.selectedIndex=-1)}function dr(e){var t=new MutationObserver(r=>{r.every(cl)||("__defaultValue"in e&&fl(e),"__value"in e&&Aa(e,e.__value))});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),ua(()=>{t.disconnect()})}function vr(e,t,r=t){var n=new WeakSet,i=!0;Gi(e,"change",a=>{var l=a?"[selected]":":checked",f;if(e.multiple)f=[].map.call(e.querySelectorAll(l),mr);else{var c=e.querySelector(l)??e.querySelector("option:not([disabled])");f=c&&mr(c)}r(f),e.__value=f,A!==null&&n.add(A)}),Fs(()=>{var a=t();if(e===document.activeElement){var l=A;if(n.has(l))return}if(Aa(e,a,i),i&&a===void 0){var f=e.querySelector(":checked");f!==null&&(a=mr(f),r(a))}e.__value=a,i=!1})}function mr(e){return"__value"in e?e.__value:e.value}function cl(e){if(e.target.closest("selectedcontent")!==null)return!0;if(e.type==="childList"){var t=[...e.addedNodes,...e.removedNodes];return t.length>0&&t.every(r=>r.nodeName==="SELECTEDCONTENT")}return!1}function nt(e,t,r=t){var n=new WeakSet;Gi(e,"input",async i=>{var a=i?e.defaultValue:e.value;if(a=$n(e)?Ln(a):a,r(a),A!==null&&n.add(A),await Vs(),a!==(a=t())){var l=e.selectionStart,f=e.selectionEnd,c=e.value.length;if(e.value=a??"",f!==null){var d=e.value.length;l===f&&f===c&&d>c?(e.selectionStart=d,e.selectionEnd=d):(e.selectionStart=l,e.selectionEnd=Math.min(f,d))}}}),ka(t)==null&&e.value&&(r($n(e)?Ln(e.value):e.value),A!==null&&n.add(A)),ca(()=>{var i=t();if(e===document.activeElement){var a=A;if(n.has(a))return}$n(e)&&i===Ln(e.value)||e.type==="date"&&!i&&!e.value||i!==e.value&&(e.value=i??"")})}function $n(e){var t=e.type;return t==="number"||t==="range"}function Ln(e){return e===""?null:+e}async function Sa(e,t,r){try{const n=await fetch(`/api${t}`,{method:e,headers:r===void 0?void 0:{"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),i=await n.json().catch(()=>({error:n.statusText}));return{ok:n.ok,data:i}}catch(n){return{ok:!1,data:{error:(n==null?void 0:n.message)??String(n)}}}}const On=e=>Sa("GET",e),di=(e,t={})=>Sa("POST",e,t);var dl=N('
',1),vl=N('
'),hl=N('

No proof possible

The statement is false, so the prover cannot produce a proof. Nothing reaches the chain.

'),_l=N('

 
'),pl=N('

');function vi(e,t){Rr(t,!0);var r=Oi(),n=St(r);{var i=a=>{var l=Oi(),f=St(l);{var c=b=>{var _=vl(),p=v(_),w=u(p);{var m=k=>{var D=dl(),S=u(St(D)),B=x(S);$(()=>y(B,`tx ${t.result.data.txHash??""}`)),E(k,D)};K(w,k=>{t.result.data.txHash&&k(m)})}$(()=>y(p,`✓ ${t.result.data.summary??t.result.data.verdict??t.result.data.lenderLearns??"Done"??""} `)),E(b,_)},d=b=>{var _=hl(),p=u(v(_),2),w=x(p,!0);$(()=>y(w,t.result.data.error)),E(b,_)},h=b=>{var _=_l(),p=v(_),w=x(p,!0),m=u(p,2),k=x(m,!0),D=u(m,2),S=x(D,!0);$(()=>{y(w,t.result.data.onChainValidation.title),y(k,t.result.data.onChainValidation.summary),y(S,t.result.data.onChainValidation.detail)}),E(b,_)},g=b=>{var _=pl(),p=v(_),w=x(p,!0);$(()=>{var m;return y(w,((m=t.result.data)==null?void 0:m.error)??"Failed")}),E(b,_)};K(f,b=>{var _,p;t.result.ok?b(c):(_=t.result.data)!=null&&_.noProof?b(d,1):(p=t.result.data)!=null&&p.onChainValidation?b(h,2):b(g,-1)})}E(a,l)};K(n,a=>{t.result&&a(i)})}E(e,r),Mr()}var hr=N(""),ml=N('

'),bl=N(" "),gl=N("
amountcommitment (u)note UTxO
"),yl=N("

: balance points

",1),wl=N(" "),xl=N('

None yet.

'),kl=N("receipt UTxOspenderprice"),El=N(" "),Al=N(" "),Sl=N("

Transactions

",1),Tl=N('

Private — the openings each wallet holds

On-chain — what anyone can see

Notes at : owner and commitment, never the amount.

note UTxOownercommitment uv

Receipts held by the retailer

',1),Cl=N(`

A. Confidential points

Loyalty points are notes whose amounts are Pedersen commitments. A transfer proves in = out1 + out2 over hidden 64-bit amounts; a redemption proves in = change + price with a public price. The PointsLedger

Issue (retailer)

Transfer

Cheat: ask for more than the sender's largest note holds — no proof exists.

Redeem at the retailer

Try to cheat: spend someone else's note

Even with a valid proof, the script requires the note owner's signature.

`);function Ol(e,t){Rr(t,!0);let r=H(null),n=H(""),i=H(null),a=H("alice"),l=H(1e3),f=H("alice"),c=H("bob"),d=H(700),h=H("bob"),g=H(120),b=H("bob"),_=H("alice");const p=["alice","bob","retailer"];async function w(){const C=await On("/points");C.ok&&R(r,C.data,!0)}async function m(C,M,O){R(n,C,!0),R(i,null),R(i,await di(M,O),!0),R(n,""),await w()}Tn(()=>{w()});var k=Cl(),D=u(v(k),2),S=u(v(D),6),B=u(D,2),te=v(B),Q=u(v(te),2),G=u(v(Q));me(G,21,()=>p,pe,(C,M)=>{var O=hr(),W=x(O,!0),T={};$(()=>{y(W,s(M)),T!==(T=s(M))&&(O.__value=T)}),E(C,O)}),dr(G);var le=u(Q,2),ce=u(v(le)),V=u(le,2),Pe=u(te,2),Ae=u(v(Pe),2),de=u(v(Ae));me(de,21,()=>p,pe,(C,M)=>{var O=hr(),W=x(O,!0),T={};$(()=>{y(W,s(M)),T!==(T=s(M))&&(O.__value=T)}),E(C,O)}),dr(de);var Re=u(Ae,2),$e=u(v(Re));me($e,21,()=>p,pe,(C,M)=>{var O=hr(),W=x(O,!0),T={};$(()=>{y(W,s(M)),T!==(T=s(M))&&(O.__value=T)}),E(C,O)}),dr($e);var mt=u(Re,2),Ot=u(v(mt)),lt=u(mt,2),ge=u(Pe,2),bt=u(v(ge),2),Lt=u(v(bt));me(Lt,21,()=>p,pe,(C,M)=>{var O=hr(),W=x(O,!0),T={};$(()=>{y(W,s(M)),T!==(T=s(M))&&(O.__value=T)}),E(C,O)}),dr(Lt);var I=u(bt,2),L=u(v(I)),ne=u(I,2),Xe=u(ge,2),F=u(v(Xe),2),oe=u(v(F));me(oe,21,()=>p,pe,(C,M)=>{var O=hr(),W=x(O,!0),T={};$(()=>{y(W,s(M)),T!==(T=s(M))&&(O.__value=T)}),E(C,O)}),dr(oe);var ve=u(F,2),Le=u(v(ve));me(Le,21,()=>p,pe,(C,M)=>{var O=hr(),W=x(O,!0),T={};$(()=>{y(W,s(M)),T!==(T=s(M))&&(O.__value=T)}),E(C,O)}),dr(Le);var ze=u(ve,2),Nt=u(B,2);{var zt=C=>{var M=ml(),O=x(M);$(()=>y(O,`${s(n)??""}… (proving and waiting for the block)`)),E(C,M)};K(Nt,C=>{s(n)&&C(zt)})}var Gt=u(Nt,2);vi(Gt,{get result(){return s(i)}});var Dr=u(Gt,2);{var Ir=C=>{var M=Tl(),O=St(M),W=v(O),T=u(v(W),2);me(T,17,()=>Object.entries(s(r).private),pe,(X,ie)=>{var xe=ii(()=>$i(s(ie),2));let Ve=()=>s(xe)[0],Ze=()=>s(xe)[1];var ut=yl(),Be=St(ut),ft=v(Be),gt=x(ft,!0),Rt=u(ft,2),Kt=x(Rt,!0),Wt=u(Be,2);{var Jt=qr=>{var hi=gl(),Ta=u(v(hi));me(Ta,21,()=>Ze().notes,pe,(Ca,Nn)=>{var _i=bl(),pi=v(_i),Oa=x(pi,!0),mi=u(pi),Na=v(mi),Pa=x(Na,!0),Ra=u(mi),Ma=v(Ra),Da=x(Ma,!0);$(()=>{y(Oa,s(Nn).amount),y(Pa,s(Nn).commitment),y(Da,s(Nn).utxo)}),E(Ca,_i)}),E(qr,hi)};K(Wt,qr=>{Ze().notes.length>0&&qr(Jt)})}$(()=>{y(gt,Ve()),y(Kt,Ze().balance)}),E(X,ut)});var re=u(W,2),ye=u(v(re),2),he=u(v(ye)),Se=x(he),Te=u(ye,2),Me=u(v(Te));me(Me,21,()=>s(r).onChain,pe,(X,ie)=>{var xe=wl(),Ve=v(xe),Ze=v(Ve),ut=x(Ze,!0),Be=u(Ve),ft=x(Be,!0),gt=u(Be),Rt=v(gt),Kt=x(Rt,!0),Wt=u(gt),Jt=v(Wt),qr=x(Jt,!0);$(()=>{y(ut,s(ie).utxo),y(ft,s(ie).owner),y(Kt,s(ie).u),y(qr,s(ie).v)}),E(X,xe)});var we=u(Te,4);{var je=X=>{var ie=xl();E(X,ie)};K(we,X=>{s(r).receipts.length===0&&X(je)})}var J=u(we,2),ee=v(J);{var _e=X=>{var ie=kl();E(X,ie)};K(ee,X=>{s(r).receipts.length>0&&X(_e)})}var He=u(ee);me(He,21,()=>s(r).receipts,pe,(X,ie)=>{var xe=El(),Ve=v(xe),Ze=v(Ve),ut=x(Ze,!0),Be=u(Ve),ft=x(Be,!0),gt=u(Be),Rt=x(gt,!0);$(()=>{y(ut,s(ie).utxo),y(ft,s(ie).spender),y(Rt,s(ie).price)}),E(X,xe)});var ot=u(O,2);{var Pt=X=>{var ie=Sl(),xe=u(St(ie),2),Ve=v(xe);me(Ve,21,()=>s(r).history,pe,(Ze,ut)=>{var Be=Al(),ft=v(Be),gt=x(ft,!0),Rt=u(ft),Kt=v(Rt),Wt=x(Kt);$(Jt=>{y(gt,s(ut).summary),y(Wt,`${Jt??""}…`)},[()=>s(ut).txHash.substring(0,20)]),E(Ze,Be)}),E(X,ie)};K(ot,X=>{s(r).history.length>0&&X(Pt)})}$(X=>y(Se,`${X??""}…`),[()=>s(r).ledgerAddress.substring(0,34)]),E(C,M)};K(Dr,C=>{s(r)&&C(Ir)})}$(()=>{var C,M,O,W;y(S,` script checks the proof, the owner's signature, issuer-only - supply and one-time receipts. Circuits: transfer ${((M=(C=s(r))==null?void 0:C.constraints)==null?void 0:M.transfer)??"…"??""} constraints, redeem - ${((W=(O=s(r))==null?void 0:O.constraints)==null?void 0:W.redeem)??"…"??""}.`),V.disabled=!!s(n),lt.disabled=!!s(n),ne.disabled=!!s(n),ze.disabled=!!s(n)}),vr(G,()=>s(a),C=>R(a,C)),nt(ce,()=>s(l),C=>R(l,C)),ke("click",V,()=>m("Issuing","/points/issue",{to:s(a),amount:s(l)})),vr(de,()=>s(f),C=>R(f,C)),vr($e,()=>s(c),C=>R(c,C)),nt(Ot,()=>s(d),C=>R(d,C)),ke("click",lt,()=>m("Proving and submitting the transfer","/points/transfer",{from:s(f),to:s(c),amount:s(d)})),vr(Lt,()=>s(h),C=>R(h,C)),nt(L,()=>s(g),C=>R(g,C)),ke("click",ne,()=>m("Proving and submitting the redemption","/points/redeem",{from:s(h),price:s(g)})),vr(oe,()=>s(b),C=>R(b,C)),vr(Le,()=>s(_),C=>R(_,C)),ke("click",ze,()=>m("Submitting the theft","/points/steal",{thief:s(b),victim:s(_)})),E(e,k),Mr()}Cn(["click"]);var Nl=N('

'),Pl=N("
income
credit score
birth year
country
blinding
"),Rl=N('

No profile issued yet.

'),Ml=N("
commitment u
commitment v
schema digest σ
holder
record token
record tx
"),Dl=N('

Nothing recorded yet.

'),Il=N('

No badge claimed yet.

'),ql=N(" "),Fl=N(`

Private — Alice's opening

On-chain — the issuance record

What the lender learns

`),$l=N(`

B. Committed credential

A credit bureau commits to four attributes of Alice's profile in one vector commitment - (schema ) and records the issuance on-chain. Alice then - proves income ≥ X ∧ credit_score ≥ Y

1. Bureau issues Alice's profile

2. Alice claims a badge from the lender

Raise a threshold above her profile to see that no proof exists.

Try to cheat: Mallory presents Alice's credential

Suppose Alice's opening leaked: Mallory has a valid proof for Alice's commitment. The issuance - record names Alice, and the gate requires the named holder's signature.

`);function Ll(e,t){Rr(t,!0);let r=H(null),n=H(""),i=H(null),a=H(85e3),l=H(720),f=H(1990),c=H(356),d=H(5e4),h=H(650);async function g(){const F=await On("/credit");F.ok&&R(r,F.data,!0)}async function b(F,oe,ve){R(n,F,!0),R(i,null),R(i,await di(oe,ve),!0),R(n,""),await g()}Tn(()=>{g()});var _=$l(),p=u(v(_),2),w=u(v(p),3),m=x(w),k=u(w,3),D=u(p,2),S=v(D),B=u(v(S),2),te=u(v(B)),Q=u(B,2),G=u(v(Q)),le=u(Q,2),ce=u(v(le)),V=u(le,2),Pe=u(v(V)),Ae=u(V,2),de=u(S,2),Re=u(v(de),2),$e=u(v(Re)),mt=u(Re,2),Ot=u(v(mt)),lt=u(mt,2),ge=u(de,2),bt=u(v(ge),4),Lt=u(D,2);{var I=F=>{var oe=Nl(),ve=x(oe);$(()=>y(ve,`${s(n)??""}… (proving and waiting for the block)`)),E(F,oe)};K(Lt,F=>{s(n)&&F(I)})}var L=u(Lt,2);vi(L,{get result(){return s(i)}});var ne=u(L,2);{var Xe=F=>{var oe=Fl(),ve=v(oe),Le=u(v(ve),2);{var ze=T=>{var re=Pl(),ye=v(re),he=v(ye),Se=u(v(he)),Te=x(Se,!0),Me=u(he),we=u(v(Me)),je=x(we,!0),J=u(Me),ee=u(v(J)),_e=x(ee,!0),He=u(J),ot=u(v(He)),Pt=x(ot,!0),X=u(He),ie=u(v(X)),xe=v(ie),Ve=x(xe,!0);$(()=>{y(Te,s(r).private.income),y(je,s(r).private.creditScore),y(_e,s(r).private.birthYear),y(Pt,s(r).private.country),y(Ve,s(r).private.blinding)}),E(T,re)},Nt=T=>{var re=Rl();E(T,re)};K(Le,T=>{s(r).private?T(ze):T(Nt,-1)})}var zt=u(ve,2),Gt=u(v(zt),2);{var Dr=T=>{var re=Ml(),ye=v(re),he=v(ye),Se=u(v(he)),Te=v(Se),Me=x(Te,!0),we=u(he),je=u(v(we)),J=v(je),ee=x(J,!0),_e=u(we),He=u(v(_e)),ot=v(He),Pt=x(ot,!0),X=u(_e),ie=u(v(X)),xe=v(ie),Ve=x(xe,!0),Ze=u(X),ut=u(v(Ze)),Be=v(ut),ft=x(Be,!0),gt=u(Ze),Rt=u(v(gt)),Kt=v(Rt),Wt=x(Kt);$(Jt=>{y(Me,s(r).onChain.u),y(ee,s(r).onChain.v),y(Pt,s(r).schema.digest),y(Ve,s(r).onChain.holder),y(ft,s(r).onChain.recordToken),y(Wt,`${Jt??""}…`)},[()=>s(r).onChain.recordTx.substring(0,20)]),E(T,re)},Ir=T=>{var re=Dl();E(T,re)};K(Gt,T=>{s(r).onChain?T(Dr):T(Ir,-1)})}var C=u(Gt,4);{var M=T=>{var re=Il();E(T,re)};K(C,T=>{s(r).claims.length===0&&T(M)})}var O=u(C,2),W=v(O);me(W,21,()=>s(r).claims,pe,(T,re)=>{var ye=ql(),he=v(ye),Se=x(he),Te=u(he),Me=v(Te),we=x(Me);$(je=>{y(Se,`${s(re).claimant??""}: ${s(re).lenderLearns??""}`),y(we,`${je??""}…`)},[()=>s(re).txHash.substring(0,16)]),E(T,ye)}),E(F,oe)};K(ne,F=>{s(r)&&F(Xe)})}$(()=>{var F,oe,ve,Le,ze,Nt,zt;y(m,`${((oe=(F=s(r))==null?void 0:F.schema)==null?void 0:oe.id)??""} v${((Le=(ve=s(r))==null?void 0:ve.schema)==null?void 0:Le.version)??""}`),y(k,` to a lender's gate and receives a badge. The lender learns that - she qualifies — not her income, score, birth year or country. Circuit: ${((ze=s(r))==null?void 0:ze.constraints)??"…"??""} constraints.`),Ae.disabled=!!s(n),lt.disabled=!!s(n)||!((Nt=s(r))!=null&&Nt.private),bt.disabled=!!s(n)||!((zt=s(r))!=null&&zt.private)}),nt(te,()=>s(a),F=>R(a,F)),nt(G,()=>s(l),F=>R(l,F)),nt(ce,()=>s(f),F=>R(f,F)),nt(Pe,()=>s(c),F=>R(c,F)),ke("click",Ae,()=>b("Committing and recording the issuance","/credit/issue",{income:s(a),creditScore:s(l),birthYear:s(f),country:s(c)})),nt($e,()=>s(d),F=>R(d,F)),nt(Ot,()=>s(h),F=>R(h,F)),ke("click",lt,()=>b("Proving Alice's predicate and claiming","/credit/claim",{who:"alice",minIncome:s(d),minScore:s(h)})),ke("click",bt,()=>b("Submitting Mallory's claim","/credit/claim",{who:"mallory",minIncome:s(d),minScore:s(h)})),E(e,_),Mr()}Cn(["click"]);var zl=N(''),jl=N(''),Hl=N('

'),Vl=N('
Auditor: the sum of all commitments opens to total liabilities of
'),Bl=N("— reserve released, tx ",1),Yl=N('
Period: phase
'),Ul=N(" "),Gl=N(" "),Kl=N('

Reserve locked: at

id hashcommitment u

Attestation tx

',1),Wl=N('

No attestation yet.

'),Jl=N(`

Private — the exchange's book and each customer's opening

Total liabilities: (never published)

customerbalancesaltblindingid hashlast check

On-chain — the period's vault

`,1),Xl=N(`

C. Hidden-liability solvency

The exchange publishes one Pedersen commitment per customer balance and proves Σ balances ≤ reserves while hiding every balance and the total. The reserve is locked in a vault for a - public attestation period

1. The book (balances in ADA)

2. Attest for a new period

Lock less than the book's total to see that no proof exists.

3. Check (during the period)

Try to cheat inside the period

Before the period ends the vault rejects a release; after it ends the release succeeds.

`);function Zl(e,t){Rr(t,!0);let r=H(null),n=H(""),i=H(null),a=H(2e3),l=H(Qt([])),f=0,c=H(Qt(Date.now()));async function d(){const I=await On("/solvency");I.ok&&(R(r,I.data,!0),f=I.data.chainTime-Date.now(),s(l).length===0&&R(l,I.data.book.map(L=>({id:L.id,balance:L.balance})),!0))}async function h(I,L,ne={}){R(n,I,!0),R(i,null),R(i,await di(L,ne),!0),R(n,""),await d()}function g(I){return Math.max(0,Math.round((I-(s(c)+f))/1e3))}Tn(()=>{d();const I=setInterval(()=>{R(c,Date.now(),!0)},1e3),L=setInterval(()=>{var ne;!s(n)&&((ne=s(r))!=null&&ne.period)&&d()},5e3);return()=>{clearInterval(I),clearInterval(L)}});let b=ii(()=>{var I,L;return((I=s(r))==null?void 0:I.period)&&!((L=s(r))!=null&&L.releaseTx)});var _=Xl(),p=u(v(_),2),w=u(v(p),4),m=u(p,2),k=v(m),D=u(v(k),2),S=v(D);me(S,21,()=>s(l),pe,(I,L,ne)=>{var Xe=zl(),F=v(Xe),oe=v(F),ve=u(F),Le=v(ve);$(()=>{oe.disabled=s(b),Le.disabled=s(b)}),nt(oe,()=>s(L).id,ze=>s(L).id=ze),nt(Le,()=>s(L).balance,ze=>s(L).balance=ze),E(I,Xe)});var B=u(D,2),te=u(k,2),Q=u(v(te),2),G=u(v(Q)),le=u(Q,2),ce=u(te,2),V=u(v(ce),2);me(V,17,()=>{var I;return((I=s(r))==null?void 0:I.book)??[]},pe,(I,L)=>{var ne=jl(),Xe=x(ne);$(()=>{var F;ne.disabled=!!s(n)||!((F=s(r))!=null&&F.period),y(Xe,`${s(L).id??""} checks`)}),ke("click",ne,()=>h(`${s(L).id} checks the attestations`,"/solvency/check",{id:s(L).id})),E(I,ne)});var Pe=u(V,2),Ae=u(ce,2),de=u(v(Ae),2),Re=u(de,2),$e=u(m,2);{var mt=I=>{var L=Hl(),ne=x(L);$(()=>y(ne,`${s(n)??""}… (proving and waiting for the block)`)),E(I,L)};K($e,I=>{s(n)&&I(mt)})}var Ot=u($e,2);vi(Ot,{get result(){return s(i)}});var lt=u(Ot,2);{var ge=I=>{var L=Vl(),ne=u(v(L)),Xe=x(ne),F=u(ne);$(()=>{y(Xe,`${s(i).data.liabilitiesAda??""} ADA`),y(F,` against ${s(i).data.reservesAda??""} ADA locked — - ${s(i).data.ok?"verified":"NOT verified"}. No single balance is revealed.`)}),E(I,L)};K(lt,I=>{var L;(L=s(i))!=null&&L.ok&&s(i).data.liabilitiesAda!==void 0&&I(ge)})}var bt=u(lt,2);{var Lt=I=>{var L=Jl(),ne=St(L);{var Xe=M=>{var O=Yl(),W=u(v(O),2),T=x(W,!0),re=u(W,2);{var ye=J=>{var ee=Fn();$(_e=>y(ee,`— starts in ${_e??""} s (attestations allowed until then)`),[()=>g(s(r).period.start)]),E(J,ee)};K(re,J=>{s(r).phase==="before"&&J(ye)})}var he=u(re,2);{var Se=J=>{var ee=Fn();$(_e=>y(ee,`— ends in ${_e??""} s (nothing can be added or released)`),[()=>g(s(r).period.end)]),E(J,ee)};K(he,J=>{s(r).phase==="during"&&J(Se)})}var Te=u(he,2);{var Me=J=>{var ee=Fn("— ended; the reserve can be released");E(J,ee)};K(Te,J=>{s(r).phase==="after"&&J(Me)})}var we=u(Te,2);{var je=J=>{var ee=Bl(),_e=u(St(ee)),He=x(_e);$(ot=>y(He,`${ot??""}…`),[()=>s(r).releaseTx.substring(0,20)]),E(J,ee)};K(we,J=>{s(r).phase==="released"&&J(je)})}$(()=>y(T,s(r).phase)),E(M,O)};K(ne,M=>{s(r).period&&M(Xe)})}var F=u(ne,2),oe=v(F),ve=u(v(oe),2),Le=u(v(ve)),ze=x(Le),Nt=u(ve,2),zt=u(v(Nt));me(zt,21,()=>s(r).book,pe,(M,O)=>{var W=Ul(),T=v(W),re=x(T,!0),ye=u(T),he=x(ye,!0),Se=u(ye),Te=v(Se),Me=x(Te,!0),we=u(Se),je=v(we),J=x(je,!0),ee=u(we),_e=v(ee),He=x(_e,!0),ot=u(ee),Pt=x(ot,!0);$(()=>{y(re,s(O).id),y(he,s(O).balance),y(Me,s(O).salt),y(J,s(O).blinding),y(He,s(O).idHash),y(Pt,s(O).check)}),E(M,W)});var Gt=u(oe,2),Dr=u(v(Gt),2);{var Ir=M=>{var O=Kl(),W=St(O),T=u(v(W)),re=x(T),ye=u(T,2),he=x(ye),Se=u(W,2),Te=u(v(Se));me(Te,21,()=>s(r).onChain??[],pe,(J,ee)=>{var _e=Gl(),He=v(_e),ot=v(He),Pt=x(ot,!0),X=u(He),ie=v(X),xe=x(ie,!0);$(()=>{y(Pt,s(ee).idHash),y(xe,s(ee).u)}),E(J,_e)});var Me=u(Se,2),we=u(v(Me)),je=x(we);$((J,ee)=>{y(re,`${s(r).reservesAda??""} ADA`),y(he,`${J??""}…`),y(je,`${ee??""}…`)},[()=>s(r).vaultAddress.substring(0,30),()=>s(r).attestTx.substring(0,20)]),E(M,O)},C=M=>{var O=Wl();E(M,O)};K(Dr,M=>{s(r).period?M(Ir):M(C,-1)})}$(()=>y(ze,`${s(r).liabilitiesAda??""} ADA`)),E(I,L)};K(bt,I=>{s(r)&&I(Lt)})}$(()=>{var I,L;y(w,`: attestations only before it starts, release only after it ends, so the same funds - cannot back attestations one after another. Customers check their own entry; an auditor opens the total by - homomorphism. Circuit: ${((I=s(r))==null?void 0:I.constraints)??"…"??""} constraints (4 customers).`),B.disabled=!!s(n)||s(b),G.disabled=s(b),le.disabled=!!s(n)||s(b),Pe.disabled=!!s(n)||!((L=s(r))!=null&&L.period),de.disabled=!!s(n)||!s(b),Re.disabled=!!s(n)||!s(b)}),ke("click",B,()=>h("Saving the book","/solvency/book",{customers:s(l)})),nt(G,()=>s(a),I=>R(a,I)),ke("click",le,()=>h("Proving solvency and locking the reserve","/solvency/attest",{reservesAda:s(a)})),ke("click",Pe,()=>h("Auditor opens the total","/solvency/audit")),ke("click",de,()=>h("Submitting another attestation","/solvency/attest-again")),ke("click",Re,()=>h("Releasing the reserve","/solvency/release")),E(e,_),Mr()}Cn(["click"]);var Ql=N(" "),eo=N("

"),to=N(`

Starting… compiling circuits, loading or generating development keys and funding demo wallets. - The first start takes a few minutes; later starts reuse the cached keys.

`),ro=N(" ",1),no=N('

'),io=N(`

Pedersen Commitments on Cardano

Hiding, binding and additive commitments with zero-knowledge proofs, verified by Plutus V3 on Yaci DevKit

Demo server. This server creates every wallet and holds every opening (amounts, blindings, - profiles, customer balances) and key on the users' behalf; real users would each keep their own. - The On-chain panels show what anyone can read from the ledger.
`);function ao(e,t){Rr(t,!0);let r=H("points"),n=H(null);async function i(){var S;const D=await On("/status");R(n,D.data,!0),(S=s(n))!=null&&S.ready||setTimeout(i,3e3)}Tn(()=>{i()});var a=io(),l=u(v(a),6);{var f=D=>{var S=to(),B=u(v(S),2);{var te=Q=>{var G=eo();me(G,21,()=>Object.entries(s(n).demos),pe,(le,ce)=>{var V=ii(()=>$i(s(ce),2));let Pe=()=>s(V)[0],Ae=()=>s(V)[1];var de=Ql();let Re;var $e=x(de);$(()=>{Re=un(de,1,"pill svelte-1n46o8q",null,Re,{ready:Ae()==="ready"}),y($e,`${Pe()??""}: ${Ae()??""}`)}),E(le,de)}),E(Q,G)};K(B,Q=>{var G;(G=s(n))!=null&&G.demos&&Q(te)})}E(D,S)};K(l,D=>{var S;(S=s(n))!=null&&S.ready||D(f)})}var c=u(l,2),d=v(c);let h;var g=u(d,2);let b;var _=u(g,2);let p;var w=u(c,2);{var m=D=>{var S=ro(),B=St(S);{var te=V=>{Ol(V,{})};K(B,V=>{s(r)==="points"&&V(te)})}var Q=u(B,2);{var G=V=>{Ll(V,{})};K(Q,V=>{s(r)==="credit"&&V(G)})}var le=u(Q,2);{var ce=V=>{Zl(V,{})};K(le,V=>{s(r)==="solvency"&&V(ce)})}E(D,S)},k=D=>{var S=no(),B=x(S);$(()=>{var te,Q;return y(B,`This demo is ${((Q=(te=s(n))==null?void 0:te.demos)==null?void 0:Q[s(r)])??"starting"??""}…`)}),E(D,S)};K(w,D=>{var S,B;((B=(S=s(n))==null?void 0:S.demos)==null?void 0:B[s(r)])==="ready"?D(m):s(n)&&D(k,1)})}$(()=>{h=un(d,1,"svelte-1n46o8q",null,h,{active:s(r)==="points"}),b=un(g,1,"svelte-1n46o8q",null,b,{active:s(r)==="credit"}),p=un(_,1,"svelte-1n46o8q",null,p,{active:s(r)==="solvency"})}),ke("click",d,()=>R(r,"points")),ke("click",g,()=>R(r,"credit")),ke("click",_,()=>R(r,"solvency")),E(e,a),Mr()}Cn(["click"]);tl(ao,{target:document.getElementById("app")}); diff --git a/pedersen-commitments/src/main/resources/static/assets/index-DamEuh0Q.css b/pedersen-commitments/src/main/resources/static/assets/index-DamEuh0Q.css deleted file mode 100644 index a14df0b..0000000 --- a/pedersen-commitments/src/main/resources/static/assets/index-DamEuh0Q.css +++ /dev/null @@ -1 +0,0 @@ -.ok.svelte-wzlqy7{background:#12261a;border:1px solid #238636;border-radius:8px;padding:10px 14px;margin:12px 0;color:#7ee787}.noproof.svelte-wzlqy7{background:#2b2111;border:1px solid #d29922;border-radius:8px;padding:10px 14px;margin:12px 0}.noproof.svelte-wzlqy7 h4:where(.svelte-wzlqy7){color:#e3b341;margin:0 0 6px}.rejected.svelte-wzlqy7{background:#2d1214;border:1px solid #da3633;border-radius:8px;padding:10px 14px;margin:12px 0}.rejected.svelte-wzlqy7 h4:where(.svelte-wzlqy7){color:#f85149;margin:0 0 6px}pre.svelte-wzlqy7{white-space:pre-wrap;overflow-wrap:anywhere;max-height:200px;overflow-y:auto;background:#161b22;padding:8px;border-radius:6px;color:#ffb4ad;font-size:.8em}p.svelte-wzlqy7{margin:4px 0}.hint.svelte-wzlqy7{color:#8b949e;font-size:.9em}code.svelte-wzlqy7{font-size:.85em;color:#79c0ff;overflow-wrap:anywhere}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;max-width:1180px;margin:0 auto;padding:20px;background:#0d1117;color:#c9d1d9}h2{color:#c9d1d9;margin:8px 0}h3{color:#58a6ff;margin:12px 0 6px;font-size:1em}.card{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:14px;margin:12px 0}.columns{display:grid;grid-template-columns:1fr 1fr;gap:16px}.panel{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:12px 14px}.panel.private{border-color:#8957e5}.panel.private h3{color:#d2a8ff}.panel.public{border-color:#1f6feb}table{width:100%;border-collapse:collapse;margin:6px 0;font-size:.9em}th,td{padding:5px 8px;text-align:left;border-bottom:1px solid #21262d}th{color:#8b949e;font-weight:400}code{font-size:.85em;color:#79c0ff}.hint{color:#8b949e;font-size:.9em}.actions{display:flex;flex-wrap:wrap;gap:12px}.action{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:10px 12px;flex:1 1 250px}.action h4{margin:0 0 8px;color:#c9d1d9}.action.cheat{border-color:#da3633}.action.cheat h4{color:#f85149}label{display:block;font-size:.85em;color:#8b949e;margin:4px 0}input,select{background:#0d1117;color:#c9d1d9;border:1px solid #30363d;border-radius:6px;padding:5px 7px;width:100%;box-sizing:border-box}button.primary,button.danger{margin-top:8px;padding:7px 14px;border:none;border-radius:6px;color:#fff;font-weight:700;cursor:pointer}button.primary{background:#238636}button.danger{background:#da3633}button:disabled{opacity:.5;cursor:not-allowed}.busy{color:#58a6ff;margin:8px 0}h1.svelte-1n46o8q{color:#58a6ff;margin-bottom:4px}.subtitle.svelte-1n46o8q{color:#8b949e;margin-top:0}.notice.svelte-1n46o8q{background:#1c1f26;border:1px solid #d29922;border-radius:8px;padding:10px 14px;color:#e3b341;font-size:.92em}nav.svelte-1n46o8q{display:flex;gap:8px;margin:18px 0 8px;flex-wrap:wrap}nav.svelte-1n46o8q button:where(.svelte-1n46o8q){padding:8px 18px;border:1px solid #30363d;background:#21262d;color:#c9d1d9;border-radius:6px;cursor:pointer}nav.svelte-1n46o8q button.active:where(.svelte-1n46o8q){background:#1f6feb;border-color:#1f6feb;color:#fff}.pill.svelte-1n46o8q{display:inline-block;padding:2px 10px;margin:2px;border-radius:12px;background:#30363d;font-size:.85em}.pill.ready.svelte-1n46o8q{background:#238636;color:#fff} diff --git a/pedersen-commitments/src/main/resources/static/index.html b/pedersen-commitments/src/main/resources/static/index.html index 7dc893f..d695e2c 100644 --- a/pedersen-commitments/src/main/resources/static/index.html +++ b/pedersen-commitments/src/main/resources/static/index.html @@ -5,8 +5,8 @@ Pedersen Commitments — ZeroJ - - + +
diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionCircuitTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionCircuitTest.java new file mode 100644 index 0000000..951a163 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionCircuitTest.java @@ -0,0 +1,145 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.auction; + +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.circuit.BidProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.circuit.SettleProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.zeroj.circuit.lib.jubjub.ElGamal; +import org.zeroj.circuit.lib.jubjub.ElGamalEncryption; +import org.zeroj.circuit.lib.jubjub.ElGamalSecretKey; +import org.zeroj.circuit.lib.jubjub.NOfNKeyContext; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The auction relations (ADR-0008 D3, D4): honest bids and settlements prove and verify; bids + * outside {@code [reserve, deposit]}, proofs for another bidder, and every wrong settlement (another + * winner, a later equal bid, a wrong price, a wrong secret, a wrong decryption) have no proof. + */ +class AuctionCircuitTest { + + static final SecureRandom RANDOM = new SecureRandom(); + static final byte[] ALICE = filled(28, (byte) 0x0a); + static final byte[] BOB = filled(28, (byte) 0x0b); + static final byte[] CAROL = filled(28, (byte) 0x0c); + static AuctionProofs proofs; + static ElGamalSecretKey auctioneer; + static NOfNKeyContext context; + + @BeforeAll + static void setup() { + proofs = new AuctionProofs(); + auctioneer = ElGamalSecretKey.generate(RANDOM); + context = NOfNKeyContext.singleKey(auctioneer); + System.out.printf("[auction circuits] bid %d constraints / %d public; settle n1 %d, n2 %d, n3 %d%n", + proofs.bid().numConstraints(), proofs.bid().numPublicInputs(), proofs.settle(1).numConstraints(), + proofs.settle(2).numConstraints(), proofs.settle(3).numConstraints()); + } + + static ElGamalEncryption enc(long amount) { + return ElGamal.encryptWithOpening(context, BigInteger.valueOf(amount), 32, RANDOM); + } + + static BigInteger pkU() { return auctioneer.publicKey().affineU(); } + + static BigInteger pkV() { return auctioneer.publicKey().affineV(); } + + @Test + @DisplayName("Bid: an honest bid proves and is bound to its bidder; a bid outside [reserve, deposit] has no proof") + void bid() { + ElGamalEncryption e = enc(40); + var inputs = AuctionProofs.bidInputs(ALICE, 100, 10, pkU(), pkV(), e); + var proof = proofs.proveBid(ALICE, 100, 10, pkU(), pkV(), e); + List pub = BidProofCircuit.publicInputs(inputs); + assertTrue(proofs.bid().verify(proof, pub)); + List otherBidder = new ArrayList<>(pub); + otherBidder.set(0, AuctionProofs.bidderInt(BOB)); + assertFalse(proofs.bid().verify(proof, otherBidder), "a proof is bound to its bidder"); + for (int i = 1; i < pub.size(); i++) { + List changed = new ArrayList<>(pub); + changed.set(i, changed.get(i).add(BigInteger.ONE)); + assertFalse(proofs.bid().verify(proof, changed), "public input " + i + " is bound"); + } + // Boundaries are inclusive. + proofs.proveBid(ALICE, 100, 10, pkU(), pkV(), enc(10)); + proofs.proveBid(ALICE, 100, 10, pkU(), pkV(), enc(100)); + assertThrows(RuntimeException.class, () -> proofs.proveBid(ALICE, 100, 10, pkU(), pkV(), enc(101)), "above the deposit"); + assertThrows(RuntimeException.class, () -> proofs.proveBid(ALICE, 100, 10, pkU(), pkV(), enc(9)), "below the reserve"); + // A ciphertext of another amount than the witness claims. + var lying = AuctionProofs.bidInputs(ALICE, 100, 10, pkU(), pkV(), e).bid(41); + assertThrows(RuntimeException.class, () -> proofs.bid().prove(lying.toWitnessMap()), "the ciphertext encrypts the bid"); + // Encrypted to another key than the public one. + var stranger = NOfNKeyContext.singleKey(ElGamalSecretKey.generate(RANDOM)); + var foreign = ElGamal.encryptWithOpening(stranger, BigInteger.valueOf(40), 32, RANDOM); + assertThrows(RuntimeException.class, () -> proofs.proveBid(ALICE, 100, 10, pkU(), pkV(), foreign), "another key"); + } + + static Lot lot(List encs, List bidders) { + List bids = new ArrayList<>(); + for (int i = 0; i < encs.size(); i++) { + var ct = encs.get(i).ciphertext(); + bids.add(new Lot.Bid(bidders.get(i), ct.handle().affineU(), ct.handle().affineV(), + ct.blinded().affineU(), ct.blinded().affineV())); + } + return new Lot(null, "00".repeat(32), ALICE, BOB, new byte[28], "x".getBytes(), 2_000_000, 100, 10, 0, 0, + pkU(), pkV(), 0, bids); + } + + @Test + @DisplayName("Settle: the earliest highest bid at its amount proves for n = 1, 2, 3; every wrong settlement has no proof") + void settle() { + BigInteger sk = auctioneer.secretScalar(); + // n = 3 with a tie: bids 40, 70, 70. The earliest highest bid is #2. + List amounts = List.of(40L, 70L, 70L); + Lot lot = lot(List.of(enc(40), enc(70), enc(70)), List.of(ALICE, BOB, CAROL)); + var proof = proofs.proveSettle(lot, 2, 70, sk, amounts); + var pub = SettleProofCircuit.publicInputs(AuctionProofs.settleInputs(lot, 2, 70, sk, amounts)); + assertTrue(proofs.settle(3).verify(proof, pub)); + for (int i = 0; i < pub.size(); i++) { + List changed = new ArrayList<>(pub); + changed.set(i, changed.get(i).add(BigInteger.ONE)); + assertFalse(proofs.settle(3).verify(proof, changed), "public input " + i + " is bound"); + } + assertThrows(RuntimeException.class, () -> proofs.proveSettle(lot, 3, 70, sk, amounts), "a later equal bid is not the winner"); + assertThrows(RuntimeException.class, () -> proofs.proveSettle(lot, 1, 40, sk, amounts), "a lower bid is not the winner"); + assertThrows(RuntimeException.class, () -> proofs.proveSettle(lot, 2, 69, sk, amounts), "the price is the winning bid"); + assertThrows(RuntimeException.class, () -> proofs.proveSettle(lot, 2, 70, sk, List.of(40L, 70L, 69L)), + "a bid decrypted to another amount"); + assertThrows(RuntimeException.class, () -> proofs.proveSettle(lot, 2, 70, sk, List.of(10L, 70L, 70L)), + "an under-reported losing bid"); + BigInteger otherSk = ElGamalSecretKey.generate(RANDOM).secretScalar(); + assertThrows(RuntimeException.class, () -> proofs.proveSettle(lot, 2, 70, otherSk, amounts), "another secret key"); + assertThrows(RuntimeException.class, () -> proofs.proveSettle(lot, 4, 70, sk, amounts), "w out of range"); + assertThrows(RuntimeException.class, () -> proofs.proveSettle(lot, 0, 70, sk, amounts), "w = 0"); + // A field element that is no index: 2^-1 mod r, and r - 1. Every one-hot flag is 0, so no proof. + BigInteger r = Fields.FR; + for (BigInteger w : List.of(BigInteger.TWO.modInverse(r), r.subtract(BigInteger.ONE))) { + var inputs = AuctionProofs.settleInputs(lot, 2, 70, sk, amounts).w(w); + assertThrows(RuntimeException.class, () -> proofs.settle(3).prove(inputs.toWitnessMap()), "w = " + w); + } + + // n = 1 and n = 2. + Lot one = lot(List.of(enc(55)), List.of(ALICE)); + assertTrue(proofs.settle(1).verify(proofs.proveSettle(one, 1, 55, sk, List.of(55L)), + SettleProofCircuit.publicInputs(AuctionProofs.settleInputs(one, 1, 55, sk, List.of(55L))))); + Lot two = lot(List.of(enc(30), enc(90)), List.of(ALICE, BOB)); + assertTrue(proofs.settle(2).verify(proofs.proveSettle(two, 2, 90, sk, List.of(30L, 90L)), + SettleProofCircuit.publicInputs(AuctionProofs.settleInputs(two, 2, 90, sk, List.of(30L, 90L))))); + } + + static byte[] filled(int length, byte value) { + byte[] out = new byte[length]; + Arrays.fill(out, value); + return out; + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionDevKitE2ETest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionDevKitE2ETest.java new file mode 100644 index 0000000..45121c5 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionDevKitE2ETest.java @@ -0,0 +1,173 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.auction; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.api.model.Result; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.common.model.Networks; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.E2E; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.AdmittedAuditor; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.AuditorKeys; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.KeyPossession; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.Registry; +import org.junit.jupiter.api.Test; +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.JubjubDiscreteLog; +import org.zeroj.circuit.lib.jubjub.RawElGamalCiphertext; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * The sealed-bid auction on Yaci DevKit (ADR-0008): an auctioneer registers its keys; a seller + * lists an item; Alice, Bob and Carol bid 40, 70 and 70 ADA (sealed); a bid above the deposit has + * no proof, a copied bid proof and a late bid are refused; the auctioneer decrypts the bids and + * settles for Bob (the earliest of the two highest) at 70; payouts are checked. A second lot with + * no settlement is refunded after its deadline. + * + *

Runs only with {@code ZEROJ_YACI_E2E=true}. + */ +class AuctionDevKitE2ETest { + + static final SecureRandom RANDOM = new SecureRandom(); + static final long BIDDING_MILLIS = 90_000; + static final long SETTLE_MILLIS = 70_000; + + @Test + void sealedBidAuctionOnDevKit() throws Exception { + assumeTrue(E2E.enabled(), "Set ZEROJ_YACI_E2E=true with DevKit running"); + BackendService backend = DevKit.backend(); + Account seller = new Account(Networks.testnet()); + Account auctioneer = new Account(Networks.testnet()); + Account alice = new Account(Networks.testnet()); + Account bob = new Account(Networks.testnet()); + Account carol = new Account(Networks.testnet()); + for (Account a : List.of(seller, auctioneer, alice, bob, carol)) DevKit.topUp(a.baseAddress(), 400); + + KeyPossession possession = new KeyPossession(); + Utxo seed = backend.getUtxoService().getUtxos(auctioneer.baseAddress(), 10, 1).getValue().getFirst(); + Registry registry = Registry.forSeed(seed.getTxHash(), seed.getOutputIndex(), possession); + AuditorKeys keys = AuditorKeys.generate(RANDOM); + ok(registry.init(backend, auctioneer, seed, keys.entry(registry.policy(), pkh(auctioneer), 0, possession)), "registry init", backend); + AuctionScript auction = new AuctionScript(new AuctionProofs(), registry, 60_000, 2_000_000); + assertTrue(auction.deploy(backend, auctioneer).isSuccessful()); + AdmittedAuditor key = registry.admitted(backend); + + // Open. + Lot lot = open(backend, auction, seller, key, "Painting"); + assertTrue(lot.bids().isEmpty()); + + // Bids. + lot = bid(backend, auction, alice, lot, key, 40); + assertThrows(RuntimeException.class, () -> auction.proofs().proveBid(pkh(bob), 100, 10, key.pkU(), key.pkV(), + ElGamal.encryptWithOpening(key.context(), BigInteger.valueOf(101), 32, RANDOM)), "a bid above the deposit has no proof"); + ElGamalEncryption bobBid = ElGamal.encryptWithOpening(key.context(), BigInteger.valueOf(70), 32, RANDOM); + var bobProof = auction.proofs().proveBid(pkh(bob), lot.deposit(), lot.reserve(), lot.pkU(), lot.pkV(), bobBid); + E2E.assertScriptRejected(auction.bid(backend, carol, lot, bobBid, bobProof), "Carol submitting Bob's bid proof"); + ok(auction.bid(backend, bob, lot, bobBid, bobProof), "bid (Bob, 70)", backend); + lot = auction.lots(backend).stream().filter(l -> l.bids().size() == 2).findFirst().orElseThrow(); + lot = bid(backend, auction, carol, lot, key, 70); + assertEquals(3, lot.bids().size()); + + // The bidding window closes; a late bid (valid past the deadline) is refused by the script. + while (DevKit.chainTimeMillis(backend) < lot.biddingEnds() + 2_000) Thread.sleep(2_000); + Account late = new Account(Networks.testnet()); + DevKit.topUp(late.baseAddress(), 300); + ElGamalEncryption lateBid = ElGamal.encryptWithOpening(key.context(), BigInteger.valueOf(90), 32, RANDOM); + E2E.assertScriptRejected(auction.bid(backend, late, lot, lateBid, + auction.proofs().proveBid(pkh(late), lot.deposit(), lot.reserve(), lot.pkU(), lot.pkV(), lateBid), + DevKit.slotAt(backend, DevKit.chainTimeMillis(backend) + 60_000)), "a bid after the window"); + + // The auctioneer decrypts and settles: Bob (bid #2), the earliest of the two highest, at 70. + JubjubDiscreteLog table = JubjubDiscreteLog.forBound((1L << 32) - 1); + List amounts = new ArrayList<>(); + for (Lot.Bid b : lot.bids()) { + ElGamalCiphertext ct = ElGamal.admit(RawElGamalCiphertext.fromAffine(b.aU(), b.aV(), b.bU(), b.bV()), + keys.context(), 32, s -> true); + amounts.add(ElGamal.decryptWithSecret(ct, keys.elgamal(), (1L << 32) - 1, table)); + } + assertEquals(List.of(40L, 70L, 70L), amounts, "the auctioneer reads every bid"); + Lot settling = lot; + assertThrows(RuntimeException.class, () -> auction.proofs().proveSettle(settling, 3, 70, + keys.elgamal().secretScalar(), amounts), "the later equal bid cannot be named the winner"); + ok(auction.settle(backend, auctioneer, lot, 2, 70, auction.proofs().proveSettle(lot, 2, 70, + keys.elgamal().secretScalar(), amounts)), "settle (3 bids)", backend); + assertTrue(auction.lots(backend).stream().noneMatch(l -> l.token().equals(settling.token())), "the lot is closed"); + String item = lot.itemUnit(); + boolean bobHasItem = backend.getUtxoService().getUtxos(AuctionScript.enterprise(pkh(bob)), 20, 1).getValue().stream() + .anyMatch(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().equals(item))); + assertTrue(bobHasItem, "the winner receives the item"); + assertEquals(BigInteger.valueOf(70_000_000L), lovelaceAt(backend, AuctionScript.enterprise(pkh(seller))), "the seller receives the price"); + assertEquals(BigInteger.valueOf(100_000_000L), lovelaceAt(backend, AuctionScript.enterprise(pkh(alice))), "Alice's deposit is returned"); + assertEquals(BigInteger.valueOf(100_000_000L), lovelaceAt(backend, AuctionScript.enterprise(pkh(carol))), "Carol's deposit is returned"); + assertEquals(BigInteger.valueOf(lot.lotAda() + 30_000_000L), lovelaceAt(backend, AuctionScript.enterprise(pkh(bob))), + "Bob receives the item with the lot ADA and his change (100 − 70)"); + + // A second lot, one bid, never settled: refunded after its deadline. + Lot second = open(backend, auction, seller, key, "Vase"); + second = bid(backend, auction, alice, second, key, 25); + while (DevKit.chainTimeMillis(backend) < second.settleBy() + 2_000) Thread.sleep(3_000); + BigInteger aliceBefore = lovelaceAt(backend, AuctionScript.enterprise(pkh(alice))); + BigInteger sellerBefore = lovelaceAt(backend, AuctionScript.enterprise(pkh(seller))); + ok(auction.refund(backend, carol, second), "refund", backend); + assertEquals(aliceBefore.add(BigInteger.valueOf(100_000_000L)), lovelaceAt(backend, AuctionScript.enterprise(pkh(alice))), + "the refund returns Alice's deposit"); + assertEquals(sellerBefore.add(BigInteger.valueOf(second.lotAda())), lovelaceAt(backend, AuctionScript.enterprise(pkh(seller))), + "the refund returns the item with the lot ADA to the seller"); + } + + private static BigInteger lovelaceAt(BackendService backend, String address) throws Exception { + BigInteger sum = BigInteger.ZERO; + var r = backend.getUtxoService().getUtxos(address, 100, 1); + if (!r.isSuccessful() || r.getValue() == null) return sum; + for (Utxo u : r.getValue()) { + for (var a : u.getAmount()) if (a.getUnit().equals("lovelace")) sum = sum.add(a.getQuantity()); + } + return sum; + } + + private static Lot open(BackendService backend, AuctionScript auction, Account seller, AdmittedAuditor key, String name) + throws Exception { + String itemName = name + "#" + RANDOM.nextInt(1_000_000); + DevKit.waitForTx(backend, AuctionScript.mintItem(backend, seller, itemName).getValue()); + long now = DevKit.chainTimeMillis(backend); + var opened = auction.open(backend, seller, AuctionScript.itemUnit(seller, itemName), 100, 10, + now + BIDDING_MILLIS, now + BIDDING_MILLIS + SETTLE_MILLIS, key); + ok(opened, "open", backend); + return auction.lots(backend).stream().filter(l -> l.utxo().getTxHash().equals(opened.getValue())).findFirst().orElseThrow(); + } + + private static Lot bid(BackendService backend, AuctionScript auction, Account bidder, Lot lot, AdmittedAuditor key, long amount) + throws Exception { + ElGamalEncryption e = ElGamal.encryptWithOpening(key.context(), BigInteger.valueOf(amount), 32, RANDOM); + var result = auction.bid(backend, bidder, lot, e, + auction.proofs().proveBid(pkh(bidder), lot.deposit(), lot.reserve(), lot.pkU(), lot.pkV(), e)); + ok(result, "bid (" + amount + ")", backend); + return auction.lots(backend).stream().filter(l -> l.utxo().getTxHash().equals(result.getValue())).findFirst().orElseThrow(); + } + + private static void ok(Result result, String what, BackendService backend) throws Exception { + assertTrue(result.isSuccessful(), what + ": " + result.getResponse()); + var budget = DevKit.lastBudget(); + System.out.printf("[DevKit auction %s] tx %s steps=%d (%.1f%%) mem=%d (%.1f%%)%n", what, result.getValue(), + budget.steps(), budget.stepsPercent(), budget.memory(), budget.memoryPercent()); + if (!what.startsWith("registry")) { + assertTrue(budget.stepsPercent() <= 80 && budget.memoryPercent() <= 80, what + " exceeds the 80% gate"); + } + DevKit.waitForTx(backend, result.getValue()); + } + + private static byte[] pkh(Account a) { + return a.hdKeyPair().getPublicKey().getKeyHash(); + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/SealedBidAuctionVmTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/SealedBidAuctionVmTest.java new file mode 100644 index 0000000..514adc3 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/SealedBidAuctionVmTest.java @@ -0,0 +1,563 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.auction; + +import com.bloxbean.cardano.client.crypto.Blake2bUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.circuit.BidProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.onchain.SealedBidAuction; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.AdmittedAuditor; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.AuditorKeys; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.KeyPossession; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.RegistryEntry; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.RegistryTestData; +import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.VerificationKeys; +import org.julclang.core.PlutusData; +import org.julclang.core.Program; +import org.julclang.ledger.Address; +import org.julclang.ledger.Credential; +import org.julclang.ledger.Interval; +import org.julclang.ledger.IntervalBound; +import org.julclang.ledger.IntervalBoundType; +import org.julclang.ledger.OutputDatum; +import org.julclang.ledger.PolicyId; +import org.julclang.ledger.PubKeyHash; +import org.julclang.ledger.ScriptHash; +import org.julclang.ledger.StakingCredential; +import org.julclang.ledger.TokenName; +import org.julclang.ledger.TxId; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxOut; +import org.julclang.ledger.TxOutRef; +import org.julclang.ledger.Value; +import org.julclang.testkit.ContractTest; +import org.julclang.testkit.ScriptContextTestBuilder; +import org.julclang.testkit.TestDataBuilder; +import org.julclang.vm.EvalResult; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.zeroj.circuit.lib.jubjub.ElGamal; +import org.zeroj.circuit.lib.jubjub.ElGamalEncryption; +import org.zeroj.circuit.lib.jubjub.JubjubCurve; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; +import org.zeroj.onchain.julc.groth16.codec.SnarkjsToCardano; + +import java.math.BigInteger; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * {@code SealedBidAuction} in the Plutus VM (ADR-0008): Open, Bid, Settle (n = 1, 2, 3), NoBids and + * Refund are accepted, with their complete-transaction cost checked against the 80% gate, and every + * mutation of ADR-0008's verification list is rejected. + */ +class SealedBidAuctionVmTest extends ContractTest { + + static final long STEP_LIMIT = 10_000_000_000L; + static final long MEMORY_LIMIT = 16_500_000L; + static final SecureRandom RANDOM = new SecureRandom(); + static final byte[] POLICY = filled(28, (byte) 0xac); + static final byte[] REGISTRY_POLICY = filled(28, (byte) 0x3e); + static final byte[] ITEM_POLICY = filled(28, (byte) 0x17); + static final byte[] ITEM_NAME = "Painting#1".getBytes(); + static final byte[] SELLER = filled(28, (byte) 0x5e); + static final byte[] AUCTIONEER = filled(28, (byte) 0xa1); + static final byte[] ALICE = filled(28, (byte) 0x0a); + static final byte[] BOB = filled(28, (byte) 0x0b); + static final byte[] CAROL = filled(28, (byte) 0x0c); + static final byte[] DAVE = filled(28, (byte) 0x0d); + static final TxOutRef SEED = new TxOutRef(TxId.of(filled(32, (byte) 0x51)), BigInteger.TWO); + static final byte[] T = tokenOf(SEED); + static final long LOT_ADA = 3_000_000; + static final long DEPOSIT = 100; + static final long RESERVE = 10; + static final long BIDDING_ENDS = 1_000_000; + static final long SETTLE_BY = 1_200_000; + static final long MIN_WINDOW = 60_000; + static final BigInteger ADA = BigInteger.valueOf(1_000_000); + static final Address LOT_ADDRESS = new Address(new Credential.ScriptCredential(ScriptHash.of(POLICY)), Optional.empty()); + static final Address STAKED_LOT = new Address(LOT_ADDRESS.credential(), Optional.of(new StakingCredential.StakingHash( + new Credential.PubKeyCredential(PubKeyHash.of(filled(28, (byte) 0x5a)))))); + + static AuctionProofs proofs; + static Program program; + static AuditorKeys auctioneerKeys; + static RegistryEntry entry; + static AdmittedAuditor auctioneer; + static List encs = new ArrayList<>(); + static List bidProofs = new ArrayList<>(); + static final List AMOUNTS = List.of(40L, 70L, 70L); + static final List BIDDERS = List.of(ALICE, BOB, CAROL); + + @BeforeAll + static void setup() { + proofs = new AuctionProofs(); + KeyPossession possession = new KeyPossession(); + auctioneerKeys = AuditorKeys.generate(RANDOM); + entry = auctioneerKeys.entry(REGISTRY_POLICY, AUCTIONEER, 0, possession); + auctioneer = AdmittedAuditor.admit(REGISTRY_POLICY, entry, possession); + program = new SealedBidAuctionVmTest().compileValidator(SealedBidAuction.class, Path.of("src/main/java")).program() + .applyParams(PlutusData.bytes(REGISTRY_POLICY), PlutusData.bytes("REG".getBytes()), + PlutusData.integer(BigInteger.valueOf(MIN_WINDOW)), PlutusData.integer(BigInteger.valueOf(2_000_000)), + PlutusData.bytes(VerificationKeys.hash(proofs.bid().compressedVk())), + PlutusData.bytes(VerificationKeys.hash(proofs.settle(1).compressedVk())), + PlutusData.bytes(VerificationKeys.hash(proofs.settle(2).compressedVk())), + PlutusData.bytes(VerificationKeys.hash(proofs.settle(3).compressedVk()))); + for (int i = 0; i < 3; i++) { + ElGamalEncryption e = ElGamal.encryptWithOpening(auctioneer.context(), BigInteger.valueOf(AMOUNTS.get(i)), 32, RANDOM); + encs.add(e); + bidProofs.add(ProverToCardano.compressProof(proofs.proveBid(BIDDERS.get(i), DEPOSIT, RESERVE, + auctioneer.pkU(), auctioneer.pkV(), e))); + } + specials(); + } + + /** A bid with a valid proof for exactly its bidder and ciphertext. */ + record Special(byte[] bidder, List ct, SnarkjsToCardano.ProofCompressed proof) {} + + static final Map SPECIAL = new EnumMap<>(BidMutation.class); + + /** Proves {@code inputs} and checks the proof off-chain (the positive control), then compresses it. */ + static Special special(byte[] bidder, BidProofCircuit.Inputs inputs) { + var proof = proofs.bid().prove(inputs.toWitnessMap()); + var pub = BidProofCircuit.publicInputs(inputs); + assertTrue(proofs.bid().verify(proof, pub), "positive control: the mutation's own proof is valid"); + return new Special(bidder, pub.subList(5, 9), ProverToCardano.compressProof(proof)); + } + + static Special fresh(byte[] bidder, long amount) { + ElGamalEncryption e = ElGamal.encryptWithOpening(auctioneer.context(), BigInteger.valueOf(amount), 32, RANDOM); + return special(bidder, AuctionProofs.bidInputs(bidder, DEPOSIT, RESERVE, auctioneer.pkU(), auctioneer.pkV(), e)); + } + + static void specials() { + SPECIAL.put(BidMutation.NONE, new Special(CAROL, List.of(encs.get(2).ciphertext().handle().affineU(), + encs.get(2).ciphertext().handle().affineV(), encs.get(2).ciphertext().blinded().affineU(), + encs.get(2).ciphertext().blinded().affineV()), bidProofs.get(2))); + SPECIAL.put(BidMutation.BY_SELLER, fresh(SELLER, 50)); + SPECIAL.put(BidMutation.BY_AUCTIONEER, fresh(AUCTIONEER, 50)); + SPECIAL.put(BidMutation.REPEATED_BIDDER, fresh(ALICE, 50)); + SPECIAL.put(BidMutation.FOURTH_BID, fresh(DAVE, 50)); + // Carol re-uses Alice's ciphertext (same handle A), proving its opening under her own key hash. + SPECIAL.put(BidMutation.COPIED_HANDLE, special(CAROL, + AuctionProofs.bidInputs(CAROL, DEPOSIT, RESERVE, auctioneer.pkU(), auctioneer.pkV(), encs.get(0)))); + // k = l: A = [l]·G is the identity, B = [m]·G. A valid R_enc proof, but a lot that could never settle. + BigInteger l = JubjubCurve.SUBGROUP_ORDER; + var b = JubjubPoint.SUBGROUP_GENERATOR.scalarMul(BigInteger.valueOf(50)).normalized(); + BigInteger carol = AuctionProofs.bidderInt(CAROL); + var identity = BidProofCircuit.inputs() + .bidderInt(carol).deposit(DEPOSIT).reserve(RESERVE).pkU(auctioneer.pkU()).pkV(auctioneer.pkV()) + .aU(BigInteger.ZERO).aV(BigInteger.ONE).bU(b.affineU()).bV(b.affineV()) + .bid(50).k(l).bidderSquared(carol.multiply(carol).mod(Fields.FR)); + SPECIAL.put(BidMutation.IDENTITY_HANDLE, special(CAROL, identity)); + } + + // ------------------------------------------------------------------ data + + static PlutusData bid(int i) { + var ct = encs.get(i).ciphertext(); + return PlutusData.constr(0, PlutusData.bytes(BIDDERS.get(i)), PlutusData.integer(ct.handle().affineU()), + PlutusData.integer(ct.handle().affineV()), PlutusData.integer(ct.blinded().affineU()), + PlutusData.integer(ct.blinded().affineV())); + } + + static List lotFields(List bids) { + return new ArrayList<>(List.of(PlutusData.bytes(SELLER), PlutusData.bytes(AUCTIONEER), PlutusData.bytes(ITEM_POLICY), + PlutusData.bytes(ITEM_NAME), PlutusData.integer(BigInteger.valueOf(LOT_ADA)), + PlutusData.integer(BigInteger.valueOf(DEPOSIT)), PlutusData.integer(BigInteger.valueOf(RESERVE)), + PlutusData.integer(BigInteger.valueOf(BIDDING_ENDS)), PlutusData.integer(BigInteger.valueOf(SETTLE_BY)), + PlutusData.integer(auctioneer.pkU()), PlutusData.integer(auctioneer.pkV()), PlutusData.integer(BigInteger.ZERO), + PlutusData.list(bids.toArray(new PlutusData[0])))); + } + + static PlutusData lot(List bids) { + return PlutusData.constr(0, lotFields(bids).toArray(new PlutusData[0])); + } + + static List bids(int n) { + List out = new ArrayList<>(); + for (int i = 0; i < n; i++) out.add(bid(i)); + return out; + } + + static Value lotValue(int bids) { + return Value.lovelace(BigInteger.valueOf(LOT_ADA).add(BigInteger.valueOf(DEPOSIT * bids).multiply(ADA))) + .merge(Value.singleton(PolicyId.of(ITEM_POLICY), TokenName.of(ITEM_NAME), BigInteger.ONE)) + .merge(Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.ONE)); + } + + static TxInInfo registryInput(PlutusData entryDatum) { + Value v = Value.lovelace(BigInteger.valueOf(8_000_000)) + .merge(Value.singleton(PolicyId.of(REGISTRY_POLICY), TokenName.of("REG".getBytes()), BigInteger.ONE)); + return new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut( + new Address(new Credential.ScriptCredential(ScriptHash.of(REGISTRY_POLICY)), Optional.empty()), v, + new OutputDatum.OutputDatumInline(entryDatum), Optional.empty())); + } + + static Interval upTo(long t) { + return new Interval(new IntervalBound(new IntervalBoundType.NegInf(), true), + new IntervalBound(new IntervalBoundType.Finite(BigInteger.valueOf(t)), false)); + } + + static Interval between(long from, long to) { + return new Interval(new IntervalBound(new IntervalBoundType.Finite(BigInteger.valueOf(from)), true), + new IntervalBound(new IntervalBoundType.Finite(BigInteger.valueOf(to)), false)); + } + + static Interval from(long t) { + return new Interval(new IntervalBound(new IntervalBoundType.Finite(BigInteger.valueOf(t)), true), + new IntervalBound(new IntervalBoundType.PosInf(), true)); + } + + static Interval always() { + return new Interval(new IntervalBound(new IntervalBoundType.NegInf(), true), new IntervalBound(new IntervalBoundType.PosInf(), true)); + } + + static TxOut payout(byte[] pkh, long lovelace, boolean withItem, boolean tagged, boolean staked) { + return payout(pkh, lovelace, withItem, tagged ? POLICY : filled(28, (byte) 0x99), tagged, staked); + } + + /** A payout tagged {@code Payout(policy, T)} (or with another token name when not {@code tagged}). */ + static TxOut payout(byte[] pkh, long lovelace, boolean withItem, byte[] policy, boolean tagged, boolean staked) { + Address to = new Address(new Credential.PubKeyCredential(PubKeyHash.of(pkh)), staked + ? Optional.of(new StakingCredential.StakingHash(new Credential.PubKeyCredential(PubKeyHash.of(filled(28, (byte) 0x66))))) + : Optional.empty()); + Value v = Value.lovelace(BigInteger.valueOf(lovelace)); + if (withItem) v = v.merge(Value.singleton(PolicyId.of(ITEM_POLICY), TokenName.of(ITEM_NAME), BigInteger.ONE)); + PlutusData tag = PlutusData.constr(0, PlutusData.bytes(policy), PlutusData.bytes(tagged ? T : filled(32, (byte) 1))); + return new TxOut(to, v, new OutputDatum.OutputDatumInline(tag), Optional.empty()); + } + + // ------------------------------------------------------------------ Open + + enum OpenMutation { + NONE, TOKEN_NOT_DERIVED, SCRIPT_INPUT_SPENT, TWO_TOKENS, ITEM_MISSING, LOT_ADA_MISMATCH, LOT_ADA_BELOW_MIN, + KEY_NOT_REGISTRY, GENERATION_WRONG, AUCTIONEER_NOT_ENTRY, WINDOW_TOO_SHORT, AFTER_BIDDING_ENDS, NO_UPPER_BOUND, + RESERVE_ABOVE_DEPOSIT, RESERVE_ONE, NOT_SIGNED, BIDS_NOT_EMPTY, STAKED_OUTPUT, EXTRA_ASSET, REGISTRY_MISSING, + TWO_TOKEN_NAMES, DEPOSIT_2_POW_32, ITEM_NAME_33_BYTES, ITEM_UNDER_OWN_POLICY + } + + @Test + @DisplayName("Open: a seller mints a one-shot lot token and locks the item; every mutation is rejected") + void open() { + var honest = evaluate(program, openContext(OpenMutation.NONE)); + assertInstanceOf(EvalResult.Success.class, honest); + report("open (mint)", honest, null); + for (OpenMutation m : OpenMutation.values()) { + if (m != OpenMutation.NONE && evaluate(program, openContext(m)) instanceof EvalResult.Success) fail("Open accepted " + m); + } + } + + private PlutusData openContext(OpenMutation m) { + Value mint = Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.valueOf(m == OpenMutation.TWO_TOKENS ? 2 : 1)); + if (m == OpenMutation.TWO_TOKEN_NAMES) mint = mint.merge(Value.singleton(PolicyId.of(POLICY), TokenName.of(filled(32, (byte) 3)), BigInteger.ONE)); + var b = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).mint(mint).redeemer(PlutusData.constr(0, PlutusData.integer(0))); + b.validRange(switch (m) { + case AFTER_BIDDING_ENDS -> upTo(BIDDING_ENDS + 1000); + case NO_UPPER_BOUND -> always(); + default -> upTo(BIDDING_ENDS - 10_000); + }); + if (m != OpenMutation.NOT_SIGNED) b.signer(SELLER); + TxOutRef seed = m == OpenMutation.TOKEN_NOT_DERIVED ? TestDataBuilder.randomTxOutRef_typed() : SEED; + b.input(new TxInInfo(seed, new TxOut(new Address(new Credential.PubKeyCredential(PubKeyHash.of(SELLER)), Optional.empty()), + Value.lovelace(BigInteger.valueOf(50_000_000)), new OutputDatum.NoOutputDatum(), Optional.empty()))); + if (m == OpenMutation.SCRIPT_INPUT_SPENT) { + b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(LOT_ADDRESS, Value.lovelace(BigInteger.valueOf(5_000_000)), + new OutputDatum.OutputDatumInline(PlutusData.integer(0)), Optional.empty()))); + } + List f = lotFields(List.of()); + switch (m) { + case LOT_ADA_BELOW_MIN -> f.set(4, PlutusData.integer(BigInteger.valueOf(1_000_000))); + case KEY_NOT_REGISTRY -> f.set(9, PlutusData.integer(auctioneer.pkU().add(BigInteger.ONE))); + case GENERATION_WRONG -> f.set(11, PlutusData.integer(BigInteger.ONE)); + case AUCTIONEER_NOT_ENTRY -> f.set(1, PlutusData.bytes(DAVE)); + case WINDOW_TOO_SHORT -> f.set(8, PlutusData.integer(BigInteger.valueOf(BIDDING_ENDS + MIN_WINDOW - 1))); + case RESERVE_ABOVE_DEPOSIT -> f.set(6, PlutusData.integer(BigInteger.valueOf(DEPOSIT + 1))); + case RESERVE_ONE -> f.set(6, PlutusData.integer(BigInteger.ONE)); + case BIDS_NOT_EMPTY -> f.set(12, PlutusData.list(bid(0))); + case DEPOSIT_2_POW_32 -> f.set(5, PlutusData.integer(BigInteger.ONE.shiftLeft(32))); + case ITEM_NAME_33_BYTES -> f.set(3, PlutusData.bytes(filled(33, (byte) 'x'))); + case ITEM_UNDER_OWN_POLICY -> f.set(2, PlutusData.bytes(POLICY)); + default -> { } + } + Value v = Value.lovelace(BigInteger.valueOf(m == OpenMutation.LOT_ADA_BELOW_MIN ? 1_000_000 + : m == OpenMutation.LOT_ADA_MISMATCH ? LOT_ADA + 1 : LOT_ADA)) + .merge(Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.valueOf(m == OpenMutation.TWO_TOKENS ? 2 : 1))); + if (m != OpenMutation.ITEM_MISSING) v = v.merge(Value.singleton(PolicyId.of(ITEM_POLICY), TokenName.of(ITEM_NAME), BigInteger.ONE)); + if (m == OpenMutation.EXTRA_ASSET) v = v.merge(Value.singleton(PolicyId.of(filled(28, (byte) 0x77)), TokenName.of("Z".getBytes()), BigInteger.ONE)); + b.output(new TxOut(m == OpenMutation.STAKED_OUTPUT ? STAKED_LOT : LOT_ADDRESS, v, + new OutputDatum.OutputDatumInline(PlutusData.constr(0, f.toArray(new PlutusData[0]))), Optional.empty())); + if (m != OpenMutation.REGISTRY_MISSING) b.referenceInput(registryInput(RegistryTestData.datum(entry))); + return b.buildPlutusData(); + } + + // ------------------------------------------------------------------ Bid + + enum BidMutation { + NONE, LATE, NO_UPPER_BOUND, UNSIGNED, BY_SELLER, BY_AUCTIONEER, REPEATED_BIDDER, FOURTH_BID, DEPOSIT_OFF_BY_ONE, + EARLIER_BID_CHANGED, COPIED_HANDLE, IDENTITY_HANDLE, STAKED_OUTPUT, TOKENLESS_INPUT, EXTRA_ASSET, MINT_DURING_BID, + PROOF_FOR_OTHER_BIDDER, WRONG_VK, TWO_LOTS, DEPOSIT_TOO_MUCH, REFERENCE_SCRIPT_ON_LOT, + // boundary cases, checked separately (AT_DEADLINE is accepted) + AT_DEADLINE, JUST_LATE + } + + @Test + @DisplayName("Bid: the third bid is appended with its deposit and proof; every mutation is rejected") + void placeBid() { + var honest = evaluate(program, bidContext(BidMutation.NONE)); + assertInstanceOf(EvalResult.Success.class, honest); + report("bid (spend, third bid)", honest, null); + for (BidMutation m : BidMutation.values()) { + if (m != BidMutation.NONE && m != BidMutation.AT_DEADLINE + && evaluate(program, bidContext(m)) instanceof EvalResult.Success) fail("Bid accepted " + m); + } + // Boundaries: an (exclusive) upper bound at exactly biddingEnds is in time; one millisecond later is not. + assertInstanceOf(EvalResult.Success.class, evaluate(program, bidContext(BidMutation.AT_DEADLINE))); + assertTrue(evaluate(program, bidContext(BidMutation.JUST_LATE)) instanceof EvalResult.Failure); + } + + /** Bid #3 (Carol) onto a lot holding Alice's and Bob's bids. */ + private PlutusData bidContext(BidMutation m) { + TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x61)), BigInteger.ZERO); + int already = m == BidMutation.FOURTH_BID ? 3 : 2; + PlutusData before = lot(bids(already)); + // Each guarded mutation carries its own valid proof (checked off-chain in setup), so only the + // targeted rule can refuse it; PROOF_FOR_OTHER_BIDDER alone reuses Carol's proof on purpose. + Special sp = SPECIAL.getOrDefault(m, SPECIAL.get(BidMutation.NONE)); + byte[] bidder = m == BidMutation.PROOF_FOR_OTHER_BIDDER ? DAVE : sp.bidder(); + BigInteger aU = sp.ct().get(0); + BigInteger aV = sp.ct().get(1); + BigInteger bU = sp.ct().get(2); + BigInteger bV = sp.ct().get(3); + SnarkjsToCardano.ProofCompressed p = sp.proof(); + PlutusData newBid = PlutusData.constr(0, PlutusData.bytes(bidder), PlutusData.integer(aU), PlutusData.integer(aV), + PlutusData.integer(bU), PlutusData.integer(bV)); + PlutusData vk = m == BidMutation.WRONG_VK ? VerificationKeys.julcData(proofs.settle(1).compressedVk()) + : VerificationKeys.julcData(proofs.bid().compressedVk()); + PlutusData redeemer = PlutusData.constr(0, PlutusData.bytes(bidder), PlutusData.integer(aU), PlutusData.integer(aV), + PlutusData.integer(bU), PlutusData.integer(bV), + PlutusData.bytes(p.piA()), PlutusData.bytes(p.piB()), PlutusData.bytes(p.piC()), vk); + var b = ScriptContextTestBuilder.spending(ownRef, before).redeemer(redeemer); + b.validRange(switch (m) { + case LATE -> upTo(BIDDING_ENDS + 1000); + case NO_UPPER_BOUND -> always(); + case AT_DEADLINE -> upTo(BIDDING_ENDS); + case JUST_LATE -> upTo(BIDDING_ENDS + 1); + default -> upTo(BIDDING_ENDS - 1000); + }); + if (m != BidMutation.UNSIGNED) b.signer(bidder); + Value in = lotValue(already); + if (m == BidMutation.TOKENLESS_INPUT) { + in = Value.lovelace(BigInteger.valueOf(LOT_ADA).add(BigInteger.valueOf(DEPOSIT * already).multiply(ADA))) + .merge(Value.singleton(PolicyId.of(ITEM_POLICY), TokenName.of(ITEM_NAME), BigInteger.ONE)); + } + b.input(new TxInInfo(ownRef, new TxOut(LOT_ADDRESS, in, new OutputDatum.OutputDatumInline(before), Optional.empty()))); + if (m == BidMutation.TWO_LOTS) { + b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(LOT_ADDRESS, lotValue(0), + new OutputDatum.OutputDatumInline(lot(List.of())), Optional.empty()))); + } + if (m == BidMutation.MINT_DURING_BID) b.mint(Value.singleton(PolicyId.of(POLICY), TokenName.of(filled(32, (byte) 9)), BigInteger.ONE)); + List after = bids(already); + if (m == BidMutation.EARLIER_BID_CHANGED) after.set(0, bid(1)); + after.add(newBid); + BigInteger lovelace = BigInteger.valueOf(LOT_ADA).add(BigInteger.valueOf(DEPOSIT * (already + 1)).multiply(ADA)); + if (m == BidMutation.DEPOSIT_OFF_BY_ONE) lovelace = lovelace.subtract(BigInteger.ONE); + if (m == BidMutation.DEPOSIT_TOO_MUCH) lovelace = lovelace.add(BigInteger.ONE); + Value out = Value.lovelace(lovelace) + .merge(Value.singleton(PolicyId.of(ITEM_POLICY), TokenName.of(ITEM_NAME), BigInteger.ONE)) + .merge(Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.ONE)); + if (m == BidMutation.EXTRA_ASSET) out = out.merge(Value.singleton(PolicyId.of(filled(28, (byte) 0x77)), TokenName.of("Z".getBytes()), BigInteger.ONE)); + b.output(new TxOut(m == BidMutation.STAKED_OUTPUT ? STAKED_LOT : LOT_ADDRESS, out, + new OutputDatum.OutputDatumInline(lot(after)), + m == BidMutation.REFERENCE_SCRIPT_ON_LOT ? Optional.of(ScriptHash.of(filled(28, (byte) 0x42))) : Optional.empty())); + return b.buildPlutusData(); + } + + // ------------------------------------------------------------------ Settle + + enum SettleMutation { + NONE, EARLY, LATE, NO_UPPER_BOUND, UNDERPAID_SELLER, UNDERPAID_WINNER, UNDERPAID_LOSER, UNTAGGED_PAYOUT, STAKED_PAYOUT, + NOT_BURNED, W_OUT_OF_RANGE, P_BELOW_RESERVE, PROOF_OVER_SUBSET, SCRIPT_OUTPUT_REMAINS, ITEM_TO_ANOTHER, WRONG_VK, + OTHER_POLICY_TAG, TWO_LOTS + } + + @Test + @DisplayName("Settle: n = 1, 2, 3 accepted with cost measured; every mutation is rejected") + void settle() { + for (int n = 1; n <= 3; n++) { + var spend = evaluate(program, settleContext(SettleMutation.NONE, n, true)); + assertInstanceOf(EvalResult.Success.class, spend); + var burn = evaluate(program, settleContext(SettleMutation.NONE, n, false)); + assertInstanceOf(EvalResult.Success.class, burn); + report("settle n=" + n + " (spend + burn)", spend, burn); + } + for (SettleMutation m : SettleMutation.values()) { + if (m != SettleMutation.NONE && evaluate(program, settleContext(m, 3, true)) instanceof EvalResult.Success) { + fail("Settle accepted " + m); + } + } + } + + /** Settles a lot of {@code n} bids (40, 70, 70): the winner is bid #min(n, 2) at its amount. */ + private PlutusData settleContext(SettleMutation m, int n, boolean spending) { + TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x62)), BigInteger.ZERO); + PlutusData datum = lot(bids(n)); + int w = Math.min(n, 2); + long p = AMOUNTS.get(w - 1); + List lotBids = new ArrayList<>(); + int proofBids = m == SettleMutation.PROOF_OVER_SUBSET ? n - 1 : n; + for (int i = 0; i < proofBids; i++) { + var ct = encs.get(i).ciphertext(); + lotBids.add(new Lot.Bid(BIDDERS.get(i), ct.handle().affineU(), ct.handle().affineV(), ct.blinded().affineU(), ct.blinded().affineV())); + } + Lot hostLot = new Lot(null, "", SELLER, AUCTIONEER, ITEM_POLICY, ITEM_NAME, LOT_ADA, DEPOSIT, RESERVE, BIDDING_ENDS, + SETTLE_BY, auctioneer.pkU(), auctioneer.pkV(), 0, lotBids); + var proof = ProverToCardano.compressProof(proofs.proveSettle(hostLot, w, p, + auctioneerKeys.elgamal().secretScalar(), AMOUNTS.subList(0, proofBids))); + long claimedW = m == SettleMutation.W_OUT_OF_RANGE ? n + 1 : w; + long claimedP = m == SettleMutation.P_BELOW_RESERVE ? RESERVE - 1 : p; + PlutusData vk = VerificationKeys.julcData(proofs.settle(m == SettleMutation.WRONG_VK ? (n == 1 ? 2 : 1) : proofBids).compressedVk()); + PlutusData redeemer = PlutusData.constr(1, PlutusData.integer(BigInteger.valueOf(claimedW)), + PlutusData.integer(BigInteger.valueOf(claimedP)), PlutusData.bytes(proof.piA()), PlutusData.bytes(proof.piB()), + PlutusData.bytes(proof.piC()), vk); + var b = spending + ? ScriptContextTestBuilder.spending(ownRef, datum).redeemer(redeemer) + : ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).redeemer(PlutusData.constr(1, PlutusData.integer(0))); + b.validRange(switch (m) { + case EARLY -> between(BIDDING_ENDS - 1000, SETTLE_BY - 1000); + case LATE -> between(BIDDING_ENDS + 1000, SETTLE_BY + 1000); + case NO_UPPER_BOUND -> from(BIDDING_ENDS + 1000); + default -> between(BIDDING_ENDS + 1000, SETTLE_BY - 1000); + }); + b.input(new TxInInfo(ownRef, new TxOut(LOT_ADDRESS, lotValue(n), new OutputDatum.OutputDatumInline(datum), Optional.empty()))); + if (m == SettleMutation.TWO_LOTS) { + // A second authentic lot of the same policy in the same transaction (one burn shown). + b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(LOT_ADDRESS, lotValue(n), + new OutputDatum.OutputDatumInline(datum), Optional.empty()))); + } + if (m != SettleMutation.NOT_BURNED) b.mint(Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.valueOf(-1))); + long deposit = DEPOSIT * 1_000_000; + b.output(payout(SELLER, p * 1_000_000 - (m == SettleMutation.UNDERPAID_SELLER ? 1 : 0), false, true, false)); + for (int i = 0; i < n; i++) { + if (i + 1 == w) { + long amount = LOT_ADA + deposit - p * 1_000_000 - (m == SettleMutation.UNDERPAID_WINNER ? 1 : 0); + byte[] to = m == SettleMutation.ITEM_TO_ANOTHER ? DAVE : BIDDERS.get(i); + b.output(payout(to, amount, true, m != SettleMutation.UNTAGGED_PAYOUT, m == SettleMutation.STAKED_PAYOUT)); + } else { + // OTHER_POLICY_TAG: a loser's refund tagged with the same T under another auction's policy. + byte[] tagPolicy = m == SettleMutation.OTHER_POLICY_TAG ? filled(28, (byte) 0xad) : POLICY; + b.output(payout(BIDDERS.get(i), deposit - (m == SettleMutation.UNDERPAID_LOSER ? 1 : 0), false, tagPolicy, true, false)); + } + } + if (m == SettleMutation.SCRIPT_OUTPUT_REMAINS) { + b.output(new TxOut(LOT_ADDRESS, Value.lovelace(BigInteger.valueOf(2_000_000)), new OutputDatum.OutputDatumInline(datum), Optional.empty())); + } + return b.buildPlutusData(); + } + + // ------------------------------------------------------------------ Burn + + @Test + @DisplayName("Burn: refused with no lot spent, with a positive mint, or with two token names") + void burnNegatives() { + var noLot = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)) + .mint(Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.valueOf(-1))) + .redeemer(PlutusData.constr(1, PlutusData.integer(0))); + assertTrue(evaluate(program, noLot.buildPlutusData()) instanceof EvalResult.Failure, "no lot spent"); + var positive = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)) + .mint(Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.ONE)) + .redeemer(PlutusData.constr(1, PlutusData.integer(0))); + positive.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(LOT_ADDRESS, lotValue(0), + new OutputDatum.OutputDatumInline(lot(List.of())), Optional.empty()))); + assertTrue(evaluate(program, positive.buildPlutusData()) instanceof EvalResult.Failure, "a positive mint under Burn"); + var two = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)) + .mint(Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.valueOf(-1)) + .merge(Value.singleton(PolicyId.of(POLICY), TokenName.of(filled(32, (byte) 4)), BigInteger.valueOf(-1)))) + .redeemer(PlutusData.constr(1, PlutusData.integer(0))); + two.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(LOT_ADDRESS, lotValue(0), + new OutputDatum.OutputDatumInline(lot(List.of())), Optional.empty()))); + assertTrue(evaluate(program, two.buildPlutusData()) instanceof EvalResult.Failure, "two token names burned"); + } + + // ------------------------------------------------------------------ Refund and NoBids + + enum CloseMutation { NONE, EARLY, UNDERPAID_BIDDER, ITEM_NOT_RETURNED, UNTAGGED, OTHER_POLICY_TAG } + + @Test + @DisplayName("Refund after settleBy and NoBids after the window are accepted; their mutations are rejected") + void refundAndNoBids() { + var refund = evaluate(program, refundContext(CloseMutation.NONE)); + assertInstanceOf(EvalResult.Success.class, refund); + report("refund (spend, 3 bids)", refund, null); + for (CloseMutation m : CloseMutation.values()) { + if (m != CloseMutation.NONE && evaluate(program, refundContext(m)) instanceof EvalResult.Success) fail("Refund accepted " + m); + } + assertInstanceOf(EvalResult.Success.class, evaluate(program, noBidsContext(0, true, BIDDING_ENDS + 1000))); + assertTrue(evaluate(program, noBidsContext(1, true, BIDDING_ENDS + 1000)) instanceof EvalResult.Failure, "NoBids with a bid"); + assertTrue(evaluate(program, noBidsContext(0, false, BIDDING_ENDS + 1000)) instanceof EvalResult.Failure, "NoBids unsigned"); + assertTrue(evaluate(program, noBidsContext(0, true, BIDDING_ENDS - 1000)) instanceof EvalResult.Failure, "NoBids early"); + } + + private PlutusData refundContext(CloseMutation m) { + TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x63)), BigInteger.ZERO); + PlutusData datum = lot(bids(3)); + var b = ScriptContextTestBuilder.spending(ownRef, datum).redeemer(PlutusData.constr(3, PlutusData.integer(0))); + b.validRange(from(m == CloseMutation.EARLY ? SETTLE_BY - 1000 : SETTLE_BY + 1000)); + b.input(new TxInInfo(ownRef, new TxOut(LOT_ADDRESS, lotValue(3), new OutputDatum.OutputDatumInline(datum), Optional.empty()))); + b.mint(Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.valueOf(-1))); + b.output(payout(SELLER, LOT_ADA, m != CloseMutation.ITEM_NOT_RETURNED, m != CloseMutation.UNTAGGED, false)); + for (int i = 0; i < 3; i++) { + byte[] tagPolicy = m == CloseMutation.OTHER_POLICY_TAG && i == 0 ? filled(28, (byte) 0xad) : POLICY; + b.output(payout(BIDDERS.get(i), DEPOSIT * 1_000_000 - (m == CloseMutation.UNDERPAID_BIDDER && i == 1 ? 1 : 0), false, + tagPolicy, true, false)); + } + return b.buildPlutusData(); + } + + private PlutusData noBidsContext(int bids, boolean signed, long from) { + TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x64)), BigInteger.ZERO); + PlutusData datum = lot(bids(bids)); + var b = ScriptContextTestBuilder.spending(ownRef, datum).redeemer(PlutusData.constr(2, PlutusData.integer(0))); + b.validRange(from(from)); + if (signed) b.signer(SELLER); + b.input(new TxInInfo(ownRef, new TxOut(LOT_ADDRESS, lotValue(bids), new OutputDatum.OutputDatumInline(datum), Optional.empty()))); + b.mint(Value.singleton(PolicyId.of(POLICY), TokenName.of(T), BigInteger.valueOf(-1))); + b.output(payout(SELLER, LOT_ADA, true, true, false)); + return b.buildPlutusData(); + } + + // ------------------------------------------------------------------ + + /** Prints the complete transaction's cost and asserts ADR-0055's 80% gate on both limits. */ + private void report(String what, EvalResult a, EvalResult b) { + long cpu = a.budgetConsumed().cpuSteps() + (b == null ? 0 : b.budgetConsumed().cpuSteps()); + long mem = a.budgetConsumed().memoryUnits() + (b == null ? 0 : b.budgetConsumed().memoryUnits()); + System.out.printf("[SealedBidAuction %s] cpu=%d (%.1f%% of steps) mem=%d (%.1f%% of memory)%n", + what, cpu, 100.0 * cpu / STEP_LIMIT, mem, 100.0 * mem / MEMORY_LIMIT); + assertTrue(cpu <= STEP_LIMIT * 8 / 10 && mem <= MEMORY_LIMIT * 8 / 10, what + " exceeds the 80% gate"); + } + + static byte[] tokenOf(TxOutRef ref) { + byte[] bytes = Arrays.copyOf(ref.txId().hash(), 34); + int index = ref.index().intValueExact(); + bytes[32] = (byte) (index >>> 8); + bytes[33] = (byte) index; + return Blake2bUtil.blake2bHash256(bytes); + } + + static byte[] filled(int length, byte value) { + byte[] out = new byte[length]; + Arrays.fill(out, value); + return out; + } +} From a8cc8765167e56299c519e2b94d2639e304ad626 Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 10 Oct 2026 19:33:01 +0800 Subject: [PATCH 07/12] build: add a root Gradle wrapper (9.2.0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The root build.gradle registers the aggregate tasks (buildAllUsecases, testAllUsecases, ...) but the repository had no root wrapper, so they needed a locally installed Gradle. The wrapper matches the modules' Gradle 9.2.0; gradle-wrapper.jar is the official one (sha256 423cb469…e8d9, as published at services.gradle.org). README: use ./gradlew, and ./gradlew -p for one module's tasks. Co-Authored-By: Claude Opus 5.5 --- README.md | 15 +- gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 45633 bytes gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 248 +++++++++++++++++++++++ gradlew.bat | 93 +++++++++ 5 files changed, 359 insertions(+), 4 deletions(-) create mode 100644 gradle/wrapper/gradle-wrapper.jar create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100755 gradlew create mode 100644 gradlew.bat diff --git a/README.md b/README.md index 4305ca6..d4a33c9 100644 --- a/README.md +++ b/README.md @@ -250,14 +250,21 @@ docker volume rm zeroj-usecases_compliance-credential-plonk-cache From the repository root: ```bash -# If Gradle is installed locally, use the root aggregate tasks: -gradle buildAllUsecasesNoTests -gradle testAllUsecases +# Root aggregate tasks (each runs the module's own wrapper): +./gradlew buildAllUsecasesNoTests +./gradlew testAllUsecases # Or use the repo script, which runs each module's wrapper: ./build-all.sh build -x test ``` +Each module is a standalone Gradle build, so the root wrapper can also run one module's tasks +with `-p`, for example the Pedersen demo UI: + +```bash +./gradlew -p pedersen-commitments bootRun -PwithFrontend # http://localhost:8093 +``` + To test against a local ZeroJ build: ```bash @@ -265,7 +272,7 @@ cd ../zeroj ./gradlew publishToMavenLocal cd ../zeroj-usecases -gradle buildAllUsecasesNoTests -PzerojVersion= +./gradlew buildAllUsecasesNoTests -PzerojVersion= ``` `` is the version the ZeroJ build published (a `-SNAPSHOT` version is diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..f8e1ee3125fe0768e9a76ee977ac089eb657005e GIT binary patch literal 45633 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�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 literal 0 HcmV?d00001 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..bad7c24 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..adff685 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega From db93967e289ea9c919a4c23e82e7dd9af8dc8675 Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 10 Oct 2026 19:42:05 +0800 Subject: [PATCH 08/12] build: pin ZeroJ 0.1.0-pre13-458bfb1-SNAPSHOT from the BloxBean snapshot repository ZeroJ's bloxbean-snapshot workflow (run 38048405332, main 458bfb1) publishes commit snapshots to https://repo.bloxbean.org/maven/snapshots. Every usecase build now lists that repository, restricted to snapshots of the org.zeroj group, so the pin resolves without a local ZeroJ publish. 458bfb1 differs from the previous pin 1e78c6f only in ZeroJ's snapshot workflow. The published jars' classes are identical to the 1e78c6f build; the only resource difference is the order of validators in zeroj-onchain-julc's plutus.json (same compiled code and hashes). Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++++ account-ownership/cli/build.gradle | 1 + account-ownership/ui/build.gradle | 1 + digital-product-passport/build.gradle | 8 ++++++++ docs/adr/0007-confidential-notes-in-pedersen-demos.md | 2 +- .../minimal-circuits/batch-threshold-matrix/build.gradle | 8 ++++++++ .../plonk/compliance-credential/build.gradle | 8 ++++++++ .../minimal-circuits/plonk/proof-of-reserves/build.gradle | 8 ++++++++ .../minimal-circuits/zk-mpf-private-registry/build.gradle | 8 ++++++++ identity-kyc/build.gradle | 8 ++++++++ nft-ownership/build.gradle | 8 ++++++++ pedersen-commitments/build.gradle | 8 ++++++++ personhood-airdrop/build.gradle | 8 ++++++++ private-voting/build.gradle | 8 ++++++++ proof-of-reserves/build.gradle | 1 + reusable-kyc/build.gradle | 8 ++++++++ selective-disclosure/build.gradle | 8 ++++++++ version.properties | 5 +++-- 18 files changed, 107 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d4a33c9..05f7751 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,10 @@ with `-p`, for example the Pedersen demo UI: ./gradlew -p pedersen-commitments bootRun -PwithFrontend # http://localhost:8093 ``` +`zerojVersion` in `version.properties` may name a ZeroJ commit snapshot +(`--SNAPSHOT`); builds resolve those from +`https://repo.bloxbean.org/maven/snapshots` (restricted to the `org.zeroj` group). + To test against a local ZeroJ build: ```bash diff --git a/account-ownership/cli/build.gradle b/account-ownership/cli/build.gradle index 7e26532..2387d93 100644 --- a/account-ownership/cli/build.gradle +++ b/account-ownership/cli/build.gradle @@ -31,6 +31,7 @@ repositories { mavenLocal() mavenCentral() maven { url = uri("https://central.sonatype.com/repository/maven-snapshots"); content { snapshotsOnly() } } + maven { url = uri("https://repo.bloxbean.org/maven/snapshots"); content { snapshotsOnly(); includeGroup("org.zeroj") } } maven { url = uri("https://repo.spring.io/milestone") } } diff --git a/account-ownership/ui/build.gradle b/account-ownership/ui/build.gradle index 7eaca6a..1eb619d 100644 --- a/account-ownership/ui/build.gradle +++ b/account-ownership/ui/build.gradle @@ -16,6 +16,7 @@ repositories { mavenLocal() mavenCentral() maven { url = uri("https://central.sonatype.com/repository/maven-snapshots"); content { snapshotsOnly() } } + maven { url = uri("https://repo.bloxbean.org/maven/snapshots"); content { snapshotsOnly(); includeGroup("org.zeroj") } } maven { url = uri("https://repo.spring.io/milestone") } } diff --git a/digital-product-passport/build.gradle b/digital-product-passport/build.gradle index c2dcb70..f168e11 100644 --- a/digital-product-passport/build.gradle +++ b/digital-product-passport/build.gradle @@ -30,6 +30,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } maven { url = uri("https://repo.spring.io/milestone") } diff --git a/docs/adr/0007-confidential-notes-in-pedersen-demos.md b/docs/adr/0007-confidential-notes-in-pedersen-demos.md index 4878957..dcdb3e5 100644 --- a/docs/adr/0007-confidential-notes-in-pedersen-demos.md +++ b/docs/adr/0007-confidential-notes-in-pedersen-demos.md @@ -451,7 +451,7 @@ their own inputs"): | ID | Scope | |---|---| -| M0 | ZeroJ snapshot `0.1.0-pre13-1e78c6f-SNAPSHOT`; the existing tests stay green. | +| M0 | ZeroJ snapshot `0.1.0-pre13-1e78c6f-SNAPSHOT` (now `0.1.0-pre13-458bfb1-SNAPSHOT` from the BloxBean snapshot repository: same library classes, only ZeroJ's snapshot workflow changed); the existing tests stay green. | | M1 | This ADR and ADR-0008. | | M2 | `AuditorRegistry`, `KeyPossessionProof`, and the key, wallet and auditor helpers. | | M3a | `NoteLedger`, the version 2 circuits, the points migration, and the layout gate. | diff --git a/examples/minimal-circuits/batch-threshold-matrix/build.gradle b/examples/minimal-circuits/batch-threshold-matrix/build.gradle index 7e4fcf2..820b3b2 100644 --- a/examples/minimal-circuits/batch-threshold-matrix/build.gradle +++ b/examples/minimal-circuits/batch-threshold-matrix/build.gradle @@ -25,6 +25,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } } def usecaseVersionsScript = { diff --git a/examples/minimal-circuits/plonk/compliance-credential/build.gradle b/examples/minimal-circuits/plonk/compliance-credential/build.gradle index c0c2b0c..acb286f 100644 --- a/examples/minimal-circuits/plonk/compliance-credential/build.gradle +++ b/examples/minimal-circuits/plonk/compliance-credential/build.gradle @@ -25,6 +25,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } } def usecaseVersionsScript = { diff --git a/examples/minimal-circuits/plonk/proof-of-reserves/build.gradle b/examples/minimal-circuits/plonk/proof-of-reserves/build.gradle index 37e02b0..c165741 100644 --- a/examples/minimal-circuits/plonk/proof-of-reserves/build.gradle +++ b/examples/minimal-circuits/plonk/proof-of-reserves/build.gradle @@ -25,6 +25,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } } def usecaseVersionsScript = { diff --git a/examples/minimal-circuits/zk-mpf-private-registry/build.gradle b/examples/minimal-circuits/zk-mpf-private-registry/build.gradle index f7fdd45..af88e28 100644 --- a/examples/minimal-circuits/zk-mpf-private-registry/build.gradle +++ b/examples/minimal-circuits/zk-mpf-private-registry/build.gradle @@ -25,6 +25,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } } def usecaseVersionsScript = { diff --git a/identity-kyc/build.gradle b/identity-kyc/build.gradle index bb2c912..a177fb2 100644 --- a/identity-kyc/build.gradle +++ b/identity-kyc/build.gradle @@ -30,6 +30,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } maven { url = uri("https://repo.spring.io/milestone") } diff --git a/nft-ownership/build.gradle b/nft-ownership/build.gradle index 3cb35b3..0af6a56 100644 --- a/nft-ownership/build.gradle +++ b/nft-ownership/build.gradle @@ -30,6 +30,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } maven { url = uri("https://repo.spring.io/milestone") } diff --git a/pedersen-commitments/build.gradle b/pedersen-commitments/build.gradle index 648008e..3626825 100644 --- a/pedersen-commitments/build.gradle +++ b/pedersen-commitments/build.gradle @@ -30,6 +30,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } maven { url = uri("https://repo.spring.io/milestone") } diff --git a/personhood-airdrop/build.gradle b/personhood-airdrop/build.gradle index c2f8d01..f1a01d9 100644 --- a/personhood-airdrop/build.gradle +++ b/personhood-airdrop/build.gradle @@ -30,6 +30,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } maven { url = uri("https://repo.spring.io/milestone") } diff --git a/private-voting/build.gradle b/private-voting/build.gradle index f1c02fc..83029e5 100644 --- a/private-voting/build.gradle +++ b/private-voting/build.gradle @@ -30,6 +30,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } maven { url = uri("https://repo.spring.io/milestone") } diff --git a/proof-of-reserves/build.gradle b/proof-of-reserves/build.gradle index 8cbe15f..b4364a2 100644 --- a/proof-of-reserves/build.gradle +++ b/proof-of-reserves/build.gradle @@ -20,6 +20,7 @@ repositories { mavenLocal() mavenCentral() maven { url = uri("https://central.sonatype.com/repository/maven-snapshots"); content { snapshotsOnly() } } + maven { url = uri("https://repo.bloxbean.org/maven/snapshots"); content { snapshotsOnly(); includeGroup("org.zeroj") } } maven { url = uri("https://repo.spring.io/milestone") } } diff --git a/reusable-kyc/build.gradle b/reusable-kyc/build.gradle index 4b8d78a..9e4298d 100644 --- a/reusable-kyc/build.gradle +++ b/reusable-kyc/build.gradle @@ -30,6 +30,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } maven { url = uri("https://repo.spring.io/milestone") } diff --git a/selective-disclosure/build.gradle b/selective-disclosure/build.gradle index 54d6946..50c2683 100644 --- a/selective-disclosure/build.gradle +++ b/selective-disclosure/build.gradle @@ -30,6 +30,14 @@ repositories { url = uri("https://central.sonatype.com/repository/maven-snapshots") content { snapshotsOnly() } } + // ZeroJ commit snapshots published by ZeroJ's bloxbean-snapshot workflow. + maven { + url = uri("https://repo.bloxbean.org/maven/snapshots") + content { + snapshotsOnly() + includeGroup("org.zeroj") + } + } maven { url = uri("https://repo.spring.io/milestone") } diff --git a/version.properties b/version.properties index 16f7f72..ec96888 100644 --- a/version.properties +++ b/version.properties @@ -2,7 +2,8 @@ # # Release: bump `version`, commit, and tag `v` (e.g. v0.1.0-pre1) to trigger a release. # Dependencies: the zeroj / julc / cardano-client versions every usecase builds against -# (published to Maven Central). +# (published to Maven Central; ZeroJ commit snapshots `--SNAPSHOT` come from +# https://repo.bloxbean.org/maven/snapshots, which every build lists for the org.zeroj group). # # Read by every build.gradle (walking up to the repo root) and by gradle/usecase-versions.gradle. # Override any of these locally with -P= (e.g. -PreleaseVersion, -PzerojVersion). @@ -11,6 +12,6 @@ version=0.1.0-pre7 # --- dependency versions --- -zerojVersion=0.1.0-pre13-1e78c6f-SNAPSHOT +zerojVersion=0.1.0-pre13-458bfb1-SNAPSHOT julcVersion=0.1.0-pre18 cclVersion=0.8.0-pre5 From 1532c87c532d1656297988df86c42035c7214922 Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 10 Oct 2026 20:21:25 +0800 Subject: [PATCH 09/12] pedersen-commitments: demo starts in ~2.5 min instead of ~25 (payroll stuck "starting") - bootRun: optimizedLaunch = false. Spring Boot's -XX:TieredStopAtLevel=1 disabled C2, so ZeroJ's point-by-point validation of the cached keys ran several times slower (note-transfer: 531 s vs 125 s). Other modules in this repository already set it. - KeyedCircuit: each cached key file is loaded and validated once per process and shared (points/payroll share note-transfer and note-redeem, four demos share key-possession); compileAll loads a demo's circuits in parallel. Validation itself is unchanged. - Funding: faucet top-ups are serialized and retried; concurrent demos made DevKit refuse one ("Topup failed") and payroll failed to start. - Starting banner: says cached keys are re-validated on every start. Measured on DevKit: all five demos ready 144 s after Tomcat started (was ~24 min for payroll); payroll and points pay/issue/transfer still prove and verify with the shared keys. Co-Authored-By: Claude Opus 5.5 --- pedersen-commitments/build.gradle | 3 + pedersen-commitments/frontend/src/App.svelte | 3 +- .../pedersen/auction/AuctionProofs.java | 17 ++++-- .../pedersen/common/KeyedCircuit.java | 59 ++++++++++++++++++- .../usecases/pedersen/notes/NoteProofs.java | 22 +++++-- .../zeroj/usecases/pedersen/web/Funding.java | 35 +++++++---- .../{index-D7BFeZ31.js => index-CZXCkFui.js} | 3 +- .../src/main/resources/static/index.html | 2 +- 8 files changed, 116 insertions(+), 28 deletions(-) rename pedersen-commitments/src/main/resources/static/assets/{index-D7BFeZ31.js => index-CZXCkFui.js} (99%) diff --git a/pedersen-commitments/build.gradle b/pedersen-commitments/build.gradle index 3626825..f01bbc4 100644 --- a/pedersen-commitments/build.gradle +++ b/pedersen-commitments/build.gradle @@ -101,6 +101,9 @@ tasks.register('walkthrough', JavaExec) { bootRun { jvmArgs '--enable-native-access=ALL-UNNAMED', '-Dzeroj.allowInsecureTrustedSetup=true' + // Spring Boot's optimized launch (-XX:TieredStopAtLevel=1) disables C2, which makes the + // pure-Java key validation, proving and verification several times slower. + optimizedLaunch = false } // Fork the compiler for the Julc annotation processor on Java 25 diff --git a/pedersen-commitments/frontend/src/App.svelte b/pedersen-commitments/frontend/src/App.svelte index c8af0dc..0a537a2 100644 --- a/pedersen-commitments/frontend/src/App.svelte +++ b/pedersen-commitments/frontend/src/App.svelte @@ -32,7 +32,8 @@ {#if !status?.ready}

Starting… compiling circuits, loading or generating development keys and funding demo wallets. - The first start takes a few minutes; later starts reuse the cached keys.

+ Each tab opens as soon as its demo is ready. Cached keys are re-validated point by point on every start (about + two minutes); the very first start also generates them, which takes longer.

{#if status?.demos}

{#each Object.entries(status.demos) as [name, s]} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionProofs.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionProofs.java index 21c02ef..de6015d 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionProofs.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionProofs.java @@ -4,13 +4,17 @@ import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.circuit.SettleProofCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; import com.bloxbean.cardano.zeroj.usecases.pedersen.common.KeyedCircuit; +import org.zeroj.circuit.CircuitBuilder; import org.zeroj.circuit.lib.jubjub.ElGamalCiphertext; import org.zeroj.circuit.lib.jubjub.ElGamalEncryption; import org.zeroj.crypto.groth16.Groth16ProofBLS381; import java.math.BigInteger; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; +import java.util.function.Supplier; /** * The auction circuits with their keys (ADR-0008 D3, D4): the bid relation and the settlement @@ -22,11 +26,14 @@ public final class AuctionProofs { private final List settle; public AuctionProofs() { - bid = KeyedCircuit.compile("sealed-bid", BidProofCircuit.build()); - settle = List.of( - KeyedCircuit.compile("sealed-bid-settle-n1", SettleProofCircuit.build(1, 4)), - KeyedCircuit.compile("sealed-bid-settle-n2", SettleProofCircuit.build(2, 8)), - KeyedCircuit.compile("sealed-bid-settle-n3", SettleProofCircuit.build(3, 12))); + Map> circuits = new LinkedHashMap<>(); + circuits.put("sealed-bid", BidProofCircuit::build); + circuits.put("sealed-bid-settle-n1", () -> SettleProofCircuit.build(1, 4)); + circuits.put("sealed-bid-settle-n2", () -> SettleProofCircuit.build(2, 8)); + circuits.put("sealed-bid-settle-n3", () -> SettleProofCircuit.build(3, 12)); + List c = KeyedCircuit.compileAll(circuits); + bid = c.getFirst(); + settle = List.copyOf(c.subList(1, 4)); } public KeyedCircuit bid() { return bid; } diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/KeyedCircuit.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/KeyedCircuit.java index e84ef3a..c7e8ca1 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/KeyedCircuit.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/KeyedCircuit.java @@ -32,6 +32,12 @@ import java.security.SecureRandom; import java.util.List; import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Supplier; /** * One compiled circuit with its Groth16 keys: proves witnesses, verifies proofs from their @@ -43,11 +49,17 @@ * the circuit fingerprint ({@code c-w-p}) and a SHA-256 of its constraints, so * a changed circuit never reuses stale keys, even one with the same shape. Production needs keys * from an MPC ceremony. + * + *

Loading a cached key validates every point (ZeroJ's {@code Groth16SetupCache}), which takes + * about two minutes for the largest circuits. So each key file is loaded once per process and shared + * by every demo that compiles the same circuit, and {@link #compileAll} loads several in parallel. */ public final class KeyedCircuit { private static final Logger log = LoggerFactory.getLogger(KeyedCircuit.class); private static final Path CACHE_DIR = Path.of("./data"); + /** Keys by cache file: a second demo compiling the same circuit waits for the first load. */ + private static final Map> SETUPS = new ConcurrentHashMap<>(); private final String name; private final CircuitBuilder circuit; @@ -73,9 +85,42 @@ public static KeyedCircuit compile(String name, CircuitBuilder circuit) { log.info("Circuit {}: {} constraints, {} public inputs ({})", name, r1cs.numConstraints(), r1cs.numPublicInputs(), fingerprint); Path cache = CACHE_DIR.resolve("setup-" + name + "-" + fingerprint + "-" + r1csDigest(r1cs.constraints()) + ".bin"); + var mine = new CompletableFuture(); + var shared = SETUPS.putIfAbsent(cache, mine); + Groth16SetupBLS381.SetupResult setup; + if (shared != null) { + setup = join(shared); + } else { + try { + setup = loadOrGenerate(name, r1cs, cache); + mine.complete(setup); + } catch (RuntimeException e) { + SETUPS.remove(cache, mine); + mine.completeExceptionally(e); + throw e; + } + } + return new KeyedCircuit(name, circuit, r1cs, setup); + } + + /** Compiles several circuits concurrently, in the order given. */ + public static List compileAll(Map> circuits) { + try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) { + List> futures = circuits.entrySet().stream() + .map(e -> CompletableFuture.supplyAsync(() -> compile(e.getKey(), e.getValue().get()), pool)) + .toList(); + return futures.stream().map(KeyedCircuit::join).toList(); + } + } + + private static Groth16SetupBLS381.SetupResult loadOrGenerate(String name, R1CSConstraintSystem r1cs, Path cache) { Groth16SetupBLS381.SetupResult setup = null; try { - if (Files.exists(cache)) setup = Groth16SetupCache.loadBls12381Setup(cache); + if (Files.exists(cache)) { + long start = System.nanoTime(); + setup = Groth16SetupCache.loadBls12381Setup(cache); + log.info("Loaded and validated the keys for {} in {} s", name, (System.nanoTime() - start) / 1_000_000_000L); + } } catch (Exception e) { log.warn("Key cache {} unreadable ({}); regenerating", cache, e.getMessage()); } @@ -90,7 +135,17 @@ public static KeyedCircuit compile(String name, CircuitBuilder circuit) { log.warn("Could not cache keys for {}: {}", name, e.getMessage()); } } - return new KeyedCircuit(name, circuit, r1cs, setup); + return setup; + } + + private static T join(CompletableFuture future) { + try { + return future.join(); + } catch (CompletionException e) { + if (e.getCause() instanceof RuntimeException r) throw r; + if (e.getCause() instanceof Error err) throw err; + throw e; + } } /** Computes the witness for {@code inputs} (throws if the relation does not hold) and proves it. */ diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteProofs.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteProofs.java index edf7a15..f009a70 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteProofs.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteProofs.java @@ -4,13 +4,17 @@ import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit.NoteIssueProofCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit.NoteRedeemProofCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit.NoteTransferProofCircuit; +import org.zeroj.circuit.CircuitBuilder; import org.zeroj.circuit.lib.jubjub.ElGamalEncryption; import org.zeroj.circuit.lib.jubjub.NoteOpening; import org.zeroj.crypto.groth16.Groth16ProofBLS381; import java.math.BigInteger; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; +import java.util.function.Supplier; /** * The note circuits with their keys (ADR-0007 N3, N4): transfer and redeem, and optionally proved @@ -36,16 +40,22 @@ private NoteProofs(KeyedCircuit transfer, KeyedCircuit redeem, KeyedCircuit issu /** Transfer and redeem only (trusted issuance). */ public static NoteProofs spendOnly() { - return new NoteProofs(KeyedCircuit.compile("note-transfer", NoteTransferProofCircuit.build()), - KeyedCircuit.compile("note-redeem", NoteRedeemProofCircuit.build()), null, null); + Map> circuits = new LinkedHashMap<>(); + circuits.put("note-transfer", NoteTransferProofCircuit::build); + circuits.put("note-redeem", NoteRedeemProofCircuit::build); + List c = KeyedCircuit.compileAll(circuits); + return new NoteProofs(c.get(0), c.get(1), null, null); } /** Transfer, redeem and proved issuance (payroll). */ public static NoteProofs withIssuance() { - return new NoteProofs(KeyedCircuit.compile("note-transfer", NoteTransferProofCircuit.build()), - KeyedCircuit.compile("note-redeem", NoteRedeemProofCircuit.build()), - KeyedCircuit.compile("note-issue-n1", NoteIssueProofCircuit.build(1, 2, 8)), - KeyedCircuit.compile("note-issue-n2", NoteIssueProofCircuit.build(2, 4, 16))); + Map> circuits = new LinkedHashMap<>(); + circuits.put("note-transfer", NoteTransferProofCircuit::build); + circuits.put("note-redeem", NoteRedeemProofCircuit::build); + circuits.put("note-issue-n1", () -> NoteIssueProofCircuit.build(1, 2, 8)); + circuits.put("note-issue-n2", () -> NoteIssueProofCircuit.build(2, 4, 16)); + List c = KeyedCircuit.compileAll(circuits); + return new NoteProofs(c.get(0), c.get(1), c.get(2), c.get(3)); } public KeyedCircuit transfer() { return transfer; } diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/Funding.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/Funding.java index d12c5d7..e576fff 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/Funding.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/Funding.java @@ -39,18 +39,7 @@ public Account newWallet(String label, int ada) { return account; } try { - var request = HttpRequest.newBuilder() - .uri(URI.create(adminUrl + "/local-cluster/api/addresses/topup")) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString( - "{\"address\":\"" + account.baseAddress() + "\",\"adaAmount\":" + ada + "}")) - .build(); - var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); - if (response.statusCode() / 100 != 2) { - throw new IllegalStateException("top-up returned " + response.statusCode() + ": " + response.body()); - } - waitForFunds(account.baseAddress()); - log.info("Funded {} with {} ADA: {}", label, ada, account.baseAddress()); + topUp(label, account.baseAddress(), ada); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IllegalStateException("interrupted while funding " + label, e); @@ -60,6 +49,28 @@ public Account newWallet(String label, int ada) { return account; } + /** + * One top-up at a time: the demos start concurrently, and DevKit's faucet refuses a top-up + * while its previous one is still in flight ("Topup failed"). Each top-up waits until its funds + * are visible, and a refused one is retried. + */ + private synchronized void topUp(String label, String address, int ada) throws Exception { + var request = HttpRequest.newBuilder() + .uri(URI.create(adminUrl + "/local-cluster/api/addresses/topup")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString("{\"address\":\"" + address + "\",\"adaAmount\":" + ada + "}")) + .build(); + for (int attempt = 1; ; attempt++) { + var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() / 100 == 2) break; + if (attempt == 5) throw new IllegalStateException("top-up returned " + response.statusCode() + ": " + response.body()); + log.warn("Top-up for {} refused ({}); retrying", label, response.statusCode()); + Thread.sleep(3_000L * attempt); + } + waitForFunds(address); + log.info("Funded {} with {} ADA: {}", label, ada, address); + } + private void waitForFunds(String address) throws Exception { for (int i = 0; i < 40; i++) { var utxos = backend.getUtxoService().getUtxos(address, 10, 1); diff --git a/pedersen-commitments/src/main/resources/static/assets/index-D7BFeZ31.js b/pedersen-commitments/src/main/resources/static/assets/index-CZXCkFui.js similarity index 99% rename from pedersen-commitments/src/main/resources/static/assets/index-D7BFeZ31.js rename to pedersen-commitments/src/main/resources/static/assets/index-CZXCkFui.js index 70a6250..2d72bdc 100644 --- a/pedersen-commitments/src/main/resources/static/assets/index-D7BFeZ31.js +++ b/pedersen-commitments/src/main/resources/static/assets/index-CZXCkFui.js @@ -37,7 +37,8 @@ var qi=Object.defineProperty;var Ta=e=>{throw TypeError(e)};var Li=(e,t,r)=>t in If it never settles, anyone can return the deposits and the item. Circuits: bid ${((A=(S=n(r))==null?void 0:S.constraints)==null?void 0:A.bid)??"…"??""} constraints, settlement of 3 bids ${((F=(N=n(r))==null?void 0:N.constraints)==null?void 0:F.settle3)??"…"??""}.`),Z.disabled=!!n(a)||n(P)==="bidding"||n(P)==="settling",pe.disabled=!!n(a)||n(P)!=="bidding",Me.disabled=!!n(a)||n(P)!=="settling",Ie.disabled=!!n(a)||n(P)!=="expired",Le.disabled=!!n(a)||n(P)==="bidding"||n(P)==="none",h(De,`The copier submits a bid proof made for ${n(_)??""}. The proof is bound to its bidder's key hash, so the lot refuses it.`),he.disabled=!!n(a)||n(P)!=="bidding",Ve.disabled=!!n(a)||n(P)!=="settling",h(Et,`Settle for bid #${n(m)??""}`)}),He(ee,()=>n(u),S=>T(u,S)),He(Ce,()=>n(v),S=>T(v,S)),He($e,()=>n(f),S=>T(f,S)),X("click",Z,()=>E("Opening the lot","/auction/open",{item:n(u),deposit:n(v),reserve:n(f)})),ft(I,()=>n(p),S=>T(p,S)),He(oe,()=>n(y),S=>T(y,S)),X("click",pe,()=>E("Proving and placing the bid","/auction/bid",{bidder:n(p),amount:n(y)})),X("click",Me,()=>E("Decrypting the bids and proving the settlement","/auction/settle",{})),X("click",Ie,()=>E("Refunding after the deadline","/auction/refund",{})),X("click",Le,()=>E("Closing without bids","/auction/no-bids",{})),ft(O,()=>n(w),S=>T(w,S)),ft(U,()=>n(_),S=>T(_,S)),X("click",he,()=>E("Submitting a copied bid","/auction/bid",{bidder:n(w),amount:n(y),copyFrom:n(_)})),He(et,()=>n(m),S=>T(m,S)),X("click",Ve,()=>E("Proving a wrong settlement","/auction/settle",{claimWinner:n(m)})),x(e,fe),nr()}Wr(["click"]);var Ol=$(" "),Dl=$("

"),Nl=$(`

Starting… compiling circuits, loading or generating development keys and funding demo wallets. - The first start takes a few minutes; later starts reuse the cached keys.

`),Rl=$(" ",1),Pl=$('

'),Ml=$(`

Pedersen Commitments on Cardano

Hiding, binding and additive commitments with zero-knowledge proofs, verified by Plutus V3 on Yaci DevKit

Demo server. This server creates every wallet and holds every key on the users' behalf — spending + Each tab opens as soon as its demo is ready. Cached keys are re-validated point by point on every start (about + two minutes); the very first start also generates them, which takes longer.

`),Rl=$(" ",1),Pl=$('

'),Ml=$(`

Pedersen Commitments on Cardano

Hiding, binding and additive commitments with zero-knowledge proofs, verified by Plutus V3 on Yaci DevKit

Demo server. This server creates every wallet and holds every key on the users' behalf — spending keys, note viewing keys, the auditor's keys — and scans the chain for them; real users would each keep their own and scan in their own wallet (ZeroJ ADR-0055 D9). Note balances are recovered from the chain, not kept in memory. The On-chain panels show what anyone can read from the ledger.
`);function Il(e,t){rr(t,!0);let r=R("points"),a=R(null);async function s(){var z;const se=await Jr("/status");T(a,se.data,!0),(z=n(a))!=null&&z.ready||setTimeout(s,3e3)}Kr(()=>{s()});var o=Ml(),l=i(d(o),6);{var u=se=>{var z=Nl(),le=i(d(z),2);{var we=ee=>{var Ee=Dl();ue(Ee,21,()=>Object.entries(n(a).demos),de,(Ce,je)=>{var $e=Hr(()=>Nn(n(je),2));let Z=()=>n($e)[0],L=()=>n($e)[1];var te=Ol();let I;var H=b(te);D(()=>{I=or(te,1,"pill svelte-1n46o8q",null,I,{ready:L()==="ready"}),h(H,`${Z()??""}: ${L()??""}`)}),x(Ce,te)}),x(ee,Ee)};G(le,ee=>{var Ee;(Ee=n(a))!=null&&Ee.demos&&ee(we)})}x(se,z)};G(l,se=>{var z;(z=n(a))!=null&&z.ready||se(u)})}var v=i(l,2),f=d(v);let p;var y=i(f,2);let w;var _=i(y,2);let m;var k=i(_,2);let g;var E=i(k,2);let J;var P=i(v,2);{var fe=se=>{var z=Rl(),le=nt(z);{var we=I=>{Fo(I,{})};G(le,I=>{n(r)==="points"&&I(we)})}var ee=i(le,2);{var Ee=I=>{fl(I,{})};G(ee,I=>{n(r)==="payroll"&&I(Ee)})}var Ce=i(ee,2);{var je=I=>{$l(I,{})};G(Ce,I=>{n(r)==="auction"&&I(je)})}var $e=i(Ce,2);{var Z=I=>{Go(I,{})};G($e,I=>{n(r)==="credit"&&I(Z)})}var L=i($e,2);{var te=I=>{ol(I,{})};G(L,I=>{n(r)==="solvency"&&I(te)})}x(se,z)},Ae=se=>{var z=Pl(),le=b(z);D(()=>{var we,ee;return h(le,`This demo is ${((ee=(we=n(a))==null?void 0:we.demos)==null?void 0:ee[n(r)])??"starting"??""}…`)}),x(se,z)};G(P,se=>{var z,le;((le=(z=n(a))==null?void 0:z.demos)==null?void 0:le[n(r)])==="ready"?se(fe):n(a)&&se(Ae,1)})}D(()=>{p=or(f,1,"svelte-1n46o8q",null,p,{active:n(r)==="points"}),w=or(y,1,"svelte-1n46o8q",null,w,{active:n(r)==="payroll"}),m=or(_,1,"svelte-1n46o8q",null,m,{active:n(r)==="auction"}),g=or(k,1,"svelte-1n46o8q",null,g,{active:n(r)==="credit"}),J=or(E,1,"svelte-1n46o8q",null,J,{active:n(r)==="solvency"})}),X("click",f,()=>T(r,"points")),X("click",y,()=>T(r,"payroll")),X("click",_,()=>T(r,"auction")),X("click",k,()=>T(r,"credit")),X("click",E,()=>T(r,"solvency")),x(e,o),nr()}Wr(["click"]);ao(Il,{target:document.getElementById("app")}); diff --git a/pedersen-commitments/src/main/resources/static/index.html b/pedersen-commitments/src/main/resources/static/index.html index d695e2c..ca63b1b 100644 --- a/pedersen-commitments/src/main/resources/static/index.html +++ b/pedersen-commitments/src/main/resources/static/index.html @@ -5,7 +5,7 @@ Pedersen Commitments — ZeroJ - + From 814b2f0db7dabafc2fde2f671ccbdd52360bb186 Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 10 Oct 2026 22:41:42 +0800 Subject: [PATCH 10/12] pedersen-commitments: lower transaction fees 12-31% without changing what any script accepts Measured on Yaci DevKit (mainnet protocol parameters), before -> after: auction bid 1.184 -> 0.897 ADA, settle (3 bids) 1.377 -> 1.028, open 0.745 -> 0.512, refund 0.678 -> 0.526; note transfer 1.415 -> 1.163, redeem 1.167 -> 0.984; payroll pay run 1.345 -> 1.111; registry init 1.381 -> 1.216. - Key carrier (ADR-0007 r3): the Groth16 verification keys move from every proof redeemer to the inline datum of an output at the script's own address without a reference script (deployed once, separately, because script plus keys exceed the transaction size limit). VkLib reads key i from the reference input at the script's payment credential; the hash check against the pinned parameter is unchanged. The transaction is 1.1-1.6 KB smaller. New VM mutations: no carrier, a carrier of another script, a wrong or rogue key in the carrier. - Constant-cost datum access: typed views (LotFields, EntryFields, CustomerFields) replace loop-based field(d, i); fixed-length checks in isNoteDatum and isLot are unrolled. Same accepted shapes; auction memory about -50%, registry -28%, notes -10 to -29%. - Evaluator margin 25% -> 5% (evaluation is deterministic; the margin is paid on every transaction). - CostProfiler (tests, ZEROJ_PROFILE=true): per-line cost of each validator's honest transaction, from Julc's source-mapped trace. All VM mutation suites and every DevKit E2E pass. The verifier's double point decompression is ZeroJ #84 (PR bloxbean/zeroj#85). Co-Authored-By: Claude Opus 5.5 --- ...07-confidential-notes-in-pedersen-demos.md | 52 ++++-- ...-sealed-bid-auction-enforced-disclosure.md | 24 ++- .../pedersen/auction/AuctionScript.java | 42 +++-- .../auction/onchain/SealedBidAuction.java | 148 +++++++++--------- .../usecases/pedersen/common/DevKit.java | 13 +- .../pedersen/notes/NoteLedgerScript.java | 65 +++++--- .../pedersen/notes/onchain/NoteLedger.java | 14 +- .../pedersen/notes/onchain/NoteLib.java | 42 +++-- .../pedersen/notes/onchain/RegistryLib.java | 37 +++-- .../pedersen/notes/onchain/VkLib.java | 39 ++++- .../solvency/onchain/SolvencyVault.java | 19 +-- .../auction/SealedBidAuctionVmTest.java | 71 +++++++-- .../pedersen/common/CostProfiler.java | 61 ++++++++ .../pedersen/credential/CreditGateVmTest.java | 11 +- .../pedersen/notes/AuditorRegistryVmTest.java | 15 +- .../pedersen/notes/NoteLedgerVmTest.java | 117 ++++++++++---- .../solvency/SolvencyVaultVmTest.java | 11 +- 17 files changed, 547 insertions(+), 234 deletions(-) create mode 100644 pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/CostProfiler.java diff --git a/docs/adr/0007-confidential-notes-in-pedersen-demos.md b/docs/adr/0007-confidential-notes-in-pedersen-demos.md index dcdb3e5..c256f59 100644 --- a/docs/adr/0007-confidential-notes-in-pedersen-demos.md +++ b/docs/adr/0007-confidential-notes-in-pedersen-demos.md @@ -143,7 +143,7 @@ a **singleton** registry token that the registry's own script moves forward on r The parameters are: - the issuer's pkh, the token name and the issuance mode; - the registry policy and token; -- the `blake2b_256(serialiseData(vk))` hashes of the verification keys: transfer, redeem, and proved issuance for one and for two notes (each redeemer carries its key; see the r2 note on script size). +- the `blake2b_256(serialiseData(vk))` hashes of the verification keys: transfer, redeem, and proved issuance for one and for two notes (the keys themselves are in the ledger's key carrier; see the r2 note on script size and r3). **Datum:** `Note(owner: B28, u: I, v: I, generation: I, audit: [I × 8], deliveries: [B89 × 2])`. - `audit` holds the two `elgamal-jubjub-v1` limb ciphertexts at width 32, `A.u, A.v, B.u, B.v` @@ -410,11 +410,31 @@ their own inputs"): budgets are per thread (R10). - Verification keys are pinned by hash: a script embedding four verification keys measured 18.1–18.9 KB, beyond the 16 KB transaction limit even for deploying a reference script. - `NoteLedger` takes `blake2b_256(serialiseData(vk))` per key, and each proof's redeemer - carries its key (on-chain `VkLib`). The ledger is deployed once as a reference script into an - output at its own address that holds no note token, so it can never be spent. + `NoteLedger` takes `blake2b_256(serialiseData(vk))` per key (on-chain `VkLib`). The ledger is + deployed once as a reference script into an output at its own address that holds no note + token, so it can never be spent. Since r3 the keys are in a second such output, the key + carrier, instead of each redeemer. - F10 (script size) stays a measurement at M3a. +- **r3** (2026-10-10; fee optimization, no change to what any script accepts): + - **Key carrier.** The verification keys moved from every proof redeemer to the inline datum of + a key carrier: an output at the script's own address with no reference script and no note + token, deployed once next to the reference script. `VkLib.referenceVk` reads key `i` from the + reference input at the script's payment credential without a reference script; the hash check + against the pinned parameter is unchanged, so where the key comes from does not affect + soundness. A reference input's datum is not part of the transaction, so the transaction is + about 1.1 to 1.6 KB smaller. VM tests: no carrier, a carrier of another script, and a wrong or + rogue key in the carrier are refused. + - **Constant-cost datum access.** Typed views (`EntryFields`, `CustomerFields`) replace + loop-based field access; `NoteLib.isNoteDatum` checks its fixed-length lists (8 audit integers, + 2 deliveries) unrolled. Same accepted shapes; fewer CEK steps. + - **Evaluator margin** 25% → 5%: evaluation is deterministic, and the margin is paid for on + every transaction. + - The on-chain Groth16 verifier's double decompression is ZeroJ issue #84. + - Measured fees on DevKit (mainnet protocol parameters), before → after: transfer 1.415 → + 1.163 ADA; redeem 1.167 → 0.984; trusted issue 0.505 → 0.469; payroll pay run of two + salaries 1.345 → 1.111; registry init 1.381 → 1.216, rotate 1.396 → 1.226. + ## Invariants | ID | Invariant | Enforced by | @@ -505,24 +525,24 @@ their own inputs"): Julc VM, Plutus V3 cost model (protocol version 11), against `maxTxExecutionUnits` (10e9 steps, 16.5e6 memory). Each figure is the **complete** transaction: every script purpose it runs, added up. -Verification keys are pinned by hash and carried in the redeemer (r2). +Verification keys are pinned by hash (r2) and read from the key carrier (r3). | Transaction | Circuit constraints | Public inputs | Julc VM steps | VM memory | DevKit steps | DevKit memory | |---|---|---|---|---|---|---| -| Transfer (spend + Split mint), direct layout | 34,184 | 24 | 76.8% | 16.2% | 76.8% | 16.2% | -| Redeem (spend + Receipt mint), direct layout | 18,366 | 15 | 58.3% | 12.7% | 58.3% | 12.7% | -| Proved issue, one note (mint) | 15,890 | 12 | 50.8% | 9.0% | — | — | -| Proved issue, two notes (mint) | 31,773 | 22 | 71.8% | 13.7% | see the payroll E2E | | -| Trusted issue (mint) | — | — | 3.7% (two notes) | 7.8% | 2.6% (one note) | 5.3% | -| Registry Init / Rotate (two possession proofs, 7 public inputs each) | 6,548 per proof | 7 | 77.7% / 78.2% | 8.6% / 9.4% | 77.8% / 78.3% | 8.6% / 9.5% | - -The VM contexts include the ledger's reference-script input, a fee-payer input and a change -output; the DevKit figures are the Julc evaluator's unpadded units for the real submitted +| Transfer (spend + Split mint), direct layout | 34,184 | 24 | 75.9% | 14.4% | 75.8% | 13.8% | +| Redeem (spend + Receipt mint), direct layout | 18,366 | 15 | 58.0% | 12.1% | 57.8% | 11.5% | +| Proved issue, one note (mint) | 15,890 | 12 | 50.5% | 8.3% | — | — | +| Proved issue, two notes (mint) | 31,773 | 22 | 71.0% | 11.8% | 71.3% | 12.2% | +| Trusted issue (mint) | — | — | 2.7% (two notes) | 5.7% | 2.1% (one note) | 4.3% | +| Registry Init / Rotate (two possession proofs, 7 public inputs each) | 6,548 per proof | 7 | 76.8% / 77.1% | 6.4% / 7.0% | 76.8% / 77.2% | 6.2% / 6.9% | + +Figures as of r3 (2026-10-10). The VM contexts include the ledger's reference-script input, its +key carrier, a fee-payer input and a change output; the DevKit figures are the Julc evaluator's unpadded units for the real submitted transaction. Both are asserted at ≤ 80% (registry transactions are outside ADR-0055's note gate). -The evaluator pads by up to 25% but never beyond `maxTxExecutionUnits`. +The evaluator pads by up to 5% (25% before r3) but never beyond `maxTxExecutionUnits`. **Gate outcome:** every note transaction is within ADR-0055's 80% gate with the **direct layout** -(spec §8.2), so the hash-compressed layout is not used. The transfer leaves 3.2 points of margin. +(spec §8.2), so the hash-compressed layout is not used. The transfer leaves 4.1 points of margin. The transfer and redeem circuits are exactly the size of ZeroJ's reference D3a circuits (34,184 and 18,366 constraints), an independent cross-check of the composition. The on-DevKit figures (from the Julc evaluator on the real transactions) are recorded at M3a's end-to-end run. diff --git a/docs/adr/0008-sealed-bid-auction-enforced-disclosure.md b/docs/adr/0008-sealed-bid-auction-enforced-disclosure.md index 618babd..2313eb9 100644 --- a/docs/adr/0008-sealed-bid-auction-enforced-disclosure.md +++ b/docs/adr/0008-sealed-bid-auction-enforced-disclosure.md @@ -237,6 +237,13 @@ bound, so an upper bound of exactly `biddingEnds` is still in time (tested at th ## Revision history - **r1** (2026-10-10): initial proposal. +- **r4** (2026-10-10; fee optimization, no change to what the script accepts): the lot datum is + read through a typed view (`LotFields`, a fixed `tailList` chain per field) instead of a loop + per access, and `isLot`'s field count is unrolled: about half the memory of every auction + transaction. The verification keys moved from the bid and settle redeemers to a key carrier + output (ADR-0007 r3). VM tests add a missing carrier and a carrier of another script. + Measured fees on DevKit, before → after: open 0.745 → 0.512 ADA; bid 1.184 → 0.897; settle + (3 bids) 1.377 → 1.028; refund 0.678 → 0.526. - **r3** (2026-10-10; implementation review, Codex C1–C5 and Claude A1–A12; no P0, both confirmed D4): payouts are tagged with `(policy, T)` (C1, A1); a lot carries no reference script (A4); the host keeps `lotAda ≥ minLotAda`, refuses to open a second lot while one is open, checks @@ -295,14 +302,15 @@ and the auction is deployed as a reference script (13 KB). | Transaction | VM steps | VM memory | DevKit steps | DevKit memory | |---|---|---|---|---| -| Open (mint) | 9.0% | 20.4% | 9.2% | 20.8% | -| Bid, the first / third (spend) | — / 51.0% | — / 22.0% | 50.9% / 51.1% | 21.6% / 22.2% | -| Settle, 1 bid (spend + burn) | 49.0% | 22.0% | — | — | -| Settle, 2 bids (spend + burn) | 57.3% | 23.7% | — | — | -| Settle, 3 bids (spend + burn) | 65.6% | 25.4% | 65.8% | 25.7% | -| Refund (spend) | 8.2% (3 bids) | 17.8% | 7.8% (1 bid) | 17.0% | +| Open (mint) | 3.1% | 6.3% | 3.3% | 6.4% | +| Bid, the first / third (spend) | — / 46.6% | — / 11.5% | 46.3% / 46.6% | 10.7% / 11.3% | +| Settle, 1 bid (spend + burn) | 44.5% | 11.3% | — | — | +| Settle, 2 bids (spend + burn) | 52.6% | 12.7% | — | — | +| Settle, 3 bids (spend + burn) | 60.8% | 14.0% | 60.7% | 13.4% | +| Refund (spend) | 4.3% (3 bids) | 8.6% | 4.1% (1 bid) | 8.1% | The DevKit columns are the evaluator's ExUnits for the real transactions of -`AuctionDevKitE2ETest` (2026-10-10), which also asserts the 80% gate. The VM transactions are -minimal (no fee input, change or reference-script input), so the DevKit figures, from the real +`AuctionDevKitE2ETest` (2026-10-10, as of r4), which also asserts the 80% gate. The VM transactions are +minimal (no fee input or change; bids and settlements carry the reference-script input and the +key carrier), so the DevKit figures, from the real transactions, are the ones the gate rests on. diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java index 1f56c09..84b1f20 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java @@ -59,6 +59,7 @@ public final class AuctionScript { private final String policyId; private final String address; private Utxo reference; + private Utxo keyCarrier; public AuctionScript(AuctionProofs proofs, Registry registry, long minWindowMillis, long minLotLovelace) { this.proofs = proofs; @@ -92,20 +93,41 @@ public AuctionScript(AuctionProofs proofs, Registry registry, long minWindowMill public long minWindow() { return minWindow; } + /** + * Deploys the script as a reference script at its own address, then the key carrier (the + * verification keys in the datum, no script; VkLib.referenceVk). Neither is an authentic lot, + * so neither can ever be spent. Two transactions: together they exceed the size limit. + */ public Result deploy(BackendService backend, Account payer) { try { - var tx = new Tx().payToContract(address, List.of(Amount.ada(30)), PlutusData.unit(), script).from(payer.baseAddress()); - var result = new QuickTxBuilder(backend).compose(tx).withSigner(SignerProviders.signerFrom(payer)).complete(); - if (result.isSuccessful()) { - DevKit.waitForTx(backend, result.getValue()); - reference = DevKit.utxosOf(backend, address, result.getValue()).getFirst(); - } + var result = new QuickTxBuilder(backend).compose(new Tx() + .payToContract(address, List.of(Amount.ada(30)), PlutusData.unit(), script).from(payer.baseAddress())) + .withSigner(SignerProviders.signerFrom(payer)).complete(); + if (!result.isSuccessful()) return result; + DevKit.waitForTx(backend, result.getValue()); + reference = DevKit.utxosOf(backend, address, result.getValue()).getFirst(); + var keys = verificationKeys(); + BigInteger lovelace = Plutus.minAda(backend, address, List.of(), keys).add(BigInteger.valueOf(1_000_000)); + var carried = new QuickTxBuilder(backend).compose(new Tx() + .payToContract(address, List.of(new Amount("lovelace", lovelace)), keys).from(payer.baseAddress())) + .withSigner(SignerProviders.signerFrom(payer)).complete(); + if (!carried.isSuccessful()) return carried; + DevKit.waitForTx(backend, carried.getValue()); + keyCarrier = DevKit.utxosOf(backend, address, carried.getValue()).getFirst(); return result; } catch (Exception e) { return Result.error(e.getMessage()); } } + /** {@code [bid, settle n=1, settle n=2, settle n=3]}, the order SealedBidAuction indexes. */ + ListPlutusData verificationKeys() { + return ListPlutusData.of(VerificationKeys.data(proofs.bid().compressedVk()), + VerificationKeys.data(proofs.settle(1).compressedVk()), + VerificationKeys.data(proofs.settle(2).compressedVk()), + VerificationKeys.data(proofs.settle(3).compressedVk())); + } + // ------------------------------------------------------------------ reading /** Every authentic lot at the auction's address. */ @@ -212,8 +234,7 @@ public Result bid(BackendService backend, Account bidder, Lot lot, ElGam var redeemer = ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( new BytesPlutusData(bid.bidder()), BigIntPlutusData.of(bid.aU()), BigIntPlutusData.of(bid.aV()), BigIntPlutusData.of(bid.bU()), BigIntPlutusData.of(bid.bV()), - new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()), - VerificationKeys.data(proofs.bid().compressedVk()))).build(); + new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()))).build(); List value = new ArrayList<>(); for (Amount a : lot.utxo().getAmount()) { value.add(a.getUnit().equals("lovelace") @@ -230,8 +251,7 @@ public Result settle(BackendService backend, Account submitter, Lot lot, var p = ProverToCardano.compressProof(proof); var redeemer = ConstrPlutusData.builder().alternative(1).data(ListPlutusData.of( BigIntPlutusData.of(w), BigIntPlutusData.of(price), - new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()), - VerificationKeys.data(proofs.settle(lot.bids().size()).compressedVk()))).build(); + new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()))).build(); var tx = closing(lot, redeemer); BigInteger deposit = BigInteger.valueOf(lot.deposit()).multiply(LOVELACE); tx = tx.payToContract(enterprise(lot.seller()), List.of(new Amount("lovelace", BigInteger.valueOf(price).multiply(LOVELACE))), @@ -317,7 +337,7 @@ private static List fullBids() { private Result submit(BackendService backend, ScriptTx tx, Account signer, Long validFrom, Long validTo) { try { - var ctx = new QuickTxBuilder(backend).compose(tx.readFrom(reference)) + var ctx = new QuickTxBuilder(backend).compose(tx.readFrom(reference, keyCarrier)) .withReferenceScripts(script) .withTxEvaluator(DevKit.evaluator(backend)) .withSigner(SignerProviders.signerFrom(signer)) diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/onchain/SealedBidAuction.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/onchain/SealedBidAuction.java index b6fa33b..0be01d2 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/onchain/SealedBidAuction.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/onchain/SealedBidAuction.java @@ -57,8 +57,8 @@ record Burn(BigInteger unused) implements LotMint {} sealed interface LotSpend permits PlaceBid, Settle, NoBids, Refund {} record PlaceBid(byte[] bidder, BigInteger aU, BigInteger aV, BigInteger bU, BigInteger bV, - byte[] piA, byte[] piB, byte[] piC, PlutusData vk) implements LotSpend {} - record Settle(BigInteger w, BigInteger p, byte[] piA, byte[] piB, byte[] piC, PlutusData vk) implements LotSpend {} + byte[] piA, byte[] piB, byte[] piC) implements LotSpend {} + record Settle(BigInteger w, BigInteger p, byte[] piA, byte[] piB, byte[] piC) implements LotSpend {} record NoBids(BigInteger unused) implements LotSpend {} record Refund(BigInteger unused) implements LotSpend {} @@ -93,29 +93,30 @@ private static boolean open(TxInfo txInfo, Credential own, byte[] policy) { } TxOut lot = onlyOwnOutput(txInfo, own); PlutusData d = ChainLib.inlineDatum(lot); - if (!isLot(d) || !Builtins.nullList(Builtins.unListData(field(d, 12)))) return false; + LotFields ld = PlutusData.cast(d, LotFields.class); + if (!isLot(d) || !Builtins.nullList(Builtins.unListData(ld.bids()))) return false; if (!authentic(lot, new Address(own, Optional.empty()), policy, token, d) - || ValuesLib.lovelaceOf(lot.value()).compareTo(Builtins.unIData(field(d, 4))) != 0) { + || ValuesLib.lovelaceOf(lot.value()).compareTo(Builtins.unIData(ld.lotAda())) != 0) { return false; } - BigInteger lotAda = Builtins.unIData(field(d, 4)); - BigInteger deposit = Builtins.unIData(field(d, 5)); - BigInteger reserve = Builtins.unIData(field(d, 6)); - BigInteger biddingEnds = Builtins.unIData(field(d, 7)); - BigInteger settleBy = Builtins.unIData(field(d, 8)); + BigInteger lotAda = Builtins.unIData(ld.lotAda()); + BigInteger deposit = Builtins.unIData(ld.deposit()); + BigInteger reserve = Builtins.unIData(ld.reserve()); + BigInteger biddingEnds = Builtins.unIData(ld.biddingEnds()); + BigInteger settleBy = Builtins.unIData(ld.settleBy()); BigInteger upper = IntervalLib.finiteUpperBound(txInfo.validRange()); PlutusData entry = RegistryLib.currentEntry(txInfo, registryPolicy, registryToken); - return ChainLib.signedBy(txInfo, Builtins.unBData(field(d, 0))) - && !Builtins.equalsByteString(Builtins.unBData(field(d, 2)), policy) + return ChainLib.signedBy(txInfo, Builtins.unBData(ld.seller())) + && !Builtins.equalsByteString(Builtins.unBData(ld.itemPolicy()), policy) && lotAda.compareTo(minLotAda) >= 0 && reserve.compareTo(BigInteger.TWO) >= 0 && reserve.compareTo(deposit) <= 0 && deposit.compareTo(BigInteger.valueOf(4294967296L)) < 0 && settleBy.subtract(biddingEnds).compareTo(minWindow) >= 0 && upper.compareTo(BigInteger.ZERO) >= 0 && upper.compareTo(biddingEnds) <= 0 - && Builtins.equalsByteString(RegistryLib.entryAuditor(entry), Builtins.unBData(field(d, 1))) - && RegistryLib.entryPkU(entry).compareTo(Builtins.unIData(field(d, 9))) == 0 - && RegistryLib.entryPkV(entry).compareTo(Builtins.unIData(field(d, 10))) == 0 - && RegistryLib.entryGeneration(entry).compareTo(Builtins.unIData(field(d, 11))) == 0; + && Builtins.equalsByteString(RegistryLib.entryAuditor(entry), Builtins.unBData(ld.auctioneer())) + && RegistryLib.entryPkU(entry).compareTo(Builtins.unIData(ld.pkU())) == 0 + && RegistryLib.entryPkV(entry).compareTo(Builtins.unIData(ld.pkV())) == 0 + && RegistryLib.entryGeneration(entry).compareTo(Builtins.unIData(ld.generation())) == 0; } // ------------------------------------------------------------------ @@ -124,6 +125,7 @@ private static boolean open(TxInfo txInfo, Credential own, byte[] policy) { @Entrypoint(purpose = Purpose.SPEND) public static boolean spend(PlutusData datum, LotSpend redeemer, ScriptContext ctx) { + LotFields ld = PlutusData.cast(datum, LotFields.class); TxInfo txInfo = ctx.txInfo(); byte[] policy = ContextsLib.ownHash(ctx); Credential own = new Credential.ScriptCredential(PlutusData.cast(policy, ScriptHash.class)); @@ -138,27 +140,28 @@ public static boolean spend(PlutusData datum, LotSpend redeemer, ScriptContext c case PlaceBid bid -> placeBid(bid, datum, lotIn, txInfo, own, exact, policy, token); case Settle settle -> settle(settle, datum, txInfo, own, policy, token); case NoBids noBids -> closing(txInfo, own, policy, token, datum) - && lowerAtLeast(txInfo, field(datum, 7)) - && Builtins.nullList(Builtins.unListData(field(datum, 12))) - && ChainLib.signedBy(txInfo, Builtins.unBData(field(datum, 0))) - && paid(txInfo, Builtins.unBData(field(datum, 0)), Builtins.unIData(field(datum, 4)), true, datum, policy, token); + && lowerAtLeast(txInfo, ld.biddingEnds()) + && Builtins.nullList(Builtins.unListData(ld.bids())) + && ChainLib.signedBy(txInfo, Builtins.unBData(ld.seller())) + && paid(txInfo, Builtins.unBData(ld.seller()), Builtins.unIData(ld.lotAda()), true, datum, policy, token); case Refund refund -> closing(txInfo, own, policy, token, datum) - && lowerAtLeast(txInfo, field(datum, 8)) - && paid(txInfo, Builtins.unBData(field(datum, 0)), Builtins.unIData(field(datum, 4)), true, datum, policy, token) - && refunded(txInfo, Builtins.unListData(field(datum, 12)), deposit(datum), BigInteger.ZERO, datum, policy, token); + && lowerAtLeast(txInfo, ld.settleBy()) + && paid(txInfo, Builtins.unBData(ld.seller()), Builtins.unIData(ld.lotAda()), true, datum, policy, token) + && refunded(txInfo, Builtins.unListData(ld.bids()), deposit(datum), BigInteger.ZERO, datum, policy, token); }; } private static boolean placeBid(PlaceBid b, PlutusData d, TxOut lotIn, TxInfo txInfo, Credential own, Address exact, byte[] policy, byte[] token) { - PlutusData bids = Builtins.unListData(field(d, 12)); + LotFields ld = PlutusData.cast(d, LotFields.class); + PlutusData bids = Builtins.unListData(ld.bids()); BigInteger upper = IntervalLib.finiteUpperBound(txInfo.validRange()); - if (upper.compareTo(BigInteger.ZERO) < 0 || upper.compareTo(Builtins.unIData(field(d, 7))) > 0 + if (upper.compareTo(BigInteger.ZERO) < 0 || upper.compareTo(Builtins.unIData(ld.biddingEnds())) > 0 || ChainLib.policyEntryCount(txInfo.mint(), policy) != 0 || Builtins.lengthOfByteString(b.bidder()) != 28 || !ChainLib.signedBy(txInfo, b.bidder()) - || Builtins.equalsByteString(b.bidder(), Builtins.unBData(field(d, 0))) - || Builtins.equalsByteString(b.bidder(), Builtins.unBData(field(d, 1))) + || Builtins.equalsByteString(b.bidder(), Builtins.unBData(ld.seller())) + || Builtins.equalsByteString(b.bidder(), Builtins.unBData(ld.auctioneer())) || ChainLib.countOutputs(txInfo.outputs(), own) != 1 || !ChainLib.canonicalField(b.aU()) || !ChainLib.canonicalField(b.aV()) || !ChainLib.canonicalField(b.bU()) || !ChainLib.canonicalField(b.bV()) @@ -195,20 +198,21 @@ private static boolean placeBid(PlaceBid b, PlutusData d, TxOut lotIn, TxInfo tx } PlutusData publicInputs = Builtins.listData( Builtins.mkCons(Builtins.iData(Builtins.byteStringToInteger(true, b.bidder())), - Builtins.mkCons(field(d, 5), - Builtins.mkCons(field(d, 6), - Builtins.mkCons(field(d, 9), - Builtins.mkCons(field(d, 10), + Builtins.mkCons(ld.deposit(), + Builtins.mkCons(ld.reserve(), + Builtins.mkCons(ld.pkU(), + Builtins.mkCons(ld.pkV(), Builtins.mkCons(Builtins.iData(b.aU()), Builtins.mkCons(Builtins.iData(b.aV()), Builtins.mkCons(Builtins.iData(b.bU()), Builtins.mkCons(Builtins.iData(b.bV()), Builtins.mkNilData())))))))))); - return VkLib.verify(publicInputs, b.piA(), b.piB(), b.piC(), b.vk(), bidVkHash); + return VkLib.verify(publicInputs, b.piA(), b.piB(), b.piC(), VkLib.referenceVk(txInfo, own, 0), bidVkHash); } private static boolean settle(Settle s, PlutusData d, TxInfo txInfo, Credential own, byte[] policy, byte[] token) { - PlutusData bids = Builtins.unListData(field(d, 12)); + LotFields ld = PlutusData.cast(d, LotFields.class); + PlutusData bids = Builtins.unListData(ld.bids()); int n = 0; PlutusData rest = bids; while (!Builtins.nullList(rest)) { @@ -216,10 +220,10 @@ private static boolean settle(Settle s, PlutusData d, TxInfo txInfo, Credential rest = Builtins.tailList(rest); } BigInteger upper = IntervalLib.finiteUpperBound(txInfo.validRange()); - BigInteger reserve = Builtins.unIData(field(d, 6)); + BigInteger reserve = Builtins.unIData(ld.reserve()); if (n < 1 || !closing(txInfo, own, policy, token, d) - || !lowerAtLeast(txInfo, field(d, 7)) - || upper.compareTo(BigInteger.ZERO) < 0 || upper.compareTo(Builtins.unIData(field(d, 8))) > 0 + || !lowerAtLeast(txInfo, ld.biddingEnds()) + || upper.compareTo(BigInteger.ZERO) < 0 || upper.compareTo(Builtins.unIData(ld.settleBy())) > 0 || s.w().compareTo(BigInteger.ONE) < 0 || s.w().compareTo(BigInteger.valueOf(n)) > 0 || s.p().compareTo(reserve) < 0 || s.p().compareTo(deposit(d)) > 0) { return false; @@ -228,16 +232,16 @@ private static boolean settle(Settle s, PlutusData d, TxInfo txInfo, Credential PlutusData publicInputs = Builtins.listData( Builtins.mkCons(Builtins.iData(s.w()), Builtins.mkCons(Builtins.iData(s.p()), - Builtins.mkCons(field(d, 9), - Builtins.mkCons(field(d, 10), + Builtins.mkCons(ld.pkU(), + Builtins.mkCons(ld.pkV(), ciphertexts(bids)))))); - if (!VkLib.verify(publicInputs, s.piA(), s.piB(), s.piC(), s.vk(), vkHash)) return false; - byte[] seller = Builtins.unBData(field(d, 0)); + if (!VkLib.verify(publicInputs, s.piA(), s.piB(), s.piC(), VkLib.referenceVk(txInfo, own, n), vkHash)) return false; + byte[] seller = Builtins.unBData(ld.seller()); BigInteger lovelace = BigInteger.valueOf(1000000); return paid(txInfo, seller, s.p().multiply(lovelace), false, d, policy, token) && refunded(txInfo, bids, deposit(d), s.w(), d, policy, token) && paid(txInfo, bidder(bids, s.w()), - Builtins.unIData(field(d, 4)).add(deposit(d).subtract(s.p()).multiply(lovelace)), true, d, policy, token); + Builtins.unIData(ld.lotAda()).add(deposit(d).subtract(s.p()).multiply(lovelace)), true, d, policy, token); } // ------------------------------------------------------------------ @@ -263,11 +267,12 @@ private static boolean lowerAtLeast(TxInfo txInfo, PlutusData bound) { */ private static boolean paid(TxInfo txInfo, byte[] pkh, BigInteger lovelace, boolean withItem, PlutusData d, byte[] policy, byte[] token) { + LotFields ld = PlutusData.cast(d, LotFields.class); Address to = new Address(new Credential.PubKeyCredential(PlutusData.cast(pkh, PubKeyHash.class)), Optional.empty()); PlutusData tag = Builtins.constrData(0, Builtins.mkCons(Builtins.bData(policy), Builtins.mkCons(Builtins.bData(token), Builtins.mkNilData()))); - byte[] itemPolicy = Builtins.unBData(field(d, 2)); - byte[] itemName = Builtins.unBData(field(d, 3)); + byte[] itemPolicy = Builtins.unBData(ld.itemPolicy()); + byte[] itemName = Builtins.unBData(ld.itemName()); boolean found = false; for (TxOut output : txInfo.outputs()) { found = found || (Builtins.equalsData(output.address(), to) @@ -340,6 +345,7 @@ private static PlutusData replaceLast(PlutusData fields, PlutusData last) { * lovelace, one unit of the item and one {@code token} under {@code policy}. */ private static boolean authentic(TxOut out, Address exact, byte[] policy, byte[] token, PlutusData d) { + LotFields ld = PlutusData.cast(d, LotFields.class); Value v = out.value(); // No reference script on a lot: it would make later spenders pay its reference-script fee. return out.referenceScript().isEmpty() @@ -348,8 +354,8 @@ private static boolean authentic(TxOut out, Address exact, byte[] policy, byte[] && ChainLib.outerEntryCount(v) == 3 && ChainLib.policyEntryCount(v, policy) == 1 && ValuesLib.assetOf(v, policy, token).compareTo(BigInteger.ONE) == 0 - && ChainLib.policyEntryCount(v, Builtins.unBData(field(d, 2))) == 1 - && ValuesLib.assetOf(v, Builtins.unBData(field(d, 2)), Builtins.unBData(field(d, 3))).compareTo(BigInteger.ONE) == 0; + && ChainLib.policyEntryCount(v, Builtins.unBData(ld.itemPolicy())) == 1 + && ValuesLib.assetOf(v, Builtins.unBData(ld.itemPolicy()), Builtins.unBData(ld.itemName())).compareTo(BigInteger.ONE) == 0; } /** The one output under the script's credential. */ @@ -370,17 +376,16 @@ private static TxOut onlyOwnOutput(TxInfo txInfo, Credential own) { * (coordinates canonical) and a list of well-formed bids. Anything else fails. */ private static boolean isLot(PlutusData d) { + LotFields ld = PlutusData.cast(d, LotFields.class); if (Builtins.constrTag(d) != 0) return false; - PlutusData f = Builtins.constrFields(d); - int count = 0; - PlutusData rest = f; - while (!Builtins.nullList(rest)) { - count = count + 1; - rest = Builtins.tailList(rest); - } - if (count != 13) return false; + // Exactly 13 fields (unrolled: fewer fails a builtin, more fails the check). + PlutusData f12 = Builtins.tailList(Builtins.tailList(Builtins.tailList(Builtins.tailList( + Builtins.tailList(Builtins.tailList(Builtins.tailList(Builtins.tailList( + Builtins.tailList(Builtins.tailList(Builtins.tailList(Builtins.tailList( + Builtins.constrFields(d))))))))))))); + if (!Builtins.nullList(Builtins.tailList(f12))) return false; boolean bidsOk = true; - PlutusData each = Builtins.unListData(field(d, 12)); + PlutusData each = Builtins.unListData(ld.bids()); while (!Builtins.nullList(each)) { PlutusData bid = Builtins.headList(each); PlutusData bf = Builtins.constrFields(bid); @@ -390,27 +395,28 @@ private static boolean isLot(PlutusData d) { each = Builtins.tailList(each); } return bidsOk - && Builtins.lengthOfByteString(Builtins.unBData(field(d, 0))) == 28 - && Builtins.lengthOfByteString(Builtins.unBData(field(d, 1))) == 28 - && Builtins.lengthOfByteString(Builtins.unBData(field(d, 2))) == 28 - && Builtins.lengthOfByteString(Builtins.unBData(field(d, 3))) <= 32 - && Builtins.unIData(field(d, 4)).compareTo(BigInteger.ZERO) > 0 - && ChainLib.canonicalField(Builtins.unIData(field(d, 9))) - && ChainLib.canonicalField(Builtins.unIData(field(d, 10))) - && Builtins.unIData(field(d, 11)).compareTo(BigInteger.ZERO) >= 0; + && Builtins.lengthOfByteString(Builtins.unBData(ld.seller())) == 28 + && Builtins.lengthOfByteString(Builtins.unBData(ld.auctioneer())) == 28 + && Builtins.lengthOfByteString(Builtins.unBData(ld.itemPolicy())) == 28 + && Builtins.lengthOfByteString(Builtins.unBData(ld.itemName())) <= 32 + && Builtins.unIData(ld.lotAda()).compareTo(BigInteger.ZERO) > 0 + && ChainLib.canonicalField(Builtins.unIData(ld.pkU())) + && ChainLib.canonicalField(Builtins.unIData(ld.pkV())) + && Builtins.unIData(ld.generation()).compareTo(BigInteger.ZERO) >= 0; } private static BigInteger deposit(PlutusData d) { - return Builtins.unIData(field(d, 5)); + LotFields ld = PlutusData.cast(d, LotFields.class); + return Builtins.unIData(ld.deposit()); } - private static PlutusData field(PlutusData d, int index) { - PlutusData rest = Builtins.constrFields(d); - int i = 0; - while (i < index) { - rest = Builtins.tailList(rest); - i = i + 1; - } - return Builtins.headList(rest); - } + /** + * A typed view of a lot datum, for constant-cost field access (each accessor is a fixed + * {@code tailList} chain, where a loop over the index cost a call and an iteration per step). + * Every component stays raw {@code Data}, so callers decode exactly as before, and + * {@link #isLot} has already checked the shape before any accessor is used. + */ + record LotFields(PlutusData seller, PlutusData auctioneer, PlutusData itemPolicy, PlutusData itemName, + PlutusData lotAda, PlutusData deposit, PlutusData reserve, PlutusData biddingEnds, + PlutusData settleBy, PlutusData pkU, PlutusData pkV, PlutusData generation, PlutusData bids) {} } diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/DevKit.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/DevKit.java index b3f3104..ff26a79 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/DevKit.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/DevKit.java @@ -80,8 +80,13 @@ public static Budget lastBudget() { /** * A Julc evaluator with slot-to-POSIX conversion anchored at the latest block (one-second - * slots), padded by 25% so fee estimates do not under-shoot, but never beyond the protocol's + * slots), padded by 5% so fee estimates do not under-shoot, but never beyond the protocol's * per-transaction maximum. The unpadded total is kept in {@link #lastBudget()}. + * + *

Script evaluation is deterministic: the margin only covers the difference between the + * transaction the units are measured on and the balanced one that is submitted (its fee and + * change amounts). The units are part of the fee, so a larger margin is paid on every + * transaction. */ public static TransactionEvaluator evaluator(BackendService backend) { var latest = call(() -> backend.getBlockService().getLatestBlock()); @@ -104,7 +109,7 @@ public static TransactionEvaluator evaluator(BackendService backend) { var params = call(() -> backend.getEpochService().getProtocolParameters()); long maxSteps = Long.parseLong(params.getMaxTxExSteps()); long maxMem = Long.parseLong(params.getMaxTxExMem()); - // Spread at most the remaining headroom over the redeemers, up to +25% each. + // Spread at most the remaining headroom over the redeemers, up to +5% each. long stepRoom = Math.max(0, maxSteps - steps); long memRoom = Math.max(0, maxMem - memory); for (EvaluationResult eval : result.getValue()) { @@ -112,8 +117,8 @@ public static TransactionEvaluator evaluator(BackendService backend) { long s0 = u.getSteps().longValueExact(); long m0 = u.getMem().longValueExact(); // stepRoom · s0 overflows a long (about 2e9 · 8e9), so share the headroom in BigInteger. - long padSteps = Math.min(s0 / 4, share(stepRoom, s0, steps)); - long padMem = Math.min(Math.max(m0 / 4, 50_000), share(memRoom, m0, memory)); + long padSteps = Math.min(s0 / 20, share(stepRoom, s0, steps)); + long padMem = Math.min(Math.max(m0 / 20, 10_000), share(memRoom, m0, memory)); eval.setExUnits(new ExUnits(BigInteger.valueOf(m0 + padMem), BigInteger.valueOf(s0 + padSteps))); } } diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerScript.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerScript.java index 8a1079f..d6d89d3 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerScript.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerScript.java @@ -22,7 +22,6 @@ import com.bloxbean.cardano.client.util.HexUtil; import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; -import com.bloxbean.cardano.zeroj.usecases.pedersen.common.KeyedCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain.NoteLedger; import org.julclang.clientlib.JulcScriptLoader; @@ -52,6 +51,7 @@ public final class NoteLedgerScript { private final String policyId; private final String address; private Utxo reference; + private Utxo keyCarrier; public NoteLedgerScript(byte[] issuerPkh, byte[] token, NoteProofs proofs, Registry registry) { this.issuerPkh = issuerPkh.clone(); @@ -99,28 +99,53 @@ public Utxo reference() { return reference; } - /** Deploys the script as a reference script at the ledger's own address (never spendable). */ + /** + * Deploys the script as a reference script at the ledger's own address, then the key carrier: + * an output there with the verification keys in its datum and no script (VkLib.referenceVk). + * Neither holds a note token, so neither can ever be spent, and wallets ignore both. Two + * transactions, because the script and the keys together exceed the transaction size limit. + */ public Result deploy(BackendService backend, Account payer) { try { - var tx = new Tx() - .payToContract(address, List.of(Amount.ada(40)), PlutusData.unit(), script) - .from(payer.baseAddress()); - var result = new QuickTxBuilder(backend).compose(tx) + var result = new QuickTxBuilder(backend).compose(new Tx() + .payToContract(address, List.of(Amount.ada(40)), PlutusData.unit(), script) + .from(payer.baseAddress())) + .withSigner(SignerProviders.signerFrom(payer)) + .complete(); + if (!result.isSuccessful()) return result; + DevKit.waitForTx(backend, result.getValue()); + reference = DevKit.utxosOf(backend, address, result.getValue()).getFirst(); + var keys = verificationKeys(); + BigInteger lovelace = Plutus.minAda(backend, address, List.of(), keys).add(BigInteger.valueOf(1_000_000)); + var carried = new QuickTxBuilder(backend).compose(new Tx() + .payToContract(address, List.of(new Amount("lovelace", lovelace)), keys) + .from(payer.baseAddress())) .withSigner(SignerProviders.signerFrom(payer)) .complete(); - if (result.isSuccessful()) { - DevKit.waitForTx(backend, result.getValue()); - reference = DevKit.utxosOf(backend, address, result.getValue()).getFirst(); - } + if (!carried.isSuccessful()) return carried; + DevKit.waitForTx(backend, carried.getValue()); + keyCarrier = DevKit.utxosOf(backend, address, carried.getValue()).getFirst(); return result; } catch (Exception e) { return Result.error(e.getMessage()); } } - /** Uses an already deployed reference script. */ - public void useReference(Utxo deployed) { + /** {@code [transfer, redeem]} and, with proved issuance, {@code issue n=1, issue n=2}: NoteLedger's key indices. */ + ListPlutusData verificationKeys() { + List keys = new ArrayList<>(List.of(VerificationKeys.data(proofs.transfer().compressedVk()), + VerificationKeys.data(proofs.redeem().compressedVk()))); + if (provedIssuance) { + keys.add(VerificationKeys.data(proofs.issue(1).compressedVk())); + keys.add(VerificationKeys.data(proofs.issue(2).compressedVk())); + } + return ListPlutusData.of(keys.toArray(new PlutusData[0])); + } + + /** Uses an already deployed reference script and key carrier. */ + public void useReference(Utxo deployed, Utxo carrier) { this.reference = deployed; + this.keyCarrier = carrier; } // ------------------------------------------------------------------ issuance @@ -140,10 +165,9 @@ public Result issue(BackendService backend, Account issuer, List provedIssue(BackendService backend, Account issuer, List notes, Groth16ProofBLS381 proof) { if (!provedIssuance) throw new IllegalStateException("this ledger issues without a proof"); - KeyedCircuit circuit = proofs.issue(notes.size()); var tx = new ScriptTx() .mintAsset(policyId, List.of(new Asset(tokenHex(), BigInteger.valueOf(notes.size()))), - proofRedeemer(3, null, proof, circuit)) + proofRedeemer(3, null, proof)) .readFrom(registry.currentUtxo(backend)); for (AuditedNote n : notes) tx = tx.payToContract(address, noteValue(backend, n), n.datum()); return submit(backend, tx, issuer); @@ -155,7 +179,7 @@ public Result provedIssue(BackendService backend, Account issuer, List transfer(BackendService backend, Account owner, Utxo note, AuditedNote out1, AuditedNote out2, Groth16ProofBLS381 proof) { var tx = new ScriptTx() - .collectFrom(note, proofRedeemer(0, null, proof, proofs.transfer())) + .collectFrom(note, proofRedeemer(0, null, proof)) .mintAsset(policyId, List.of(new Asset(tokenHex(), BigInteger.ONE)), ConstrPlutusData.builder().alternative(1).data(ListPlutusData.of(BigIntPlutusData.of(0))).build()) .readFrom(registry.currentUtxo(backend)) @@ -178,7 +202,7 @@ public Result transferWithStakeVariantNote(BackendService backend, Accou throw new IllegalStateException(e); } var tx = new ScriptTx() - .collectFrom(note, proofRedeemer(0, null, proof, proofs.transfer())) + .collectFrom(note, proofRedeemer(0, null, proof)) .mintAsset(policyId, List.of(new Asset(tokenHex(), BigInteger.ONE)), ConstrPlutusData.builder().alternative(1).data(ListPlutusData.of(BigIntPlutusData.of(0))).build()) .readFrom(registry.currentUtxo(backend)) @@ -192,7 +216,7 @@ public Result redeem(BackendService backend, Account owner, String issue AuditedNote change, long price, Groth16ProofBLS381 proof) { byte[] receipt = receiptName(note); var tx = new ScriptTx() - .collectFrom(note, proofRedeemer(1, BigInteger.valueOf(price), proof, proofs.redeem())) + .collectFrom(note, proofRedeemer(1, BigInteger.valueOf(price), proof)) .mintAsset(policyId, List.of(new Asset("0x" + HexUtil.encodeHexString(receipt), BigInteger.ONE)), ConstrPlutusData.builder().alternative(2).data(ListPlutusData.of(BigIntPlutusData.of(0))).build()) .readFrom(registry.currentUtxo(backend)) @@ -205,15 +229,14 @@ public Result redeem(BackendService backend, Account owner, String issue // ------------------------------------------------------------------ encodings - /** {@code Constr tag [price?, piA, piB, piC, vk]}. */ - private static ConstrPlutusData proofRedeemer(int tag, BigInteger price, Groth16ProofBLS381 proof, KeyedCircuit circuit) { + /** {@code Constr tag [price?, piA, piB, piC]}; the key is in the reference-script output. */ + private static ConstrPlutusData proofRedeemer(int tag, BigInteger price, Groth16ProofBLS381 proof) { var p = ProverToCardano.compressProof(proof); List fields = new ArrayList<>(); if (price != null) fields.add(BigIntPlutusData.of(price)); fields.add(new BytesPlutusData(p.piA())); fields.add(new BytesPlutusData(p.piB())); fields.add(new BytesPlutusData(p.piC())); - fields.add(VerificationKeys.data(circuit.compressedVk())); return ConstrPlutusData.builder().alternative(tag).data(ListPlutusData.of(fields.toArray(new PlutusData[0]))).build(); } @@ -244,7 +267,7 @@ private String tokenHex() { private Result submit(BackendService backend, ScriptTx tx, Account signer) { try { - return new QuickTxBuilder(backend).compose(tx.readFrom(reference())) + return new QuickTxBuilder(backend).compose(tx.readFrom(reference(), keyCarrier)) .withReferenceScripts(script) .withTxEvaluator(DevKit.evaluator(backend)) .withSigner(SignerProviders.signerFrom(signer)) diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLedger.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLedger.java index 31ab061..40a1657 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLedger.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLedger.java @@ -76,11 +76,11 @@ sealed interface NoteMint permits Issue, Split, Receipt, ProvedIssue {} record Issue(BigInteger count) implements NoteMint {} record Split(BigInteger count) implements NoteMint {} record Receipt(BigInteger count) implements NoteMint {} - record ProvedIssue(byte[] piA, byte[] piB, byte[] piC, PlutusData vk) implements NoteMint {} + record ProvedIssue(byte[] piA, byte[] piB, byte[] piC) implements NoteMint {} sealed interface NoteSpend permits Transfer, Redeem {} - record Transfer(byte[] piA, byte[] piB, byte[] piC, PlutusData vk) implements NoteSpend {} - record Redeem(BigInteger price, byte[] piA, byte[] piB, byte[] piC, PlutusData vk) implements NoteSpend {} + record Transfer(byte[] piA, byte[] piB, byte[] piC) implements NoteSpend {} + record Redeem(BigInteger price, byte[] piA, byte[] piB, byte[] piC) implements NoteSpend {} // ------------------------------------------------------------------ // Minting @@ -166,7 +166,7 @@ private static boolean provedIssue(ProvedIssue p, TxInfo txInfo, Credential own) Builtins.mkCons(Builtins.iData(NoteLib.noteU(first)), Builtins.mkCons(Builtins.iData(NoteLib.noteV(first)), appendList(pk, NoteLib.prependAudit(a1, Builtins.mkNilData()))))); - return VkLib.verify(inputs, p.piA(), p.piB(), p.piC(), p.vk(), issue1VkHash); + return VkLib.verify(inputs, p.piA(), p.piB(), p.piC(), VkLib.referenceVk(txInfo, own, 2), issue1VkHash); } PlutusData a2 = NoteLib.noteAudit(second); if (!NoteLib.ownHandlesDistinct(a2) || !NoteLib.handlesDisjoint(a1, a2)) return false; @@ -176,7 +176,7 @@ private static boolean provedIssue(ProvedIssue p, TxInfo txInfo, Credential own) Builtins.mkCons(Builtins.iData(NoteLib.noteV(first)), Builtins.mkCons(Builtins.iData(NoteLib.noteV(second)), appendList(pk, NoteLib.prependAudit(a1, NoteLib.prependAudit(a2, Builtins.mkNilData())))))))); - return VkLib.verify(inputs, p.piA(), p.piB(), p.piC(), p.vk(), issue2VkHash); + return VkLib.verify(inputs, p.piA(), p.piB(), p.piC(), VkLib.referenceVk(txInfo, own, 3), issue2VkHash); } /** The two-element list {@code pair} followed by {@code rest}. */ @@ -257,7 +257,7 @@ private static boolean transfer(Transfer t, Note in, TxInfo txInfo, Credential o Builtins.mkCons(Builtins.iData(RegistryLib.entryPkU(entry)), Builtins.mkCons(Builtins.iData(RegistryLib.entryPkV(entry)), NoteLib.prependAudit(a1, NoteLib.prependAudit(a2, Builtins.mkNilData()))))))))))); - return VkLib.verify(publicInputs, t.piA(), t.piB(), t.piC(), t.vk(), transferVkHash); + return VkLib.verify(publicInputs, t.piA(), t.piB(), t.piC(), VkLib.referenceVk(txInfo, own, 0), transferVkHash); } private static boolean redeem(Redeem r, Note in, TxInInfo ownInput, TxInfo txInfo, Credential own, @@ -307,6 +307,6 @@ private static boolean redeem(Redeem r, Note in, TxInInfo ownInput, TxInfo txInf Builtins.mkCons(Builtins.iData(RegistryLib.entryPkU(entry)), Builtins.mkCons(Builtins.iData(RegistryLib.entryPkV(entry)), NoteLib.prependAudit(audit, Builtins.mkNilData()))))))))); - return VkLib.verify(publicInputs, r.piA(), r.piB(), r.piC(), r.vk(), redeemVkHash); + return VkLib.verify(publicInputs, r.piA(), r.piB(), r.piC(), VkLib.referenceVk(txInfo, own, 1), redeemVkHash); } } diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLib.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLib.java index 3d02e8e..3d2691d 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLib.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/NoteLib.java @@ -62,24 +62,32 @@ public static boolean isNoteDatum(PlutusData value, BigInteger generation) { if (!ChainLib.canonicalField(Builtins.unIData(Builtins.headList(f1)))) return false; if (!ChainLib.canonicalField(Builtins.unIData(Builtins.headList(f2)))) return false; if (Builtins.unIData(Builtins.headList(f3)).compareTo(generation) != 0) return false; - int count = 0; - boolean canonical = true; - PlutusData rest = Builtins.unListData(Builtins.headList(f4)); - while (!Builtins.nullList(rest)) { - canonical = canonical && ChainLib.canonicalField(Builtins.unIData(Builtins.headList(rest))); - count = count + 1; - rest = Builtins.tailList(rest); - } - if (!canonical || count != 8) return false; - int deliveries = 0; - boolean lengths = true; - PlutusData each = Builtins.unListData(Builtins.headList(f5)); - while (!Builtins.nullList(each)) { - lengths = lengths && Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(each))) == 89; - deliveries = deliveries + 1; - each = Builtins.tailList(each); + // Exactly 8 canonical audit integers and exactly 2 deliveries of 89 bytes. Unrolled: the + // lengths are fixed, and a Julc loop costs far more per element than the checks themselves. + PlutusData a0 = Builtins.unListData(Builtins.headList(f4)); + PlutusData a1 = Builtins.tailList(a0); + PlutusData a2 = Builtins.tailList(a1); + PlutusData a3 = Builtins.tailList(a2); + PlutusData a4 = Builtins.tailList(a3); + PlutusData a5 = Builtins.tailList(a4); + PlutusData a6 = Builtins.tailList(a5); + PlutusData a7 = Builtins.tailList(a6); + if (!Builtins.nullList(Builtins.tailList(a7))) return false; + if (!ChainLib.canonicalField(Builtins.unIData(Builtins.headList(a0))) + || !ChainLib.canonicalField(Builtins.unIData(Builtins.headList(a1))) + || !ChainLib.canonicalField(Builtins.unIData(Builtins.headList(a2))) + || !ChainLib.canonicalField(Builtins.unIData(Builtins.headList(a3))) + || !ChainLib.canonicalField(Builtins.unIData(Builtins.headList(a4))) + || !ChainLib.canonicalField(Builtins.unIData(Builtins.headList(a5))) + || !ChainLib.canonicalField(Builtins.unIData(Builtins.headList(a6))) + || !ChainLib.canonicalField(Builtins.unIData(Builtins.headList(a7)))) { + return false; } - return lengths && deliveries == 2; + PlutusData d0 = Builtins.unListData(Builtins.headList(f5)); + PlutusData d1 = Builtins.tailList(d0); + return Builtins.nullList(Builtins.tailList(d1)) + && Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(d0))) == 89 + && Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(d1))) == 89; } public static BigInteger noteU(PlutusData note) { diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/RegistryLib.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/RegistryLib.java index d3cbaea..423b15f 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/RegistryLib.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/RegistryLib.java @@ -81,43 +81,46 @@ public static byte[] entryAuditor(PlutusData entry) { } public static BigInteger entryGeneration(PlutusData entry) { - return Builtins.unIData(field(entry, 1)); + EntryFields ef = PlutusData.cast(entry, EntryFields.class); + return Builtins.unIData(ef.generation()); } public static BigInteger entryPkU(PlutusData entry) { - return Builtins.unIData(field(entry, 2)); + EntryFields ef = PlutusData.cast(entry, EntryFields.class); + return Builtins.unIData(ef.pkU()); } public static BigInteger entryPkV(PlutusData entry) { - return Builtins.unIData(field(entry, 3)); + EntryFields ef = PlutusData.cast(entry, EntryFields.class); + return Builtins.unIData(ef.pkV()); } public static BigInteger entryViewU(PlutusData entry) { - return Builtins.unIData(field(entry, 5)); + EntryFields ef = PlutusData.cast(entry, EntryFields.class); + return Builtins.unIData(ef.viewU()); } public static BigInteger entryViewV(PlutusData entry) { - return Builtins.unIData(field(entry, 6)); + EntryFields ef = PlutusData.cast(entry, EntryFields.class); + return Builtins.unIData(ef.viewV()); } public static byte[] entryPkProof(PlutusData entry) { - return Builtins.unBData(field(entry, 8)); + EntryFields ef = PlutusData.cast(entry, EntryFields.class); + return Builtins.unBData(ef.pkProof()); } public static byte[] entryViewProof(PlutusData entry) { - return Builtins.unBData(field(entry, 9)); + EntryFields ef = PlutusData.cast(entry, EntryFields.class); + return Builtins.unBData(ef.viewProof()); } - /** Field {@code index} of a constructor. */ - private static PlutusData field(PlutusData entry, int index) { - PlutusData rest = Builtins.constrFields(entry); - int i = 0; - while (i < index) { - rest = Builtins.tailList(rest); - i = i + 1; - } - return Builtins.headList(rest); - } + /** + * A typed view of a registry entry for constant-cost field access (a fixed {@code tailList} + * chain instead of a loop). Components stay raw {@code Data}; callers decode as before. + */ + record EntryFields(PlutusData auditor, PlutusData generation, PlutusData pkU, PlutusData pkV, PlutusData pkEnc, + PlutusData viewU, PlutusData viewV, PlutusData viewKey, PlutusData pkProof, PlutusData viewProof) {} /** * The entry of the exactly one reference input that holds the registry token diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/VkLib.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/VkLib.java index 07df253..5b3370e 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/VkLib.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/onchain/VkLib.java @@ -1,16 +1,28 @@ package com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain; import org.julclang.core.PlutusData; +import org.julclang.ledger.Credential; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxInfo; +import org.julclang.ledger.TxOut; import org.julclang.stdlib.Builtins; import org.julclang.stdlib.annotation.OnchainLibrary; import org.zeroj.onchain.julc.groth16.lib.Groth16BLS12381Lib; +import java.math.BigInteger; + /** * Groth16 verification against a verification key pinned by hash (ADR-0007 N2): the script - * parameter is {@code blake2b_256(serialiseData(vk))}, and the redeemer carries + * parameter is {@code blake2b_256(serialiseData(vk))} with * {@code vk = Constr 0 [B alpha, B beta, B gamma, B delta, [B ic_0, …]]}. A key whose hash differs * is refused before any pairing. This keeps the verification keys out of the script, so the ledger * fits a reference script. + * + *

The keys themselves travel in the inline datum (a list of keys) of a key carrier: an + * output at the script's own address without a reference script, deployed once and referenced by + * every transaction. A reference input's datum is not part of the transaction, so it costs no size + * fee, where a key in the redeemer cost about a kilobyte per transaction. Where the key comes from + * does not matter for soundness: only a key whose hash is the pinned parameter is ever used. */ @OnchainLibrary public class VkLib { @@ -30,4 +42,29 @@ public static boolean verify(PlutusData publicInputs, byte[] piA, byte[] piB, by Builtins.unBData(Builtins.headList(f3)), Builtins.headList(f4)); } + + /** + * Key {@code index} (0 to 3) of the key list in the inline datum of a reference input at the + * script's own payment credential {@code own} that carries no reference script (the key + * carrier). No such input, a datum that is not a list, or a shorter list makes a builtin fail + * (fail closed); the caller's hash check decides whether the key is the right one. + */ + public static PlutusData referenceVk(TxInfo txInfo, Credential own, int index) { + PlutusData found = Builtins.iData(BigInteger.ZERO); + for (TxInInfo reference : txInfo.referenceInputs()) { + TxOut out = reference.resolved(); + if (out.referenceScript().isEmpty() && Builtins.equalsData(out.address().credential(), own)) { + found = ChainLib.inlineDatum(out); + } else { + found = found; + } + } + PlutusData k0 = Builtins.unListData(found); + if (index == 0) return Builtins.headList(k0); + PlutusData k1 = Builtins.tailList(k0); + if (index == 1) return Builtins.headList(k1); + PlutusData k2 = Builtins.tailList(k1); + if (index == 2) return Builtins.headList(k2); + return Builtins.headList(Builtins.tailList(k2)); + } } diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/onchain/SolvencyVault.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/onchain/SolvencyVault.java index 49e40b7..38c3411 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/onchain/SolvencyVault.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/onchain/SolvencyVault.java @@ -126,10 +126,11 @@ private static boolean attest(Attest a, TxInfo txInfo, Credential own, byte[] po PlutusData cursor = entries; while (!Builtins.nullList(cursor)) { PlutusData entry = Builtins.headList(cursor); + CustomerFields cf = PlutusData.cast(entry, CustomerFields.class); boolean ok = isEntry(entry); wellFormed = wellFormed && ok; - reversedU = Builtins.mkCons(Builtins.iData(entryField(entry, 1)), reversedU); - reversedV = Builtins.mkCons(Builtins.iData(entryField(entry, 2)), reversedV); + reversedU = Builtins.mkCons(Builtins.iData(Builtins.unIData(cf.u())), reversedU); + reversedV = Builtins.mkCons(Builtins.iData(Builtins.unIData(cf.v())), reversedV); count = count + 1; cursor = Builtins.tailList(cursor); } @@ -186,15 +187,11 @@ && canonicalField(Builtins.unIData(Builtins.headList(f2))) && Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(f3))) == 89; } - private static BigInteger entryField(PlutusData entry, int index) { - PlutusData f = Builtins.constrFields(entry); - int i = 0; - while (i < index) { - f = Builtins.tailList(f); - i = i + 1; - } - return Builtins.unIData(Builtins.headList(f)); - } + /** + * A typed view of a customer entry {@code Entry(idHash, u, v, delivery)} for constant-cost + * field access. Components stay raw {@code Data}; callers decode as before. + */ + record CustomerFields(PlutusData idHash, PlutusData u, PlutusData v, PlutusData delivery) {} private static int countInputs(JulcList inputs, Credential own) { int n = 0; diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/SealedBidAuctionVmTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/SealedBidAuctionVmTest.java index 514adc3..9177fca 100644 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/SealedBidAuctionVmTest.java +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/SealedBidAuctionVmTest.java @@ -1,5 +1,6 @@ package com.bloxbean.cardano.zeroj.usecases.pedersen.auction; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.CostProfiler; import com.bloxbean.cardano.client.crypto.Blake2bUtil; import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.circuit.BidProofCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.auction.onchain.SealedBidAuction; @@ -10,6 +11,7 @@ import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.RegistryEntry; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.RegistryTestData; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.VerificationKeys; +import org.julclang.compiler.CompileResult; import org.julclang.core.PlutusData; import org.julclang.core.Program; import org.julclang.ledger.Address; @@ -91,6 +93,7 @@ class SealedBidAuctionVmTest extends ContractTest { static AuctionProofs proofs; static Program program; + static CompileResult compiled; static AuditorKeys auctioneerKeys; static RegistryEntry entry; static AdmittedAuditor auctioneer; @@ -106,7 +109,8 @@ static void setup() { auctioneerKeys = AuditorKeys.generate(RANDOM); entry = auctioneerKeys.entry(REGISTRY_POLICY, AUCTIONEER, 0, possession); auctioneer = AdmittedAuditor.admit(REGISTRY_POLICY, entry, possession); - program = new SealedBidAuctionVmTest().compileValidator(SealedBidAuction.class, Path.of("src/main/java")).program() + compiled = new SealedBidAuctionVmTest().compileValidatorWithSourceMap(SealedBidAuction.class, Path.of("src/main/java")); + program = compiled.program() .applyParams(PlutusData.bytes(REGISTRY_POLICY), PlutusData.bytes("REG".getBytes()), PlutusData.integer(BigInteger.valueOf(MIN_WINDOW)), PlutusData.integer(BigInteger.valueOf(2_000_000)), PlutusData.bytes(VerificationKeys.hash(proofs.bid().compressedVk())), @@ -122,6 +126,32 @@ static void setup() { specials(); } + /** + * The carrier's key list: slot 0 the bid key, slots 1 to 3 the settlement keys for 1 to 3 bids. + * Each argument names the circuit placed in that slot (0 = bid, 1 to 3 = settle n), so a test + * can put a wrong key in a slot. + */ + static PlutusData keys(int... circuits) { + PlutusData[] list = new PlutusData[circuits.length]; + for (int i = 0; i < circuits.length; i++) { + list[i] = VerificationKeys.julcData(circuits[i] == 0 ? proofs.bid().compressedVk() : proofs.settle(circuits[i]).compressedVk()); + } + return PlutusData.list(list); + } + + /** + * The auction's key carrier: an output at the script's address, without a reference script, + * with the verification keys in its datum (VkLib.referenceVk). Also references the auction's + * reference-script output, as a real transaction does. + */ + static void carrier(ScriptContextTestBuilder b, PlutusData keys) { + b.referenceInput(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(LOT_ADDRESS, + Value.lovelace(BigInteger.valueOf(30_000_000)), new OutputDatum.OutputDatumInline(PlutusData.constr(0)), + Optional.of(ScriptHash.of(POLICY))))); + b.referenceInput(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(LOT_ADDRESS, + Value.lovelace(BigInteger.valueOf(25_000_000)), new OutputDatum.OutputDatumInline(keys), Optional.empty()))); + } + /** A bid with a valid proof for exactly its bidder and ciphertext. */ record Special(byte[] bidder, List ct, SnarkjsToCardano.ProofCompressed proof) {} @@ -250,7 +280,9 @@ enum OpenMutation { @Test @DisplayName("Open: a seller mints a one-shot lot token and locks the item; every mutation is rejected") void open() { - var honest = evaluate(program, openContext(OpenMutation.NONE)); + var openCtx = openContext(OpenMutation.NONE); + var honest = evaluate(program, openCtx); + CostProfiler.profile("auction open", program, compiled, openCtx); assertInstanceOf(EvalResult.Success.class, honest); report("open (mint)", honest, null); for (OpenMutation m : OpenMutation.values()) { @@ -306,7 +338,7 @@ private PlutusData openContext(OpenMutation m) { enum BidMutation { NONE, LATE, NO_UPPER_BOUND, UNSIGNED, BY_SELLER, BY_AUCTIONEER, REPEATED_BIDDER, FOURTH_BID, DEPOSIT_OFF_BY_ONE, EARLIER_BID_CHANGED, COPIED_HANDLE, IDENTITY_HANDLE, STAKED_OUTPUT, TOKENLESS_INPUT, EXTRA_ASSET, MINT_DURING_BID, - PROOF_FOR_OTHER_BIDDER, WRONG_VK, TWO_LOTS, DEPOSIT_TOO_MUCH, REFERENCE_SCRIPT_ON_LOT, + PROOF_FOR_OTHER_BIDDER, WRONG_VK, NO_VK_CARRIER, VK_CARRIER_OTHER_SCRIPT, TWO_LOTS, DEPOSIT_TOO_MUCH, REFERENCE_SCRIPT_ON_LOT, // boundary cases, checked separately (AT_DEADLINE is accepted) AT_DEADLINE, JUST_LATE } @@ -314,7 +346,9 @@ enum BidMutation { @Test @DisplayName("Bid: the third bid is appended with its deposit and proof; every mutation is rejected") void placeBid() { - var honest = evaluate(program, bidContext(BidMutation.NONE)); + var bidCtx = bidContext(BidMutation.NONE); + var honest = evaluate(program, bidCtx); + CostProfiler.profile("auction bid", program, compiled, bidCtx); assertInstanceOf(EvalResult.Success.class, honest); report("bid (spend, third bid)", honest, null); for (BidMutation m : BidMutation.values()) { @@ -342,12 +376,20 @@ private PlutusData bidContext(BidMutation m) { SnarkjsToCardano.ProofCompressed p = sp.proof(); PlutusData newBid = PlutusData.constr(0, PlutusData.bytes(bidder), PlutusData.integer(aU), PlutusData.integer(aV), PlutusData.integer(bU), PlutusData.integer(bV)); - PlutusData vk = m == BidMutation.WRONG_VK ? VerificationKeys.julcData(proofs.settle(1).compressedVk()) - : VerificationKeys.julcData(proofs.bid().compressedVk()); PlutusData redeemer = PlutusData.constr(0, PlutusData.bytes(bidder), PlutusData.integer(aU), PlutusData.integer(aV), PlutusData.integer(bU), PlutusData.integer(bV), - PlutusData.bytes(p.piA()), PlutusData.bytes(p.piB()), PlutusData.bytes(p.piC()), vk); + PlutusData.bytes(p.piA()), PlutusData.bytes(p.piB()), PlutusData.bytes(p.piC())); var b = ScriptContextTestBuilder.spending(ownRef, before).redeemer(redeemer); + // WRONG_VK: a settlement key in the bid slot of the carrier. + if (m == BidMutation.VK_CARRIER_OTHER_SCRIPT) { + // The right keys, but in a carrier at another script's address. + b.referenceInput(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut( + new Address(new Credential.ScriptCredential(ScriptHash.of(filled(28, (byte) 0x66))), Optional.empty()), + Value.lovelace(BigInteger.valueOf(25_000_000)), new OutputDatum.OutputDatumInline(keys(0, 1, 2, 3)), + Optional.empty()))); + } else if (m != BidMutation.NO_VK_CARRIER) { + carrier(b, m == BidMutation.WRONG_VK ? keys(1, 1, 2, 3) : keys(0, 1, 2, 3)); + } b.validRange(switch (m) { case LATE -> upTo(BIDDING_ENDS + 1000); case NO_UPPER_BOUND -> always(); @@ -395,7 +437,9 @@ enum SettleMutation { @DisplayName("Settle: n = 1, 2, 3 accepted with cost measured; every mutation is rejected") void settle() { for (int n = 1; n <= 3; n++) { - var spend = evaluate(program, settleContext(SettleMutation.NONE, n, true)); + var settleCtx = settleContext(SettleMutation.NONE, n, true); + var spend = evaluate(program, settleCtx); + CostProfiler.profile("auction settle n=" + n, program, compiled, settleCtx); assertInstanceOf(EvalResult.Success.class, spend); var burn = evaluate(program, settleContext(SettleMutation.NONE, n, false)); assertInstanceOf(EvalResult.Success.class, burn); @@ -426,13 +470,16 @@ private PlutusData settleContext(SettleMutation m, int n, boolean spending) { auctioneerKeys.elgamal().secretScalar(), AMOUNTS.subList(0, proofBids))); long claimedW = m == SettleMutation.W_OUT_OF_RANGE ? n + 1 : w; long claimedP = m == SettleMutation.P_BELOW_RESERVE ? RESERVE - 1 : p; - PlutusData vk = VerificationKeys.julcData(proofs.settle(m == SettleMutation.WRONG_VK ? (n == 1 ? 2 : 1) : proofBids).compressedVk()); PlutusData redeemer = PlutusData.constr(1, PlutusData.integer(BigInteger.valueOf(claimedW)), PlutusData.integer(BigInteger.valueOf(claimedP)), PlutusData.bytes(proof.piA()), PlutusData.bytes(proof.piB()), - PlutusData.bytes(proof.piC()), vk); + PlutusData.bytes(proof.piC())); var b = spending ? ScriptContextTestBuilder.spending(ownRef, datum).redeemer(redeemer) : ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).redeemer(PlutusData.constr(1, PlutusData.integer(0))); + // WRONG_VK: another settlement size's key in this size's slot of the carrier. + int other = n == 1 ? 2 : 1; + carrier(b, m != SettleMutation.WRONG_VK ? keys(0, 1, 2, 3) + : keys(0, n == 1 ? other : 1, n == 2 ? other : 2, n == 3 ? other : 3)); b.validRange(switch (m) { case EARLY -> between(BIDDING_ENDS - 1000, SETTLE_BY - 1000); case LATE -> between(BIDDING_ENDS + 1000, SETTLE_BY + 1000); @@ -496,7 +543,9 @@ enum CloseMutation { NONE, EARLY, UNDERPAID_BIDDER, ITEM_NOT_RETURNED, UNTAGGED, @Test @DisplayName("Refund after settleBy and NoBids after the window are accepted; their mutations are rejected") void refundAndNoBids() { - var refund = evaluate(program, refundContext(CloseMutation.NONE)); + var refundCtx = refundContext(CloseMutation.NONE); + var refund = evaluate(program, refundCtx); + CostProfiler.profile("auction refund", program, compiled, refundCtx); assertInstanceOf(EvalResult.Success.class, refund); report("refund (spend, 3 bids)", refund, null); for (CloseMutation m : CloseMutation.values()) { diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/CostProfiler.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/CostProfiler.java new file mode 100644 index 0000000..113caf6 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/CostProfiler.java @@ -0,0 +1,61 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.common; + +import org.julclang.compiler.CompileResult; +import org.julclang.core.PlutusData; +import org.julclang.core.Program; +import org.julclang.vm.EvalOptions; +import org.julclang.vm.EvalResult; +import org.julclang.vm.JulcVm; +import org.julclang.vm.trace.ExecutionTraceEntry; + +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Opt-in cost profile of a validator evaluation ({@code ZEROJ_PROFILE=true}): re-runs the context + * with Julc's source-mapped execution tracing and prints the CPU and memory spent per line of the + * validator. Library code without a source map (ZeroJ's Groth16 verifier, Julc's stdlib) is + * reported as one "untraced" remainder. Used to find where a transaction's fee goes. + */ +public final class CostProfiler { + + private CostProfiler() {} + + public static boolean enabled() { + return "true".equalsIgnoreCase(System.getenv("ZEROJ_PROFILE")); + } + + public static void profile(String label, Program program, CompileResult compiled, PlutusData context) { + if (!enabled()) return; + EvalResult result = JulcVm.create().evaluateWithArgs(program, compiled.target().ledgerTarget(), List.of(context), + null, EvalOptions.DEFAULT.withSourceMap(compiled.sourceMap()).withTracing(true)); + long cpu = result.budgetConsumed().cpuSteps(); + long mem = result.budgetConsumed().memoryUnits(); + Map lines = new LinkedHashMap<>(); + for (ExecutionTraceEntry e : result.executionTrace()) { + long[] acc = lines.computeIfAbsent(e.fileName() + ":" + e.line(), k -> new long[3]); + acc[0] += e.cpuDelta(); + acc[1] += e.memDelta(); + acc[2]++; + } + long tracedCpu = lines.values().stream().mapToLong(a -> a[0]).sum(); + long tracedMem = lines.values().stream().mapToLong(a -> a[1]).sum(); + var out = new StringBuilder(); + out.append(String.format("[profile %s] success=%s cpu=%,d mem=%,d; untraced (libraries) cpu=%,d (%.0f%%) mem=%,d (%.0f%%)%n", + label, result.isSuccess(), cpu, mem, cpu - tracedCpu, 100.0 * (cpu - tracedCpu) / cpu, + mem - tracedMem, 100.0 * (mem - tracedMem) / mem)); + appendTop(out, "cpu", lines, 0, cpu); + appendTop(out, "mem", lines, 1, mem); + System.out.print(out); + } + + private static void appendTop(StringBuilder out, String what, Map lines, int index, long total) { + lines.entrySet().stream() + .sorted(Comparator.comparingLong((Map.Entry e) -> e.getValue()[index]).reversed()) + .limit(10) + .forEach(e -> out.append(String.format(" top %s %-34s %,15d (%4.1f%%) visits=%d%n", what, e.getKey(), + e.getValue()[index], 100.0 * e.getValue()[index] / total, e.getValue()[2]))); + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGateVmTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGateVmTest.java index 273020f..b54df19 100644 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGateVmTest.java +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGateVmTest.java @@ -1,10 +1,12 @@ package com.bloxbean.cardano.zeroj.usecases.pedersen.credential; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.CostProfiler; import com.bloxbean.cardano.client.crypto.Blake2bUtil; import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.CreditGate.Profile; import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.circuit.CreditProfileProof; import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.onchain.CreditGatePolicy; +import org.julclang.compiler.CompileResult; import org.julclang.core.PlutusData; import org.julclang.core.Program; import org.julclang.ledger.Address; @@ -48,6 +50,7 @@ class CreditGateVmTest extends ContractTest { private static final byte[] MALLORY = filled(28, (byte) 0x3e); private static Program program; + private static CompileResult compiled; private static Profile profile; private static PedersenVectorCommitment commitment; private static SnarkjsToCardano.ProofCompressed proof; @@ -62,8 +65,8 @@ static void setup() { // Valid, but for lower thresholds than the gate's. lowThresholdProof = ProverToCardano.compressProof(gate.prove(profile, 40_000, 600)); var vk = gate.circuit().compressedVk(); - program = new CreditGateVmTest().compileValidator(CreditGatePolicy.class, Path.of("src/main/java")) - .program().applyParams( + compiled = new CreditGateVmTest().compileValidatorWithSourceMap(CreditGatePolicy.class, Path.of("src/main/java")); + program = compiled.program().applyParams( PlutusData.bytes(Fields.i2osp(CreditProfileProof.SCHEMA.digest(), 32)), PlutusData.bytes(BUREAU), PlutusData.integer(BigInteger.valueOf(CreditCircuitTest.MIN_INCOME)), @@ -82,7 +85,9 @@ enum Mutation { @Test @DisplayName("Credit gate: a qualifying issued credential mints a badge; every mutation is rejected") void gate() { - var ok = evaluate(program, context(Mutation.NONE)); + var ctx = context(Mutation.NONE); + var ok = evaluate(program, ctx); + CostProfiler.profile("credit gate", program, compiled, ctx); assertSuccess(ok); System.out.println("[CreditGatePolicy] budget: " + ok.budgetConsumed()); for (Mutation m : Mutation.values()) { diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorRegistryVmTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorRegistryVmTest.java index 82c7167..8b3c0df 100644 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorRegistryVmTest.java +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorRegistryVmTest.java @@ -1,9 +1,11 @@ package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.CostProfiler; import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; import com.bloxbean.cardano.zeroj.usecases.pedersen.common.ProofBytes; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit.KeyPossessionProofCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain.AuditorRegistry; +import org.julclang.compiler.CompileResult; import org.julclang.core.PlutusData; import org.julclang.core.Program; import org.julclang.ledger.Address; @@ -64,6 +66,7 @@ class AuditorRegistryVmTest extends ContractTest { static final SecureRandom RANDOM = new SecureRandom(); private static Program program; + private static CompileResult compiled; private static KeyPossession possession; private static AuditorKeys keys0; private static RegistryEntry gen0; @@ -80,8 +83,8 @@ static void setup() { var vk = possession.circuit().compressedVk(); JubjubPoint g = JubjubPoint.SUBGROUP_GENERATOR.normalized(); PlutusData[] ic = vk.ic().stream().map(PlutusData::bytes).toArray(PlutusData[]::new); - program = new AuditorRegistryVmTest().compileValidator(AuditorRegistry.class, Path.of("src/main/java")) - .program().applyParams(PlutusData.bytes(seedRef), PlutusData.bytes(TOKEN), + compiled = new AuditorRegistryVmTest().compileValidatorWithSourceMap(AuditorRegistry.class, Path.of("src/main/java")); + program = compiled.program().applyParams(PlutusData.bytes(seedRef), PlutusData.bytes(TOKEN), PlutusData.bytes(KeyPossession.ctxPrefix(KeyPossession.KeyType.ELGAMAL)), PlutusData.bytes(KeyPossession.ctxPrefix(KeyPossession.KeyType.VIEWING)), PlutusData.integer(g.affineU()), PlutusData.integer(g.affineV()), @@ -208,7 +211,9 @@ enum InitMutation { @Test @DisplayName("Init: the seed-bound singleton is minted once into a well-formed, possession-verified entry; every mutation is rejected") void init() { - var honest = evaluate(program, initContext(InitMutation.NONE, EntryMutation.NONE)); + var initCtx = initContext(InitMutation.NONE, EntryMutation.NONE); + var honest = evaluate(program, initCtx); + CostProfiler.profile("registry init", program, compiled, initCtx); assertInstanceOf(EvalResult.Success.class, honest); System.out.println("[AuditorRegistry init] budget: " + honest.budgetConsumed()); for (InitMutation m : InitMutation.values()) { @@ -265,7 +270,9 @@ enum RotateMutation { @Test @DisplayName("Rotate: the entry moves forward one generation under both auditors' signatures; every mutation is rejected") void rotate() { - var honest = evaluate(program, rotateContext(RotateMutation.NONE, EntryMutation.NONE)); + var rotateCtx = rotateContext(RotateMutation.NONE, EntryMutation.NONE); + var honest = evaluate(program, rotateCtx); + CostProfiler.profile("registry rotate", program, compiled, rotateCtx); assertInstanceOf(EvalResult.Success.class, honest); System.out.println("[AuditorRegistry rotate] budget: " + honest.budgetConsumed()); for (RotateMutation m : RotateMutation.values()) { diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerVmTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerVmTest.java index 14b5082..51b519f 100644 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerVmTest.java +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerVmTest.java @@ -1,11 +1,13 @@ package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.CostProfiler; import com.bloxbean.cardano.client.crypto.Blake2bUtil; import com.bloxbean.cardano.zeroj.usecases.pedersen.common.KeyedCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit.NoteIssueProofCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit.NoteRedeemProofCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.circuit.NoteTransferProofCircuit; import com.bloxbean.cardano.zeroj.usecases.pedersen.notes.onchain.NoteLedger; +import org.julclang.compiler.CompileResult; import org.julclang.core.PlutusData; import org.julclang.core.Program; import org.julclang.ledger.Address; @@ -81,6 +83,7 @@ class NoteLedgerVmTest extends ContractTest { static NoteProofs proofs; static Program points; static Program payroll; + static CompileResult compiled; static KeyPossession possession; static RegistryEntry entry; static RegistryEntry otherEntry; @@ -104,9 +107,9 @@ static void setup() { otherEntry = AuditorKeys.generate(RANDOM).entry(REGISTRY_POLICY, AUDITOR, GENERATION, possession); auditor = AdmittedAuditor.admit(REGISTRY_POLICY, entry, possession); otherAuditor = AdmittedAuditor.admit(REGISTRY_POLICY, otherEntry, possession); - var compiled = new NoteLedgerVmTest().compileValidator(NoteLedger.class, Path.of("src/main/java")).program(); - points = compiled.applyParams(params(false)); - payroll = compiled.applyParams(params(true)); + compiled = new NoteLedgerVmTest().compileValidatorWithSourceMap(NoteLedger.class, Path.of("src/main/java")); + points = compiled.program().applyParams(params(false)); + payroll = compiled.program().applyParams(params(true)); long balance = 0x1_0000_1000L; // above 2^32: both limbs non-zero in = spent(balance); @@ -174,11 +177,32 @@ static PlutusData vk(SnarkjsToCardano.VkCompressed vk) { return VerificationKeys.julcData(vk); } + /** The carrier's key list in NoteLedger's index order: transfer, redeem, issue n=1, issue n=2. */ + static PlutusData keys(SnarkjsToCardano.VkCompressed transfer, SnarkjsToCardano.VkCompressed redeem, + SnarkjsToCardano.VkCompressed issue1, SnarkjsToCardano.VkCompressed issue2) { + return PlutusData.list(vk(transfer), vk(redeem), vk(issue1), vk(issue2)); + } + + static PlutusData honestKeys() { + return keys(proofs.transfer().compressedVk(), proofs.redeem().compressedVk(), + proofs.issue(1).compressedVk(), proofs.issue(2).compressedVk()); + } + + /** + * The ledger's key carrier: an output at the script's address ({@code scriptHash}), without a + * reference script, with the verification keys in its datum (VkLib.referenceVk). + */ + static void carrier(ScriptContextTestBuilder b, PlutusData keys, byte[] scriptHash) { + Address at = new Address(new Credential.ScriptCredential(ScriptHash.of(scriptHash)), Optional.empty()); + b.referenceInput(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(at, ada(25), + new OutputDatum.OutputDatumInline(keys), Optional.empty()))); + } + // ------------------------------------------------------------------ Transfer enum TransferMutation { NONE, NO_SIGNER, TAMPERED_PROOF, WRONG_VK, SWAPPED_OUTPUTS, EXTRA_SCRIPT_INPUT, EXTRA_STAKED_SCRIPT_INPUT, - THREE_OUTPUTS, MINT_TWO, OUTPUT_TWO_TOKENS, OUTPUT_EXTRA_ASSET, NON_CANONICAL_OUTPUT, INPUT_WITHOUT_TOKEN, + NO_VK_CARRIER, VK_CARRIER_OTHER_SCRIPT, THREE_OUTPUTS, MINT_TWO, OUTPUT_TWO_TOKENS, OUTPUT_EXTRA_ASSET, NON_CANONICAL_OUTPUT, INPUT_WITHOUT_TOKEN, STAKE_VARIANT_EXTRA_OUTPUT, STAKE_VARIANT_NOTE, AUDIT_ABSENT, AUDIT_WRONG_OUT1, AUDIT_WRONG_OUT2, AUDIT_SWAPPED_BETWEEN_OUTPUTS, AUDIT_LIMBS_SWAPPED, AUDIT_NON_CANONICAL, AUDIT_SEVEN_ENTRIES, DELIVERY_SHORT, DELIVERY_MISSING, DELIVERY_EXTRA, STALE_GENERATION, @@ -189,9 +213,13 @@ enum TransferMutation { @Test @DisplayName("Transfer: accepted by both purposes, complete cost measured; every mutation is rejected") void transfer() { - var spend = evaluate(points, transferSpend(TransferMutation.NONE, out1, out2, transferProof)); + var transferCtx = transferSpend(TransferMutation.NONE, out1, out2, transferProof); + var spend = evaluate(points, transferCtx); + CostProfiler.profile("note transfer (spend)", points, compiled, transferCtx); assertInstanceOf(EvalResult.Success.class, spend); - var mint = evaluate(points, transferMint(TransferMutation.NONE)); + var splitCtx = transferMint(TransferMutation.NONE); + var mint = evaluate(points, splitCtx); + CostProfiler.profile("note transfer (Split mint)", points, compiled, splitCtx); assertInstanceOf(EvalResult.Success.class, mint); report("transfer (spend + Split mint)", spend, mint, proofs.transfer()); for (TransferMutation m : TransferMutation.values()) { @@ -241,20 +269,27 @@ private PlutusData transferSpend(TransferMutation m, AuditedNote a, AuditedNote private PlutusData transferSpend(TransferMutation m, PlutusData a, PlutusData b, SnarkjsToCardano.ProofCompressed p) { TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x44)), BigInteger.ZERO); byte[] piA = m == TransferMutation.TAMPERED_PROOF ? flipped(p.piA()) : p.piA(); - PlutusData key = m == TransferMutation.WRONG_VK ? vk(proofs.redeem().compressedVk()) : vk(proofs.transfer().compressedVk()); var builder = ScriptContextTestBuilder.spending(ownRef, inDatum()).redeemer(PlutusData.constr(0, - PlutusData.bytes(piA), PlutusData.bytes(p.piB()), PlutusData.bytes(p.piC()), key)); - return transferTx(m, builder, ownRef, a, b).buildPlutusData(); + PlutusData.bytes(piA), PlutusData.bytes(p.piB()), PlutusData.bytes(p.piC()))); + return transferTx(m, builder, ownRef, a, b, transferKeys(m)).buildPlutusData(); + } + + /** The carrier's keys for a transfer mutation: the redeem key in the transfer slot for WRONG_VK. */ + private static PlutusData transferKeys(TransferMutation m) { + return m == TransferMutation.WRONG_VK + ? keys(proofs.redeem().compressedVk(), proofs.redeem().compressedVk(), proofs.issue(1).compressedVk(), + proofs.issue(2).compressedVk()) + : honestKeys(); } private PlutusData transferMint(TransferMutation m) { TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x44)), BigInteger.ZERO); var builder = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).redeemer(PlutusData.constr(1, PlutusData.integer(0))); - return transferTx(m, builder, ownRef, noteDatum(out1), noteDatum(out2)).buildPlutusData(); + return transferTx(m, builder, ownRef, noteDatum(out1), noteDatum(out2), honestKeys()).buildPlutusData(); } private ScriptContextTestBuilder transferTx(TransferMutation m, ScriptContextTestBuilder b, TxOutRef ownRef, - PlutusData first, PlutusData second) { + PlutusData first, PlutusData second, PlutusData keys) { b.mint(token(PTS, m == TransferMutation.MINT_TWO ? 2 : 1)); if (m != TransferMutation.NO_SIGNER) b.signer(ALICE); if (m == TransferMutation.NO_NOTE_SPENT) { @@ -309,7 +344,14 @@ private ScriptContextTestBuilder transferTx(TransferMutation m, ScriptContextTes if (m == TransferMutation.THREE_OUTPUTS) b.output(noteOut(LEDGER, noteDatum(note(ALICE, 0, aliceView)), 1)); if (m == TransferMutation.STAKE_VARIANT_EXTRA_OUTPUT) b.output(noteOut(STAKED_LEDGER, noteDatum(out1), 0)); registry(b, m.name()); - realistic(b); + if (m == TransferMutation.NO_VK_CARRIER) { + realistic(b, null); + } else if (m == TransferMutation.VK_CARRIER_OTHER_SCRIPT) { + carrier(b, keys, filled(28, (byte) 0x66)); + realistic(b, null); + } else { + realistic(b, keys); + } return b; } @@ -317,9 +359,11 @@ private ScriptContextTestBuilder transferTx(TransferMutation m, ScriptContextTes * What a real transaction also carries, for honest costs: the ledger's own reference-script * output (at the ledger address, no token), the fee payer's input and its change output. */ - private static void realistic(ScriptContextTestBuilder b) { + private static void realistic(ScriptContextTestBuilder b, PlutusData keys) { + // The reference-script output (no keys) and, unless a mutation drops it, the key carrier. b.referenceInput(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(LEDGER, ada(40), new OutputDatum.OutputDatumInline(PlutusData.integer(BigInteger.ZERO)), Optional.of(ScriptHash.of(POLICY))))); + if (keys != null) carrier(b, keys, POLICY); b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(ALICE_WALLET, ada(50), new OutputDatum.NoOutputDatum(), Optional.empty()))); b.output(new TxOut(ALICE_WALLET, ada(45), new OutputDatum.NoOutputDatum(), Optional.empty())); @@ -359,7 +403,9 @@ enum RedeemMutation { @Test @DisplayName("Redeem: accepted by both purposes, complete cost measured; every mutation is rejected") void redeem() { - var spend = evaluate(points, redeemSpend(RedeemMutation.NONE)); + var redeemCtx = redeemSpend(RedeemMutation.NONE); + var spend = evaluate(points, redeemCtx); + CostProfiler.profile("note redeem (spend)", points, compiled, redeemCtx); assertInstanceOf(EvalResult.Success.class, spend); var mint = evaluate(points, redeemMint()); assertInstanceOf(EvalResult.Success.class, mint); @@ -383,11 +429,14 @@ private PlutusData redeemSpend(RedeemMutation m) { case PRICE_TOO_LARGE -> 1L << 32; default -> PRICE; }; - PlutusData key = m == RedeemMutation.WRONG_VK ? vk(proofs.transfer().compressedVk()) : vk(proofs.redeem().compressedVk()); var b = ScriptContextTestBuilder.spending(ownRef, inDatum()).redeemer(PlutusData.constr(1, PlutusData.integer(BigInteger.valueOf(price)), PlutusData.bytes(redeemProof.piA()), - PlutusData.bytes(redeemProof.piB()), PlutusData.bytes(redeemProof.piC()), key)); - return redeemTx(m, b, ownRef).buildPlutusData(); + PlutusData.bytes(redeemProof.piB()), PlutusData.bytes(redeemProof.piC()))); + PlutusData keys = m == RedeemMutation.WRONG_VK + ? keys(proofs.transfer().compressedVk(), proofs.transfer().compressedVk(), proofs.issue(1).compressedVk(), + proofs.issue(2).compressedVk()) + : honestKeys(); + return redeemTx(m, b, ownRef, keys).buildPlutusData(); } private PlutusData redeemMint() { @@ -397,10 +446,10 @@ private PlutusData redeemMint() { private PlutusData redeemMint(RedeemMutation m) { TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x45)), BigInteger.ONE); var b = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).redeemer(PlutusData.constr(2, PlutusData.integer(0))); - return redeemTx(m, b, ownRef).buildPlutusData(); + return redeemTx(m, b, ownRef, honestKeys()).buildPlutusData(); } - private ScriptContextTestBuilder redeemTx(RedeemMutation m, ScriptContextTestBuilder b, TxOutRef ownRef) { + private ScriptContextTestBuilder redeemTx(RedeemMutation m, ScriptContextTestBuilder b, TxOutRef ownRef, PlutusData keys) { byte[] receipt = switch (m) { case RECEIPT_NAME_NOT_DERIVED -> filled(32, (byte) 0x77); case RECEIPT_NAME_NOT_32_BYTES -> filled(31, (byte) 0x77); @@ -437,7 +486,7 @@ private ScriptContextTestBuilder redeemTx(RedeemMutation m, ScriptContextTestBui b.output(new TxOut(to, ada(2).merge(token(receipt, 1)), new OutputDatum.OutputDatumInline(PlutusData.constr(0, PlutusData.bytes(ALICE), PlutusData.integer(BigInteger.valueOf(receiptPrice)))), Optional.empty())); registry(b, m.name()); - realistic(b); + realistic(b, keys); return b; } @@ -451,7 +500,9 @@ enum IssueMutation { @Test @DisplayName("Trusted issue (points): the issuer mints notes of the current generation; every mutation is rejected") void trustedIssue() { - var honest = evaluate(points, issueContext(IssueMutation.NONE)); + var issueCtx = issueContext(IssueMutation.NONE); + var honest = evaluate(points, issueCtx); + CostProfiler.profile("note trusted issue", points, compiled, issueCtx); assertInstanceOf(EvalResult.Success.class, honest); System.out.println("[NoteLedger issue (trusted, 2 notes)] budget: " + honest.budgetConsumed()); for (IssueMutation m : IssueMutation.values()) { @@ -464,7 +515,7 @@ void trustedIssue() { private PlutusData issueContext(IssueMutation m) { PlutusData redeemer = m == IssueMutation.PROVED_ISSUE_IN_TRUSTED_MODE ? PlutusData.constr(3, PlutusData.bytes(transferProof.piA()), PlutusData.bytes(transferProof.piB()), - PlutusData.bytes(transferProof.piC()), vk(proofs.transfer().compressedVk())) + PlutusData.bytes(transferProof.piC())) : PlutusData.constr(0, PlutusData.integer(0)); var b = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).mint(token(PTS, 2)).redeemer(redeemer); if (m != IssueMutation.NO_SIGNER) b.signer(ISSUER); @@ -493,7 +544,9 @@ void provedIssue() { for (int n = 1; n <= 2; n++) { List notes = n == 1 ? List.of(out1) : List.of(out1, out2); var proof = compress(proofs.proveIssue(notes, auditor)); - var honest = evaluate(payroll, provedIssueContext(ProvedIssueMutation.NONE, notes, proof)); + var provedCtx = provedIssueContext(ProvedIssueMutation.NONE, notes, proof); + var honest = evaluate(payroll, provedCtx); + CostProfiler.profile("note proved issue n=" + n, payroll, compiled, provedCtx); assertInstanceOf(EvalResult.Success.class, honest); report("proved issue n=" + n + " (mint only)", honest, null, proofs.issue(n)); } @@ -560,8 +613,12 @@ private ScriptContextTestBuilder provedIssueBuilder(List datums, Sna SnarkjsToCardano.VkCompressed key) { var b = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).mint(token(PTS, datums.size())) .redeemer(PlutusData.constr(3, PlutusData.bytes(proof.piA()), PlutusData.bytes(proof.piB()), - PlutusData.bytes(proof.piC()), vk(key))); + PlutusData.bytes(proof.piC()))); for (PlutusData d : datums) b.output(noteOut(LEDGER, d, 1)); + // {@code key} goes in the slot of this note count (index 2 for n = 1, 3 for n = 2). + carrier(b, datums.size() == 1 + ? keys(proofs.transfer().compressedVk(), proofs.redeem().compressedVk(), key, proofs.issue(2).compressedVk()) + : keys(proofs.transfer().compressedVk(), proofs.redeem().compressedVk(), proofs.issue(1).compressedVk(), key), POLICY); return b; } @@ -582,19 +639,21 @@ void rogueVerificationKeysAreRefused() { assertTrue(rogueTransfer.verify(tProof, NoteTransferProofCircuit.publicInputs(t)), "positive control: valid under the rogue key"); var tp = compress(tProof); var spend = ScriptContextTestBuilder.spending(new TxOutRef(TxId.of(filled(32, (byte) 0x44)), BigInteger.ZERO), inDatum()) - .redeemer(PlutusData.constr(0, PlutusData.bytes(tp.piA()), PlutusData.bytes(tp.piB()), PlutusData.bytes(tp.piC()), - vk(rogueTransfer.compressedVk()))); + .redeemer(PlutusData.constr(0, PlutusData.bytes(tp.piA()), PlutusData.bytes(tp.piB()), PlutusData.bytes(tp.piC()))); var ctx = transferTx(TransferMutation.NONE, spend, new TxOutRef(TxId.of(filled(32, (byte) 0x44)), BigInteger.ZERO), - noteDatum(out1), noteDatum(out2)).buildPlutusData(); + noteDatum(out1), noteDatum(out2), keys(rogueTransfer.compressedVk(), proofs.redeem().compressedVk(), + proofs.issue(1).compressedVk(), proofs.issue(2).compressedVk())).buildPlutusData(); assertTrue(evaluate(points, ctx) instanceof EvalResult.Failure, "a transfer proof under a rogue key is refused"); var r = NoteProofs.redeemInputs(in, change, PRICE, auditor); var rp = compress(rogueRedeem.prove(r.toWitnessMap())); var rSpend = ScriptContextTestBuilder.spending(new TxOutRef(TxId.of(filled(32, (byte) 0x45)), BigInteger.ONE), inDatum()) .redeemer(PlutusData.constr(1, PlutusData.integer(BigInteger.valueOf(PRICE)), PlutusData.bytes(rp.piA()), - PlutusData.bytes(rp.piB()), PlutusData.bytes(rp.piC()), vk(rogueRedeem.compressedVk()))); + PlutusData.bytes(rp.piB()), PlutusData.bytes(rp.piC()))); assertTrue(evaluate(points, redeemTx(RedeemMutation.NONE, rSpend, - new TxOutRef(TxId.of(filled(32, (byte) 0x45)), BigInteger.ONE)).buildPlutusData()) instanceof EvalResult.Failure, + new TxOutRef(TxId.of(filled(32, (byte) 0x45)), BigInteger.ONE), keys(proofs.transfer().compressedVk(), + rogueRedeem.compressedVk(), proofs.issue(1).compressedVk(), proofs.issue(2).compressedVk())) + .buildPlutusData()) instanceof EvalResult.Failure, "a redeem proof under a rogue key is refused"); var ip = compress(rogueIssue.prove(NoteProofs.issueInputs(List.of(out1), auditor).toWitnessMap())); diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyVaultVmTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyVaultVmTest.java index e336196..89889d2 100644 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyVaultVmTest.java +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyVaultVmTest.java @@ -1,9 +1,11 @@ package com.bloxbean.cardano.zeroj.usecases.pedersen.solvency; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.CostProfiler; import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation.Customer; import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation.Entry; import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.onchain.SolvencyVault; import org.zeroj.circuit.lib.jubjub.NoteViewingKey; +import org.julclang.compiler.CompileResult; import org.julclang.core.PlutusData; import org.julclang.core.Program; import org.julclang.ledger.Address; @@ -63,6 +65,7 @@ class SolvencyVaultVmTest extends ContractTest { Optional.of(new StakingCredential.StakingHash(new Credential.PubKeyCredential(PubKeyHash.of(filled(28, (byte) 0x5a)))))); private static Program program; + private static CompileResult compiled; private static List entries; private static SnarkjsToCardano.ProofCompressed proof; @@ -73,8 +76,8 @@ static void setup() { entries = SolvencyAttestation.entries(book); proof = ProverToCardano.compressProof(solvency.prove(RESERVES, book)); var vk = solvency.circuit().compressedVk(); - program = new SolvencyVaultVmTest().compileValidator(SolvencyVault.class, Path.of("src/main/java")) - .program().applyParams( + compiled = new SolvencyVaultVmTest().compileValidatorWithSourceMap(SolvencyVault.class, Path.of("src/main/java")); + program = compiled.program().applyParams( PlutusData.bytes(EXCHANGE), PlutusData.bytes(TOKEN), PlutusData.integer(BigInteger.valueOf(SolvencyCircuitTest.N)), PlutusData.integer(BigInteger.valueOf(PERIOD_START)), @@ -97,7 +100,9 @@ enum Attest { @Test @DisplayName("Attest: an honest attestation locks the reserve; every mutation is rejected") void attest() { - var ok = evaluate(program, attestContext(Attest.NONE)); + var ctx = attestContext(Attest.NONE); + var ok = evaluate(program, ctx); + CostProfiler.profile("solvency attest", program, compiled, ctx); assertSuccess(ok); System.out.println("[SolvencyVault attest] budget: " + ok.budgetConsumed()); for (Attest m : Attest.values()) { From 11a623800569fceea30aea99a58ed861cef0f49e Mon Sep 17 00:00:00 2001 From: Satya Date: Sat, 10 Oct 2026 23:39:16 +0800 Subject: [PATCH 11/12] pedersen-commitments: retry the key-carrier deployment when the indexer lags The carrier transaction spends the payer's change from the reference-script deployment confirmed just before it; a stale UTxO view made it fail once on DevKit (payroll E2E). It is retried up to four times, and the E2E tests now print the deployment's failure reason. Co-Authored-By: Claude Opus 5.5 --- .../pedersen/auction/AuctionScript.java | 13 ++++++++++--- .../pedersen/notes/NoteLedgerScript.java | 17 ++++++++++++----- .../pedersen/auction/AuctionDevKitE2ETest.java | 3 ++- .../pedersen/notes/PayrollDevKitE2ETest.java | 3 ++- 4 files changed, 26 insertions(+), 10 deletions(-) diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java index 84b1f20..55bdc28 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionScript.java @@ -108,9 +108,16 @@ public Result deploy(BackendService backend, Account payer) { reference = DevKit.utxosOf(backend, address, result.getValue()).getFirst(); var keys = verificationKeys(); BigInteger lovelace = Plutus.minAda(backend, address, List.of(), keys).add(BigInteger.valueOf(1_000_000)); - var carried = new QuickTxBuilder(backend).compose(new Tx() - .payToContract(address, List.of(new Amount("lovelace", lovelace)), keys).from(payer.baseAddress())) - .withSigner(SignerProviders.signerFrom(payer)).complete(); + // The carrier spends the payer's change from the deployment just confirmed; the + // indexer can lag a moment behind, so a refused attempt is retried. + Result carried = null; + for (int attempt = 1; attempt <= 4; attempt++) { + carried = new QuickTxBuilder(backend).compose(new Tx() + .payToContract(address, List.of(new Amount("lovelace", lovelace)), keys).from(payer.baseAddress())) + .withSigner(SignerProviders.signerFrom(payer)).complete(); + if (carried.isSuccessful()) break; + Thread.sleep(3_000L * attempt); + } if (!carried.isSuccessful()) return carried; DevKit.waitForTx(backend, carried.getValue()); keyCarrier = DevKit.utxosOf(backend, address, carried.getValue()).getFirst(); diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerScript.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerScript.java index d6d89d3..e8aa521 100644 --- a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerScript.java +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerScript.java @@ -117,11 +117,18 @@ public Result deploy(BackendService backend, Account payer) { reference = DevKit.utxosOf(backend, address, result.getValue()).getFirst(); var keys = verificationKeys(); BigInteger lovelace = Plutus.minAda(backend, address, List.of(), keys).add(BigInteger.valueOf(1_000_000)); - var carried = new QuickTxBuilder(backend).compose(new Tx() - .payToContract(address, List.of(new Amount("lovelace", lovelace)), keys) - .from(payer.baseAddress())) - .withSigner(SignerProviders.signerFrom(payer)) - .complete(); + // The carrier spends the payer's change from the deployment just confirmed; the + // indexer can lag a moment behind, so a refused attempt is retried. + Result carried = null; + for (int attempt = 1; attempt <= 4; attempt++) { + carried = new QuickTxBuilder(backend).compose(new Tx() + .payToContract(address, List.of(new Amount("lovelace", lovelace)), keys) + .from(payer.baseAddress())) + .withSigner(SignerProviders.signerFrom(payer)) + .complete(); + if (carried.isSuccessful()) break; + Thread.sleep(3_000L * attempt); + } if (!carried.isSuccessful()) return carried; DevKit.waitForTx(backend, carried.getValue()); keyCarrier = DevKit.utxosOf(backend, address, carried.getValue()).getFirst(); diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionDevKitE2ETest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionDevKitE2ETest.java index 45121c5..dc8b1ba 100644 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionDevKitE2ETest.java +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionDevKitE2ETest.java @@ -60,7 +60,8 @@ void sealedBidAuctionOnDevKit() throws Exception { AuditorKeys keys = AuditorKeys.generate(RANDOM); ok(registry.init(backend, auctioneer, seed, keys.entry(registry.policy(), pkh(auctioneer), 0, possession)), "registry init", backend); AuctionScript auction = new AuctionScript(new AuctionProofs(), registry, 60_000, 2_000_000); - assertTrue(auction.deploy(backend, auctioneer).isSuccessful()); + var deployed1 = auction.deploy(backend, auctioneer); + assertTrue(deployed1.isSuccessful(), "deploy: " + deployed1.getResponse()); AdmittedAuditor key = registry.admitted(backend); // Open. diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/PayrollDevKitE2ETest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/PayrollDevKitE2ETest.java index 4939f0d..835fc71 100644 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/PayrollDevKitE2ETest.java +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/PayrollDevKitE2ETest.java @@ -53,7 +53,8 @@ void payrollOnDevKit() throws Exception { ok(registry.init(backend, tax, seed, taxKeys.entry(registry.policy(), pkh(tax), 0, possession)), "registry init", backend); NoteLedgerScript ledger = new NoteLedgerScript(pkh(employer), "SAL".getBytes(StandardCharsets.UTF_8), NoteProofs.withIssuance(), registry); - assertTrue(ledger.deploy(backend, employer).isSuccessful()); + var deployed1 = ledger.deploy(backend, employer); + assertTrue(deployed1.isSuccessful(), "deploy: " + deployed1.getResponse()); AdmittedAuditor auditor = registry.admitted(backend); AuditorView taxView = new AuditorView(Map.of(0L, taxKeys), ledger); From eb333be70cc0db2f42e151de60ca60508210ab3f Mon Sep 17 00:00:00 2001 From: Satya Date: Sun, 11 Oct 2026 14:32:52 +0800 Subject: [PATCH 12/12] build: pin ZeroJ 0.1.0-pre13-6a89f8a-SNAPSHOT (release candidate) The snapshot of ZeroJ main 6a89f8a (PRs #85/#86, on-chain verifier decompression, on top of everything since pre12), published to the BloxBean snapshot repository by the snapshot workflow, run 38113510199. Verified on this branch: ./gradlew test in all 14 modules (139 tests, 0 failures) and every DevKit E2E (private-voting, pedersen-commitments x6, proof-of-reserves, reusable-kyc, both PlonK examples, the account-ownership prove/verify flow) green. Co-Authored-By: Claude Opus 5.5 --- version.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.properties b/version.properties index ec96888..b3f33f8 100644 --- a/version.properties +++ b/version.properties @@ -12,6 +12,6 @@ version=0.1.0-pre7 # --- dependency versions --- -zerojVersion=0.1.0-pre13-458bfb1-SNAPSHOT +zerojVersion=0.1.0-pre13-6a89f8a-SNAPSHOT julcVersion=0.1.0-pre18 cclVersion=0.8.0-pre5