diff --git a/README.md b/README.md index d405ce8..a8c1cf4 100644 --- a/README.md +++ b/README.md @@ -250,14 +250,25 @@ 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 +``` + +`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 @@ -265,7 +276,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/account-ownership/cli/build.gradle b/account-ownership/cli/build.gradle index c26b802..55d92d5 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/demo.sh b/demo.sh index 729992d..502cc07 100755 --- a/demo.sh +++ b/demo.sh @@ -307,14 +307,19 @@ run_flow() { post_json "/api/kyc/claim" "{\"recipientAddress\":\"${recipient}\"}" ;; pedersen-commitments) - # /api/status answers while the demos warm up; wait until all three are ready. - for _ in $(seq 1 120); do + # /api/status answers while the demos warm up; wait until every demo is ready. + for _ in $(seq 1 200); do curl -fsS "${BASE_URL}/api/status" | grep -q '"ready":true' && break sleep 3 done post_json "/api/points/issue" '{"to":"alice","amount":1000}' post_json "/api/points/transfer" '{"from":"alice","to":"bob","amount":700}' post_json "/api/points/redeem" '{"from":"bob","price":120}' + post_json "/api/payroll/pay" '{"to":"carol","amount":5000}' + post_json "/api/payroll/transfer" '{"from":"carol","to":"dave","amount":800}' + post_json "/api/auction/open" '{"item":"Painting","deposit":100,"reserve":10}' + post_json "/api/auction/bid" '{"bidder":"alice","amount":40}' + post_json "/api/auction/bid" '{"bidder":"bob","amount":70}' post_json "/api/credit/issue" '{"income":85000,"creditScore":720,"birthYear":1990,"country":356}' post_json "/api/credit/claim" '{"who":"alice","minIncome":50000,"minScore":650}' post_json "/api/solvency/attest" '{"reservesAda":2000}' 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/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..c256f59 --- /dev/null +++ b/docs/adr/0007-confidential-notes-in-pedersen-demos.md @@ -0,0 +1,556 @@ +# 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 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, 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, 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 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 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), 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 + 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 `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` + 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 are replaced by new ones (`NoteTransferProof` and `NoteRedeemProof`, under new +circuit names and so new keys). 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. + - 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). + - M3–M5 implementation review (Claude R1–R12, Codex C1–C6; no P0): a same-shape rogue + verification key is tested against the hash pin (R1); the 80% gate is asserted in the VM and on + DevKit, with realistic transaction contexts (R2, C5); malformed issuer data is reported per note + (R3, C2); a note's origin counts only a consumed note of this ledger, and failed lookups are not + cached (R4); payroll history comes from the mint history (C4); amounts are `BigInteger` (R9, C1); + the solvency audit needs a live attestation (C3); missing tests added (mint without a spent note, + source scan, readable-not-mine, payroll DevKit E2E); the stake-variant and retired-key cheats now + exercise the address and key rules themselves (R6, R8); rotation keeps keys before submitting (R7); + 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 (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 | +|---|---|---| +| 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 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. +- **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` (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. | +| 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 + +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 (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 | 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 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 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. + +## 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..2313eb9 --- /dev/null +++ b/docs/adr/0008-sealed-bid-auction-enforced-disclosure.md @@ -0,0 +1,316 @@ +# 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(policy, T)`: the lot token's full asset identity. The +same seed spent in one transaction could give two differently parameterized auction scripts the +same token name `T` (implementation review, Codex C1), so the policy is part of the tag; one +output can never satisfy two lots' payouts. 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. This relies on Plutus V3's +convention that a transaction's validity interval has an inclusive lower and an exclusive upper +bound, so an upper bound of exactly `biddingEnds` is still in time (tested at the boundary). + +| 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 unique under this policy +(another auction policy could mint the same name, which is why payouts carry the policy too).
  • 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(policy, 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(policy, 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 `(policy, 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 of this auction script per transaction; payouts are tagged with the lot token's policy and name; 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 the design and implementation + reviewers verified that the gadget supports it: the key path, the shared cached decomposition, + and the `u ≠ 0` rule. ZeroJ's specs define decryption only through `R_dleq` decryption shares + (spec §9.2, §10.2), which publish `D = [sk]·A` and so would reveal every bid as `B − D`; that is + why D4 keeps the decryption inside the proof. 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. +- **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 + the lot's full pinned tuple before bidding, sweeps payouts back to the wallet, and checks each + decrypted bid against the lot (C2–C5, A6–A8); every bid mutation is tested with its own valid + proof, and the missing tests were added (A2, A3, A12). +- **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(policy, 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**: see below. + +## Measurements + +Circuits: the bid relation has 7,011 constraints and 9 public inputs. Settlement has 6,950 +(n = 1), 13,330 (n = 2) and 19,710 (n = 3) constraints, with 8, 12 and 16 public inputs. + +Julc VM, Plutus V3 cost model (protocol version 11). Each figure is the complete transaction +(every script purpose it runs), against `maxTxExecutionUnits` (10e9 steps, 16.5e6 memory), and +the test asserts ADR-0055's 80% gate. Verification keys are pinned by hash (as `NoteLedger`), +and the auction is deployed as a reference script (13 KB). + +| Transaction | VM steps | VM memory | DevKit steps | DevKit memory | +|---|---|---|---|---| +| 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, 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/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/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ 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 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/README.md b/pedersen-commitments/README.md index 8e3e7c9..fafa383 100644 --- a/pedersen-commitments/README.md +++ b/pedersen-commitments/README.md @@ -1,7 +1,8 @@ # Pedersen Commitment Demos on Cardano -Three small use cases built on ZeroJ's Pedersen commitments (`pedersen-jubjub-v1` and -`pedersen-jubjub-vector-v1`, ZeroJ ADR-0051). Each one runs end to end on Yaci DevKit: +Five use cases built on ZeroJ's Pedersen commitments (`pedersen-jubjub-v1` and +`pedersen-jubjub-vector-v1`, ZeroJ ADR-0051), confidential notes (`confidential-note-jubjub-v1`, +ZeroJ ADR-0055) and exponential ElGamal (`elgamal-jubjub-v1`, ZeroJ ADR-0052). Each one runs end to end on Yaci DevKit: - circuits proved with pure-Java Groth16 on BLS12-381; - Plutus V3 validators written in Java with Julc; - transactions built with cardano-client-lib. @@ -11,7 +12,9 @@ A web UI (Spring Boot + Svelte, port **8093**) has one tab per demo. Each tab sh read), and offers "try to cheat" actions that end in "no proof possible" or a validator rejection. A CLI walkthrough and the test suites run the same flows. -Design and threat model: [ADR-0006](../docs/adr/0006-pedersen-commitment-demos.md). +Design and threat model: [ADR-0006](../docs/adr/0006-pedersen-commitment-demos.md), +[ADR-0007](../docs/adr/0007-confidential-notes-in-pedersen-demos.md) (notes, payroll, solvency +deliveries) and [ADR-0008](../docs/adr/0008-sealed-bid-auction-enforced-disclosure.md) (auction). ## Why Pedersen commitments @@ -31,25 +34,60 @@ records and time locks. --- -## A. Confidential points +## A. Confidential points — notes with on-chain delivery and an enforced auditor amount -A retailer's loyalty points are **notes** whose amounts are commitments. +A retailer's loyalty points are **notes** (ZeroJ ADR-0055 `confidential-note-jubjub-v1`; this repo's +ADR-0007). Each note carries: +- the owner and the Pedersen commitment `C = [v]·G + [r]·H` to its amount; +- the opening `(v, r)` encrypted on-chain to the owner and to an **auditor** (Sapling-style + key agreement, BLAKE2b KDF, ChaCha20-Poly1305): wallets and the auditor recover every note from + chain data alone; +- the amount as two 32-bit `elgamal-jubjub-v1` limb ciphertexts to the auditor, which the transfer + proof binds to the commitment (ADR-0055 D3a): the auditor's amount is **enforced**, not just + delivered. | Step | On-chain | Hidden | |---|---|---| -| The retailer issues Alice 1,000 points | Owner and commitment | 1,000 | -| Alice sends Bob 700 and keeps 300 | Two new commitments and a proof that `in = out1 + out2` | 1,000 / 700 / 300 | -| Bob pays 120 at the retailer and keeps 580 | Price 120, a change commitment, and a receipt token for the retailer | 700 / 580 | - -`PointsLedger` is one multi-validator: the points policy and the note address. It enforces: -- only the retailer issues points; -- a split mints exactly one note token, and only alongside a proved transfer; -- only the owner spends a note, and one note per transaction; -- amounts are 64-bit and balance as integers, so they cannot wrap around the curve order; -- a receipt token, named after the redeemed note, can be minted only by a valid redemption, so - receipts cannot be forged or replayed. - -**Not hidden:** owners, so the transfer graph is public; and the redeemed price. +| The retailer issues Alice 1,000 points | Owner, commitment, limbs, deliveries | 1,000 | +| Alice sends Bob 700 and keeps 300 | Two new notes and a proof that `in = out1 + out2` and that both notes' limbs encrypt their amounts | 1,000 / 700 / 300 | +| Bob pays 120 at the retailer and keeps 580 | Price 120, a change note, a receipt token for the retailer | 700 / 580 | + +`NoteLedger` is one multi-validator: the note policy and the note address. It enforces: +- only the retailer issues (trusted for supply and for issued notes' audit data); +- every note output sits at the ledger's **exact** address with exactly one token and the + current auditor key generation (no stake-credential variants: ADR-0055 M3 criterion (a)); +- transfers and redemptions prove the balance and the auditor limbs, against the key read from + the auditor's registry (`AuditorRegistry`: a singleton entry whose two possession proofs are + verified on-chain, rotated under the auditor's signature); +- only the owner spends a note, one note per transaction; receipts cannot be forged or replayed. + +Wallets count a note only if its delivery opens **and** it names them as owner; an owned note +that does not open is reported as **unopenable**. The auditor reads each amount from the limbs +and labels it *proof-enforced* or *issuer-claimed*. + +**Not hidden:** owners (the transfer graph), the redeemed price, the reader policy. + +## Confidential payroll — proof-enforced issuance + +The same ledger with **proved issuance** (ADR-0055 Q9 (b)): the employer pays one or two salaries +per transaction with a proof that each salary note's limbs encrypt its committed amount to the +tax authority's registered key. The tax authority reads every salary from the chain — including +payslips already transferred or cashed out — and an employer that tries to under-report one has +no proof. Employees read their payslips with their viewing keys. + +## Sealed-bid auction — enforced bid disclosure (ADR-0008) + +Each bid is encrypted to the auctioneer with a proof that it lies between the reserve and the +common deposit, so a bidder cannot refuse to reveal (there is no reveal phase). The lot is one +state UTxO; bids are appended with their deposits. After the bidding window the auctioneer +decrypts every bid and proves — reusing the ElGamal encryption relation with its own secret as the +randomness and each bid's handle as the key — that the named bid is the earliest highest one at +its amount. Losers get their deposits back, the seller the price, the winner the item and the +change; every payout is tagged with the lot's unique token. If the auctioneer never settles, +anyone can refund after the deadline. + +**Trust:** the auctioneer sees every bid (it could leak them); losing bids never appear on chain. +Three distinct keys can fill a lot (no sybil protection in the demo). ## B. Committed credential gate @@ -88,7 +126,10 @@ proves that the hidden total is at most `R`. This follows the Provisions approac back attestations one after another. - During the period each customer derives the period's vault script themselves and reads every attestation it holds. They check that their entry, found by `blake2b(len(id) ‖ id ‖ salt)`, - appears exactly once, and then open it. + appears exactly once, and open its **on-chain delivery** with their own viewing key: the opening + comes from the chain, not from the exchange, and an entry that does not open is evidence. +- The attestation also carries the total's opening encrypted to the auditor's registered key; the + auditor opens it against the sum of the on-chain commitments. **Not provided:** - borrowed reserves, held for the period; @@ -117,7 +158,7 @@ for a scripted happy path). The image needs a ZeroJ release that includes the Pe commitment profiles (ADR-0051). Until that release, use the jar above, which builds against the version in `version.properties`. -On first start the app compiles the four circuits and runs single-party **development** setups, +On first start the app compiles the circuits and runs single-party **development** setups, cached in `data/` and keyed by an R1CS digest. It also creates and funds its demo wallets with DevKit's top-up API. `/api/status` reports each demo as `ready`; the UI waits for that. @@ -125,21 +166,24 @@ What each tab does: | Tab | Steps | Try to cheat | |---|---|---| -| A. Confidential points | The retailer issues points; holders transfer them (amounts hidden) and redeem at a public price (a receipt token goes to the retailer). | Transfer more than the largest note holds: no proof possible. Spend someone else's note: the script rejects it. | +| A. Confidential points | The retailer issues points; holders transfer them (amounts hidden) and redeem at a public price; wallets and the auditor read everything from the chain; the auditor can rotate its keys. | Transfer more than the largest note holds: no proof. A garbage delivery: unopenable for the recipient, the auditor still reads the amount. Under-report an issuance: accepted but flagged issuer-claimed. Limbs to the retired key, or a note at a stake-variant address: the ledger rejects it. Spend someone else's note: rejected. | +| Confidential payroll | The employer pays salaries (proved issuance); employees read payslips; the tax authority sees every salary and its history. | Under-report a salary: no proof. A garbage payslip, or limbs to the retired key, as above. | +| Sealed-bid auction | The seller lists an item; three bidders bid sealed amounts within a 2-minute window; the auctioneer settles with a proof; refund after the deadline. | Bid above the deposit: no proof. Copy another bidder's proof: rejected. Name a later or lower bid as the winner: no proof. | | B. Committed credential | The bureau issues a profile (four attributes, one commitment) and records it; Alice claims a badge against the lender's thresholds. | A threshold above her profile: no proof possible. Mallory presents Alice's commitment with a valid proof: the gate rejects it, because the record names Alice. | -| C. Hidden-liability solvency | Edit the book (4 customers); attest with locked reserves for a period that starts about 45 s later and lasts 180 s; customers check; the auditor opens the total; release after the period. | Lock less than the book: no proof possible. Attest again, or release, inside the period: the vault rejects it. | +| C. Hidden-liability solvency | Edit the book (4 customers); attest with locked reserves for a period that starts about 45 s later and lasts 180 s; customers decrypt their entries from the chain; the auditor opens the total from its delivery; release after the period. | Lock less than the book: no proof. A garbage delivery for one customer: their check reports it unopenable. Attest again, or release, inside the period: the vault rejects it. | Configuration (`application.yml`, or environment variables with Spring's relaxed binding): - `cardano.yaci.base-url` and `cardano.yaci.admin-url`; - `cardano.blockfrost.base-url`, which overrides the provider; -- `solvency.period-lead-seconds` and `solvency.period-length-seconds`. +- `solvency.period-lead-seconds` and `solvency.period-length-seconds`; +- `auction.bidding-seconds` and `auction.settle-seconds`. **CLI walkthrough and tests.** ```bash -./gradlew walkthrough # narrated run of all three demos on DevKit (no UI) +./gradlew walkthrough # narrated run of demos A–C on DevKit (no UI) ./gradlew test # circuits, checks, Plutus VM mutation tests -ZEROJ_YACI_E2E=true ./gradlew test # + the three DevKit end-to-end tests +ZEROJ_YACI_E2E=true ./gradlew test # + the DevKit end-to-end tests (points, payroll, auction, credit, solvency) ``` The walkthrough and the tests read `ZEROJ_YACI_STORE_URL` / `ZEROJ_YACI_ADMIN_URL` when DevKit @@ -149,23 +193,33 @@ submitted. ## Measured -| Circuit | Constraints | On-chain verification (CPU / mem) | -|---|---:|---| -| `points-transfer` (in = out1 + out2) | 7,231 | 3.85e9 / 1.19M | -| `points-redeem` (in = change + price) | 4,886 | 3.64e9 / 1.08M | -| `credit-profile-check` (4 attributes, 2 predicates) | 3,047 | 3.52e9 / 0.67M | -| `hidden-liability-solvency-n4` | 10,042 | 4.41e9 / 1.25M | +Complete transactions (every script purpose), as a share of `maxTxExecutionUnits` (10e9 steps, +16.5e6 memory); ADR-0055 adopts its auditor relation only within 80%. + +| Transaction | Constraints | Steps | Memory | +|---|---:|---|---| +| Points/payroll transfer (`note-transfer`, 24 public inputs) | 34,184 | 76.8% (DevKit) | 16.2% | +| Points/payroll redeem (`note-redeem`, 15) | 18,366 | 58.3% (DevKit) | 12.7% | +| Payroll pay run, 1 / 2 salaries (`note-issue`) | 15,890 / 31,773 | 50.8% / 71.8% (VM) | 9.0% / 13.7% | +| Auction bid (`sealed-bid`) | 7,011 | 51.0% (VM) | 22.0% | +| Auction settle, 3 bids (`sealed-bid-settle-n3`) | 19,710 | 65.6% (VM) | 25.4% | +| Auditor registry Init / Rotate (two possession proofs) | 6,548 each | 77.8% / 78.3% (DevKit) | 8.6% / 9.5% | +| `credit-profile-check` | 3,047 | 3.52e9 | 0.67M | +| `hidden-liability-solvency-n4` | 10,042 | 4.41e9 | 1.25M | ## Layout ``` src/main/java/.../pedersen/ common/ KeyedCircuit (dev keys, JSON verification), DevKit, Plutus encodings - points/ ConfidentialPoints; circuit/PointsTransferProof, PointsRedeemProof; onchain/PointsLedger + notes/ confidential notes (ADR-0007): AuditorRegistry, NoteLedger, VkLib (on-chain); + note-transfer/redeem/issue and key-possession circuits; wallet (NoteWallet), + auditor (AuditorView), keys and registry admission, transaction builders + auction/ sealed-bid auction (ADR-0008): SealedBidAuction, bid and settle circuits, AuctionScript credential/ CreditGate; circuit/CreditProfileProof; onchain/CreditGatePolicy solvency/ SolvencyAttestation; circuit/HiddenLiabilitySolvencyProof; onchain/SolvencyVault - web/ Spring services and REST API behind the UI (PointsService, CreditService, - SolvencyService, DemoController, DemoErrors, Funding) + web/ Spring services and REST API behind the UI (NoteDemo with PointsService and + PayrollService, AuctionService, CreditService, SolvencyService, DemoController) PedersenCommitmentsApplication.java the web app (port 8093) PedersenDemos.java the CLI walkthrough (./gradlew walkthrough) frontend/ Svelte 5 + Vite UI, built into src/main/resources/static @@ -175,8 +229,11 @@ frontend/ Svelte 5 + Vite UI, built into src/main/resources/static - **Dev trusted setup only.** Whoever holds the toxic waste can forge proofs. Production needs an MPC ceremony. -- **Openings are delivered off-chain.** The demos hand them over in-process. The web demo's - server holds every wallet's keys and openings on the users' behalf, and its API is - unauthenticated. +- **Demo custody.** The web demo's server holds every wallet's spending and viewing keys and the + auditors' keys, and scans the chain on their behalf; its API is unauthenticated. Real wallets + scan in their own process (ADR-0055 D9: never as a shared or network-facing service). +- **Unreviewed assumptions.** The note delivery profile rests on ADR-0055's assumptions A1–A3, + and the auction's settlement relation is this repo's own composition (ADR-0008); both need + external review. - **Not audited.** These are demos of protocol patterns, not production systems; see the "Not provided" lists above and ADR-0006. diff --git a/pedersen-commitments/build.gradle b/pedersen-commitments/build.gradle index 646054d..f01bbc4 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") } @@ -59,6 +67,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}" @@ -92,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 1abdb09..0a537a2 100644 --- a/pedersen-commitments/frontend/src/App.svelte +++ b/pedersen-commitments/frontend/src/App.svelte @@ -3,6 +3,8 @@ import Points from './tabs/Points.svelte'; import Credit from './tabs/Credit.svelte'; import Solvency from './tabs/Solvency.svelte'; + import Payroll from './tabs/Payroll.svelte'; + import Auction from './tabs/Auction.svelte'; let tab = $state('points'); let status = $state(null); @@ -21,15 +23,17 @@

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.
{#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]} @@ -42,12 +46,16 @@

{#if status?.demos?.[tab] === 'ready'} {#if tab === 'points'}{/if} + {#if tab === 'payroll'}{/if} + {#if tab === 'auction'}{/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/Auction.svelte b/pedersen-commitments/frontend/src/tabs/Auction.svelte new file mode 100644 index 0000000..3bbf587 --- /dev/null +++ b/pedersen-commitments/frontend/src/tabs/Auction.svelte @@ -0,0 +1,158 @@ + + +
+

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/frontend/src/tabs/Payroll.svelte b/pedersen-commitments/frontend/src/tabs/Payroll.svelte new file mode 100644 index 0000000..cb2244f --- /dev/null +++ b/pedersen-commitments/frontend/src/tabs/Payroll.svelte @@ -0,0 +1,116 @@ + + +
+

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 state.auditor.payslips} +
+

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.

+ + + + {#each state.auditor.payslips as p}{/each} + +
payslip UTxOemployeesalaryorigincheck
{p.utxo}{p.owner}{p.amount}{p.origin}{p.status}
+

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

+
+ {/if} + + {/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 @@ - + +
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..dc8b1ba --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/AuctionDevKitE2ETest.java @@ -0,0 +1,174 @@ +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); + var deployed1 = auction.deploy(backend, auctioneer); + assertTrue(deployed1.isSuccessful(), "deploy: " + deployed1.getResponse()); + 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..9177fca --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/auction/SealedBidAuctionVmTest.java @@ -0,0 +1,612 @@ +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; +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.compiler.CompileResult; +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 CompileResult compiled; + 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); + 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())), + 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(); + } + + /** + * 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) {} + + 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 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()) { + 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, 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 + } + + @Test + @DisplayName("Bid: the third bid is appended with its deposit and proof; every mutation is rejected") + void placeBid() { + 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()) { + 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 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())); + 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(); + 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 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); + 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 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())); + 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); + 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 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()) { + 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; + } +} 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/common/DevKitPaddingTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/DevKitPaddingTest.java new file mode 100644 index 0000000..142d567 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/DevKitPaddingTest.java @@ -0,0 +1,18 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.common; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** The evaluator's headroom share must not overflow for transactions near the step limit. */ +class DevKitPaddingTest { + + @Test + @DisplayName("Headroom is shared without long overflow (2.2e9 · 7.8e9 > Long.MAX_VALUE)") + void shareDoesNotOverflow() { + assertEquals(2_220_000_000L, DevKit.share(2_220_000_000L, 7_780_000_000L, 7_780_000_000L)); + assertEquals(1_110_000_000L, DevKit.share(2_220_000_000L, 3_890_000_000L, 7_780_000_000L)); + assertEquals(0, DevKit.share(5, 5, 0)); + } +} 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 new file mode 100644 index 0000000..8b3c0df --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/AuditorRegistryVmTest.java @@ -0,0 +1,357 @@ +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; +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 CompileResult compiled; + 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); + 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()), + 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 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()) { + 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 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()) { + 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/NoteCircuitTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteCircuitTest.java new file mode 100644 index 0000000..7916c61 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteCircuitTest.java @@ -0,0 +1,180 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +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.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.ElGamalSecretKey; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.NoteOpening; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The note circuits (ADR-0007 N3, N4): honest proofs verify against exactly the public inputs the + * ledger rebuilds, and every invalid witness of ZeroJ ADR-0055 I12 has no satisfying assignment. + */ +class NoteCircuitTest { + + static final SecureRandom RANDOM = new SecureRandom(); + static final byte[] ALICE = filled(28, (byte) 0x0a); + static final byte[] BOB = filled(28, (byte) 0x0b); + static final BigInteger TWO_32 = BigInteger.ONE.shiftLeft(32); + + static NoteProofs proofs; + static AuditorKeys auditorKeys; + static AdmittedAuditor auditor; + static NoteViewingKey aliceView = NoteViewingKey.generate(RANDOM); + static NoteViewingKey bobView = NoteViewingKey.generate(RANDOM); + + @BeforeAll + static void setup() { + proofs = NoteProofs.withIssuance(); + auditorKeys = AuditorKeys.generate(RANDOM); + KeyPossession possession = new KeyPossession(); + byte[] registry = filled(28, (byte) 0x3e); + auditor = AdmittedAuditor.admit(registry, auditorKeys.entry(registry, filled(28, (byte) 0xa1), 0, possession), possession); + System.out.printf("[note circuits] transfer %d constraints / %d public; redeem %d / %d; issue1 %d / %d; issue2 %d / %d%n", + proofs.transfer().numConstraints(), proofs.transfer().numPublicInputs(), + proofs.redeem().numConstraints(), proofs.redeem().numPublicInputs(), + proofs.issue(1).numConstraints(), proofs.issue(1).numPublicInputs(), + proofs.issue(2).numConstraints(), proofs.issue(2).numPublicInputs()); + } + + static NoteProofs.Spent spent(long amount) { + NoteOpening o = NoteOpening.random(BigInteger.valueOf(amount), RANDOM); + JubjubPoint c = o.commitment().normalized(); + return new NoteProofs.Spent(o, c.affineU(), c.affineV()); + } + + static AuditedNote note(byte[] owner, long amount, NoteViewingKey view) { + return AuditedNote.create(owner, amount, view.readerKey(), auditor, RANDOM); + } + + @Test + @DisplayName("Honest transfer, redeem and issuance proofs verify against the ledger's public inputs, and only those") + void honest() { + long big = 0x1_2345_6789L; // above 2^32, so both limbs are non-zero + NoteProofs.Spent in = spent(big); + AuditedNote o1 = note(BOB, 700, bobView); + AuditedNote o2 = note(ALICE, big - 700, aliceView); + var t = NoteProofs.transferInputs(in, o1, o2, auditor); + List tPublic = NoteTransferProofCircuit.publicInputs(t); + assertEquals(24, tPublic.size()); + var tProof = proofs.proveTransfer(in, o1, o2, auditor); + assertTrue(proofs.transfer().verify(tProof, tPublic)); + List wrong = new ArrayList<>(tPublic); + wrong.set(10, wrong.get(10).add(BigInteger.ONE)); + assertTrue(!proofs.transfer().verify(tProof, wrong), "an audit coordinate is bound"); + + AuditedNote change = note(ALICE, big - 120, aliceView); + var r = NoteProofs.redeemInputs(in, change, 120, auditor); + assertEquals(15, NoteRedeemProofCircuit.publicInputs(r).size()); + assertTrue(proofs.redeem().verify(proofs.proveRedeem(in, change, 120, auditor), NoteRedeemProofCircuit.publicInputs(r))); + + for (int n = 1; n <= 2; n++) { + List issued = n == 1 ? List.of(note(ALICE, 5_000, aliceView)) + : List.of(note(ALICE, 5_000, aliceView), note(BOB, big, bobView)); + var i = NoteProofs.issueInputs(issued, auditor); + List iPublic = NoteIssueProofCircuit.publicInputs(i); + assertEquals(10 * n + 2, iPublic.size()); + assertTrue(proofs.issue(n).verify(proofs.proveIssue(issued, auditor), iPublic)); + } + } + + @Test + @DisplayName("I12 invalid witnesses: wrong limb, limb at 2^32, swapped limbs, swapped notes, another key, another amount") + void invalidTransferWitnesses() { + NoteProofs.Spent in = spent(1_000); + AuditedNote o1 = note(BOB, 700, bobView); + AuditedNote o2 = note(ALICE, 300, aliceView); + List a1 = o1.audit(); + List a2 = o2.audit(); + + noTransferWitness(in, o1, o2, i -> i.o1L0(o1.limbs().get(0).message().add(BigInteger.ONE)), + "a limb that is not the encrypted message"); + // A limb at 2^32: out2 = 2^32 + 300 has limbs (300, 1). (300 + 2^32, 0) recombines to the + // same amount and is encrypted honestly (test fixture), so only the 32-bit range refuses it. + NoteProofs.Spent bigIn = spent(TWO_32.longValueExact() + 1_000); + AuditedNote small = note(BOB, 700, bobView); + AuditedNote big = note(ALICE, TWO_32.longValueExact() + 300, aliceView); + BigInteger k0 = big.limbs().get(0).randomness(); + BigInteger k1 = big.limbs().get(1).randomness(); + BigInteger l0 = big.limbs().get(0).message().add(TWO_32); + assertEquals(BigInteger.ONE, big.limbs().get(1).message()); + JubjubPoint pk = auditorKeys.elgamal().publicKey().point(); + List c0 = fixtureLimb(l0, k0, pk); + List c1 = fixtureLimb(BigInteger.ZERO, k1, pk); + noTransferWitness(bigIn, small, big, i -> i.o2L0(l0).o2L1(BigInteger.ZERO) + .o2a0u(c0.get(0)).o2a0v(c0.get(1)).o2b0u(c0.get(2)).o2b0v(c0.get(3)) + .o2a1u(c1.get(0)).o2a1v(c1.get(1)).o2b1u(c1.get(2)).o2b1v(c1.get(3)), "a limb at or above 2^32"); + // Positive control: the same mutation tooling with the honest decomposition proves. + proofs.transfer().prove(NoteProofs.transferInputs(bigIn, small, big, auditor).toWitnessMap()); + noTransferWitness(in, o1, o2, i -> i + .o1a0u(a1.get(4)).o1a0v(a1.get(5)).o1b0u(a1.get(6)).o1b0v(a1.get(7)) + .o1a1u(a1.get(0)).o1a1v(a1.get(1)).o1b1u(a1.get(2)).o1b1v(a1.get(3)), "limb ciphertexts swapped"); + noTransferWitness(in, o1, o2, i -> i + .o1a0u(a2.get(0)).o1a0v(a2.get(1)).o1b0u(a2.get(2)).o1b0v(a2.get(3)) + .o1a1u(a2.get(4)).o1a1v(a2.get(5)).o1b1u(a2.get(6)).o1b1v(a2.get(7)) + .o2a0u(a1.get(0)).o2a0v(a1.get(1)).o2b0u(a1.get(2)).o2b0v(a1.get(3)) + .o2a1u(a1.get(4)).o2a1v(a1.get(5)).o2b1u(a1.get(6)).o2b1v(a1.get(7)), "audit data swapped between notes"); + var stranger = ElGamalSecretKey.generate(RANDOM).publicKey(); + noTransferWitness(in, o1, o2, i -> i.pkU(stranger.affineU()).pkV(stranger.affineV()), "another key"); + var other = ElGamal.encryptWithOpening(auditor.context(), BigInteger.valueOf(701), 32, RANDOM); + noTransferWitness(in, o1, o2, i -> { + var ct = other.ciphertext(); + i.o1L0(other.message()).o1K0(other.randomness()) + .o1a0u(ct.handle().affineU()).o1a0v(ct.handle().affineV()) + .o1b0u(ct.blinded().affineU()).o1b0v(ct.blinded().affineV()); + }, "limbs of another amount"); + } + + @Test + @DisplayName("Proved issuance: an issuer whose audit ciphertext under-reports the amount has no proof (Q9 (b))") + void underReportedIssuanceHasNoProof() { + AuditedNote honest = note(ALICE, 5_000, aliceView); + AuditedNote understated = honest.withLimbs(AuditedNote.limbsOf(BigInteger.valueOf(500), auditor, RANDOM)); + assertThrows(RuntimeException.class, () -> proofs.proveIssue(List.of(understated), auditor)); + assertThrows(RuntimeException.class, () -> proofs.proveIssue(List.of(note(BOB, 9, bobView), understated), auditor)); + proofs.proveIssue(List.of(honest), auditor); + } + + private static void noTransferWitness(NoteProofs.Spent in, AuditedNote o1, AuditedNote o2, + Consumer mutate, String what) { + var inputs = NoteProofs.transferInputs(in, o1, o2, auditor); + mutate.accept(inputs); + Map> w = inputs.toWitnessMap(); + assertThrows(RuntimeException.class, () -> proofs.transfer().prove(w), what); + } + + /** + * Test fixture only. A limb ciphertext from a chosen {@code m} and {@code k} with the + * variable-time {@code scalarMul}, to build out-of-range limbs the library refuses to encrypt. + */ + private static List fixtureLimb(BigInteger m, BigInteger k, JubjubPoint pk) { + JubjubPoint g = JubjubPoint.SUBGROUP_GENERATOR; + JubjubPoint a = g.scalarMul(k).normalized(); + JubjubPoint b = g.scalarMul(m).add(pk.scalarMul(k)).normalized(); + return List.of(a.affineU(), a.affineV(), b.affineU(), b.affineV()); + } + + 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/NoteLedgerVmTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerVmTest.java new file mode 100644 index 0000000..51b519f --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteLedgerVmTest.java @@ -0,0 +1,718 @@ +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; +import org.julclang.ledger.Credential; +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 org.zeroj.circuit.lib.jubjub.NoteOpening; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; +import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; +import org.zeroj.onchain.julc.groth16.codec.SnarkjsToCardano; + +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 NoteLedger} in the Plutus VM (ADR-0007 N2–N4; ZeroJ ADR-0055 M3). Honest issuance (trusted + * and proved), transfer and redemption are accepted, and their complete-transaction cost (spending + * plus minting purpose) is printed against the per-transaction limits for ADR-0055's 80% gate. + * Every mutation of ADR-0006 P1–P8, ADR-0055 D3a/D8 and ADR-0007 N2 is rejected, including an + * output under the ledger's payment credential with another stake credential (M3 criterion (a)). + */ +class NoteLedgerVmTest 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) 0x9a); + static final byte[] REGISTRY_POLICY = filled(28, (byte) 0x3e); + static final byte[] ISSUER = filled(28, (byte) 0x15); + static final byte[] ALICE = filled(28, (byte) 0x0a); + static final byte[] BOB = filled(28, (byte) 0x0b); + static final byte[] AUDITOR = filled(28, (byte) 0xa1); + static final byte[] PTS = "PTS".getBytes(StandardCharsets.UTF_8); + static final byte[] REG = Registry.TOKEN; + static final long GENERATION = 3; + static final long PRICE = 120; + static final Address LEDGER = new Address(new Credential.ScriptCredential(ScriptHash.of(POLICY)), Optional.empty()); + static final Address STAKED_LEDGER = new Address(LEDGER.credential(), Optional.of(new StakingCredential.StakingHash( + new Credential.PubKeyCredential(PubKeyHash.of(filled(28, (byte) 0x5a)))))); + static final Address REGISTRY = new Address(new Credential.ScriptCredential(ScriptHash.of(REGISTRY_POLICY)), Optional.empty()); + static final Address ISSUER_ADDRESS = new Address(new Credential.PubKeyCredential(PubKeyHash.of(ISSUER)), Optional.empty()); + static final Address ALICE_WALLET = new Address(new Credential.PubKeyCredential(PubKeyHash.of(ALICE)), Optional.empty()); + + static NoteProofs proofs; + static Program points; + static Program payroll; + static CompileResult compiled; + static KeyPossession possession; + static RegistryEntry entry; + static RegistryEntry otherEntry; + static AdmittedAuditor auditor; + static AdmittedAuditor otherAuditor; + static NoteViewingKey aliceView = NoteViewingKey.generate(RANDOM); + static NoteViewingKey bobView = NoteViewingKey.generate(RANDOM); + + static NoteProofs.Spent in; + static AuditedNote out1; + static AuditedNote out2; + static AuditedNote change; + static SnarkjsToCardano.ProofCompressed transferProof; + static SnarkjsToCardano.ProofCompressed redeemProof; + + @BeforeAll + static void setup() { + proofs = NoteProofs.withIssuance(); + possession = new KeyPossession(); + entry = AuditorKeys.generate(RANDOM).entry(REGISTRY_POLICY, AUDITOR, GENERATION, possession); + otherEntry = AuditorKeys.generate(RANDOM).entry(REGISTRY_POLICY, AUDITOR, GENERATION, possession); + auditor = AdmittedAuditor.admit(REGISTRY_POLICY, entry, possession); + otherAuditor = AdmittedAuditor.admit(REGISTRY_POLICY, otherEntry, possession); + 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); + out1 = note(BOB, 700, bobView); + out2 = note(ALICE, balance - 700, aliceView); + change = note(ALICE, balance - PRICE, aliceView); + transferProof = compress(proofs.proveTransfer(in, out1, out2, auditor)); + redeemProof = compress(proofs.proveRedeem(in, change, PRICE, auditor)); + } + + static PlutusData[] params(boolean proved) { + return new PlutusData[]{PlutusData.bytes(ISSUER), PlutusData.bytes(PTS), + PlutusData.integer(BigInteger.valueOf(proved ? 1 : 0)), + PlutusData.bytes(REGISTRY_POLICY), PlutusData.bytes(REG), + PlutusData.bytes(VerificationKeys.hash(proofs.transfer().compressedVk())), + PlutusData.bytes(VerificationKeys.hash(proofs.redeem().compressedVk())), + PlutusData.bytes(proved ? VerificationKeys.hash(proofs.issue(1).compressedVk()) : new byte[32]), + PlutusData.bytes(proved ? VerificationKeys.hash(proofs.issue(2).compressedVk()) : new byte[32])}; + } + + static NoteProofs.Spent spent(long amount) { + NoteOpening o = NoteOpening.random(BigInteger.valueOf(amount), RANDOM); + JubjubPoint c = o.commitment().normalized(); + return new NoteProofs.Spent(o, c.affineU(), c.affineV()); + } + + static AuditedNote note(byte[] owner, long amount, NoteViewingKey view) { + return AuditedNote.create(owner, amount, view.readerKey(), auditor, RANDOM); + } + + static SnarkjsToCardano.ProofCompressed compress(Groth16ProofBLS381 proof) { + return ProverToCardano.compressProof(proof); + } + + // ------------------------------------------------------------------ encodings + + /** {@code Note(owner, u, v, generation, audit, deliveries)} with explicit audit data and deliveries. */ + static PlutusData noteDatum(byte[] owner, BigInteger u, BigInteger v, long generation, List audit, + List deliveries) { + PlutusData[] a = audit.stream().map(PlutusData::integer).toArray(PlutusData[]::new); + PlutusData[] d = deliveries.stream().map(PlutusData::bytes).toArray(PlutusData[]::new); + return PlutusData.constr(0, PlutusData.bytes(owner), PlutusData.integer(u), PlutusData.integer(v), + PlutusData.integer(BigInteger.valueOf(generation)), PlutusData.list(a), PlutusData.list(d)); + } + + static PlutusData noteDatum(AuditedNote n) { + return noteDatum(n.owner(), n.u(), n.v(), GENERATION, n.audit(), n.deliveries()); + } + + static TxOut noteOut(Address at, PlutusData datum, int tokens) { + return new TxOut(at, ada(4).merge(token(PTS, tokens)), new OutputDatum.OutputDatumInline(datum), Optional.empty()); + } + + static TxInInfo registryInput(RegistryEntry e, long quantity, PlutusData datum) { + Value value = ada(8).merge(Value.singleton(PolicyId.of(REGISTRY_POLICY), TokenName.of(REG), BigInteger.valueOf(quantity))); + return new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), + new TxOut(REGISTRY, value, new OutputDatum.OutputDatumInline(datum), Optional.empty())); + } + + static PlutusData entryDatum(RegistryEntry e) { + return AuditorRegistryVmTest.datum(e); + } + + 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, + 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, + REGISTRY_MISSING, REGISTRY_OTHER_KEY, REGISTRY_SECOND_ENTRY, REGISTRY_QUANTITY_TWO, REGISTRY_EXTRA_FIELD, + REGISTRY_WRONG_TOKEN, NO_NOTE_SPENT + } + + @Test + @DisplayName("Transfer: accepted by both purposes, complete cost measured; every mutation is rejected") + void transfer() { + 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 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()) { + if (m != TransferMutation.NONE + && evaluate(points, transferSpend(m, out1, out2, transferProof)) instanceof EvalResult.Success) { + fail("Transfer spend accepted " + m); + } + } + for (TransferMutation m : List.of(TransferMutation.MINT_TWO, TransferMutation.EXTRA_SCRIPT_INPUT, + TransferMutation.EXTRA_STAKED_SCRIPT_INPUT, TransferMutation.NO_NOTE_SPENT)) { + if (evaluate(points, transferMint(m)) instanceof EvalResult.Success) fail("Split mint accepted " + m); + } + } + + @Test + @DisplayName("Transfer: one limb randomness reused (within a note, across notes) proves, but the ledger refuses") + void reusedHandles() { + // Reuse within out1: limb 1 encrypted with limb 0's k (test fixture; the prover cannot be stopped). + BigInteger k = out1.limbs().get(0).randomness(); + List c = fixtureLimb(out1.limbs().get(1).message(), k, auditor); + var inputs = NoteProofs.transferInputs(in, out1, out2, auditor) + .o1K1(k).o1a1u(c.get(0)).o1a1v(c.get(1)).o1b1u(c.get(2)).o1b1v(c.get(3)); + var proof = compress(proofs.transfer().prove(inputs.toWitnessMap())); + List a1 = new ArrayList<>(out1.audit().subList(0, 4)); + a1.addAll(c); + PlutusData o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION, a1, out1.deliveries()); + if (evaluate(points, transferSpend(TransferMutation.NONE, o1, noteDatum(out2), proof)) instanceof EvalResult.Success) { + fail("one k for both limbs of a note was accepted"); + } + // Reuse across notes: out2's limb 0 with out1's limb-0 k. + List c2 = fixtureLimb(out2.limbs().get(0).message(), k, auditor); + var inputs2 = NoteProofs.transferInputs(in, out1, out2, auditor) + .o2K0(k).o2a0u(c2.get(0)).o2a0v(c2.get(1)).o2b0u(c2.get(2)).o2b0v(c2.get(3)); + var proof2 = compress(proofs.transfer().prove(inputs2.toWitnessMap())); + List a2 = new ArrayList<>(c2); + a2.addAll(out2.audit().subList(4, 8)); + PlutusData o2 = noteDatum(out2.owner(), out2.u(), out2.v(), GENERATION, a2, out2.deliveries()); + if (evaluate(points, transferSpend(TransferMutation.NONE, noteDatum(out1), o2, proof2)) instanceof EvalResult.Success) { + fail("one k across two notes was accepted"); + } + } + + private PlutusData transferSpend(TransferMutation m, AuditedNote a, AuditedNote b, SnarkjsToCardano.ProofCompressed p) { + return transferSpend(m, noteDatum(a), noteDatum(b), p); + } + + 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(); + var builder = ScriptContextTestBuilder.spending(ownRef, inDatum()).redeemer(PlutusData.constr(0, + 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), honestKeys()).buildPlutusData(); + } + + private ScriptContextTestBuilder transferTx(TransferMutation m, ScriptContextTestBuilder b, TxOutRef ownRef, + 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) { + // "Free tokens": a Split mint with no note spent, the new notes paid to the exact address. + b.input(new TxInInfo(ownRef, new TxOut(ALICE_WALLET, ada(10), new OutputDatum.NoOutputDatum(), Optional.empty()))); + } else { + b.input(m == TransferMutation.INPUT_WITHOUT_TOKEN + ? new TxInInfo(ownRef, new TxOut(LEDGER, ada(4), new OutputDatum.OutputDatumInline(inDatum()), Optional.empty())) + : new TxInInfo(ownRef, noteOut(LEDGER, inDatum(), 1))); + } + if (m == TransferMutation.EXTRA_SCRIPT_INPUT) { + b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), noteOut(LEDGER, noteDatum(out1), 1))); + } + if (m == TransferMutation.EXTRA_STAKED_SCRIPT_INPUT) { + b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), noteOut(STAKED_LEDGER, noteDatum(out1), 1))); + } + PlutusData o1 = first; + PlutusData o2 = second; + List a1 = new ArrayList<>(out1.audit()); + List a2 = new ArrayList<>(out2.audit()); + List d1 = new ArrayList<>(out1.deliveries()); + switch (m) { + case SWAPPED_OUTPUTS -> { o1 = second; o2 = first; } + case AUDIT_ABSENT -> o1 = PlutusData.constr(0, PlutusData.bytes(out1.owner()), PlutusData.integer(out1.u()), + PlutusData.integer(out1.v()), PlutusData.integer(BigInteger.valueOf(GENERATION)), + PlutusData.list(out1.deliveries().stream().map(PlutusData::bytes).toArray(PlutusData[]::new))); + case AUDIT_WRONG_OUT1 -> { a1.set(5, a1.get(5).add(BigInteger.ONE)); o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION, a1, d1); } + case AUDIT_WRONG_OUT2 -> { a2.set(0, a2.get(0).add(BigInteger.ONE)); o2 = noteDatum(out2.owner(), out2.u(), out2.v(), GENERATION, a2, out2.deliveries()); } + case AUDIT_SWAPPED_BETWEEN_OUTPUTS -> { + o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION, a2, d1); + o2 = noteDatum(out2.owner(), out2.u(), out2.v(), GENERATION, a1, out2.deliveries()); + } + case AUDIT_LIMBS_SWAPPED -> { + List s = new ArrayList<>(a1.subList(4, 8)); + s.addAll(a1.subList(0, 4)); + o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION, s, d1); + } + case AUDIT_NON_CANONICAL -> { a1.set(2, a1.get(2).add(JubjubCurve.BASE_FIELD_PRIME)); o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION, a1, d1); } + case AUDIT_SEVEN_ENTRIES -> o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION, a1.subList(0, 7), d1); + case DELIVERY_SHORT -> { d1.set(1, Arrays.copyOf(d1.get(1), 88)); o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION, a1, d1); } + case DELIVERY_MISSING -> { d1.remove(1); o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION, a1, d1); } + case DELIVERY_EXTRA -> { d1.add(d1.get(0)); o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION, a1, d1); } + case STALE_GENERATION -> o1 = noteDatum(out1.owner(), out1.u(), out1.v(), GENERATION - 1, a1, d1); + case NON_CANONICAL_OUTPUT -> o2 = noteDatum(out2.owner(), out2.u().add(JubjubCurve.BASE_FIELD_PRIME), out2.v(), + GENERATION, a2, out2.deliveries()); + default -> { } + } + Value v1 = ada(4).merge(token(PTS, m == TransferMutation.OUTPUT_TWO_TOKENS ? 2 : 1)); + if (m == TransferMutation.OUTPUT_EXTRA_ASSET) v1 = v1.merge(Value.singleton(PolicyId.of(filled(28, (byte) 0x77)), TokenName.of("Z".getBytes()), BigInteger.ONE)); + b.output(new TxOut(LEDGER, v1, new OutputDatum.OutputDatumInline(o1), Optional.empty())); + b.output(noteOut(m == TransferMutation.STAKE_VARIANT_NOTE ? STAKED_LEDGER : LEDGER, o2, 1)); + 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()); + 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; + } + + /** + * 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, 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())); + } + + /** The registry reference input, or a mutation of it named by {@code m}. */ + private static void registry(ScriptContextTestBuilder b, String m) { + switch (m) { + case "REGISTRY_MISSING" -> { } + case "REGISTRY_OTHER_KEY" -> b.referenceInput(registryInput(otherEntry, 1, entryDatum(otherEntry))); + case "REGISTRY_SECOND_ENTRY" -> { + b.referenceInput(registryInput(entry, 1, entryDatum(entry))); + b.referenceInput(registryInput(otherEntry, 1, entryDatum(otherEntry))); + } + case "REGISTRY_QUANTITY_TWO" -> b.referenceInput(registryInput(entry, 2, entryDatum(entry))); + case "REGISTRY_EXTRA_FIELD" -> { + List f = AuditorRegistryVmTest.fields(entry); + f.add(PlutusData.integer(BigInteger.ONE)); + b.referenceInput(registryInput(entry, 1, AuditorRegistryVmTest.constr(f))); + } + case "REGISTRY_WRONG_TOKEN" -> b.referenceInput(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), + new TxOut(REGISTRY, ada(8).merge(Value.singleton(PolicyId.of(REGISTRY_POLICY), TokenName.of("REX".getBytes()), BigInteger.ONE)), + new OutputDatum.OutputDatumInline(entryDatum(entry)), Optional.empty()))); + default -> b.referenceInput(registryInput(entry, 1, entryDatum(entry))); + } + } + + // ------------------------------------------------------------------ Redeem + + enum RedeemMutation { + NONE, NO_SIGNER, PRICE_IN_REDEEMER, RECEIPT_PRICE, RECEIPT_TO_OTHER, RECEIPT_NAME_NOT_DERIVED, NO_RECEIPT_MINTED, + ALSO_MINT_PTS, PRICE_ZERO, PRICE_TOO_LARGE, TWO_CHANGE_NOTES, STAKE_VARIANT_CHANGE, AUDIT_WRONG, DELIVERY_MISSING, + STALE_GENERATION, REGISTRY_MISSING, REGISTRY_OTHER_KEY, WRONG_VK, NO_NOTE_SPENT, TWO_NOTES_SPENT, + RECEIPT_NAME_NOT_32_BYTES + } + + @Test + @DisplayName("Redeem: accepted by both purposes, complete cost measured; every mutation is rejected") + void redeem() { + 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); + report("redeem (spend + Receipt mint)", spend, mint, proofs.redeem()); + for (RedeemMutation m : RedeemMutation.values()) { + if (m != RedeemMutation.NONE && evaluate(points, redeemSpend(m)) instanceof EvalResult.Success) { + fail("Redeem spend accepted " + m); + } + } + for (RedeemMutation m : List.of(RedeemMutation.ALSO_MINT_PTS, RedeemMutation.NO_NOTE_SPENT, + RedeemMutation.TWO_NOTES_SPENT, RedeemMutation.RECEIPT_NAME_NOT_32_BYTES)) { + if (evaluate(points, redeemMint(m)) instanceof EvalResult.Success) fail("Receipt mint accepted " + m); + } + } + + private PlutusData redeemSpend(RedeemMutation m) { + TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x45)), BigInteger.ONE); + long price = switch (m) { + case PRICE_IN_REDEEMER -> PRICE - 1; + case PRICE_ZERO -> 0; + case PRICE_TOO_LARGE -> 1L << 32; + default -> PRICE; + }; + 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()))); + 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() { + return redeemMint(RedeemMutation.NONE); + } + + 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, honestKeys()).buildPlutusData(); + } + + 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); + default -> receiptName(ownRef); + }; + Value mint = m == RedeemMutation.NO_RECEIPT_MINTED ? Value.zero() : token(receipt, 1); + if (m == RedeemMutation.ALSO_MINT_PTS) mint = mint.merge(token(PTS, 1)); + b.mint(mint); + if (m != RedeemMutation.NO_SIGNER) b.signer(ALICE); + b.input(m == RedeemMutation.NO_NOTE_SPENT + ? new TxInInfo(ownRef, new TxOut(ALICE_WALLET, ada(10), new OutputDatum.NoOutputDatum(), Optional.empty())) + : new TxInInfo(ownRef, noteOut(LEDGER, inDatum(), 1))); + if (m == RedeemMutation.TWO_NOTES_SPENT) { + b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), noteOut(LEDGER, noteDatum(out1), 1))); + } + List a = new ArrayList<>(change.audit()); + List d = new ArrayList<>(change.deliveries()); + long generation = GENERATION; + switch (m) { + case AUDIT_WRONG -> a.set(7, a.get(7).add(BigInteger.ONE)); + case DELIVERY_MISSING -> d.remove(1); + case STALE_GENERATION -> generation = GENERATION - 1; + default -> { } + } + PlutusData c = noteDatum(change.owner(), change.u(), change.v(), generation, a, d); + b.output(noteOut(m == RedeemMutation.STAKE_VARIANT_CHANGE ? STAKED_LEDGER : LEDGER, c, 1)); + if (m == RedeemMutation.TWO_CHANGE_NOTES) b.output(noteOut(LEDGER, noteDatum(note(ALICE, 0, aliceView)), 1)); + long receiptPrice = switch (m) { + case RECEIPT_PRICE -> PRICE + 1; + case PRICE_IN_REDEEMER -> PRICE - 1; + default -> PRICE; + }; + Address to = m == RedeemMutation.RECEIPT_TO_OTHER ? ALICE_WALLET : ISSUER_ADDRESS; + 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, keys); + return b; + } + + // ------------------------------------------------------------------ Issue (trusted, points) + + enum IssueMutation { + NONE, NO_SIGNER, NOTE_SPENT, COUNT_MISMATCH, STAKE_VARIANT_NOTE, STAKE_VARIANT_EXTRA_OUTPUT, DELIVERY_SHORT, + STALE_GENERATION, REGISTRY_MISSING, PROVED_ISSUE_IN_TRUSTED_MODE + } + + @Test + @DisplayName("Trusted issue (points): the issuer mints notes of the current generation; every mutation is rejected") + void trustedIssue() { + 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()) { + if (m != IssueMutation.NONE && evaluate(points, issueContext(m)) instanceof EvalResult.Success) { + fail("Issue accepted " + m); + } + } + } + + 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())) + : 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); + if (m == IssueMutation.NOTE_SPENT) b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), noteOut(LEDGER, inDatum(), 1))); + List d = new ArrayList<>(out1.deliveries()); + if (m == IssueMutation.DELIVERY_SHORT) d.set(0, Arrays.copyOf(d.get(0), 88)); + long generation = m == IssueMutation.STALE_GENERATION ? GENERATION - 1 : GENERATION; + b.output(noteOut(m == IssueMutation.STAKE_VARIANT_NOTE ? STAKED_LEDGER : LEDGER, + noteDatum(out1.owner(), out1.u(), out1.v(), generation, out1.audit(), d), 1)); + if (m != IssueMutation.COUNT_MISMATCH) b.output(noteOut(LEDGER, noteDatum(out2), 1)); + if (m == IssueMutation.STAKE_VARIANT_EXTRA_OUTPUT) b.output(noteOut(STAKED_LEDGER, noteDatum(out1), 0)); + registry(b, m.name()); + return b.buildPlutusData(); + } + + // ------------------------------------------------------------------ ProvedIssue (payroll) + + enum ProvedIssueMutation { + NONE, UNDER_REPORTED_IN_DATUM, PROOF_FOR_OTHER_KEY, REUSED_HANDLE_ACROSS_NOTES, COUNT_MISMATCH, + LEDGER_INPUT_SPENT, NO_SIGNER, WRONG_VK, TRUSTED_ISSUE_IN_PROVED_MODE, STAKE_VARIANT_EXTRA_OUTPUT, REGISTRY_MISSING + } + + @Test + @DisplayName("Proved issue (payroll): n = 1 and n = 2 accepted with cost measured; an issuer that under-reports or mutates is refused") + 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 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)); + } + List notes = List.of(out1, out2); + var proof = compress(proofs.proveIssue(notes, auditor)); + for (ProvedIssueMutation m : ProvedIssueMutation.values()) { + if (m == ProvedIssueMutation.NONE || m == ProvedIssueMutation.PROOF_FOR_OTHER_KEY + || m == ProvedIssueMutation.REUSED_HANDLE_ACROSS_NOTES) { + continue; + } + if (evaluate(payroll, provedIssueContext(m, notes, proof)) instanceof EvalResult.Success) { + fail("ProvedIssue accepted " + m); + } + } + // Limbs to another key, proved honestly against that key: the ledger feeds the registry key. + AuditedNote foreign1 = AuditedNote.create(ALICE, 5_000, aliceView.readerKey(), otherAuditor, RANDOM); + var foreignProof = compress(proofs.proveIssue(List.of(foreign1), otherAuditor)); + if (evaluate(payroll, provedIssueContext(ProvedIssueMutation.PROOF_FOR_OTHER_KEY, List.of(foreign1), foreignProof)) + instanceof EvalResult.Success) { + fail("ProvedIssue accepted limbs to a key that is not the registry's"); + } + // One k for limb 0 of both notes: provable, refused by the distinct-handle rule. + BigInteger k = out1.limbs().get(0).randomness(); + List c = fixtureLimb(out2.limbs().get(0).message(), k, auditor); + var inputs = NoteProofs.issueInputs(notes, auditor); + List audit = new ArrayList<>(out1.audit()); + List a2 = new ArrayList<>(c); + a2.addAll(out2.audit().subList(4, 8)); + audit.addAll(a2); + List ks = new ArrayList<>(List.of(k, out1.limbs().get(1).randomness(), k, out2.limbs().get(1).randomness())); + inputs.audit(audit).randomness(ks); + var reusedProof = compress(proofs.issue(2).prove(inputs.toWitnessMap())); + var b = provedIssueBuilder(List.of(noteDatum(out1), noteDatum(out2.owner(), out2.u(), out2.v(), GENERATION, a2, out2.deliveries())), + reusedProof, proofs.issue(2).compressedVk()); + if (evaluate(payroll, b.buildPlutusData()) instanceof EvalResult.Success) fail("ProvedIssue accepted a reused handle"); + } + + private PlutusData provedIssueContext(ProvedIssueMutation m, List notes, SnarkjsToCardano.ProofCompressed proof) { + List datums = new ArrayList<>(); + for (AuditedNote n : notes) datums.add(noteDatum(n)); + if (m == ProvedIssueMutation.UNDER_REPORTED_IN_DATUM) { + AuditedNote under = notes.getFirst().withLimbs(AuditedNote.limbsOf(BigInteger.valueOf(1), auditor, RANDOM)); + datums.set(0, noteDatum(under)); + } + var vkUsed = m == ProvedIssueMutation.WRONG_VK ? proofs.issue(notes.size() == 1 ? 2 : 1).compressedVk() + : proofs.issue(notes.size()).compressedVk(); + if (m == ProvedIssueMutation.TRUSTED_ISSUE_IN_PROVED_MODE) { + var b = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).mint(token(PTS, datums.size())) + .redeemer(PlutusData.constr(0, PlutusData.integer(0))).signer(ISSUER); + for (PlutusData d : datums) b.output(noteOut(LEDGER, d, 1)); + registry(b, "NONE"); + return b.buildPlutusData(); + } + var b = provedIssueBuilder(datums, proof, vkUsed); + if (m == ProvedIssueMutation.COUNT_MISMATCH) b.mint(token(PTS, 1)); + if (m == ProvedIssueMutation.LEDGER_INPUT_SPENT) b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), noteOut(LEDGER, inDatum(), 1))); + if (m == ProvedIssueMutation.STAKE_VARIANT_EXTRA_OUTPUT) b.output(noteOut(STAKED_LEDGER, noteDatum(out1), 0)); + if (m != ProvedIssueMutation.NO_SIGNER) b.signer(ISSUER); + registry(b, m.name()); + return b.buildPlutusData(); + } + + private ScriptContextTestBuilder provedIssueBuilder(List datums, SnarkjsToCardano.ProofCompressed proof, + 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()))); + 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; + } + + // ------------------------------------------------------------------ rogue verification keys + + @Test + @DisplayName("Hash-pinned keys: an honest proof under a fresh setup of the same circuit (same shape) is refused") + void rogueVerificationKeysAreRefused() { + // Another party's setup of exactly the same circuits: same key shape, a trapdoor it knows. + var rogueTransfer = KeyedCircuit.compile("note-transfer-rogue", NoteTransferProofCircuit.build()); + var rogueRedeem = KeyedCircuit.compile("note-redeem-rogue", + NoteRedeemProofCircuit.build()); + var rogueIssue = KeyedCircuit.compile("note-issue-n1-rogue", NoteIssueProofCircuit.build(1, 2, 8)); + assertTrue(rogueTransfer.compressedVk().ic().size() == proofs.transfer().compressedVk().ic().size()); + + var t = NoteProofs.transferInputs(in, out1, out2, auditor); + var tProof = rogueTransfer.prove(t.toWitnessMap()); + 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()))); + var ctx = transferTx(TransferMutation.NONE, spend, new TxOutRef(TxId.of(filled(32, (byte) 0x44)), BigInteger.ZERO), + 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()))); + assertTrue(evaluate(points, redeemTx(RedeemMutation.NONE, rSpend, + 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())); + var b = provedIssueBuilder(List.of(noteDatum(out1)), ip, rogueIssue.compressedVk()).signer(ISSUER); + registry(b, "NONE"); + assertTrue(evaluate(payroll, b.buildPlutusData()) instanceof EvalResult.Failure, "an issuance proof under a rogue key is refused"); + } + + // ------------------------------------------------------------------ helpers + + private void report(String what, EvalResult spend, EvalResult mint, KeyedCircuit circuit) { + long cpu = spend.budgetConsumed().cpuSteps() + (mint == null ? 0 : mint.budgetConsumed().cpuSteps()); + long mem = spend.budgetConsumed().memoryUnits() + (mint == null ? 0 : mint.budgetConsumed().memoryUnits()); + System.out.printf("[NoteLedger %s] constraints=%d publicInputs=%d cpu=%d (%.1f%% of steps) mem=%d (%.1f%% of memory)%n", + what, circuit.numConstraints(), circuit.numPublicInputs(), cpu, 100.0 * cpu / STEP_LIMIT, + mem, 100.0 * mem / MEMORY_LIMIT); + // ZeroJ ADR-0055 Q5: D3a is adopted only within 80% of both per-transaction limits. + assertTrue(cpu <= STEP_LIMIT * 8 / 10 && mem <= MEMORY_LIMIT * 8 / 10, + what + " exceeds the 80% gate"); + } + + static PlutusData inDatum() { + return noteDatum(ALICE, in.u(), in.v(), GENERATION - 1, out1.audit(), out1.deliveries()); + } + + /** Test fixture only. A limb ciphertext with a chosen {@code k} (variable-time {@code scalarMul}). */ + static List fixtureLimb(BigInteger m, BigInteger k, AdmittedAuditor a) { + JubjubPoint g = JubjubPoint.SUBGROUP_GENERATOR; + JubjubPoint pk = a.context().jointKey().point(); + JubjubPoint ha = g.scalarMul(k).normalized(); + JubjubPoint hb = g.scalarMul(m).add(pk.scalarMul(k)).normalized(); + return List.of(ha.affineU(), ha.affineV(), hb.affineU(), hb.affineV()); + } + + static Value token(byte[] name, long qty) { + return Value.singleton(PolicyId.of(POLICY), TokenName.of(name), BigInteger.valueOf(qty)); + } + + static Value ada(long ada) { + return Value.lovelace(BigInteger.valueOf(ada * 1_000_000)); + } + + static byte[] receiptName(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[] flipped(byte[] bytes) { + byte[] copy = bytes.clone(); + copy[copy.length - 1] ^= 1; + return copy; + } + + 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/NoteWalletTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteWalletTest.java new file mode 100644 index 0000000..7bb19e4 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/NoteWalletTest.java @@ -0,0 +1,71 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import com.bloxbean.cardano.client.api.model.Utxo; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The wallet's view (ADR-0007 N5, N-I7): a note counts as the wallet's only if its delivery opens + * and it names the wallet as owner. A note whose delivery opens but which someone else owns + * (a copied commitment, or a sender's mistake) is "readable, not mine"; an owned note that does not + * open is reported as unopenable. + */ +class NoteWalletTest { + + static final SecureRandom RANDOM = new SecureRandom(); + static final byte[] ALICE = filled(28, (byte) 0x0a); + static final byte[] MALLORY = filled(28, (byte) 0x0e); + static AdmittedAuditor auditor; + + @BeforeAll + static void setup() { + KeyPossession possession = new KeyPossession(); + byte[] registry = filled(28, (byte) 0x3e); + auditor = AdmittedAuditor.admit(registry, AuditorKeys.generate(RANDOM).entry(registry, filled(28, (byte) 0xa1), 0, possession), + possession); + } + + static ChainNote chain(AuditedNote n, int index) { + Utxo u = new Utxo(); + u.setTxHash("00".repeat(32)); + u.setOutputIndex(index); + return new ChainNote(u, n.owner(), n.u(), n.v(), n.generation(), n.audit(), n.deliveries()); + } + + @Test + @DisplayName("Owned and opening: counted. Opening but owned by another: not counted. Owned but garbage: unopenable.") + void ownershipIsNotDecryptability() { + NoteViewingKey alice = NoteViewingKey.generate(RANDOM); + AuditedNote mine = AuditedNote.create(ALICE, 500, alice.readerKey(), auditor, RANDOM); + // Mallory's note whose delivery opens with Alice's key: readable by Alice, spendable only by Mallory. + AuditedNote notMine = AuditedNote.create(MALLORY, 9_000, alice.readerKey(), auditor, RANDOM); + byte[] garbage = new byte[89]; + RANDOM.nextBytes(garbage); + AuditedNote garbled = AuditedNote.create(ALICE, 70, alice.readerKey(), auditor, RANDOM); + garbled = garbled.withDeliveries(List.of(garbage, garbled.deliveries().get(1))); + AuditedNote someoneElses = AuditedNote.create(MALLORY, 1, NoteViewingKey.generate(RANDOM).readerKey(), auditor, RANDOM); + + var scan = NoteWallet.scan(List.of(chain(mine, 0), chain(notMine, 1), chain(garbled, 2), chain(someoneElses, 3)), ALICE, alice); + assertEquals(BigInteger.valueOf(500), scan.balance(), "only the owned, opening note counts"); + assertEquals(1, scan.owned().size()); + assertEquals(1, scan.readableNotMine().size(), "the readable note owned by Mallory is reported, not counted"); + assertEquals(1, scan.unopenable().size(), "the owned garbage note is reported as unopenable"); + assertTrue(Arrays.equals(MALLORY, scan.readableNotMine().getFirst().owner())); + } + + 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/PayrollDevKitE2ETest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/PayrollDevKitE2ETest.java new file mode 100644 index 0000000..835fc71 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/PayrollDevKitE2ETest.java @@ -0,0 +1,112 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +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 org.junit.jupiter.api.Test; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +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; + +/** + * Confidential payroll on Yaci DevKit (ADR-0007 N4, N8; ZeroJ ADR-0055 Q9 (b)): proof-enforced + * issuance of two salaries in one pay run, payslips recovered from the chain by each employee, the + * tax authority's view of every salary (proof-enforced), salary history surviving a transfer, and + * an under-reported salary that has no proof. + * + *

Runs only with {@code ZEROJ_YACI_E2E=true}. + */ +class PayrollDevKitE2ETest { + + static final SecureRandom RANDOM = new SecureRandom(); + + @Test + void payrollOnDevKit() throws Exception { + assumeTrue(E2E.enabled(), "Set ZEROJ_YACI_E2E=true with DevKit running"); + BackendService backend = DevKit.backend(); + Account employer = new Account(Networks.testnet()); + Account carol = new Account(Networks.testnet()); + Account dave = new Account(Networks.testnet()); + Account tax = new Account(Networks.testnet()); + for (Account a : List.of(employer, carol, dave, tax)) DevKit.topUp(a.baseAddress(), 300); + NoteViewingKey carolView = NoteViewingKey.generate(RANDOM); + NoteViewingKey daveView = NoteViewingKey.generate(RANDOM); + + KeyPossession possession = new KeyPossession(); + Utxo seed = backend.getUtxoService().getUtxos(tax.baseAddress(), 10, 1).getValue().getFirst(); + Registry registry = Registry.forSeed(seed.getTxHash(), seed.getOutputIndex(), possession); + AuditorKeys taxKeys = AuditorKeys.generate(RANDOM); + 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); + 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); + + // An under-reported salary has no issuance proof. + AuditedNote honest = AuditedNote.create(pkh(carol), 5_000, carolView.readerKey(), auditor, RANDOM); + AuditedNote understated = honest.withLimbs(AuditedNote.limbsOf(BigInteger.valueOf(3_000), auditor, RANDOM)); + assertThrows(RuntimeException.class, () -> ledger.proofs().proveIssue(List.of(understated), auditor), + "an employer cannot under-report a salary to the tax authority"); + + // A pay run of two salaries, one proof. + AuditedNote daveSalary = AuditedNote.create(pkh(dave), 4_200, daveView.readerKey(), auditor, RANDOM); + List run = List.of(honest, daveSalary); + ok(ledger.provedIssue(backend, employer, run, ledger.proofs().proveIssue(run, auditor)), "pay run (2 salaries)", backend); + + assertEquals(BigInteger.valueOf(5_000), NoteWallet.scan(ChainNote.all(backend, ledger), pkh(carol), carolView).balance(), + "Carol reads her payslip from the chain"); + assertEquals(BigInteger.valueOf(4_200), NoteWallet.scan(ChainNote.all(backend, ledger), pkh(dave), daveView).balance()); + for (ChainNote n : ChainNote.all(backend, ledger)) { + var a = taxView.audit(n); + assertEquals(AuditorView.Origin.PROOF_ENFORCED, a.origin(), "every salary is proof-enforced"); + assertTrue(a.consistent()); + } + + // Carol pays Dave 800: salary history is unchanged in the tax view. + var carolNote = NoteWallet.scan(ChainNote.all(backend, ledger), pkh(carol), carolView).owned().getFirst(); + AuditedNote toDave = AuditedNote.create(pkh(dave), 800, daveView.readerKey(), auditor, RANDOM); + AuditedNote carolRest = AuditedNote.create(pkh(carol), 4_200, carolView.readerKey(), auditor, RANDOM); + ok(ledger.transfer(backend, carol, carolNote.note().utxo(), toDave, carolRest, + ledger.proofs().proveTransfer(carolNote.spent(), toDave, carolRest, auditor)), "transfer", backend); + BigInteger carolPaid = BigInteger.ZERO; + BigInteger davePaid = BigInteger.ZERO; + for (ChainNote n : taxView.issuedNotes(ledger)) { + BigInteger amount = taxView.audit(n).amount().orElseThrow(); + if (Arrays.equals(n.owner(), pkh(carol))) carolPaid = carolPaid.add(amount); + else davePaid = davePaid.add(amount); + } + assertEquals(BigInteger.valueOf(5_000), carolPaid, "Carol's salary history survives her transfer"); + assertEquals(BigInteger.valueOf(4_200), davePaid); + } + + 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 %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/notes/PointsNotesDevKitE2ETest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/PointsNotesDevKitE2ETest.java new file mode 100644 index 0000000..9cd1c3e --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/PointsNotesDevKitE2ETest.java @@ -0,0 +1,168 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +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 org.junit.jupiter.api.Test; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * ZeroJ ADR-0055 M3 on Yaci DevKit (ADR-0007): confidential points as notes with on-chain + * deliveries and an enforced auditor amount. + * + *

    + *
  1. An auditor registers its keys (on-chain possession proofs); the retailer deploys the ledger.
  2. + *
  3. The retailer issues Alice 1,000 points; Alice recovers her note from the chain.
  4. + *
  5. Alice sends Bob 700. A tampered proof and a spend by Bob are refused. Bob and Alice recover + * their notes; the auditor reads 700 and 300 from the limbs, proof-enforced.
  6. + *
  7. Alice sends Bob 100 with a garbage delivery: Bob's wallet reports it unopenable, while the + * auditor still reads the amount.
  8. + *
  9. Bob redeems 120 at the retailer and keeps the change.
  10. + *
  11. The auditor rotates its keys: a transfer whose limbs go to the retired key is refused; one + * to the new key is accepted, and the auditor reads both generations.
  12. + *
+ * Each accepted transaction's complete script cost is printed against the 80% gate. + * + *

Runs only with {@code ZEROJ_YACI_E2E=true}. + */ +class PointsNotesDevKitE2ETest { + + static final SecureRandom RANDOM = new SecureRandom(); + + @Test + void confidentialPointsWithNotesOnDevKit() throws Exception { + assumeTrue(E2E.enabled(), "Set ZEROJ_YACI_E2E=true with DevKit running"); + BackendService backend = DevKit.backend(); + Account retailer = new Account(Networks.testnet()); + Account alice = new Account(Networks.testnet()); + Account bob = new Account(Networks.testnet()); + Account auditorAccount = new Account(Networks.testnet()); + for (Account a : List.of(retailer, alice, bob, auditorAccount)) DevKit.topUp(a.baseAddress(), 300); + NoteViewingKey aliceView = NoteViewingKey.generate(RANDOM); + NoteViewingKey bobView = NoteViewingKey.generate(RANDOM); + + // 1. Registry and ledger. + KeyPossession possession = new KeyPossession(); + Utxo seed = backend.getUtxoService().getUtxos(auditorAccount.baseAddress(), 10, 1).getValue().getFirst(); + Registry registry = Registry.forSeed(seed.getTxHash(), seed.getOutputIndex(), possession); + AuditorKeys gen0 = AuditorKeys.generate(RANDOM); + ok(registry.init(backend, auditorAccount, seed, gen0.entry(registry.policy(), pkh(auditorAccount), 0, possession)), + "registry init", backend); + NoteLedgerScript ledger = new NoteLedgerScript(pkh(retailer), "PTS".getBytes(StandardCharsets.UTF_8), + NoteProofs.spendOnly(), registry); + assertTrue(ledger.deploy(backend, retailer).isSuccessful(), "deploy the ledger's reference script"); + AdmittedAuditor auditor = registry.admitted(backend); + AuditorView auditorView = new AuditorView(new HashMap<>(Map.of(0L, gen0)), ledger); + + // 2. Issue 1,000 to Alice; she recovers it from the chain. + AuditedNote issued = AuditedNote.create(pkh(alice), 1_000, aliceView.readerKey(), auditor, RANDOM); + ok(ledger.issue(backend, retailer, List.of(issued)), "issue", backend); + var aliceScan = NoteWallet.scan(ChainNote.all(backend, ledger), pkh(alice), aliceView); + assertEquals(BigInteger.valueOf(1_000), aliceScan.balance(), "Alice recovers her issued note from the chain"); + var auditIssued = auditorView.audit(aliceScan.owned().getFirst().note()); + assertEquals(BigInteger.valueOf(1_000), auditIssued.amount().orElseThrow()); + assertEquals(AuditorView.Origin.ISSUER_CLAIMED, auditIssued.origin()); + assertTrue(auditIssued.consistent()); + + // 3. Alice sends Bob 700. + var source = aliceScan.owned().getFirst(); + AuditedNote toBob = AuditedNote.create(pkh(bob), 700, bobView.readerKey(), auditor, RANDOM); + AuditedNote aliceChange = AuditedNote.create(pkh(alice), 300, aliceView.readerKey(), auditor, RANDOM); + var proof = ledger.proofs().proveTransfer(source.spent(), toBob, aliceChange, auditor); + var other = ledger.proofs().proveTransfer(source.spent(), + AuditedNote.create(pkh(bob), 700, bobView.readerKey(), auditor, RANDOM), aliceChange, auditor); + E2E.assertScriptRejected(ledger.transfer(backend, alice, source.note().utxo(), toBob, aliceChange, other), + "a proof for other commitments"); + E2E.assertScriptRejected(ledger.transfer(backend, bob, source.note().utxo(), toBob, aliceChange, proof), + "a spend not signed by the owner"); + ok(ledger.transfer(backend, alice, source.note().utxo(), toBob, aliceChange, proof), "transfer", backend); + var bobScan = NoteWallet.scan(ChainNote.all(backend, ledger), pkh(bob), bobView); + assertEquals(BigInteger.valueOf(700), bobScan.balance(), "Bob recovers 700 from the chain"); + aliceScan = NoteWallet.scan(ChainNote.all(backend, ledger), pkh(alice), aliceView); + assertEquals(BigInteger.valueOf(300), aliceScan.balance()); + for (var owned : List.of(bobScan.owned().getFirst(), aliceScan.owned().getFirst())) { + var audited = auditorView.audit(owned.note()); + assertEquals(owned.opening().value(), audited.amount().orElseThrow(), "the auditor reads the amount (sender, owner and auditor agree)"); + assertEquals(AuditorView.Origin.PROOF_ENFORCED, audited.origin()); + assertTrue(audited.consistent()); + } + + // 4. A garbage delivery to Bob: unopenable for Bob, the auditor still reads the amount. + var aliceNote = aliceScan.owned().getFirst(); + byte[] garbage = new byte[89]; + RANDOM.nextBytes(garbage); + AuditedNote garbled = AuditedNote.create(pkh(bob), 100, bobView.readerKey(), auditor, RANDOM); + garbled = garbled.withDeliveries(List.of(garbage, garbled.deliveries().get(1))); + AuditedNote aliceRest = AuditedNote.create(pkh(alice), 200, aliceView.readerKey(), auditor, RANDOM); + ok(ledger.transfer(backend, alice, aliceNote.note().utxo(), garbled, aliceRest, + ledger.proofs().proveTransfer(aliceNote.spent(), garbled, aliceRest, auditor)), "transfer with a garbage delivery", backend); + bobScan = NoteWallet.scan(ChainNote.all(backend, ledger), pkh(bob), bobView); + assertEquals(BigInteger.valueOf(700), bobScan.balance(), "the garbled note is not spendable"); + assertEquals(1, bobScan.unopenable().size(), "Bob's wallet reports the owned note it cannot open"); + var garbledAudit = auditorView.audit(bobScan.unopenable().getFirst()); + assertEquals(BigInteger.valueOf(100), garbledAudit.amount().orElseThrow(), "the auditor reads the amount anyway (D3a)"); + + // 5. Bob redeems 120 of his 700. + var bobNote = bobScan.owned().getFirst(); + AuditedNote bobChange = AuditedNote.create(pkh(bob), 580, bobView.readerKey(), auditor, RANDOM); + ok(ledger.redeem(backend, bob, retailer.baseAddress(), bobNote.note().utxo(), bobChange, 120, + ledger.proofs().proveRedeem(bobNote.spent(), bobChange, 120, auditor)), "redeem", backend); + bobScan = NoteWallet.scan(ChainNote.all(backend, ledger), pkh(bob), bobView); + assertEquals(BigInteger.valueOf(580), bobScan.balance()); + + // 6. Rotation: the auditor moves to generation 1. + AuditorKeys gen1 = AuditorKeys.generate(RANDOM); + ok(registry.rotate(backend, auditorAccount, auditorAccount, gen1.entry(registry.policy(), pkh(auditorAccount), 1, possession)), + "registry rotate", backend); + AdmittedAuditor rotated = registry.admitted(backend); + assertEquals(1, rotated.generation()); + aliceScan = NoteWallet.scan(ChainNote.all(backend, ledger), pkh(alice), aliceView); + var aliceNote2 = aliceScan.owned().getFirst(); + // Limbs to the retired key, but with the current generation number: only the key binding refuses them. + AuditedNote stale1 = AuditedNote.create(pkh(bob), 50, bobView.readerKey(), auditor, RANDOM).atGeneration(1); + AuditedNote stale2 = AuditedNote.create(pkh(alice), 150, aliceView.readerKey(), auditor, RANDOM).atGeneration(1); + E2E.assertScriptRejected(ledger.transfer(backend, alice, aliceNote2.note().utxo(), stale1, stale2, + ledger.proofs().proveTransfer(aliceNote2.spent(), stale1, stale2, auditor)), "limbs to the retired key"); + AuditedNote fresh1 = AuditedNote.create(pkh(bob), 50, bobView.readerKey(), rotated, RANDOM); + AuditedNote fresh2 = AuditedNote.create(pkh(alice), 150, aliceView.readerKey(), rotated, RANDOM); + ok(ledger.transfer(backend, alice, aliceNote2.note().utxo(), fresh1, fresh2, + ledger.proofs().proveTransfer(aliceNote2.spent(), fresh1, fresh2, rotated)), "transfer after rotation", backend); + auditorView = new AuditorView(Map.of(0L, gen0, 1L, gen1), ledger); + BigInteger audited = BigInteger.ZERO; + for (ChainNote n : ChainNote.all(backend, ledger)) audited = audited.add(auditorView.audit(n).amount().orElseThrow()); + // Live notes: Bob's change 580, the garbled 100, Bob's 50 (generation 1), Alice's 150 (generation 1). + assertEquals(BigInteger.valueOf(880), audited, "the auditor reads every live note, across both generations"); + System.out.println("[DevKit points] auditor total across generations: " + audited); + } + + 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 %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")) { + // ZeroJ ADR-0055 note 8: the application's complete transaction, measured on DevKit, within 80%. + 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/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; + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryTestData.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryTestData.java new file mode 100644 index 0000000..a3dff38 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/RegistryTestData.java @@ -0,0 +1,13 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import org.julclang.core.PlutusData; + +/** A registry entry as Julc data, for VM tests outside this package. */ +public final class RegistryTestData { + + private RegistryTestData() {} + + public static PlutusData datum(RegistryEntry entry) { + return AuditorRegistryVmTest.datum(entry); + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/SecretPathSourceTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/SecretPathSourceTest.java new file mode 100644 index 0000000..de15d26 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/notes/SecretPathSourceTest.java @@ -0,0 +1,45 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.notes; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.regex.Pattern; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * ADR-0007 N-I6 (ZeroJ ADR-0055 M3 criterion (b)): main code never calls ZeroJ's variable-time + * {@code scalarMul} (meant for public scalars). Secret limbs, ephemerals and openings go through + * {@code ElGamal.encryptWithOpening}, {@code ConfidentialNotes.seal} and the scanner, which use + * the blinded best-effort schedule. The blinded {@code scalarMulSecretBlindedBestEffort} is not + * matched. + */ +class SecretPathSourceTest { + + private static final Pattern VARIABLE_TIME = Pattern.compile("\\.scalarMul\\("); + + @Test + @DisplayName("No variable-time scalarMul in main sources") + void noVariableTimeScalarMulInMain() throws IOException { + List offenders; + try (Stream files = Files.walk(Path.of("src/main/java"))) { + offenders = files.filter(p -> p.toString().endsWith(".java")).flatMap(p -> { + try { + List lines = Files.readAllLines(p); + return IntStream.range(0, lines.size()) + .filter(i -> VARIABLE_TIME.matcher(lines.get(i)).find()) + .mapToObj(i -> p + ":" + (i + 1)); + } catch (IOException e) { + throw new IllegalStateException(e); + } + }).toList(); + } + assertEquals(List.of(), offenders, "variable-time scalarMul in main code"); + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsCircuitTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsCircuitTest.java deleted file mode 100644 index e267d11..0000000 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsCircuitTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.bloxbean.cardano.zeroj.usecases.pedersen.points; - -import com.bloxbean.cardano.zeroj.usecases.pedersen.points.ConfidentialPoints.Note; -import com.bloxbean.cardano.zeroj.usecases.pedersen.points.circuit.PointsRedeemProofCircuit; -import com.bloxbean.cardano.zeroj.usecases.pedersen.points.circuit.PointsTransferProofCircuit; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.zeroj.api.CurveId; -import org.zeroj.circuit.lib.jubjub.JubjubCurve; -import org.zeroj.circuit.lib.jubjub.PedersenCommitment; - -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.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** Demo A's relations: honest transfers and redemptions prove; unbalanced or overflowing ones do not. */ -class PointsCircuitTest { - - static final byte[] ALICE = filled((byte) 0xa1); - static final byte[] BOB = filled((byte) 0xb0); - private static ConfidentialPoints points; - - @BeforeAll - static void setup() { - points = new ConfidentialPoints(); - } - - @Test - @DisplayName("Transfer: balanced split proves and verifies; any changed commitment is rejected") - void transferProves() { - Note in = Note.of(ALICE, 1_000), out1 = Note.of(BOB, 700), out2 = Note.of(ALICE, 300); - var inputs = ConfidentialPoints.transferInputs(in, out1, out2); - var proof = points.proveTransfer(in, out1, out2); - List pub = PointsTransferProofCircuit.publicInputs(inputs); - assertTrue(points.transferCircuit().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(points.transferCircuit().verify(proof, changed), "public input " + i); - } - System.out.println("[points-transfer] constraints: " + points.transferCircuit().numConstraints()); - } - - @Test - @DisplayName("Transfer: no witness for an unbalanced split, a wrong commitment or a wrapped amount") - void transferRejects() { - var circuit = points.transferCircuit().circuit(); - Note in = Note.of(ALICE, 1_000); - assertThrows(RuntimeException.class, () -> circuit.calculateWitness( - ConfidentialPoints.transferInputs(in, Note.of(BOB, 701), Note.of(ALICE, 300)).toWitnessMap(), CurveId.BLS12_381)); - var wrongCommitment = ConfidentialPoints.transferInputs(in, Note.of(BOB, 700), Note.of(ALICE, 300)); - var other = PedersenCommitment.commit(BigInteger.valueOf(700), PedersenCommitment.randomBlinding(new SecureRandom())).normalized(); - wrongCommitment.out1U(other.affineU()).out1V(other.affineV()); - assertThrows(RuntimeException.class, () -> circuit.calculateWitness(wrongCommitment.toWitnessMap(), CurveId.BLS12_381)); - // Wraparound: l − 1 = (l − 6) + 5 balances mod l, but l − 1 is not a 64-bit amount. - BigInteger lMinusOne = JubjubCurve.SUBGROUP_ORDER.subtract(BigInteger.ONE); - BigInteger r = PedersenCommitment.randomBlinding(new SecureRandom()); - var huge = PedersenCommitment.commit(lMinusOne, r).normalized(); - var wrapped = ConfidentialPoints.transferInputs(in, Note.of(BOB, 5), Note.of(ALICE, 0)) - .inAmount(lMinusOne).inBlinding(r).inU(huge.affineU()).inV(huge.affineV()); - assertThrows(RuntimeException.class, () -> circuit.calculateWitness(wrapped.toWitnessMap(), CurveId.BLS12_381)); - } - - @Test - @DisplayName("Redeem: in = change + price proves; a different price or an oversized price is rejected") - void redeemProvesAndRejects() { - Note in = Note.of(ALICE, 500), change = Note.of(ALICE, 380); - var inputs = ConfidentialPoints.redeemInputs(in, change, 120); - var proof = points.proveRedeem(in, change, 120); - List pub = PointsRedeemProofCircuit.publicInputs(inputs); - assertTrue(points.redeemCircuit().verify(proof, pub)); - List cheaper = new ArrayList<>(pub); - cheaper.set(4, BigInteger.valueOf(119)); - assertFalse(points.redeemCircuit().verify(proof, cheaper), "a proof for 120 must not pay 119"); - - var circuit = points.redeemCircuit().circuit(); - assertDoesNotThrow(() -> circuit.calculateWitness(inputs.toWitnessMap(), CurveId.BLS12_381)); - assertThrows(RuntimeException.class, () -> circuit.calculateWitness( - ConfidentialPoints.redeemInputs(in, change, 121).toWitnessMap(), CurveId.BLS12_381)); - // Isolate the price's 32-bit range: in = change + 2^32 balances, but the price is too wide. - Note big = Note.of(ALICE, (1L << 32) + 380); - assertThrows(RuntimeException.class, () -> circuit.calculateWitness( - ConfidentialPoints.redeemInputs(big, change, 0).price(BigInteger.ONE.shiftLeft(32)).toWitnessMap(), - CurveId.BLS12_381)); - System.out.println("[points-redeem] constraints: " + points.redeemCircuit().numConstraints()); - } - - static byte[] filled(byte b) { - byte[] out = new byte[28]; - Arrays.fill(out, b); - return out; - } -} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsDevKitE2ETest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsDevKitE2ETest.java deleted file mode 100644 index 77d580a..0000000 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsDevKitE2ETest.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.bloxbean.cardano.zeroj.usecases.pedersen.points; - -import com.bloxbean.cardano.client.account.Account; -import com.bloxbean.cardano.client.api.model.Utxo; -import com.bloxbean.cardano.client.common.model.Networks; -import com.bloxbean.cardano.client.util.HexUtil; -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.common.Plutus; -import com.bloxbean.cardano.zeroj.usecases.pedersen.points.ConfidentialPoints.Note; -import org.junit.jupiter.api.Test; - -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * Demo A on Yaci DevKit: the retailer issues points to Alice; Alice sends Bob 700 of her 1,000 - * points privately; Bob spends 120 at the retailer and keeps the change. Amounts never appear - * on-chain except the redeemed price. A tampered proof and a spend without the owner's signature - * are rejected. - * - *

Runs only with {@code ZEROJ_YACI_E2E=true}. - */ -class PointsDevKitE2ETest { - - @Test - void confidentialPointsOnDevKit() throws Exception { - assumeTrue(E2E.enabled(), "Set ZEROJ_YACI_E2E=true with DevKit running"); - var backend = DevKit.backend(); - var retailer = new Account(Networks.testnet()); - var alice = new Account(Networks.testnet()); - var bob = new Account(Networks.testnet()); - for (Account a : List.of(retailer, alice, bob)) DevKit.topUp(a.baseAddress(), 200); - byte[] alicePkh = alice.hdKeyPair().getPublicKey().getKeyHash(); - byte[] bobPkh = bob.hdKeyPair().getPublicKey().getKeyHash(); - - var points = new ConfidentialPoints(); - var script = points.script(retailer.hdKeyPair().getPublicKey().getKeyHash()); - String ledger = ConfidentialPoints.address(script); - String policyId = Plutus.policyId(script); - - // 1. The retailer issues 1,000 points to Alice. - Note aliceNote = Note.of(alicePkh, 1_000); - var issued = ConfidentialPoints.issue(backend, script, retailer, List.of(aliceNote)); - assertTrue(issued.isSuccessful(), "issue: " + issued.getResponse()); - DevKit.waitForTx(backend, issued.getValue()); - Utxo aliceUtxo = DevKit.utxosOf(backend, ledger, issued.getValue()).getFirst(); - - // 2. Alice sends Bob 700 and keeps 300. Rejected first: a tampered proof, and Bob trying to - // spend Alice's note. - Note toBob = Note.of(bobPkh, 700); - Note aliceChange = Note.of(alicePkh, 300); - var proof = points.proveTransfer(aliceNote, toBob, aliceChange); - var tampered = points.proveTransfer(aliceNote, Note.of(bobPkh, 700), Note.of(alicePkh, 300)); - E2E.assertScriptRejected(ConfidentialPoints.transfer(backend, script, alice, aliceUtxo, toBob, aliceChange, tampered), - "a proof for other commitments"); - E2E.assertScriptRejected(ConfidentialPoints.transfer(backend, script, bob, aliceUtxo, toBob, aliceChange, proof), - "a spend not signed by the owner"); - var sent = ConfidentialPoints.transfer(backend, script, alice, aliceUtxo, toBob, aliceChange, proof); - assertTrue(sent.isSuccessful(), "transfer: " + sent.getResponse()); - DevKit.waitForTx(backend, sent.getValue()); - List notes = DevKit.utxosOf(backend, ledger, sent.getValue()); - assertEquals(2, notes.size()); - Utxo bobUtxo = notes.stream().filter(u -> u.getOutputIndex() == 0).findFirst().orElseThrow(); - - // 3. Bob spends 120 at the retailer: change note 580, receipt token to the retailer. - Note bobChange = Note.of(bobPkh, 580); - var redeemed = ConfidentialPoints.redeem(backend, script, bob, retailer.baseAddress(), bobUtxo, - bobChange, 120, points.proveRedeem(toBob, bobChange, 120)); - assertTrue(redeemed.isSuccessful(), "redeem: " + redeemed.getResponse()); - DevKit.waitForTx(backend, redeemed.getValue()); - - String receiptUnit = policyId + HexUtil.encodeHexString( - ConfidentialPoints.receiptName(bobUtxo)); - boolean receiptHeld = DevKit.utxosOf(backend, retailer.baseAddress(), redeemed.getValue()).stream() - .anyMatch(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().equals(receiptUnit))); - assertTrue(receiptHeld, "the retailer holds the receipt token"); - // 4. The note Bob redeemed is gone: redeeming it again is impossible, so the receipt is unique. - assertTrue(DevKit.utxosOf(backend, ledger, sent.getValue()).stream().noneMatch(u -> u.getOutputIndex() == 0)); - System.out.println("Points on DevKit: issue " + issued.getValue() + ", transfer " + sent.getValue() - + ", redeem " + redeemed.getValue()); - } -} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsLedgerVmTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsLedgerVmTest.java deleted file mode 100644 index 0c44be0..0000000 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsLedgerVmTest.java +++ /dev/null @@ -1,336 +0,0 @@ -package com.bloxbean.cardano.zeroj.usecases.pedersen.points; - -import com.bloxbean.cardano.client.crypto.Blake2bUtil; -import com.bloxbean.cardano.zeroj.usecases.pedersen.points.ConfidentialPoints.Note; -import com.bloxbean.cardano.zeroj.usecases.pedersen.points.onchain.PointsLedger; -import org.julclang.core.PlutusData; -import org.julclang.core.Program; -import org.julclang.ledger.Address; -import org.julclang.ledger.Credential; -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.onchain.julc.groth16.codec.ProverToCardano; -import org.zeroj.onchain.julc.groth16.codec.SnarkjsToCardano; - -import java.math.BigInteger; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import static org.junit.jupiter.api.Assertions.fail; - -/** - * {@code PointsLedger} in the Plutus VM (ADR-0006 demo A): honest issue, transfer and redemption - * are accepted; every mutation that would break P1–P8 is rejected. - */ -class PointsLedgerVmTest extends ContractTest { - - private static final byte[] POLICY = filled(28, (byte) 0x9a); - private static final byte[] ISSUER = filled(28, (byte) 0x15); - private static final byte[] ALICE = PointsCircuitTest.ALICE; - private static final byte[] BOB = PointsCircuitTest.BOB; - private static final byte[] PTS = ConfidentialPoints.NOTE_TOKEN; - private static final Address LEDGER = new Address( - new Credential.ScriptCredential(ScriptHash.of(POLICY)), Optional.empty()); - private static final Address ISSUER_ADDRESS = new Address( - new Credential.PubKeyCredential(PubKeyHash.of(ISSUER)), Optional.empty()); - private static final Address ALICE_WALLET = new Address( - new Credential.PubKeyCredential(PubKeyHash.of(ALICE)), Optional.empty()); - - private static Program program; - private static Note in; - private static Note out1; - private static Note out2; - private static Note change; - private static SnarkjsToCardano.ProofCompressed transferProof; - private static SnarkjsToCardano.ProofCompressed redeemProof; - private static final long PRICE = 120; - - @BeforeAll - static void setup() { - var points = new ConfidentialPoints(); - in = Note.of(ALICE, 1_000); - out1 = Note.of(BOB, 700); - out2 = Note.of(ALICE, 300); - change = Note.of(ALICE, 880); - transferProof = ProverToCardano.compressProof(points.proveTransfer(in, out1, out2)); - redeemProof = ProverToCardano.compressProof(points.proveRedeem(in, change, PRICE)); - var t = points.transferCircuit().compressedVk(); - var r = points.redeemCircuit().compressedVk(); - program = new PointsLedgerVmTest().compileValidator( - PointsLedger.class, Path.of("src/main/java")) - .program().applyParams( - PlutusData.bytes(ISSUER), PlutusData.bytes(PTS), - PlutusData.bytes(t.alpha()), PlutusData.bytes(t.beta()), - PlutusData.bytes(t.gamma()), PlutusData.bytes(t.delta()), icData(t.ic()), - PlutusData.bytes(r.alpha()), PlutusData.bytes(r.beta()), - PlutusData.bytes(r.gamma()), PlutusData.bytes(r.delta()), icData(r.ic())); - } - - // ------------------------------------------------------------------ - // Issue - // ------------------------------------------------------------------ - - enum IssueMutation { NONE, NO_SIGNER, NOTE_SPENT, COUNT_MISMATCH, TWO_TOKENS_IN_NOTE, EXTRA_MINT_ENTRY, SHORT_OWNER } - - @Test - @DisplayName("Issue: the issuer mints one token per new note; every mutation is rejected") - void issue() { - assertSuccess(evaluate(program, issueContext(IssueMutation.NONE))); - for (IssueMutation m : IssueMutation.values()) { - if (m != IssueMutation.NONE && evaluate(program, issueContext(m)) instanceof EvalResult.Success) { - fail("Issue accepted " + m); - } - } - } - - private PlutusData issueContext(IssueMutation m) { - Value mint = Value.singleton(PolicyId.of(POLICY), TokenName.of(PTS), BigInteger.TWO); - if (m == IssueMutation.EXTRA_MINT_ENTRY) mint = mint.merge(token(filled(32, (byte) 1), 1)); - var b = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).mint(mint).redeemer(action(0)); - if (m != IssueMutation.NO_SIGNER) b.signer(ISSUER); - if (m == IssueMutation.NOTE_SPENT) b.input(noteInput(in, TestDataBuilder.randomTxOutRef_typed())); - Note first = m == IssueMutation.SHORT_OWNER - ? new Note(Arrays.copyOf(ALICE, 27), 10, in.blinding(), in.commitment()) : in; - b.output(noteOut(first, m == IssueMutation.TWO_TOKENS_IN_NOTE ? 2 : 1)); - // TWO_TOKENS_IN_NOTE keeps the output count right (2 notes for n = 2): only the - // one-token-per-note rule can reject it. - if (m != IssueMutation.COUNT_MISMATCH) b.output(noteOut(out1, m == IssueMutation.TWO_TOKENS_IN_NOTE ? 0 : 1)); - return b.buildPlutusData(); - } - - // ------------------------------------------------------------------ - // Transfer (spend + Split mint) - // ------------------------------------------------------------------ - - enum TransferMutation { - NONE, NO_SIGNER, MALFORMED_PROOF, SWAPPED_OUTPUTS, OUTPUT_COMMITMENT, EXTRA_SCRIPT_INPUT, - EXTRA_STAKED_SCRIPT_INPUT, THREE_OUTPUTS, MINT_TWO, MINT_RECEIPT_INSTEAD, OUTPUT_TWO_TOKENS, - NON_CANONICAL_OUTPUT, INPUT_WITHOUT_TOKEN, NO_NOTE_SPENT - } - - @Test - @DisplayName("Transfer: an honest split is accepted by both purposes; every mutation is rejected") - void transfer() { - var spend = evaluate(program, transferSpend(TransferMutation.NONE)); - assertSuccess(spend); - System.out.println("[PointsLedger transfer] budget: " + spend.budgetConsumed()); - assertSuccess(evaluate(program, transferMint(TransferMutation.NONE))); - for (TransferMutation m : TransferMutation.values()) { - if (m != TransferMutation.NONE && evaluate(program, transferSpend(m)) instanceof EvalResult.Success) { - fail("Transfer spend accepted " + m); - } - } - for (TransferMutation m : List.of(TransferMutation.MINT_TWO, TransferMutation.EXTRA_SCRIPT_INPUT, - TransferMutation.EXTRA_STAKED_SCRIPT_INPUT, TransferMutation.NO_NOTE_SPENT)) { - if (evaluate(program, transferMint(m)) instanceof EvalResult.Success) fail("Split mint accepted " + m); - } - } - - private ScriptContextTestBuilder transferTx(TransferMutation m, ScriptContextTestBuilder b, TxOutRef ownRef) { - Value mint = token(PTS, m == TransferMutation.MINT_TWO ? 2 : 1); - if (m == TransferMutation.MINT_RECEIPT_INSTEAD) mint = token(receiptName(ownRef), 1); - b.mint(mint); - if (m != TransferMutation.NO_SIGNER) b.signer(ALICE); - if (m == TransferMutation.NO_NOTE_SPENT) { - // "Free PTS": a Split mint with no note spent (a wallet input instead). - b.input(new TxInInfo(ownRef, new TxOut(ALICE_WALLET, ada(), new OutputDatum.NoOutputDatum(), Optional.empty()))); - } else { - b.input(m == TransferMutation.INPUT_WITHOUT_TOKEN - ? new TxInInfo(ownRef, new TxOut(LEDGER, ada(), inline(noteDatum(in)), Optional.empty())) - : noteInput(in, ownRef)); - } - if (m == TransferMutation.EXTRA_SCRIPT_INPUT) b.input(noteInput(Note.of(ALICE, 5), TestDataBuilder.randomTxOutRef_typed())); - if (m == TransferMutation.EXTRA_STAKED_SCRIPT_INPUT) { - Address staked = new Address(LEDGER.credential(), Optional.of(new StakingCredential.StakingHash( - new Credential.PubKeyCredential(PubKeyHash.of(filled(28, (byte) 0x5a)))))); - b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), - new TxOut(staked, ada().merge(token(PTS, 1)), inline(noteDatum(Note.of(ALICE, 5))), Optional.empty()))); - } - Note first = m == TransferMutation.SWAPPED_OUTPUTS ? out2 : out1; - Note second = m == TransferMutation.SWAPPED_OUTPUTS ? out1 : out2; - if (m == TransferMutation.OUTPUT_COMMITMENT) second = Note.of(ALICE, 300); - b.output(noteOut(first, m == TransferMutation.OUTPUT_TWO_TOKENS ? 2 : 1)); - if (m == TransferMutation.NON_CANONICAL_OUTPUT) { - b.output(new TxOut(LEDGER, ada().merge(token(PTS, 1)), inline(PlutusData.constr(0, - PlutusData.bytes(second.owner()), - PlutusData.integer(second.commitment().affineU().add(JubjubCurve.BASE_FIELD_PRIME)), - PlutusData.integer(second.commitment().affineV()))), Optional.empty())); - } else { - b.output(noteOut(second, 1)); - } - if (m == TransferMutation.THREE_OUTPUTS) b.output(noteOut(Note.of(ALICE, 0), 1)); - return b; - } - - private PlutusData transferSpend(TransferMutation m) { - TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x44)), BigInteger.ZERO); - byte[] piA = m == TransferMutation.MALFORMED_PROOF ? flipped(transferProof.piA()) : transferProof.piA(); - var b = ScriptContextTestBuilder.spending(ownRef, noteDatum(in)).redeemer(PlutusData.constr(0, - PlutusData.bytes(piA), PlutusData.bytes(transferProof.piB()), PlutusData.bytes(transferProof.piC()))); - return transferTx(m, b, ownRef).buildPlutusData(); - } - - private PlutusData transferMint(TransferMutation m) { - TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x44)), BigInteger.ZERO); - var b = ScriptContextTestBuilder.minting(PolicyId.of(POLICY)).redeemer(action(1)); - return transferTx(m, b, ownRef).buildPlutusData(); - } - - // ------------------------------------------------------------------ - // Redeem (spend + Receipt mint) - // ------------------------------------------------------------------ - - enum RedeemMutation { - NONE, NO_SIGNER, PRICE_IN_REDEEMER, RECEIPT_PRICE, RECEIPT_TO_OTHER, RECEIPT_NAME_NOT_DERIVED, - NO_RECEIPT_MINTED, ALSO_MINT_PTS, CHANGE_COMMITMENT, PRICE_ZERO, PRICE_TOO_LARGE, TWO_CHANGE_NOTES, - RECEIPT_WITHOUT_TOKEN, NO_NOTE_SPENT, TWO_NOTES_SPENT, RECEIPT_NAME_NOT_32_BYTES - } - - @Test - @DisplayName("Redeem: an honest redemption is accepted by both purposes; every mutation is rejected") - void redeem() { - var spend = evaluate(program, redeemSpend(RedeemMutation.NONE)); - assertSuccess(spend); - System.out.println("[PointsLedger redeem] budget: " + spend.budgetConsumed()); - assertSuccess(evaluate(program, redeemMint(RedeemMutation.NONE))); - for (RedeemMutation m : RedeemMutation.values()) { - if (m != RedeemMutation.NONE && evaluate(program, redeemSpend(m)) instanceof EvalResult.Success) { - fail("Redeem spend accepted " + m); - } - } - for (RedeemMutation m : List.of(RedeemMutation.ALSO_MINT_PTS, RedeemMutation.NO_NOTE_SPENT, - RedeemMutation.TWO_NOTES_SPENT, RedeemMutation.RECEIPT_NAME_NOT_32_BYTES)) { - if (evaluate(program, redeemMint(m)) instanceof EvalResult.Success) fail("Receipt mint accepted " + m); - } - } - - private ScriptContextTestBuilder redeemTx(RedeemMutation m, ScriptContextTestBuilder b, TxOutRef ownRef) { - byte[] receipt = switch (m) { - case RECEIPT_NAME_NOT_DERIVED -> filled(32, (byte) 0x77); - case RECEIPT_NAME_NOT_32_BYTES -> filled(31, (byte) 0x77); - default -> receiptName(ownRef); - }; - Value mint = m == RedeemMutation.NO_RECEIPT_MINTED ? Value.zero() : token(receipt, 1); - if (m == RedeemMutation.ALSO_MINT_PTS) mint = mint.merge(token(PTS, 1)); - b.mint(mint); - if (m != RedeemMutation.NO_SIGNER) b.signer(ALICE); - if (m == RedeemMutation.NO_NOTE_SPENT) { - b.input(new TxInInfo(ownRef, new TxOut(ALICE_WALLET, ada(), new OutputDatum.NoOutputDatum(), Optional.empty()))); - } else { - b.input(noteInput(in, ownRef)); - } - if (m == RedeemMutation.TWO_NOTES_SPENT) b.input(noteInput(Note.of(ALICE, 5), TestDataBuilder.randomTxOutRef_typed())); - Note c = m == RedeemMutation.CHANGE_COMMITMENT ? Note.of(ALICE, 880) : change; - b.output(noteOut(c, 1)); - if (m == RedeemMutation.TWO_CHANGE_NOTES) b.output(noteOut(Note.of(ALICE, 0), 1)); - long receiptPrice = switch (m) { - case RECEIPT_PRICE -> PRICE + 1; - // Redeemer and receipt agree on 119; only the proof (made for 120) can reject it. - case PRICE_IN_REDEEMER -> PRICE - 1; - default -> PRICE; - }; - Address to = m == RedeemMutation.RECEIPT_TO_OTHER ? ALICE_WALLET : ISSUER_ADDRESS; - Value receiptValue = m == RedeemMutation.RECEIPT_WITHOUT_TOKEN ? ada() : ada().merge(token(receipt, 1)); - b.output(new TxOut(to, receiptValue, inline(PlutusData.constr(0, - PlutusData.bytes(ALICE), PlutusData.integer(BigInteger.valueOf(receiptPrice)))), Optional.empty())); - return b; - } - - private PlutusData redeemSpend(RedeemMutation m) { - TxOutRef ownRef = new TxOutRef(TxId.of(filled(32, (byte) 0x45)), BigInteger.ONE); - long price = switch (m) { - case PRICE_IN_REDEEMER -> PRICE - 1; - case PRICE_ZERO -> 0; - case PRICE_TOO_LARGE -> 1L << 32; - default -> PRICE; - }; - var b = ScriptContextTestBuilder.spending(ownRef, noteDatum(in)).redeemer(PlutusData.constr(1, - PlutusData.integer(BigInteger.valueOf(price)), - PlutusData.bytes(redeemProof.piA()), PlutusData.bytes(redeemProof.piB()), PlutusData.bytes(redeemProof.piC()))); - return redeemTx(m, b, ownRef).buildPlutusData(); - } - - 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(action(2)); - return redeemTx(m, b, ownRef).buildPlutusData(); - } - - // ------------------------------------------------------------------ - // Encodings - // ------------------------------------------------------------------ - - private static TxInInfo noteInput(Note n, TxOutRef ref) { - return new TxInInfo(ref, noteOut(n, 1)); - } - - private static TxOut noteOut(Note n, int tokens) { - return new TxOut(LEDGER, ada().merge(token(PTS, tokens)), inline(noteDatum(n)), Optional.empty()); - } - - private static PlutusData noteDatum(Note n) { - return PlutusData.constr(0, PlutusData.bytes(n.owner()), - PlutusData.integer(n.commitment().affineU()), PlutusData.integer(n.commitment().affineV())); - } - - private static OutputDatum inline(PlutusData d) { - return new OutputDatum.OutputDatumInline(d); - } - - private static Value ada() { - return Value.lovelace(BigInteger.valueOf(2_000_000)); - } - - private static Value token(byte[] name, long qty) { - return Value.singleton(PolicyId.of(POLICY), TokenName.of(name), BigInteger.valueOf(qty)); - } - - private static PlutusData action(int tag) { - return PlutusData.constr(tag, PlutusData.integer(0)); - } - - private static byte[] receiptName(TxOutRef ref) { - int index = ref.index().intValueExact(); - byte[] bytes = Arrays.copyOf(ref.txId().hash(), 34); - bytes[32] = (byte) (index >>> 8); - bytes[33] = (byte) index; - return Blake2bUtil.blake2bHash256(bytes); - } - - private static PlutusData icData(List ic) { - PlutusData[] points = new PlutusData[ic.size()]; - for (int i = 0; i < ic.size(); i++) points[i] = PlutusData.bytes(ic.get(i)); - return PlutusData.list(points); - } - - private static byte[] flipped(byte[] bytes) { - byte[] copy = bytes.clone(); - copy[copy.length - 1] ^= 1; - return copy; - } - - private 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/solvency/SolvencyCircuitTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyCircuitTest.java index 7e7ccd0..fb26066 100644 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyCircuitTest.java +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyCircuitTest.java @@ -15,8 +15,16 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation.Check; +import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation.Attestation; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; +import org.zeroj.circuit.lib.jubjub.NoteOpening; +import org.zeroj.circuit.lib.jubjub.ConfidentialNotes; +import java.util.Map; +import java.util.LinkedHashMap; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -27,9 +35,17 @@ class SolvencyCircuitTest { static final int N = 4; private static SolvencyAttestation solvency; + static final Map KEYS = new LinkedHashMap<>(); + + static { + for (String id : List.of("alice", "bob", "carol", "dave")) KEYS.put(id, NoteViewingKey.generate(new SecureRandom())); + } + static List book() { - return List.of(Customer.of("alice", 500_000_000L), Customer.of("bob", 1_200_000_000L), - Customer.of("carol", 300_000_000L), Customer.of("dave", 0)); + return List.of(Customer.of("alice", 500_000_000L, KEYS.get("alice").readerKey()), + Customer.of("bob", 1_200_000_000L, KEYS.get("bob").readerKey()), + Customer.of("carol", 300_000_000L, KEYS.get("carol").readerKey()), + Customer.of("dave", 0, KEYS.get("dave").readerKey())); } @BeforeAll @@ -84,37 +100,55 @@ void insolventOrMalformedHasNoWitness() { } @Test - @DisplayName("Customer check: own entry exactly once and opening; understated and duplicated entries are caught") + @DisplayName("Customer check from on-chain deliveries: own entry exactly once, opening to the balance; understated, duplicated and garbled entries are caught") void customerCheck() { var book = book(); List entries = SolvencyAttestation.entries(book); - for (Customer c : book) assertTrue(SolvencyAttestation.customerCheck(entries, c)); - // Understated balance: the entry no longer opens to the customer's balance. + for (Customer c : book) { + assertEquals(Check.LISTED_ONCE_CORRECT, SolvencyAttestation.customerCheck(entries, c, KEYS.get(c.id()))); + } Customer alice = book.getFirst(); + // Understated balance, delivered honestly: the opening is the understated one. var cheaper = new ArrayList<>(entries); - cheaper.set(0, new Entry(alice.idHash(), PedersenCommitment.commit(BigInteger.ONE, alice.blinding()).normalized())); - assertFalse(SolvencyAttestation.customerCheck(cheaper, alice)); + BigInteger r = alice.blinding(); + var understated = NoteOpening.of(BigInteger.ONE, r); + cheaper.set(0, new Entry(alice.idHash(), understated.commitment().normalized(), + ConfidentialNotes.seal(understated, List.of(alice.readerKey()), new SecureRandom()).getFirst())); + assertEquals(Check.WRONG_BALANCE, SolvencyAttestation.customerCheck(cheaper, alice, KEYS.get("alice"))); + // The real commitment with a delivery that does not open to it. + var garbled = SolvencyAttestation.withGarbageFor(entries, book, "alice"); + assertEquals(Check.UNOPENABLE, SolvencyAttestation.customerCheck(garbled, alice, KEYS.get("alice"))); + // Another customer's key cannot read alice's entry. + assertEquals(Check.UNOPENABLE, SolvencyAttestation.customerCheck(entries, alice, KEYS.get("bob"))); // Listed twice (e.g. to show two views): refused. var twice = new ArrayList<>(entries); twice.set(3, entries.getFirst()); - assertFalse(SolvencyAttestation.customerCheck(twice, alice)); + assertEquals(Check.LISTED_TWICE, SolvencyAttestation.customerCheck(twice, alice, KEYS.get("alice"))); + assertEquals(Check.MISSING, SolvencyAttestation.customerCheck(entries.subList(1, 4), alice, KEYS.get("alice"))); // Different ids give different id hashes. (The 32-byte salt is fixed-size, so id ‖ salt is // already unambiguous; the length prefix keeps it so if the salt format ever changes.) What // the encoding cannot stop is the exchange handing two customers the same id: ids must be // identifiers the customer can confirm and no one else shares (ADR-0006). byte[] s = new byte[32]; - assertFalse(Arrays.equals(new Customer("12", s, 1, BigInteger.ONE).idHash(), - new Customer("123", s, 1, BigInteger.ONE).idHash())); + assertFalse(Arrays.equals(new Customer("12", s, 1, BigInteger.ONE, alice.readerKey()).idHash(), + new Customer("123", s, 1, BigInteger.ONE, alice.readerKey()).idHash())); } @Test - @DisplayName("Auditor: the sum of the commitments opens to total liabilities, and to nothing else") + @DisplayName("Auditor: its on-chain delivery opens to total liabilities against the sum of the commitments, and only there") void auditorOpening() { var book = book(); List entries = SolvencyAttestation.entries(book); + NoteViewingKey auditor = NoteViewingKey.generate(new SecureRandom()); + byte[] delivery = SolvencyAttestation.auditorDelivery(book, auditor.readerKey()); + assertEquals(BigInteger.valueOf(2_000_000_000L), + SolvencyAttestation.auditorCheck(new Attestation(entries, delivery), auditor).orElseThrow()); + // An entry dropped from the sum: the delivery no longer opens. + assertTrue(SolvencyAttestation.auditorCheck(new Attestation(entries.subList(0, 3), delivery), auditor).isEmpty()); + // Another key cannot read it. + assertTrue(SolvencyAttestation.auditorCheck(new Attestation(entries, delivery), + NoteViewingKey.generate(new SecureRandom())).isEmpty()); AuditOpening opening = SolvencyAttestation.auditOpening(book); - assertTrue(SolvencyAttestation.auditorCheck(entries, opening)); - assertFalse(SolvencyAttestation.auditorCheck(entries, - new AuditOpening(opening.liabilities().subtract(BigInteger.ONE), opening.blinding()))); + assertEquals(BigInteger.valueOf(2_000_000_000L), opening.liabilities()); } } diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyDevKitE2ETest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyDevKitE2ETest.java index 63f3252..02f501e 100644 --- a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyDevKitE2ETest.java +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyDevKitE2ETest.java @@ -9,9 +9,13 @@ import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation.Customer; import org.junit.jupiter.api.Test; +import org.zeroj.circuit.lib.jubjub.NoteViewingKey; +import java.math.BigInteger; +import java.security.SecureRandom; import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -47,9 +51,12 @@ void solvencyOnDevKit() throws Exception { assertThrows(RuntimeException.class, () -> solvency.prove(reserves - 1, book), "insolvent books have no proof"); var proof = solvency.prove(reserves, book); - // Before the period: attest, with a validity range ending at the period start. + // Before the period: attest, with a validity range ending at the period start. Each entry's + // opening is delivered to its customer, and the total's to the auditor (ADR-0007 N6). + NoteViewingKey auditor = NoteViewingKey.generate(new SecureRandom()); + byte[] auditorDelivery = SolvencyAttestation.auditorDelivery(book, auditor.readerKey()); var attested = SolvencyAttestation.attest(backend, vault, exchange, reserves, - SolvencyAttestation.entries(book), proof, DevKit.slotAt(backend, period.start())); + SolvencyAttestation.entries(book), auditorDelivery, proof, DevKit.slotAt(backend, period.start())); assertTrue(attested.isSuccessful(), "attest: " + attested.getResponse()); DevKit.waitForTx(backend, attested.getValue()); @@ -58,27 +65,33 @@ void solvencyOnDevKit() throws Exception { while (DevKit.chainTimeMillis(backend) < period.start() + 2_000) Thread.sleep(2_000); var entries = SolvencyAttestation.liveEntries(backend, vault); for (Customer c : book) { - assertTrue(SolvencyAttestation.customerCheck(entries, c), c.id() + " is listed once and opens"); + assertEquals(SolvencyAttestation.Check.LISTED_ONCE_CORRECT, + SolvencyAttestation.customerCheck(entries, c, SolvencyCircuitTest.KEYS.get(c.id())), + c.id() + " decrypts their entry from the chain"); } - assertFalse(SolvencyAttestation.customerCheck(entries, Customer.of("eve", 1)), "a stranger has no entry"); - assertTrue(SolvencyAttestation.auditorCheck(entries, SolvencyAttestation.auditOpening(book)), - "the auditor opens total liabilities from the on-chain entries"); + NoteViewingKey eve = NoteViewingKey.generate(new SecureRandom()); + assertEquals(SolvencyAttestation.Check.MISSING, + SolvencyAttestation.customerCheck(entries, Customer.of("eve", 1, eve.readerKey()), eve), "a stranger has no entry"); + var live = SolvencyAttestation.liveAttestations(backend, vault); + assertEquals(1, live.size()); + assertEquals(BigInteger.valueOf(reserves), SolvencyAttestation.auditorCheck(live.getFirst(), auditor).orElseThrow(), + "the auditor opens total liabilities from its on-chain delivery"); // Inside the period nothing changes: a second attestation (here, the same reserves for // the same book again, valid until a minute from now) and an early release are rejected. E2E.assertScriptRejected(SolvencyAttestation.attest(backend, vault, exchange, reserves, - SolvencyAttestation.entries(book), proof, + SolvencyAttestation.entries(book), auditorDelivery, proof, DevKit.slotAt(backend, DevKit.chainTimeMillis(backend) + 60_000)), "an attestation inside the period"); String tokenUnit = Plutus.policyId(vault) + HexUtil.encodeHexString(SolvencyAttestation.ATTEST_TOKEN); - Utxo live = DevKit.utxosOf(backend, vaultAddress, attested.getValue()).stream() + Utxo liveUtxo = DevKit.utxosOf(backend, vaultAddress, attested.getValue()).stream() .filter(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().equals(tokenUnit))) .findFirst().orElseThrow(); - E2E.assertScriptRejected(SolvencyAttestation.release(backend, vault, exchange, live, + E2E.assertScriptRejected(SolvencyAttestation.release(backend, vault, exchange, liveUtxo, DevKit.slotAt(backend, DevKit.chainTimeMillis(backend))), "a release inside the period"); // After the period: released, attestation token burned. while (DevKit.chainTimeMillis(backend) < period.end() + 2_000) Thread.sleep(3_000); - var released = SolvencyAttestation.release(backend, vault, exchange, live, DevKit.slotAt(backend, period.end()) + 1); + var released = SolvencyAttestation.release(backend, vault, exchange, liveUtxo, DevKit.slotAt(backend, period.end()) + 1); assertTrue(released.isSuccessful(), "release: " + released.getResponse()); DevKit.waitForTx(backend, released.getValue()); System.out.println("Solvency on DevKit: attest " + attested.getValue() + ", release " + released.getValue()); 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 c36617f..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,8 +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; @@ -32,6 +35,7 @@ import org.zeroj.onchain.julc.groth16.codec.SnarkjsToCardano; import java.math.BigInteger; +import java.security.SecureRandom; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; @@ -61,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; @@ -71,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)), @@ -88,13 +93,16 @@ static void setup() { enum Attest { NONE, NO_SIGNER, MALFORMED_PROOF, LESS_LOCKED, EXTRA_TOKEN_IN_VAULT, VAULT_ELSEWHERE, STAKED_VAULT, MISSING_ENTRY, EXTRA_ENTRY, SWAPPED_ENTRIES, NON_CANONICAL_U, SHORT_ID_HASH, TWO_TOKENS, EXTRA_MINT_ENTRY, - VAULT_SPENT_IN_SAME_TX, AFTER_PERIOD_START, NO_UPPER_BOUND + VAULT_SPENT_IN_SAME_TX, AFTER_PERIOD_START, NO_UPPER_BOUND, + SHORT_DELIVERY, ENTRY_WITHOUT_DELIVERY, NO_AUDITOR_DELIVERY, SHORT_AUDITOR_DELIVERY, EXTRA_ATTESTATION_FIELD } @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()) { @@ -120,7 +128,7 @@ private PlutusData attestContext(Attest m) { if (m == Attest.VAULT_SPENT_IN_SAME_TX) { b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), new TxOut(VAULT_ADDRESS, Value.lovelace(BigInteger.valueOf(RESERVES)).merge(token(1)), - new OutputDatum.OutputDatumInline(attestation(entries, false)), Optional.empty()))); + new OutputDatum.OutputDatumInline(attestation(entries, Attest.NONE)), Optional.empty()))); } List published = new ArrayList<>(entries); if (m == Attest.MISSING_ENTRY) published.remove(3); @@ -129,7 +137,10 @@ private PlutusData attestContext(Attest m) { published.set(0, entries.get(1)); published.set(1, entries.get(0)); } - if (m == Attest.SHORT_ID_HASH) published.set(0, new Entry(Arrays.copyOf(entries.getFirst().idHash(), 31), entries.getFirst().commitment())); + if (m == Attest.SHORT_ID_HASH) published.set(0, new Entry(Arrays.copyOf(entries.getFirst().idHash(), 31), + entries.getFirst().commitment(), entries.getFirst().delivery())); + if (m == Attest.SHORT_DELIVERY) published.set(1, new Entry(entries.get(1).idHash(), entries.get(1).commitment(), + Arrays.copyOf(entries.get(1).delivery(), 88))); long locked = m == Attest.LESS_LOCKED ? RESERVES - 1 : RESERVES; Value vaultValue = Value.lovelace(BigInteger.valueOf(locked)).merge(token(m == Attest.TWO_TOKENS ? 2 : 1)); if (m == Attest.EXTRA_TOKEN_IN_VAULT) vaultValue = vaultValue.merge(Value.singleton(PolicyId.of(filled(28, (byte) 3)), TokenName.of(new byte[] {1}), BigInteger.ONE)); @@ -139,7 +150,7 @@ private PlutusData attestContext(Attest m) { default -> VAULT_ADDRESS; }; b.output(new TxOut(to, vaultValue, - new OutputDatum.OutputDatumInline(attestation(published, m == Attest.NON_CANONICAL_U)), Optional.empty())); + new OutputDatum.OutputDatumInline(attestation(published, m)), Optional.empty())); return b.buildPlutusData(); } @@ -181,7 +192,7 @@ private ScriptContextTestBuilder releaseTx(Release m, ScriptContextTestBuilder b private PlutusData releaseSpend(Release m) { TxOutRef ref = TestDataBuilder.randomTxOutRef_typed(); - var b = ScriptContextTestBuilder.spending(ref, attestation(entries, false)).redeemer(PlutusData.constr(0)); + var b = ScriptContextTestBuilder.spending(ref, attestation(entries, Attest.NONE)).redeemer(PlutusData.constr(0)); return releaseTx(m, b, ref).buildPlutusData(); } @@ -195,21 +206,33 @@ private PlutusData releaseBurn(Release m) { private static TxOut vaultOut() { return new TxOut(VAULT_ADDRESS, Value.lovelace(BigInteger.valueOf(RESERVES)).merge(token(1)), - new OutputDatum.OutputDatumInline(attestation(entries, false)), Optional.empty()); + new OutputDatum.OutputDatumInline(attestation(entries, Attest.NONE)), Optional.empty()); } - private static PlutusData attestation(List es, boolean nonCanonical) { + /** {@code Attestation([Entry(idHash, u, v, delivery)], auditorDelivery)}, or a mutation of it. */ + private static PlutusData attestation(List es, Attest m) { PlutusData[] items = new PlutusData[es.size()]; for (int i = 0; i < es.size(); i++) { Entry e = es.get(i); BigInteger u = e.commitment().affineU(); - if (nonCanonical && i == 0) u = u.add(JubjubCurve.BASE_FIELD_PRIME); - items[i] = PlutusData.constr(0, PlutusData.bytes(e.idHash()), PlutusData.integer(u), - PlutusData.integer(e.commitment().affineV())); + if (m == Attest.NON_CANONICAL_U && i == 0) u = u.add(JubjubCurve.BASE_FIELD_PRIME); + items[i] = m == Attest.ENTRY_WITHOUT_DELIVERY && i == 2 + ? PlutusData.constr(0, PlutusData.bytes(e.idHash()), PlutusData.integer(u), PlutusData.integer(e.commitment().affineV())) + : PlutusData.constr(0, PlutusData.bytes(e.idHash()), PlutusData.integer(u), + PlutusData.integer(e.commitment().affineV()), PlutusData.bytes(e.delivery())); } - return PlutusData.constr(0, PlutusData.list(items)); + return switch (m) { + case NO_AUDITOR_DELIVERY -> PlutusData.constr(0, PlutusData.list(items)); + case SHORT_AUDITOR_DELIVERY -> PlutusData.constr(0, PlutusData.list(items), PlutusData.bytes(new byte[88])); + case EXTRA_ATTESTATION_FIELD -> PlutusData.constr(0, PlutusData.list(items), PlutusData.bytes(AUDITOR_DELIVERY), + PlutusData.integer(BigInteger.ONE)); + default -> PlutusData.constr(0, PlutusData.list(items), PlutusData.bytes(AUDITOR_DELIVERY)); + }; } + private static final byte[] AUDITOR_DELIVERY = SolvencyAttestation.auditorDelivery(SolvencyCircuitTest.book(), + NoteViewingKey.generate(new SecureRandom()).readerKey()); + private static Value token(long qty) { return Value.singleton(PolicyId.of(VAULT), TokenName.of(TOKEN), BigInteger.valueOf(qty)); } 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 6fa0b30..96df961 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).