diff --git a/.gitignore b/.gitignore index 15dfee9..63a06fd 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,7 @@ build/ node_modules/ *.class *.jar +!gradle-wrapper.jar *.log .idea/ *.iml diff --git a/CLAUDE.md b/CLAUDE.md index 07dd36e..06d8f62 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,7 +12,7 @@ GroupId: `com.bloxbean.cardano` | Build | Gradle | 9.2+ | | Frontend | Svelte 5 + Vite | Latest | | Frontend packaging | Build to `src/main/resources/static/`, served by Spring Boot | -| ZK Proofs | zeroj (`org.zeroj`, Maven Central) | 0.1.0-pre12 | +| ZK Proofs | zeroj (`org.zeroj`, Maven Central) | 0.1.0-pre13 | | On-chain scripts | Julc (`org.julclang`) | 0.1.0-pre18 | | Cardano client | cardano-client-lib | 0.8.0-pre5 | | Cardano networks | Yaci DevKit (local) + Preprod (testnet) | diff --git a/README.md b/README.md index 87cef2e..d405ce8 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,7 @@ zeroj-usecases/ digital-product-passport/ Spring Boot E2E, CircuitSpec reference selective-disclosure/ Spring Boot E2E reusable-kyc/ Spring Boot E2E, BBS selective disclosure + pedersen-commitments/ Spring Boot E2E, three Pedersen commitment demos examples/ minimal-circuits/ @@ -82,11 +83,12 @@ zeroj-usecases/ | [proof-of-reserves](proof-of-reserves/README.md) | Reserves cover liabilities without exposing balances | 8089 | Symbolic annotations | | [identity-kyc](identity-kyc/README.md) | Age and country eligibility without revealing personal data | 8087 | Symbolic annotations | | [nft-ownership](nft-ownership/README.md) | NFT ownership without revealing wallet or token | 8085 | Symbolic annotations | -| [private-voting](private-voting/README.md) | Eligible voter, one private vote, no double-vote | 8086 | Symbolic annotations | +| [private-voting](private-voting/README.md) | Eligible voter, one encrypted vote, no double-vote; only the total is ever decrypted | 8086 | Symbolic annotations | | [personhood-airdrop](personhood-airdrop/SYBIL_AIRDROP_TUTORIAL.md) | One claim per person per epoch | 8083 | Symbolic annotations | | [digital-product-passport](digital-product-passport/README.md) | Product compliance without exposing supply-chain data | 8088 | `CircuitSpec` | | [selective-disclosure](selective-disclosure/SELECTIVE_DISCLOSURE_TUTORIAL.md) | Multiple predicates from one signed credential | 8091 | Symbolic annotations | | [reusable-kyc](reusable-kyc/README.md) | KYC once, reveal only the attributes each service needs — **BBS proof verified natively on-chain** | 8092 | BBS (no circuit) | +| [pedersen-commitments](pedersen-commitments/README.md) | Confidential points that still add up; one committed credential, prove only a predicate; solvency with hidden liabilities | 8093 | Symbolic annotations | Some apps have native Spring ports that overlap, such as 8085. The Docker demo maps them to distinct host ports so multiple profiles can exist without port @@ -100,10 +102,10 @@ For the Docker demo path: - Docker with Compose v2 - Yaci DevKit running on the host -Docker demos use the released ZeroJ version configured by `ZEROJ_VERSION` -(`0.1.0-pre12` by default). A sibling ZeroJ checkout is optional and only needed -when you explicitly opt into publishing a local ZeroJ build during Docker image -builds. +Docker demos build against the ZeroJ version in `version.properties` (`zerojVersion`), the +same one the Gradle builds use; set `ZEROJ_VERSION` to override it. A sibling ZeroJ checkout is +optional and only needed when you explicitly opt into publishing a local ZeroJ build during +Docker image builds. For direct Java runs: diff --git a/account-ownership/cli/build.gradle b/account-ownership/cli/build.gradle index 7e26532..c26b802 100644 --- a/account-ownership/cli/build.gradle +++ b/account-ownership/cli/build.gradle @@ -34,7 +34,7 @@ repositories { maven { url = uri("https://repo.spring.io/milestone") } } -def zerojVersion = ver('zerojVersion', '0.1.0-pre12') +def zerojVersion = ver('zerojVersion', '0.1.0-pre13') def julcVersion = ver('julcVersion', '0.1.0-pre18') def cclVersion = ver('cclVersion', '0.8.0-pre5') diff --git a/build-all.sh b/build-all.sh index 8338658..733c1ff 100755 --- a/build-all.sh +++ b/build-all.sh @@ -7,6 +7,7 @@ projects=( nft-ownership personhood-airdrop private-voting + pedersen-commitments proof-of-reserves selective-disclosure examples/minimal-circuits/batch-threshold-matrix diff --git a/build.gradle b/build.gradle index 6b93910..6b58e33 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,7 @@ def usecaseProjects = [ 'nft-ownership', 'personhood-airdrop', 'private-voting', + 'pedersen-commitments', 'proof-of-reserves', 'selective-disclosure', 'examples/minimal-circuits/batch-threshold-matrix', diff --git a/compose.demo.yml b/compose.demo.yml index af03a77..db5fdea 100644 --- a/compose.demo.yml +++ b/compose.demo.yml @@ -26,7 +26,7 @@ x-spring-build: &spring-build zeroj-src: ${ZEROJ_SOURCE_CONTEXT:-docker/empty-zeroj-context} dockerfile: docker/spring-usecase.Dockerfile args: - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} services: @@ -37,7 +37,7 @@ services: <<: *spring-build args: USECASE_DIR: proof-of-reserves - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *spring-env @@ -54,7 +54,7 @@ services: <<: *spring-build args: USECASE_DIR: identity-kyc - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *spring-env @@ -71,7 +71,7 @@ services: <<: *spring-build args: USECASE_DIR: nft-ownership - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *spring-env @@ -88,7 +88,7 @@ services: <<: *spring-build args: USECASE_DIR: private-voting - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *spring-env @@ -105,7 +105,7 @@ services: <<: *spring-build args: USECASE_DIR: personhood-airdrop - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *spring-env @@ -122,7 +122,7 @@ services: <<: *spring-build args: USECASE_DIR: digital-product-passport - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *spring-env @@ -140,7 +140,7 @@ services: <<: *spring-build args: USECASE_DIR: selective-disclosure - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *spring-env @@ -157,7 +157,7 @@ services: <<: *spring-build args: USECASE_DIR: reusable-kyc - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *spring-env @@ -167,6 +167,23 @@ services: volumes: - reusable-kyc-data:/app/data + pedersen-commitments: + profiles: ["pedersen-commitments", "spring"] + <<: *host-provider + build: + <<: *spring-build + args: + USECASE_DIR: pedersen-commitments + ZEROJ_VERSION: ${ZEROJ_VERSION:-} + PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} + environment: + <<: *spring-env + SERVER_PORT: 8080 + ports: + - "${PEDERSEN_COMMITMENTS_PORT:-8093}:8080" + volumes: + - pedersen-commitments-data:/app/data + volumes: proof-of-reserves-data: identity-kyc-data: @@ -176,3 +193,4 @@ volumes: dpp-data: selective-disclosure-data: reusable-kyc-data: + pedersen-commitments-data: diff --git a/compose.yml b/compose.yml index 7869727..f733d42 100644 --- a/compose.yml +++ b/compose.yml @@ -26,7 +26,7 @@ services: args: USECASE_DIR: examples/minimal-circuits/plonk/proof-of-reserves APP_NAME: proof-of-reserves-plonk - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *yaci-env @@ -44,7 +44,7 @@ services: args: USECASE_DIR: examples/minimal-circuits/plonk/compliance-credential APP_NAME: compliance-credential-plonk - ZEROJ_VERSION: ${ZEROJ_VERSION:-0.1.0-pre12} + ZEROJ_VERSION: ${ZEROJ_VERSION:-} PUBLISH_LOCAL_ZEROJ: ${PUBLISH_LOCAL_ZEROJ:-false} environment: <<: *yaci-env diff --git a/demo-cache/pedersen-commitments/manifest.json b/demo-cache/pedersen-commitments/manifest.json new file mode 100644 index 0000000..f8a1369 --- /dev/null +++ b/demo-cache/pedersen-commitments/manifest.json @@ -0,0 +1,7 @@ +{ + "usecase": "pedersen-commitments", + "devOnly": true, + "trustedSetup": "single-party development setup", + "artifacts": [], + "note": "No setup files are committed for this demo. The four circuits (points-transfer, points-redeem, credit-profile-check, hidden-liability-solvency-n4) are set up on first start and cached in /app/data, keyed by an R1CS digest." +} diff --git a/demo.sh b/demo.sh index 8d8846a..729992d 100755 --- a/demo.sh +++ b/demo.sh @@ -17,6 +17,7 @@ Usecases (canonical name, optional aliases, and default UI port): digital-product-passport (dpp) 8088 selective-disclosure (selective) 8091 reusable-kyc (kyc) 8092 + pedersen-commitments (pedersen) 8093 Options: --run Run the happy-path curl flow after the UI is healthy. @@ -130,6 +131,13 @@ case "${USECASE}" in PORT="${REUSABLE_KYC_PORT:-8092}" HEALTH="/api/kyc/status" ;; + pedersen|pedersen-commitments) + PROFILE="pedersen-commitments" + SERVICE="pedersen-commitments" + VOLUME="pedersen-commitments-data" + PORT="${PEDERSEN_COMMITMENTS_PORT:-8093}" + HEALTH="/api/status" + ;; *) echo "Unknown usecase: ${USECASE}" >&2 usage @@ -298,6 +306,19 @@ run_flow() { # no nonce here: the on-chain header is derived from the voucher UTxO + recipient 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 + 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/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}' + ;; esac } diff --git a/digital-product-passport/gradle/wrapper/gradle-wrapper.jar b/digital-product-passport/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/digital-product-passport/gradle/wrapper/gradle-wrapper.jar differ diff --git a/docker/cli-usecase.Dockerfile b/docker/cli-usecase.Dockerfile index 289eea7..c9cf078 100644 --- a/docker/cli-usecase.Dockerfile +++ b/docker/cli-usecase.Dockerfile @@ -2,7 +2,8 @@ FROM eclipse-temurin:25-jdk AS build ARG USECASE_DIR ARG APP_NAME -ARG ZEROJ_VERSION=0.1.0-pre12 +# Empty = use zerojVersion from version.properties (copied below); set to override. +ARG ZEROJ_VERSION= ARG PUBLISH_LOCAL_ZEROJ=false ARG ZEROJ_PUBLISH_TASKS=":zeroj-api:publishToMavenLocal :zeroj-backend-spi:publishToMavenLocal :zeroj-codec:publishToMavenLocal :zeroj-bls12381:publishToMavenLocal :zeroj-blst:publishToMavenLocal :zeroj-crypto:publishToMavenLocal :zeroj-circuit-dsl:publishToMavenLocal :zeroj-circuit-annotation-api:publishToMavenLocal :zeroj-circuit-lib:publishToMavenLocal :zeroj-circuit-annotation-processor:publishToMavenLocal :zeroj-verifier-groth16:publishToMavenLocal :zeroj-verifier-plonk:publishToMavenLocal :zeroj-onchain-julc:publishToMavenLocal" @@ -15,11 +16,12 @@ RUN if [ "${PUBLISH_LOCAL_ZEROJ}" = "true" ]; then \ fi WORKDIR /workspace/usecase +COPY version.properties /workspace/version.properties COPY gradle/usecase-versions.gradle /workspace/gradle/usecase-versions.gradle COPY ${USECASE_DIR}/ ./ RUN chmod +x ./gradlew \ - && ./gradlew --no-daemon installDist -x test -PzerojVersion=${ZEROJ_VERSION} + && ./gradlew --no-daemon installDist -x test ${ZEROJ_VERSION:+-PzerojVersion=${ZEROJ_VERSION}} FROM eclipse-temurin:25-jre diff --git a/docker/spring-usecase.Dockerfile b/docker/spring-usecase.Dockerfile index c0b72c8..d20ee1e 100644 --- a/docker/spring-usecase.Dockerfile +++ b/docker/spring-usecase.Dockerfile @@ -1,7 +1,8 @@ FROM eclipse-temurin:25-jdk AS build ARG USECASE_DIR -ARG ZEROJ_VERSION=0.1.0-pre12 +# Empty = use zerojVersion from version.properties (copied below); set to override. +ARG ZEROJ_VERSION= ARG PUBLISH_LOCAL_ZEROJ=false ARG ZEROJ_PUBLISH_TASKS=":zeroj-api:publishToMavenLocal :zeroj-backend-spi:publishToMavenLocal :zeroj-codec:publishToMavenLocal :zeroj-bls12381:publishToMavenLocal :zeroj-blst:publishToMavenLocal :zeroj-crypto:publishToMavenLocal :zeroj-circuit-dsl:publishToMavenLocal :zeroj-circuit-annotation-api:publishToMavenLocal :zeroj-circuit-annotation-processor:publishToMavenLocal :zeroj-circuit-lib:publishToMavenLocal :zeroj-verifier-groth16:publishToMavenLocal :zeroj-onchain-julc:publishToMavenLocal" @@ -14,11 +15,12 @@ RUN if [ "${PUBLISH_LOCAL_ZEROJ}" = "true" ]; then \ fi WORKDIR /workspace/usecase +COPY version.properties /workspace/version.properties COPY gradle/usecase-versions.gradle /workspace/gradle/usecase-versions.gradle COPY ${USECASE_DIR}/ ./ RUN chmod +x ./gradlew \ - && ./gradlew --no-daemon bootJar -x test -PzerojVersion=${ZEROJ_VERSION} \ + && ./gradlew --no-daemon bootJar -x test ${ZEROJ_VERSION:+-PzerojVersion=${ZEROJ_VERSION}} \ && jar_file="$(find build/libs -maxdepth 1 -type f -name '*.jar' ! -name '*-plain.jar' | head -n 1)" \ && test -n "${jar_file}" \ && cp "${jar_file}" /workspace/app.jar diff --git a/docs/adr/0005-private-ballot-homomorphic-tally.md b/docs/adr/0005-private-ballot-homomorphic-tally.md new file mode 100644 index 0000000..17ceb62 --- /dev/null +++ b/docs/adr/0005-private-ballot-homomorphic-tally.md @@ -0,0 +1,490 @@ +# ADR-0005: Private ballots with a homomorphic tally (private-voting) + +- **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; + r4, 2026-10-05: ElGamal moved to ZeroJ's `elgamal-jubjub-v1`, see + [On ZeroJ `elgamal-jubjub-v1`](#on-zeroj-elgamal-jubjub-v1-r4)) +- **Fixes:** [zeroj-usecases#7](https://github.com/bloxbean/zeroj-usecases/issues/7) +- **Related:** ZeroJ ADR-0052 and `docs/specs/elgamal-jubjub-v1.md` (exponential ElGamal on + Jubjub; this demo is its milestone M3 consumer), ZeroJ ADR-0051 (Pedersen commitment profiles; + finding F7, scope item D8), ZeroJ ADR-0037/0038 (Jubjub gadget hardening), + [ADR-0006](0006-pedersen-commitment-demos.md). +- **Risk:** R2. This is a protocol integration with on-chain binding. It uses + only primitives ZeroJ already implements and tests: Jubjub arithmetic, Poseidon, Groth16, the + Plutus V3 Groth16 verifier and, since r4, the `elgamal-jubjub-v1` relations and host API. No + new primitive is implemented here. The ballot relation is new to this repository, though, so it + is specified exactly here and reviewed like an R3 relation. + +## Context + +The demo claims that "the proof reveals nothing about which voter cast the vote or how they +voted". Issue #7 shows the claim is false for the vote. The ballot is `Poseidon(vote, nullifier)` +and the nullifier is public. Since `vote ∈ {0, 1}`, anyone can hash both candidates and compare. +`TallyService` does exactly this to count votes. + +Re-reading the on-chain path while designing the fix found four more gaps. Each one breaks the +tally's integrity, and each would also break a homomorphic tally: + +| # | Gap | Consequence | +|---|---|---| +| G1 | `VoteZkMintingPolicy` takes `electionId`, `voterRoot` and `commitment` from the redeemer and checks them against nothing. | A proof against an attacker's own voter tree is accepted. Eligibility is not enforced, and one person can cast any number of ballots. | +| G2 | The list node's key, and the ballot stored in its datum, are not tied to the proved nullifier and commitment. | A voter can mint the nullifier token again and insert it under a fresh list key, and so vote twice. The stored ballot need not be the proved one. | +| G3 | The list spend validator only requires the list policy to run. An insert checks the anchor, but not other spent list nodes. | An insert transaction can also spend other voters' nodes, then drop or rewrite their ballots. | +| G4 | No voting deadline. | Ballots can be added at any time. With a decryptable tally, decrypting before and after a ballot reveals that ballot. | +| G5 | `InitList` is not one-shot. | A second root starts a parallel list in which the same nullifier can be inserted again. | + +## Threat model and trust assumptions + +**Adversaries.** + +| Adversary | Goal | Capabilities | +|---|---|---| +| Malicious voter | Vote twice; cast an invalid ballot (a value other than 0 or 1, or a different key); replace or remove other ballots; learn other voters' votes. | Builds arbitrary transactions; mints its own nullifier token outside the list; sends junk to the list address. | +| Outsider | Same goals, without being eligible. | — | +| Public observer | Learn individual votes from chain data. | — | +| Up to n − 1 colluding trustees | Decrypt individual ballots; publish a wrong total. | — | +| Chain reorganisation | Change the ballot set after the tally. | — | + +**Trusted.** +- At least one trustee is honest and available. +- The Groth16 setups of both circuits are honest. With the dev setup this demo uses, whoever + holds the toxic waste can forge every proof, including a proof of possession for a rogue key. +- The election administrator publishes the manifest (below) and deploys scripts that match it. + Anyone can check this. +- Plutus V3 and the ledger enforce validity intervals and minting as specified. + +**Not trusted.** Redeemer contents, every output that a validator has not checked, and every +UTxO at the list address that does not satisfy the node rules below. + +## Decision + +Replace the ballot with **exponential ElGamal over the Jubjub prime-order subgroup** under an +election key that is **additively shared by n trustees**. Ballots are proved well-formed with +Groth16 and verified on-chain. Their sum is decrypted **once, after an on-chain deadline and +finality**. Each trustee proves its decryption share, and anyone can check the tally from chain +data and the election manifest. This is the Cramer–Gennaro–Schoenmakers construction [CGS97] +with n-of-n sharing in place of threshold sharing. + +The ballot's second component, `B = [v]·G + [k]·PK`, is a Pedersen commitment to the vote whose +blinding base is the election key. Nobody can open a single ballot. The trustees can jointly +remove the blinding from the *sum*, because they hold the key behind that base. + +### Notation + +- `𝔾` is the Jubjub prime-order subgroup, of order `l`. `G` is `JubjubPoint.SUBGROUP_GENERATOR`, + the value base of `pedersen-jubjub-v1`. `p` is the BLS12-381 scalar field. +- Random scalars are 64 bytes reduced mod `l` (`elgamal-jubjub-v1` §2, the `pedersen-jubjub-v1` + sampler; secret keys are resampled at zero). +- `I2OSP32(x)` is the 32-byte big-endian encoding. + +### Election key + +Each trustee `j ∈ {1..n}` (the demo uses `n = 3`): + +1. samples `sk_j ∈ [1, l)` and publishes `PK_j = [sk_j]·G`; +2. publishes a **key proof** `π_key_j`, a Groth16 proof of `R_dleq` (below) with `X = G` and + `D = P = PK_j`. This proves knowledge of `sk_j` (proof of possession). The verifier always + sets `X = G` itself, so a decryption-share proof cannot pass as a key proof. + +The election key is `PK = Σ_j PK_j`. It is accepted only if every `π_key_j` verifies, the +`PK_j` are pairwise distinct, and neither any `PK_j` nor `PK` is the identity. Proof of +possession blocks the rogue-key attack: a trustee who publishes `PK_n = [x]·G − Σ_{j s.kind() == POSSESSION && verifyDleq(proof, s.publicInputs()))`, then `ElGamalPublicKey.aggregate` → `NOfNKeyContext` | +| Ballot | `ElGamal.encryptWithOpening(context, v, 1, rng)`; the opening is the witness | +| Ledger read | `RawElGamalCiphertext.fromAffine` (canonical, on-curve, subgroup) | +| Admission | `ElGamal.admit(raw, context, 1, verifier)`: delegated verification, below | +| Sum | `ElGamalCiphertext.sum` (bound `|𝔅|`) | +| Shares | `ElGamal.decryptionShare(sk_j, total)`; proof of `share.statement()`; published `share.encode()` | +| Combination | `VerifiedDecryptionShare.verify(total, PK_j, D_j, s -> s.kind() == DECRYPTION_SHARE && verifyDleq(proof, s.publicInputs()))`, then `ElGamal.decrypt(total, shares, total.bound())` | + +**Admission by delegated verification.** `elgamal-jubjub-v1` §10.1 gives a ciphertext a key +context and a plaintext bound only through local encryption, verified admission, or a sum of +admitted ciphertexts. The tally admits the ledger's ballots with a verifier that does not +re-verify the Groth16 proof. §10.1 names this delegation: an on-chain validator verified the +statement before the ciphertext reached the ledger, and the caller establishes from chain data +that the ciphertext is one such validator accepted. Here: + +1. The verifier is reachable only with an `OnChainVoteService.BallotNode`, whose constructor is + private to the list walk (V11). A node's ciphertext is the inline datum of a list node that + holds exactly one nullifier token minted under the ballot policy. +2. The ledger mints that token only if the policy succeeds. The policy verifies `R_ballot`, which + embeds `R_enc(1)`, for its parameter key and the datum of the one output holding the token + (rule 3). The list validator keeps that datum afterwards (V3, V5). +3. The verifier accepts a statement only if its width is 1, the node's policy id equals the + ballot-policy hash recomputed from the manifest (election id, voter root, key, deadline, + verification key), the statement's key is the policy's key parameter, and its ciphertext is the + node's datum. + +A ciphertext that reached the ledger any other way never gets a bound, so the bounded search +cannot be fooled by a sum that wrapped mod `l`. + +**Verification rebuilds everything.** `TallyService.verify` uses no state of the tally that it +checks. It rebuilds the key context from the manifest's key encodings and key proofs, recomputes +the script hashes, re-walks and re-admits the ballots, accepts each share only through its +proof, and decrypts again. + +**No ballots.** The library has no empty sum and no admitted zero ciphertext. With no ballots, +nothing is decrypted, no shares are published, and YES = NO = 0. The verifier checks exactly +that. + +**Compiled-system decision.** The circuits are new versions with new artifacts: + +| Circuit | Version | Constraints (r3 → r4) | +|---|---|---| +| `private-ballot`, depth 4 | 2 → 3 | 8,022 → 8,013 | +| `private-ballot`, depth 10 | 2 → 3 | 9,486 → 9,477 | +| `trustee-dleq` | 1 → 2 | 6,546 → 6,546 | + +- The ballot circuit has a new R1CS, so it gets a new setup, a new verification key and so a new + ballot-policy hash. The list policy is parameterised by the ballot-policy hash, so its hash + changes too. +- The library's DLEQ relation compiles to the same R1CS as the prototype's (same constraint + digest). It still gets a new setup under its new version, so that each version has its own + artifacts. +- The public-input order, the datum encoding and the validator source are unchanged. +- An existing election would keep its old circuit: its scripts carry that circuit's verification + key, and its ballots can only be checked against it. The demo persists no election that must + survive a restart, so nothing is migrated. +- The key caches are named by circuit version (`setup-private-ballot-d-v3-…`, + `setup-trustee-dleq-v2-…`). The old caches under `data/` (no version in the name) are stale: + they are never loaded again and can be deleted. + +## Invariants + +| ID | Invariant | Enforced by | +|---|---|---| +| V1 | Eligibility: a ballot is accepted only with a proof against the script-fixed `voterRoot` and `electionId`. | ZK policy parameters (1, 4) | +| V2 | One ballot per eligible voter. | `N` is the token name and the list key; the sorted list; one-shot root (5, 7) | +| V3 | The stored ballot is the proved ballot. | `(A, B)` read from the only output holding `N` (3) | +| V4 | Each ballot encrypts 0 or 1 under the election key. | `R_ballot` 1–4 | +| V5 | Existing ballots are immutable, and nodes are unambiguous. | One list input per insert; anchor `userData` preserved; exact values (6, 8) | +| V6 | No ballot after the deadline. | Validity-range check (2) | +| V7 | One decryption, over the final set, after the deadline and finality. | Trustee service | +| V8 | The decryption is correct. | `π_dec_j` per trustee (`VerifiedDecryptionShare.verify`); every ballot admitted at width 1; unique `T ∈ [0, |𝔅|]` (`ElGamal.decrypt`) | +| V9 | The key setup is sound. | Proof of possession per `PK_j` (`VerifiedKeyShare.verify`); distinct keys; `PK ≠ O` (`ElGamalPublicKey.aggregate`) | +| V10 | On-chain integers are canonical. | Every public input and token-derived scalar is checked `< p` | +| V11 | The ballot set is the whole list. | Root walk, full coverage, per-node checks, fail closed, published digest | +| V12 | The scripts are the published election. | Manifest with full keys and scripts; hashes recomputed; root minted once by the seed's spender | + +## Alternatives considered + +1. **A hiding commitment per ballot**, either `Poseidon(v, N, r)` or Pedersen `[v]·G + [r]·H`. + This hides each vote, but then nobody can tally (issue #7). +2. **Pedersen commitments with the openings encrypted to an authority.** The authority sees every + vote. +3. **Twisted ElGamal**, `C = [v]·G + [k]·H` with `D = [k]·PK`. `C` is exactly a + `pedersen-jubjub-v1` commitment, which is attractive. Decryption needs `sk⁻¹`, though, which + does not split additively across trustees, so one key holder could decrypt every ballot. +4. **A Chaum–Pedersen Σ-protocol for `R_dleq`.** It is smaller and needs no setup. It does need a + pinned Fiat–Shamir transcript, which this stack does not yet have (ZeroJ ADR-0051 D7 is + blocked on one). Groth16 reuses reviewed machinery and adds no transcript. Revisit once a + transcript is pinned. +5. **Verifying the tally on-chain.** Jubjub aggregation on-chain is cheap field arithmetic, but + verifying n decryption proofs in one transaction exceeds the per-transaction budget. The + tally is verified off-chain from chain data. Per-trustee share transactions are future work. + +## Milestones + +| Milestone | Scope | +|---|---| +| B0 | This ADR. | +| B1 | Ballot and DLEQ circuits, host ElGamal and tally, and circuit negatives. | +| B2 | On-chain policy and list changes, and Plutus VM mutation tests for V1–V6 and V10. | +| B3 | Services, manifest, ballot-set walk, API, UI and README; DevKit end-to-end run. | +| B4 (r4) | Move to ZeroJ `elgamal-jubjub-v1` (ZeroJ ADR-0052 M3): library relations and host API, new circuit versions, the ciphertext-compatibility differential. | + +## Verification + +- **Host:** homomorphic sums and decryption through the library's safe layer; refusal of + duplicate, cancelling, identity and non-subgroup keys, of non-canonical, off-curve and + small-order ledger points, and of out-of-width votes. +- **Ciphertext compatibility (r4).** A standalone Python reimplementation of Jubjub ElGamal and + the tally, from the curve definition, fixed the prototype's vectors. The library must accept + them: it builds the context from the vector secrets, admits each vector ciphertext (through + `RawElGamalCiphertext.fromAffine`) with a verifier that checks its opening, and its decryption + shares and tally must equal the vectors'. A wrong opening, a tampered `B`, another context and + a missing or repeated share are refused. +- **Circuit negatives:** + - `v = 2`; + - `A` and `B` built from different `k`; + - `B` under another key; + - an identity key, and an off-curve key; + - a wrong nullifier; + - a non-member leaf, and another root; + - a public input changed after proving; + - a DLEQ statement with the wrong share, the wrong key or the wrong base; a share proof + presented as a key proof; one trustee's key proof for another trustee's key. +- **Plutus VM mutations:** + - root, election id and key not from the parameters (G1); + - list key not equal to the nullifier (G2); + - a second list input (G3); + - after the deadline, or no upper bound (G4); + - an `InitList` without the seed (G5); + - a datum ballot that differs from the proved one; + - **a pre-minted copy of `N` in another output**; + - stray tokens in the new node or the continuing anchor; + - extra list or nullifier mint entries; + - non-canonical coordinates. +- **DevKit:** cast ballots; script rejections (local Julc evaluation, as the node would run them; + rejected transactions are not submitted) of a swapped ballot, a double vote + forced past the client, and a ballot valid past the deadline; close; walk the list; admit and + tally; verify every share, the manifest and the seed binding; a forged share and a changed + count do not verify. +- **Mutation checks:** removing the one-unit rule or the exact anchor datum makes a VM test fail. + +## Production gates (not met by this demo) + +- An MPC trusted-setup ceremony for both circuits. +- Threshold distributed key generation and independent trustee custody. +- Voters holding their own keys and proving client-side, with a relayer for submission. +- A finality policy for the tally on public networks. +- External review of the relations and the validators. + +## References + +- [CGS97] R. Cramer, R. Gennaro, B. Schoenmakers. *A Secure and Optimally Efficient + Multi-Authority Election Scheme.* EUROCRYPT 1997. +- [RY07] T. Ristenpart, S. Yilek. *The Power of Proofs-of-Possession.* EUROCRYPT 2007. +- [Ped91] T. P. Pedersen. *A Threshold Cryptosystem without a Trusted Party.* EUROCRYPT 1991. +- [GJKR07] R. Gennaro, S. Jarecki, H. Krawczyk, T. Rabin. *Secure Distributed Key Generation for + Discrete-Log Based Cryptosystems.* J. Cryptology 2007. +- ZeroJ `docs/specs/pedersen-jubjub-v1.md` (bases and scalar sampling) and ADR-0051. diff --git a/docs/adr/0006-pedersen-commitment-demos.md b/docs/adr/0006-pedersen-commitment-demos.md new file mode 100644 index 0000000..a40ef12 --- /dev/null +++ b/docs/adr/0006-pedersen-commitment-demos.md @@ -0,0 +1,352 @@ +# ADR-0006: Pedersen commitment demos — confidential points, committed credentials, hidden-liability solvency + +- **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) +- **Related:** + - ZeroJ ADR-0051 and its specs, `pedersen-jubjub-v1` and `pedersen-jubjub-vector-v1`. + - ZeroJ's reference validators `ConfidentialNoteValidator` and + `VectorCommitmentConsumerValidator`. + - [ADR-0005](0005-private-ballot-homomorphic-tally.md), for the homomorphic tally. +- **Risk:** R2. These are application protocols and on-chain integrations built on + primitives ZeroJ has already reviewed. No primitive is implemented here. + +## Context + +ZeroJ ADR-0051 added hiding-safe Pedersen commitments, homomorphic balance checks without +wraparound, and schema-bound vector commitments. This ADR adds three demos. Each shows a +different property of the commitment, and each runs end to end on Yaci DevKit. + +| Demo | Property shown | ZeroJ API used | +|---|---|---| +| A. Confidential points | Additive homomorphism: conservation of hidden amounts, mixed with public amounts | `ZkPedersenCommitment.commit`, `ZkPedersen.assertBalanced`, `Term.amount` | +| B. Committed credential gate | One commitment to several attributes; predicates over a subset; schema binding and provenance | `ZkPedersenVector.bindSchema` / `commit`, `PedersenVectorSchema` | +| C. Hidden-liability solvency | Hiding per-customer commitments, checked by each customer; the aggregate opened only to an auditor | `ZkPedersenCommitment.commit`, host-side `PedersenCommitment` | + +The demos live in `pedersen-commitments/`, a single Gradle project with one package per demo. It +has no web UI. It provides a runnable walkthrough, Plutus VM tests and DevKit end-to-end tests. + +**Common rules,** taken from AGENTS.md ("proof validity is not authorization"): +- Every public input comes from script parameters or the ledger, never from the redeemer alone. + The one exception is demo A's redeemed `price`, which the proof binds and the receipt records. +- Every on-chain integer is checked to be canonical (`< p`). +- Script inputs are counted by payment credential, so the same script under another staking key + cannot double-satisfy. +- A policy's own mint entry is checked exactly, not just "contains". +- Every key comes from a dev trusted setup. That is demo-only. + +## Threat model + +| Demo | Adversary | Goal | Trusted | +|---|---|---|---| +| A | A note holder or an outsider | Create points from nothing; spend someone else's note; spend twice; forge a redemption receipt; overflow an amount. | The issuer, for supply. The dev setup. | +| B | A non-qualifying holder or a third party | Obtain a badge without a qualifying, issued credential; re-label a credential under another schema; use someone else's credential. | The bureau's key. The dev setup. | +| C | The exchange | Attest with liabilities greater than reserves; understate or omit a customer; count reserves twice; change an attestation after proving it. | Nobody beyond the dev setup. Customers must check their own entry. | + +Out of scope throughout: +- network-level privacy; +- delivery of openings and credentials, which happens off-chain; +- front-running of the demo's own transactions. + +--- + +## A. Confidential points + +A retailer's loyalty points are notes whose amounts are Pedersen commitments. Holders move +points between themselves privately, and spend points at the retailer for a public price. + +**Script.** `PointsLedger`, a multi-validator, so its hash is both the note address's payment +credential and the points policy id. +- Parameters: `issuerPkh`, the transfer key and the redeem key. +- A **note** is an output whose payment credential is the script, carrying exactly one `PTS` + token and nothing else under the policy, with inline datum `Note(owner: B28, u, v)`. +- A **receipt** is an output whose payment credential is the issuer's key. It holds one receipt + token, named `blake2b_256(txId ‖ I2OSP2(index))` of the redeemed note, with inline datum + `Receipt(owner, price)`. + +**Circuits.** +- `PointsTransferProof`, public `[in.u, in.v, o1.u, o1.v, o2.u, o2.v]`: proves + `in = o1 + o2` over 64-bit amounts. +- `PointsRedeemProof`, public `[in.u, in.v, out.u, out.v, price]`, where `price` is a public + 32-bit amount: proves `in = out + price`. +- Both use 252-bit blindings and `assertBalanced`, so wraparound is refused when the circuit is + defined (ADR-0051 D3a). + +**Minting purpose.** For each redeemer, the policy's own mint entry must be exactly as listed. + +- `Issue`: + - the mint entry is exactly `{PTS: n}`, with `n ≥ 1`; + - the issuer signs; + - no input carries the script credential; + - exactly `n` outputs carry the script credential, each one a well-formed note. +- `Split`: + - the mint entry is exactly `{PTS: 1}`; + - exactly one input carries the script credential. That input's spending purpose enforces the + transfer. +- `Receipt`: + - the mint entry is exactly `{receiptName: 1}`; + - exactly one input carries the script credential, and `receiptName` is derived from that + input's reference. That input's spending purpose enforces the redemption. + +**Spending purpose.** Datum `Note`. Both redeemers require that the owner signs and that the +transaction spends exactly one script-credential input, holding exactly one `PTS`. + +- `Transfer(proof)`: + - exactly two script-credential outputs, both notes, in order; + - the policy mint entry is exactly `{PTS: 1}`; + - the transfer proof verifies over the input datum and the two output datums. +- `Redeem(price, proof)`: + - exactly one script-credential output, a note; + - `1 ≤ price < 2^32`; + - the policy mint entry is exactly `{receiptName(own input): 1}`; + - an output to `issuerPkh` holds that receipt token, with inline datum `Receipt(owner, price)`; + - the redeem proof verifies. + +The retailer honours a redemption only for a receipt that holds a receipt token under the +points policy, and only once per token name. Only a valid `Redeem` can mint one, and each note +can be redeemed once. + +| ID | Invariant | +|---|---| +| P1 | Supply: `PTS` comes into existence only through an issuer-signed `Issue`, or the `+1` of a proved transfer. | +| P2 | Conservation: `in = o1 + o2` and `in = out + price`, as integers over 64-bit amounts. | +| P3 | Authorization: the note's owner signs. | +| P4 | One note per transaction, counted by payment credential. | +| P5 | State binding: commitments come from datums; `price` is bound by the proof and recorded in the receipt. | +| P6 | Only outputs at the script credential with exactly one `PTS` are notes. Anything else is ignored by wallets. | +| P7 | Receipts cannot be forged, because the receipt token is minted only with a valid redemption. | +| P8 | Canonical coordinates and price; owners are exactly 28 bytes. | + +**Copying commitments.** The sender knows the opening of every output it creates, including the +recipient's. It can therefore later create its own notes with the same commitment, funded from +its own value. Transfer proofs bind commitments, not UTxOs (as `ConfidentialNoteValidator` +documents), so a proof for the recipient's note also verifies against such a copy. Nothing is +stolen, but notes with equal commitments become linkable. A recipient who wants unlinkability +should re-split its note. + +**Not hidden:** +- the owners, which are key hashes in datums, so the transfer graph is public; +- the redeemed price; +- 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. + +--- + +## B. Committed credential gate + +A credit bureau issues one vector commitment to a holder's profile. The schema is +`zeroj.demo.credit-profile` v1, with entries `income/64, credit_score/16, birth_year/16, +country/16`. A lender's gate mints an access badge when the holder proves +`income ≥ minIncome ∧ credit_score ≥ minScore`. The proof reveals nothing else, and in particular +not `birth_year` or `country`. + +**Issuance record.** +- The bureau's native-script policy mints a record token named + `blake2b_256(I2OSP32(u) ‖ I2OSP32(v) ‖ I2OSP32(σ) ‖ holderPkh)`. +- The token sits at an output with inline datum `Record(u, v, σ, holderPkh)`. +- This is the authenticated issuance record that `pedersen-jubjub-vector-v1` §6 requires, + extended with the holder. Because the name commits to the datum, a record cannot be relabelled. + +**Gate.** `CreditGatePolicy`, a minting policy. +- Parameters: `σ`, `issuerPolicyId`, `minIncome`, `minScore` and the verification key. +- Redeemer: `Claim(holderPkh, u, v, proof)`. + +The gate checks: +- the holder signs; +- the lengths are right and `σ`, `u`, `v` are canonical; +- a reference input holds the exact record token, with the exact record datum; +- the gate's mint entry is exactly `{holderPkh: 1}`; +- the badge is paid to an output whose payment credential is the holder's key; +- Groth16 verifies over `[σ, u, v, minIncome, minScore]`, with every value from the parameters + or the record. + +**Circuit.** `CreditProfileProof` does three things: +1. binds `σ` as a public input with `ZkPedersenVector.bindSchema`; +2. commits to the four attributes with a 252-bit blinding; +3. asserts the two predicates against the public thresholds. + +**Consumer rule.** A lender that admits badge holders checks that the badge's name equals a key +that signed the presenting transaction. Badges can be moved like any token, so holding one proves +nothing on its own. + +| ID | Invariant | +|---|---| +| C1 | Statement binding: `σ` is a public input fixed by the gate's parameters. | +| C2 | Provenance: no record, no badge. The record token name commits to `(u, v, σ, holder)` (fail closed). | +| C3 | Holder binding: the record names the holder; the holder signs; the badge is named after the holder and paid to the holder. | +| C4 | Predicates: `income ≥ minIncome` and `credit_score ≥ minScore`, with the thresholds from the parameters. | +| C5 | Canonical integers and exact lengths. | + +**Not provided:** +- **Unlinkability:** presentations reuse `(u, v)`, so they can be linked. The BBS-based + `reusable-kyc` demo shows unlinkable presentations. +- **One-time use:** a holder can mint more badges for itself. That is harmless under the consumer + rule. +- **Revocation:** out of scope; see ADR-0004 for a status registry. + +--- + +## C. Hidden-liability solvency (Provisions-style) + +An exchange publishes one Pedersen commitment per customer balance, and proves that the hidden +total is at most the reserves it **locks** for an **attestation period**. Each customer checks +their own entry. Nobody learns another customer's balance or the total liabilities. The total +can be opened to an auditor through homomorphism, without opening any single entry. This follows +the Provisions approach [DBB+15]. + +The existing `proof-of-reserves` demo publishes the total liabilities, and its Merkle sum tree +reveals partial sums along each path. This demo hides both. + +**Why a period.** Solvency is a claim about one moment, and every customer must check the same +moment. Without a shared period, the exchange can reuse the same funds one after another: +1. attest for customers 1–4 with `R`; +2. let them check; +3. release; +4. attest for customers 5–8 with the same `R`. + +Each customer sees a correct, unique entry, and the book is only half covered. A period fixes +this, because every attestation of the period must be locked **at the same time**, from before +the period starts until after it ends. Within that window, attestations that split the customers +between them are backed by the sum of their separately locked reserves. + +**Script.** `SolvencyVault`, a multi-validator, so the attestation policy and the vault address +share one hash. +- Parameters: `exchangePkh`, the attestation token name, `N`, `periodStart`, `periodEnd` (POSIX ms) + and the verification key for `N` entries (`N = 4` in the demo). +- Each period therefore has its own script hash. The exchange announces its periods publicly, as + a schedule. The schedule publishes **every** vault parameter set used for a period. Customers + and the auditor add up across all of them. A period told to a customer privately proves nothing. +- `periodStart < periodEnd` is enforced off-chain, when the vault is derived. A malformed vault + cannot fool customers, because they derive the vault from the schedule themselves. + +**What the period guarantees.** The guarantee holds **per period**. Within one period, every +attestation is locked over the whole period at once, so its reserves are counted once. A check +covers only the period checked. + +With a recurring schedule, such as monthly periods, the exchange could list one group of +customers only in one period and another group only in the next, backed by the same funds. That +is the omission limitation, applied per period. So: +- each period's attestations must cover the whole book; +- customers should check every period they rely on, and in particular the current one. + +**Attest (minting purpose).** +- The exchange signs, and no vault output is spent. +- The validity range ends at or before `periodStart`: no attestation can be added once the + period has begun. +- The policy's mint entry is exactly one attestation token, with quantity 1. +- The output holding it has exactly the vault's enterprise address (no staking part), so + customers find every attestation at one address. +- Its inline datum is `Attestation([Entry(idHash: B32, u, v)] × N)`. +- Its value is the attested reserve `R` in lovelace (`R < 2^64`) plus the token, and nothing else. +- The entry count is exactly `N`, and every value is canonical. +- Groth16 verifies over `[R, u_1, …, u_N, v_1, …, v_N]`. + +**Release (spending purpose).** +- The validity range starts at or after `periodEnd`. +- The exchange signs. +- Exactly one vault output is spent. +- The attestation token is burned. + +During `[periodStart, periodEnd]` the set of attestations for the period cannot change: none can +be added, and none released. Neither a reserve nor a datum can change either. + +**Circuit.** `HiddenLiabilitySolvencyProof(N)` does three things: +1. commits each balance (64 bits) with a 252-bit blinding; +2. binds each commitment to its public coordinates; +3. proves `Σ b_i ≤ R`. + +The sum cannot wrap, because `N·2^64 ≪ p`. The circuit allows `N ≤ 16`. On-chain verification +costs two G1 scalar multiplications per customer: measured at 4.4e9 steps for `N = 4`, which puts +the 10e9 per-transaction limit near `N ≈ 19`. + +**Customer check (off-chain), during the period.** +1. Derive the period's vault script from the published parameters and verification key, and use + its hash. Never trust a script the exchange merely points to. +2. Read every UTxO at the vault address holding that policy's attestation token. +3. Check that the customer's `idHash` appears **exactly once** across all their entries. + - `idHash = blake2b_256(I2OSP2(len(id)) ‖ UTF-8(id) ‖ salt)`, with a 32-byte salt per period. + - `id` must be an identifier the customer can confirm independently and that no one else + shares, such as their account login. Otherwise the exchange could give two customers with + equal balances the same `(id, salt, blinding)`, and count one entry for both. +4. Check that the entry opens to the customer's `(balance, blinding)`. + +**Auditor check (off-chain).** The exchange hands the auditor `(L, Σ r_i mod l)`. The auditor +checks `Σ C_i = Commit(L, Σ r_i)` against the on-chain entries and learns `L` and nothing else. + +**Trusted setup.** The verification key must come from a setup the exchange could not subvert, +such as an MPC ceremony. Whoever holds the toxic waste can prove false solvency. In this demo the +exchange's process runs the single-party dev setup, which is acceptable only as a demo. + +| ID | Invariant | +|---|---| +| S1 | Solvency: `Σ b_i ≤ R`, where `R` is the lovelace locked in the attestation output from before `periodStart` until after `periodEnd`. | +| S2 | No negative balances: each `b_i < 2^64`, proved. | +| S3 | Binding: the proof covers exactly the datum's entries, in order. Neither the datum nor the reserve can change while the attestation is live. | +| S4 | Provenance: the exchange signs, under the period's vault script. | +| S5 | Canonical integers. | +| S6 | Inclusion is detected by customers (exactly once across the period's attestations), not prevented on-chain. | +| S7 | No reuse: all of a period's attestations are locked simultaneously throughout the period. | + +**Not provided:** +- **Borrowed reserves:** an exchange can borrow funds for the whole period. +- **Outside the period:** before `periodStart` and after `periodEnd`, the attestation proves + nothing. +- **Omission and understatement:** these are caught only by customers who check. +- **The customer count:** `N` per attestation is public. Padding with commitments to 0, which are + indistinguishable from any other commitment, hides the true count. +- **Linkage across periods:** a persistent salt links a customer's entries across periods. Use a + fresh salt each period. + +## Alternatives considered + +- **Re-using ZeroJ's reference validators as-is.** They are references for statement and context + 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. +- **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. + +## Milestones + +| Milestone | Scope | +|---|---| +| D0 | This ADR. | +| D1 | Project skeleton, shared helpers, and demo A (circuits, script, VM mutations, DevKit). | +| D2 | Demo B. | +| D3 | Demo C. | +| D4 | README, walkthrough runner, and `build-all.sh`. | + +## Verification + +- **Circuit negatives:** + - unbalanced or overflowing amounts; + - a wrong commitment; + - a predicate just below the threshold; + - the wrong schema digest; + - liabilities greater than reserves. +- **Plutus VM mutation tests** for each invariant, as in ZeroJ's M4 tests: + - a missing signer; + - a tampered proof; + - swapped or extra outputs; + - an extra staked script input; + - extra mint entries; + - a missing or relabelled record; + - a forged or unbound receipt; + - a badge sent elsewhere; + - the wrong entry count; + - an attestation after `periodStart`, or a vault with a staking part; + - an early release; + - non-canonical values. +- **DevKit end-to-end** for each demo, including script rejections. A rejection is the + script failing in local Julc evaluation, run as the node would run it. Rejected transactions + are never submitted, which would cost collateral. + +## References + +- [DBB+15] G. G. Dagher, B. Bünz, J. Bonneau, J. Clark, D. Boneh. *Provisions: Privacy-preserving + proofs of solvency for Bitcoin exchanges.* ACM CCS 2015. +- ZeroJ `docs/specs/pedersen-jubjub-v1.md` and `docs/specs/pedersen-jubjub-vector-v1.md` (§5–§6). diff --git a/examples/minimal-circuits/plonk/compliance-credential/gradle/wrapper/gradle-wrapper.jar b/examples/minimal-circuits/plonk/compliance-credential/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/examples/minimal-circuits/plonk/compliance-credential/gradle/wrapper/gradle-wrapper.jar differ diff --git a/examples/minimal-circuits/plonk/proof-of-reserves/gradle/wrapper/gradle-wrapper.jar b/examples/minimal-circuits/plonk/proof-of-reserves/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/examples/minimal-circuits/plonk/proof-of-reserves/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/usecase-versions.gradle b/gradle/usecase-versions.gradle index 9f7094e..c5288ea 100644 --- a/gradle/usecase-versions.gradle +++ b/gradle/usecase-versions.gradle @@ -14,7 +14,7 @@ def versions = { }() ext { - zerojVersion = project.findProperty('zerojVersion') ?: System.getenv('ZEROJ_VERSION') ?: versions.getProperty('zerojVersion') ?: '0.1.0-pre12' + zerojVersion = project.findProperty('zerojVersion') ?: System.getenv('ZEROJ_VERSION') ?: versions.getProperty('zerojVersion') ?: '0.1.0-pre13' julcVersion = project.findProperty('julcVersion') ?: System.getenv('JULC_VERSION') ?: versions.getProperty('julcVersion') ?: '0.1.0-pre18' cclVersion = project.findProperty('cclVersion') ?: System.getenv('CCL_VERSION') ?: versions.getProperty('cclVersion') ?: '0.8.0-pre5' } diff --git a/identity-kyc/gradle/wrapper/gradle-wrapper.jar b/identity-kyc/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/identity-kyc/gradle/wrapper/gradle-wrapper.jar differ diff --git a/pedersen-commitments/README.md b/pedersen-commitments/README.md new file mode 100644 index 0000000..8e3e7c9 --- /dev/null +++ b/pedersen-commitments/README.md @@ -0,0 +1,182 @@ +# 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: +- circuits proved with pure-Java Groth16 on BLS12-381; +- Plutus V3 validators written in Java with Julc; +- transactions built with cardano-client-lib. + +A web UI (Spring Boot + Svelte, port **8093**) has one tab per demo. Each tab shows the +**private** side (the openings the wallets hold) next to the **on-chain** side (what anyone can +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). + +## Why Pedersen commitments + +A Pedersen commitment `C = [v]·G + [r]·H` locks in a value `v` with a random blinding `r`. It +has three properties: + +| Property | Meaning | Where it shows | +|---|---|---| +| **Hiding** | `C` reveals nothing about `v`. | Every demo: balances, amounts and attributes stay off-chain. | +| **Binding** | Nobody can later open `C` to a different value. | Proofs are about the committed value, not a claimed one. | +| **Additive** | `C(a) + C(b) = C(a+b)`. | Demo A: hidden amounts balance. Demo C: an auditor opens a total. | + +A commitment on its own proves nothing. The ZK proof is what shows a hidden value satisfies a +rule, such as "these amounts balance", "this income is at least X", or "these balances sum to at +most R". The validator is what ties the proof to the transaction: signatures, outputs, issuance +records and time locks. + +--- + +## A. Confidential points + +A retailer's loyalty points are **notes** whose amounts are commitments. + +| 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. + +## B. Committed credential gate + +A credit bureau commits to Alice's whole profile in **one vector commitment**, under the schema +`zeroj.demo.credit-profile` v1: income, credit score, birth year and country. It records the +issuance on-chain with a token whose name binds the commitment, the schema digest and Alice's key. + +Alice proves `income ≥ 50,000 ∧ credit_score ≥ 650` to a lender's `CreditGatePolicy` and +receives an access badge. The lender learns that she qualifies, and not her income, score, birth +year or country. + +The gate refuses: +- a claim without the issuance record (fail closed); +- a commitment relabelled under another schema, or recorded for another holder; +- proofs for weaker thresholds; +- a badge that is not paid to the holder. + +**Not provided:** unlinkability, since presentations reuse the commitment. The BBS-based +`reusable-kyc` demo shows unlinkable presentations. + +## C. Solvency with hidden liabilities + +An exchange publishes one commitment per customer balance. It locks reserves `R` in a vault and +proves that the hidden total is at most `R`. This follows the Provisions approach from CCS 2015. + +| | Merkle sum tree (`proof-of-reserves`) | Pedersen (this demo) | +|---|---|---| +| Total liabilities | Public | Hidden | +| Other customers' balances | Partial sums leak along the path | Hidden | +| A customer's check | Merkle path | Opens their own commitment | +| Auditor | Sees the total | Opens the sum of commitments, by homomorphism | + +- Solvency is attested for a public **period**, and each period has its own vault script. + Attestations can be made only **before** the period starts and released only **after** it + ends. So every attestation of the period is locked at the same time, and the same funds cannot + 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. + +**Not provided:** +- borrowed reserves, held for the period; +- protection against a setup the exchange ran itself: the verification key must come from a + setup the exchange cannot subvert; +- omission, which only the customers who check will catch; +- the customer count, which is public (pad with commitments to 0 to hide it). + +--- + +## Run + +Yaci DevKit must be running (`yaci-cli devkit start`), with Java 25 (`sdk use java 25.0.2-graal`). + +**Web UI.** + +```bash +./gradlew clean bootJar -PwithFrontend # builds the Svelte UI into the jar +java --enable-native-access=ALL-UNNAMED -Dzeroj.allowInsecureTrustedSetup=true \ + -jar build/libs/pedersen-commitments-*.jar +# open http://localhost:8093 +``` + +You can also start it from the repository root with Docker: `./demo.sh pedersen` (add `--run` +for a scripted happy path). The image needs a ZeroJ release that includes the Pedersen +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, +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. + +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. | +| 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. | + +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`. + +**CLI walkthrough and tests.** + +```bash +./gradlew walkthrough # narrated run of all three demos 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 +``` + +The walkthrough and the tests read `ZEROJ_YACI_STORE_URL` / `ZEROJ_YACI_ADMIN_URL` when DevKit +uses non-default ports. Script rejections in the tests are the scripts failing in local Julc +evaluation of the real transaction, as the node would run them; rejected transactions are not +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 | + +## Layout + +``` +src/main/java/.../pedersen/ + common/ KeyedCircuit (dev keys, JSON verification), DevKit, Plutus encodings + points/ ConfidentialPoints; circuit/PointsTransferProof, PointsRedeemProof; onchain/PointsLedger + 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) + 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 +``` + +## Important + +- **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. +- **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 new file mode 100644 index 0000000..646054d --- /dev/null +++ b/pedersen-commitments/build.gradle @@ -0,0 +1,143 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.5.0-M3' + id 'io.spring.dependency-management' version '1.1.7' +} + +group = 'com.bloxbean.cardano.zeroj.usecases' +// Release version: repo-wide version.properties (single source), overridable with -PreleaseVersion. +version = project.findProperty('releaseVersion') ?: { + for (def dir = projectDir; dir != null; dir = dir.parentFile) { + def vf = new File(dir, 'version.properties') + if (vf.isFile()) { def p = new Properties(); vf.withInputStream { p.load(it) }; return p.getProperty('version') } + } + return '0.1.0-SNAPSHOT' +}() +java { + toolchain { + languageVersion = JavaLanguageVersion.of(25) + } +} + +springBoot { + mainClass = 'com.bloxbean.cardano.zeroj.usecases.pedersen.PedersenCommitmentsApplication' +} + +repositories { + mavenCentral() + mavenLocal() + maven { + url = uri("https://central.sonatype.com/repository/maven-snapshots") + content { snapshotsOnly() } + } + maven { + url = uri("https://repo.spring.io/milestone") + } +} + +def usecaseVersionsScript = { + def dir = projectDir + while (dir != null) { + def candidate = new File(dir, 'gradle/usecase-versions.gradle') + if (candidate.isFile()) { + return candidate + } + dir = dir.parentFile + } + throw new GradleException('Could not find gradle/usecase-versions.gradle') +}() +apply from: usecaseVersionsScript + +dependencies { + // Spring Boot — the web UI and its REST API + implementation 'org.springframework.boot:spring-boot-starter-web' + + // ZeroJ — circuits, Pedersen gadgets, Groth16 prover/verifier, on-chain verifier library + implementation "org.zeroj:zeroj-api:${zerojVersion}" + implementation "org.zeroj:zeroj-circuit-dsl:${zerojVersion}" + implementation "org.zeroj:zeroj-circuit-lib:${zerojVersion}" + 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-codec:${zerojVersion}" + implementation "org.zeroj:zeroj-verifier-groth16:${zerojVersion}" + implementation "org.zeroj:zeroj-onchain-julc:${zerojVersion}" + annotationProcessor "org.zeroj:zeroj-onchain-julc:${zerojVersion}" + + // Julc — Java to Plutus V3 + implementation "org.julclang:julc-stdlib:${julcVersion}" + annotationProcessor "org.julclang:julc-annotation-processor:${julcVersion}" + implementation "org.julclang:julc-cardano-client-lib:${julcVersion}" + runtimeOnly "org.julclang:julc-vm-java:${julcVersion}" + + // Cardano Client Lib — transactions against Yaci DevKit + implementation "com.bloxbean.cardano:cardano-client-lib:${cclVersion}" + implementation "com.bloxbean.cardano:cardano-client-backend-blockfrost:${cclVersion}" + + testImplementation platform('org.junit:junit-bom:5.11.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' + testImplementation "org.julclang:julc-testkit:${julcVersion}" + testRuntimeOnly "org.julclang:julc-vm-java:${julcVersion}" +} + +// The narrated CLI walkthrough of all three demos on a running Yaci DevKit (no UI). +tasks.register('walkthrough', JavaExec) { + group = 'application' + description = 'Runs the three Pedersen demos end to end on Yaci DevKit from the command line.' + classpath = sourceSets.main.runtimeClasspath + mainClass = 'com.bloxbean.cardano.zeroj.usecases.pedersen.PedersenDemos' + jvmArgs '--enable-native-access=ALL-UNNAMED', '-Dzeroj.allowInsecureTrustedSetup=true' +} + +bootRun { + jvmArgs '--enable-native-access=ALL-UNNAMED', '-Dzeroj.allowInsecureTrustedSetup=true' +} + +// Fork the compiler for the Julc annotation processor on Java 25 +compileJava { + options.compilerArgs.add('-proc:full') + options.fork = true + options.forkOptions.jvmArgs = ['--enable-native-access=ALL-UNNAMED'] +} +compileTestJava { + options.compilerArgs.add('-proc:full') + options.fork = true + options.forkOptions.jvmArgs = ['--enable-native-access=ALL-UNNAMED'] +} + +test { + useJUnitPlatform() + jvmArgs '--enable-native-access=ALL-UNNAMED' + maxHeapSize = '4g' + systemProperty "zeroj.allowInsecureTrustedSetup", "true" + systemProperty "zeroj.yaci.e2e", System.getenv("ZEROJ_YACI_E2E") ?: "" + environment "ZEROJ_YACI_E2E", System.getenv("ZEROJ_YACI_E2E") ?: "" + testLogging { + events "passed", "failed", "skipped" + showStandardStreams = true + } +} + +// === Frontend build (Svelte + Vite) === + +def frontendDir = file('frontend') + +tasks.register('npmInstall', Exec) { + workingDir frontendDir + commandLine 'npm', 'install' + inputs.file(new File(frontendDir, 'package.json')) + outputs.dir(new File(frontendDir, 'node_modules')) +} + +tasks.register('buildFrontend', Exec) { + dependsOn 'npmInstall' + workingDir frontendDir + commandLine 'npm', 'run', 'build' + inputs.dir(new File(frontendDir, 'src')) + outputs.dir(file('src/main/resources/static')) +} + +if (project.hasProperty('withFrontend')) { + processResources.dependsOn buildFrontend +} diff --git a/pedersen-commitments/frontend/index.html b/pedersen-commitments/frontend/index.html new file mode 100644 index 0000000..9157b02 --- /dev/null +++ b/pedersen-commitments/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + Pedersen Commitments — ZeroJ + + + +
+ + + diff --git a/pedersen-commitments/frontend/package-lock.json b/pedersen-commitments/frontend/package-lock.json new file mode 100644 index 0000000..d41efe2 --- /dev/null +++ b/pedersen-commitments/frontend/package-lock.json @@ -0,0 +1,1425 @@ +{ + "name": "pedersen-commitments-frontend", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pedersen-commitments-frontend", + "version": "0.1.0", + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^5.0.3", + "svelte": "^5.19.0", + "vite": "^6.1.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", + "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", + "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", + "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", + "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", + "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", + "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", + "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", + "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", + "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", + "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", + "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", + "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", + "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", + "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", + "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", + "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", + "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", + "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", + "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", + "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", + "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", + "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", + "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", + "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", + "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", + "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/lzma-linux-x64-gnu": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz", + "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^22.20 || ^24.12 || >=25" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.0.tgz", + "integrity": "sha512-FLLpX941CD/7aBvX3GqLGBM9OvY5PGXTryPJkG5r5/OuBpZpV5k45Uo3RxAvqd35tsyc3hH1bhtz921IKzoIzg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.0.tgz", + "integrity": "sha512-iI32XM/jnDYJsvx5ai/za/7gWO9XoSeFFtU06/ZCaRgyilfJOjaopD3nOpk2WrTCGOyeDt4hleUiGOAnd5tHNg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.0.tgz", + "integrity": "sha512-dRBZlbt2sEtF8Mn4MODThze9fIPdDoOhVSlXMAKy5dQbOYK9pOOoPY4Fat3OTtr0+8zbJo5TTZwlsfxY/kDNJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.0.tgz", + "integrity": "sha512-Y3whrJOMucfkhgNkvcM93M6j8C53iEAMmPMYD99C6G1kUy4ELigLWk9ar2/4aCBSRgsql0zdlOemLgW2m5GZgQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.0.tgz", + "integrity": "sha512-S6S1GEzPjFF6IONYJX3AKt/799+8RgBgCcwRnUo+Ep1IvBxUbw5M51iU0TDdK2NWWVnSvCQ8yi6Em0fGASMOng==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.0.tgz", + "integrity": "sha512-Ed1DPoFENkXj4IGzSB12SesV40iP6LxCCrbTIkSGIQBpOOxpBM+0kj62lmaeIHfMWTDoddqTOtqc7s8LYfn+Pw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.0.tgz", + "integrity": "sha512-J/6xhutJPtFyIkmHdf4olOdHHKH5kOJNumojdWn+Elv5ICEYTVOa362Vw27TxsK0BLzb1le3EDlO3UbvFK1lnQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.0.tgz", + "integrity": "sha512-G4L/Nnx59d2LvDoV/P4S5lZ7oVLT6hodOHMacqjiq2LL2gts86KbkEBTYL53+fBt0odhf7XPIbIATGoYiJctxg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.0.tgz", + "integrity": "sha512-zF16pvJDEUksGYRbfnXne7pdklAyj2XDmJeYKgP93oq0cUyX9Y8O7lUo1R+IY1GagP/YBvCEDCe7eEcAKpw//g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.0.tgz", + "integrity": "sha512-nIggWn8n+w12+R5lsV+PYYoUY8vuObxPAQqJI7WES+9v0qspYuAHoZMfYM0yLxlipasT5BY9ht5W8t5c/rSCkg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.0.tgz", + "integrity": "sha512-WLOTiHPzszP0dxIMsHpFeDSOSB5I49Mj8K4+yKE3H1X/D0JRG5XZ5jrctJLMjnUc/LUzaKiwq6EHWNJ8pup8PA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.0.tgz", + "integrity": "sha512-35RK9aRhh7g7Pmeu5gQ01aCvrhXzj9LoBE6xtUcEH1ns+nyTaSzxSpADmBQINu4QiTDGvmQYwo1j5hlg1rRXFw==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.0.tgz", + "integrity": "sha512-RqTfnpoTjuWfPAmqK5p2edt2AMCDJWm6oTn7sKfmyx+6tRga0ip05SJ977o6udTcIiDeF/CJMUfkaN4gtWt6Aw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.0.tgz", + "integrity": "sha512-RQjZPigjxFvFZDijG6rjlSXxhRaTf9zLYVpGK+lVcga64oMqP1GbgVqCb46eHTTceSIgp89Ja0y5aPe3GFBYHg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.0.tgz", + "integrity": "sha512-tjL58mgQcTRnDRpeky+Sth1MKQeYi2Ct6r3Luq9E5aTSjnM/i/JbozqZkKqp9thM5+oDSZxo+05f9kdQedfTGA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.0.tgz", + "integrity": "sha512-ictoRyVaoZ8C67myHef+8hhCa6IplXJJ/xUCkVCxziV4zxMZh+jvhkhGsPBLqj1S72fnqD0QH5zL4lcaa4X7DQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.0.tgz", + "integrity": "sha512-8aVvZ2hfr9RLFzBQkQNmYeHLDja8fLeQAmLt757zdKN/B+8L809KlLJKctQjS22wZotptV8G6o7fVPuAs8S1tQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.0.tgz", + "integrity": "sha512-2dEF8GAcDKwshUfydD+GhosppNyBzhVUHkdFF3CXd3FpOkzj/RZzF5aoEtzklujklT5qFVRU2GK/cFeLaTNKVg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.0.tgz", + "integrity": "sha512-3XHTvoo2hKkh0MiOfS7SkhHjMaaWF7P4F3drocZZaho/Z8w7h/jpnuBHm91BOQLfvrKHs1yR+zir4E8RI3XzTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.0.tgz", + "integrity": "sha512-HKtkzodL4a3KFWDXDoO61cRynAWTR3LnAE0oGtfG9lcNFpNuVYUFOByxDgNqEvic9rvaQbAj+SFwTEWDptRaIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.0.tgz", + "integrity": "sha512-JBsxqiY16uyyCujtoC3s7zL+SrYyNElptD7K4V+KUoJ2V8/XG3hPWpheK+SuPwNh1cikJvIZmIdsrYXvD6PLJw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.0.tgz", + "integrity": "sha512-S5Qrijh37qhnUYQ0ay8WN3LuWeKjow7wTUyCOPMZtnXiBXYXdsZETI6ZLfYnQAKovltckPLBFdNeD61P2rJc7g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.0.tgz", + "integrity": "sha512-zbZ6iMmLFEsCtTdc2/y1F/cDFVNNCPF7Ae8PCT/wdPE//hGwYp6r+MyCLMFX+kOeIe09Pz6ASfnnfpSTN1FJQQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.0.tgz", + "integrity": "sha512-L6Hw69oNpuYaOr1zCG30v0/DqKYCSRwodPGwIcVZ/6f8SOzq9rxtL/xNVI5MO4wjli+Ko0ErK9uHJL3mNPt8wQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.0.tgz", + "integrity": "sha512-nl+CTWIgOGszQmUz/kanfgrfFZ4qiwxKIfT/ryl3N3Ewk5tqizmYtNXiqb7Bu/fDtNgu1kyxdFiAUJNur3iysg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@sveltejs/acorn-typescript": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz", + "integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^8.9.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-5.1.1.tgz", + "integrity": "sha512-Y1Cs7hhTc+a5E9Va/xwKlAJoariQyHY+5zBgCZg4PFWNYQ1nMN9sjK1zhw1gK69DuqVP++sht/1GZg1aRwmAXQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@sveltejs/vite-plugin-svelte-inspector": "^4.0.1", + "debug": "^4.4.1", + "deepmerge": "^4.3.1", + "kleur": "^4.1.5", + "magic-string": "^0.30.17", + "vitefu": "^1.0.6" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22" + }, + "peerDependencies": { + "svelte": "^5.0.0", + "vite": "^6.0.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte-inspector": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte-inspector/-/vite-plugin-svelte-inspector-4.0.1.tgz", + "integrity": "sha512-J/Nmb2Q2y7mck2hyCX4ckVHcR5tu2J+MtBEQqpDrrgELZ2uvraQcK/ioCV61AqkdXFgriksOKIceDcQmqnGhVw==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.7" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22" + }, + "peerDependencies": { + "@sveltejs/vite-plugin-svelte": "^5.0.0", + "svelte": "^5.0.0", + "vite": "^6.0.0" + } + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/acorn": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz", + "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aria-query": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", + "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/devalue": { + "version": "5.9.4", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz", + "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.25.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", + "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.25.12", + "@esbuild/android-arm": "0.25.12", + "@esbuild/android-arm64": "0.25.12", + "@esbuild/android-x64": "0.25.12", + "@esbuild/darwin-arm64": "0.25.12", + "@esbuild/darwin-x64": "0.25.12", + "@esbuild/freebsd-arm64": "0.25.12", + "@esbuild/freebsd-x64": "0.25.12", + "@esbuild/linux-arm": "0.25.12", + "@esbuild/linux-arm64": "0.25.12", + "@esbuild/linux-ia32": "0.25.12", + "@esbuild/linux-loong64": "0.25.12", + "@esbuild/linux-mips64el": "0.25.12", + "@esbuild/linux-ppc64": "0.25.12", + "@esbuild/linux-riscv64": "0.25.12", + "@esbuild/linux-s390x": "0.25.12", + "@esbuild/linux-x64": "0.25.12", + "@esbuild/netbsd-arm64": "0.25.12", + "@esbuild/netbsd-x64": "0.25.12", + "@esbuild/openbsd-arm64": "0.25.12", + "@esbuild/openbsd-x64": "0.25.12", + "@esbuild/openharmony-arm64": "0.25.12", + "@esbuild/sunos-x64": "0.25.12", + "@esbuild/win32-arm64": "0.25.12", + "@esbuild/win32-ia32": "0.25.12", + "@esbuild/win32-x64": "0.25.12" + } + }, + "node_modules/esm-env": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", + "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esrap": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz", + "integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "peerDependencies": { + "@typescript-eslint/types": "^8.2.0" + }, + "peerDependenciesMeta": { + "@typescript-eslint/types": { + "optional": true + } + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/is-reference": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", + "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.6" + } + }, + "node_modules/kleur": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz", + "integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "dev": true, + "license": "MIT" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.19", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz", + "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rollup": { + "version": "4.64.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.0.tgz", + "integrity": "sha512-gjA/kFeDfffII8COoPsvLPvE16hWDTEc1+0QKQNKUkuV8iJjqsC4xXs8/FzuL0v9EV39kuxTbAgcFoTRyy2TGQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "1.0.9" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@napi-rs/lzma-linux-x64-gnu": "1.5.1", + "@rollup/rollup-android-arm-eabi": "4.64.0", + "@rollup/rollup-android-arm64": "4.64.0", + "@rollup/rollup-darwin-arm64": "4.64.0", + "@rollup/rollup-darwin-x64": "4.64.0", + "@rollup/rollup-freebsd-arm64": "4.64.0", + "@rollup/rollup-freebsd-x64": "4.64.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.64.0", + "@rollup/rollup-linux-arm-musleabihf": "4.64.0", + "@rollup/rollup-linux-arm64-gnu": "4.64.0", + "@rollup/rollup-linux-arm64-musl": "4.64.0", + "@rollup/rollup-linux-loong64-gnu": "4.64.0", + "@rollup/rollup-linux-loong64-musl": "4.64.0", + "@rollup/rollup-linux-ppc64-gnu": "4.64.0", + "@rollup/rollup-linux-ppc64-musl": "4.64.0", + "@rollup/rollup-linux-riscv64-gnu": "4.64.0", + "@rollup/rollup-linux-riscv64-musl": "4.64.0", + "@rollup/rollup-linux-s390x-gnu": "4.64.0", + "@rollup/rollup-linux-x64-gnu": "4.64.0", + "@rollup/rollup-linux-x64-musl": "4.64.0", + "@rollup/rollup-openbsd-x64": "4.64.0", + "@rollup/rollup-openharmony-arm64": "4.64.0", + "@rollup/rollup-win32-arm64-msvc": "4.64.0", + "@rollup/rollup-win32-ia32-msvc": "4.64.0", + "@rollup/rollup-win32-x64-gnu": "4.64.0", + "@rollup/rollup-win32-x64-msvc": "4.64.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/svelte": { + "version": "5.57.1", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.1.tgz", + "integrity": "sha512-Uqj49lWKB+iSSnneuwiYYJ7MZgkB+eXr0LXBhv4uDuAkXqnWmq65Sxflfvp0Lc6MdKjMUxGaeOKWJqz5SNiVIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "@jridgewell/sourcemap-codec": "^1.6.0", + "@sveltejs/acorn-typescript": "^1.0.13", + "@types/estree": "^1.0.9", + "acorn": "^8.18.0", + "aria-query": "5.3.1", + "axobject-query": "^4.1.0", + "clsx": "^2.1.1", + "devalue": "^5.9.2", + "esm-env": "^1.2.1", + "esrap": "^2.3.6", + "is-reference": "^3.0.3", + "locate-character": "^3.0.0", + "magic-string": "^0.30.11", + "zimmerframe": "^1.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/vite": { + "version": "6.4.3", + "resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz", + "integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.25.0", + "fdir": "^6.4.4", + "picomatch": "^4.0.2", + "postcss": "^8.5.3", + "rollup": "^4.34.9", + "tinyglobby": "^0.2.13" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || ^20.0.0 || >=22.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", + "jiti": ">=1.21.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitefu": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz", + "integrity": "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==", + "dev": true, + "license": "MIT", + "workspaces": [ + "tests/deps/*", + "tests/projects/*", + "tests/projects/workspace/packages/*" + ], + "peerDependencies": { + "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + }, + "node_modules/zimmerframe": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz", + "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/pedersen-commitments/frontend/package.json b/pedersen-commitments/frontend/package.json new file mode 100644 index 0000000..0a74984 --- /dev/null +++ b/pedersen-commitments/frontend/package.json @@ -0,0 +1,16 @@ +{ + "name": "pedersen-commitments-frontend", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "^5.0.3", + "svelte": "^5.19.0", + "vite": "^6.1.0" + } +} diff --git a/pedersen-commitments/frontend/src/App.svelte b/pedersen-commitments/frontend/src/App.svelte new file mode 100644 index 0000000..1abdb09 --- /dev/null +++ b/pedersen-commitments/frontend/src/App.svelte @@ -0,0 +1,100 @@ + + +
+

Pedersen Commitments on Cardano

+

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

+ +
+ Demo server. This server creates every wallet and holds every opening (amounts, blindings, + profiles, customer balances) and key on the users' behalf; real users would each keep their own. + The On-chain panels show what anyone can read from the ledger. +
+ + {#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.

+ {#if status?.demos} +

+ {#each Object.entries(status.demos) as [name, s]} + {name}: {s} + {/each} +

+ {/if} +
+ {/if} + + + + {#if status?.demos?.[tab] === 'ready'} + {#if tab === 'points'}{/if} + {#if tab === 'credit'}{/if} + {#if tab === 'solvency'}{/if} + {:else if status} +

This demo is {status?.demos?.[tab] ?? 'starting'}…

+ {/if} +
+ + diff --git a/pedersen-commitments/frontend/src/lib/Outcome.svelte b/pedersen-commitments/frontend/src/lib/Outcome.svelte new file mode 100644 index 0000000..2f9f05a --- /dev/null +++ b/pedersen-commitments/frontend/src/lib/Outcome.svelte @@ -0,0 +1,40 @@ + + +{#if result} + {#if result.ok} +
+ ✓ {result.data.summary ?? result.data.verdict ?? result.data.lenderLearns ?? 'Done'} + {#if result.data.txHash}
tx {result.data.txHash}{/if} +
+ {:else if result.data?.noProof} +
+

No proof possible

+

{result.data.error}

+

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

+
+ {:else if result.data?.onChainValidation} +
+

{result.data.onChainValidation.title}

+

{result.data.onChainValidation.summary}

+
{result.data.onChainValidation.detail}
+
+ {:else} +

{result.data?.error ?? 'Failed'}

+ {/if} +{/if} + + diff --git a/pedersen-commitments/frontend/src/lib/api.ts b/pedersen-commitments/frontend/src/lib/api.ts new file mode 100644 index 0000000..7480992 --- /dev/null +++ b/pedersen-commitments/frontend/src/lib/api.ts @@ -0,0 +1,20 @@ +// Native fetch only (no axios). Every call resolves to { ok, data }; errors carry the +// server's JSON body (noProof / onChainValidation) for the error panel. +export type ApiResult = { ok: boolean; data: any }; + +async function call(method: string, path: string, body?: unknown): Promise { + try { + const res = await fetch(`/api${path}`, { + method, + headers: body === undefined ? undefined : { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + const data = await res.json().catch(() => ({ error: res.statusText })); + return { ok: res.ok, data }; + } catch (e: any) { + return { ok: false, data: { error: e?.message ?? String(e) } }; + } +} + +export const get = (path: string) => call('GET', path); +export const post = (path: string, body: unknown = {}) => call('POST', path, body); diff --git a/pedersen-commitments/frontend/src/main.ts b/pedersen-commitments/frontend/src/main.ts new file mode 100644 index 0000000..350691a --- /dev/null +++ b/pedersen-commitments/frontend/src/main.ts @@ -0,0 +1,6 @@ +import App from './App.svelte'; +import { mount } from 'svelte'; + +const app = mount(App, { target: document.getElementById('app')! }); + +export default app; diff --git a/pedersen-commitments/frontend/src/tabs/Credit.svelte b/pedersen-commitments/frontend/src/tabs/Credit.svelte new file mode 100644 index 0000000..2aa6720 --- /dev/null +++ b/pedersen-commitments/frontend/src/tabs/Credit.svelte @@ -0,0 +1,106 @@ + + +
+

B. Committed credential

+

A credit bureau commits to four attributes of Alice's profile in one vector commitment + (schema {state?.schema?.id} v{state?.schema?.version}) and records the issuance on-chain. Alice then + proves income ≥ X ∧ credit_score ≥ Y to a lender's gate and receives a badge. The lender learns that + she qualifies — not her income, score, birth year or country. Circuit: {state?.constraints ?? '…'} constraints.

+ +
+
+

1. Bureau issues Alice's profile

+ + + + + +
+
+

2. Alice claims a badge from the lender

+ + + +

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

+
+
+

Try to cheat: Mallory presents Alice's credential

+

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

+ +
+
+ + {#if busy}

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

{/if} + + + {#if state} +
+
+

Private — Alice's opening

+ {#if state.private} + + + + + + + + +
income{state.private.income}
credit score{state.private.creditScore}
birth year{state.private.birthYear}
country{state.private.country}
blinding{state.private.blinding}
+ {:else}

No profile issued yet.

{/if} +
+
+

On-chain — the issuance record

+ {#if state.onChain} + + + + + + + + + +
commitment u{state.onChain.u}
commitment v{state.onChain.v}
schema digest σ{state.schema.digest}
holder{state.onChain.holder}
record token{state.onChain.recordToken}
record tx{state.onChain.recordTx.substring(0, 20)}…
+ {:else}

Nothing recorded yet.

{/if} +

What the lender learns

+ {#if state.claims.length === 0}

No badge claimed yet.

{/if} + + + {#each state.claims as c}{/each} + +
{c.claimant}: {c.lenderLearns}{c.txHash.substring(0, 16)}…
+
+
+ {/if} +
diff --git a/pedersen-commitments/frontend/src/tabs/Points.svelte b/pedersen-commitments/frontend/src/tabs/Points.svelte new file mode 100644 index 0000000..058109b --- /dev/null +++ b/pedersen-commitments/frontend/src/tabs/Points.svelte @@ -0,0 +1,123 @@ + + +
+

A. Confidential points

+

Loyalty points are notes whose amounts are Pedersen commitments. A transfer proves + in = out1 + out2 over hidden 64-bit amounts; a redemption proves in = change + price + with a public price. The PointsLedger script checks the proof, the owner's signature, issuer-only + supply and one-time receipts. Circuits: transfer {state?.constraints?.transfer ?? '…'} constraints, redeem + {state?.constraints?.redeem ?? '…'}.

+ +
+
+

Issue (retailer)

+ + + +
+
+

Transfer

+ + + + +

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

+
+
+

Redeem at the retailer

+ + + +
+
+

Try to cheat: spend someone else's note

+ + + +

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

+
+
+ + {#if busy}

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

{/if} + + + {#if state} +
+
+

Private — the openings each wallet holds

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

{label}: balance {w.balance} points

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

On-chain — what anyone can see

+

Notes at {state.ledgerAddress.substring(0, 34)}…: owner and commitment, never the amount.

+ + + + {#each state.onChain as n}{/each} + +
note UTxOownercommitment uv
{n.utxo}{n.owner}{n.u}{n.v}
+

Receipts held by the retailer

+ {#if state.receipts.length === 0}

None yet.

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

Transactions

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

C. Hidden-liability solvency

+

The exchange publishes one Pedersen commitment per customer balance and proves + Σ balances ≤ reserves while hiding every balance and the total. The reserve is locked in a vault for a + public attestation period: attestations only before it starts, release only after it ends, so the same funds + cannot back attestations one after another. Customers check their own entry; an auditor opens the total by + homomorphism. Circuit: {state?.constraints ?? '…'} constraints (4 customers).

+ +
+
+

1. The book (balances in ADA)

+ + + {#each rows as r} + + {/each} + +
+ +
+
+

2. Attest for a new period

+ + +

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

+
+
+

3. Check (during the period)

+ {#each state?.book ?? [] as c} + + {/each} + +
+
+

Try to cheat inside the period

+ + +

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

+
+
+ + {#if busy}

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

{/if} + + {#if result?.ok && result.data.liabilitiesAda !== undefined} +
Auditor: the sum of all commitments opens to total liabilities of + {result.data.liabilitiesAda} ADA against {result.data.reservesAda} ADA locked — + {result.data.ok ? 'verified' : 'NOT verified'}. No single balance is revealed.
+ {/if} + + {#if state} + {#if state.period} +
+ Period: phase {state.phase} + {#if state.phase === 'before'} — starts in {seconds(state.period.start)} s (attestations allowed until then){/if} + {#if state.phase === 'during'} — ends in {seconds(state.period.end)} s (nothing can be added or released){/if} + {#if state.phase === 'after'} — ended; the reserve can be released{/if} + {#if state.phase === 'released'} — reserve released, tx {state.releaseTx.substring(0, 20)}…{/if} +
+ {/if} +
+
+

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

+

Total liabilities: {state.liabilitiesAda} ADA (never published)

+ + + + {#each state.book as c} + + {/each} + +
customerbalancesaltblindingid hashlast check
{c.id}{c.balance}{c.salt}{c.blinding}{c.idHash}{c.check}
+
+
+

On-chain — the period's vault

+ {#if state.period} +

Reserve locked: {state.reservesAda} ADA at {state.vaultAddress.substring(0, 30)}…

+ + + + {#each state.onChain ?? [] as e}{/each} + +
id hashcommitment u
{e.idHash}{e.u}
+

Attestation tx {state.attestTx.substring(0, 20)}…

+ {:else}

No attestation yet.

{/if} +
+
+ {/if} +
diff --git a/pedersen-commitments/frontend/svelte.config.js b/pedersen-commitments/frontend/svelte.config.js new file mode 100644 index 0000000..4c6b24b --- /dev/null +++ b/pedersen-commitments/frontend/svelte.config.js @@ -0,0 +1,5 @@ +import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; + +export default { + preprocess: vitePreprocess(), +}; diff --git a/pedersen-commitments/frontend/vite.config.ts b/pedersen-commitments/frontend/vite.config.ts new file mode 100644 index 0000000..fc61d72 --- /dev/null +++ b/pedersen-commitments/frontend/vite.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from 'vite'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; + +export default defineConfig({ + plugins: [svelte()], + build: { + outDir: '../src/main/resources/static', + emptyOutDir: true, + }, + server: { + port: 5175, + proxy: { + '/api': 'http://localhost:8093', + }, + }, +}); diff --git a/pedersen-commitments/gradle/wrapper/gradle-wrapper.jar b/pedersen-commitments/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/pedersen-commitments/gradle/wrapper/gradle-wrapper.jar differ diff --git a/pedersen-commitments/gradle/wrapper/gradle-wrapper.properties b/pedersen-commitments/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..7687eb5 --- /dev/null +++ b/pedersen-commitments/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Feb 06 21:12:56 SGT 2026 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/pedersen-commitments/gradlew b/pedersen-commitments/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/pedersen-commitments/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 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. +# + +############################################################################## +# +# 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/master/subprojects/plugins/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# 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"' + +# 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 + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# 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 + which java >/dev/null 2>&1 || 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 + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + 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 + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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/pedersen-commitments/gradlew.bat b/pedersen-commitments/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/pedersen-commitments/gradlew.bat @@ -0,0 +1,89 @@ +@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 + +@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=. +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%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/pedersen-commitments/settings.gradle b/pedersen-commitments/settings.gradle new file mode 100644 index 0000000..466be1a --- /dev/null +++ b/pedersen-commitments/settings.gradle @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + gradlePluginPortal() + maven { url = uri("https://repo.spring.io/milestone") } + } +} + +rootProject.name = 'pedersen-commitments' diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/PedersenCommitmentsApplication.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/PedersenCommitmentsApplication.java new file mode 100644 index 0000000..6d89392 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/PedersenCommitmentsApplication.java @@ -0,0 +1,16 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Web UI for the three Pedersen commitment demos (ADR-0006): confidential points, a committed + * credential gate, and solvency with hidden liabilities, on Yaci DevKit. + */ +@SpringBootApplication +public class PedersenCommitmentsApplication { + + public static void main(String[] args) { + SpringApplication.run(PedersenCommitmentsApplication.class, args); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/PedersenDemos.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/PedersenDemos.java new file mode 100644 index 0000000..6bb3a4f --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/PedersenDemos.java @@ -0,0 +1,156 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen; + +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.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; +import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.CreditGate; +import com.bloxbean.cardano.zeroj.usecases.pedersen.points.ConfidentialPoints; +import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation; + +import java.time.Instant; +import java.util.List; + +/** + * A walkthrough of the three Pedersen commitment demos on a running Yaci DevKit: + * {@code ./gradlew run}. Each step prints what goes on-chain and what stays private. + */ +public final class PedersenDemos { + + private PedersenDemos() {} + + public static void main(String[] args) throws Exception { + if (!DevKit.reachable()) { + System.err.println("Yaci DevKit is not reachable at " + DevKit.STORE_URL + + " (set ZEROJ_YACI_STORE_URL / ZEROJ_YACI_ADMIN_URL)"); + System.exit(1); + } + BackendService backend = DevKit.backend(); + confidentialPoints(backend); + creditGate(backend); + solvency(backend); + System.out.println("\nAll three demos completed on DevKit."); + } + + private static void confidentialPoints(BackendService backend) throws Exception { + header("A. Confidential points — hidden balances that still add up"); + var retailer = funded(); + var alice = funded(); + var bob = funded(); + var points = new ConfidentialPoints(); + var script = points.script(pkh(retailer)); + String ledger = ConfidentialPoints.address(script); + + var aliceNote = ConfidentialPoints.Note.of(pkh(alice), 1_000); + String issued = ok(ConfidentialPoints.issue(backend, script, retailer, List.of(aliceNote)), "issue"); + DevKit.waitForTx(backend, issued); + step("Retailer issued Alice a note. On-chain: owner + commitment (u = %s…). Amount: hidden.", + aliceNote.commitment().affineU().toString(16).substring(0, 12)); + + var toBob = ConfidentialPoints.Note.of(pkh(bob), 700); + var change = ConfidentialPoints.Note.of(pkh(alice), 300); + Utxo note = DevKit.utxosOf(backend, ledger, issued).getFirst(); + String sent = ok(ConfidentialPoints.transfer(backend, script, alice, note, toBob, change, + points.proveTransfer(aliceNote, toBob, change)), "transfer"); + DevKit.waitForTx(backend, sent); + step("Alice split her note for Bob. The proof shows in = out1 + out2 over 64-bit amounts; nobody else" + + " learns 1,000 / 700 / 300."); + + var bobChange = ConfidentialPoints.Note.of(pkh(bob), 580); + Utxo bobNote = DevKit.utxosOf(backend, ledger, sent).stream().filter(u -> u.getOutputIndex() == 0).findFirst().orElseThrow(); + String redeemed = ok(ConfidentialPoints.redeem(backend, script, bob, retailer.baseAddress(), bobNote, bobChange, + 120, points.proveRedeem(toBob, bobChange, 120)), "redeem"); + DevKit.waitForTx(backend, redeemed); + step("Bob paid a public price of 120 from a hidden balance and kept hidden change; the retailer" + + " received a receipt token only a valid redemption can mint. tx %s", redeemed); + } + + private static void creditGate(BackendService backend) throws Exception { + header("B. Committed credential — prove a predicate, reveal nothing else"); + var bureau = funded(); + var alice = funded(); + var credit = new CreditGate(); + byte[] bureauPolicy = HexUtil.decodeHexString(CreditGate.bureauPolicy(bureau).getPolicyId()); + var gate = credit.gate(bureauPolicy, 50_000, 650); + + var profile = CreditGate.Profile.of(85_000, 720, 1990, 356); + var commitment = profile.commitment(); + String issued = ok(CreditGate.issueRecord(backend, bureau, alice.baseAddress(), pkh(alice), commitment), "record"); + DevKit.waitForTx(backend, issued); + step("Bureau committed to Alice's income, credit score, birth year and country in ONE commitment," + + " and recorded the issuance on-chain (schema-bound, holder-bound)."); + + Utxo record = DevKit.utxosOf(backend, alice.baseAddress(), issued).stream() + .filter(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().startsWith(HexUtil.encodeHexString(bureauPolicy)))) + .findFirst().orElseThrow(); + String claimed = ok(CreditGate.claim(backend, gate, alice, commitment, record, + credit.prove(profile, 50_000, 650)), "claim"); + DevKit.waitForTx(backend, claimed); + step("Alice proved income ≥ 50,000 and score ≥ 650 and received the lender's badge. The lender" + + " never saw 85,000, 720, her birth year or country. tx %s", claimed); + } + + private static void solvency(BackendService backend) throws Exception { + header("C. Solvency — liabilities stay hidden, reserves are locked"); + var exchange = funded(5_000); + var solvency = new SolvencyAttestation(4); + long now = DevKit.chainTimeMillis(backend); + var period = new SolvencyAttestation.Period(now + 40_000, now + 100_000); + var vault = solvency.vault(pkh(exchange), period); + var book = List.of(SolvencyAttestation.Customer.of("alice", 500_000_000L), + SolvencyAttestation.Customer.of("bob", 1_200_000_000L), + SolvencyAttestation.Customer.of("carol", 300_000_000L), + SolvencyAttestation.Customer.of("dave", 0)); + long reserves = 2_000_000_000L; + String attested = ok(SolvencyAttestation.attest(backend, vault, exchange, reserves, + SolvencyAttestation.entries(book), solvency.prove(reserves, book), + DevKit.slotAt(backend, period.start())), "attest"); + DevKit.waitForTx(backend, attested); + step("Before the period starts, the exchange locked 2,000 ADA and proved its hidden liabilities are" + + " covered. On-chain: one commitment per customer, never a balance or the total."); + + while (DevKit.chainTimeMillis(backend) < period.start()) Thread.sleep(2_000); + step("The period %s – %s has begun: no attestation can be added or released until it ends.", + Instant.ofEpochMilli(period.start()), Instant.ofEpochMilli(period.end())); + var entries = SolvencyAttestation.liveEntries(backend, vault); + for (var c : book) { + step("%s checks the period's attestations from chain data: %s", c.id(), + SolvencyAttestation.customerCheck(entries, c) ? "listed once, balance correct" : "MISSING OR WRONG"); + } + step("Auditor opens the sum of all commitments: total liabilities %s (no single balance revealed)", + SolvencyAttestation.auditorCheck(entries, SolvencyAttestation.auditOpening(book)) ? "verified" : "FAILED"); + } + + // ------------------------------------------------------------------ + + private static Account funded() throws Exception { + return funded(200); + } + + private static Account funded(int ada) throws Exception { + var account = new Account(Networks.testnet()); + DevKit.topUp(account.baseAddress(), ada); + return account; + } + + private static byte[] pkh(Account account) { + return account.hdKeyPair().getPublicKey().getKeyHash(); + } + + private static String ok(Result result, String what) { + if (!result.isSuccessful()) throw new IllegalStateException(what + " failed: " + result.getResponse()); + return result.getValue(); + } + + private static void header(String title) { + System.out.println("\n=== " + title + " ==="); + } + + private static void step(String format, Object... args) { + System.out.println(" • " + String.format(format, args)); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/DevKit.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/DevKit.java new file mode 100644 index 0000000..868492a --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/DevKit.java @@ -0,0 +1,151 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.common; + +import com.bloxbean.cardano.client.api.TransactionEvaluator; +import com.bloxbean.cardano.client.api.model.EvaluationResult; +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.backend.api.DefaultProtocolParamsSupplier; +import com.bloxbean.cardano.client.backend.api.DefaultScriptSupplier; +import com.bloxbean.cardano.client.backend.api.DefaultUtxoSupplier; +import com.bloxbean.cardano.client.backend.blockfrost.service.BFBackendService; +import com.bloxbean.cardano.client.plutus.spec.ExUnits; +import org.julclang.clientlib.eval.JulcTransactionEvaluator; +import org.julclang.clientlib.eval.SlotConfig; + +import java.math.BigInteger; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +/** + * Yaci DevKit access for the demos. URLs default to a local DevKit and can be overridden with + * {@code ZEROJ_YACI_STORE_URL} and {@code ZEROJ_YACI_ADMIN_URL}. + * + *

Script costs are evaluated locally with Julc ({@link #evaluator}), because DevKit's + * {@code /evaluate} endpoint cannot initialise blst in its aarch64 container. The node still + * validates every submitted transaction. + */ +public final class DevKit { + + public static final String STORE_URL = env("ZEROJ_YACI_STORE_URL", "http://localhost:8080/api/v1/"); + public static final String ADMIN_URL = env("ZEROJ_YACI_ADMIN_URL", "http://localhost:10000"); + + private DevKit() {} + + public static BackendService backend() { + return new BFBackendService(STORE_URL, ""); + } + + public static boolean reachable() { + try { + var request = HttpRequest.newBuilder().uri(URI.create(STORE_URL + "blocks/latest")) + .timeout(Duration.ofSeconds(3)).GET().build(); + return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).statusCode() == 200; + } catch (Exception e) { + return false; + } + } + + public static void topUp(String address, int ada) throws Exception { + var request = HttpRequest.newBuilder() + .uri(URI.create(ADMIN_URL + "/local-cluster/api/addresses/topup")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString( + "{\"address\":\"" + address + "\",\"adaAmount\":" + ada + "}")) + .build(); + HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + Thread.sleep(3_000); + } + + /** + * A Julc evaluator with slot-to-POSIX conversion anchored at the latest block (one-second + * slots), padded by 25% so fee estimates do not under-shoot. + */ + public static TransactionEvaluator evaluator(BackendService backend) { + var latest = call(() -> backend.getBlockService().getLatestBlock()); + var slotConfig = new SlotConfig(latest.getSlot(), latest.getTime() * 1000, 1000); + var evaluator = new JulcTransactionEvaluator( + new DefaultUtxoSupplier(backend.getUtxoService()), + new DefaultProtocolParamsSupplier(backend.getEpochService()), + new DefaultScriptSupplier(backend.getScriptService()), + slotConfig); + return (tx, utxos) -> { + var result = evaluator.evaluateTx(tx, utxos); + if (result.isSuccessful() && result.getValue() != null) { + for (EvaluationResult eval : result.getValue()) { + ExUnits u = eval.getExUnits(); + eval.setExUnits(new ExUnits( + u.getMem().add(u.getMem().divide(BigInteger.valueOf(4)).max(BigInteger.valueOf(50_000))), + u.getSteps().add(u.getSteps().divide(BigInteger.valueOf(4))))); + } + } + return result; + }; + } + + /** The slot whose start time is the latest at or before {@code posixMillis}. */ + public static long slotAt(BackendService backend, long posixMillis) { + var latest = call(() -> backend.getBlockService().getLatestBlock()); + return latest.getSlot() + (Math.floorDiv(posixMillis, 1000L) - latest.getTime()); + } + + /** The chain's current POSIX time in milliseconds, from the latest block. */ + public static long chainTimeMillis(BackendService backend) { + return call(() -> backend.getBlockService().getLatestBlock()).getTime() * 1000; + } + + public static void waitForTx(BackendService backend, String txHash) throws InterruptedException { + for (int i = 0; i < 40; i++) { + Thread.sleep(1_500); + try { + var r = backend.getTransactionService().getTransaction(txHash); + if (r.isSuccessful() && r.getValue() != null) return; + } catch (Exception ignored) { + // not indexed yet + } + } + throw new IllegalStateException("transaction not confirmed: " + txHash); + } + + /** Every UTxO at {@code address} created by {@code txHash}. */ + public static List utxosOf(BackendService backend, String address, String txHash) throws Exception { + List out = new ArrayList<>(); + for (int page = 1; ; page++) { + var result = backend.getUtxoService().getUtxos(address, 100, page); + if (!result.isSuccessful() || result.getValue() == null || result.getValue().isEmpty()) break; + for (Utxo u : result.getValue()) { + if (u.getTxHash().equals(txHash)) out.add(u); + } + if (result.getValue().size() < 100) break; + } + return out; + } + + private interface Call { + Result get() throws Exception; + } + + private static T call(Call call) { + try { + var result = call.get(); + if (!result.isSuccessful() || result.getValue() == null) { + throw new IllegalStateException(result.getResponse()); + } + return result.getValue(); + } catch (IllegalStateException e) { + throw e; + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static String env(String name, String fallback) { + String v = System.getenv(name); + return v == null || v.isBlank() ? fallback : v; + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Fields.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Fields.java new file mode 100644 index 0000000..ff16a3b --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Fields.java @@ -0,0 +1,44 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.common; + +import java.math.BigInteger; +import java.security.SecureRandom; + +/** BLS12-381 scalar-field constants and fixed-width encodings shared by the demos. */ +public final class Fields { + + /** The BLS12-381 scalar field order {@code p}, which is also Jubjub's base field. */ + public static final BigInteger FR = new BigInteger( + "52435875175126190479447740508185965837690552500527637822603658699938581184513"); + + private Fields() {} + + public static BigInteger randomFr(SecureRandom random) { + byte[] bytes = new byte[64]; + random.nextBytes(bytes); + return new BigInteger(1, bytes).mod(FR); + } + + /** {@code I2OSP(value, width)}: big-endian, left-padded; throws if it does not fit. */ + public static byte[] i2osp(BigInteger value, int width) { + if (value.signum() < 0 || value.bitLength() > width * 8) { + throw new IllegalArgumentException("value does not fit in " + width + " bytes"); + } + byte[] raw = value.toByteArray(); + byte[] out = new byte[width]; + int copy = Math.min(raw.length, width); + System.arraycopy(raw, raw.length - copy, out, width - copy, copy); + return out; + } + + public static byte[] concat(byte[]... parts) { + int length = 0; + for (byte[] p : parts) length += p.length; + byte[] out = new byte[length]; + int offset = 0; + for (byte[] p : parts) { + System.arraycopy(p, 0, out, offset, p.length); + offset += p.length; + } + return out; + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/KeyedCircuit.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/KeyedCircuit.java new file mode 100644 index 0000000..e84ef3a --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/KeyedCircuit.java @@ -0,0 +1,144 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.common; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zeroj.api.CircuitId; +import org.zeroj.api.CurveId; +import org.zeroj.api.ProofSystemId; +import org.zeroj.api.R1CSConstraint; +import org.zeroj.api.VerificationMaterial; +import org.zeroj.circuit.CircuitBuilder; +import org.zeroj.circuit.r1cs.R1CSConstraintSystem; +import org.zeroj.codec.SnarkjsJsonCodec; +import org.zeroj.crypto.groth16.Groth16Keys; +import org.zeroj.crypto.groth16.Groth16Pipeline; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; +import org.zeroj.crypto.setup.Groth16SetupBLS381; +import org.zeroj.crypto.setup.Groth16SetupCache; +import org.zeroj.crypto.snarkjs.SnarkjsGroth16Json; +import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; +import org.zeroj.onchain.julc.groth16.codec.SnarkjsToCardano; +import org.zeroj.verifier.groth16.bls12381.Groth16BLS12381PureJavaVerifier; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.TreeMap; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.util.List; +import java.util.Map; + +/** + * One compiled circuit with its Groth16 keys: proves witnesses, verifies proofs from their + * snarkjs-format JSON, and exports the verification key in the compressed form the on-chain + * verifier takes. + * + *

Keys come from a single-party development setup (requires + * {@code -Dzeroj.allowInsecureTrustedSetup=true}). They are cached under {@code ./data}, keyed by + * the circuit fingerprint ({@code c-w-p}) and a SHA-256 of its constraints, so + * a changed circuit never reuses stale keys, even one with the same shape. Production needs keys + * from an MPC ceremony. + */ +public final class KeyedCircuit { + + private static final Logger log = LoggerFactory.getLogger(KeyedCircuit.class); + private static final Path CACHE_DIR = Path.of("./data"); + + private final String name; + private final CircuitBuilder circuit; + private final R1CSConstraintSystem r1cs; + private final Groth16SetupBLS381.SetupResult setup; + private final Groth16Keys keys; + private final String verificationKeyJson; + + private KeyedCircuit(String name, CircuitBuilder circuit, R1CSConstraintSystem r1cs, + Groth16SetupBLS381.SetupResult setup) { + this.name = name; + this.circuit = circuit; + this.r1cs = r1cs; + this.setup = setup; + this.keys = Groth16Keys.of(setup); + this.verificationKeyJson = SnarkjsGroth16Json.verificationKeyJson(setup); + } + + public static KeyedCircuit compile(String name, CircuitBuilder circuit) { + R1CSConstraintSystem r1cs = circuit.compileR1CS(CurveId.BLS12_381); + String fingerprint = Groth16Pipeline.fingerprint( + r1cs.numConstraints(), r1cs.numWires(), r1cs.numPublicInputs()); + log.info("Circuit {}: {} constraints, {} public inputs ({})", + name, r1cs.numConstraints(), r1cs.numPublicInputs(), fingerprint); + Path cache = CACHE_DIR.resolve("setup-" + name + "-" + fingerprint + "-" + r1csDigest(r1cs.constraints()) + ".bin"); + Groth16SetupBLS381.SetupResult setup = null; + try { + if (Files.exists(cache)) setup = Groth16SetupCache.loadBls12381Setup(cache); + } catch (Exception e) { + log.warn("Key cache {} unreadable ({}); regenerating", cache, e.getMessage()); + } + if (setup == null) { + log.info("Running single-party DEV setup for {} (not for production)...", name); + setup = Groth16SetupBLS381.setup(r1cs.constraints(), r1cs.numWires(), r1cs.numPublicInputs(), + Fields.randomFr(new SecureRandom())); + try { + Files.createDirectories(CACHE_DIR); + Groth16SetupCache.saveBls12381Setup(setup, cache); + } catch (Exception e) { + log.warn("Could not cache keys for {}: {}", name, e.getMessage()); + } + } + return new KeyedCircuit(name, circuit, r1cs, setup); + } + + /** Computes the witness for {@code inputs} (throws if the relation does not hold) and proves it. */ + public Groth16ProofBLS381 prove(Map> inputs) { + BigInteger[] witness = circuit.calculateWitness(inputs, CurveId.BLS12_381); + return keys.prove(witness, r1cs.constraints()); + } + + /** Verifies a proof against {@code publicInputs} with ZeroJ's pure-Java verifier, from JSON. */ + public boolean verify(Groth16ProofBLS381 proof, List publicInputs) { + var circuitId = new CircuitId(name); + String proofJson = SnarkjsGroth16Json.proofJson(proof); + String publicJson = SnarkjsGroth16Json.publicJson(publicInputs.toArray(new BigInteger[0])); + var envelope = SnarkjsJsonCodec.toEnvelopeFromJson(proofJson, verificationKeyJson, publicJson, circuitId); + var material = VerificationMaterial.of(verificationKeyJson.getBytes(StandardCharsets.UTF_8), + ProofSystemId.GROTH16, CurveId.BLS12_381, circuitId); + return new Groth16BLS12381PureJavaVerifier().verify(envelope, material).proofValid(); + } + + /** The verification key compressed for {@code Groth16BLS12381Lib} on-chain. */ + public SnarkjsToCardano.VkCompressed compressedVk() { + return ProverToCardano.compressVk(setup); + } + + public CircuitBuilder circuit() { return circuit; } + + public int numConstraints() { return r1cs.numConstraints(); } + + public int numPublicInputs() { return r1cs.numPublicInputs(); } + + /** SHA-256 over every constraint's A, B and C terms, in order, wires sorted; first 8 bytes, hex. */ + static String r1csDigest(List constraints) { + try { + MessageDigest sha = MessageDigest.getInstance("SHA-256"); + for (R1CSConstraint row : constraints) { + for (Map terms : List.of(row.a(), row.b(), row.c())) { + sha.update(ByteBuffer.allocate(4).putInt(terms.size()).array()); + for (var term : new TreeMap<>(terms).entrySet()) { + sha.update(ByteBuffer.allocate(4).putInt(term.getKey()).array()); + byte[] coefficient = term.getValue().toByteArray(); + sha.update(ByteBuffer.allocate(4).putInt(coefficient.length).array()); + sha.update(coefficient); + } + } + } + return HexFormat.of().formatHex(sha.digest(), 0, 8); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Plutus.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Plutus.java new file mode 100644 index 0000000..5f24703 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/Plutus.java @@ -0,0 +1,42 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.common; + +import com.bloxbean.cardano.client.exception.CborSerializationException; +import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ConstrPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ListPlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusScript; +import com.bloxbean.cardano.client.util.HexUtil; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; +import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; + +import java.util.List; + +/** Off-chain Plutus data encodings shared by the demos. */ +public final class Plutus { + + private Plutus() {} + + /** The script's hash, hex: its policy id and its payment credential. */ + public static String policyId(PlutusScript script) { + try { + return HexUtil.encodeHexString(script.getScriptHash()); + } catch (CborSerializationException e) { + throw new IllegalStateException(e); + } + } + + /** The verification key's IC points as a list of compressed G1 byte strings. */ + public static ListPlutusData icData(List ic) { + PlutusData[] values = new PlutusData[ic.size()]; + for (int i = 0; i < ic.size(); i++) values[i] = new BytesPlutusData(ic.get(i)); + return ListPlutusData.of(values); + } + + /** {@code Constr 0 [B piA, B piB, B piC]}: a Groth16 proof as a redeemer. */ + public static ConstrPlutusData proofRedeemer(Groth16ProofBLS381 proof) { + var p = ProverToCardano.compressProof(proof); + return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()))).build(); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGate.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGate.java new file mode 100644 index 0000000..93508c4 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGate.java @@ -0,0 +1,161 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.credential; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.api.model.Amount; +import com.bloxbean.cardano.client.api.model.Result; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.crypto.Blake2bUtil; +import com.bloxbean.cardano.client.crypto.VerificationKey; +import com.bloxbean.cardano.client.function.helper.SignerProviders; +import com.bloxbean.cardano.client.plutus.spec.BigIntPlutusData; +import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ConstrPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ListPlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusScript; +import com.bloxbean.cardano.client.quicktx.QuickTxBuilder; +import com.bloxbean.cardano.client.quicktx.ScriptTx; +import com.bloxbean.cardano.client.quicktx.Tx; +import com.bloxbean.cardano.client.transaction.spec.Asset; +import com.bloxbean.cardano.client.transaction.spec.script.ScriptPubkey; +import com.bloxbean.cardano.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.KeyedCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; +import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.circuit.CreditProfileProof; +import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.circuit.CreditProfileProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.onchain.CreditGatePolicy; +import org.julclang.clientlib.JulcScriptLoader; +import org.zeroj.circuit.lib.jubjub.PedersenCommitment; +import org.zeroj.circuit.lib.jubjub.PedersenVectorCommitment; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; +import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; + +import java.math.BigInteger; +import java.security.SecureRandom; +import java.util.List; + +/** + * Committed credentials (ADR-0006 demo B): the bureau issues one vector commitment to a holder's + * credit profile; the holder later proves predicates over it to a lender's gate. + */ +public final class CreditGate { + + private static final SecureRandom RANDOM = new SecureRandom(); + + /** A credit profile and the blinding of its commitment: the holder's opening. */ + public record Profile(long income, int creditScore, int birthYear, int country, BigInteger blinding) { + public static Profile of(long income, int creditScore, int birthYear, int country) { + return new Profile(income, creditScore, birthYear, country, PedersenCommitment.randomBlinding(RANDOM)); + } + + public List values() { + return List.of(BigInteger.valueOf(income), BigInteger.valueOf(creditScore), + BigInteger.valueOf(birthYear), BigInteger.valueOf(country)); + } + + public PedersenVectorCommitment commitment() { + return PedersenVectorCommitment.commit(CreditProfileProof.SCHEMA, values(), blinding); + } + } + + private final KeyedCircuit circuit; + + public CreditGate() { + circuit = KeyedCircuit.compile("credit-profile-check", CreditProfileProofCircuit.build()); + } + + public KeyedCircuit circuit() { return circuit; } + + public static CreditProfileProofCircuit.Inputs inputs(Profile p, long minIncome, int minScore) { + var c = p.commitment().point().normalized(); + return CreditProfileProofCircuit.inputs() + .schemaDigest(CreditProfileProof.SCHEMA.digest()) + .u(c.affineU()).v(c.affineV()) + .minIncome(minIncome).minScore(minScore) + .income(p.income()).creditScore(p.creditScore()) + .birthYear(p.birthYear()).country(p.country()) + .blinding(p.blinding()); + } + + /** Proves the profile meets the thresholds; throws if it does not. */ + public Groth16ProofBLS381 prove(Profile p, long minIncome, int minScore) { + return circuit.prove(inputs(p, minIncome, minScore).toWitnessMap()); + } + + /** The lender's gate for one bureau and one pair of thresholds. */ + public PlutusScript gate(byte[] issuerPolicyId, long minIncome, int minScore) { + var vk = circuit.compressedVk(); + return JulcScriptLoader.load(CreditGatePolicy.class, + new BytesPlutusData(Fields.i2osp(CreditProfileProof.SCHEMA.digest(), 32)), + new BytesPlutusData(issuerPolicyId), + BigIntPlutusData.of(minIncome), + BigIntPlutusData.of(minScore), + new BytesPlutusData(vk.alpha()), new BytesPlutusData(vk.beta()), + new BytesPlutusData(vk.gamma()), new BytesPlutusData(vk.delta()), Plutus.icData(vk.ic())); + } + + /** The bureau's issuing policy: a native script that only its key can satisfy. */ + public static ScriptPubkey bureauPolicy(Account bureau) throws Exception { + return ScriptPubkey.create(VerificationKey.create(bureau.publicKeyBytes())); + } + + /** {@code blake2b_256(I2OSP32(u) ‖ I2OSP32(v) ‖ I2OSP32(σ) ‖ holder)}. */ + public static byte[] recordTokenName(PedersenVectorCommitment c, byte[] holder) { + var p = c.point().normalized(); + return Blake2bUtil.blake2bHash256(Fields.concat(Fields.i2osp(p.affineU(), 32), Fields.i2osp(p.affineV(), 32), + Fields.i2osp(c.schema().digest(), 32), holder)); + } + + /** {@code Record(u, v, σ, holder)}. */ + public static ConstrPlutusData recordDatum(PedersenVectorCommitment c, byte[] holder) { + var p = c.point().normalized(); + return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + BigIntPlutusData.of(p.affineU()), BigIntPlutusData.of(p.affineV()), + BigIntPlutusData.of(c.schema().digest()), new BytesPlutusData(holder))).build(); + } + + /** The bureau records the issuance on-chain, at the holder's address. */ + public static Result issueRecord(BackendService backend, Account bureau, String holderAddress, + byte[] holder, PedersenVectorCommitment c) throws Exception { + ScriptPubkey policy = bureauPolicy(bureau); + byte[] name = recordTokenName(c, holder); + String unit = policy.getPolicyId() + HexUtil.encodeHexString(name); + var tx = new Tx() + .mintAssets(policy, new Asset("0x" + HexUtil.encodeHexString(name), BigInteger.ONE)) + .payToContract(holderAddress, List.of(Amount.ada(2), new Amount(unit, BigInteger.ONE)), + recordDatum(c, holder)) + .from(bureau.baseAddress()); + return new QuickTxBuilder(backend).compose(tx).withSigner(SignerProviders.signerFrom(bureau)).complete(); + } + + /** The holder claims a badge from the gate, referencing the issuance record. */ + public static Result claim(BackendService backend, PlutusScript gate, Account holder, + PedersenVectorCommitment c, Utxo record, Groth16ProofBLS381 proof) { + byte[] holderPkh = holder.hdKeyPair().getPublicKey().getKeyHash(); + String policyId = Plutus.policyId(gate); + var p = c.point().normalized(); + var pc = ProverToCardano.compressProof(proof); + var redeemer = ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(holderPkh), + BigIntPlutusData.of(p.affineU()), BigIntPlutusData.of(p.affineV()), + new BytesPlutusData(pc.piA()), new BytesPlutusData(pc.piB()), new BytesPlutusData(pc.piC()))).build(); + var tx = new ScriptTx() + .mintAsset(gate, List.of(new Asset("0x" + HexUtil.encodeHexString(holderPkh), BigInteger.ONE)), redeemer) + .payToAddress(holder.baseAddress(), + List.of(Amount.ada(2), new Amount(policyId + HexUtil.encodeHexString(holderPkh), BigInteger.ONE))); + if (record != null) tx = tx.readFrom(record); + try { + return new QuickTxBuilder(backend).compose(tx) + .withTxEvaluator(DevKit.evaluator(backend)) + .withSigner(SignerProviders.signerFrom(holder)) + .withRequiredSigners(holderPkh) + .feePayer(holder.baseAddress()) + .collateralPayer(holder.baseAddress()) + .complete(); + } catch (RuntimeException e) { + return Result.error(e.getMessage()); + } + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/circuit/CreditProfileProof.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/circuit/CreditProfileProof.java new file mode 100644 index 0000000..9f3e508 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/circuit/CreditProfileProof.java @@ -0,0 +1,54 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.credential.circuit; + +import org.zeroj.circuit.annotation.Prove; +import org.zeroj.circuit.annotation.Public; +import org.zeroj.circuit.annotation.Secret; +import org.zeroj.circuit.annotation.UInt; +import org.zeroj.circuit.annotation.ZKCircuit; +import org.zeroj.circuit.annotation.ZkContext; +import org.zeroj.circuit.annotation.ZkField; +import org.zeroj.circuit.annotation.ZkUInt; +import org.zeroj.circuit.lib.jubjub.PedersenVectorSchema; +import org.zeroj.circuit.lib.jubjub.PedersenVectorSchema.Entry; +import org.zeroj.circuit.lib.zk.ZkPedersenVector; + +import java.util.List; + +/** + * A credit check against a committed profile (ADR-0006 demo B). + * + *

The bureau committed to four attributes in one {@code pedersen-jubjub-vector-v1} commitment + * under {@link #SCHEMA}. The holder proves {@code income ≥ minIncome} and + * {@code creditScore ≥ minScore} and reveals nothing else: not the income, not the score, and + * nothing about {@code birthYear} or {@code country}, which are committed but not used. + * + *

Public, in order: {@code σ, u, v, minIncome, minScore}. {@code σ} is the schema digest, + * constrained to {@link #SCHEMA} by {@code bindSchema}, so a commitment issued under any other + * schema cannot be presented as a credit profile. + */ +@ZKCircuit(name = "credit-profile-check", version = 1) +public class CreditProfileProof { + + public static final PedersenVectorSchema SCHEMA = PedersenVectorSchema.of("zeroj.demo.credit-profile", 1, + List.of(new Entry("income", 64), new Entry("credit_score", 16), + new Entry("birth_year", 16), new Entry("country", 16))); + + @Prove + void prove(ZkContext zk, + @Public ZkField schemaDigest, + @Public ZkField u, + @Public ZkField v, + @Public @UInt(bits = 64) ZkUInt minIncome, + @Public @UInt(bits = 16) ZkUInt minScore, + @Secret @UInt(bits = 64) ZkUInt income, + @Secret @UInt(bits = 16) ZkUInt creditScore, + @Secret @UInt(bits = 16) ZkUInt birthYear, + @Secret @UInt(bits = 16) ZkUInt country, + @Secret @UInt(bits = 252) ZkUInt blinding) { + var binding = ZkPedersenVector.bindSchema(zk, SCHEMA, schemaDigest); + ZkPedersenVector.commit(zk, binding, List.of(income, creditScore, birthYear, country), blinding) + .assertAffineEquals(zk, u, v); + income.gte(minIncome).assertTrue(); + creditScore.gte(minScore).assertTrue(); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/onchain/CreditGatePolicy.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/onchain/CreditGatePolicy.java new file mode 100644 index 0000000..484aa97 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/onchain/CreditGatePolicy.java @@ -0,0 +1,168 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.credential.onchain; + +import org.julclang.core.PlutusData; +import org.julclang.ledger.Credential; +import org.julclang.ledger.OutputDatum; +import org.julclang.ledger.PubKeyHash; +import org.julclang.ledger.ScriptContext; +import org.julclang.ledger.ScriptInfo; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxInfo; +import org.julclang.ledger.TxOut; +import org.julclang.ledger.Value; +import org.julclang.stdlib.Builtins; +import org.julclang.stdlib.annotation.Entrypoint; +import org.julclang.stdlib.annotation.MintingValidator; +import org.julclang.stdlib.annotation.Param; +import org.julclang.stdlib.lib.ValuesLib; +import org.zeroj.onchain.julc.groth16.lib.Groth16BLS12381Lib; + +import java.math.BigInteger; + +/** + * A lender's credit gate (ADR-0006 demo B): mints an access badge to a holder whose committed + * credit profile meets the lender's thresholds. + * + *

Redeemer {@code Claim(holder, u, v, proof)}. The public inputs are + * {@code [σ, u, v, minIncome, minScore]}: {@code σ} and the thresholds are parameters; {@code (u, v)} + * must match an issuance record the transaction references, a token under the bureau's + * policy named {@code blake2b_256(I2OSP32(u) ‖ I2OSP32(v) ‖ I2OSP32(σ) ‖ holder)} at an output + * whose inline datum is {@code Record(u, v, σ, holder)}. No record, no badge (fail closed); and + * because the name commits to the datum, a record cannot be relabelled to another commitment, + * schema or holder. + * + *

The holder must sign; the gate's mint entry is exactly one badge named after the holder, and + * it must be paid to an output with the holder's payment credential. Consumers of badges must + * also check that the badge's name signed their transaction. + */ +@MintingValidator +public class CreditGatePolicy { + + @Param static byte[] schemaDigest; // σ, I2OSP32 + @Param static byte[] issuerPolicyId; + @Param static BigInteger minIncome; + @Param static BigInteger minScore; + @Param static byte[] vkAlpha; + @Param static byte[] vkBeta; + @Param static byte[] vkGamma; + @Param static byte[] vkDelta; + @Param static PlutusData vkIc; + + record Claim(byte[] holder, BigInteger u, BigInteger v, byte[] piA, byte[] piB, byte[] piC) {} + + @Entrypoint + public static boolean validate(Claim claim, ScriptContext ctx) { + TxInfo txInfo = ctx.txInfo(); + ScriptInfo.MintingScript mintInfo = (ScriptInfo.MintingScript) ctx.scriptInfo(); + byte[] policy = PlutusData.cast(mintInfo.policyId(), byte[].class); + BigInteger sigma = Builtins.byteStringToInteger(true, schemaDigest); + byte[] holder = claim.holder(); + if (Builtins.lengthOfByteString(schemaDigest) != 32 + || Builtins.lengthOfByteString(issuerPolicyId) != 28 + || Builtins.lengthOfByteString(holder) != 28 + || !canonicalField(sigma) || !canonicalField(claim.u()) || !canonicalField(claim.v()) + || !signedBy(txInfo, holder)) { + return false; + } + + // Exactly one badge, named after the holder, paid to the holder. + if (policyEntryCount(txInfo.mint(), policy) != 1 + || ValuesLib.assetOf(txInfo.mint(), policy, holder).compareTo(BigInteger.ONE) != 0) { + return false; + } + Credential holderCredential = new Credential.PubKeyCredential(PlutusData.cast(holder, PubKeyHash.class)); + boolean paidToHolder = false; + for (TxOut output : txInfo.outputs()) { + paidToHolder = paidToHolder + || (Builtins.equalsData(output.address().credential(), holderCredential) + && ValuesLib.assetOf(output.value(), policy, holder).compareTo(BigInteger.ONE) == 0); + } + if (!paidToHolder) return false; + + // The issuance record, by its exact token and its exact datum. + byte[] recordToken = Builtins.blake2b_256(Builtins.appendByteString( + Builtins.integerToByteString(true, 32, claim.u()), + Builtins.appendByteString(Builtins.integerToByteString(true, 32, claim.v()), + Builtins.appendByteString(schemaDigest, holder)))); + PlutusData expectedRecord = Builtins.constrData(0, + Builtins.mkCons(Builtins.iData(claim.u()), + Builtins.mkCons(Builtins.iData(claim.v()), + Builtins.mkCons(Builtins.iData(sigma), + Builtins.mkCons(Builtins.bData(holder), + Builtins.mkNilData()))))); + boolean recorded = false; + for (TxInInfo reference : txInfo.referenceInputs()) { + TxOut record = reference.resolved(); + recorded = recorded + || (ValuesLib.assetOf(record.value(), issuerPolicyId, recordToken).compareTo(BigInteger.ZERO) > 0 + && Builtins.equalsData(inlineDatum(record), expectedRecord)); + } + if (!recorded) return false; + + PlutusData publicInputs = Builtins.listData( + Builtins.mkCons(Builtins.iData(sigma), + Builtins.mkCons(Builtins.iData(claim.u()), + Builtins.mkCons(Builtins.iData(claim.v()), + Builtins.mkCons(Builtins.iData(minIncome), + Builtins.mkCons(Builtins.iData(minScore), + Builtins.mkNilData())))))); + return Groth16BLS12381Lib.verify(publicInputs, claim.piA(), claim.piB(), claim.piC(), + vkAlpha, vkBeta, vkGamma, vkDelta, vkIc); + } + + private static boolean signedBy(TxInfo txInfo, byte[] pkh) { + boolean found = false; + for (var signer : txInfo.signatories()) { + found = found || Builtins.equalsByteString(signer.hash(), pkh); + } + return found; + } + + private static int policyEntryCount(Value value, byte[] policy) { + var outerPairs = Builtins.unMapData(value); + PlutusData target = Builtins.bData(policy); + int count = 0; + PlutusData current = outerPairs; + while (!Builtins.nullList(current)) { + var outerPair = Builtins.headList(current); + if (Builtins.equalsData(Builtins.fstPair(outerPair), target)) { + count = innerEntryCount((PlutusData.MapData) Builtins.sndPair(outerPair)); + current = Builtins.mkNilPairData(); + } else { + current = Builtins.tailList(current); + } + } + return count; + } + + private static int innerEntryCount(PlutusData.MapData innerPairs) { + int count = 0; + PlutusData current = Builtins.unMapData(innerPairs); + while (!Builtins.nullList(current)) { + count = count + 1; + current = Builtins.tailList(current); + } + return count; + } + + private static PlutusData inlineDatum(TxOut output) { + return switch (output.datum()) { + case OutputDatum.OutputDatumInline inline -> inline.datum(); + case OutputDatum.OutputDatumHash ignored -> Builtins.iData(BigInteger.ZERO); + case OutputDatum.NoOutputDatum ignored -> Builtins.iData(BigInteger.ZERO); + }; + } + + private static boolean canonicalField(BigInteger value) { + return value.compareTo(BigInteger.ZERO) >= 0 && value.compareTo(fr()) < 0; + } + + private static BigInteger fr() { + BigInteger base = BigInteger.valueOf(1000000000000000000L); + return BigInteger.valueOf(52435L).multiply(base) + .add(BigInteger.valueOf(875175126190479447L)).multiply(base) + .add(BigInteger.valueOf(740508185965837690L)).multiply(base) + .add(BigInteger.valueOf(552500527637822603L)).multiply(base) + .add(BigInteger.valueOf(658699938581184513L)); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/ConfidentialPoints.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/ConfidentialPoints.java new file mode 100644 index 0000000..ee03c62 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/ConfidentialPoints.java @@ -0,0 +1,245 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.points; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.address.AddressProvider; +import com.bloxbean.cardano.client.api.model.Amount; +import com.bloxbean.cardano.client.api.model.Result; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.common.model.Networks; +import com.bloxbean.cardano.client.crypto.Blake2bUtil; +import com.bloxbean.cardano.client.function.helper.SignerProviders; +import com.bloxbean.cardano.client.plutus.spec.BigIntPlutusData; +import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ConstrPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ListPlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusScript; +import com.bloxbean.cardano.client.quicktx.QuickTxBuilder; +import com.bloxbean.cardano.client.quicktx.ScriptTx; +import com.bloxbean.cardano.client.transaction.spec.Asset; +import com.bloxbean.cardano.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.KeyedCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; +import com.bloxbean.cardano.zeroj.usecases.pedersen.points.circuit.PointsRedeemProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.points.circuit.PointsTransferProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.points.onchain.PointsLedger; +import org.julclang.clientlib.JulcScriptLoader; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.PedersenCommitment; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; +import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; + +/** + * Confidential loyalty points (ADR-0006 demo A): the wallet side and the transactions. + * + *

A {@link Note}'s amount and blinding are its opening; only the owner (and whoever + * created the note) knows it. On-chain there is only the commitment. + */ +public final class ConfidentialPoints { + + /** The note token's name under the points policy. */ + public static final byte[] NOTE_TOKEN = "PTS".getBytes(StandardCharsets.UTF_8); + private static final SecureRandom RANDOM = new SecureRandom(); + + /** A note as its owner sees it: owner key hash, hidden amount, blinding and commitment. */ + public record Note(byte[] owner, long amount, BigInteger blinding, JubjubPoint commitment) { + public static Note of(byte[] owner, long amount) { + BigInteger r = PedersenCommitment.randomBlinding(RANDOM); + return new Note(owner, amount, r, PedersenCommitment.commit(BigInteger.valueOf(amount), r).normalized()); + } + } + + private final KeyedCircuit transfer; + private final KeyedCircuit redeem; + + public ConfidentialPoints() { + transfer = KeyedCircuit.compile("points-transfer", PointsTransferProofCircuit.build()); + redeem = KeyedCircuit.compile("points-redeem", PointsRedeemProofCircuit.build()); + } + + public KeyedCircuit transferCircuit() { return transfer; } + + public KeyedCircuit redeemCircuit() { return redeem; } + + // ------------------------------------------------------------------ + // Proofs + // ------------------------------------------------------------------ + + public static PointsTransferProofCircuit.Inputs transferInputs(Note in, Note out1, Note out2) { + return PointsTransferProofCircuit.inputs() + .inU(in.commitment().affineU()).inV(in.commitment().affineV()) + .out1U(out1.commitment().affineU()).out1V(out1.commitment().affineV()) + .out2U(out2.commitment().affineU()).out2V(out2.commitment().affineV()) + .inAmount(in.amount()).inBlinding(in.blinding()) + .out1Amount(out1.amount()).out1Blinding(out1.blinding()) + .out2Amount(out2.amount()).out2Blinding(out2.blinding()); + } + + public static PointsRedeemProofCircuit.Inputs redeemInputs(Note in, Note change, long price) { + return PointsRedeemProofCircuit.inputs() + .inU(in.commitment().affineU()).inV(in.commitment().affineV()) + .changeU(change.commitment().affineU()).changeV(change.commitment().affineV()) + .price(price) + .inAmount(in.amount()).inBlinding(in.blinding()) + .changeAmount(change.amount()).changeBlinding(change.blinding()); + } + + /** Proves {@code in = out1 + out2}; throws if the amounts do not balance. */ + public Groth16ProofBLS381 proveTransfer(Note in, Note out1, Note out2) { + return transfer.prove(transferInputs(in, out1, out2).toWitnessMap()); + } + + /** Proves {@code in = change + price}; throws if the amounts do not balance. */ + public Groth16ProofBLS381 proveRedeem(Note in, Note change, long price) { + return redeem.prove(redeemInputs(in, change, price).toWitnessMap()); + } + + // ------------------------------------------------------------------ + // Script and encodings + // ------------------------------------------------------------------ + + /** The points ledger for one issuer: policy id and note address share its hash. */ + public PlutusScript script(byte[] issuerPkh) { + var t = transfer.compressedVk(); + var r = redeem.compressedVk(); + return JulcScriptLoader.load(PointsLedger.class, + new BytesPlutusData(issuerPkh), + new BytesPlutusData(NOTE_TOKEN), + new BytesPlutusData(t.alpha()), new BytesPlutusData(t.beta()), + new BytesPlutusData(t.gamma()), new BytesPlutusData(t.delta()), Plutus.icData(t.ic()), + new BytesPlutusData(r.alpha()), new BytesPlutusData(r.beta()), + new BytesPlutusData(r.gamma()), new BytesPlutusData(r.delta()), Plutus.icData(r.ic())); + } + + /** {@code Note(owner, u, v)}. */ + public static ConstrPlutusData noteDatum(Note n) { + return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(n.owner()), + BigIntPlutusData.of(n.commitment().affineU()), + BigIntPlutusData.of(n.commitment().affineV()))).build(); + } + + /** {@code Receipt(owner, price)}. */ + public static ConstrPlutusData receiptDatum(byte[] owner, long price) { + return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(owner), BigIntPlutusData.of(price))).build(); + } + + /** The receipt token's name: {@code blake2b_256(txId ‖ I2OSP2(index))} of the redeemed note. */ + public static byte[] receiptName(Utxo note) { + return Blake2bUtil.blake2bHash256(Fields.concat(HexUtil.decodeHexString(note.getTxHash()), + Fields.i2osp(BigInteger.valueOf(note.getOutputIndex()), 2))); + } + + // ------------------------------------------------------------------ + // Transactions + // ------------------------------------------------------------------ + + /** The issuer creates new notes. */ + public static Result issue(BackendService backend, PlutusScript script, Account issuer, + List notes) { + String policyId = Plutus.policyId(script); + String address = address(script); + var tx = new ScriptTx() + .mintAsset(script, List.of(new Asset("0x" + HexUtil.encodeHexString(NOTE_TOKEN), + BigInteger.valueOf(notes.size()))), action(0)); + for (Note n : notes) { + tx = tx.payToContract(address, noteAmounts(policyId), noteDatum(n)); + } + return new QuickTxBuilder(backend).compose(tx) + .withTxEvaluator(DevKit.evaluator(backend)) + .withSigner(SignerProviders.signerFrom(issuer)) + .withRequiredSigners(issuer.hdKeyPair().getPublicKey().getKeyHash()) + .feePayer(issuer.baseAddress()) + .collateralPayer(issuer.baseAddress()) + .complete(); + } + + /** The owner splits {@code noteUtxo} into two notes, with a proof that the amounts balance. */ + public static Result transfer(BackendService backend, PlutusScript script, Account owner, + Utxo noteUtxo, Note out1, Note out2, Groth16ProofBLS381 proof) { + String policyId = Plutus.policyId(script); + String address = address(script); + var p = ProverToCardano.compressProof(proof); + var redeemer = ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()))).build(); + var tx = new ScriptTx() + .collectFrom(noteUtxo, redeemer) + .mintAsset(script, List.of(new Asset("0x" + HexUtil.encodeHexString(NOTE_TOKEN), BigInteger.ONE)), + action(1)) + .payToContract(address, noteAmounts(policyId), noteDatum(out1)) + .payToContract(address, noteAmounts(policyId), noteDatum(out2)) + .attachSpendingValidator(script); + return submit(backend, tx, owner); + } + + /** + * The owner spends {@code price} points at the issuer and keeps {@code change} as a new note + * (which may belong to someone else). A receipt token goes to the issuer with datum + * {@code Receipt(owner, price)}, naming the spender. + */ + public static Result redeem(BackendService backend, PlutusScript script, Account owner, + String issuerAddress, Utxo noteUtxo, Note change, long price, + Groth16ProofBLS381 proof) { + String policyId = Plutus.policyId(script); + String address = address(script); + byte[] receipt = receiptName(noteUtxo); + var p = ProverToCardano.compressProof(proof); + var redeemer = ConstrPlutusData.builder().alternative(1).data(ListPlutusData.of( + BigIntPlutusData.of(price), + new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()))).build(); + var tx = new ScriptTx() + .collectFrom(noteUtxo, redeemer) + .mintAsset(script, List.of(new Asset("0x" + HexUtil.encodeHexString(receipt), BigInteger.ONE)), + action(2)) + .payToContract(address, noteAmounts(policyId), noteDatum(change)) + .payToContract(issuerAddress, + List.of(Amount.ada(2), new Amount(policyId + HexUtil.encodeHexString(receipt), BigInteger.ONE)), + receiptDatum(owner.hdKeyPair().getPublicKey().getKeyHash(), price)) + .attachSpendingValidator(script); + return submit(backend, tx, owner); + } + + public static String address(PlutusScript script) { + try { + return AddressProvider.getEntAddress(script, Networks.testnet()).toBech32(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static List noteAmounts(String policyId) { + List amounts = new ArrayList<>(); + amounts.add(Amount.ada(2)); + amounts.add(new Amount(policyId + HexUtil.encodeHexString(NOTE_TOKEN), BigInteger.ONE)); + return amounts; + } + + /** {@code Issue} / {@code Split} / {@code Receipt}: {@code Constr tag [I 0]}. */ + private static PlutusData action(int tag) { + return ConstrPlutusData.builder().alternative(tag).data(ListPlutusData.of(BigIntPlutusData.of(0))).build(); + } + + private static Result submit(BackendService backend, ScriptTx tx, Account owner) { + try { + return new QuickTxBuilder(backend).compose(tx) + .withTxEvaluator(DevKit.evaluator(backend)) + .withSigner(SignerProviders.signerFrom(owner)) + .withRequiredSigners(owner.hdKeyPair().getPublicKey().getKeyHash()) + .feePayer(owner.baseAddress()) + .collateralPayer(owner.baseAddress()) + .complete(); + } catch (RuntimeException e) { + return Result.error(e.getMessage()); + } + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/circuit/PointsRedeemProof.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/circuit/PointsRedeemProof.java new file mode 100644 index 0000000..5cfb680 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/circuit/PointsRedeemProof.java @@ -0,0 +1,44 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.points.circuit; + +import org.zeroj.circuit.annotation.Prove; +import org.zeroj.circuit.annotation.Public; +import org.zeroj.circuit.annotation.Secret; +import org.zeroj.circuit.annotation.UInt; +import org.zeroj.circuit.annotation.ZKCircuit; +import org.zeroj.circuit.annotation.ZkContext; +import org.zeroj.circuit.annotation.ZkField; +import org.zeroj.circuit.annotation.ZkUInt; +import org.zeroj.circuit.lib.zk.ZkPedersen; +import org.zeroj.circuit.lib.zk.ZkPedersenCommitment; + +import java.util.List; + +/** + * Spending points at the retailer (ADR-0006 demo A): a hidden balance pays a public price and + * keeps a hidden change. + * + *

Public, in order: {@code in.u, in.v, change.u, change.v, price}. The prover knows openings of + * both commitments, with 64-bit amounts and 252-bit blindings, such that {@code in = change + price} + * as integers, where {@code price} is a public 32-bit amount. This is the homomorphic balance with + * a public term: the commitments hide the balance and the change, while the redeemed price is + * visible to everyone. + */ +@ZKCircuit(name = "points-redeem", version = 1) +public class PointsRedeemProof { + + @Prove + void prove(ZkContext zk, + @Public ZkField inU, @Public ZkField inV, + @Public ZkField changeU, @Public ZkField changeV, + @Public @UInt(bits = 32) ZkUInt price, + @Secret @UInt(bits = 64) ZkUInt inAmount, @Secret @UInt(bits = 252) ZkUInt inBlinding, + @Secret @UInt(bits = 64) ZkUInt changeAmount, @Secret @UInt(bits = 252) ZkUInt changeBlinding) { + var in = ZkPedersenCommitment.commit(zk, inAmount, inBlinding); + var change = ZkPedersenCommitment.commit(zk, changeAmount, changeBlinding); + in.assertAffineEquals(zk, inU, inV); + change.assertAffineEquals(zk, changeU, changeV); + ZkPedersen.assertBalanced(zk, + List.of(ZkPedersen.Term.of(in)), + List.of(ZkPedersen.Term.of(change), ZkPedersen.Term.amount(price))); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/circuit/PointsTransferProof.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/circuit/PointsTransferProof.java new file mode 100644 index 0000000..7e250cd --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/circuit/PointsTransferProof.java @@ -0,0 +1,46 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.points.circuit; + +import org.zeroj.circuit.annotation.Prove; +import org.zeroj.circuit.annotation.Public; +import org.zeroj.circuit.annotation.Secret; +import org.zeroj.circuit.annotation.UInt; +import org.zeroj.circuit.annotation.ZKCircuit; +import org.zeroj.circuit.annotation.ZkContext; +import org.zeroj.circuit.annotation.ZkField; +import org.zeroj.circuit.annotation.ZkUInt; +import org.zeroj.circuit.lib.zk.ZkPedersen; +import org.zeroj.circuit.lib.zk.ZkPedersenCommitment; + +import java.util.List; + +/** + * A private points transfer (ADR-0006 demo A): one note is split into two, and the amounts stay + * hidden. + * + *

Public, in order: {@code in.u, in.v, out1.u, out1.v, out2.u, out2.v}, the affine + * {@code pedersen-jubjub-v1} commitments of the spent note and the two new notes. The prover knows + * an opening of all three, with 64-bit amounts and 252-bit blindings, such that + * {@code in = out1 + out2} as integers. {@code assertBalanced} rules out wraparound mod {@code l}. + */ +@ZKCircuit(name = "points-transfer", version = 1) +public class PointsTransferProof { + + @Prove + void prove(ZkContext zk, + @Public ZkField inU, @Public ZkField inV, + @Public ZkField out1U, @Public ZkField out1V, + @Public ZkField out2U, @Public ZkField out2V, + @Secret @UInt(bits = 64) ZkUInt inAmount, @Secret @UInt(bits = 252) ZkUInt inBlinding, + @Secret @UInt(bits = 64) ZkUInt out1Amount, @Secret @UInt(bits = 252) ZkUInt out1Blinding, + @Secret @UInt(bits = 64) ZkUInt out2Amount, @Secret @UInt(bits = 252) ZkUInt out2Blinding) { + var in = ZkPedersenCommitment.commit(zk, inAmount, inBlinding); + var out1 = ZkPedersenCommitment.commit(zk, out1Amount, out1Blinding); + var out2 = ZkPedersenCommitment.commit(zk, out2Amount, out2Blinding); + in.assertAffineEquals(zk, inU, inV); + out1.assertAffineEquals(zk, out1U, out1V); + out2.assertAffineEquals(zk, out2U, out2V); + ZkPedersen.assertBalanced(zk, + List.of(ZkPedersen.Term.of(in)), + List.of(ZkPedersen.Term.of(out1), ZkPedersen.Term.of(out2))); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/onchain/PointsLedger.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/onchain/PointsLedger.java new file mode 100644 index 0000000..e932e36 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/onchain/PointsLedger.java @@ -0,0 +1,370 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.points.onchain; + +import org.julclang.core.PlutusData; +import org.julclang.core.types.JulcList; +import org.julclang.ledger.Credential; +import org.julclang.ledger.OutputDatum; +import org.julclang.ledger.PubKeyHash; +import org.julclang.ledger.ScriptContext; +import org.julclang.ledger.ScriptHash; +import org.julclang.ledger.ScriptInfo; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxInfo; +import org.julclang.ledger.TxOut; +import org.julclang.ledger.Value; +import org.julclang.stdlib.Builtins; +import org.julclang.stdlib.annotation.Entrypoint; +import org.julclang.stdlib.annotation.MultiValidator; +import org.julclang.stdlib.annotation.Param; +import org.julclang.stdlib.annotation.Purpose; +import org.julclang.stdlib.lib.ContextsLib; +import org.julclang.stdlib.lib.ValuesLib; +import org.zeroj.onchain.julc.groth16.lib.Groth16BLS12381Lib; + +import java.math.BigInteger; + +/** + * Confidential loyalty points (ADR-0006 demo A). One script is both the points policy and the + * note address, so its hash is the policy id and the notes' payment credential. + * + *

A note is an output at the script credential holding exactly one {@code noteToken} and + * nothing else under the policy, with inline datum {@code Note(owner, u, v)}: the owner's key hash + * and the affine {@code pedersen-jubjub-v1} commitment to its amount. + * + *

    + *
  • Issue (mint): the issuer signs and mints {@code n} note tokens into exactly {@code n} + * new notes; no note is spent. The issuer is trusted for supply.
  • + *
  • Transfer (spend + {@code Split} mint): the owner splits one note into two, proving + * {@code in = out1 + out2} over hidden 64-bit amounts. One note token is minted for the + * second output.
  • + *
  • Redeem (spend + {@code Receipt} mint): the owner pays a public {@code price} from a + * note and keeps a hidden change note, proving {@code in = change + price}. A receipt token, + * named after the redeemed note's output reference, is minted to the issuer with datum + * {@code Receipt(owner, price)}. Only a valid redemption can mint one, and each note can be + * redeemed once, so receipts cannot be forged or replayed.
  • + *
+ * + *

Every public input comes from datums and outputs; the price comes from the redeemer and is + * bound by the proof and recorded in the receipt. Script inputs are counted by payment credential, + * so two notes can never be spent in one transaction. Every coordinate is checked canonical. + */ +@MultiValidator +public class PointsLedger { + + @Param static byte[] issuerPkh; + @Param static byte[] noteToken; + @Param static byte[] transferAlpha; + @Param static byte[] transferBeta; + @Param static byte[] transferGamma; + @Param static byte[] transferDelta; + @Param static PlutusData transferIc; + @Param static byte[] redeemAlpha; + @Param static byte[] redeemBeta; + @Param static byte[] redeemGamma; + @Param static byte[] redeemDelta; + @Param static PlutusData redeemIc; + + record Note(byte[] owner, BigInteger u, BigInteger v) {} + + sealed interface PointsMint permits Issue, Split, Receipt {} + record Issue(BigInteger count) implements PointsMint {} + record Split(BigInteger count) implements PointsMint {} + record Receipt(BigInteger count) implements PointsMint {} + + sealed interface NoteSpend permits Transfer, Redeem {} + record Transfer(byte[] piA, byte[] piB, byte[] piC) implements NoteSpend {} + record Redeem(BigInteger price, byte[] piA, byte[] piB, byte[] piC) implements NoteSpend {} + + // ------------------------------------------------------------------ + // Minting + // ------------------------------------------------------------------ + + @Entrypoint(purpose = Purpose.MINT) + public static boolean mint(PointsMint redeemer, ScriptContext ctx) { + TxInfo txInfo = ctx.txInfo(); + ScriptInfo.MintingScript mintInfo = (ScriptInfo.MintingScript) ctx.scriptInfo(); + byte[] policy = PlutusData.cast(mintInfo.policyId(), byte[].class); + Credential own = new Credential.ScriptCredential(PlutusData.cast(policy, ScriptHash.class)); + int ownInputs = countInputs(txInfo.inputs(), own); + // Every action mints exactly one token name under this policy. + if (policyEntryCount(txInfo.mint(), policy) != 1) return false; + + return switch (redeemer) { + case Issue issue -> { + BigInteger n = ValuesLib.assetOf(txInfo.mint(), policy, noteToken); + yield signedBy(txInfo, issuerPkh) && ownInputs == 0 + && n.compareTo(BigInteger.ONE) >= 0 + && BigInteger.valueOf(countOutputs(txInfo.outputs(), own)).compareTo(n) == 0 + && allNotes(txInfo.outputs(), own, policy); + } + // The spent note's spending purpose proves the transfer; here only the count. + case Split split -> ownInputs == 1 + && ValuesLib.assetOf(txInfo.mint(), policy, noteToken).compareTo(BigInteger.ONE) == 0; + // The spent note's spending purpose proves the redemption and pins the receipt name. + case Receipt receipt -> { + byte[] name = ValuesLib.findTokenName(txInfo.mint(), policy, BigInteger.ONE); + yield ownInputs == 1 && Builtins.lengthOfByteString(name) == 32; + } + }; + } + + // ------------------------------------------------------------------ + // Spending a note + // ------------------------------------------------------------------ + + @Entrypoint(purpose = Purpose.SPEND) + public static boolean spend(Note datum, NoteSpend redeemer, ScriptContext ctx) { + TxInfo txInfo = ctx.txInfo(); + byte[] policy = ContextsLib.ownHash(ctx); + Credential own = new Credential.ScriptCredential(PlutusData.cast(policy, ScriptHash.class)); + if (Builtins.lengthOfByteString(datum.owner()) != 28 + || !canonicalField(datum.u()) || !canonicalField(datum.v()) + || !signedBy(txInfo, datum.owner())) { + return false; + } + var ownInputOptional = ContextsLib.findOwnInput(ctx); + if (ownInputOptional.isEmpty()) return false; + TxInInfo ownInput = ownInputOptional.get(); + if (countInputs(txInfo.inputs(), own) != 1 + || ValuesLib.assetOf(ownInput.resolved().value(), policy, noteToken).compareTo(BigInteger.ONE) != 0 + || policyEntryCount(txInfo.mint(), policy) != 1) { + return false; + } + return switch (redeemer) { + case Transfer transfer -> transfer(transfer, datum, txInfo, own, policy); + case Redeem redeem -> redeem(redeem, datum, ownInput, txInfo, own, policy); + }; + } + + private static boolean transfer(Transfer t, Note in, TxInfo txInfo, Credential own, byte[] policy) { + if (ValuesLib.assetOf(txInfo.mint(), policy, noteToken).compareTo(BigInteger.ONE) != 0) return false; + int notes = 0; + boolean wellFormed = true; + BigInteger o1u = BigInteger.ZERO; + BigInteger o1v = BigInteger.ZERO; + BigInteger o2u = BigInteger.ZERO; + BigInteger o2v = BigInteger.ZERO; + for (TxOut output : txInfo.outputs()) { + if (Builtins.equalsData(output.address().credential(), own)) { + boolean ok = isNote(output, policy); + wellFormed = wellFormed && ok; + PlutusData d = inlineDatum(output); + if (ok && notes == 0) { + o1u = noteU(d); + o1v = noteV(d); + } else { + o1u = o1u; + o1v = o1v; + } + if (ok && notes == 1) { + o2u = noteU(d); + o2v = noteV(d); + } else { + o2u = o2u; + o2v = o2v; + } + notes = notes + 1; + } else { + notes = notes; + } + } + if (notes != 2 || !wellFormed) return false; + PlutusData publicInputs = Builtins.listData( + Builtins.mkCons(Builtins.iData(in.u()), + Builtins.mkCons(Builtins.iData(in.v()), + Builtins.mkCons(Builtins.iData(o1u), + Builtins.mkCons(Builtins.iData(o1v), + Builtins.mkCons(Builtins.iData(o2u), + Builtins.mkCons(Builtins.iData(o2v), + Builtins.mkNilData()))))))); + return Groth16BLS12381Lib.verify(publicInputs, t.piA(), t.piB(), t.piC(), + transferAlpha, transferBeta, transferGamma, transferDelta, transferIc); + } + + private static boolean redeem(Redeem r, Note in, TxInInfo ownInput, TxInfo txInfo, + Credential own, byte[] policy) { + BigInteger price = r.price(); + if (price.compareTo(BigInteger.ONE) < 0 || price.compareTo(BigInteger.valueOf(4294967296L)) >= 0) { + return false; + } + // The receipt token is named after the redeemed note's output reference: one per note. + byte[] receiptName = ValuesLib.uniqueTokenName(ownInput.outRef()); + if (ValuesLib.assetOf(txInfo.mint(), policy, receiptName).compareTo(BigInteger.ONE) != 0) return false; + + Credential issuer = new Credential.PubKeyCredential(PlutusData.cast(issuerPkh, PubKeyHash.class)); + PlutusData expectedReceipt = Builtins.constrData(0, + Builtins.mkCons(Builtins.bData(in.owner()), + Builtins.mkCons(Builtins.iData(price), + Builtins.mkNilData()))); + int notes = 0; + boolean wellFormed = true; + boolean receipted = false; + BigInteger cu = BigInteger.ZERO; + BigInteger cv = BigInteger.ZERO; + for (TxOut output : txInfo.outputs()) { + if (Builtins.equalsData(output.address().credential(), own)) { + boolean ok = isNote(output, policy); + wellFormed = wellFormed && ok; + PlutusData d = inlineDatum(output); + if (ok && notes == 0) { + cu = noteU(d); + cv = noteV(d); + } else { + cu = cu; + cv = cv; + } + notes = notes + 1; + } else { + notes = notes; + } + boolean receipt = Builtins.equalsData(output.address().credential(), issuer) + && ValuesLib.assetOf(output.value(), policy, receiptName).compareTo(BigInteger.ONE) == 0 + && Builtins.equalsData(inlineDatum(output), expectedReceipt); + receipted = receipted || receipt; + } + if (notes != 1 || !wellFormed || !receipted) return false; + PlutusData publicInputs = Builtins.listData( + Builtins.mkCons(Builtins.iData(in.u()), + Builtins.mkCons(Builtins.iData(in.v()), + Builtins.mkCons(Builtins.iData(cu), + Builtins.mkCons(Builtins.iData(cv), + Builtins.mkCons(Builtins.iData(price), + Builtins.mkNilData())))))); + return Groth16BLS12381Lib.verify(publicInputs, r.piA(), r.piB(), r.piC(), + redeemAlpha, redeemBeta, redeemGamma, redeemDelta, redeemIc); + } + + // ------------------------------------------------------------------ + // Helpers + // ------------------------------------------------------------------ + + /** + * A note: exactly one note token and nothing else under the policy, and an inline + * {@code Note(owner: 28 bytes, u, v)} datum with canonical coordinates. + */ + private static boolean isNote(TxOut output, byte[] policy) { + if (ValuesLib.assetOf(output.value(), policy, noteToken).compareTo(BigInteger.ONE) != 0 + || policyEntryCount(output.value(), policy) != 1) { + return false; + } + PlutusData d = inlineDatum(output); + return isNoteDatum(d) && canonicalField(noteU(d)) && canonicalField(noteV(d)); + } + + private static boolean allNotes(JulcList outputs, Credential own, byte[] policy) { + boolean ok = true; + for (TxOut output : outputs) { + if (Builtins.equalsData(output.address().credential(), own)) { + ok = ok && isNote(output, policy); + } else { + ok = ok; + } + } + return ok; + } + + private static int countInputs(JulcList inputs, Credential own) { + int n = 0; + for (TxInInfo input : inputs) { + if (Builtins.equalsData(input.resolved().address().credential(), own)) { + n = n + 1; + } else { + n = n; + } + } + return n; + } + + private static int countOutputs(JulcList outputs, Credential own) { + int n = 0; + for (TxOut output : outputs) { + if (Builtins.equalsData(output.address().credential(), own)) { + n = n + 1; + } else { + n = n; + } + } + return n; + } + + private static boolean signedBy(TxInfo txInfo, byte[] pkh) { + boolean found = false; + for (var signer : txInfo.signatories()) { + found = found || Builtins.equalsByteString(signer.hash(), pkh); + } + return found; + } + + /** The number of token names (any quantity) under {@code policy}. */ + private static int policyEntryCount(Value value, byte[] policy) { + var outerPairs = Builtins.unMapData(value); + PlutusData target = Builtins.bData(policy); + int count = 0; + PlutusData current = outerPairs; + while (!Builtins.nullList(current)) { + var outerPair = Builtins.headList(current); + if (Builtins.equalsData(Builtins.fstPair(outerPair), target)) { + count = innerEntryCount((PlutusData.MapData) Builtins.sndPair(outerPair)); + current = Builtins.mkNilPairData(); + } else { + current = Builtins.tailList(current); + } + } + return count; + } + + private static int innerEntryCount(PlutusData.MapData innerPairs) { + int count = 0; + PlutusData current = Builtins.unMapData(innerPairs); + while (!Builtins.nullList(current)) { + count = count + 1; + current = Builtins.tailList(current); + } + return count; + } + + /** The inline datum; a missing or hashed datum yields an integer, which is never a note. */ + private static PlutusData inlineDatum(TxOut output) { + return switch (output.datum()) { + case OutputDatum.OutputDatumInline inline -> inline.datum(); + case OutputDatum.OutputDatumHash ignored -> Builtins.iData(BigInteger.ZERO); + case OutputDatum.NoOutputDatum ignored -> Builtins.iData(BigInteger.ZERO); + }; + } + + /** {@code Constr 0 [B(28), I, I]}; any other shape returns false or fails a builtin. */ + private static boolean isNoteDatum(PlutusData value) { + if (Builtins.constrTag(value) != 0) return false; + PlutusData fields = Builtins.constrFields(value); + if (Builtins.nullList(fields)) return false; + PlutusData rest = Builtins.tailList(fields); + if (Builtins.nullList(rest)) return false; + PlutusData rest2 = Builtins.tailList(rest); + if (Builtins.nullList(rest2)) return false; + return Builtins.nullList(Builtins.tailList(rest2)) + && Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(fields))) == 28 + && Builtins.unIData(Builtins.headList(rest)).compareTo(BigInteger.ZERO) >= 0 + && Builtins.unIData(Builtins.headList(rest2)).compareTo(BigInteger.ZERO) >= 0; + } + + private static BigInteger noteU(PlutusData note) { + return Builtins.unIData(Builtins.headList(Builtins.tailList(Builtins.constrFields(note)))); + } + + private static BigInteger noteV(PlutusData note) { + return Builtins.unIData(Builtins.headList(Builtins.tailList(Builtins.tailList(Builtins.constrFields(note))))); + } + + private static boolean canonicalField(BigInteger value) { + return value.compareTo(BigInteger.ZERO) >= 0 && value.compareTo(fr()) < 0; + } + + private static BigInteger fr() { + BigInteger base = BigInteger.valueOf(1000000000000000000L); + return BigInteger.valueOf(52435L).multiply(base) + .add(BigInteger.valueOf(875175126190479447L)).multiply(base) + .add(BigInteger.valueOf(740508185965837690L)).multiply(base) + .add(BigInteger.valueOf(552500527637822603L)).multiply(base) + .add(BigInteger.valueOf(658699938581184513L)); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyAttestation.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyAttestation.java new file mode 100644 index 0000000..18a48f7 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyAttestation.java @@ -0,0 +1,282 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.solvency; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.address.AddressProvider; +import com.bloxbean.cardano.client.api.model.Amount; +import com.bloxbean.cardano.client.api.model.Result; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.common.model.Networks; +import com.bloxbean.cardano.client.crypto.Blake2bUtil; +import com.bloxbean.cardano.client.function.helper.SignerProviders; +import com.bloxbean.cardano.client.plutus.spec.BigIntPlutusData; +import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ConstrPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ListPlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusScript; +import com.bloxbean.cardano.client.quicktx.QuickTxBuilder; +import com.bloxbean.cardano.client.quicktx.ScriptTx; +import com.bloxbean.cardano.client.transaction.spec.Asset; +import com.bloxbean.cardano.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Fields; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.KeyedCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; +import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.circuit.HiddenLiabilitySolvencyProofCircuit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.onchain.SolvencyVault; +import org.julclang.clientlib.JulcScriptLoader; +import org.zeroj.circuit.lib.jubjub.JubjubCurve; +import org.zeroj.circuit.lib.jubjub.JubjubPoint; +import org.zeroj.circuit.lib.jubjub.PedersenCommitment; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; +import org.zeroj.onchain.julc.groth16.codec.ProverToCardano; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Hidden-liability solvency (ADR-0006 demo C): one Pedersen commitment per customer balance, + * a proof that the hidden total is at most the reserve locked in the vault, a check each customer + * runs on their own entry, and an aggregate opening for an auditor. + */ +public final class SolvencyAttestation { + + public static final byte[] ATTEST_TOKEN = "ATTEST".getBytes(StandardCharsets.UTF_8); + private static final SecureRandom RANDOM = new SecureRandom(); + + /** + * A customer as the exchange sees them: id, a fresh 32-byte salt for this period, the + * balance and its blinding. The customer receives everything but the other customers' data. + */ + public record Customer(String id, byte[] salt, long balance, BigInteger blinding) { + public static Customer of(String id, long balance) { + byte[] salt = new byte[32]; + RANDOM.nextBytes(salt); + return new Customer(id, salt, balance, PedersenCommitment.randomBlinding(RANDOM)); + } + + /** {@code blake2b_256(I2OSP2(len(id)) ‖ UTF-8(id) ‖ salt)}: unambiguous for any id. */ + public byte[] idHash() { + byte[] utf8 = id.getBytes(StandardCharsets.UTF_8); + return Blake2bUtil.blake2bHash256(Fields.concat( + Fields.i2osp(BigInteger.valueOf(utf8.length), 2), utf8, salt)); + } + + public JubjubPoint commitment() { + return PedersenCommitment.commit(BigInteger.valueOf(balance), blinding).normalized(); + } + } + + /** A published entry: the customer's id hash and balance commitment. */ + public record Entry(byte[] idHash, JubjubPoint commitment) {} + + /** + * An attestation period {@code [start, end]} (POSIX ms), from the exchange's public schedule. + * Attestations must be made before {@code start} and stay locked until after {@code end}. + */ + public record Period(long start, long end) { + public Period { + if (end <= start) throw new IllegalArgumentException("period must end after it starts"); + } + } + + private final int customers; + private final KeyedCircuit circuit; + + public SolvencyAttestation(int customers) { + this.customers = customers; + this.circuit = KeyedCircuit.compile("hidden-liability-solvency-n" + customers, + HiddenLiabilitySolvencyProofCircuit.build(customers)); + } + + public KeyedCircuit circuit() { return circuit; } + + public int customers() { return customers; } + + public static List entries(List book) { + return book.stream().map(c -> new Entry(c.idHash(), c.commitment())).toList(); + } + + public static HiddenLiabilitySolvencyProofCircuit.Inputs inputs(long reserves, List book) { + return HiddenLiabilitySolvencyProofCircuit.inputs(book.size()) + .reserves(reserves) + .liabilityU(book.stream().map(c -> c.commitment().affineU()).toList()) + .liabilityV(book.stream().map(c -> c.commitment().affineV()).toList()) + .balances(book.stream().map(c -> BigInteger.valueOf(c.balance())).toList()) + .blindings(book.stream().map(Customer::blinding).toList()); + } + + /** Proves {@code Σ balances ≤ reserves}; throws if the exchange is not solvent. */ + public Groth16ProofBLS381 prove(long reserves, List book) { + if (book.size() != customers) throw new IllegalArgumentException("expected " + customers + " customers"); + return circuit.prove(inputs(reserves, book).toWitnessMap()); + } + + // ------------------------------------------------------------------ + // Checks anyone can run + // ------------------------------------------------------------------ + + /** + * The customer's check over a set of entries: their id hash appears exactly once, and that + * entry opens to their balance. Pass every entry of the period ({@link #liveEntries}). + */ + public static boolean customerCheck(List entries, Customer me) { + byte[] mine = me.idHash(); + List matches = entries.stream().filter(e -> Arrays.equals(e.idHash(), mine)).toList(); + return matches.size() == 1 + && PedersenCommitment.verify(matches.getFirst().commitment(), BigInteger.valueOf(me.balance()), me.blinding()); + } + + /** What the exchange hands an auditor: total liabilities and the sum of the blindings mod l. */ + public record AuditOpening(BigInteger liabilities, BigInteger blinding) {} + + public static AuditOpening auditOpening(List book) { + BigInteger total = BigInteger.ZERO; + BigInteger r = BigInteger.ZERO; + for (Customer c : book) { + total = total.add(BigInteger.valueOf(c.balance())); + r = r.add(c.blinding()).mod(JubjubCurve.SUBGROUP_ORDER); + } + return new AuditOpening(total, r); + } + + /** + * The auditor's check, by homomorphism: {@code Σ C_i = Commit(L, Σ r_i)} over the published + * entries. Reveals {@code L} to the auditor and nothing about any single balance. + */ + public static boolean auditorCheck(List entries, AuditOpening opening) { + JubjubPoint sum = JubjubPoint.IDENTITY; + for (Entry e : entries) sum = sum.add(e.commitment()); + return PedersenCommitment.verify(sum.normalized(), opening.liabilities(), opening.blinding()); + } + + // ------------------------------------------------------------------ + // Script, datums and transactions + // ------------------------------------------------------------------ + + /** + * The vault for one exchange and one period. Customers derive it themselves from the published + * parameters and verification key, and never take a script the exchange merely points to. + */ + public PlutusScript vault(byte[] exchangePkh, Period period) { + var vk = circuit.compressedVk(); + return JulcScriptLoader.load(SolvencyVault.class, + new BytesPlutusData(exchangePkh), + new BytesPlutusData(ATTEST_TOKEN), + BigIntPlutusData.of(customers), + BigIntPlutusData.of(period.start()), + BigIntPlutusData.of(period.end()), + new BytesPlutusData(vk.alpha()), new BytesPlutusData(vk.beta()), + new BytesPlutusData(vk.gamma()), new BytesPlutusData(vk.delta()), Plutus.icData(vk.ic())); + } + + public static String address(PlutusScript script) { + try { + return AddressProvider.getEntAddress(script, Networks.testnet()).toBech32(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + /** {@code Attestation([Entry(idHash, u, v)])}. */ + public static ConstrPlutusData attestationDatum(List entries) { + List items = new ArrayList<>(); + for (Entry e : entries) { + items.add(ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(e.idHash()), + BigIntPlutusData.of(e.commitment().affineU()), + BigIntPlutusData.of(e.commitment().affineV()))).build()); + } + return ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + ListPlutusData.of(items.toArray(new PlutusData[0])))).build(); + } + + /** + * The entries of a live attestation, read from the vault output's inline datum, as a customer + * or auditor would read them from the chain. + */ + public static List readEntries(Utxo vaultUtxo) { + try { + var datum = (ConstrPlutusData) PlutusData.deserialize(HexUtil.decodeHexString(vaultUtxo.getInlineDatum())); + var entries = (ListPlutusData) datum.getData().getPlutusDataList().get(0); + List out = new ArrayList<>(); + for (PlutusData item : entries.getPlutusDataList()) { + var f = ((ConstrPlutusData) item).getData().getPlutusDataList(); + out.add(new Entry(((BytesPlutusData) f.get(0)).getValue(), JubjubPoint.fromAffine( + ((BigIntPlutusData) f.get(1)).getValue(), ((BigIntPlutusData) f.get(2)).getValue()))); + } + return out; + } catch (Exception e) { + throw new IllegalArgumentException("not an attestation datum", e); + } + } + + /** + * Every entry of every live attestation of {@code vault}'s period: all UTxOs at the vault's + * address that hold its attestation token. This is the set a customer checks. + */ + public static List liveEntries(BackendService backend, PlutusScript vault) throws Exception { + String unit = Plutus.policyId(vault) + HexUtil.encodeHexString(ATTEST_TOKEN); + List all = new ArrayList<>(); + for (int page = 1; ; page++) { + var result = backend.getUtxoService().getUtxos(address(vault), 100, page); + if (!result.isSuccessful() || result.getValue() == null || result.getValue().isEmpty()) break; + for (Utxo u : result.getValue()) { + if (u.getAmount().stream().anyMatch(a -> a.getUnit().equals(unit))) all.addAll(readEntries(u)); + } + if (result.getValue().size() < 100) break; + } + return all; + } + + /** Locks {@code reservesLovelace} in the vault with the attestation, minting its token. */ + public static Result attest(BackendService backend, PlutusScript vault, Account exchange, + long reservesLovelace, List entries, + Groth16ProofBLS381 proof, long validToSlot) { + String policyId = Plutus.policyId(vault); + var p = ProverToCardano.compressProof(proof); + var redeemer = ConstrPlutusData.builder().alternative(0).data(ListPlutusData.of( + new BytesPlutusData(p.piA()), new BytesPlutusData(p.piB()), new BytesPlutusData(p.piC()))).build(); + var tx = new ScriptTx() + .mintAsset(vault, List.of(new Asset("0x" + HexUtil.encodeHexString(ATTEST_TOKEN), BigInteger.ONE)), redeemer) + .payToContract(address(vault), + List.of(new Amount("lovelace", BigInteger.valueOf(reservesLovelace)), + new Amount(policyId + HexUtil.encodeHexString(ATTEST_TOKEN), BigInteger.ONE)), + attestationDatum(entries)); + return submit(backend, tx, exchange, null, validToSlot); + } + + /** Releases the reserve once the period has ended, burning the attestation token. */ + public static Result release(BackendService backend, PlutusScript vault, Account exchange, + Utxo vaultUtxo, Long validFromSlot) { + var burn = ConstrPlutusData.builder().alternative(1).data(ListPlutusData.of(BigIntPlutusData.of(0))).build(); + var tx = new ScriptTx() + .collectFrom(vaultUtxo, ConstrPlutusData.of(0)) + .mintAsset(vault, List.of(new Asset("0x" + HexUtil.encodeHexString(ATTEST_TOKEN), BigInteger.ONE.negate())), burn) + .payToAddress(exchange.baseAddress(), Amount.ada(2)) + .attachSpendingValidator(vault); + return submit(backend, tx, exchange, validFromSlot, null); + } + + private static Result submit(BackendService backend, ScriptTx tx, Account exchange, + Long validFrom, Long validTo) { + try { + var ctx = new QuickTxBuilder(backend).compose(tx) + .withTxEvaluator(DevKit.evaluator(backend)) + .withSigner(SignerProviders.signerFrom(exchange)) + .withRequiredSigners(exchange.hdKeyPair().getPublicKey().getKeyHash()) + .feePayer(exchange.baseAddress()) + .collateralPayer(exchange.baseAddress()); + if (validFrom != null) ctx = ctx.validFrom(validFrom); + if (validTo != null) ctx = ctx.validTo(validTo); + return ctx.complete(); + } catch (RuntimeException e) { + return Result.error(e.getMessage()); + } + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/circuit/HiddenLiabilitySolvencyProof.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/circuit/HiddenLiabilitySolvencyProof.java new file mode 100644 index 0000000..ed11625 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/circuit/HiddenLiabilitySolvencyProof.java @@ -0,0 +1,56 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.circuit; + +import org.zeroj.circuit.annotation.CircuitParam; +import org.zeroj.circuit.annotation.FixedSize; +import org.zeroj.circuit.annotation.Prove; +import org.zeroj.circuit.annotation.Public; +import org.zeroj.circuit.annotation.Secret; +import org.zeroj.circuit.annotation.UInt; +import org.zeroj.circuit.annotation.ZKCircuit; +import org.zeroj.circuit.annotation.ZkArray; +import org.zeroj.circuit.annotation.ZkContext; +import org.zeroj.circuit.annotation.ZkField; +import org.zeroj.circuit.annotation.ZkUInt; +import org.zeroj.circuit.lib.zk.ZkPedersenCommitment; + +/** + * Solvency with hidden liabilities (ADR-0006 demo C, after Provisions). + * + *

Public, in order: {@code R, u_1..u_N, v_1..v_N}: the attested reserve and the affine + * {@code pedersen-jubjub-v1} commitment of each customer's balance. The prover knows every opening, + * with 64-bit balances and 252-bit blindings, and proves {@code Σ b_i ≤ R}. Neither the balances + * nor their total are revealed. With {@code N·2^64 ≪ p} the sum cannot wrap. + */ +@ZKCircuit( + name = "hidden-liability-solvency", + nameTemplate = "hidden-liability-solvency-n{customers}", + version = 1) +public class HiddenLiabilitySolvencyProof { + + private final int customers; + + public HiddenLiabilitySolvencyProof(@CircuitParam("customers") int customers) { + // Each customer adds two public inputs, i.e. two G1 scalar multiplications on-chain; + // 4.4e9 steps at N = 4 puts the 10e9 per-transaction limit near N = 19 (ADR-0006). + if (customers < 1 || customers > 16) { + throw new IllegalArgumentException("customers must be in [1, 16]"); + } + this.customers = customers; + } + + @Prove + void prove(ZkContext zk, + @Public @UInt(bits = 64) ZkUInt reserves, + @Public @FixedSize(param = "customers") ZkArray liabilityU, + @Public @FixedSize(param = "customers") ZkArray liabilityV, + @Secret @UInt(bits = 64) @FixedSize(param = "customers") ZkArray balances, + @Secret @UInt(bits = 252) @FixedSize(param = "customers") ZkArray blindings) { + ZkUInt total = null; + for (int i = 0; i < customers; i++) { + ZkPedersenCommitment.commit(zk, balances.get(i), blindings.get(i)) + .assertAffineEquals(zk, liabilityU.get(i), liabilityV.get(i)); + total = total == null ? balances.get(i) : total.add(balances.get(i)); + } + total.lte(reserves).assertTrue(); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/onchain/SolvencyVault.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/onchain/SolvencyVault.java new file mode 100644 index 0000000..b5184f8 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/onchain/SolvencyVault.java @@ -0,0 +1,263 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.onchain; + +import org.julclang.core.PlutusData; +import org.julclang.core.types.JulcList; +import org.julclang.ledger.Address; +import org.julclang.ledger.Credential; +import org.julclang.ledger.OutputDatum; +import org.julclang.ledger.ScriptContext; +import org.julclang.ledger.ScriptHash; +import org.julclang.ledger.ScriptInfo; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxInfo; +import org.julclang.ledger.TxOut; +import org.julclang.ledger.Value; +import org.julclang.stdlib.Builtins; +import org.julclang.stdlib.annotation.Entrypoint; +import org.julclang.stdlib.annotation.MultiValidator; +import org.julclang.stdlib.annotation.Param; +import org.julclang.stdlib.annotation.Purpose; +import org.julclang.stdlib.lib.ContextsLib; +import org.julclang.stdlib.lib.IntervalLib; +import org.julclang.stdlib.lib.ValuesLib; +import org.zeroj.onchain.julc.groth16.lib.Groth16BLS12381Lib; + +import java.math.BigInteger; +import java.util.Optional; + +/** + * Solvency attestations with hidden liabilities (ADR-0006 demo C). One script is the attestation + * policy and the vault address, and it is specific to one attestation period + * {@code [periodStart, periodEnd]}. + * + *

Attest (mint): before the period starts (validity range ending at or before + * {@code periodStart}), the exchange signs and mints one attestation token into a vault output at + * exactly the vault's enterprise address, whose inline datum is + * {@code Attestation([Entry(idHash, u, v)] × N)} and whose value is the attested reserve {@code R} + * in lovelace plus the token. The proof shows {@code Σ b_i ≤ R} over the hidden balances committed + * in the entries; its public inputs are {@code [R, u_1..u_N, v_1..v_N]}, read from that output. + * + *

Release (spend + burn): only after the period ends (validity range starting at or after + * {@code periodEnd}), with the exchange's signature, burning the attestation token. + * + *

So every attestation of the period is locked for the whole period at once: none can be added + * or released inside it, and the same reserve cannot back attestations one after another. + */ +@MultiValidator +public class SolvencyVault { + + @Param static byte[] exchangePkh; + @Param static byte[] attestToken; + @Param static BigInteger entryCount; + @Param static BigInteger periodStart; // POSIX ms + @Param static BigInteger periodEnd; // POSIX ms + @Param static byte[] vkAlpha; + @Param static byte[] vkBeta; + @Param static byte[] vkGamma; + @Param static byte[] vkDelta; + @Param static PlutusData vkIc; + + sealed interface VaultMint permits Attest, Burn {} + record Attest(byte[] piA, byte[] piB, byte[] piC) implements VaultMint {} + record Burn(BigInteger count) implements VaultMint {} + + @Entrypoint(purpose = Purpose.MINT) + public static boolean mint(VaultMint redeemer, ScriptContext ctx) { + TxInfo txInfo = ctx.txInfo(); + ScriptInfo.MintingScript mintInfo = (ScriptInfo.MintingScript) ctx.scriptInfo(); + byte[] policy = PlutusData.cast(mintInfo.policyId(), byte[].class); + Credential own = new Credential.ScriptCredential(PlutusData.cast(policy, ScriptHash.class)); + if (policyEntryCount(txInfo.mint(), policy) != 1) return false; + int ownInputs = countInputs(txInfo.inputs(), own); + return switch (redeemer) { + case Attest attest -> ownInputs == 0 && attest(attest, txInfo, own, policy); + // The spent vault output's spending purpose checks the unlock time and signature. + case Burn burn -> ownInputs == 1 + && ValuesLib.assetOf(txInfo.mint(), policy, attestToken).compareTo(BigInteger.valueOf(-1)) == 0; + }; + } + + private static boolean attest(Attest a, TxInfo txInfo, Credential own, byte[] policy) { + BigInteger upper = IntervalLib.finiteUpperBound(txInfo.validRange()); + if (!signedBy(txInfo, exchangePkh) + || upper.compareTo(BigInteger.ZERO) < 0 || upper.compareTo(periodStart) > 0 + || ValuesLib.assetOf(txInfo.mint(), policy, attestToken).compareTo(BigInteger.ONE) != 0) { + return false; + } + // The one output holding the token: at the vault, lovelace plus the token only. + int holders = 0; + TxOut vault = txInfo.outputs().get(0); + for (TxOut output : txInfo.outputs()) { + if (ValuesLib.assetOf(output.value(), policy, attestToken).compareTo(BigInteger.ZERO) > 0) { + holders = holders + 1; + vault = output; + } else { + holders = holders; + } + } + Address vaultAddress = new Address(own, Optional.empty()); + if (holders != 1 + || !Builtins.equalsData(vault.address(), vaultAddress) + || outerEntryCount(vault.value()) != 2 + || policyEntryCount(vault.value(), policy) != 1) { + return false; + } + BigInteger reserves = ValuesLib.lovelaceOf(vault.value()); + if (reserves.compareTo(BigInteger.valueOf(4294967296L).multiply(BigInteger.valueOf(4294967296L))) >= 0) return false; + + PlutusData datum = inlineDatum(vault); + if (Builtins.constrTag(datum) != 0) return false; + PlutusData fields = Builtins.constrFields(datum); + PlutusData entries = Builtins.unListData(Builtins.headList(fields)); + if (!Builtins.nullList(Builtins.tailList(fields))) return false; + + // [R, u_1..u_N, v_1..v_N], with every entry checked: 32-byte idHash, canonical u and v. + int count = 0; + boolean wellFormed = true; + PlutusData reversedV = Builtins.mkNilData(); + PlutusData reversedU = Builtins.mkNilData(); + PlutusData cursor = entries; + while (!Builtins.nullList(cursor)) { + PlutusData entry = Builtins.headList(cursor); + boolean ok = isEntry(entry); + wellFormed = wellFormed && ok; + reversedU = Builtins.mkCons(Builtins.iData(entryField(entry, 1)), reversedU); + reversedV = Builtins.mkCons(Builtins.iData(entryField(entry, 2)), reversedV); + count = count + 1; + cursor = Builtins.tailList(cursor); + } + if (!wellFormed || BigInteger.valueOf(count).compareTo(entryCount) != 0) return false; + PlutusData publicInputs = Builtins.mkNilData(); + PlutusData vs = reversedV; + while (!Builtins.nullList(vs)) { + publicInputs = Builtins.mkCons(Builtins.headList(vs), publicInputs); + vs = Builtins.tailList(vs); + } + PlutusData us = reversedU; + while (!Builtins.nullList(us)) { + publicInputs = Builtins.mkCons(Builtins.headList(us), publicInputs); + us = Builtins.tailList(us); + } + PlutusData withReserves = Builtins.mkCons(Builtins.iData(reserves), publicInputs); + return Groth16BLS12381Lib.verify(Builtins.listData(withReserves), a.piA(), a.piB(), a.piC(), + vkAlpha, vkBeta, vkGamma, vkDelta, vkIc); + } + + @Entrypoint(purpose = Purpose.SPEND) + public static boolean spend(PlutusData datum, PlutusData redeemer, ScriptContext ctx) { + TxInfo txInfo = ctx.txInfo(); + byte[] policy = ContextsLib.ownHash(ctx); + Credential own = new Credential.ScriptCredential(PlutusData.cast(policy, ScriptHash.class)); + BigInteger from = IntervalLib.finiteLowerBound(txInfo.validRange()); + return signedBy(txInfo, exchangePkh) + && from.compareTo(BigInteger.ZERO) >= 0 && from.compareTo(periodEnd) >= 0 + && countInputs(txInfo.inputs(), own) == 1 + && policyEntryCount(txInfo.mint(), policy) == 1 + && ValuesLib.assetOf(txInfo.mint(), policy, attestToken).compareTo(BigInteger.valueOf(-1)) == 0; + } + + // ------------------------------------------------------------------ + + /** {@code Constr 0 [B(32), I, I]} with canonical coordinates. */ + private static boolean isEntry(PlutusData entry) { + if (Builtins.constrTag(entry) != 0) return false; + PlutusData f = Builtins.constrFields(entry); + if (Builtins.nullList(f)) return false; + PlutusData f1 = Builtins.tailList(f); + if (Builtins.nullList(f1)) return false; + PlutusData f2 = Builtins.tailList(f1); + if (Builtins.nullList(f2) || !Builtins.nullList(Builtins.tailList(f2))) return false; + return Builtins.lengthOfByteString(Builtins.unBData(Builtins.headList(f))) == 32 + && canonicalField(Builtins.unIData(Builtins.headList(f1))) + && canonicalField(Builtins.unIData(Builtins.headList(f2))); + } + + private static BigInteger entryField(PlutusData entry, int index) { + PlutusData f = Builtins.constrFields(entry); + int i = 0; + while (i < index) { + f = Builtins.tailList(f); + i = i + 1; + } + return Builtins.unIData(Builtins.headList(f)); + } + + private static int countInputs(JulcList inputs, Credential own) { + int n = 0; + for (TxInInfo input : inputs) { + if (Builtins.equalsData(input.resolved().address().credential(), own)) { + n = n + 1; + } else { + n = n; + } + } + return n; + } + + private static boolean signedBy(TxInfo txInfo, byte[] pkh) { + boolean found = false; + for (var signer : txInfo.signatories()) { + found = found || Builtins.equalsByteString(signer.hash(), pkh); + } + return found; + } + + private static int policyEntryCount(Value value, byte[] policy) { + var outerPairs = Builtins.unMapData(value); + PlutusData target = Builtins.bData(policy); + int count = 0; + PlutusData current = outerPairs; + while (!Builtins.nullList(current)) { + var outerPair = Builtins.headList(current); + if (Builtins.equalsData(Builtins.fstPair(outerPair), target)) { + count = innerEntryCount((PlutusData.MapData) Builtins.sndPair(outerPair)); + current = Builtins.mkNilPairData(); + } else { + current = Builtins.tailList(current); + } + } + return count; + } + + private static int innerEntryCount(PlutusData.MapData innerPairs) { + int count = 0; + PlutusData current = Builtins.unMapData(innerPairs); + while (!Builtins.nullList(current)) { + count = count + 1; + current = Builtins.tailList(current); + } + return count; + } + + private static int outerEntryCount(Value value) { + var outerPairs = Builtins.unMapData(value); + int count = 0; + PlutusData current = outerPairs; + while (!Builtins.nullList(current)) { + count = count + 1; + current = Builtins.tailList(current); + } + return count; + } + + private static PlutusData inlineDatum(TxOut output) { + return switch (output.datum()) { + case OutputDatum.OutputDatumInline inline -> inline.datum(); + case OutputDatum.OutputDatumHash ignored -> Builtins.iData(BigInteger.ZERO); + case OutputDatum.NoOutputDatum ignored -> Builtins.iData(BigInteger.ZERO); + }; + } + + private static boolean canonicalField(BigInteger value) { + return value.compareTo(BigInteger.ZERO) >= 0 && value.compareTo(fr()) < 0; + } + + private static BigInteger fr() { + BigInteger base = BigInteger.valueOf(1000000000000000000L); + return BigInteger.valueOf(52435L).multiply(base) + .add(BigInteger.valueOf(875175126190479447L)).multiply(base) + .add(BigInteger.valueOf(740508185965837690L)).multiply(base) + .add(BigInteger.valueOf(552500527637822603L)).multiply(base) + .add(BigInteger.valueOf(658699938581184513L)); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/CardanoConfig.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/CardanoConfig.java new file mode 100644 index 0000000..09fca21 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/CardanoConfig.java @@ -0,0 +1,32 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.web; + +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.backend.blockfrost.service.BFBackendService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** The Blockfrost-compatible provider (Yaci Store on DevKit). */ +@Configuration +public class CardanoConfig { + + private static final Logger log = LoggerFactory.getLogger(CardanoConfig.class); + + @Value("${cardano.yaci.base-url}") + private String yaciBaseUrl; + + @Value("${cardano.blockfrost.base-url:}") + private String overrideBaseUrl; + + @Value("${cardano.blockfrost.project-id:}") + private String projectId; + + @Bean + public BackendService backendService() { + String baseUrl = overrideBaseUrl != null && !overrideBaseUrl.isBlank() ? overrideBaseUrl : yaciBaseUrl; + log.info("Using Blockfrost-compatible backend at {}", baseUrl); + return new BFBackendService(baseUrl, projectId == null ? "" : projectId); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/CreditService.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/CreditService.java new file mode 100644 index 0000000..9265a32 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/CreditService.java @@ -0,0 +1,152 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.web; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; +import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.CreditGate; +import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.CreditGate.Profile; +import com.bloxbean.cardano.zeroj.usecases.pedersen.credential.circuit.CreditProfileProof; +import org.springframework.stereotype.Service; +import org.zeroj.circuit.lib.jubjub.PedersenCommitment; +import org.zeroj.circuit.lib.jubjub.PedersenVectorCommitment; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; + +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Demo B, the committed credential gate, for the UI. The bureau, Alice (the holder) and Mallory + * (an impostor) are wallets this server creates. The server keeps Alice's profile and blinding, + * her opening, on her behalf; on-chain there is only the commitment and the issuance record. + */ +@Service +public class CreditService { + + private static final SecureRandom RANDOM = new SecureRandom(); + + private final BackendService backend; + private final Funding funding; + + private CreditGate credit; + private Account bureau; + private Account alice; + private Account mallory; + private byte[] bureauPolicy; + + private Profile profile; + private PedersenVectorCommitment commitment; + private Utxo record; + private String recordTx; + private final List> claims = new ArrayList<>(); + + public CreditService(BackendService backend, Funding funding) { + this.backend = backend; + this.funding = funding; + } + + synchronized void ensureReady() throws Exception { + if (credit != null) return; + var c = new CreditGate(); + bureau = funding.newWallet("credit/bureau", 200); + alice = funding.newWallet("credit/alice", 200); + mallory = funding.newWallet("credit/mallory", 200); + bureauPolicy = HexUtil.decodeHexString(CreditGate.bureauPolicy(bureau).getPolicyId()); + credit = c; + } + + /** The bureau commits to Alice's profile and records the issuance on-chain. */ + public synchronized Map issue(long income, int score, int birthYear, int country) throws Exception { + ensureReady(); + if (income < 0 || score < 0 || score > 0xffff || birthYear < 0 || birthYear > 0xffff + || country < 0 || country > 0xffff) { + throw new IllegalArgumentException("income must be >= 0; score, birth year and country must fit in 16 bits"); + } + Profile p = new Profile(income, score, birthYear, country, PedersenCommitment.randomBlinding(RANDOM)); + PedersenVectorCommitment c = p.commitment(); + String tx = DemoErrors.require(CreditGate.issueRecord(backend, bureau, alice.baseAddress(), + PointsService.pkh(alice), c), "Issuance record"); + DevKit.waitForTx(backend, tx); + String unitPrefix = HexUtil.encodeHexString(bureauPolicy); + record = DevKit.utxosOf(backend, alice.baseAddress(), tx).stream() + .filter(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().startsWith(unitPrefix))) + .findFirst().orElseThrow(() -> new IllegalStateException("issuance record not found")); + profile = p; + commitment = c; + recordTx = tx; + claims.clear(); + return Map.of("summary", "Bureau issued Alice's profile and recorded it on-chain", "txHash", tx); + } + + /** + * Alice ({@code who = "alice"}) or Mallory ({@code "mallory"}, presenting Alice's commitment and + * a valid proof as if her opening leaked) claims a badge from the lender's gate. + */ + public synchronized Map claim(String who, long minIncome, int minScore) throws Exception { + ensureReady(); + if (profile == null) throw new IllegalStateException("issue a profile first"); + if (minIncome < 0 || minScore < 0 || minScore > 0xffff) { + throw new IllegalArgumentException("thresholds out of range"); + } + Account claimant = switch (who) { + case "alice" -> alice; + case "mallory" -> mallory; + default -> throw new IllegalArgumentException("unknown claimant: " + who); + }; + var proof = provePredicate(minIncome, minScore); + var gate = credit.gate(bureauPolicy, minIncome, minScore); + String tx = DemoErrors.require(CreditGate.claim(backend, gate, claimant, commitment, record, proof), + who.equals("mallory") ? "Mallory's claim with Alice's credential" : "Alice's claim"); + DevKit.waitForTx(backend, tx); + Map entry = new LinkedHashMap<>(); + entry.put("claimant", who); + entry.put("minIncome", minIncome); + entry.put("minScore", minScore); + entry.put("lenderLearns", "qualifies (income ≥ " + minIncome + ", score ≥ " + minScore + ")"); + entry.put("badgePolicy", Plutus.policyId(gate)); + entry.put("txHash", tx); + claims.add(0, entry); + return entry; + } + + private Groth16ProofBLS381 provePredicate(long minIncome, int minScore) { + try { + return credit.prove(profile, minIncome, minScore); + } catch (RuntimeException e) { + throw new DemoErrors.NoProof("Alice's committed profile does not meet income ≥ " + minIncome + + " and score ≥ " + minScore + ", so no proof exists. The lender learns only that no badge" + + " was claimed.", e); + } + } + + public synchronized Map state() throws Exception { + ensureReady(); + Map body = new LinkedHashMap<>(); + var schema = CreditProfileProof.SCHEMA; + body.put("schema", Map.of("id", schema.id(), "version", schema.version(), + "digest", PointsService.shortHex(schema.digest()), + "entries", schema.entries().stream().map(e -> e.label() + "/" + e.width()).toList())); + body.put("constraints", credit.circuit().numConstraints()); + body.put("holderAddress", alice.baseAddress()); + if (profile != null) { + body.put("private", Map.of("income", profile.income(), "creditScore", profile.creditScore(), + "birthYear", profile.birthYear(), "country", profile.country(), + "blinding", PointsService.shortHex(profile.blinding()))); + var point = commitment.point().normalized(); + body.put("onChain", Map.of( + "recordTx", recordTx, + "recordToken", HexUtil.encodeHexString(CreditGate.recordTokenName(commitment, PointsService.pkh(alice))) + .substring(0, 16) + "…", + "u", PointsService.shortHex(point.affineU()), + "v", PointsService.shortHex(point.affineV()), + "holder", HexUtil.encodeHexString(PointsService.pkh(alice)).substring(0, 16) + "…")); + } + body.put("claims", List.copyOf(claims)); + return body; + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoController.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoController.java new file mode 100644 index 0000000..dd1162d --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoController.java @@ -0,0 +1,167 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.web; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** REST API behind the three tabs. Every action runs on Yaci DevKit; errors map in {@link DemoErrors}. */ +@RestController +@RequestMapping("/api") +@CrossOrigin(origins = "*") +public class DemoController { + + private static final Logger log = LoggerFactory.getLogger(DemoController.class); + + private final PointsService points; + private final CreditService credit; + private final SolvencyService solvency; + private final Map readiness = new ConcurrentHashMap<>( + Map.of("points", "starting", "credit", "starting", "solvency", "starting")); + + public DemoController(PointsService points, CreditService credit, SolvencyService solvency) { + this.points = points; + this.credit = credit; + this.solvency = solvency; + } + + /** Compiles circuits, loads or generates dev keys and funds wallets in the background. */ + @EventListener(ApplicationReadyEvent.class) + public void warmUp() { + warm("points", () -> points.ensureReady()); + warm("credit", () -> credit.ensureReady()); + warm("solvency", () -> solvency.ensureReady()); + } + + private interface Init { + void run() throws Exception; + } + + private void warm(String name, Init init) { + Thread.ofVirtual().name("warm-" + name).start(() -> { + try { + init.run(); + readiness.put(name, "ready"); + log.info("{} demo ready", name); + } catch (Exception e) { + readiness.put(name, "failed: " + e.getMessage()); + log.error("{} demo failed to start", name, e); + } + }); + } + + /** Health and readiness of the three demos. */ + @GetMapping("/status") + public Map status() { + return Map.of("demos", Map.copyOf(readiness), + "ready", readiness.values().stream().allMatch("ready"::equals)); + } + + // --- A. Confidential points ------------------------------------------------------------- + + @GetMapping("/points") + public Map pointsState() throws Exception { + return points.state(); + } + + @PostMapping("/points/issue") + public Map issue(@RequestBody Map r) throws Exception { + return points.issue(str(r, "to"), num(r, "amount")); + } + + @PostMapping("/points/transfer") + public Map transfer(@RequestBody Map r) throws Exception { + return points.transfer(str(r, "from"), str(r, "to"), num(r, "amount")); + } + + @PostMapping("/points/redeem") + public Map redeem(@RequestBody Map r) throws Exception { + return points.redeem(str(r, "from"), num(r, "price")); + } + + @PostMapping("/points/steal") + public Map steal(@RequestBody Map r) throws Exception { + return points.steal(str(r, "thief"), str(r, "victim")); + } + + // --- B. Committed credential ------------------------------------------------------------ + + @GetMapping("/credit") + public Map creditState() throws Exception { + return credit.state(); + } + + @PostMapping("/credit/issue") + public Map issueProfile(@RequestBody Map r) throws Exception { + return credit.issue(num(r, "income"), (int) num(r, "creditScore"), (int) num(r, "birthYear"), + (int) num(r, "country")); + } + + @PostMapping("/credit/claim") + public Map claim(@RequestBody Map r) throws Exception { + return credit.claim(str(r, "who"), num(r, "minIncome"), (int) num(r, "minScore")); + } + + // --- C. Solvency ------------------------------------------------------------------------ + + @GetMapping("/solvency") + public Map solvencyState() throws Exception { + return solvency.state(); + } + + @PostMapping("/solvency/book") + @SuppressWarnings("unchecked") + public Map book(@RequestBody Map r) throws Exception { + return solvency.setBook((List>) r.get("customers")); + } + + @PostMapping("/solvency/attest") + public Map attest(@RequestBody Map r) throws Exception { + return solvency.attest(num(r, "reservesAda")); + } + + @PostMapping("/solvency/attest-again") + public Map attestAgain() throws Exception { + return solvency.attestAgain(); + } + + @PostMapping("/solvency/check") + public Map check(@RequestBody Map r) throws Exception { + return solvency.check(str(r, "id")); + } + + @PostMapping("/solvency/audit") + public Map audit() throws Exception { + return solvency.audit(); + } + + @PostMapping("/solvency/release") + public Map release() throws Exception { + return solvency.release(); + } + + // ---------------------------------------------------------------------------------------- + + private static String str(Map r, String key) { + Object v = r.get(key); + if (v == null) throw new IllegalArgumentException("missing " + key); + return v.toString(); + } + + private static long num(Map r, String key) { + Object v = r.get(key); + if (v instanceof Number n) return n.longValue(); + if (v instanceof String s && !s.isBlank()) return Long.parseLong(s.trim()); + throw new IllegalArgumentException("missing or invalid " + key); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoErrors.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoErrors.java new file mode 100644 index 0000000..2224235 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/DemoErrors.java @@ -0,0 +1,90 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.web; + +import com.bloxbean.cardano.client.api.model.Result; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * The two ways a demo action is refused, mapped to JSON the UI shows: + *

    + *
  • {@link NoProof}: the statement is false, so the prover cannot produce a proof at all + * (nothing reaches the chain);
  • + *
  • {@link Rejected}: a transaction was built, and a validator returned false when the + * transaction was evaluated (locally with Julc, as the node would run it), so it was not + * submitted.
  • + *
+ */ +@RestControllerAdvice +public class DemoErrors { + + private static final Logger log = LoggerFactory.getLogger(DemoErrors.class); + + /** The relation does not hold for this witness: no proof exists. */ + public static class NoProof extends RuntimeException { + public NoProof(String message, Throwable cause) { + super(message, cause); + } + } + + /** A transaction failed; {@link #scriptRejection} tells whether a validator rejected it. */ + public static class Rejected extends RuntimeException { + private final String what; + private final String detail; + + public Rejected(String what, String detail) { + super(what + ": " + detail); + this.what = what; + this.detail = detail; + } + + boolean scriptRejection() { + return detail != null && (detail.contains("Script evaluation failed") + || detail.equals("Error while evaluating script cost")); + } + } + + /** The submitted transaction's hash, or {@link Rejected} if it failed. */ + public static String require(Result result, String what) { + if (!result.isSuccessful()) throw new Rejected(what, String.valueOf(result.getResponse())); + return result.getValue(); + } + + @ExceptionHandler(NoProof.class) + public ResponseEntity> noProof(NoProof e) { + Map body = new LinkedHashMap<>(); + body.put("error", e.getMessage()); + body.put("noProof", true); + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(body); + } + + @ExceptionHandler(Rejected.class) + public ResponseEntity> rejected(Rejected e) { + Map body = new LinkedHashMap<>(); + body.put("error", e.getMessage()); + body.put("onChainRejection", e.scriptRejection()); + if (e.scriptRejection()) { + body.put("onChainValidation", Map.of( + "title", "The on-chain validator rejected this transaction", + "summary", e.what + " was built and evaluated against the real ledger state, and the Plutus script" + + " returned false, so it was not submitted.", + "detail", e.detail.equals("Error while evaluating script cost") + ? e.detail + " — cardano-client-lib reports a failing minting script this way;" + + " the script's own failure trace is in the server log." + : e.detail)); + } + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(body); + } + + @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class}) + public ResponseEntity> badRequest(RuntimeException e) { + log.warn("Request failed: {}", e.getMessage()); + return ResponseEntity.badRequest().body(Map.of("error", String.valueOf(e.getMessage()))); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/Funding.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/Funding.java new file mode 100644 index 0000000..d12c5d7 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/Funding.java @@ -0,0 +1,71 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.web; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.common.model.Networks; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +/** Creates demo wallets and funds them through DevKit's top-up API. */ +@Component +public class Funding { + + private static final Logger log = LoggerFactory.getLogger(Funding.class); + + @Value("${cardano.yaci.admin-url:http://localhost:10000}") + private String adminUrl; + + @Value("${demo.topup.enabled:true}") + private boolean topUpEnabled; + + private final BackendService backend; + + public Funding(BackendService backend) { + this.backend = backend; + } + + /** A fresh wallet with {@code ada} topped up, ready to pay fees and collateral. */ + public Account newWallet(String label, int ada) { + var account = new Account(Networks.testnet()); + if (!topUpEnabled) { + log.warn("Top-up disabled: fund {} at {} yourself", label, account.baseAddress()); + return account; + } + try { + var request = HttpRequest.newBuilder() + .uri(URI.create(adminUrl + "/local-cluster/api/addresses/topup")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString( + "{\"address\":\"" + account.baseAddress() + "\",\"adaAmount\":" + ada + "}")) + .build(); + var response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() / 100 != 2) { + throw new IllegalStateException("top-up returned " + response.statusCode() + ": " + response.body()); + } + waitForFunds(account.baseAddress()); + log.info("Funded {} with {} ADA: {}", label, ada, account.baseAddress()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("interrupted while funding " + label, e); + } catch (Exception e) { + throw new IllegalStateException("could not fund " + label + " via " + adminUrl + ": " + e.getMessage(), e); + } + return account; + } + + private void waitForFunds(String address) throws Exception { + for (int i = 0; i < 40; i++) { + var utxos = backend.getUtxoService().getUtxos(address, 10, 1); + if (utxos.isSuccessful() && utxos.getValue() != null && !utxos.getValue().isEmpty()) return; + Thread.sleep(1_000); + } + throw new IllegalStateException("top-up for " + address + " not visible after 40 s"); + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/PointsService.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/PointsService.java new file mode 100644 index 0000000..4741449 --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/PointsService.java @@ -0,0 +1,302 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.web; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.plutus.spec.BigIntPlutusData; +import com.bloxbean.cardano.client.plutus.spec.BytesPlutusData; +import com.bloxbean.cardano.client.plutus.spec.ConstrPlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusData; +import com.bloxbean.cardano.client.plutus.spec.PlutusScript; +import com.bloxbean.cardano.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; +import com.bloxbean.cardano.zeroj.usecases.pedersen.points.ConfidentialPoints; +import com.bloxbean.cardano.zeroj.usecases.pedersen.points.ConfidentialPoints.Note; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Demo A, confidential points, for the UI. The retailer, Alice and Bob are wallets this server + * creates; the server also keeps each wallet's note openings (amount and blinding) on its + * behalf, which in a real deployment only the owner would hold. On-chain there are only + * commitments. + */ +@Service +public class PointsService { + + private static final Logger log = LoggerFactory.getLogger(PointsService.class); + static final List WALLETS = List.of("retailer", "alice", "bob"); + + private final BackendService backend; + private final Funding funding; + + private ConfidentialPoints points; + private PlutusScript script; + private String ledger; + private String policyId; + private final Map wallets = new LinkedHashMap<>(); + private final Map> notes = new LinkedHashMap<>(); + private final List> history = new ArrayList<>(); + + /** A note this server holds the opening of, and where it sits on-chain. */ + record HeldNote(Note note, String txHash, int index) {} + + public PointsService(BackendService backend, Funding funding) { + this.backend = backend; + this.funding = funding; + } + + /** Compiles the circuits (cached dev keys) and creates the funded wallets, once. */ + synchronized void ensureReady() { + if (points != null) return; + var p = new ConfidentialPoints(); + for (String label : WALLETS) { + wallets.put(label, funding.newWallet("points/" + label, 200)); + notes.put(label, new ArrayList<>()); + } + script = p.script(pkh(wallets.get("retailer"))); + ledger = ConfidentialPoints.address(script); + policyId = Plutus.policyId(script); + points = p; + log.info("Points ledger {} (policy {})", ledger, policyId); + } + + // ------------------------------------------------------------------ + // Actions + // ------------------------------------------------------------------ + + /** The retailer issues {@code amount} points to {@code to}. */ + public synchronized Map issue(String to, long amount) throws Exception { + ensureReady(); + requireHolder(to); + requireAmount(amount); + Note note = Note.of(pkh(wallets.get(to)), amount); + String tx = DemoErrors.require(ConfidentialPoints.issue(backend, script, wallets.get("retailer"), List.of(note)), "Issue"); + DevKit.waitForTx(backend, tx); + notes.get(to).add(locate(tx, note)); + return record("issue", "Retailer issued " + amount + " points to " + to, tx); + } + + /** + * {@code from} sends {@code amount} to {@code to}, splitting one of its notes. Asking for more + * than the note holds is the "cheat": the prover cannot produce a proof that + * {@code in = out1 + out2}. + */ + public synchronized Map transfer(String from, String to, long amount) throws Exception { + ensureReady(); + requireHolder(from); + requireHolder(to); + requireAmount(amount); + HeldNote source = largest(from); + Note out1 = Note.of(pkh(wallets.get(to)), amount); + Note out2 = Note.of(pkh(wallets.get(from)), Math.max(0, source.note().amount() - amount)); + var proof = prove(() -> points.proveTransfer(source.note(), out1, out2), + from + "'s note holds " + source.note().amount() + " points; no proof exists that it splits into " + + amount + " + " + out2.amount()); + String tx = DemoErrors.require(ConfidentialPoints.transfer(backend, script, wallets.get(from), + utxo(source), out1, out2, proof), "Transfer"); + DevKit.waitForTx(backend, tx); + notes.get(from).remove(source); + notes.get(to).add(locate(tx, out1)); + notes.get(from).add(locate(tx, out2)); + return record("transfer", from + " sent " + amount + " points to " + to + " (amounts hidden on-chain)", tx); + } + + /** {@code from} pays a public {@code price} at the retailer and keeps the hidden change. */ + public synchronized Map redeem(String from, long price) throws Exception { + ensureReady(); + requireHolder(from); + requireAmount(price); + if (price >= 1L << 32) throw new IllegalArgumentException("price must be below 2^32"); + HeldNote source = largest(from); + Note change = Note.of(pkh(wallets.get(from)), Math.max(0, source.note().amount() - price)); + var proof = prove(() -> points.proveRedeem(source.note(), change, price), + from + "'s note holds " + source.note().amount() + " points; no proof exists that it pays " + + price + " and keeps " + change.amount()); + String tx = DemoErrors.require(ConfidentialPoints.redeem(backend, script, wallets.get(from), + wallets.get("retailer").baseAddress(), utxo(source), change, price, proof), "Redeem"); + DevKit.waitForTx(backend, tx); + notes.get(from).remove(source); + notes.get(from).add(locate(tx, change)); + return record("redeem", from + " paid " + price + " points at the retailer (price public, balance hidden)", tx); + } + + /** + * The other "cheat": {@code thief} spends one of {@code victim}'s notes. The server even holds + * the victim's opening, so the proof is valid; the validator still rejects the transaction + * because the note's owner did not sign it. + */ + public synchronized Map steal(String thief, String victim) throws Exception { + ensureReady(); + requireHolder(thief); + requireHolder(victim); + if (thief.equals(victim)) throw new IllegalArgumentException("pick two different wallets"); + HeldNote target = largest(victim); + Note toThief = Note.of(pkh(wallets.get(thief)), target.note().amount()); + Note zero = Note.of(pkh(wallets.get(thief)), 0); + var proof = points.proveTransfer(target.note(), toThief, zero); + DemoErrors.require(ConfidentialPoints.transfer(backend, script, wallets.get(thief), utxo(target), + toThief, zero, proof), thief + " spending " + victim + "'s note"); + throw new IllegalStateException("unexpected: the ledger accepted a spend without the owner's signature"); + } + + // ------------------------------------------------------------------ + // State for the UI + // ------------------------------------------------------------------ + + public synchronized Map state() throws Exception { + ensureReady(); + Map privateView = new LinkedHashMap<>(); + for (String label : WALLETS) { + List> held = new ArrayList<>(); + long total = 0; + for (HeldNote h : notes.get(label)) { + total += h.note().amount(); + held.add(Map.of("amount", h.note().amount(), + "commitment", shortHex(h.note().commitment().affineU()), + "utxo", h.txHash().substring(0, 12) + "…#" + h.index())); + } + privateView.put(label, Map.of("address", wallets.get(label).baseAddress(), + "balance", total, "notes", held)); + } + + List> onChain = new ArrayList<>(); + for (Utxo u : utxosAt(ledger)) { + ConstrPlutusData d = datum(u); + if (d == null || !holdsNoteToken(u)) continue; + var f = d.getData().getPlutusDataList(); + onChain.add(Map.of( + "utxo", u.getTxHash().substring(0, 12) + "…#" + u.getOutputIndex(), + "owner", labelOf(((BytesPlutusData) f.get(0)).getValue()), + "u", shortHex(((BigIntPlutusData) f.get(1)).getValue()), + "v", shortHex(((BigIntPlutusData) f.get(2)).getValue()))); + } + List> receipts = new ArrayList<>(); + for (Utxo u : utxosAt(wallets.get("retailer").baseAddress())) { + boolean receipt = u.getAmount().stream().anyMatch(a -> a.getUnit().startsWith(policyId) + && a.getUnit().length() == policyId.length() + 64); + ConstrPlutusData d = datum(u); + if (!receipt || d == null) continue; + var f = d.getData().getPlutusDataList(); + receipts.add(Map.of("utxo", u.getTxHash().substring(0, 12) + "…#" + u.getOutputIndex(), + "spender", labelOf(((BytesPlutusData) f.get(0)).getValue()), + "price", ((BigIntPlutusData) f.get(1)).getValue())); + } + + Map body = new LinkedHashMap<>(); + body.put("policyId", policyId); + body.put("ledgerAddress", ledger); + body.put("private", privateView); + body.put("onChain", onChain); + body.put("receipts", receipts); + body.put("history", List.copyOf(history)); + body.put("constraints", Map.of("transfer", points.transferCircuit().numConstraints(), + "redeem", points.redeemCircuit().numConstraints())); + return body; + } + + // ------------------------------------------------------------------ + + private interface Prover { + T prove(); + } + + private static T prove(Prover prover, String noProofMessage) { + try { + return prover.prove(); + } catch (RuntimeException e) { + throw new DemoErrors.NoProof(noProofMessage, e); + } + } + + private HeldNote largest(String label) { + return notes.get(label).stream().max(Comparator.comparingLong(h -> h.note().amount())) + .orElseThrow(() -> new IllegalStateException(label + " holds no notes yet; issue some points first")); + } + + /** The output of {@code tx} at the ledger whose datum commits to {@code note}. */ + private HeldNote locate(String tx, Note note) throws Exception { + for (Utxo u : DevKit.utxosOf(backend, ledger, tx)) { + ConstrPlutusData d = datum(u); + if (d == null) continue; + var f = d.getData().getPlutusDataList(); + if (((BigIntPlutusData) f.get(1)).getValue().equals(note.commitment().affineU()) + && ((BigIntPlutusData) f.get(2)).getValue().equals(note.commitment().affineV())) { + return new HeldNote(note, tx, u.getOutputIndex()); + } + } + throw new IllegalStateException("note output of " + tx + " not found"); + } + + private Utxo utxo(HeldNote h) throws Exception { + return DevKit.utxosOf(backend, ledger, h.txHash()).stream() + .filter(u -> u.getOutputIndex() == h.index()).findFirst() + .orElseThrow(() -> new IllegalStateException("note " + h.txHash() + "#" + h.index() + " is spent")); + } + + private boolean holdsNoteToken(Utxo u) { + String unit = policyId + HexUtil.encodeHexString(ConfidentialPoints.NOTE_TOKEN); + return u.getAmount().stream().anyMatch(a -> a.getUnit().equals(unit)); + } + + private List utxosAt(String address) throws Exception { + List all = new ArrayList<>(); + for (int page = 1; ; page++) { + var r = backend.getUtxoService().getUtxos(address, 100, page); + if (!r.isSuccessful() || r.getValue() == null || r.getValue().isEmpty()) break; + all.addAll(r.getValue()); + if (r.getValue().size() < 100) break; + } + return all; + } + + private static ConstrPlutusData datum(Utxo u) { + try { + if (u.getInlineDatum() == null || u.getInlineDatum().isEmpty()) return null; + var d = PlutusData.deserialize(HexUtil.decodeHexString(u.getInlineDatum())); + return d instanceof ConstrPlutusData c ? c : null; + } catch (Exception e) { + return null; + } + } + + private String labelOf(byte[] pkh) { + for (var e : wallets.entrySet()) { + if (Arrays.equals(pkh(e.getValue()), pkh)) return e.getKey(); + } + return HexUtil.encodeHexString(pkh).substring(0, 10) + "…"; + } + + private Map record(String action, String summary, String tx) { + var entry = Map.of("action", action, "summary", summary, "txHash", tx); + history.add(0, entry); + return entry; + } + + private void requireHolder(String label) { + if (!wallets.containsKey(label)) throw new IllegalArgumentException("unknown wallet: " + label); + } + + private static void requireAmount(long amount) { + if (amount <= 0) throw new IllegalArgumentException("amount must be positive"); + } + + static byte[] pkh(Account account) { + return account.hdKeyPair().getPublicKey().getKeyHash(); + } + + static String shortHex(BigInteger value) { + String hex = value.toString(16); + return hex.substring(0, Math.min(14, hex.length())) + "…"; + } +} diff --git a/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/SolvencyService.java b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/SolvencyService.java new file mode 100644 index 0000000..a70a54a --- /dev/null +++ b/pedersen-commitments/src/main/java/com/bloxbean/cardano/zeroj/usecases/pedersen/web/SolvencyService.java @@ -0,0 +1,240 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.web; + +import com.bloxbean.cardano.client.account.Account; +import com.bloxbean.cardano.client.api.model.Utxo; +import com.bloxbean.cardano.client.backend.api.BackendService; +import com.bloxbean.cardano.client.plutus.spec.PlutusScript; +import com.bloxbean.cardano.client.util.HexUtil; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.DevKit; +import com.bloxbean.cardano.zeroj.usecases.pedersen.common.Plutus; +import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation; +import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation.Customer; +import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation.Period; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.zeroj.crypto.groth16.Groth16ProofBLS381; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Demo C, solvency with hidden liabilities, for the UI. The exchange is a wallet this server + * creates; the server keeps every customer's balance, salt and blinding (their openings) on their + * behalf. On-chain there is one commitment per customer and the locked reserve. + */ +@Service +public class SolvencyService { + + static final int CUSTOMERS = 4; + private static final long LOVELACE = 1_000_000L; + + @Value("${solvency.period-lead-seconds:45}") + private long leadSeconds = 45; + + @Value("${solvency.period-length-seconds:180}") + private long lengthSeconds = 180; + + private final BackendService backend; + private final Funding funding; + + private SolvencyAttestation solvency; + private Account exchange; + private List book = List.of(); + + private Period period; + private PlutusScript vault; + private String attestTx; + private long attestedReserves; + private String releaseTx; + private final Map lastChecks = new LinkedHashMap<>(); + + public SolvencyService(BackendService backend, Funding funding) { + this.backend = backend; + this.funding = funding; + } + + synchronized void ensureReady() { + if (solvency != null) return; + var s = new SolvencyAttestation(CUSTOMERS); + exchange = funding.newWallet("solvency/exchange", 5_000); + book = List.of(Customer.of("alice", 500 * LOVELACE), Customer.of("bob", 1_200 * LOVELACE), + Customer.of("carol", 300 * LOVELACE), Customer.of("dave", 0)); + solvency = s; + } + + /** Replaces the book (four customers, balances in ADA) while no attestation is live. */ + public synchronized Map setBook(List> rows) throws Exception { + ensureReady(); + if (live()) throw new IllegalStateException("an attestation is live; release it after its period first"); + if (rows == null || rows.size() != CUSTOMERS) { + throw new IllegalArgumentException("the circuit takes exactly " + CUSTOMERS + " customers (pad with 0 balances)"); + } + List next = new ArrayList<>(); + var ids = new HashSet(); + for (var row : rows) { + String id = String.valueOf(row.get("id")).trim(); + long ada = ((Number) row.get("balance")).longValue(); + if (id.isEmpty() || !ids.add(id)) throw new IllegalArgumentException("customer ids must be unique and non-empty"); + if (ada < 0 || ada > 1_000_000_000L) throw new IllegalArgumentException("balance out of range"); + next.add(Customer.of(id, ada * LOVELACE)); + } + book = List.copyOf(next); + period = null; + vault = null; + attestTx = null; + releaseTx = null; + lastChecks.clear(); + return Map.of("summary", "Book updated with fresh salts and blindings"); + } + + /** + * Locks {@code reservesAda} for a new period that starts {@code leadSeconds} from now. An + * insolvent book has no proof. + */ + public synchronized Map attest(long reservesAda) throws Exception { + ensureReady(); + if (live()) throw new IllegalStateException("an attestation is already live; release it after its period"); + if (reservesAda <= 0) throw new IllegalArgumentException("reserves must be positive"); + long reserves = reservesAda * LOVELACE; + long now = DevKit.chainTimeMillis(backend); + Period next = new Period(now + leadSeconds * 1000, now + (leadSeconds + lengthSeconds) * 1000); + var proof = proveSolvent(reserves); + PlutusScript v = solvency.vault(PointsService.pkh(exchange), next); + String tx = DemoErrors.require(SolvencyAttestation.attest(backend, v, exchange, reserves, + SolvencyAttestation.entries(book), proof, DevKit.slotAt(backend, next.start())), "Attestation"); + DevKit.waitForTx(backend, tx); + period = next; + vault = v; + attestTx = tx; + attestedReserves = reserves; + releaseTx = null; + lastChecks.clear(); + return Map.of("summary", "Exchange locked " + reservesAda + " ADA and attested for the period", "txHash", tx); + } + + /** + * The "cheat": add a second attestation for the same period once it has begun (here, the same + * book again). The vault refuses anything whose validity range ends after the period start. + */ + public synchronized Map attestAgain() throws Exception { + ensureReady(); + if (vault == null) throw new IllegalStateException("attest first"); + var proof = proveSolvent(attestedReserves); + long until = DevKit.chainTimeMillis(backend) + 60_000; + DemoErrors.require(SolvencyAttestation.attest(backend, vault, exchange, attestedReserves, + SolvencyAttestation.entries(book), proof, DevKit.slotAt(backend, until)), + "A second attestation inside the period"); + throw new IllegalStateException("unexpected: the vault accepted an attestation after the period start"); + } + + /** A customer's check: listed exactly once across the period's attestations, entry opens. */ + public synchronized Map check(String id) throws Exception { + ensureReady(); + if (vault == null) throw new IllegalStateException("attest first"); + Customer customer = book.stream().filter(c -> c.id().equals(id)).findFirst() + .orElseThrow(() -> new IllegalArgumentException("unknown customer: " + id)); + boolean ok = SolvencyAttestation.customerCheck(SolvencyAttestation.liveEntries(backend, vault), customer); + String verdict = ok ? "listed exactly once, and the entry opens to the balance" : "MISSING OR WRONG"; + lastChecks.put(id, verdict); + return Map.of("customer", id, "ok", ok, "verdict", verdict, "phase", phase()); + } + + /** The auditor opens the sum of all commitments with (L, Σr) and learns L, nothing else. */ + public synchronized Map audit() throws Exception { + ensureReady(); + if (vault == null) throw new IllegalStateException("attest first"); + var opening = SolvencyAttestation.auditOpening(book); + boolean ok = SolvencyAttestation.auditorCheck(SolvencyAttestation.liveEntries(backend, vault), opening); + return Map.of("ok", ok, + "summary", ok ? "Auditor opened the sum of all on-chain commitments" : "The aggregate opening did not verify", + "liabilitiesAda", opening.liabilities().divide(BigInteger.valueOf(LOVELACE)), + "reservesAda", attestedReserves / LOVELACE); + } + + /** Releases the reserve; before the period ends the vault rejects it. */ + public synchronized Map release() throws Exception { + ensureReady(); + if (vault == null || attestTx == null || releaseTx != null) throw new IllegalStateException("nothing to release"); + Utxo live = liveUtxo(); + long now = DevKit.chainTimeMillis(backend); + long from = now < period.end() ? DevKit.slotAt(backend, now) : DevKit.slotAt(backend, period.end()) + 1; + String tx = DemoErrors.require(SolvencyAttestation.release(backend, vault, exchange, live, from), + now < period.end() ? "A release inside the period" : "Release"); + DevKit.waitForTx(backend, tx); + releaseTx = tx; + return Map.of("summary", "Reserve released after the period; attestation token burned", "txHash", tx); + } + + public synchronized Map state() throws Exception { + ensureReady(); + Map body = new LinkedHashMap<>(); + long now = DevKit.chainTimeMillis(backend); + body.put("chainTime", now); + body.put("phase", phase()); + body.put("constraints", solvency.circuit().numConstraints()); + body.put("exchangeAddress", exchange.baseAddress()); + List> privateBook = new ArrayList<>(); + long total = 0; + for (Customer c : book) { + total += c.balance(); + privateBook.add(Map.of("id", c.id(), "balance", c.balance() / LOVELACE, + "salt", HexUtil.encodeHexString(c.salt()).substring(0, 12) + "…", + "blinding", PointsService.shortHex(c.blinding()), + "idHash", HexUtil.encodeHexString(c.idHash()).substring(0, 12) + "…", + "check", lastChecks.getOrDefault(c.id(), ""))); + } + body.put("book", privateBook); + body.put("liabilitiesAda", total / LOVELACE); + if (period != null) { + body.put("period", Map.of("start", period.start(), "end", period.end())); + body.put("vaultAddress", SolvencyAttestation.address(vault)); + body.put("vaultPolicy", Plutus.policyId(vault)); + body.put("attestTx", attestTx); + body.put("reservesAda", attestedReserves / LOVELACE); + if (releaseTx != null) body.put("releaseTx", releaseTx); + List> entries = new ArrayList<>(); + for (var e : SolvencyAttestation.liveEntries(backend, vault)) { + entries.add(Map.of("idHash", HexUtil.encodeHexString(e.idHash()).substring(0, 12) + "…", + "u", PointsService.shortHex(e.commitment().affineU()))); + } + body.put("onChain", entries); + } + return body; + } + + // ------------------------------------------------------------------ + + private Groth16ProofBLS381 proveSolvent(long reserves) { + try { + return solvency.prove(reserves, book); + } catch (RuntimeException e) { + long liabilities = book.stream().mapToLong(Customer::balance).sum(); + throw new DemoErrors.NoProof("Liabilities (" + liabilities / LOVELACE + " ADA) exceed the reserves (" + + reserves / LOVELACE + " ADA), so no proof of solvency exists.", e); + } + } + + private boolean live() { + return attestTx != null && releaseTx == null; + } + + private String phase() throws Exception { + if (period == null) return "none"; + if (releaseTx != null) return "released"; + long now = DevKit.chainTimeMillis(backend); + if (now < period.start()) return "before"; + if (now <= period.end()) return "during"; + return "after"; + } + + private Utxo liveUtxo() throws Exception { + String unit = Plutus.policyId(vault) + HexUtil.encodeHexString(SolvencyAttestation.ATTEST_TOKEN); + return DevKit.utxosOf(backend, SolvencyAttestation.address(vault), attestTx).stream() + .filter(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().equals(unit))) + .findFirst().orElseThrow(() -> new IllegalStateException("the attestation output is not live")); + } +} diff --git a/pedersen-commitments/src/main/resources/application.yml b/pedersen-commitments/src/main/resources/application.yml new file mode 100644 index 0000000..9ecd817 --- /dev/null +++ b/pedersen-commitments/src/main/resources/application.yml @@ -0,0 +1,26 @@ +server: + port: 8093 + +spring: + application: + name: pedersen-commitments-demo + +cardano: + # The demos create and fund their own wallets with DevKit's top-up API, so they run on DevKit. + network: yaci + yaci: + base-url: http://localhost:8080/api/v1/ + admin-url: http://localhost:10000 + blockfrost: + # Overrides the provider (for example from Docker); empty means use cardano.yaci.base-url. + base-url: "" + project-id: "" + +demo: + topup: + enabled: true + +solvency: + # An attestation must be made before its period starts and released after it ends. + period-lead-seconds: 45 + period-length-seconds: 180 diff --git a/pedersen-commitments/src/main/resources/static/assets/index-DTT4oLQg.js b/pedersen-commitments/src/main/resources/static/assets/index-DTT4oLQg.js new file mode 100644 index 0000000..3296d08 --- /dev/null +++ b/pedersen-commitments/src/main/resources/static/assets/index-DTT4oLQg.js @@ -0,0 +1,15 @@ +var Ia=Object.defineProperty;var bi=e=>{throw TypeError(e)};var qa=(e,t,r)=>t in e?Ia(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ye=(e,t,r)=>qa(e,typeof t!="symbol"?t+"":t,r),Pn=(e,t,r)=>t.has(e)||bi("Cannot "+r);var o=(e,t,r)=>(Pn(e,t,"read from private field"),r?r.call(e):t.get(e)),q=(e,t,r)=>t.has(e)?bi("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),P=(e,t,r,n)=>(Pn(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),z=(e,t,r)=>(Pn(e,t,"access private method"),r);(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))n(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const l of a.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function n(i){if(i.ep)return;i.ep=!0;const a=r(i);fetch(i.href,a)}})();const Fa="5";var Ri;typeof window<"u"&&((Ri=window.__svelte??(window.__svelte={})).v??(Ri.v=new Set)).add(Fa);const $a=1,La=2,Di=4,za=8,ja=16,Ha=1,Va=2,ue=Symbol("uninitialized"),Ii=!1;var En=Array.isArray,Ba=Array.prototype.indexOf,hn=Array.prototype.includes,An=Array.from,qi=Object.defineProperty,Br=Object.getOwnPropertyDescriptor,Ya=Object.prototype,Ua=Array.prototype,Ga=Object.getPrototypeOf,gi=Object.isExtensible;const Ka=()=>{};function Wa(e){for(var t=0;t{e=n,t=i});return{promise:r,resolve:e,reject:t}}function $i(e,t){if(Array.isArray(e))return e;if(!(Symbol.iterator in e))return Array.from(e);const r=[];for(const n of e)if(r.push(n),r.length===t)break;return r}const Ee=2,Ar=4,Sn=8,Li=1<<24,ht=16,at=32,Ft=64,zn=128,ti=256,pt=512,fe=1024,se=2048,it=4096,Ne=8192,Ie=16384,Nr=32768,jn=1<<25,Sr=65536,_n=1<<17,Ja=1<<18,Pr=1<<19,Xa=1<<20,Et=1<<25,pn=1<<21,pr=1<<22,Yt=1<<23,Yr=Symbol("$state"),zi=Symbol("component"),Za=Symbol("attributes"),Hn=Symbol("class"),Qa=Symbol("style"),$r=Symbol("text"),fn=Symbol("form reset"),nn=new class extends Error{constructor(){super(...arguments);Ye(this,"name","StaleReactionError");Ye(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};function es(){console.warn("https://svelte.dev/e/derived_inert")}function ts(){console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function rs(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}function ji(e){return e===this.v}function ns(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function Hi(e){return!ns(e,this.v)}function is(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function as(e,t,r){throw new Error("https://svelte.dev/e/each_key_duplicate")}function ss(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function ls(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function os(e){throw new Error("https://svelte.dev/e/effect_orphan")}function us(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function fs(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function cs(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function ds(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function vs(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}let hs=!1,qe=null;function Tr(e){qe=e}function Rr(e,t=!1,r){qe={p:qe,i:!1,c:null,e:null,s:e,x:null,r:U,l:null}}function Mr(e){var t=qe,r=t.e;if(r!==null){t.e=null;for(var n of r)fa(n)}return t.i=!0,qe=t.p,Vi(e)}function Vi(e={}){return qi(e,zi,{value:!0}),e}function Bi(){return!0}let Zt=[];function Yi(){var e=Zt;Zt=[],Wa(e)}function Bt(e){if(Zt.length===0&&!Gr){var t=Zt;queueMicrotask(()=>{t===Zt&&Yi()})}Zt.push(e)}function _s(){for(;Zt.length>0;)Yi()}const ps=-7169;function ae(e,t){e.f=e.f&ps|t}function ri(e){(e.f&pt)!==0||e.deps===null?ae(e,fe):ae(e,it)}function Ui(e,t,r){(e.f&se)!==0?t.add(e):(e.f&it)!==0&&r.add(e),ae(e,fe)}let yi=!1;function ms(){yi||(yi=!0,document.addEventListener("reset",e=>{Promise.resolve().then(()=>{var t;if(!e.defaultPrevented)for(const r of e.target.elements)(t=r[fn])==null||t.call(r)})},{capture:!0}))}function an(e){var t=j,r=U;st(null),Ct(null);try{return e()}finally{st(t),Ct(r)}}function Gi(e,t,r,n=r){e.addEventListener(t,()=>an(r));const i=e[fn];i?e[fn]=()=>{i(),n(!0)}:e[fn]=()=>n(!0),ms()}function bs(e,t,r,n){const i=ni;var a=e.filter(_=>!_.settled),l=t.map(i);if(r.length===0&&a.length===0){n(l);return}var f=U,c=gs(),d=a.length===1?a[0].promise:a.length>1?Promise.all(a.map(_=>_.promise)):null;function h(_){if((f.f&Ie)===0){c();try{n([...l,..._])}catch(p){kt(p,f)}mn()}}var g=Ki();if(r.length===0){d.then(()=>h([])).finally(g);return}function b(){Promise.all(r.map(_=>ys(_))).then(h).catch(_=>kt(_,f)).finally(g)}d?d.then(()=>{c(),b(),mn()}):b()}function gs(){var e=U,t=j,r=qe,n=A;return function(a=!0){Ct(e),st(t),Tr(r),a&&(e.f&Ie)===0&&(n==null||n.activate(),n==null||n.apply())}}function mn(e=!0){Ct(null),st(null),Tr(null),e&&(A==null||A.deactivate())}function Ki(){var e=U,t=e.b,r=A,n=!!(t!=null&&t.is_rendered());return t==null||t.update_pending_count(1,r),r.increment(n,e),()=>{t==null||t.update_pending_count(-1,r),r.decrement(n,e)}}function ni(e){var t=Ee|se;return U!==null&&(U.f|=Pr),{ctx:qe,deps:null,effects:null,equals:ji,f:t,fn:e,reactions:null,rv:0,v:ue,wv:0,parent:U,ac:null}}const Lr=Symbol("obsolete");function ys(e,t,r){let n=U;n===null&&is();var i=void 0,a=fr(ue),l=!j,f=new Set;return $s(()=>{var _,p;var c=U,d=Fi();i=d.promise;try{Promise.resolve(e()).then(d.resolve,w=>{w!==nn&&d.reject(w)}).finally(mn)}catch(w){d.reject(w),mn()}var h=A;if(l){if((c.f&Nr)!==0)var g=Ki();if((_=n.b)!=null&&_.is_rendered())(p=h.async_deriveds.get(c))==null||p.reject(Lr);else for(const w of f.values())w.reject(Lr);f.add(d),h.async_deriveds.set(c,d)}const b=(w,m=void 0)=>{g==null||g(),f.delete(d),m!==Lr&&(h.activate(),m?(a.f|=Yt,Cr(a,m)):((a.f&Yt)!==0&&(a.f^=Yt),Cr(a,w)),h.deactivate())};d.promise.then(b,w=>b(null,w||"unknown"))}),ua(()=>{for(const c of f)c.reject(Lr)}),new Promise(c=>{function d(h){function g(){h===i?c(a):d(i)}h.then(g,g)}d(i)})}function ii(e){const t=ni(e);return pa(t),t}function ws(e){const t=ni(e);return t.equals=Hi,t}function xs(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r{r.ac.abort(nn),r.ac=null}),r.fn!==null&&(r.teardown=Ka),Xr(r,0),fi(r))}function Ji(e){if(e.effects!==null)for(const t of e.effects)t.teardown&&t.fn!==null&&Or(t)}let Rn=null,cr=null,A=null,Ur=null,be=null,Vn=null,Gr=!1,Mn=!1,Kr=null,cn=null;var wi=0;let Es=1;var br,Ht,rr,gr,yr,wr,Mt,xr,Ue,Zr,Dt,dt,yt,kr,nr,Y,Bn,Yn,zr,Un,Xi,Zi,_r,As,jr;const wn=class wn{constructor(){q(this,Y);Ye(this,"id",Es++);q(this,br,!1);Ye(this,"linked",!0);q(this,Ht,null);q(this,rr,null);Ye(this,"async_deriveds",new Map);Ye(this,"current",new Map);Ye(this,"previous",new Map);q(this,gr,new Set);q(this,yr,new Set);q(this,wr,0);q(this,Mt,new Map);q(this,xr,null);q(this,Ue,[]);q(this,Zr,[]);q(this,Dt,new Set);q(this,dt,new Set);q(this,yt,new Map);q(this,kr,new Set);Ye(this,"is_fork",!1);q(this,nr,!1);cr===null?Rn=cr=this:(P(cr,rr,this),P(this,Ht,cr)),cr=this}skip_effect(t){o(this,yt).has(t)||o(this,yt).set(t,{d:[],m:[]}),o(this,kr).delete(t)}unskip_effect(t,r=n=>this.schedule(n)){var n=o(this,yt).get(t);if(n){o(this,yt).delete(t);for(var i of n.d)ae(i,se),r(i);for(i of n.m)ae(i,it),r(i)}o(this,kr).add(t)}capture(t,r,n=!1){t.v!==ue&&!this.previous.has(t)&&this.previous.set(t,t.v),(t.f&Yt)===0&&(this.current.set(t,[r,n]),be==null||be.set(t,r)),this.is_fork||(t.v=r)}activate(){A=this}deactivate(){A=null,be=null}flush(){try{Mn=!0,A=this,z(this,Y,zr).call(this)}finally{wi=0,Vn=null,Kr=null,cn=null,Mn=!1,A=null,be=null,At.clear()}}discard(){var t;for(const r of o(this,yr))r(this);o(this,yr).clear();for(const r of this.async_deriveds.values())r.reject(Lr);z(this,Y,jr).call(this),(t=o(this,xr))==null||t.resolve()}register_created_effect(t){o(this,Zr).push(t)}increment(t,r){if(P(this,wr,o(this,wr)+1),t){let n=o(this,Mt).get(r)??0;o(this,Mt).set(r,n+1)}}decrement(t,r){if(P(this,wr,o(this,wr)-1),t){let n=o(this,Mt).get(r)??0;n===1?o(this,Mt).delete(r):o(this,Mt).set(r,n-1)}o(this,nr)||(P(this,nr,!0),Bt(()=>{P(this,nr,!1),this.linked&&this.flush()}))}transfer_effects(t,r){for(const n of t)o(this,Dt).add(n);for(const n of r)o(this,dt).add(n);t.clear(),r.clear()}oncommit(t){o(this,gr).add(t)}ondiscard(t){o(this,yr).add(t)}settled(){return(o(this,xr)??P(this,xr,Fi())).promise}static ensure(){if(A===null){const t=A=new wn;!Mn&&!Gr&&Bt(()=>{o(t,br)||t.flush()})}return A}apply(){{be=null;return}}schedule(t){var r;if(Vn=t,(r=t.b)!=null&&r.is_pending&&(t.f&(Ar|Sn|Li))!==0&&(t.f&Nr)===0){t.b.defer_effect(t);return}o(this,Ue).push(t)}};br=new WeakMap,Ht=new WeakMap,rr=new WeakMap,gr=new WeakMap,yr=new WeakMap,wr=new WeakMap,Mt=new WeakMap,xr=new WeakMap,Ue=new WeakMap,Zr=new WeakMap,Dt=new WeakMap,dt=new WeakMap,yt=new WeakMap,kr=new WeakMap,nr=new WeakMap,Y=new WeakSet,Bn=function(){if(this.is_fork)return!0;for(const n of o(this,Mt).keys()){for(var t=n,r=!1;t.parent!==null;){if(o(this,yt).has(t)){r=!0;break}t=t.parent}if(!r)return!0}return!1},Yn=function(){var t=[];for(const a of o(this,Ue))if(!((a.f&Ie)!==0||(a.f&(se|it))===0)){for(var r=a,n=!1;r.parent!==null;){r=r.parent;var i=r.f;if((i&(Ft|at))!==0){if((i&fe)===0){n=!0;break}r.f^=fe}}n||t.push(r)}return P(this,Ue,[]),t},zr=function(){var f,c,d,h;P(this,br,!0);for(const g of o(this,Dt))o(this,dt).delete(g),ae(g,se),this.schedule(g);for(const g of o(this,dt))ae(g,it),this.schedule(g);this.apply();for(var t=Kr=[],r=[],n=cn=[];o(this,Ue).length>0;){wi++>1e3&&(z(this,Y,jr).call(this),Ts());for(const g of z(this,Y,Yn).call(this))try{z(this,Y,Un).call(this,g,t,r)}catch(b){throw ta(g),z(this,Y,Bn).call(this)||this.discard(),b}}if(A=null,n.length>0){var i=wn.ensure();for(const g of n)i.schedule(g)}if(Kr=null,cn=null,z(this,Y,Bn).call(this)){z(this,Y,_r).call(this,r),z(this,Y,_r).call(this,t);for(const[g,b]of o(this,yt))ea(g,b);n.length>0&&z(f=A,Y,zr).call(f);return}const a=z(this,Y,Xi).call(this);if(a){z(this,Y,_r).call(this,r),z(this,Y,_r).call(this,t),z(c=a,Y,Zi).call(c,this);return}o(this,Dt).clear(),o(this,dt).clear();for(const g of o(this,gr))g(this);o(this,gr).clear(),Ur=this,xi(r),xi(t),Ur=null,(d=o(this,xr))==null||d.resolve();var l=A;if(o(this,wr)===0&&(o(this,Ue).length===0||l!==null)&&z(this,Y,jr).call(this),o(this,Ue).length>0)if(l!==null){for(const g of o(this,Ue))o(l,Ue).push(g);P(this,Ue,[])}else l=this;l!==null&&(At.clear(),z(h=l,Y,zr).call(h))},Un=function(t,r,n){t.f^=fe;for(var i=t.first;i!==null;){var a=i.f,l=(a&(at|Ft))!==0,f=l&&(a&fe)!==0,c=f||(a&Ne)!==0||o(this,yt).has(i);if(!c&&i.fn!==null){l?i.f^=fe:(a&Ar)!==0?r.push(i):ln(i)&&((a&ht)!==0&&o(this,dt).add(i),Or(i));var d=i.first;if(d!==null){i=d;continue}}for(;i!==null;){var h=i.next;if(h!==null){i=h;break}i=i.parent}}},Xi=function(){for(var t=o(this,Ht);t!==null;){if(!t.is_fork){for(const[r,[,n]]of this.current)if(t.current.has(r)&&!n)return t}t=o(t,Ht)}return null},Zi=function(t){var n;for(const[i,a]of t.current)!this.previous.has(i)&&t.previous.has(i)&&this.previous.set(i,t.previous.get(i)),this.current.set(i,a);for(const[i,a]of t.async_deriveds){const l=this.async_deriveds.get(i);l&&a.promise.then(l.resolve).catch(l.reject)}t.async_deriveds.clear(),this.transfer_effects(o(t,Dt),o(t,dt));const r=i=>{var a=i.reactions;if(a!==null&&!((i.f&Ee)!==0&&(i.f&(se|it))===0))for(const c of a){var l=c.f;if((l&Ee)!==0)r(c);else{var f=c;l&(pr|ht)&&!this.async_deriveds.has(f)&&(o(this,dt).delete(f),ae(f,se),this.schedule(f))}}};for(const i of this.current.keys())r(i);this.oncommit(()=>t.discard()),z(n=t,Y,jr).call(n),A=this,z(this,Y,zr).call(this)},_r=function(t){for(var r=0;r!_.current.get(p)[1]);if(!(!o(_,br)||i.length===0)){var a=i.filter(p=>!this.current.has(p));if(a.length===0)t&&_.discard();else if(r.length>0){if(t)for(const p of o(this,kr))_.unskip_effect(p,w=>{var m;(w.f&(ht|pr))!==0?_.schedule(w):z(m=_,Y,_r).call(m,[w])});_.activate();var l=new Set,f=new Map;for(var c of r)Qi(c,a,l,f);f=new Map;var d=[..._.current].filter(([p,w])=>{const m=this.current.get(p);return m?m[0]!==w[0]||m[1]!==w[1]:!0}).map(([p])=>p);if(d.length>0)for(const p of o(this,Zr))(p.f&(Ie|Ne|_n))===0&&si(p,d,f)&&((p.f&(pr|ht))!==0?(ae(p,se),_.schedule(p)):o(_,Dt).add(p));if(o(_,Ue).length>0&&!o(_,nr)){_.apply();for(var h of z(g=_,Y,Yn).call(g))z(b=_,Y,Un).call(b,h,[],[])}_.deactivate()}}}},jr=function(){if(this.linked){var t=o(this,Ht),r=o(this,rr);t===null?Rn=r:P(t,rr,r),r===null?cr=t:P(r,Ht,t),this.linked=!1}};let ur=wn;function Ss(e){var t=Gr;Gr=!0;try{for(var r;;){if(_s(),A===null)return r;A.flush()}}finally{Gr=t}}function Ts(){try{us()}catch(e){kt(e,Vn)}}let ct=null;function xi(e){var t=e.length;if(t!==0){for(var r=0;r0)){At.clear();for(const i of ct){if((i.f&(Ie|Ne))!==0)continue;const a=[i];let l=i.parent;for(;l!==null;)ct.has(l)&&(ct.delete(l),a.push(l)),l=l.parent;for(let f=a.length-1;f>=0;f--){const c=a[f];(c.f&(Ie|Ne))===0&&Or(c)}}ct.clear()}}ct=null}}function Qi(e,t,r,n){if(!r.has(e)&&(r.add(e),e.reactions!==null))for(const i of e.reactions){const a=i.f;(a&Ee)!==0?Qi(i,t,r,n):(a&(pr|ht))!==0&&(a&se)===0&&si(i,t,n)&&(ae(i,se),li(i))}}function si(e,t,r){const n=r.get(e);if(n!==void 0)return n;if(e.deps!==null)for(const i of e.deps){if(hn.call(t,i))return!0;if((i.f&Ee)!==0&&si(i,t,r))return r.set(i,!0),!0}return r.set(e,!1),!1}function li(e){A.schedule(e)}function ea(e,t){if(!((e.f&at)!==0&&(e.f&fe)!==0)){(e.f&se)!==0?t.d.push(e):(e.f&it)!==0&&t.m.push(e),ae(e,fe);for(var r=e.first;r!==null;)ea(r,t),r=r.next}}function ta(e){ae(e,fe);for(var t=e.first;t!==null;)ta(t),t=t.next}let bn=new Set;const At=new Map;let ra=!1;function fr(e,t){var r={f:0,v:e,reactions:null,equals:ji,rv:0,wv:0};return r}function H(e,t){const r=fr(e);return pa(r),r}function Cs(e,t=!1,r=!0){const n=fr(e);return t||(n.equals=Hi),n}function R(e,t,r=!1){j!==null&&(!_t||(j.f&_n)!==0)&&Bi()&&(j.f&(Ee|ht|pr|_n))!==0&&(Tt===null||!Tt.has(e))&&ds();let n=r?Qt(t):t;return Cr(e,n,cn)}var Xt=null,Gn=0;function Cr(e,t,r=null){if(!e.equals(t)){Ut?At.set(e,t):At.has(e)||At.set(e,e.v);var n=ur.ensure();if(n.capture(e,t),(e.f&Ee)!==0){const i=e;(e.f&se)!==0&&ai(i),be===null&&ri(i)}e.wv=ba(),Xt=null,Gn=0,na(e,se,r),Xt=null,U!==null&&(U.f&fe)!==0&&(U.f&(at|Ft))===0&&(Qe===null?js([e]):Qe.push(e)),!n.is_fork&&bn.size>0&&!ra&&Os()}return t}function Os(){ra=!1;for(const e of bn){(e.f&fe)!==0&&ae(e,it);let t;try{t=ln(e)}catch{t=!0}t&&Or(e)}bn.clear()}function Wr(e){R(e,e.v+1)}function na(e,t,r){var n=e.reactions;if(n!==null){var i=n.length;if(Gn+=i,Gn>1e5&&Xt===null&&(Xt=new Set),Xt!==null){if(Xt.has(e))return;Xt.add(e)}for(var a=0;a{if(or===a)return f();var c=j,d=or;st(null),Si(a);var h=f();return st(c),Si(d),h};return n&&r.set("length",H(e.length)),new Proxy(e,{defineProperty(f,c,d){(!("value"in d)||d.configurable===!1||d.enumerable===!1||d.writable===!1)&&fs();var h=r.get(c);return h===void 0?l(()=>{var g=H(d.value);return r.set(c,g),g}):R(h,d.value,!0),!0},deleteProperty(f,c){var d=r.get(c);if(d===void 0){if(c in f){const h=l(()=>H(ue));r.set(c,h),Wr(i)}}else R(d,ue),Wr(i);return!0},get(f,c,d){var _;if(c===Yr)return e;var h=r.get(c),g=c in f;if(h===void 0&&(!g||(_=Br(f,c))!=null&&_.writable)&&(h=l(()=>{var p=Qt(g?f[c]:ue),w=H(p);return w}),r.set(c,h)),h!==void 0){var b=s(h);return b===ue?void 0:b}return Reflect.get(f,c,d)},getOwnPropertyDescriptor(f,c){var b;(b=this.has)==null||b.call(this,f,c);var d=Reflect.getOwnPropertyDescriptor(f,c),h=r.get(c);if(h!==void 0){var g=s(h);if(g===ue)return;if(d&&"value"in d)d.value=g;else return{enumerable:!0,configurable:!0,value:g,writable:!0}}return d},has(f,c){var b;if(c===Yr)return!0;var d=r.get(c),h=d!==void 0&&d.v!==ue||Reflect.has(f,c);if(d!==void 0||U!==null&&(!h||(b=Br(f,c))!=null&&b.writable)){d===void 0&&(d=l(()=>{var _=h?Qt(f[c]):ue,p=H(_);return p}),r.set(c,d));var g=s(d);if(g===ue)return!1}return h},set(f,c,d,h){var S;var g=r.get(c),b=c in f;if(n&&c==="length")for(var _=d;_H(ue)),r.set(_+"",p))}if(g===void 0)(!b||(S=Br(f,c))!=null&&S.writable)&&(g=l(()=>H(void 0)),R(g,Qt(d)),r.set(c,g));else{b=g.v!==ue;var w=l(()=>Qt(d));R(g,w)}var m=Reflect.getOwnPropertyDescriptor(f,c);if(m!=null&&m.set&&m.set.call(h,d),!b){if(n&&typeof c=="string"){var k=r.get("length"),D=Number(c);Number.isInteger(D)&&D>=k.v&&R(k,D+1)}Wr(i)}return!0},ownKeys(f){s(i);var c=Reflect.ownKeys(f).filter(g=>{var b=r.get(g);return b===void 0||b.v!==ue});for(var[d,h]of r)h.v!==ue&&!(d in f)&&c.push(d);return c},setPrototypeOf(){cs()}})}function ki(e){try{if(e!==null&&typeof e=="object"&&Yr in e)return e[Yr]}catch{}return e}function ia(e,t){return Object.is(ki(e),ki(t))}var Ei,aa,sa,la;function Ns(){if(Ei===void 0){Ei=window,aa=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,r=Text.prototype;sa=Br(t,"firstChild").get,la=Br(t,"nextSibling").get,gi(e)&&(e[Hn]=void 0,e[Za]=null,e[Qa]=void 0,e.__e=void 0),gi(r)&&(r[$r]=void 0)}}function qt(e=""){return document.createTextNode(e)}function Jr(e){return sa.call(e)}function sn(e){return la.call(e)}function v(e,t){return Jr(e)}function St(e,t=!1){{var r=Jr(e);return r instanceof Comment&&r.data===""?sn(r):r}}function x(e,t=!1){return Jr(e)}function u(e,t=1,r=!1){let n=e;for(;t--;)n=sn(n);return n}function Ps(e){e.textContent=""}function oa(){return!1}function Rs(e,t,r){return r?document.createElement(e,{is:r}):document.createElement(e)}function Ms(e){var t=U;if(t===null)return j.f|=Yt,e;if((t.f&Nr)===0&&(t.f&Ar)===0)throw e;kt(e,t)}function kt(e,t){if(!(t!==null&&(t.f&Ie)!==0)){for(;t!==null;){if((t.f&zn)!==0&&(t.f&(Ie|jn))===0){if((t.f&Nr)===0)throw e;try{t.b.error(e);return}catch(r){e=r}}t=t.parent}throw e}}function Ds(e){U===null&&(j===null&&os(),ls()),Ut&&ss()}function Is(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function $t(e,t){var r=U;r!==null&&(r.f&Ne)!==0&&(e|=Ne);var n={ctx:qe,deps:null,nodes:null,f:e|se|pt,first:null,fn:t,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};A==null||A.register_created_effect(n);var i=n;if((e&Ar)!==0)Kr!==null?Kr.push(n):ur.ensure().schedule(n);else if(t!==null){try{Or(n)}catch(l){throw Fe(n),l}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&(i.f&Pr)===0&&(i=i.first,(e&ht)!==0&&(e&Sr)!==0&&i!==null&&(i.f|=Sr))}if(i!==null&&(i.parent=r,r!==null&&Is(i,r),j!==null&&(j.f&Ee)!==0&&(e&Ft)===0)){var a=j;(a.effects??(a.effects=[])).push(i)}return n}function oi(){return j!==null&&!_t}function ua(e){const t=$t(Sn,null);return ae(t,fe),t.teardown=e,t}function Tn(e){Ds();var t=U.f,r=!j&&(t&at)!==0&&qe!==null&&!qe.i;if(r){var n=qe;(n.e??(n.e=[])).push(e)}else return fa(e)}function fa(e){return $t(Ar|Xa,e)}function qs(e){ur.ensure();const t=$t(Ft|Pr,e);return(r={})=>new Promise(n=>{r.outro?lr(t,()=>{Fe(t),n(void 0)}):(Fe(t),n(void 0))})}function Fs(e){return $t(Ar,e)}function $s(e){return $t(pr|Pr,e)}function ca(e,t=0){return $t(Sn|t,e)}function $(e,t=[],r=[],n=[]){bs(n,t,r,i=>{$t(Sn,()=>{e(...i.map(s))})})}function ui(e,t=0){var r=$t(ht|t,e);return r}function rt(e){return $t(at|Pr,e)}function da(e){var t=e.teardown;if(t!==null){const r=Ut,n=j;Ai(!0),st(null);try{t.call(null)}catch(i){kt(i,e.parent)}finally{Ai(r),st(n)}}}function fi(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){const i=r.ac;i!==null&&an(()=>{i.abort(nn)});var n=r.next;(r.f&Ft)!==0?r.parent=null:Fe(r,t),r=n}}function Ls(e){for(var t=e.first;t!==null;){var r=t.next;(t.f&at)===0&&Fe(t),t=r}}function Fe(e,t=!0){var r=!1;(t||(e.f&Ja)!==0)&&e.nodes!==null&&e.nodes.end!==null&&(zs(e.nodes.start,e.nodes.end),r=!0),e.f|=jn,fi(e,t&&!r),Xr(e,0);var n=e.nodes&&e.nodes.t;if(n!==null)for(const a of n)a.stop();da(e),e.f^=jn,e.f|=Ie;var i=e.parent;i!==null&&i.first!==null&&va(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function zs(e,t){for(;e!==null;){var r=e===t?null:sn(e);e.remove(),e=r}}function va(e){var t=e.parent,r=e.prev,n=e.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function lr(e,t,r=!0){var n=[];e.f|=ti,ha(e,n,!0);var i=()=>{r&&Fe(e),t&&t()},a=n.length;if(a>0){var l=()=>--a||i();for(var f of n)f.out(l)}else i()}function ha(e,t,r){if((e.f&Ne)===0){e.f^=Ne;var n=e.nodes&&e.nodes.t;if(n!==null)for(const f of n)(f.is_global||r)&&t.push(f);for(var i=e.first;i!==null;){var a=i.next;if((i.f&Ft)===0){var l=(i.f&Sr)!==0||(i.f&at)!==0&&(e.f&ht)!==0;ha(i,t,l?r:!1)}i=a}}}function gn(e){e.f&=~ti,_a(e,!0)}function _a(e,t){if((e.f&ti)===0&&(e.f&Ne)!==0){e.f^=Ne,(e.f&fe)===0&&(ae(e,se),ur.ensure().schedule(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&Sr)!==0||(r.f&at)!==0;_a(r,i?t:!1),r=n}var a=e.nodes&&e.nodes.t;if(a!==null)for(const l of a)(l.is_global||t)&&l.in()}}function ci(e,t){if(e.nodes)for(var r=e.nodes.start,n=e.nodes.end;r!==null;){var i=r===n?null:sn(r);t.append(r),r=i}}let dn=!1,Ut=!1;function Ai(e){Ut=e}let j=null,_t=!1;function st(e){j=e}let U=null;function Ct(e){U=e}let Tt=null;function pa(e){j!==null&&((j.f&pn)!==0||(j.f&Ee)!==0)&&(Tt??(Tt=new Set)).add(e)}let De=null,Je=0,Qe=null;function js(e){Qe=e}let ma=1,er=0,or=er;function Si(e){or=e}function ba(){return++ma}function ln(e){var t=e.f;if((t&se)!==0)return!0;if((t&it)!==0){for(var r=e.deps,n=r.length,i=0;ie.wv)return!0}(t&pt)!==0&&be===null&&ae(e,fe)}return!1}function ga(e,t,r=!0){var n=e.reactions;if(n!==null&&!(Tt!==null&&Tt.has(e)))for(var i=0;i{e.ac.abort(nn)}),e.ac=null);try{e.f|=pn;var h=e.fn,g=h();e.f|=Nr;var b=Ti(e);if(Bi()&&Qe!==null&&!_t&&b!==null&&(e.f&(Ee|it|se))===0)for(var _=0;_0)for(t.length=Je+De.length,n=0;n{a.ac.abort(nn),a.ac=null,ae(a,se)}),ks(a),Xr(a,0)}}function Xr(e,t){var r=e.deps;if(r!==null)for(var n=t;n{In=!1,Dn=null}));var l=0,f=Dn===e&&e[tr];if(f){var c=i.indexOf(f);if(c!==-1&&(t===document||t===window)){e[tr]=t;return}var d=i.indexOf(t);if(d===-1)return;c<=d&&(l=c)}if(a=i[l]||e.target,a!==t){qi(e,"currentTarget",{configurable:!0,get(){return a||r}});var h=j,g=U;st(null),Ct(null);try{for(var b,_=[];a!==null&&a!==t;){try{var p=(m=a[tr])==null?void 0:m[n];p!=null&&(!a.disabled||e.target===a)&&p.call(a,e)}catch(k){b?_.push(k):b=k}if(e.cancelBubble)break;l++,a=l{throw k});throw b}}finally{e[tr]=t,delete e.currentTarget,st(h),Ct(g)}}}var Mi;const qn=((Mi=globalThis==null?void 0:globalThis.window)==null?void 0:Mi.trustedTypes)&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:e=>e});function Bs(e){return(qn==null?void 0:qn.createHTML(e))??e}function Ys(e){var t=Rs("template");return t.innerHTML=Bs(e.replaceAll("","")),t.content}function yn(e,t){var r=U;r.nodes===null&&(r.nodes={start:e,end:t,a:null,t:null})}function N(e,t){var r=(t&Ha)!==0,n=(t&Va)!==0,i,a=!e.startsWith("");return()=>{i===void 0&&(i=Ys(a?e:""+e),r||(i=Jr(i)));var l=n||aa?document.importNode(i,!0):i.cloneNode(!0);if(r){var f=Jr(l),c=l.lastChild;yn(f,c)}else yn(l,l);return l}}function Fn(e=""){{var t=qt(e+"");return yn(t,t),t}}function Oi(){var e=document.createDocumentFragment(),t=document.createComment(""),r=qt();return e.append(t,r),yn(t,r),e}function E(e,t){e!==null&&e.before(t)}const Us=["touchstart","touchmove"];function Gs(e){return Us.includes(e)}function Ks(e){let t=0,r=fr(0),n;return()=>{oi()&&(s(r),ca(()=>(t===0&&(n=ka(()=>e(()=>Wr(r)))),t+=1,()=>{Bt(()=>{t-=1,t===0&&(n==null||n(),n=void 0,Wr(r))})})))}}var Ws=Sr|Pr;function Js(e,t,r,n){new Xs(e,t,r,n)}var et,ei,tt,ir,Ce,Ge,Oe,Ke,wt,ar,Vt,Er,Qr,en,It,xn,Z,Zs,Qs,Wn,el,Jn,Hr,vn,Xn,Zn;class Xs{constructor(t,r,n,i){q(this,Z);Ye(this,"parent");Ye(this,"is_pending",!1);Ye(this,"transform_error");q(this,et);q(this,ei,null);q(this,tt);q(this,ir);q(this,Ce);q(this,Ge,null);q(this,Oe,null);q(this,Ke,null);q(this,wt,null);q(this,ar,0);q(this,Vt,0);q(this,Er,!1);q(this,Qr,new Set);q(this,en,new Set);q(this,It,null);q(this,xn,Ks(()=>(P(this,It,fr(o(this,ar))),()=>{P(this,It,null)})));var a;P(this,et,t),P(this,tt,r),P(this,ir,l=>{var f=U;f.b=this,f.f|=zn,n(l)}),this.parent=U.b,this.transform_error=i??((a=this.parent)==null?void 0:a.transform_error)??(l=>l),P(this,Ce,ui(()=>{z(this,Z,Jn).call(this)},Ws))}defer_effect(t){Ui(t,o(this,Qr),o(this,en))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!o(this,tt).pending}update_pending_count(t,r){z(this,Z,Xn).call(this,t,r),P(this,ar,o(this,ar)+t),!(!o(this,It)||o(this,Er))&&(P(this,Er,!0),Bt(()=>{P(this,Er,!1),o(this,It)&&Cr(o(this,It),o(this,ar))}))}get_effect_pending(){return o(this,xn).call(this),s(o(this,It))}error(t){if(!o(this,tt).onerror&&!o(this,tt).failed)throw t;A!=null&&A.is_fork?(o(this,Ge)&&A.skip_effect(o(this,Ge)),o(this,Oe)&&A.skip_effect(o(this,Oe)),o(this,Ke)&&A.skip_effect(o(this,Ke)),A.oncommit(()=>{z(this,Z,Zn).call(this,t)})):z(this,Z,Zn).call(this,t)}}et=new WeakMap,ei=new WeakMap,tt=new WeakMap,ir=new WeakMap,Ce=new WeakMap,Ge=new WeakMap,Oe=new WeakMap,Ke=new WeakMap,wt=new WeakMap,ar=new WeakMap,Vt=new WeakMap,Er=new WeakMap,Qr=new WeakMap,en=new WeakMap,It=new WeakMap,xn=new WeakMap,Z=new WeakSet,Zs=function(){try{P(this,Ge,rt(()=>o(this,ir).call(this,o(this,et))))}catch(t){this.error(t)}},Qs=function(t){const r=o(this,tt).failed,{reset:n,invoke_onerror:i}=z(this,Z,Wn).call(this,t);Bt(i),r&&P(this,Ke,rt(()=>{r(o(this,et),()=>t,()=>n)}))},Wn=function(t){var r=!1,n=!1;const i=()=>{if(r){rs();return}r=!0,n&&vs(),o(this,Ke)!==null&&lr(o(this,Ke),()=>{P(this,Ke,null)}),z(this,Z,vn).call(this,()=>{z(this,Z,Jn).call(this)})};return{reset:i,invoke_onerror:()=>{var l,f;try{n=!0,(f=(l=o(this,tt)).onerror)==null||f.call(l,t,i),n=!1}catch(c){kt(c,o(this,Ce)&&o(this,Ce).parent)}}}},el=function(){const t=o(this,tt).pending;t&&(this.is_pending=!0,P(this,Oe,rt(()=>t(o(this,et)))),Bt(()=>{var r=P(this,wt,document.createDocumentFragment()),n=qt(),i=!1;if(r.append(n),P(this,Ge,z(this,Z,vn).call(this,()=>{try{return rt(()=>o(this,ir).call(this,n))}catch(a){try{this.error(a),i=!0}catch(l){kt(l,o(this,Ce).parent)}return null}})),o(this,Ge)===null){P(this,wt,null),i&&z(this,Z,Hr).call(this,A);return}o(this,Vt)===0&&(o(this,et).before(r),P(this,wt,null),lr(o(this,Oe),()=>{P(this,Oe,null)}),z(this,Z,Hr).call(this,A))}))},Jn=function(){try{if(this.is_pending=this.has_pending_snippet(),P(this,Vt,0),P(this,ar,0),P(this,Ge,rt(()=>{o(this,ir).call(this,o(this,et))})),o(this,Vt)>0){var t=P(this,wt,document.createDocumentFragment());ci(o(this,Ge),t);const r=o(this,tt).pending;P(this,Oe,rt(()=>r(o(this,et))))}else z(this,Z,Hr).call(this,A)}catch(r){this.error(r)}},Hr=function(t){this.is_pending=!1,t.transfer_effects(o(this,Qr),o(this,en))},vn=function(t){var r=U,n=j,i=qe;Ct(o(this,Ce)),st(o(this,Ce)),Tr(o(this,Ce).ctx);try{return ur.ensure(),t()}finally{Ct(r),st(n),Tr(i)}},Xn=function(t,r){var n;if(!this.has_pending_snippet()){this.parent&&z(n=this.parent,Z,Xn).call(n,t,r);return}P(this,Vt,o(this,Vt)+t),o(this,Vt)===0&&(z(this,Z,Hr).call(this,r),o(this,Oe)&&lr(o(this,Oe),()=>{P(this,Oe,null)}),o(this,wt)&&(o(this,et).before(o(this,wt)),P(this,wt,null)))},Zn=function(t){o(this,Ge)&&(Fe(o(this,Ge)),P(this,Ge,null)),o(this,Oe)&&(Fe(o(this,Oe)),P(this,Oe,null)),o(this,Ke)&&(Fe(o(this,Ke)),P(this,Ke,null));let r=o(this,tt).failed;const n=i=>{const{reset:a,invoke_onerror:l}=z(this,Z,Wn).call(this,i);l(),r&&P(this,Ke,z(this,Z,vn).call(this,()=>{try{return rt(()=>{var f=U;f.b=this,f.f|=zn,r(o(this,et),()=>i,()=>a)})}catch(f){return kt(f,o(this,Ce).parent),null}}))};Bt(()=>{var i;try{i=this.transform_error(t)}catch(a){kt(a,o(this,Ce)&&o(this,Ce).parent);return}i!==null&&typeof i=="object"&&typeof i.then=="function"?i.then(n,a=>kt(a,o(this,Ce)&&o(this,Ce).parent)):n(i)})};function y(e,t){var r=t==null?"":typeof t=="object"?`${t}`:t;r!==(e[$r]??(e[$r]=e.nodeValue))&&(e[$r]=r,e.nodeValue=`${r}`)}function tl(e,t){return rl(e,t)}const on=new Map;function rl(e,{target:t,anchor:r,props:n={},events:i,context:a,intro:l=!0,transformError:f}){Ns();var c=void 0,d=qs(()=>{var h=r??t.appendChild(qt());Js(h,{pending:()=>{}},_=>{Rr({});var p=qe;a&&(p.c=a),i&&(n.$$events=i),c=e(_,n)||Vi(),Mr()},f);var g=new Set,b=_=>{for(var p=0;p<_.length;p++){var w=_[p];if(!g.has(w)){g.add(w);var m=Gs(w);for(const S of[t,document]){var k=on.get(S);k===void 0&&(k=new Map,on.set(S,k));var D=k.get(w);D===void 0?(S.addEventListener(w,Ci,{passive:m}),k.set(w,1)):k.set(w,D+1)}}}};return b(An(Ea)),Kn.add(b),()=>{var m;for(var _ of g)for(const k of[t,document]){var p=on.get(k),w=p.get(_);--w==0?(k.removeEventListener(_,Ci),p.delete(_),p.size===0&&on.delete(k)):p.set(_,w)}Kn.delete(b),h!==r&&((m=h.parentNode)==null||m.removeChild(h))}});return nl.set(c,d),c}let nl=new WeakMap;var vt,xt,We,sr,tn,rn,kn;class il{constructor(t,r=!0){Ye(this,"anchor");q(this,vt,new Map);q(this,xt,new Map);q(this,We,new Map);q(this,sr,new Set);q(this,tn,!0);q(this,rn,t=>{if(o(this,vt).has(t)){var r=o(this,vt).get(t),n=o(this,xt).get(r);if(n)gn(n),o(this,sr).delete(r);else{var i=o(this,We).get(r);i&&(gn(i.effect),o(this,xt).set(r,i.effect),o(this,We).delete(r),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),n=i.effect)}for(const[a,l]of o(this,vt)){if(o(this,vt).delete(a),a===t)break;const f=o(this,We).get(l);f&&(Fe(f.effect),o(this,We).delete(l))}for(const[a,l]of o(this,xt)){if(a===r||o(this,sr).has(a))continue;const f=()=>{if(Array.from(o(this,vt).values()).includes(a)){var d=document.createDocumentFragment();ci(l,d),d.append(qt()),o(this,We).set(a,{effect:l,fragment:d})}else Fe(l);o(this,sr).delete(a),o(this,xt).delete(a)};o(this,tn)||!n?(o(this,sr).add(a),lr(l,f,!1)):f()}}});q(this,kn,t=>{o(this,vt).delete(t);const r=Array.from(o(this,vt).values());for(const[n,i]of o(this,We))r.includes(n)||(Fe(i.effect),o(this,We).delete(n))});this.anchor=t,P(this,tn,r)}ensure(t,r){var n=A,i=oa();if(r&&!o(this,xt).has(t)&&!o(this,We).has(t))if(i){var a=document.createDocumentFragment(),l=qt();a.append(l),o(this,We).set(t,{effect:rt(()=>r(l)),fragment:a})}else o(this,xt).set(t,rt(()=>r(this.anchor)));if(o(this,vt).set(n,t),i){for(const[f,c]of o(this,xt))f===t?n.unskip_effect(c):n.skip_effect(c);for(const[f,c]of o(this,We))f===t?n.unskip_effect(c.effect):n.skip_effect(c.effect);n.oncommit(o(this,rn)),n.ondiscard(o(this,kn))}else o(this,rn).call(this,n)}}vt=new WeakMap,xt=new WeakMap,We=new WeakMap,sr=new WeakMap,tn=new WeakMap,rn=new WeakMap,kn=new WeakMap;function K(e,t,r=!1){var n=new il(e),i=r?Sr:0;function a(l,f){n.ensure(l,f)}ui(()=>{var l=!1;t((f,c=0)=>{l=!0,a(c,f)}),l||a(-1,null)},i)}function pe(e,t){return t}function al(e,t,r){for(var n=[],i=t.length,a,l=t.length,f=0;f{if(a){if(a.pending.delete(g),a.done.add(g),a.pending.size===0){var b=e.outrogroups;Qn(e,An(a.done)),b.delete(a),b.size===0&&(e.outrogroups=null)}}else l-=1},!1)}if(l===0){var c=n.length===0&&r!==null&&e.pending.size===0;if(c){var d=r,h=d.parentNode;Ps(h),h.append(d),e.items.clear()}Qn(e,t,!c)}else a={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(a)}function Qn(e,t,r=!0){var n;if(e.pending.size>0){n=new Set;for(const l of e.pending.values())for(const f of l)n.add(e.items.get(f).e)}for(var i=0;i{var S=r();return En(S)?S:S==null?[]:An(S)}),b,_=new Map,p=!0;function w(S){(D.effect.f&Ie)===0&&(D.pending.delete(S),D.fallback=h,sl(D,b,l,t,n),h!==null&&(b.length===0?(h.f&Et)===0?gn(h):(h.f^=Et,Vr(h,null,l)):lr(h,()=>{h=null})))}function m(S){D.pending.delete(S)}var k=ui(()=>{b=s(g);for(var S=b.length,B=new Set,te=A,Q=oa(),G=0;Ga(l)):(h=rt(()=>a(Ni??(Ni=qt()))),h.f|=Et)),S>B.size&&as(),!p)if(_.set(te,B),Q){for(const[Pe,Ae]of f)B.has(Pe)||te.skip_effect(Ae.e);te.oncommit(w),te.ondiscard(m)}else w(te);s(g)}),D={effect:k,items:f,pending:_,outrogroups:null,fallback:h};p=!1}function Fr(e){for(;e!==null&&(e.f&at)===0;)e=e.next;return e}function sl(e,t,r,n,i){var V,Pe,Ae,de,Re,$e,mt,Ot,lt;var a=(n&za)!==0,l=t.length,f=e.items,c=Fr(e.effect.first),d,h=null,g,b=[],_=[],p,w,m,k;if(a)for(k=0;k0){var ce=(n&Di)!==0&&l===0?r:null;if(a){for(k=0;k{var ge,bt;if(g!==void 0)for(m of g)(bt=(ge=m.nodes)==null?void 0:ge.a)==null||bt.apply()})}function ll(e,t,r,n,i,a,l,f){var c=(l&$a)!==0?(l&ja)===0?Cs(r,!1,!1):fr(r):null,d=(l&La)!==0?fr(i):null;return{v:c,i:d,e:rt(()=>(a(t,c??r,d??i,f),()=>{e.delete(n)}))}}function Vr(e,t,r){if(e.nodes)for(var n=e.nodes.start,i=e.nodes.end,a=t&&(t.f&Et)===0?t.nodes.start:r;n!==null;){var l=sn(n);if(a.before(n),n===i)return;n=l}}function jt(e,t,r){t===null?e.effect.first=r:t.next=r,r===null?e.effect.last=t:r.prev=t}const Pi=[...` +\r\f \v\uFEFF`];function ol(e,t,r){var n=e==null?"":""+e;if(r){for(var i of Object.keys(r))if(r[i])n=n?n+" "+i:i;else if(n.length)for(var a=i.length,l=0;(l=n.indexOf(i,l))>=0;){var f=l+a;(l===0||Pi.includes(n[l-1]))&&(f===n.length||Pi.includes(n[f]))?n=(l===0?"":n.substring(0,l))+n.substring(f+1):l=f}}return n===""?null:n}function un(e,t,r,n,i,a){var l=e[Hn];if(l!==r||l===void 0){var f=ol(r,n,a);f==null?e.removeAttribute("class"):e.className=f,e[Hn]=r}else if(a&&i!==a)for(var c in a){var d=!!a[c];(i==null||d!==!!i[c])&&e.classList.toggle(c,d)}return a}function ul(e,t){t?e.hasAttribute("selected")||e.setAttribute("selected",""):e.removeAttribute("selected")}function fl(e,t){var r=e.__defaultValue,n=e.multiple,i=n?r??[]:null;if(!(n&&!En(i))){e.selectedIndex;for(var a of e.options){var l=mr(a);ul(a,n?i.includes(l):ia(l,r))}}}function Aa(e,t,r=!1){if(e.multiple){if(t==null)return;if(!En(t))return ts();for(var n of e.options)n.selected=t.includes(mr(n));return}for(n of e.options){var i=mr(n);if(ia(i,t)){n.selected=!0;return}}(!r||t!==void 0)&&(e.selectedIndex=-1)}function dr(e){var t=new MutationObserver(r=>{r.every(cl)||("__defaultValue"in e&&fl(e),"__value"in e&&Aa(e,e.__value))});t.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),ua(()=>{t.disconnect()})}function vr(e,t,r=t){var n=new WeakSet,i=!0;Gi(e,"change",a=>{var l=a?"[selected]":":checked",f;if(e.multiple)f=[].map.call(e.querySelectorAll(l),mr);else{var c=e.querySelector(l)??e.querySelector("option:not([disabled])");f=c&&mr(c)}r(f),e.__value=f,A!==null&&n.add(A)}),Fs(()=>{var a=t();if(e===document.activeElement){var l=A;if(n.has(l))return}if(Aa(e,a,i),i&&a===void 0){var f=e.querySelector(":checked");f!==null&&(a=mr(f),r(a))}e.__value=a,i=!1})}function mr(e){return"__value"in e?e.__value:e.value}function cl(e){if(e.target.closest("selectedcontent")!==null)return!0;if(e.type==="childList"){var t=[...e.addedNodes,...e.removedNodes];return t.length>0&&t.every(r=>r.nodeName==="SELECTEDCONTENT")}return!1}function nt(e,t,r=t){var n=new WeakSet;Gi(e,"input",async i=>{var a=i?e.defaultValue:e.value;if(a=$n(e)?Ln(a):a,r(a),A!==null&&n.add(A),await Vs(),a!==(a=t())){var l=e.selectionStart,f=e.selectionEnd,c=e.value.length;if(e.value=a??"",f!==null){var d=e.value.length;l===f&&f===c&&d>c?(e.selectionStart=d,e.selectionEnd=d):(e.selectionStart=l,e.selectionEnd=Math.min(f,d))}}}),ka(t)==null&&e.value&&(r($n(e)?Ln(e.value):e.value),A!==null&&n.add(A)),ca(()=>{var i=t();if(e===document.activeElement){var a=A;if(n.has(a))return}$n(e)&&i===Ln(e.value)||e.type==="date"&&!i&&!e.value||i!==e.value&&(e.value=i??"")})}function $n(e){var t=e.type;return t==="number"||t==="range"}function Ln(e){return e===""?null:+e}async function Sa(e,t,r){try{const n=await fetch(`/api${t}`,{method:e,headers:r===void 0?void 0:{"Content-Type":"application/json"},body:r===void 0?void 0:JSON.stringify(r)}),i=await n.json().catch(()=>({error:n.statusText}));return{ok:n.ok,data:i}}catch(n){return{ok:!1,data:{error:(n==null?void 0:n.message)??String(n)}}}}const On=e=>Sa("GET",e),di=(e,t={})=>Sa("POST",e,t);var dl=N('
',1),vl=N('
'),hl=N('

No proof possible

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

'),_l=N('

 
'),pl=N('

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

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

: balance points

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

None yet.

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

Transactions

",1),Tl=N('

Private — the openings each wallet holds

On-chain — what anyone can see

Notes at : owner and commitment, never the amount.

note UTxOownercommitment uv

Receipts held by the retailer

',1),Cl=N(`

A. Confidential points

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

Issue (retailer)

Transfer

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

Redeem at the retailer

Try to cheat: spend someone else's note

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

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

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

No profile issued yet.

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

Nothing recorded yet.

'),Il=N('

No badge claimed yet.

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

Private — Alice's opening

On-chain — the issuance record

What the lender learns

`),$l=N(`

B. Committed credential

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

1. Bureau issues Alice's profile

2. Alice claims a badge from the lender

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

Try to cheat: Mallory presents Alice's credential

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

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

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

Reserve locked: at

id hashcommitment u

Attestation tx

',1),Wl=N('

No attestation yet.

'),Jl=N(`

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

Total liabilities: (never published)

customerbalancesaltblindingid hashlast check

On-chain — the period's vault

`,1),Xl=N(`

C. Hidden-liability solvency

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

1. The book (balances in ADA)

2. Attest for a new period

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

3. Check (during the period)

Try to cheat inside the period

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

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

"),to=N(`

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

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

'),io=N(`

Pedersen Commitments on Cardano

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

Demo server. This server creates every wallet and holds every opening (amounts, blindings, + profiles, customer balances) and key on the users' behalf; real users would each keep their own. + The On-chain panels show what anyone can read from the ledger.
`);function ao(e,t){Rr(t,!0);let r=H("points"),n=H(null);async function i(){var S;const D=await On("/status");R(n,D.data,!0),(S=s(n))!=null&&S.ready||setTimeout(i,3e3)}Tn(()=>{i()});var a=io(),l=u(v(a),6);{var f=D=>{var S=to(),B=u(v(S),2);{var te=Q=>{var G=eo();me(G,21,()=>Object.entries(s(n).demos),pe,(le,ce)=>{var V=ii(()=>$i(s(ce),2));let Pe=()=>s(V)[0],Ae=()=>s(V)[1];var de=Ql();let Re;var $e=x(de);$(()=>{Re=un(de,1,"pill svelte-1n46o8q",null,Re,{ready:Ae()==="ready"}),y($e,`${Pe()??""}: ${Ae()??""}`)}),E(le,de)}),E(Q,G)};K(B,Q=>{var G;(G=s(n))!=null&&G.demos&&Q(te)})}E(D,S)};K(l,D=>{var S;(S=s(n))!=null&&S.ready||D(f)})}var c=u(l,2),d=v(c);let h;var g=u(d,2);let b;var _=u(g,2);let p;var w=u(c,2);{var m=D=>{var S=ro(),B=St(S);{var te=V=>{Ol(V,{})};K(B,V=>{s(r)==="points"&&V(te)})}var Q=u(B,2);{var G=V=>{Ll(V,{})};K(Q,V=>{s(r)==="credit"&&V(G)})}var le=u(Q,2);{var ce=V=>{Zl(V,{})};K(le,V=>{s(r)==="solvency"&&V(ce)})}E(D,S)},k=D=>{var S=no(),B=x(S);$(()=>{var te,Q;return y(B,`This demo is ${((Q=(te=s(n))==null?void 0:te.demos)==null?void 0:Q[s(r)])??"starting"??""}…`)}),E(D,S)};K(w,D=>{var S,B;((B=(S=s(n))==null?void 0:S.demos)==null?void 0:B[s(r)])==="ready"?D(m):s(n)&&D(k,1)})}$(()=>{h=un(d,1,"svelte-1n46o8q",null,h,{active:s(r)==="points"}),b=un(g,1,"svelte-1n46o8q",null,b,{active:s(r)==="credit"}),p=un(_,1,"svelte-1n46o8q",null,p,{active:s(r)==="solvency"})}),ke("click",d,()=>R(r,"points")),ke("click",g,()=>R(r,"credit")),ke("click",_,()=>R(r,"solvency")),E(e,a),Mr()}Cn(["click"]);tl(ao,{target:document.getElementById("app")}); diff --git a/pedersen-commitments/src/main/resources/static/assets/index-DamEuh0Q.css b/pedersen-commitments/src/main/resources/static/assets/index-DamEuh0Q.css new file mode 100644 index 0000000..a14df0b --- /dev/null +++ b/pedersen-commitments/src/main/resources/static/assets/index-DamEuh0Q.css @@ -0,0 +1 @@ +.ok.svelte-wzlqy7{background:#12261a;border:1px solid #238636;border-radius:8px;padding:10px 14px;margin:12px 0;color:#7ee787}.noproof.svelte-wzlqy7{background:#2b2111;border:1px solid #d29922;border-radius:8px;padding:10px 14px;margin:12px 0}.noproof.svelte-wzlqy7 h4:where(.svelte-wzlqy7){color:#e3b341;margin:0 0 6px}.rejected.svelte-wzlqy7{background:#2d1214;border:1px solid #da3633;border-radius:8px;padding:10px 14px;margin:12px 0}.rejected.svelte-wzlqy7 h4:where(.svelte-wzlqy7){color:#f85149;margin:0 0 6px}pre.svelte-wzlqy7{white-space:pre-wrap;overflow-wrap:anywhere;max-height:200px;overflow-y:auto;background:#161b22;padding:8px;border-radius:6px;color:#ffb4ad;font-size:.8em}p.svelte-wzlqy7{margin:4px 0}.hint.svelte-wzlqy7{color:#8b949e;font-size:.9em}code.svelte-wzlqy7{font-size:.85em;color:#79c0ff;overflow-wrap:anywhere}body{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;max-width:1180px;margin:0 auto;padding:20px;background:#0d1117;color:#c9d1d9}h2{color:#c9d1d9;margin:8px 0}h3{color:#58a6ff;margin:12px 0 6px;font-size:1em}.card{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:14px;margin:12px 0}.columns{display:grid;grid-template-columns:1fr 1fr;gap:16px}.panel{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:12px 14px}.panel.private{border-color:#8957e5}.panel.private h3{color:#d2a8ff}.panel.public{border-color:#1f6feb}table{width:100%;border-collapse:collapse;margin:6px 0;font-size:.9em}th,td{padding:5px 8px;text-align:left;border-bottom:1px solid #21262d}th{color:#8b949e;font-weight:400}code{font-size:.85em;color:#79c0ff}.hint{color:#8b949e;font-size:.9em}.actions{display:flex;flex-wrap:wrap;gap:12px}.action{background:#161b22;border:1px solid #30363d;border-radius:8px;padding:10px 12px;flex:1 1 250px}.action h4{margin:0 0 8px;color:#c9d1d9}.action.cheat{border-color:#da3633}.action.cheat h4{color:#f85149}label{display:block;font-size:.85em;color:#8b949e;margin:4px 0}input,select{background:#0d1117;color:#c9d1d9;border:1px solid #30363d;border-radius:6px;padding:5px 7px;width:100%;box-sizing:border-box}button.primary,button.danger{margin-top:8px;padding:7px 14px;border:none;border-radius:6px;color:#fff;font-weight:700;cursor:pointer}button.primary{background:#238636}button.danger{background:#da3633}button:disabled{opacity:.5;cursor:not-allowed}.busy{color:#58a6ff;margin:8px 0}h1.svelte-1n46o8q{color:#58a6ff;margin-bottom:4px}.subtitle.svelte-1n46o8q{color:#8b949e;margin-top:0}.notice.svelte-1n46o8q{background:#1c1f26;border:1px solid #d29922;border-radius:8px;padding:10px 14px;color:#e3b341;font-size:.92em}nav.svelte-1n46o8q{display:flex;gap:8px;margin:18px 0 8px;flex-wrap:wrap}nav.svelte-1n46o8q button:where(.svelte-1n46o8q){padding:8px 18px;border:1px solid #30363d;background:#21262d;color:#c9d1d9;border-radius:6px;cursor:pointer}nav.svelte-1n46o8q button.active:where(.svelte-1n46o8q){background:#1f6feb;border-color:#1f6feb;color:#fff}.pill.svelte-1n46o8q{display:inline-block;padding:2px 10px;margin:2px;border-radius:12px;background:#30363d;font-size:.85em}.pill.ready.svelte-1n46o8q{background:#238636;color:#fff} diff --git a/pedersen-commitments/src/main/resources/static/index.html b/pedersen-commitments/src/main/resources/static/index.html new file mode 100644 index 0000000..7dc893f --- /dev/null +++ b/pedersen-commitments/src/main/resources/static/index.html @@ -0,0 +1,14 @@ + + + + + + Pedersen Commitments — ZeroJ + + + + + +
+ + diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/E2E.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/E2E.java new file mode 100644 index 0000000..494e279 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/common/E2E.java @@ -0,0 +1,34 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.common; + +import com.bloxbean.cardano.client.api.model.Result; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Shared assertions for the DevKit end-to-end tests. */ +public final class E2E { + + private E2E() {} + + /** Whether DevKit tests are enabled ({@code ZEROJ_YACI_E2E=true}) and DevKit answers. */ + public static boolean enabled() { + return Boolean.getBoolean("zeroj.yaci.e2e") && DevKit.reachable(); + } + + /** + * The transaction failed, and it failed in script evaluation (not, say, for lack of funds). + * Evaluation is the local Julc evaluator running the script on the real transaction, as the + * node would; a rejected transaction is never submitted (that would cost collateral). + * CCL reports a failing script as {@code "... Script evaluation failed for [i] ..."} + * when a spend is involved, and as {@code "Error while evaluating script cost"} for mint-only + * transactions (the script's own failure is logged); both come only from the script + * evaluator. + */ + public static void assertScriptRejected(Result result, String what) { + assertFalse(result.isSuccessful(), what + " must be rejected"); + String response = String.valueOf(result.getResponse()); + System.out.println("Rejected (" + what + "): " + response.substring(0, Math.min(140, response.length()))); + assertTrue(response.contains("Script evaluation failed") || response.equals("Error while evaluating script cost"), + what + " must be rejected by a script: " + response); + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditCircuitTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditCircuitTest.java new file mode 100644 index 0000000..fa1441c --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditCircuitTest.java @@ -0,0 +1,82 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.credential; + +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.circuit.CreditProfileProofCircuit; +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.PedersenVectorCommitment; +import org.zeroj.circuit.lib.jubjub.PedersenVectorSchema; +import org.zeroj.circuit.lib.jubjub.PedersenVectorSchema.Entry; + +import java.math.BigInteger; +import java.util.ArrayList; +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 B's relation: predicates over a committed profile, bound to its schema. */ +class CreditCircuitTest { + + static final long MIN_INCOME = 50_000; + static final int MIN_SCORE = 650; + private static CreditGate gate; + + @BeforeAll + static void setup() { + gate = new CreditGate(); + } + + @Test + @DisplayName("A qualifying profile proves; the proof is bound to σ, the commitment and both thresholds") + void qualifyingProfileProves() { + Profile p = Profile.of(85_000, 720, 1990, 356); + var proof = gate.prove(p, MIN_INCOME, MIN_SCORE); + List pub = CreditProfileProofCircuit.publicInputs(CreditGate.inputs(p, MIN_INCOME, MIN_SCORE)); + assertTrue(gate.circuit().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(gate.circuit().verify(proof, changed), "public input " + i + " not bound"); + } + System.out.println("[credit-profile-check] constraints: " + gate.circuit().numConstraints()); + } + + @Test + @DisplayName("Thresholds are inclusive; one below either threshold has no witness") + void thresholds() { + var circuit = gate.circuit().circuit(); + assertDoesNotThrow(() -> circuit.calculateWitness( + CreditGate.inputs(Profile.of(MIN_INCOME, MIN_SCORE, 2000, 1), MIN_INCOME, MIN_SCORE).toWitnessMap(), + CurveId.BLS12_381)); + assertThrows(RuntimeException.class, () -> circuit.calculateWitness( + CreditGate.inputs(Profile.of(MIN_INCOME - 1, 800, 2000, 1), MIN_INCOME, MIN_SCORE).toWitnessMap(), + CurveId.BLS12_381)); + assertThrows(RuntimeException.class, () -> circuit.calculateWitness( + CreditGate.inputs(Profile.of(900_000, MIN_SCORE - 1, 2000, 1), MIN_INCOME, MIN_SCORE).toWitnessMap(), + CurveId.BLS12_381)); + } + + @Test + @DisplayName("Schema binding: another schema's digest, or a commitment made under another schema, has no witness") + void schemaBinding() { + var circuit = gate.circuit().circuit(); + Profile p = Profile.of(85_000, 720, 1990, 356); + // Same shape, different meaning: "score" first. Its digest is not this circuit's σ. + PedersenVectorSchema other = PedersenVectorSchema.of("zeroj.demo.credit-profile", 2, List.of( + new Entry("income", 64), new Entry("credit_score", 16), new Entry("birth_year", 16), new Entry("country", 16))); + assertThrows(RuntimeException.class, () -> circuit.calculateWitness( + CreditGate.inputs(p, MIN_INCOME, MIN_SCORE).schemaDigest(other.digest()).toWitnessMap(), CurveId.BLS12_381)); + // The commitment of other attribute values: the opening does not match (u, v). + var c = PedersenVectorCommitment.commit(CreditProfileProof.SCHEMA, + List.of(BigInteger.valueOf(85_000), BigInteger.valueOf(720), BigInteger.valueOf(1991), BigInteger.valueOf(356)), + p.blinding()).point().normalized(); + assertThrows(RuntimeException.class, () -> circuit.calculateWitness( + CreditGate.inputs(p, MIN_INCOME, MIN_SCORE).u(c.affineU()).v(c.affineV()).toWitnessMap(), CurveId.BLS12_381)); + } +} diff --git a/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGateDevKitE2ETest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGateDevKitE2ETest.java new file mode 100644 index 0000000..fed00c2 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGateDevKitE2ETest.java @@ -0,0 +1,75 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.credential; + +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.credential.CreditGate.Profile; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * Demo B on Yaci DevKit: a bureau issues Alice a committed credit profile and records the + * issuance on-chain; Alice proves {@code income ≥ 50,000 ∧ credit_score ≥ 650} to a lender's gate + * and receives a badge, revealing nothing else. Rejected by the gate script (local Julc evaluation, as the node would run it): the claim + * without the issuance record, and Mallory presenting Alice's commitment with a valid proof. + * A profile below the thresholds cannot be proved at all. + * + *

Runs only with {@code ZEROJ_YACI_E2E=true}. + */ +class CreditGateDevKitE2ETest { + + @Test + void creditGateOnDevKit() throws Exception { + assumeTrue(E2E.enabled(), "Set ZEROJ_YACI_E2E=true with DevKit running"); + var backend = DevKit.backend(); + var bureau = new Account(Networks.testnet()); + var alice = new Account(Networks.testnet()); + var mallory = new Account(Networks.testnet()); + for (Account a : List.of(bureau, alice, mallory)) DevKit.topUp(a.baseAddress(), 200); + byte[] alicePkh = alice.hdKeyPair().getPublicKey().getKeyHash(); + + var credit = new CreditGate(); + long minIncome = 50_000; + int minScore = 650; + byte[] bureauPolicy = HexUtil.decodeHexString(CreditGate.bureauPolicy(bureau).getPolicyId()); + var gate = credit.gate(bureauPolicy, minIncome, minScore); + + // The bureau issues Alice's profile: the opening goes to Alice, the record goes on-chain. + Profile profile = Profile.of(85_000, 720, 1990, 356); + var commitment = profile.commitment(); + var issued = CreditGate.issueRecord(backend, bureau, alice.baseAddress(), alicePkh, commitment); + assertTrue(issued.isSuccessful(), "issue: " + issued.getResponse()); + DevKit.waitForTx(backend, issued.getValue()); + Utxo record = DevKit.utxosOf(backend, alice.baseAddress(), issued.getValue()).stream() + .filter(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().startsWith(HexUtil.encodeHexString(bureauPolicy)))) + .findFirst().orElseThrow(); + + var proof = credit.prove(profile, minIncome, minScore); + + // Without the issuance record: fail closed. + E2E.assertScriptRejected( + CreditGate.claim(backend, gate, alice, commitment, null, proof), "a claim without the issuance record"); + // Mallory with Alice's commitment and a valid proof (say the opening leaked): the record names Alice. + E2E.assertScriptRejected( + CreditGate.claim(backend, gate, mallory, commitment, record, proof), "Mallory presenting Alice's credential"); + // A profile below the thresholds has no proof at all. + assertThrows(RuntimeException.class, () -> credit.prove(Profile.of(42_000, 720, 1990, 356), minIncome, minScore)); + + var claimed = CreditGate.claim(backend, gate, alice, commitment, record, proof); + assertTrue(claimed.isSuccessful(), "claim: " + claimed.getResponse()); + DevKit.waitForTx(backend, claimed.getValue()); + String badgeUnit = Plutus.policyId(gate) + HexUtil.encodeHexString(alicePkh); + assertTrue(DevKit.utxosOf(backend, alice.baseAddress(), claimed.getValue()).stream() + .anyMatch(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().equals(badgeUnit))), "Alice holds the badge"); + System.out.println("Credit gate on DevKit: record " + issued.getValue() + ", badge " + claimed.getValue()); + } +} 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 new file mode 100644 index 0000000..273020f --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/credential/CreditGateVmTest.java @@ -0,0 +1,170 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.credential; + +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.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.TokenName; +import org.julclang.ledger.TxInInfo; +import org.julclang.ledger.TxOut; +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.PedersenVectorCommitment; +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 CreditGatePolicy} in the Plutus VM (ADR-0006 demo B): a qualifying, issued credential + * gets a badge; every mutation that would break C1–C5 is rejected. + */ +class CreditGateVmTest extends ContractTest { + + private static final byte[] GATE = filled(28, (byte) 0x6a); + private static final byte[] BUREAU = filled(28, (byte) 0xb7); + private static final byte[] HOLDER = filled(28, (byte) 0xa1); + private static final byte[] MALLORY = filled(28, (byte) 0x3e); + + private static Program program; + private static Profile profile; + private static PedersenVectorCommitment commitment; + private static SnarkjsToCardano.ProofCompressed proof; + private static SnarkjsToCardano.ProofCompressed lowThresholdProof; + + @BeforeAll + static void setup() { + var gate = new CreditGate(); + profile = Profile.of(85_000, 720, 1990, 356); + commitment = profile.commitment(); + proof = ProverToCardano.compressProof(gate.prove(profile, CreditCircuitTest.MIN_INCOME, CreditCircuitTest.MIN_SCORE)); + // 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( + PlutusData.bytes(Fields.i2osp(CreditProfileProof.SCHEMA.digest(), 32)), + PlutusData.bytes(BUREAU), + PlutusData.integer(BigInteger.valueOf(CreditCircuitTest.MIN_INCOME)), + PlutusData.integer(BigInteger.valueOf(CreditCircuitTest.MIN_SCORE)), + PlutusData.bytes(vk.alpha()), PlutusData.bytes(vk.beta()), + PlutusData.bytes(vk.gamma()), PlutusData.bytes(vk.delta()), icData(vk.ic())); + } + + enum Mutation { + NONE, NO_SIGNER, MALFORMED_PROOF, LOWER_THRESHOLD_PROOF, NO_RECORD, RECORD_OTHER_SCHEMA_DATUM, + RECORD_FOR_OTHER_HOLDER, RECORD_UNDER_OTHER_POLICY, RECORD_AS_INPUT_NOT_REFERENCE, BADGE_NAME_NOT_HOLDER, + BADGE_TO_OTHER, TWO_BADGES, EXTRA_MINT_ENTRY, OTHER_COMMITMENT, NON_CANONICAL_U, SHORT_HOLDER, + IMPOSTOR_HOLDER + } + + @Test + @DisplayName("Credit gate: a qualifying issued credential mints a badge; every mutation is rejected") + void gate() { + var ok = evaluate(program, context(Mutation.NONE)); + assertSuccess(ok); + System.out.println("[CreditGatePolicy] budget: " + ok.budgetConsumed()); + for (Mutation m : Mutation.values()) { + if (m != Mutation.NONE && evaluate(program, context(m)) instanceof EvalResult.Success) { + fail("credit gate accepted " + m); + } + } + } + + private PlutusData context(Mutation m) { + byte[] holder = switch (m) { + case SHORT_HOLDER -> Arrays.copyOf(HOLDER, 27); + case IMPOSTOR_HOLDER -> MALLORY; // Mallory presents the holder's commitment as hers + default -> HOLDER; + }; + var point = commitment.point().normalized(); + BigInteger u = m == Mutation.NON_CANONICAL_U ? point.affineU().add(JubjubCurve.BASE_FIELD_PRIME) : point.affineU(); + BigInteger v = point.affineV(); + if (m == Mutation.OTHER_COMMITMENT) { + var other = Profile.of(85_000, 720, 1990, 356).commitment().point().normalized(); + u = other.affineU(); + v = other.affineV(); + } + var p = m == Mutation.LOWER_THRESHOLD_PROOF ? lowThresholdProof : proof; + byte[] piA = m == Mutation.MALFORMED_PROOF ? flipped(p.piA()) : p.piA(); + + byte[] badgeName = m == Mutation.BADGE_NAME_NOT_HOLDER ? MALLORY : holder; + Value mint = Value.singleton(PolicyId.of(GATE), TokenName.of(badgeName), BigInteger.valueOf(m == Mutation.TWO_BADGES ? 2 : 1)); + if (m == Mutation.EXTRA_MINT_ENTRY) mint = mint.merge(Value.singleton(PolicyId.of(GATE), TokenName.of(filled(28, (byte) 1)), BigInteger.ONE)); + + var b = ScriptContextTestBuilder.minting(PolicyId.of(GATE)) + .mint(mint) + .redeemer(PlutusData.constr(0, PlutusData.bytes(holder), PlutusData.integer(u), PlutusData.integer(v), + PlutusData.bytes(piA), PlutusData.bytes(p.piB()), PlutusData.bytes(p.piC()))); + if (m != Mutation.NO_SIGNER) b.signer(holder); + + // The issuance record names the honest holder (and, for the impostor, still the honest holder). + byte[] recordHolder = m == Mutation.RECORD_FOR_OTHER_HOLDER ? MALLORY : HOLDER; + byte[] recordPolicy = m == Mutation.RECORD_UNDER_OTHER_POLICY ? filled(28, (byte) 0x99) : BUREAU; + BigInteger recordSigma = m == Mutation.RECORD_OTHER_SCHEMA_DATUM + ? CreditProfileProof.SCHEMA.digest().add(BigInteger.ONE) : CreditProfileProof.SCHEMA.digest(); + // NON_CANONICAL_U: the record is made for the same u + p, so the record lookup matches and + // only the gate's canonical check (and the verifier's own) can reject it. + BigInteger recordU = m == Mutation.NON_CANONICAL_U ? u : point.affineU(); + byte[] recordName = Blake2bUtil.blake2bHash256(Fields.concat(Fields.i2osp(recordU, 32), + Fields.i2osp(point.affineV(), 32), Fields.i2osp(CreditProfileProof.SCHEMA.digest(), 32), recordHolder)); + TxOut record = new TxOut(TestDataBuilder.pubKeyAddress(PubKeyHash.of(HOLDER)), + Value.lovelace(BigInteger.valueOf(2_000_000)).merge( + Value.singleton(PolicyId.of(recordPolicy), TokenName.of(recordName), BigInteger.ONE)), + new OutputDatum.OutputDatumInline(PlutusData.constr(0, + PlutusData.integer(recordU), PlutusData.integer(point.affineV()), + PlutusData.integer(recordSigma), PlutusData.bytes(recordHolder))), + Optional.empty()); + if (m == Mutation.RECORD_AS_INPUT_NOT_REFERENCE) { + b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), record)); + } else if (m != Mutation.NO_RECORD) { + b.referenceInput(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), record)); + } + + byte[] payee = m == Mutation.BADGE_TO_OTHER ? MALLORY : holder; + b.output(new TxOut(new Address(new Credential.PubKeyCredential(PubKeyHash.of(payee)), Optional.empty()), + Value.lovelace(BigInteger.valueOf(2_000_000)).merge( + Value.singleton(PolicyId.of(GATE), TokenName.of(badgeName), BigInteger.ONE)), + new OutputDatum.NoOutputDatum(), Optional.empty())); + return b.buildPlutusData(); + } + + 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/points/PointsCircuitTest.java b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsCircuitTest.java new file mode 100644 index 0000000..e267d11 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsCircuitTest.java @@ -0,0 +1,101 @@ +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 new file mode 100644 index 0000000..77d580a --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsDevKitE2ETest.java @@ -0,0 +1,87 @@ +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 new file mode 100644 index 0000000..0c44be0 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/points/PointsLedgerVmTest.java @@ -0,0 +1,336 @@ +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 new file mode 100644 index 0000000..7e7ccd0 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyCircuitTest.java @@ -0,0 +1,120 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.solvency; + +import com.bloxbean.cardano.zeroj.usecases.pedersen.solvency.SolvencyAttestation.AuditOpening; +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.circuit.HiddenLiabilitySolvencyProofCircuit; +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.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 C: the solvency relation, the customer check and the auditor's aggregate opening. */ +class SolvencyCircuitTest { + + static final int N = 4; + private static SolvencyAttestation solvency; + + 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)); + } + + @BeforeAll + static void setup() { + solvency = new SolvencyAttestation(N); + } + + @Test + @DisplayName("Solvent book proves; every public input is bound; liabilities equal to reserves are allowed") + void solventProves() { + var book = book(); + long reserves = 2_000_000_000L; + var proof = solvency.prove(reserves, book); + List pub = HiddenLiabilitySolvencyProofCircuit.publicInputs(SolvencyAttestation.inputs(reserves, book)); + assertTrue(solvency.circuit().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(solvency.circuit().verify(proof, changed), "public input " + i + " not bound"); + } + assertDoesNotThrow(() -> solvency.circuit().circuit().calculateWitness( + SolvencyAttestation.inputs(2_000_000_000L, book).toWitnessMap(), CurveId.BLS12_381)); + System.out.println("[hidden-liability-solvency-n4] constraints: " + solvency.circuit().numConstraints()); + } + + @Test + @DisplayName("No witness when liabilities exceed reserves, a commitment is wrong, or a balance is not 64-bit") + void insolventOrMalformedHasNoWitness() { + var circuit = solvency.circuit().circuit(); + var book = book(); + assertThrows(RuntimeException.class, () -> circuit.calculateWitness( + SolvencyAttestation.inputs(1_999_999_999L, book).toWitnessMap(), CurveId.BLS12_381)); + // Understating alice's balance in the proof while publishing her real commitment. + var understated = SolvencyAttestation.inputs(2_000_000_000L, book); + understated.balances(List.of(BigInteger.ONE, BigInteger.valueOf(1_200_000_000L), + BigInteger.valueOf(300_000_000L), BigInteger.ZERO)); + assertThrows(RuntimeException.class, () -> circuit.calculateWitness(understated.toWitnessMap(), CurveId.BLS12_381)); + // A balance of 2^64 cannot be committed as a 64-bit amount. + BigInteger huge = BigInteger.ONE.shiftLeft(64); + BigInteger r = PedersenCommitment.randomBlinding(new SecureRandom()); + var c = PedersenCommitment.commit(huge, r).normalized(); + var overflow = SolvencyAttestation.inputs(2_000_000_000L, book); + var us = new ArrayList<>(book.stream().map(x -> x.commitment().affineU()).toList()); + var vs = new ArrayList<>(book.stream().map(x -> x.commitment().affineV()).toList()); + us.set(3, c.affineU()); + vs.set(3, c.affineV()); + overflow.liabilityU(us).liabilityV(vs) + .balances(List.of(BigInteger.valueOf(500_000_000L), BigInteger.valueOf(1_200_000_000L), + BigInteger.valueOf(300_000_000L), huge)) + .blindings(List.of(book.get(0).blinding(), book.get(1).blinding(), book.get(2).blinding(), r)); + assertThrows(RuntimeException.class, () -> circuit.calculateWitness(overflow.toWitnessMap(), CurveId.BLS12_381)); + } + + @Test + @DisplayName("Customer check: own entry exactly once and opening; understated and duplicated 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. + Customer alice = book.getFirst(); + var cheaper = new ArrayList<>(entries); + cheaper.set(0, new Entry(alice.idHash(), PedersenCommitment.commit(BigInteger.ONE, alice.blinding()).normalized())); + assertFalse(SolvencyAttestation.customerCheck(cheaper, alice)); + // Listed twice (e.g. to show two views): refused. + var twice = new ArrayList<>(entries); + twice.set(3, entries.getFirst()); + assertFalse(SolvencyAttestation.customerCheck(twice, 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())); + } + + @Test + @DisplayName("Auditor: the sum of the commitments opens to total liabilities, and to nothing else") + void auditorOpening() { + var book = book(); + List entries = SolvencyAttestation.entries(book); + AuditOpening opening = SolvencyAttestation.auditOpening(book); + assertTrue(SolvencyAttestation.auditorCheck(entries, opening)); + assertFalse(SolvencyAttestation.auditorCheck(entries, + new AuditOpening(opening.liabilities().subtract(BigInteger.ONE), opening.blinding()))); + } +} 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 new file mode 100644 index 0000000..63f3252 --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyDevKitE2ETest.java @@ -0,0 +1,86 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.solvency; + +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.solvency.SolvencyAttestation.Customer; +import org.junit.jupiter.api.Test; + +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; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +/** + * Demo C on Yaci DevKit: before an attestation period, an exchange with four customers locks + * 2,000 ADA and attests that its hidden liabilities are covered. During the period each customer + * checks every attestation of the period's vault from chain data and finds their entry exactly + * once; an auditor opens the total by homomorphism; an insolvent book cannot be proved; a second + * attestation and an early release are rejected by the vault. After the period the release burns + * the attestation. + * + *

Runs only with {@code ZEROJ_YACI_E2E=true}. + */ +class SolvencyDevKitE2ETest { + + @Test + void solvencyOnDevKit() throws Exception { + assumeTrue(E2E.enabled(), "Set ZEROJ_YACI_E2E=true with DevKit running"); + var backend = DevKit.backend(); + var exchange = new Account(Networks.testnet()); + DevKit.topUp(exchange.baseAddress(), 5_000); + + var solvency = new SolvencyAttestation(SolvencyCircuitTest.N); + long now = DevKit.chainTimeMillis(backend); + var period = new SolvencyAttestation.Period(now + 40_000, now + 90_000); + var vault = solvency.vault(exchange.hdKeyPair().getPublicKey().getKeyHash(), period); + String vaultAddress = SolvencyAttestation.address(vault); + List book = SolvencyCircuitTest.book(); // 2,000 ADA of liabilities, in lovelace + long reserves = 2_000_000_000L; + + 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. + var attested = SolvencyAttestation.attest(backend, vault, exchange, reserves, + SolvencyAttestation.entries(book), proof, DevKit.slotAt(backend, period.start())); + assertTrue(attested.isSuccessful(), "attest: " + attested.getResponse()); + DevKit.waitForTx(backend, attested.getValue()); + + // During the period: customers and the auditor check every live attestation of the + // period's vault, which they derive themselves. + 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"); + } + 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"); + + // 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, + 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() + .filter(u -> u.getAmount().stream().anyMatch(a -> a.getUnit().equals(tokenUnit))) + .findFirst().orElseThrow(); + E2E.assertScriptRejected(SolvencyAttestation.release(backend, vault, exchange, live, + 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); + 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 new file mode 100644 index 0000000..c36617f --- /dev/null +++ b/pedersen-commitments/src/test/java/com/bloxbean/cardano/zeroj/usecases/pedersen/solvency/SolvencyVaultVmTest.java @@ -0,0 +1,234 @@ +package com.bloxbean.cardano.zeroj.usecases.pedersen.solvency; + +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.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.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.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.fail; + +/** + * {@code SolvencyVault} in the Plutus VM (ADR-0006 demo C): an honest attestation before the + * period and an honest release after it are accepted; every mutation that would break S1–S7 is + * rejected. + */ +class SolvencyVaultVmTest extends ContractTest { + + private static final byte[] VAULT = filled(28, (byte) 0x5f); + private static final byte[] EXCHANGE = filled(28, (byte) 0xe5); + private static final byte[] TOKEN = SolvencyAttestation.ATTEST_TOKEN; + private static final Address VAULT_ADDRESS = new Address( + new Credential.ScriptCredential(ScriptHash.of(VAULT)), Optional.empty()); + private static final Address EXCHANGE_ADDRESS = new Address( + new Credential.PubKeyCredential(PubKeyHash.of(EXCHANGE)), Optional.empty()); + private static final long RESERVES = 2_000_000_000L; + private static final long PERIOD_START = 1_800_000_000_000L; + private static final long PERIOD_END = PERIOD_START + 86_400_000L; + private static final Address STAKED_VAULT_ADDRESS = new Address(VAULT_ADDRESS.credential(), + Optional.of(new StakingCredential.StakingHash(new Credential.PubKeyCredential(PubKeyHash.of(filled(28, (byte) 0x5a)))))); + + private static Program program; + private static List entries; + private static SnarkjsToCardano.ProofCompressed proof; + + @BeforeAll + static void setup() { + var solvency = new SolvencyAttestation(SolvencyCircuitTest.N); + List book = SolvencyCircuitTest.book(); + 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( + PlutusData.bytes(EXCHANGE), PlutusData.bytes(TOKEN), + PlutusData.integer(BigInteger.valueOf(SolvencyCircuitTest.N)), + PlutusData.integer(BigInteger.valueOf(PERIOD_START)), + PlutusData.integer(BigInteger.valueOf(PERIOD_END)), + PlutusData.bytes(vk.alpha()), PlutusData.bytes(vk.beta()), + PlutusData.bytes(vk.gamma()), PlutusData.bytes(vk.delta()), icData(vk.ic())); + } + + // ------------------------------------------------------------------ + // Attest + // ------------------------------------------------------------------ + + 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 + } + + @Test + @DisplayName("Attest: an honest attestation locks the reserve; every mutation is rejected") + void attest() { + var ok = evaluate(program, attestContext(Attest.NONE)); + assertSuccess(ok); + System.out.println("[SolvencyVault attest] budget: " + ok.budgetConsumed()); + for (Attest m : Attest.values()) { + if (m != Attest.NONE && evaluate(program, attestContext(m)) instanceof EvalResult.Success) { + fail("attest accepted " + m); + } + } + } + + private PlutusData attestContext(Attest m) { + Value mint = token(m == Attest.TWO_TOKENS ? 2 : 1); + if (m == Attest.EXTRA_MINT_ENTRY) mint = mint.merge(Value.singleton(PolicyId.of(VAULT), TokenName.of(new byte[] {7}), BigInteger.ONE)); + byte[] piA = m == Attest.MALFORMED_PROOF ? flipped(proof.piA()) : proof.piA(); + IntervalBound upper = switch (m) { + case AFTER_PERIOD_START -> new IntervalBound(new IntervalBoundType.Finite(BigInteger.valueOf(PERIOD_START + 1000)), false); + case NO_UPPER_BOUND -> new IntervalBound(new IntervalBoundType.PosInf(), true); + default -> new IntervalBound(new IntervalBoundType.Finite(BigInteger.valueOf(PERIOD_START)), false); + }; + var b = ScriptContextTestBuilder.minting(PolicyId.of(VAULT)).mint(mint) + .validRange(new Interval(new IntervalBound(new IntervalBoundType.NegInf(), true), upper)) + .redeemer(PlutusData.constr(0, PlutusData.bytes(piA), PlutusData.bytes(proof.piB()), PlutusData.bytes(proof.piC()))); + if (m != Attest.NO_SIGNER) b.signer(EXCHANGE); + 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()))); + } + List published = new ArrayList<>(entries); + if (m == Attest.MISSING_ENTRY) published.remove(3); + if (m == Attest.EXTRA_ENTRY) published.add(entries.getFirst()); + if (m == Attest.SWAPPED_ENTRIES) { + 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())); + 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)); + Address to = switch (m) { + case VAULT_ELSEWHERE -> EXCHANGE_ADDRESS; + case STAKED_VAULT -> STAKED_VAULT_ADDRESS; + default -> VAULT_ADDRESS; + }; + b.output(new TxOut(to, vaultValue, + new OutputDatum.OutputDatumInline(attestation(published, m == Attest.NON_CANONICAL_U)), Optional.empty())); + return b.buildPlutusData(); + } + + // ------------------------------------------------------------------ + // Release + // ------------------------------------------------------------------ + + enum Release { NONE, BEFORE_PERIOD_END, NO_LOWER_BOUND, NO_SIGNER, NO_BURN, TWO_VAULTS } + + @Test + @DisplayName("Release: after the period, with the exchange's signature and a burn; every mutation is rejected") + void release() { + assertSuccess(evaluate(program, releaseSpend(Release.NONE))); + assertSuccess(evaluate(program, releaseBurn(Release.NONE))); + for (Release m : Release.values()) { + if (m != Release.NONE && evaluate(program, releaseSpend(m)) instanceof EvalResult.Success) { + fail("release accepted " + m); + } + } + if (evaluate(program, releaseBurn(Release.TWO_VAULTS)) instanceof EvalResult.Success) { + fail("burn accepted with two vault inputs"); + } + } + + private ScriptContextTestBuilder releaseTx(Release m, ScriptContextTestBuilder b, TxOutRef ref) { + b.mint(m == Release.NO_BURN ? Value.zero() : token(-1)); + if (m != Release.NO_SIGNER) b.signer(EXCHANGE); + long from = m == Release.BEFORE_PERIOD_END ? PERIOD_END - 1000 : PERIOD_END; + IntervalBound lower = m == Release.NO_LOWER_BOUND + ? new IntervalBound(new IntervalBoundType.NegInf(), true) + : new IntervalBound(new IntervalBoundType.Finite(BigInteger.valueOf(from)), true); + b.validRange(new Interval(lower, new IntervalBound(new IntervalBoundType.PosInf(), true))); + b.input(new TxInInfo(ref, vaultOut())); + if (m == Release.TWO_VAULTS) b.input(new TxInInfo(TestDataBuilder.randomTxOutRef_typed(), vaultOut())); + b.output(new TxOut(EXCHANGE_ADDRESS, Value.lovelace(BigInteger.valueOf(RESERVES)), + new OutputDatum.NoOutputDatum(), Optional.empty())); + return b; + } + + private PlutusData releaseSpend(Release m) { + TxOutRef ref = TestDataBuilder.randomTxOutRef_typed(); + var b = ScriptContextTestBuilder.spending(ref, attestation(entries, false)).redeemer(PlutusData.constr(0)); + return releaseTx(m, b, ref).buildPlutusData(); + } + + private PlutusData releaseBurn(Release m) { + TxOutRef ref = TestDataBuilder.randomTxOutRef_typed(); + var b = ScriptContextTestBuilder.minting(PolicyId.of(VAULT)).redeemer(PlutusData.constr(1, PlutusData.integer(0))); + return releaseTx(m, b, ref).buildPlutusData(); + } + + // ------------------------------------------------------------------ + + 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()); + } + + private static PlutusData attestation(List es, boolean nonCanonical) { + 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())); + } + return PlutusData.constr(0, PlutusData.list(items)); + } + + private static Value token(long qty) { + return Value.singleton(PolicyId.of(VAULT), TokenName.of(TOKEN), BigInteger.valueOf(qty)); + } + + 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/personhood-airdrop/gradle/wrapper/gradle-wrapper.jar b/personhood-airdrop/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f8e1ee3 Binary files /dev/null and b/personhood-airdrop/gradle/wrapper/gradle-wrapper.jar differ diff --git a/private-voting/README.md b/private-voting/README.md index c4451a5..9a6105d 100644 --- a/private-voting/README.md +++ b/private-voting/README.md @@ -1,19 +1,51 @@ -# Private Voting Demo — Anonymous DAO Governance on Cardano +# Private Voting Demo — Encrypted Ballots and a Homomorphic Tally on Cardano -Cast votes in a DAO election **without revealing your identity or vote choice**. Uses zero-knowledge proofs (Groth16 on BLS12-381) with on-chain verification and a sorted linked list for nullifier-based double-vote prevention. +Cast votes in a DAO election **without revealing who you are or how you voted**. Each ballot is +an encryption of 0 or 1 under a key that a set of trustees share. Ballots are added up while +still encrypted, and only the final total is decrypted, once, after voting closes. Zero-knowledge +proofs (Groth16 on BLS12-381) are verified on-chain with Plutus V3. A sorted linked list of +nullifiers prevents double voting. -Built with [ZeroJ](https://github.com/bloxbean/zeroj) — a pure Java ZK toolkit for Cardano. +Built with [ZeroJ](https://github.com/bloxbean/zeroj), a pure Java ZK toolkit for Cardano. +Design: [ADR-0005](../docs/adr/0005-private-ballot-homomorphic-tally.md), which fixes +[issue #7](https://github.com/bloxbean/zeroj-usecases/issues/7). -## What This Demo Does +The ElGamal itself is not implemented here. The encryption relation, the trustee DLEQ relation, +and the host-side keys, admission, homomorphic sum and verified decryption all come from ZeroJ's +`elgamal-jubjub-v1` profile (ZeroJ ADR-0052 and `docs/specs/elgamal-jubjub-v1.md`). This demo +adds the voting rules around them: eligibility, nullifiers, the on-chain list and deadline, and +decrypting once. -1. **Creates an election** with 5 test voter accounts (auto-funded on Yaci DevKit) -2. **Builds a voter eligibility Merkle tree** — root published as public input -3. **Voters cast votes (YES/NO)** — ZK proof proves eligibility without revealing identity -4. **On-chain verification** — Groth16 proof verified via Plutus V3 BLS12-381 builtins -5. **Nullifier prevents double-voting** — sorted linked list on-chain -6. **Tally** — commitments on-chain are decoded to count YES/NO votes +## What This Demo Does -The proof reveals **nothing** about which voter cast the vote or how they voted. The verifier only learns: "an eligible voter cast a valid vote." +1. **Creates an election** with 5 test voters and **3 trustees**. Each trustee generates a share + of the election key and proves it knows the secret behind it. The election key is the sum of + the shares. +2. **Builds a voter eligibility Merkle tree.** Its root, the election id, the election key and the + voting deadline become parameters of the on-chain scripts. +3. **Voters cast YES or NO.** The vote is encrypted with exponential ElGamal on the Jubjub curve + (`elgamal-jubjub-v1`, width 1): `A = [k]·G`, `B = [vote]·G + [k]·PK`. A ZK proof shows that + the voter is eligible, that the nullifier is theirs, and that the ballot encrypts a 0 or a 1, + without revealing which. +4. **On-chain verification.** The ballot policy verifies the proof, with every public input taken + from its parameters or from the ledger. The vote list stores the ballot under the voter's + nullifier, so each voter can vote once. +5. **Tally after the deadline.** Anyone can add up the encrypted ballots. Each trustee decrypts + its share of the sum and proves it did so correctly. The shares together reveal the number of + YES votes. The result re-verifies from chain data and the election manifest. + +**What stays private.** +- **Public observers** see encrypted ballots, nullifiers and the final totals. They cannot open a + ballot, nor link a nullifier to a voter. +- **Trustees** cannot decrypt a single ballot unless all of them collude. Decrypting the running + total early would let anyone compare two totals and learn one vote, so the tally is decrypted + exactly once, after the deadline. +- **The vote list is public:** anyone can see how many ballots were cast and when. + +**Demo shortcuts.** The server holds every voter's and every trustee's secret and proves on their +behalf, so in this demo the server knows every vote. The protocol separates these roles; the demo +does not. The trusted setup is single-party and for development only. See +[Important Notes](#important-notes). ## Prerequisites @@ -46,7 +78,11 @@ java --enable-native-access=ALL-UNNAMED \ -jar build/libs/private-voting-*.jar ``` -Startup takes ~55 seconds (circuit compilation + trusted setup + voter account creation). +Startup takes about 2 minutes the first time (circuit compilation and the dev setup for both circuits); the keys are then cached under `data/`, and later starts are faster. + +The cache file names carry the circuit version (`setup-private-ballot-d10-v3-…`, +`setup-trustee-dleq-v2-…`). Caches from before the move to `elgamal-jubjub-v1` (names without +`-v3`/`-v2`) belong to the old circuits, are never loaded again, and can be deleted. ### 6. Open UI: **http://localhost:8086** @@ -77,9 +113,13 @@ curl -X POST http://localhost:8086/api/vote \ -H "Content-Type: application/json" \ -d '{"voterLabel":"voter1","vote":0}' -# Tally +# Tally: before the deadline only the encrypted sum; after it the decrypted totals, +# the trustee shares with their proofs, and the verification checks curl http://localhost:8086/api/results | python3 -m json.tool -# → {yes: 2, no: 1, total: 3} +# → {phase: "decrypted", yes: 2, no: 1, total: 3, verified: true, checks: [...]} + +# The election manifest: everything needed to re-check the scripts and the tally +curl http://localhost:8086/api/election/manifest | python3 -m json.tool ``` ## API Reference @@ -91,18 +131,50 @@ curl http://localhost:8086/api/results | python3 -m json.tool | POST | `/api/election/register` | Register voter (`label`, `secretKey`) | | POST | `/api/election/finalize` | Build voter Merkle tree | | POST | `/api/vote` | Cast vote (`voterLabel`, `vote`: 0=NO, 1=YES) | -| GET | `/api/results` | Tally (yes, no, total, individual votes) | +| GET | `/api/election/manifest` | Election manifest (keys and key proofs, verification keys, scripts and hashes, seed) | +| GET | `/api/results` | Tally: encrypted sum while open; totals, shares and checks after the deadline | | GET | `/api/status` | System status (circuit, election, votes) | ## How It Works -Each vote submission: -1. Generates a ZK proof (~13-27s, pure Java BLS12-381 Groth16) -2. Submits a Cardano transaction with two minting policies: - - **VoteZkMintingPolicy** — verifies the Groth16 proof on-chain - - **VoteListValidator** — inserts nullifier into sorted linked list -3. The nullifier is deterministic: `Poseidon(secretKey, electionId)` — same voter + same election = same nullifier -4. The commitment `Poseidon(vote, nullifier)` is stored on-chain for tallying +Each vote: +1. Encrypts the vote under the election's key context with fresh randomness `k` + (`ElGamal.encryptWithOpening`, width 1). The opening `(v, k)` is the proof's witness. +2. Generates a ZK proof of the ballot relation (`PrivateBallotProof`, built on + `ZkElGamal.encrypt`): 9,477 constraints at depth 10. +3. Submits a Cardano transaction, valid only until the voting deadline, in which: + - **VoteZkMintingPolicy** mints the nullifier token. It verifies the Groth16 proof against the + election id, voter root and election key fixed in its parameters, and against the ballot + read from the new list node's datum. + - **VoteListValidator** inserts a node keyed by the nullifier into the sorted list. The list + admits each nullifier once, an insert can touch only its anchor, and the root can be + created only once. +4. The nullifier is `Poseidon(secretKey, electionId)`: the same voter and the same election always + give the same nullifier. + +The election key (`ElectionService`): each trustee generates an `ElGamalSecretKey` and proves +possession of it with `TrusteeShareProof`. Each key is registered with +`VerifiedKeyShare.verify`, which hands the key proof's verifier the possession statement the +library builds, and the keys are aggregated into an n-of-n key context +(`ElGamalPublicKey.aggregate`). The manifest publishes every key encoding with its proof, so +anyone rebuilds the same context. + +The tally (`TallyService`): +1. Walks the vote list from its root. It fails closed if the list is broken, if any list token + lies outside the walk, or if any node is malformed. Each ballot is decoded with + `RawElGamalCiphertext.fromAffine` (canonical coordinates, prime-order subgroup). +2. Admits every ballot into the election's key context with `ElGamal.admit` at width 1. The + ballot proof is not re-checked: the ballot policy verified it on-chain before minting the + node's nullifier token, and admission is reached only for ciphertexts read from such nodes + (spec `elgamal-jubjub-v1` §10.1, delegated verification). Then sums them + (`ElGamalCiphertext.sum`). +3. After the deadline (plus a settling margin), asks each trustee for its decryption share + (`ElGamal.decryptionShare`) with a proof of the share's statement (`TrusteeShareProof`). A + share counts only after `VerifiedDecryptionShare.verify` accepts its proof. +4. Recovers the YES count with `ElGamal.decrypt`, which needs one verified share per trustee and + searches `[0, |ballots|]`. Publishes it with a digest of the ballot set, then re-verifies + everything from public data: the key context from the manifest, the ballots re-admitted from + the chain, the share proofs, and the decryption. ## Tech Stack @@ -123,7 +195,8 @@ private-voting/ ├── build.gradle ├── src/main/java/.../voting/ │ ├── PrivateVotingApplication.java -│ ├── circuit/PrivateVoteProof.java # Symbolic annotation ZK circuit +│ ├── circuit/PrivateBallotProof.java # Ballot relation (eligibility + ZkElGamal.encrypt) +│ ├── circuit/TrusteeShareProof.java # Key / decryption-share proofs (ZkElGamal DLEQ) │ ├── config/CardanoConfig.java # Network config │ ├── controller/ │ │ ├── ElectionController.java # Election management API @@ -133,8 +206,8 @@ private-voting/ │ │ ├── ElectionService.java # Voter registration + Merkle tree │ │ ├── AccountSetupService.java # Test account creation │ │ ├── OnChainVoteService.java # On-chain tx building -│ │ ├── TallyService.java # Vote counting -│ │ └── ProofCompressor.java # BLS point compression +│ │ ├── KeyedCircuit.java # Circuit + dev keys + JSON verification +│ │ └── TallyService.java # Homomorphic tally and verification │ └── onchain/ │ ├── VoteZkMintingPolicy.java # Groth16 verifier (Plutus V3) │ ├── VoteListValidator.java # Sorted linked list (Plutus V3) @@ -147,7 +220,42 @@ private-voting/ ## Important Notes -- Trusted setup is **dev-only** (single-party). Production requires MPC ceremony. -- Vote privacy: votes are private during voting but can be decoded during tally (commitment = Poseidon(vote, nullifier) with vote in {0,1}). For full tally privacy, a homomorphic scheme is needed. -- Each on-chain nullifier node locks ~2 ADA (reclaimable after election). -- 5 test voters are auto-created at startup with deterministic secret keys. +- **Dev trusted setup.** The setup is single-party. Whoever holds its toxic waste can forge + ballots and trustee proofs. Production needs an MPC ceremony for both circuits. +- **Trust in the trustees.** They decrypt n-of-n: all must take part (liveness), and all must + collude to open a single ballot (privacy). Threshold sharing with distributed key generation is + future work. +- **Not provided:** receipt-freeness and coercion resistance. A voter can reveal `k` to prove + their vote. A small or unanimous result also reveals how everyone voted. +- **Linkability.** On a real network, voters submitting their own transactions would link their + nullifier to their wallet through fees and timing. A relayer is needed. The demo submits every + ballot from one admin wallet. +- **Finality.** On a public network the tally must wait for the deadline plus a finality margin; + configure `election.tally-settle-seconds`. +- **Locked ADA.** Each on-chain vote node locks about 2 ADA. +- **Unauthenticated endpoints.** The demo's HTTP API is open: `GET /api/results` after the + deadline triggers the one-time decryption, and `POST /api/election/create` is refused once an + election is finalized. A real deployment authenticates trustees and the administrator. +- **Test voters.** 5 test voters are auto-created at startup with deterministic secret keys. + +## Configuration + +| Property | Default | Meaning | +|---|---|---| +| `zk.tree-depth` | 10 | Eligibility tree depth (up to 1024 voters) | +| `election.trustee-count` | 3 | Trustees holding shares of the election key | +| `election.voting-window-seconds` | 600 | Ballots are accepted until this long after startup | +| `election.tally-settle-seconds` | 20 | Wait after the deadline before decrypting | + +## Tests + +```bash +./gradlew test # circuits, ElGamal compatibility, Plutus VM mutation tests +ZEROJ_YACI_E2E=true ./gradlew test # + a full election on a running Yaci DevKit +``` + +`ElGamalCompatibilityTest` is the ciphertext-compatibility differential: the ballots fixed by an +independent Python reference (`src/test/resources/elgamal-reference/`, which re-implements +Jubjub and the tally from the curve definition without ZeroJ) are admitted, summed and decrypted +by ZeroJ's `elgamal-jubjub-v1` API, and the library's decryption shares and tally must equal the +reference's. diff --git a/private-voting/build.gradle b/private-voting/build.gradle index 40895f7..f1c02fc 100644 --- a/private-voting/build.gradle +++ b/private-voting/build.gradle @@ -101,6 +101,8 @@ test { useJUnitPlatform() jvmArgs '--enable-native-access=ALL-UNNAMED' systemProperty "zeroj.allowInsecureTrustedSetup", "true" + systemProperty "zeroj.yaci.e2e", System.getenv("ZEROJ_YACI_E2E") ?: "" + environment "ZEROJ_YACI_E2E", System.getenv("ZEROJ_YACI_E2E") ?: "" testLogging { events "passed", "failed", "skipped" showStandardStreams = true diff --git a/private-voting/frontend/src/App.svelte b/private-voting/frontend/src/App.svelte index 88f517f..8195eec 100644 --- a/private-voting/frontend/src/App.svelte +++ b/private-voting/frontend/src/App.svelte @@ -8,7 +8,22 @@ let voteResult = $state(null); let loading = $state(false); let message = $state(''); - let voteTxHashes = $state<{label: string, vote: string, txHash: string}[]>([]); + let submissions = $state<{label: string, ballotA: string, txHash: string}[]>([]); + let now = $state(Date.now()); + + $effect(() => { + const timer = setInterval(() => { now = Date.now(); }, 1000); + return () => clearInterval(timer); + }); + + function short(hex: string | undefined, n = 12) { + return hex ? hex.substring(0, n) + '…' : ''; + } + + function remaining(deadline: number) { + const s = Math.max(0, Math.floor((deadline - now) / 1000)); + return `${Math.floor(s / 60)}m ${s % 60}s`; + } async function loadStatus() { status = await api.status(); @@ -18,19 +33,15 @@ async function castVote(voterLabel: string, vote: number) { loading = true; voteResult = null; - message = `${voterLabel} is voting ${vote === 1 ? 'YES' : 'NO'}... (generating ZK proof + on-chain tx)`; + message = `${voterLabel}: encrypting the vote, proving the ballot, submitting on-chain…`; try { const result = await api.castVote(voterLabel, vote); voteResult = result; if (result.error) { message = `Failed: ${result.error}`; } else { - voteTxHashes = [...voteTxHashes, { - label: voterLabel, - vote: result.vote, - txHash: result.txHash - }]; - message = `${voterLabel} voted ${result.vote} — tx: ${result.txHash.substring(0, 16)}... (${result.provingTimeMs}ms)`; + submissions = [...submissions, { label: voterLabel, ballotA: result.ballot.A.u, txHash: result.txHash }]; + message = `${voterLabel}'s encrypted ballot is on-chain — tx ${short(result.txHash, 16)} (${result.provingTimeMs} ms to prove)`; } } catch (e: any) { message = `Error: ${e.message}`; @@ -42,13 +53,12 @@ voteResults = await api.results(); } - // Load on mount $effect(() => { loadStatus(); });

Private Voting Demo

-

Anonymous DAO governance on Cardano with zero-knowledge proofs

+

Encrypted ballots, a homomorphic tally and trustee decryption on Cardano