feat(shielded): note-based shielded balance pool for CL8Y-controlled CW20 code ids #1583

Open
opened 2026-10-29 00:32:16 +00:00 by PlasticDigits · 0 comments
Owner

Problem and scope

Build the custody and note layer for shielded balances of CL8Y-controlled CW20 assets: a new shielded-pool contract that (a) accepts deposits of allowlisted, code-id-pinned CW20s, (b) represents each deposit as a note commitment in an append-only Merkle tree, (c) authorises spending by a note key signature plus a nullifier (no wallet address in the spend path), and (d) pays out to a caller-chosen destination with an optional relayer fee.

This issue delivers the primitive only: deposit (Shield), withdraw (Unshield), change notes, note queries, liability accounting, caps, migration, and the internal settlement hook that the sibling swap issue consumes. Atomic private swaps, indexer work and dApp work are separate issues and must not be started as a partial substitute for this layer.

The scope is deliberately not a general mixer and not an anonymity system:

  • Allowlisted CL8Y-controlled CW20 code ids only; no third-party tokens, no native LUNC/USTC, no IBC assets, no P2P note transfers, no cross-pool transfers.
  • Phase 1 does not hide amounts or the note graph from a chain analyst. Public CW20 transfers and public note commitments mean deposit amounts, swap amounts and withdrawals remain public chain data. The achievable guarantee is that the DEX contracts, indexer and API never receive or publish a link between a shield key and the user's wallet, and that swaps are executed by the pool rather than by the user's address (sibling issue). Note loss is unrecoverable; stolen note keys are bearer theft.
  • A ZK membership/nullifier verifier is explicitly out of scope and gated behind a separate gas/audit decision (see § Constraints).

Current codebase and investigation

Reviewed checkout: /home/answorld/repos/cl8y-dex-terraclassic at 38c154958. No shielded, nullifier, commitment or note code exists in the repository: the only matches for shielded are unrelated comments in indexer/tests/api_evidence_daily.rs.

  • smartcontracts/Cargo.toml is a CosmWasm 1.5.11 workspace (cosmwasm-std = 1.5.11) with singleton-style contracts under smartcontracts/contracts/ (factory, pair, router, fee-discount, faucet, hooks, community-tax-token, community-tax-autolp, community-token-launcher, bridge-debt-token, bridge-debt). Shared types live in smartcontracts/packages/dex-common.
  • There is no signature verification in any contract today (ed25519_verify / secp256k1_verify are unused). There is no Merkle tree, nullifier set, commitment scheme or note store. Any note design must prove on-chain verification and gas cost on columbus-5; do not assume a precompile.
  • CW20 custody patterns to reuse: bridge-debt-token (receipt token), community-tax-autolp, and the community-tax-token Adopt path. bridge-debt / bridge-debt-token currently lack ensure_from_older_version in migrate (internal audit BD-3); do not repeat that mistake.
  • The CW20 Send hook does not necessarily deliver the declared transfer amount. community-tax-token execute_send calls tax::execute_send_hook(&to, &sender, credit, msg) with the post-tax credit, so a deposit hook must use the hook's amount/credit and never a user-declared amount. community-tax-token SendFrom extra-debits the owner (preview.debit = amount + tax for a pair-direct sell) and requires allowance.
  • Token/code-id inventory (public chain): cw20-mintable 10184; community-tax-token instances 11611 / 11619 / 11626 / 11630 (refresh per the #611 program); CL8Y token instance; bridge-debt-token instance. Current factory whitelist is [6036, 8266, 10184, 11611, 11619, 11630] per the deploy traces; 6036 (TerraSwap legacy) and 8266 (third-party template) are not CL8Y-controlled and must not be admitted by this feature. The cw20-codeid-audits catalogue documents known-bad fee-on-transfer/ALPHA 8654.
  • The code-id guard pattern is smartcontracts/contracts/pair/src/asset_code_id_guard.rs: pin the live ContractInfo.code_id at instantiate/refresh, re-check it on every write, and require the factory IsCodeIdWhitelisted query. Errors fail closed (AssetCodeIdGuardUnavailable). The pool must mirror this rather than trusting a stored address alone.
  • Governance and upgrades: factory governance / DEX 2-of-3, wasm-admin migration runbook docs/runbooks/wasm-admin-migration.md, code-id audit procedure cw20-codeid-audits/PROCEDURE.md, TVL/security ladder in docs/security-posture.md, retail gas census ADR docs/adr/0004-terraclassic-retail-gas-census.md, evidence/privacy precedent in docs/qa/issue-1397/README.md.
  • QA conventions: docs/qa/issue-<N>/README.md, scripts/qa/verify-issue-<N>.sh or scripts/verify-issue-<N>.sh, and a make verify-issue-<N> target. LocalTerra patterns are in docs/localterra-sdk53.md, scripts/setup-cloud-agent-localterra.sh, and docs/runbooks/.

Why a new implementation is needed

All CL8Y-controlled balances and swaps are currently attributable to a wallet address: pair emits sender/receiver, community-tax-token records exemptions and guard state per address, and the indexer publishes swap_events.sender, /api/v1/pairs/{addr}/trades, /api/v1/traders/{addr}, trader_positions and leaderboards. Users who hold or trade CL8Y, community-tax tokens or cw20-mintable assets have no supported path that keeps their position and trading out of the DEX's own data products, and no way to hold a pooled balance that is spendable by a key rather than by a wallet account.

A note-based custody contract is the minimal on-chain primitive that makes a private swap path possible: it aggregates balances at one address, authorises spends without exposing the wallet, and gives the swap issue an atomic settlement point. Without it, any "private" frontend would merely be a wallet-address rotation, which provides no DEX-level non-attribution and no atomic swap output.

Relevant files

New work:

  • smartcontracts/contracts/shielded-pool/Cargo.toml
  • smartcontracts/contracts/shielded-pool/src/{lib,contract,msg,state,error,note,tree,spend,query,tests,multitest}.rs
  • smartcontracts/Cargo.toml (workspace member)
  • smartcontracts/packages/dex-common/src/ (only if shared types are required by the sibling router/swap issue)
  • scripts/qa/verify-issue-<N>.sh, Makefile
  • docs/shielded-pool.md, docs/qa/issue-<N>/README.md, skills/AGENTS_SHIELDED_POOL.md
  • Updates: docs/security-model.md, docs/security-posture.md, docs/contracts-security-audit.md, docs/runbooks/wasm-admin-migration.md, docs/runbooks/cw20-whitelist-policy.md

Reference implementations to read before coding: smartcontracts/contracts/pair/src/asset_code_id_guard.rs, smartcontracts/contracts/community-tax-token/src/{contract,tax}.rs, smartcontracts/contracts/bridge-debt-token/src/contract.rs, smartcontracts/contracts/factory/src/contract.rs (WHITELISTED_CODE_IDS), docs/adr/0004-terraclassic-retail-gas-census.md.

  1. New crate, no changes to existing contracts in this issue. Instantiate with { factory, governance, router, allowed_tokens, limits }. router is stored for the sibling swap issue; the pool must not call it yet.

  2. Note model (versioned). A note opening is
    { version: u8, token: Addr, amount: Uint128, owner_pubkey: Binary (32-byte ed25519 public key), blinding: Binary (32 bytes), leaf_index: u32 }.
    commitment = SHA256("cl8y-shielded-note-v1" || chain_id || pool_addr || token || amount || owner_pubkey || blinding).
    Compute commitments inside the contract from the opening; never accept an externally supplied commitment as authoritative. Bind chain_id and the pool address so proofs and signatures cannot be replayed across chains or pools. Keep version in the preimage so a future encrypted/ZK note version can coexist.

  3. Tree and nullifier state. Append-only Merkle tree of depth 32 with SHA256 pair hashing and a zero-subtree optimisation. Persist only the nodes/frontier needed for insertion and proofs; store a bounded history of recent roots (at least 64, configurable) so a note inserted while a spend is prepared remains spendable. NULLIFIERS: Map<[u8;32], NullifierRecord { height, tx_index }>; a nullifier is SHA256("cl8y-shielded-nullifier-v1" || commitment) — deterministic, single-use, and not secret. Do not reuse a nullifier domain across note versions.

  4. Deposit (Receive(Cw20ReceiveMsg)). Accept only Cw20HookMsg::ShieldNote { owner_pubkey, blinding } from an allowlisted token contract. Validate: token is allowlisted and its live code_id equals the pin and is factory-whitelisted (mirror asset_code_id_guard); amount > 0; decimals 6–18 (decimals are display-only; do not do unit conversion on-chain); per-note min/max; per-token TVL cap; per-block and per-address deposit caps; note key is a valid 32-byte ed25519 key and is not the pool/factory/router address; deposit delay config. Use the hook's amount (post-tax credit), not a declared amount. Insert the note, increase per-token LIABILITY, emit action=shield_note with the commitment, token, amount, owner pubkey, leaf index and the new root. Because public CW20 transfers and public openings are phase-1 policy, the deposit event may carry the opening; the note's safety must not depend on keeping the opening secret — authorisation is the owner key signature, not knowledge of the opening.

  5. Withdraw (Unshield). Input a single note opening plus its Merkle path against a stored root (any root in history), a nullifier, destination, relayer_fee, deadline, and an ed25519 signature. Verify in this order: deadline → note is well formed and token allowlisted/pinned → commitment matches → path matches a stored root → note key is the signer → nullifier unused → fee ≤ configured cap and ≤ amount → destination validates and is not blacklisted (factory BlacklistCheck) → mark the nullifier, decrease liability, transfer amount - fee to destination and fee to info.sender if non-zero. Emit a spend event with the nullifier and leaf index but no wallet address. A failed transfer must revert the whole call (no partial state).

  6. Change notes and output notes. The pool creates output notes itself with a fresh blinding (SHA256(pool || nullifier || leaf_index || output_counter) is acceptable because openings are public in phase 1) and the owner pubkey bound in the signed digest. Change = input note amount − withdrawn amount − relayer fee. Never accept a user-supplied output blinding in phase 1; that only creates a theft surface with no safety benefit. Insert output notes in the same call and emit them.

  7. Canonical spend digest. Define one documented digest used by Unshield and by the sibling swap issue:
    SHA256(domain || chain_id || pool || version || token || amount || leaf_index || commitment || nullifier || relayer_fee || len(destination) || destination || output_owner_pubkey || deadline || context_hash),
    where context_hash is SHA256("unshield") or the swap-route digest supplied by the sibling issue. Verify with cosmwasm_std::ed25519_verify; record the measured gas and wasmvm support on columbus-5. If ed25519 verification is not available or is outside the retail gas envelope, fall back to secp256k1_verify and document the change; do not ship a hand-rolled curve implementation.

  8. Swap settlement primitive (defined here, used later). Expose an internal CommitSwapOutput { pending_id, token, min_output, owner_pubkey, relayer_fee? , deadline } hook that is callable only by the stored router, only while a PENDING_SETTLEMENT entry with that pending_id exists in the current tx, and only for an allowlisted token. It computes the output note from the actual received credit, checks >= min_output, inserts the note, updates liability, clears the pending entry, and must be exactly-once. Unshield and the sibling PrivateSwap share the same note/liability code. If the router cannot deliver a hook, the recommended fallback is a submessage reply that reads the pool's post-swap CW20 balance delta under a per-tx pending record; both options need tests proving no cross-credit between two swaps in one tx.

  9. Queries. Config, AllowedToken { token }, Root, RootHistory, NoteCount, Note { leaf_index } (commitment + token/amount metadata only), Nullifier { nullifier }, Liability { token }, Reconcile {} (on-chain CW20 balance vs liability per allowlisted token), PendingSettlement. Do not add a qeury that filters notes by owner pubkey; note discovery is the indexer issue's range-based endpoint.

  10. Admin surface. UpdateConfig (governance) may add/remove tokens, change caps, deposit delay, relayer fee cap and root-history length; PauseDeposits blocks new deposits only. There must be no admin message that moves pool funds, spends a note, burns a nullifier, or blocks a withdrawal. Governance can rotate the router only while no settlement is pending. Migration must preserve the tree, nullifier set, liability and pending state, and must reject a version downgrade/unknown version (ensure_from_older_version pattern, see BD-3).

  11. Privacy statement. Write docs/shielded-pool.md with an explicit claim matrix: what is hidden (the DEX's own attribution; the swap sender is the pool), what is public (amounts, deposit tx, note graph, timings), what is not provided (anonymity, amount privacy, sanction-resistant mixing), and what the user must do (fresh, unlinked deposit source; one key per deposit; no destination reuse). Any "anonymity"/"mixer" wording is forbidden. The dApp notice is the frontend issue's responsibility, but the contract-level docs must be correct first.

Constraints and guardrails

  • Token admission: allowlist only instances whose live code_id is pinned and factory-whitelisted, and whose initial set is limited to cw20-mintable 10184, the current community-tax-token instance ids, bridge-debt-token, and the CL8Y token instance. Exclude 6036, 8266, 8654 and every third-party/rebase/fee-on-transfer token. Adding a code id is a governance action with a written review; a code-id drift or failed factory query fails closed.
  • Solvency: per-token LIABILITY must equal the sum of unspent note amounts plus pending settlement inputs. The pool's CW20 balance must be >= LIABILITY. Any discrepancy is a bug: fail the write that would increase it and expose Reconcile; do not add an admin "fix" path.
  • No rehypothecation: pool balances are never lent, staked, deposited into AutoLP or used as a treasury. No hooks on deposits/withdrawals except the router settlement hook.
  • No fund-moving admin: no pause/withdraw/blacklist message on notes. Withdrawals remain live while deposits are paused. The only privileged actions are token/config changes, deposit pause and router rotation under the restriction above.
  • Caps and abuse bounds: note min/max, per-token TVL cap, per-block deposit count/size, per-address deposit cap per epoch, root-history length, note count (tree depth) and nullifier growth are bounded and configurable. Per-address caps are for spam/structuring bounds, not a privacy feature; do not assert sybil resistance.
  • Tax and guard interaction: a deposit of a community-tax-token may incur the configured transfer tax (the hook amount is the net credit) and a swap by the pool may incur sell/buy tax (sibling issue). The pool must never be registered as protocol-exempt or manager-exempt, and must never use another wallet's exemption. Do not add the pool to PROTOCOL_EXEMPT, MANAGER_EXEMPT or the fee-discount registry.
  • Gas and wasm: use make build-optimized and record checksums. Measure deposit, withdraw, change-note and no-op gas on LocalTerra; document the envelope and the ed25519 verify cost in docs/shielded-pool.md. If verification exceeds the retail envelope, stop and revise the design rather than shipping an unusable contract.
  • Dependencies: prefer sha2 and the cosmwasm-std crypto API. Any new curve/cipher dependency needs a written justification, licence/supply-chain review (docs/supply-chain-security.md), and a cw20-codeid-audits-style decompile of the built wasm. Do not vendor crypto code.
  • Data hygiene: never put a wallet address, note private key, API key, mnemonic or user conversation into storage, events, tests, fixtures, issue text or logs. Public chain identifiers are fine. Note keys in tests must be deterministic test vectors, clearly marked non-production.
  • Compatibility: do not change pair, router, factory, community-tax-token or cw20-mintable behaviour in this issue. The settlement hook may be unreachable until the sibling issue lands; tests may exercise it with a stub router.

Acceptance criteria

  • AC1: A new shielded-pool contract builds with the optimized optimizer, is schema-exported, has a cw2 identity, a versioned migrate that preserves tree/nullifiers/liability/pending state, and rejects unknown or older versions.
  • AC2: Deposit accepts only allowlisted, pinned, factory-whitelisted CW20s; rejects native, unknown tokens, code-id drift, factory-query failure, zero/under-min/over-max amounts, invalid note keys, and pool/factory/router-owned notes. It credits the hook's post-tax amount, never a declared amount.
  • AC3: Note commitments bind chain id, pool address, version, token, amount, owner key and blinding. Replaying the same opening on another chain/pool or under another version fails.
  • AC4: Unshield verifies deadline, membership against a historical root, key signature, nullifier freshness and destination; pays amount - fee to the destination and fee to the submitter; consumes the nullifier exactly once; never leaves partial state on a failed CW20 transfer.
  • AC5: Two spends of the same note in one tx, in different txs, or in different orders fail on the second; a note inserted after the proof was built is spendable via a stored root, and a note older than the root window produces a deterministic error (not a panic).
  • AC6: Change and settlement outputs are created by the pool with pool-chosen blindings and the owner key from the signed digest; a submitter cannot substitute its own key, destination, fee or amount.
  • AC7: Reconcile/liability accounting matches the contract's CW20 balances across deposit, withdraw, change, settlement, tax-affected deposits and failed calls; Reconcile is exposed and tested.
  • AC8: No admin message can move, spend, pause or seize notes; PauseDeposits does not block Unshield; migration preserves pending settlements or refuses to migrate while one exists.
  • AC9: Caps (note min/max, TVL, per-block, per-address) fail closed and are documented; the allowlist is governance-controlled and code-id-pinned.
  • AC10: docs/shielded-pool.md contains the claim matrix, failure modes, gas envelope, key/backup model and the explicit "not an anonymity system / not a mixer" statement; security docs and invariant matrix are updated; make verify-issue-<N> and docs/qa/issue-<N>/README.md exist.
  • AC11: The settlement hook is callable only by the configured router with an existing pending id, is exactly-once, rejects output below min_output, and cannot be satisfied by a third party sending tokens to the pool.

Test plan: functional paths

Path Required checks
Deposit Allowed tokens 10184 / community-tax-token / bridge-debt-token / CL8Y; 6, 9, 12 and 18 decimals; min-1, min, max, over-max; zero; duplicate blinding; invalid/short/oversized pubkey; pool/factory/router key; transfer tax >0 (note = post-tax credit); deposit pause; per-block/per-address/TVL caps; event fields and leaf index; root history growth.
Note tree Empty tree; first insert; 2, 3, 32, 33, 1024 inserts; proof verification for every leaf at multiple depths; sibling/zero-subtree correctness; historical root spend; root eviction; proof for a non-existent/renumbered leaf; deterministic error for an unknown root.
Spend Withdraw all, withdraw partial (change), zero-fee, max-fee, over-cap fee; destination = fresh address, = submitter, = pool, = invalid, = blacklisted; deadline = now, now+1, past; signature valid/invalid/malleable/wrong key/wrong digest field; replay same tx; two notes in one tx; failed CW20 transfer (insufficient pool balance forced by a test mutant) must revert.
Change/output Change amount = input − withdraw − fee; dust change; zero change; output amount >= min; output below min reverts; pool-chosen blinding; owner key binding; commitment recomputation; multiple outputs in one tx are distinct.
Settlement stub Exactly-once CommitSwapOutput; wrong router; missing pending id; wrong token; below min; duplicate same tx; pending expiry/deadline; third-party token donation without a pending id; migration while pending.
Queries/admin Config, Root, RootHistory, Note, Nullifier, Liability, Reconcile, PendingSettlement; UpdateConfig auth; token add/remove auth; router rotation while pending rejected; PauseDeposits auth and effect; unknown message/version rejected.
Migration v1 → v2 preserves leaf count, roots, nullifiers, liability, pending settlement, config and token pins; version rollback rejected; state-compatible schema check; old proofs still verify.
Gas Deposit, withdraw (with/without change, with/without fee), settlement, and ed25519 verification measured on LocalTerra; record p50/max and compare with the documented envelope.

Test plan: attacks, hacks and abuse

  • Double spend / replay: same note twice sequentially and concurrently; same signed digest on another pool/chain/version; signature reused with altered destination, fee, amount, token, owner key or deadline. All must fail.
  • Forgery: random/zero/all-0xff signatures, wrong key type, public key not 32 bytes, digest length tricks, signature malleability, and a note whose commitment is recomputed with a different blinding. No path may accept a signature from any key other than the note's.
  • Theft / redirection: submitter substitutes its own destination, owner key, change blindings, fee recipient or fee amount; a griefer front-runs a spend with a copied calldata and a different destination; a relayer withholds the change note. Verify only the signed destination/owner can receive and that the change note stays spendable by the owner.
  • Tree manipulation: forged Merkle path, wrong sibling order, proof for a leaf from another root, path for the zero subtree, leaf index overflow, tree depth overflow/panic, and a proof generated against a root that was never inserted.
  • Nullifier abuse: pre-computing a nullifier from a public opening and burning it without a valid spend; nullifier collision across versions/domains; reusing a nullifier in another pool; nullifier map growth griefing (bounded by min note/deposit caps; measure storage growth).
  • Token abuse: fee-on-transfer/rebase token masquerading under an allowed address via MsgMigrateContract (code-id drift must fail); a token that re-enters receive; a token whose transfer returns without transferring; decimals >18 or 0; a token that burns on transfer; community-tax SendFrom allowance weirdness. No deposit may inflate liability above the actual credit.
  • Solvency / accounting: deposit-then-tax mismatch, failed transfer after state mutation, settlement double-credit, two swaps in one tx cross-crediting, donation to the pool, withdrawal of the last note, and a forced liability > balance. Every case must revert or be visible through Reconcile; never silently mint a note.
  • Admin / governance: non-governance UpdateConfig/pause/router rotation; governance attempts to add a token that is not pinned/whitelisted; adding the pool to a token's exemption map (out of contract, but test the token side does not let the pool evade tax); wasm migration with malformed/old state; a rogue token address that self-reports an allowed code id.
  • DoS and resource: oversized hook payloads, many deposits in one tx/block, deep root history, note count at the tree bound, unlimited query ranges, and contracts returning huge metadata. Bound all loops and storage writes.
  • Privacy leakage: note openings/keys in errors, attributes, logs, tests, fixtures or docs; an indexer-visible query that filters by owner key; a spend attribute that includes the submitter as "owner". Prove the emitted attributes and query surface contain only the documented public fields.

Verification criteria

  • make verify-issue-<N> runs cargo fmt --check, cargo clippy -D warnings, unit + multitest tests for the new crate, schema export check, the workspace build, and the documentation cross-link check.
  • Multitest uses the real cw20-mintable analogue, the real community-tax-token crate (including tax >0 and SendFrom extra-debit) and a bridge-debt-token analogue; the fee-on-transfer/ALPHA mutant is rejected.
  • LocalTerra E2E (opt-in flag, e.g. VERIFY_ISSUE_<N>_CHAIN=1): store + instantiate the optimized pool, deposit via cw20-mintable, withdraw to a fresh address, deposit via community-tax-token, verify the tax affects the note and the pool balance matches Reconcile. Capture transaction receipts without any personal or wallet data.
  • Gas receipts from LocalTerra are attached to docs/qa/issue-<N>/README.md, including ed25519 verification and a comparison to the retail envelope; a failure to stay within the envelope is reported as FAIL, not skipped.
  • docs/shielded-pool.md, docs/security-model.md, docs/security-posture.md, docs/contracts-security-audit.md, docs/runbooks/wasm-admin-migration.md and the new agent skill are updated and cross-linked.
  • docs/qa/issue-<N>/README.md records the agent checklist, explicit skip policy and evidence. Unavailable live/device checks may be explicit SKIP with overall PASS WITH SKIPS; executed failures remain FAIL.
  • No user conversation, personal data, wallet-owner identity or private key appears in issue text, docs, fixtures, logs or receipts.

Out of scope / follow-ups

  • Atomic private swaps and tax/route binding: #1584.
  • Indexer classification, non-attribution, note discovery: #1585.
  • dApp vault, backup, shield/swap/unshield UX: #1586.
  • Threat model, abuse policy, relayer operations, monitoring and staged rollout: #1587.
  • Encrypted note payloads, ZK membership/nullifier proofs, ring signatures, P2P notes, cross-pool transfers, limit orders, native-asset shielding: not in phase 1. A ZK or cipher design may only start after this layer is audited and the gas envelope is measured.
## Problem and scope Build the custody and note layer for **shielded balances** of CL8Y-controlled CW20 assets: a new `shielded-pool` contract that (a) accepts deposits of allowlisted, code-id-pinned CW20s, (b) represents each deposit as a note commitment in an append-only Merkle tree, (c) authorises spending by a note key signature plus a nullifier (no wallet address in the spend path), and (d) pays out to a caller-chosen destination with an optional relayer fee. This issue delivers the primitive only: deposit (`Shield`), withdraw (`Unshield`), change notes, note queries, liability accounting, caps, migration, and the internal settlement hook that the sibling swap issue consumes. Atomic private swaps, indexer work and dApp work are separate issues and must not be started as a partial substitute for this layer. The scope is deliberately **not** a general mixer and **not** an anonymity system: - Allowlisted CL8Y-controlled CW20 code ids only; no third-party tokens, no native LUNC/USTC, no IBC assets, no P2P note transfers, no cross-pool transfers. - Phase 1 does **not** hide amounts or the note graph from a chain analyst. Public CW20 transfers and public note commitments mean deposit amounts, swap amounts and withdrawals remain public chain data. The achievable guarantee is that the DEX contracts, indexer and API never receive or publish a link between a shield key and the user's wallet, and that swaps are executed by the pool rather than by the user's address (sibling issue). Note loss is unrecoverable; stolen note keys are bearer theft. - A ZK membership/nullifier verifier is explicitly out of scope and gated behind a separate gas/audit decision (see § Constraints). ## Current codebase and investigation Reviewed checkout: `/home/answorld/repos/cl8y-dex-terraclassic` at `38c154958`. No shielded, nullifier, commitment or note code exists in the repository: the only matches for `shielded` are unrelated comments in `indexer/tests/api_evidence_daily.rs`. - `smartcontracts/Cargo.toml` is a CosmWasm 1.5.11 workspace (`cosmwasm-std = 1.5.11`) with singleton-style contracts under `smartcontracts/contracts/` (factory, pair, router, fee-discount, faucet, hooks, community-tax-token, community-tax-autolp, community-token-launcher, bridge-debt-token, bridge-debt). Shared types live in `smartcontracts/packages/dex-common`. - There is **no signature verification** in any contract today (`ed25519_verify` / `secp256k1_verify` are unused). There is no Merkle tree, nullifier set, commitment scheme or note store. Any note design must prove on-chain verification and gas cost on columbus-5; do not assume a precompile. - CW20 custody patterns to reuse: `bridge-debt-token` (receipt token), `community-tax-autolp`, and the `community-tax-token` `Adopt` path. `bridge-debt` / `bridge-debt-token` currently lack `ensure_from_older_version` in `migrate` (internal audit BD-3); do not repeat that mistake. - The CW20 `Send` hook does not necessarily deliver the declared transfer amount. `community-tax-token` `execute_send` calls `tax::execute_send_hook(&to, &sender, credit, msg)` with the **post-tax credit**, so a deposit hook must use the hook's `amount`/credit and never a user-declared amount. `community-tax-token` `SendFrom` extra-debits the owner (`preview.debit = amount + tax` for a pair-direct sell) and requires allowance. - Token/code-id inventory (public chain): `cw20-mintable` **10184**; `community-tax-token` instances **11611 / 11619 / 11626 / 11630** (refresh per the #611 program); CL8Y token instance; `bridge-debt-token` instance. Current factory whitelist is `[6036, 8266, 10184, 11611, 11619, 11630]` per the deploy traces; **6036** (TerraSwap legacy) and **8266** (third-party template) are not CL8Y-controlled and must not be admitted by this feature. The `cw20-codeid-audits` catalogue documents known-bad fee-on-transfer/ALPHA **8654**. - The code-id guard pattern is `smartcontracts/contracts/pair/src/asset_code_id_guard.rs`: pin the live `ContractInfo.code_id` at instantiate/refresh, re-check it on every write, and require the factory `IsCodeIdWhitelisted` query. Errors fail closed (`AssetCodeIdGuardUnavailable`). The pool must mirror this rather than trusting a stored address alone. - Governance and upgrades: factory governance / DEX 2-of-3, wasm-admin migration runbook `docs/runbooks/wasm-admin-migration.md`, code-id audit procedure `cw20-codeid-audits/PROCEDURE.md`, TVL/security ladder in `docs/security-posture.md`, retail gas census ADR `docs/adr/0004-terraclassic-retail-gas-census.md`, evidence/privacy precedent in `docs/qa/issue-1397/README.md`. - QA conventions: `docs/qa/issue-<N>/README.md`, `scripts/qa/verify-issue-<N>.sh` or `scripts/verify-issue-<N>.sh`, and a `make verify-issue-<N>` target. LocalTerra patterns are in `docs/localterra-sdk53.md`, `scripts/setup-cloud-agent-localterra.sh`, and `docs/runbooks/`. ## Why a new implementation is needed All CL8Y-controlled balances and swaps are currently attributable to a wallet address: `pair` emits `sender`/`receiver`, `community-tax-token` records exemptions and guard state per address, and the indexer publishes `swap_events.sender`, `/api/v1/pairs/{addr}/trades`, `/api/v1/traders/{addr}`, `trader_positions` and leaderboards. Users who hold or trade CL8Y, community-tax tokens or `cw20-mintable` assets have no supported path that keeps their position and trading out of the DEX's own data products, and no way to hold a pooled balance that is spendable by a key rather than by a wallet account. A note-based custody contract is the minimal on-chain primitive that makes a private swap path possible: it aggregates balances at one address, authorises spends without exposing the wallet, and gives the swap issue an atomic settlement point. Without it, any "private" frontend would merely be a wallet-address rotation, which provides no DEX-level non-attribution and no atomic swap output. ## Relevant files New work: - `smartcontracts/contracts/shielded-pool/Cargo.toml` - `smartcontracts/contracts/shielded-pool/src/{lib,contract,msg,state,error,note,tree,spend,query,tests,multitest}.rs` - `smartcontracts/Cargo.toml` (workspace member) - `smartcontracts/packages/dex-common/src/` (only if shared types are required by the sibling router/swap issue) - `scripts/qa/verify-issue-<N>.sh`, `Makefile` - `docs/shielded-pool.md`, `docs/qa/issue-<N>/README.md`, `skills/AGENTS_SHIELDED_POOL.md` - Updates: `docs/security-model.md`, `docs/security-posture.md`, `docs/contracts-security-audit.md`, `docs/runbooks/wasm-admin-migration.md`, `docs/runbooks/cw20-whitelist-policy.md` Reference implementations to read before coding: `smartcontracts/contracts/pair/src/asset_code_id_guard.rs`, `smartcontracts/contracts/community-tax-token/src/{contract,tax}.rs`, `smartcontracts/contracts/bridge-debt-token/src/contract.rs`, `smartcontracts/contracts/factory/src/contract.rs` (`WHITELISTED_CODE_IDS`), `docs/adr/0004-terraclassic-retail-gas-census.md`. ## Recommended direction 1. **New crate, no changes to existing contracts in this issue.** Instantiate with `{ factory, governance, router, allowed_tokens, limits }`. `router` is stored for the sibling swap issue; the pool must not call it yet. 2. **Note model (versioned).** A note opening is `{ version: u8, token: Addr, amount: Uint128, owner_pubkey: Binary (32-byte ed25519 public key), blinding: Binary (32 bytes), leaf_index: u32 }`. `commitment = SHA256("cl8y-shielded-note-v1" || chain_id || pool_addr || token || amount || owner_pubkey || blinding)`. Compute commitments inside the contract from the opening; never accept an externally supplied commitment as authoritative. Bind `chain_id` and the pool address so proofs and signatures cannot be replayed across chains or pools. Keep `version` in the preimage so a future encrypted/ZK note version can coexist. 3. **Tree and nullifier state.** Append-only Merkle tree of depth **32** with SHA256 pair hashing and a zero-subtree optimisation. Persist only the nodes/frontier needed for insertion and proofs; store a bounded history of recent roots (at least 64, configurable) so a note inserted while a spend is prepared remains spendable. `NULLIFIERS: Map<[u8;32], NullifierRecord { height, tx_index }>`; a nullifier is `SHA256("cl8y-shielded-nullifier-v1" || commitment)` — deterministic, single-use, and not secret. Do not reuse a nullifier domain across note versions. 4. **Deposit (`Receive(Cw20ReceiveMsg)`).** Accept only `Cw20HookMsg::ShieldNote { owner_pubkey, blinding }` from an allowlisted token contract. Validate: token is allowlisted and its live `code_id` equals the pin and is factory-whitelisted (mirror `asset_code_id_guard`); `amount > 0`; decimals 6–18 (**decimals are display-only; do not do unit conversion on-chain**); per-note min/max; per-token TVL cap; per-block and per-address deposit caps; note key is a valid 32-byte ed25519 key and is not the pool/factory/router address; deposit delay config. Use the hook's `amount` (post-tax credit), not a declared amount. Insert the note, increase per-token `LIABILITY`, emit `action=shield_note` with the commitment, token, amount, owner pubkey, leaf index and the new root. Because public CW20 transfers and public openings are phase-1 policy, the deposit event may carry the opening; the note's safety must not depend on keeping the opening secret — **authorisation is the owner key signature, not knowledge of the opening**. 5. **Withdraw (`Unshield`).** Input a single note opening plus its Merkle path against a stored root (any root in history), a `nullifier`, `destination`, `relayer_fee`, `deadline`, and an ed25519 signature. Verify in this order: deadline → note is well formed and token allowlisted/pinned → commitment matches → path matches a stored root → note key is the signer → nullifier unused → fee ≤ configured cap and ≤ amount → destination validates and is not blacklisted (factory `BlacklistCheck`) → mark the nullifier, decrease liability, transfer `amount - fee` to `destination` and `fee` to `info.sender` if non-zero. Emit a spend event with the nullifier and leaf index but **no wallet address**. A failed transfer must revert the whole call (no partial state). 6. **Change notes and output notes.** The pool creates output notes itself with a fresh blinding (`SHA256(pool || nullifier || leaf_index || output_counter)` is acceptable because openings are public in phase 1) and the owner pubkey bound in the signed digest. Change = input note amount − withdrawn amount − relayer fee. Never accept a user-supplied output blinding in phase 1; that only creates a theft surface with no safety benefit. Insert output notes in the same call and emit them. 7. **Canonical spend digest.** Define one documented digest used by `Unshield` and by the sibling swap issue: `SHA256(domain || chain_id || pool || version || token || amount || leaf_index || commitment || nullifier || relayer_fee || len(destination) || destination || output_owner_pubkey || deadline || context_hash)`, where `context_hash` is `SHA256("unshield")` or the swap-route digest supplied by the sibling issue. Verify with `cosmwasm_std::ed25519_verify`; record the measured gas and wasmvm support on columbus-5. If ed25519 verification is not available or is outside the retail gas envelope, fall back to `secp256k1_verify` and document the change; do not ship a hand-rolled curve implementation. 8. **Swap settlement primitive (defined here, used later).** Expose an internal `CommitSwapOutput { pending_id, token, min_output, owner_pubkey, relayer_fee? , deadline }` hook that is callable only by the stored `router`, only while a `PENDING_SETTLEMENT` entry with that `pending_id` exists in the current tx, and only for an allowlisted token. It computes the output note from the actual received credit, checks `>= min_output`, inserts the note, updates liability, clears the pending entry, and must be exactly-once. `Unshield` and the sibling `PrivateSwap` share the same note/liability code. If the router cannot deliver a hook, the recommended fallback is a submessage reply that reads the pool's post-swap CW20 balance delta under a per-tx pending record; both options need tests proving no cross-credit between two swaps in one tx. 9. **Queries.** `Config`, `AllowedToken { token }`, `Root`, `RootHistory`, `NoteCount`, `Note { leaf_index }` (commitment + token/amount metadata only), `Nullifier { nullifier }`, `Liability { token }`, `Reconcile {}` (on-chain CW20 balance vs liability per allowlisted token), `PendingSettlement`. Do not add a qeury that filters notes by owner pubkey; note discovery is the indexer issue's range-based endpoint. 10. **Admin surface.** `UpdateConfig` (governance) may add/remove tokens, change caps, deposit delay, relayer fee cap and root-history length; `PauseDeposits` blocks new deposits only. There must be **no** admin message that moves pool funds, spends a note, burns a nullifier, or blocks a withdrawal. Governance can rotate the router only while no settlement is pending. Migration must preserve the tree, nullifier set, liability and pending state, and must reject a version downgrade/unknown version (`ensure_from_older_version` pattern, see BD-3). 11. **Privacy statement.** Write `docs/shielded-pool.md` with an explicit claim matrix: what is hidden (the DEX's own attribution; the swap sender is the pool), what is public (amounts, deposit tx, note graph, timings), what is not provided (anonymity, amount privacy, sanction-resistant mixing), and what the user must do (fresh, unlinked deposit source; one key per deposit; no destination reuse). Any "anonymity"/"mixer" wording is forbidden. The dApp notice is the frontend issue's responsibility, but the contract-level docs must be correct first. ## Constraints and guardrails - **Token admission:** allowlist only instances whose live `code_id` is pinned **and** factory-whitelisted, and whose initial set is limited to `cw20-mintable` 10184, the current `community-tax-token` instance ids, `bridge-debt-token`, and the CL8Y token instance. Exclude 6036, 8266, 8654 and every third-party/rebase/fee-on-transfer token. Adding a code id is a governance action with a written review; a code-id drift or failed factory query fails closed. - **Solvency:** per-token `LIABILITY` must equal the sum of unspent note amounts plus pending settlement inputs. The pool's CW20 balance must be `>= LIABILITY`. Any discrepancy is a bug: fail the write that would increase it and expose `Reconcile`; do not add an admin "fix" path. - **No rehypothecation:** pool balances are never lent, staked, deposited into AutoLP or used as a treasury. No hooks on deposits/withdrawals except the router settlement hook. - **No fund-moving admin:** no pause/withdraw/blacklist message on notes. Withdrawals remain live while deposits are paused. The only privileged actions are token/config changes, deposit pause and router rotation under the restriction above. - **Caps and abuse bounds:** note min/max, per-token TVL cap, per-block deposit count/size, per-address deposit cap per epoch, root-history length, note count (tree depth) and nullifier growth are bounded and configurable. Per-address caps are for spam/structuring bounds, not a privacy feature; do not assert sybil resistance. - **Tax and guard interaction:** a deposit of a `community-tax-token` may incur the configured transfer tax (the hook amount is the net credit) and a swap by the pool may incur sell/buy tax (sibling issue). The pool must never be registered as protocol-exempt or manager-exempt, and must never use another wallet's exemption. Do not add the pool to `PROTOCOL_EXEMPT`, `MANAGER_EXEMPT` or the fee-discount registry. - **Gas and wasm:** use `make build-optimized` and record checksums. Measure deposit, withdraw, change-note and no-op gas on LocalTerra; document the envelope and the ed25519 verify cost in `docs/shielded-pool.md`. If verification exceeds the retail envelope, stop and revise the design rather than shipping an unusable contract. - **Dependencies:** prefer `sha2` and the `cosmwasm-std` crypto API. Any new curve/cipher dependency needs a written justification, licence/supply-chain review (`docs/supply-chain-security.md`), and a `cw20-codeid-audits`-style decompile of the built wasm. Do not vendor crypto code. - **Data hygiene:** never put a wallet address, note private key, API key, mnemonic or user conversation into storage, events, tests, fixtures, issue text or logs. Public chain identifiers are fine. Note keys in tests must be deterministic test vectors, clearly marked non-production. - **Compatibility:** do not change `pair`, `router`, `factory`, `community-tax-token` or `cw20-mintable` behaviour in this issue. The settlement hook may be unreachable until the sibling issue lands; tests may exercise it with a stub router. ## Acceptance criteria - [ ] AC1: A new `shielded-pool` contract builds with the optimized optimizer, is schema-exported, has a cw2 identity, a versioned migrate that preserves tree/nullifiers/liability/pending state, and rejects unknown or older versions. - [ ] AC2: Deposit accepts only allowlisted, pinned, factory-whitelisted CW20s; rejects native, unknown tokens, code-id drift, factory-query failure, zero/under-min/over-max amounts, invalid note keys, and pool/factory/router-owned notes. It credits the hook's post-tax amount, never a declared amount. - [ ] AC3: Note commitments bind chain id, pool address, version, token, amount, owner key and blinding. Replaying the same opening on another chain/pool or under another version fails. - [ ] AC4: `Unshield` verifies deadline, membership against a historical root, key signature, nullifier freshness and destination; pays `amount - fee` to the destination and `fee` to the submitter; consumes the nullifier exactly once; never leaves partial state on a failed CW20 transfer. - [ ] AC5: Two spends of the same note in one tx, in different txs, or in different orders fail on the second; a note inserted after the proof was built is spendable via a stored root, and a note older than the root window produces a deterministic error (not a panic). - [ ] AC6: Change and settlement outputs are created by the pool with pool-chosen blindings and the owner key from the signed digest; a submitter cannot substitute its own key, destination, fee or amount. - [ ] AC7: `Reconcile`/liability accounting matches the contract's CW20 balances across deposit, withdraw, change, settlement, tax-affected deposits and failed calls; `Reconcile` is exposed and tested. - [ ] AC8: No admin message can move, spend, pause or seize notes; `PauseDeposits` does not block `Unshield`; migration preserves pending settlements or refuses to migrate while one exists. - [ ] AC9: Caps (note min/max, TVL, per-block, per-address) fail closed and are documented; the allowlist is governance-controlled and code-id-pinned. - [ ] AC10: `docs/shielded-pool.md` contains the claim matrix, failure modes, gas envelope, key/backup model and the explicit "not an anonymity system / not a mixer" statement; security docs and invariant matrix are updated; `make verify-issue-<N>` and `docs/qa/issue-<N>/README.md` exist. - [ ] AC11: The settlement hook is callable only by the configured router with an existing pending id, is exactly-once, rejects output below `min_output`, and cannot be satisfied by a third party sending tokens to the pool. ## Test plan: functional paths | Path | Required checks | | --- | --- | | Deposit | Allowed tokens 10184 / community-tax-token / bridge-debt-token / CL8Y; 6, 9, 12 and 18 decimals; min-1, min, max, over-max; zero; duplicate blinding; invalid/short/oversized pubkey; pool/factory/router key; transfer tax >0 (note = post-tax credit); deposit pause; per-block/per-address/TVL caps; event fields and leaf index; root history growth. | | Note tree | Empty tree; first insert; 2, 3, 32, 33, 1024 inserts; proof verification for every leaf at multiple depths; sibling/zero-subtree correctness; historical root spend; root eviction; proof for a non-existent/renumbered leaf; deterministic error for an unknown root. | | Spend | Withdraw all, withdraw partial (change), zero-fee, max-fee, over-cap fee; destination = fresh address, = submitter, = pool, = invalid, = blacklisted; deadline = now, now+1, past; signature valid/invalid/malleable/wrong key/wrong digest field; replay same tx; two notes in one tx; failed CW20 transfer (insufficient pool balance forced by a test mutant) must revert. | | Change/output | Change amount = input − withdraw − fee; dust change; zero change; output amount >= min; output below min reverts; pool-chosen blinding; owner key binding; commitment recomputation; multiple outputs in one tx are distinct. | | Settlement stub | Exactly-once `CommitSwapOutput`; wrong router; missing pending id; wrong token; below min; duplicate same tx; pending expiry/deadline; third-party token donation without a pending id; migration while pending. | | Queries/admin | `Config`, `Root`, `RootHistory`, `Note`, `Nullifier`, `Liability`, `Reconcile`, `PendingSettlement`; `UpdateConfig` auth; token add/remove auth; router rotation while pending rejected; `PauseDeposits` auth and effect; unknown message/version rejected. | | Migration | v1 → v2 preserves leaf count, roots, nullifiers, liability, pending settlement, config and token pins; version rollback rejected; state-compatible schema check; old proofs still verify. | | Gas | Deposit, withdraw (with/without change, with/without fee), settlement, and ed25519 verification measured on LocalTerra; record p50/max and compare with the documented envelope. | ## Test plan: attacks, hacks and abuse - **Double spend / replay:** same note twice sequentially and concurrently; same signed digest on another pool/chain/version; signature reused with altered destination, fee, amount, token, owner key or deadline. All must fail. - **Forgery:** random/zero/all-`0xff` signatures, wrong key type, public key not 32 bytes, digest length tricks, signature malleability, and a note whose commitment is recomputed with a different blinding. No path may accept a signature from any key other than the note's. - **Theft / redirection:** submitter substitutes its own destination, owner key, change blindings, fee recipient or fee amount; a griefer front-runs a spend with a copied calldata and a different destination; a relayer withholds the change note. Verify only the signed destination/owner can receive and that the change note stays spendable by the owner. - **Tree manipulation:** forged Merkle path, wrong sibling order, proof for a leaf from another root, path for the zero subtree, leaf index overflow, tree depth overflow/panic, and a proof generated against a root that was never inserted. - **Nullifier abuse:** pre-computing a nullifier from a public opening and burning it without a valid spend; nullifier collision across versions/domains; reusing a nullifier in another pool; nullifier map growth griefing (bounded by min note/deposit caps; measure storage growth). - **Token abuse:** fee-on-transfer/rebase token masquerading under an allowed address via `MsgMigrateContract` (code-id drift must fail); a token that re-enters `receive`; a token whose transfer returns without transferring; decimals >18 or 0; a token that burns on transfer; community-tax `SendFrom` allowance weirdness. No deposit may inflate liability above the actual credit. - **Solvency / accounting:** deposit-then-tax mismatch, failed transfer after state mutation, settlement double-credit, two swaps in one tx cross-crediting, donation to the pool, withdrawal of the last note, and a forced liability > balance. Every case must revert or be visible through `Reconcile`; never silently mint a note. - **Admin / governance:** non-governance `UpdateConfig`/pause/router rotation; governance attempts to add a token that is not pinned/whitelisted; adding the pool to a token's exemption map (out of contract, but test the token side does not let the pool evade tax); wasm migration with malformed/old state; a rogue token address that self-reports an allowed code id. - **DoS and resource:** oversized hook payloads, many deposits in one tx/block, deep root history, note count at the tree bound, unlimited query ranges, and contracts returning huge metadata. Bound all loops and storage writes. - **Privacy leakage:** note openings/keys in errors, attributes, logs, tests, fixtures or docs; an indexer-visible query that filters by owner key; a spend attribute that includes the submitter as "owner". Prove the emitted attributes and query surface contain only the documented public fields. ## Verification criteria - [ ] `make verify-issue-<N>` runs `cargo fmt --check`, `cargo clippy -D warnings`, unit + multitest tests for the new crate, schema export check, the workspace build, and the documentation cross-link check. - [ ] Multitest uses the real `cw20-mintable` analogue, the real `community-tax-token` crate (including tax >0 and `SendFrom` extra-debit) and a bridge-debt-token analogue; the fee-on-transfer/ALPHA mutant is rejected. - [ ] LocalTerra E2E (opt-in flag, e.g. `VERIFY_ISSUE_<N>_CHAIN=1`): store + instantiate the optimized pool, deposit via `cw20-mintable`, withdraw to a fresh address, deposit via `community-tax-token`, verify the tax affects the note and the pool balance matches `Reconcile`. Capture transaction receipts without any personal or wallet data. - [ ] Gas receipts from LocalTerra are attached to `docs/qa/issue-<N>/README.md`, including ed25519 verification and a comparison to the retail envelope; a failure to stay within the envelope is reported as FAIL, not skipped. - [ ] `docs/shielded-pool.md`, `docs/security-model.md`, `docs/security-posture.md`, `docs/contracts-security-audit.md`, `docs/runbooks/wasm-admin-migration.md` and the new agent skill are updated and cross-linked. - [ ] `docs/qa/issue-<N>/README.md` records the agent checklist, explicit skip policy and evidence. Unavailable live/device checks may be explicit SKIP with overall PASS WITH SKIPS; executed failures remain FAIL. - [ ] No user conversation, personal data, wallet-owner identity or private key appears in issue text, docs, fixtures, logs or receipts. ## Out of scope / follow-ups - Atomic private swaps and tax/route binding: #1584. - Indexer classification, non-attribution, note discovery: #1585. - dApp vault, backup, shield/swap/unshield UX: #1586. - Threat model, abuse policy, relayer operations, monitoring and staged rollout: #1587. - Encrypted note payloads, ZK membership/nullifier proofs, ring signatures, P2P notes, cross-pool transfers, limit orders, native-asset shielding: not in phase 1. A ZK or cipher design may only start after this layer is audited and the gas envelope is measured.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
code/cl8y-dex-terraclassic#1583
No description provided.