Protocol
Protocol spec v2.1
On this page
- 0. What changed from v2 (review response)
- 1. Notation
- 2. Assets [Design]
- 3. Cryptographic primitives
- 3.1 Field [Established]
- 3.2 Poseidon [Established]
- 3.3 Domain separation [Design]
- 3.4 Merkle tree [Design on Established pattern]
- 4. Notes and keys [Design]
- 5. The join-split statement (one circuit, Gate 3)
- 5.1 As built at Gate 3 [Design]
- 6. Public inputs and encoding (frozen for Gate 3)
- 7. Vault rules (Gate 4)
- 7.1 Roots: valid forever (review issue 5) [Design]
- 7.2 Pending deposits, approval and ragequit (review issue 4) [Design; ragequit concept from Privacy Pools, section 16]
- 7.2.1 As built at Gate 4 [Design]
- 7.3 Other vault rules (unchanged from v2, restated)
- 8. Note encryption and the correctness check (review issue 2)
- 8.1 Construction [Established primitives; Design composition, same shape as Zcash Sapling in-band note encryption]
- 8.1.1 Gate 5 additions (as built) [Design]
- 8.2 Mandatory sender self-check [Design]
- 8.3 TypeScript test vectors [Landed at Gate 5: test-vectors/note-encryption.json, keys.json, links.json]
- 9. Keys, wrapping and backup (review issue 3) [Design]
- 10. Claim links and races (review issue 6)
- 10.1 Format [Design]
- 10.2 Race cases: required adversarial tests with expected outcomes
- 10.3 Link exposure guidance (in-app copy and threats doc) [Design]
- 11. Proof system and setup [Established tools; Design plan]
- 12. Privacy limits (what is NOT hidden)
- 13. Threat model summary (expanded in threats.md at Gate 4)
- 14. Licences
- 15. Gate status
- 16. Prior art (neutral; we claim no new primitive)
- 16.1 Products in the same category (checked 17–18 Nov 2026, neutral)
- 17. Open questions (owner and deadline)
Rendered from
spec/Spec-v2.1.mdin the repository. Section numbers are stable link targets (for example §7.2).
Project name: Batin (Arabic bātin, "the hidden, inner side"). It was renamed from "Sei Private Pay" on 18 Nov 2026. Protocol identifiers keep their original sei-private-pay/v1/… and spp-… strings (section 3.3).
Status: draft for Godwin's approval, 17 Nov 2026 (WAT). Gate 3 notes added the same day. Supersedes v2 where they differ. Everything in v2 that this document doesn't touch still stands (no owner, no upgrade, immutable verifier, per-asset caps, testnet first, foundation-before-features).
Testnet only: Sei Atlantic-2, chain id 1328. Nothing in this revision is deployed to mainnet (1329).
How to read this spec. Every rule carries one of three labels:
- [Established] means standard, published cryptography or a pattern used by existing systems. We use it and don't claim it.
- [Design] means our choice for this product. It's reviewable and could have gone another way.
- [Open] means unresolved. Each one must be closed before the gate named next to it.
0. What changed from v2 (review response)
| # | Review issue | v2.1 resolution | Section |
|---|---|---|---|
| 1 | Cross-asset anonymity claimed while tokenId was public |
The asset is now private in transfers. A public publicAssetId is non-zero only when value crosses the vault boundary (extAmount ≠ 0 or fee ≠ 0). Private transfers have fee = 0, with gas self-submitted or sponsored. Asset ids are renumbered so that 0 means "none". |
2, 5, 6 |
| 2 | Encryption correctness | A fixed ciphertext format (BabyJubJub ECDH, HKDF-SHA256, ChaCha20-Poly1305 with the commitment as associated data). The client must decrypt its own ciphertext and recompute the commitment before submitting. TypeScript test vectors are specified, including negative cases. Proving encryption in-circuit is a v3 item. | 8 |
| 3 | Key derivation from signatures | A random 32-byte seed generated on the phone, wrapped with a key from the WebAuthn PRF extension, plus an encrypted backup file. Keys derived from signatures are forbidden. | 9 |
| 4 | ASP and ragequit underspecified | Deposits enter a pending record of (commitments, depositor, asset, amount). A pending deposit is not in the note tree. It moves to approved (inserted into the tree, so it becomes spendable) or refunded (only the depositor can trigger this, and the funds go back to the depositor). Both states are terminal. | 7.2 |
| 5 | 100-root window can expire honest proofs | Every root ever produced stays valid forever (mapping(bytes32 => bool)). That costs one new slot (72k gas on Sei) per insertion transaction. |
7.1 |
| 6 | Claim-link races | Four adversarial cases with exact expected outcomes and required tests, plus link-exposure guidance for phones. | 10 |
| — | Precision gaps | Pinned: the BN254 field, Poseidon parameters, domain tags, the zero leaf, Groth16 versions, the Phase-2 plan, the ciphertext format, public-input encoding and the privacy limits. | 3, 6, 11, 12 |
1. Notation
ris the BN254 scalar field modulus (section 3.1). "Field element" means an integer in[0, r). Every encoding is canonical: an input ≥ris rejected, never reduced. The only exception is a hash output that the spec explicitly says to reduce, using the formkeccak256(x) mod r.H(a, b, …)is Poseidon over BN254 with the arity shown (section 3.2).- Byte strings are big-endian unless a format says otherwise.
‖is byte concatenation.
2. Assets [Design]
| assetId | Asset | Testnet (1328) | Mainnet (1329) | Decimals | Per-deposit cap (testnet) | Vault cap (testnet) |
|---|---|---|---|---|---|---|
| 0 | none (reserved: "no public asset") | — | — | — | — | — |
| 1 | Native SEI | msg.value |
msg.value |
18 | 100 SEI | 10,000 SEI |
| 2 | Native USDC | 0x4fCF1784B31630811181f670Aea7A7bEF803eaED |
0xe15fC38F6D8c56aF07bbCBe3BAf5708A2Bf42392 |
6 | 500 USDC | 25,000 USDC |
Change from v2: SEI moves from 0 to 1 and USDC from 1 to 2. That frees 0 to mean "this transaction exposes no asset", which is what makes the private-asset rule in section 5 checkable. The token table and caps are immutable constructor arguments.
3. Cryptographic primitives
3.1 Field [Established]
r = 21888242871839275222246405745257275088548364400416034343698204186575808495617
= 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001
This is the scalar field of BN254 (alt_bn128). It's the field of the EVM precompiles at 0x06/0x07/0x08 (EIP-196/197), which are live on Sei 1328 and 1329 according to the build plan's live checks.
3.2 Poseidon [Established]
We use the circomlib Poseidon instance (Grassi et al., "Poseidon", USENIX Security 2021):
- Field: BN254
r. - S-box: x^5.
- Width:
t = arity + 1. - Full rounds:
R_F = 8. - Partial rounds:
R_P = 56, 57, 56, 60, 60fort = 2, 3, 4, 5, 6. - Constants: the round constants and MDS matrices are the ones circomlib ships (
poseidon_constants.json), which are byte-identical in poseidon-lite and poseidon-solidity. - State and output: the initial capacity element is 0, and the output is state[0].
Anchor value, checked in both test suites: H(1, 2) = 7853200120776062878684798364095072458815029376092732009249414926327459813530.
Implementations [Design]:
| Where | Implementation | Licence |
|---|---|---|
| TypeScript runtime | poseidon-lite@0.3.0 |
MIT |
| Solidity (tree only) | PoseidonT3 from poseidon-solidity@0.0.5, vendored unmodified at packages/contracts/src/vendor/PoseidonT3.sol (sha256 08a7493be37838166954af6c77d583d797cc17d37673196498fc70cbf557831c) |
MIT |
| Circuits (Gate 3) | circomlib 2.0.5 Poseidon(n) templates via the single seam packages/circuits/circuits/lib.circom (provisional, section 14) |
GPL-3.0 |
| Cross-check only (tests, never shipped) | circomlibjs@0.1.7 |
GPL-3.0 |
Note that PoseidonT3.hash silently reduces inputs mod r. Every Solidity caller in this repo rejects non-canonical inputs before hashing (the LeafNotInField error), so two different bytes32 values can never hash identically.
3.3 Domain separation [Design]
Every in-circuit hash takes a fixed tag as its first input. Each tag is keccak256(utf8(label)) mod r.
Frozen identifier [Design]. The label prefix sei-private-pay/v1/ (and the spp-note-v1 / spp-seed-v1 AEAD strings in sections 8–9) is a protocol identifier, not the brand. It was kept through the rename to Batin, because changing it would change the three tags and the zero leaf. That would change every Gate 2 vector, the circuit constants, the trusted setup and the deployed verifier. The domain separation itself is unaffected: it only needs the labels to be distinct and fixed.
| Name | Label | Value |
|---|---|---|
TAG_OWNER |
sei-private-pay/v1/owner |
0x2f21eef2e8f95ed293b8b4760b7acbb8fb8aedb25fbafa59ff451573e8542c54 |
TAG_COMMITMENT |
sei-private-pay/v1/commitment |
0x0ce2b8f17ee23cc7d31b728e7e43788bfe85d0048216bfc1e2de473aad0b6c1c |
TAG_NULLIFIER |
sei-private-pay/v1/nullifier |
0x0e5e3819d74a56ef92f7cfd1b595e5d4e33044b98df82663a6ebed4a878c8ae7 |
ZERO_LEAF (not a tag) |
sei-private-pay/v1/zero-leaf |
0x0beef61890a1891c1b2bee10cc24f967ca9fc65d26b5a9fcfc33216df6806e93 |
| Hash | Arity | Definition |
|---|---|---|
| Merkle node | 2 | H(left, right), untagged |
| Owner public value | 2 | ownerPub = H(TAG_OWNER, spendKey) |
| Nullifier | 4 | nf = H(TAG_NULLIFIER, commitment, leafIndex, spendKey) |
| Commitment | 5 | cm = H(TAG_COMMITMENT, tokenId, amount, ownerPub, blinding) |
Rationale:
- Different arities use different Poseidon permutations, so they're already separated.
- The tags separate same-arity uses and give a version prefix (
/v1/). - Merkle nodes stay untagged because they're the only hash computed on-chain, at about 32k gas each (measured), and a tag would cost a wider permutation.
- The one same-arity overlap is node versus
ownerPub. A collision needs a Merkle left child equal toTAG_OWNER. Children are commitments or node hashes (Poseidon outputs) or zero-subtree values, so that requires finding a Poseidon preimage. In addition,ownerPubnever appears where a node is checked, or the other way round.
Changes from v2:
ownerPubwasH(spendKey).- The commitment order changed to put
tokenIdfirst. - The nullifier order changed to (commitment, leafIndex, spendKey).
All of these are free to change before Gate 3, because no circuit exists yet.
3.4 Merkle tree [Design on Established pattern]
- Append-only binary tree. Depth is 20 (1,048,576 leaves, which is 524,288 two-output transactions). Leaves are commitments.
- Empty leaves:
zeros[0] = ZERO_LEAF,zeros[i+1] = H(zeros[i], zeros[i]), andzeros[d]is the empty root at depthd.- Depth-20 empty root:
0x13c5576a29f3443513d5bc31baf9e74ac2947abaccf5e3199c4d3843d08468e1. ZERO_LEAFis a nothing-up-my-sleeve value, not 0, so an empty slot can't be confused with a leaf whose value is 0.
- Depth-20 empty root:
- Storage: only the frontier (
filledSubtrees[level]), pluscurrentRoot,nextIndexand the all-roots mapping (section 7.1).- Solidity uses a generated
zeros(i)table (MerkleZeros.sol) instead of storage. This saves 21 slots, which is 1.5M gas on Sei.
- Solidity uses a generated
- Paths:
pathIndices[i]is bitiofleafIndex. A 0 bit means the running node is the left child at leveli. - Insertion:
insert(leaf)adds one leaf andinsertPair(left, right)adds two siblings with one root update.- The vault only uses
insertPair, because every transaction has exactly 2 outputs. That keepsnextIndexeven and writes one root per transaction. insertPairat an odd index reverts.- Both TypeScript and Solidity enforce that
insertPair(a, b)equalsinsert(a); insert(b)(fuzzed in Foundry).
- The vault only uses
- Full tree: reverts with
TreeFull. The fix is a new pool. Migration means unshield then shield, which is public (section 12).
Gate 2 implements this. Section 15 has the evidence.
4. Notes and keys [Design]
note = (tokenId, amount, ownerPub, blinding)
ownerPub = H(TAG_OWNER, spendKey)
commitment = H(TAG_COMMITMENT, tokenId, amount, ownerPub, blinding)
nullifier = H(TAG_NULLIFIER, commitment, leafIndex, spendKey)
tokenId ∈ {1, 2}for real notes.amountis in[0, 2^96), in base units (wei for SEI, 10^-6 USDC for USDC).blindingis a uniform field element. It's sampled as 48 random bytes modr, so the bias is below 2^-128.spendKeyis a field element. It never leaves the device, and it's the only secret needed to spend.- Dummy inputs have amount 0 and a fresh random
spendKey. They skip membership but still publish a nullifier, so they're indistinguishable from real inputs. - Dummy outputs have amount 0, and their owner is the sender. They're encrypted like real outputs, so they're indistinguishable.
Account keys (section 9): seed gives spendKey and viewKey.
viewKeyis a BabyJubJub scalar used only for note encryption.viewPub = viewKey · B8.- A user's receiving address is the pair
(ownerPub, viewPub).
5. The join-split statement (one circuit, Gate 3)
There are two inputs and two outputs, always [Established: Zcash Sprout, Tornado Nova]. The circuit proves:
- Ranges:
- Every input and output
amount, plusfee, is in[0, 2^96)(Num2Bits(96)). |extAmount| < 2^96. This is checked on the field encodingextAmount + 2^96 ∈ [0, 2^97).- The sum of two 96-bit inputs plus a 96-bit
extAmountis far belowr, so conservation can't wrap.
- Every input and output
- One private asset:
- A private witness
tokenIdequals thetokenIdof all four notes. tokenIdis not a public input.
- A private witness
- Public asset rule [Design; matches Aztec Connect's
public_asset_idrule, see section 16]:isNone = (publicAssetId == 0) isNone * extAmount == 0 // no asset exposed ⇒ no value crosses the boundary isNone * fee == 0 // ... and no fee (1 - isNone) * (tokenId - publicAssetId) == 0 // asset exposed ⇒ it is the real one - Conservation:
in0 + in1 + extAmount == out0 + out1 + feeover the field. - Membership:
- Each input with
amount ≠ 0has a valid path torootand a valid path toaspRoot. - Each input with
amount = 0has both checks disabled. This is the standard "skip when zero" pattern, multiplying the root check byamount != 0.
- Each input with
- Nullifiers:
nf_i == H(TAG_NULLIFIER, cm_i, leafIndex_i, spendKey_i).cm_iis recomputed from the input note withownerPub = H(TAG_OWNER, spendKey_i).nf_0 ≠ nf_1, which is also checked on-chain.
- Outputs:
outCm_j == H(TAG_COMMITMENT, tokenId, outAmount_j, outOwnerPub_j, outBlinding_j). - Binding:
chainId,poolandextDataHashare public inputs, squared once in-circuit so they can't be optimised away [Established: the Tornado pattern].
Fee and gas decision (review issue 1) [Design]: option A, private transfers have fee = 0.
- Rule. A transaction with
publicAssetId = 0(transfer or claim) must havefee = 0. The circuit enforces this (rule 3). Its gas is paid by:- self-submission: the user's own public Sei account. This links that account to "made a private transaction", though not to amounts, assets or counterparties.
- sponsored submission: a relayer or ERC-4337 paymaster pays gas and is reimbursed outside the pool, for example from an operator budget. At the build plan's estimate of 1.0M gas × 55 gwei, about $0.002 per transfer, sponsoring is affordable.
- Unshield fees. Only unshields carry a fee, paid in the already-public asset to the bound relayer.
- Shield fees. Shields must have
fee = 0andrelayer = 0, because the depositor submits the shield themselves. - Why not option B (fee from a separate SEI note).
- It needs a second asset lane in the circuit: a third input and output, or a mixed-asset conservation check. That means a bigger circuit and slower phone proving.
- The public fee amount would still be a SEI value attached to every transfer, which is a fingerprint.
- Option B stays a v3 candidate if a sponsor can't be found.
- Why not keep a same-asset fee. A public fee in the transfer's own asset leaks the asset by magnitude: 1e15 wei and 1e4 USDC base units are trivially told apart. That would make the "asset is private" claim false.
- Consequence for the privacy claim.
- Within private transfers and claims, an observer can't tell SEI notes from USDC notes. The set of transfer outputs is one cross-asset pool.
- Shield outputs and unshield change outputs are asset-labelled, because they come from transactions with a public asset.
- So an unshield of USDC hides among every transfer output plus every USDC-labelled leaf. It does not hide among SEI-labelled leaves.
- That is the exact claim. Section 12 lists everything else that leaks.
- [Open, moved to Gate 5] Sponsor abuse. Valid zero-value transfers can be generated without funds, because both inputs can be dummies. The relayer needs off-chain rate limiting, or the circuit could require
in0 + in1 > 0whenpublicAssetId = 0. Gate 3 did not add thein0 + in1 > 0constraint, so the circuit stays minimal. The relayer's rate limit is the planned answer, and the constraint can be added later at the cost of a new setup and verifier.
5.1 As built at Gate 3 [Design]
packages/circuits/circuits/joinsplit.circom, JoinSplit(20):
- Size: 22,292 non-linear constraints and 12 public inputs.
- Private inputs:
tokenId.- Per input:
amount,spendKey,blinding,leafIndex, and the path for each tree. The ASP path is a separate witness, so a different ASP tree later doesn't change the interface. - Per output:
amount,ownerPub,blinding.
- Membership: the path bits are
Num2Bits(20)(leafIndex), which also forcesleafIndex < 2^20. Membership uses circomlibForceEqualIfEnabledwithenabled = amount. - Nullifier uniqueness: enforced in-circuit with
IsEqual(nf0, nf1) === 0. The vault re-checks it. - Range checks:
Num2Bits(96)on all four amounts and onfee.Num2Bits(97)(extAmount + 2^96).
Every rule in section 5 has a negative test that asserts the specific constraint line rejecting the witness.
6. Public inputs and encoding (frozen for Gate 3)
The circuit declares its public inputs in exactly this order, so snarkjs emits them in this order (there are no circuit outputs). The Solidity uint256[12] uses the same order. A test in each gate asserts the order against spec/public-inputs.json, which is generated at Gate 3.
| # | Name | Solidity source | Encoding |
|---|---|---|---|
| 0 | root |
calldata bytes32 |
uint256. Must satisfy isKnownRoot. |
| 1 | aspRoot |
calldata bytes32 |
uint256. v2.1: must also satisfy isKnownRoot (section 7.2). |
| 2 | nullifier0 |
calldata | uint256 < r, unspent, and different from nullifier1 |
| 3 | nullifier1 |
calldata | same rules |
| 4 | commitment0 |
calldata | uint256 < r |
| 5 | commitment1 |
calldata | uint256 < r |
| 6 | extAmount |
int256 |
Requires -2^96 < x < 2^96. Field-encoded as `x ≥ 0 ? x : r − |
| 7 | fee |
uint256 |
< 2^96 |
| 8 | publicAssetId |
uint256 |
0, or a listed asset id |
| 9 | chainId |
block.chainid |
Never taken from calldata |
| 10 | pool |
uint256(uint160(address(this))) |
Never taken from calldata |
| 11 | extDataHash |
computed | uint256(keccak256(abi.encode(recipient, relayer, encryptedOutput0, encryptedOutput1))) mod r |
Every value is checked < r before verification, which defends against public-input aliasing (Groth16 malleability).
extData:
recipientis anaddress: the unshield destination, or0.relayeris anaddress.- If it's non-zero, only that
msg.sendermay submit, and it receivesfee. - If it's zero, anyone may submit and
feemust be 0.
- If it's non-zero, only that
encryptedOutput0andencryptedOutput1arebytes, each exactly 113 bytes (section 8).
Contract-side validity by transaction kind:
| Kind | publicAssetId | extAmount | fee | recipient | relayer | msg.value |
|---|---|---|---|---|---|---|
| Shield | 1 or 2 | > 0 | 0 | 0 | 0 | extAmount if SEI, else 0 |
| Transfer or claim | 0 | 0 | 0 | 0 | any | 0 |
| Unshield | 1 or 2 | < 0 | ≥ 0 | ≠ 0 | any (must be ≠ 0 if fee > 0) | 0 |
7. Vault rules (Gate 4)
7.1 Roots: valid forever (review issue 5) [Design]
mapping(bytes32 => bool) knownRoots. Every root produced is stored and never removed. The empty root counts as known, andbytes32(0)never does.- Safety. The tree is append-only, so membership under an old root still means the leaf is in the tree. Double spends are stopped by nullifiers, not by root freshness. This is the same reasoning Railgun documents for accepting any historical root [Established].
- Cost. One new slot per insertion transaction, which is 72,000 gas on Sei (governance proposal #109), about $0.00015 at the build plan's prices. A ring buffer would rewrite warm slots more cheaply, but it can invalidate honest proofs under load. Correctness wins.
- Privacy note. Proving against an old root shows the spent note was inserted before that root. Clients must use the latest root they know, and only fall back to an older one when retrying.
7.2 Pending deposits, approval and ragequit (review issue 4) [Design; ragequit concept from Privacy Pools, section 16]
A shield doesn't touch the note tree. It creates a pending deposit:
DepositRecord {
commitment0, commitment1 // the two shield outputs (one may be a dummy)
depositor // msg.sender of the shield tx
assetId // publicAssetId (1 or 2)
amount // extAmount (> 0), exactly what the vault received
state // PENDING | APPROVED | REFUNDED
}
id = sequential uint256; event DepositPending(id, depositor, assetId, amount, commitment0, commitment1, encryptedOutput0, encryptedOutput1)
State machine. No other transitions exist, and APPROVED and REFUNDED are terminal:
| From | To | Who | Effect |
|---|---|---|---|
| (none) | PENDING | anyone, via shield | Proof verified (dummy inputs, outputs well formed, sum = amount). Funds pulled with a balance-delta check for USDC, or msg.value == amount for SEI. Caps enforced. Shield nullifiers marked spent. |
| PENDING | APPROVED | ASP poster only | insertPair(commitment0, commitment1). The notes become spendable. A batch approve writes one root at the end. |
| PENDING | REFUNDED | depositor only (msg.sender == depositor) |
Sends amount of assetId to depositor after the state update. The call is non-reentrant. The commitments are never inserted, so they can never be spent. |
Properties tests must assert:
- A refunded deposit can never be approved, and an approved one can never be refunded.
- The ASP poster can only move PENDING to APPROVED. It can't move funds or block a refund. Its worst case is refusing to approve, and then the depositor ragequits.
- There's no time limit on a refund. A refund racing an approval is resolved by whichever transaction lands first, and the other reverts.
- If USDC blacklists the depositor, the refund reverts and the record stays PENDING. Approval is still possible later.
- Accounting: for each asset,
vault balance == Σ unspent approved notes + Σ PENDING amounts. This is the fuzzed invariant from v2, extended.
On testnet the ASP poster is the deployer burner key, and an approval script approves everything. On mainnet it's a multisig or timelock [Open, pre-mainnet].
aspRoot in v2.1. Admission is now done by gating insertion, so for v2.1 the contract requires aspRoot to be a known root of the same tree, which in practice means the same value as root. The circuit keeps the second membership proof so the public-input interface doesn't change when retroactive exclusion, an association-set subset with lineage, arrives.
- [Open, pre-mainnet] Retroactive exclusion must not break "never frozen". Approved notes would need a lineage-aware exit (as in Privacy Pools' label lineage) before any ASP can exclude them.
- [Open, Godwin] Gate 3 kept
aspRoot, which was the default. Dropping it would remove about 10k of the 22,292 constraints (two depth-20 paths) and cut phone proving time. That's Godwin's call. Changing it now means recompiling, rerunning the setup and regenerating the verifier, but no contract has been deployed yet.
7.2.1 As built at Gate 4 [Design]
packages/contracts/src/BatinPool.sol, extending IncrementalMerkleTree (depth 20) and calling the Gate 3 Groth16Verifier.
- Storage per deposit: two slots. The record stores
keccak256(abi.encode(c0, c1))plus a packed slot{depositor, assetId, state, uint80 amount}. The ASP poster re-supplies(c0, c1)from theDepositPendingevent and the contract checks the hash. This saves two 72k-gas slots per shield on Sei.uint80is far above the per-deposit caps, and the constructor enforces it. - Entry points:
shield(payable; creates PENDING),approve(ids[], pairs[])(ASP poster; one root per batch via_insertPairs),refund(id)(depositor only), andtransact(transfer, claim or unshield). - Shield checks:
publicAssetId∈ {1, 2},extAmount > 0,fee = 0,recipient = relayer = 0,msg.value == extAmountfor SEI and 0 for USDC, the per-deposit cap, then the proof. BothrootandaspRootmust be known roots (the shield's dummy inputs make the value irrelevant to the circuit). The pool cap is checked against the actual balance after funds arrive. - Common checks: 113-byte ciphertexts, known
root/aspRoot,−2^96 < extAmount < 2^96,fee < 2^96, distinct and unspent nullifiers, and nullifiers and commitments< r.chainId = block.chainidandpool = address(this)are never taken from calldata. - Transfers out: a reentrancy lock; state is written before any transfer; SEI goes by low-level call and a failure reverts the whole transaction; USDC uses a SafeERC20-style call (accepts no return data or
true); shields check the USDC balance delta. pendingTotal[asset]is tracked on-chain, so the accounting invariant is checkable from outside.- No owner, no upgrade, no sweep, no verifier swap. Tokens, verifier, ASP poster and caps are immutable.
SECURITY_NOTICE()returns a TESTNET ONLY / NOT FOR PRODUCTION string.
7.3 Other vault rules (unchanged from v2, restated)
require(chainId == block.chainid && pool == address(this)). Both values are computed from chain state, never taken from calldata.- Nullifiers:
mapping(bytes32 => bool), two new slots per transaction (144k gas on Sei). - Unshield sends assets last, after all state changes, behind a reentrancy guard. It sends native SEI with a low-level call, and a failed send reverts the whole transaction.
- No owner, no upgrade, no verifier swap, no sweep. The ASP poster role can only approve pending deposits.
8. Note encryption and the correctness check (review issue 2)
8.1 Construction [Established primitives; Design composition, same shape as Zcash Sapling in-band note encryption]
- Curve: BabyJubJub (EIP-2494) over
r. GeneratorB8, prime subgroup order:l = 2736030358979909402780800718157159386076813972158567259200215660948447373041 - Point packing: the circomlib/EIP-2494 32-byte format (y little-endian, with the top bit carrying the sign of x). TypeScript uses
@zk-kit/baby-jubjub(MIT). - Unpacking rejects any encoding that isn't on the curve, not in the prime-order subgroup (
l·P ≠ O), or the identity.
To encrypt note to recipient (ownerPub, viewPub = V) for vault (chainId, pool) with output commitment cm:
e ← uniform in [1, l) (48 random bytes mod l, retry on 0)
E = e · B8
S = e · V
okm = HKDF-SHA256(ikm = pack(S), salt = "sei-private-pay/v1/note-enc",
info = pack(E) ‖ pack(V), L = 44)
key = okm[0..32], nonce = okm[32..44]
pt (64B) = 0x01 ‖ tokenId (1B) ‖ amount (12B, uint96 BE) ‖ blinding (32B) ‖ 0x00 × 18
ad = "spp-note-v1" ‖ uint256(chainId) (32B) ‖ pool (20B) ‖ cm (32B)
ct ‖ tag = ChaCha20-Poly1305(key, nonce, pt, ad) (RFC 8439)
output = 0x01 ‖ pack(E) ‖ ct (64B) ‖ tag (16B) = 113 bytes, fixed
eis fresh for every output, so each (key, nonce) pair is used exactly once.- Putting
cm,chainIdandpoolin the associated data means a ciphertext can't be replayed against another commitment, chain or pool without failing the tag. - Fixed length, with dummy outputs encrypted too, means ciphertext size reveals nothing.
- Scanning (recovery after a lost phone):
- For every
encryptedOutputevent, try decrypting withviewKey. - On tag success, parse the plaintext and recompute
cmusing your ownownerPub. - Accept the note only if it equals the on-chain commitment.
- For every
8.1.1 Gate 5 additions (as built) [Design]
Plaintext kinds. Byte 0 of the 64-byte plaintext is a kind.
0x01: an ordinary note. The 32-byte field holdsblinding.0x02: a claim-link note. The 32-byte field holdslinkSecret. It's encrypted to the sender's ownviewPub. After a restore, the sender's scanner re-derives the link's spend key and blinding, so it can show and reclaim unclaimed links, and see claimed ones as spent.- Any other kind, or non-zero padding, is rejected.
- Consequence: a
viewKeyexported to an auditor also reveals the secrets of unclaimed outgoing links, which are spendable. The export UI must say so. [Open, v3] Use a separate link-recovery key.
Pending deposits. A shield's ciphertexts are emitted only in
DepositPending. The approval re-emits the commitment with an empty ciphertext. The scanner joins the two by commitment.Library. Curve arithmetic comes from
@zk-kit/baby-jubjub1.0.3 (MIT), butpackages/sdk/src/babyjub.tsdoes its own strict packing and unpacking:y < r- the sign bit is canonical (
x = 0with the sign bit set is rejected) - on the curve
l·P = O- not the identity
ChaCha20-Poly1305 and HKDF come from
@noble/ciphersand@noble/hashes(MIT).Cross-checks in the tests:
- point packing equals circomlibjs on random points
- every positive vector opens with Node's own
hkdfSyncandchacha20-poly1305
8.2 Mandatory sender self-check [Design]
Before a proof is submitted, the client must do all of the following for each output. Any failure aborts before anything is signed or sent.
- Parse its own 113-byte output. Check the version, the length, and that
Eunpacks and equalse · B8for theeit kept in memory. - Re-derive
S = e · Vand (key, nonce), then AEAD-decrypt using the exactadthe vault will emit (block.chainid, the pool and the proof'scommitment_j). - Recompute
cm' = H(TAG_COMMITMENT, tokenId, amount, ownerPub, blinding)from the decrypted plaintext and the intended recipient'sownerPub. Requirecm' == commitment_j. - If the output is to self (change or dummy), also decrypt through the recipient path with its own
viewKey, which exercises the scanner code end to end.
What this catches:
- Client bugs, serialisation mismatches, a wrong chain or pool, and a ciphertext and commitment that don't match. These are the failures that would strand funds "successfully inserted but unrecoverable".
- It does not catch a sender who encrypts to a wrong
viewPub. The address is the pair(ownerPub, viewPub), so the app must treat it as one unit from one source: a name-registry record or a link. A malicious sender can always burn their own money, and the recipient never counts a payment until their scanner accepts it. - [v3] Proving the encryption relation in-circuit removes the trust in the sender's client.
8.3 TypeScript test vectors [Landed at Gate 5: test-vectors/note-encryption.json, keys.json, links.json]
test-vectors/note-encryption.json will hold:
- Positive vectors. Fixed
viewKey,e,note,chainId = 1328,poolandcm, giving the expectedE,key,nonce,adand the full 113-byte output. It covers SEI (18-decimal amount near 2^96), USDC, and a dummy (amount 0). - Negative vectors. Each must fail closed:
- one tag byte flipped
- one ciphertext byte flipped
adwith another pooladwith another chain idadwith another commitment- the wrong view key
Enot in the subgroupEas the identity- a truncated output (112 bytes)
- version byte 0x02
- The self-check must pass on every positive vector and fail on a ciphertext built for one commitment but submitted with another.
9. Keys, wrapping and backup (review issue 3) [Design]
- Seed. 32 bytes from
crypto.getRandomValueson the phone. It's the only long-term secret. - Derivation:
ikm = seed, salt = "sei-private-pay/v1/keys" spendKey = OS2IP(HKDF-SHA256(ikm, salt, info="spend", L=48)) mod r viewKey = OS2IP(HKDF-SHA256(ikm, salt, info="view", L=48)) mod l (reject 0) - Forbidden. Keys must never be derived from a wallet signature or a WebAuthn assertion. WebAuthn signatures are randomised (ECDSA) and are not a stable secret. Wallet signatures depend on the wallet implementation and can be phished into existence.
- At-rest wrapping with the WebAuthn PRF extension (hmac-secret):
- At account creation: create a passkey requesting
extensions: { prf: { eval: { first: SHA-256("sei-private-pay/v1/prf-wrap") } } }. - Then
wrapKey = HKDF-SHA256(prfOutput, info="seed-wrap", L=32), andwrapped = AES-256-GCM(wrapKey, iv = 12 random bytes, seed, ad = "spp-seed-v1" ‖ credentialId). The wrapped seed is stored in IndexedDB. - To unlock:
navigator.credentials.getwith the same PRF salt, then unwrap. - Support: PRF is reported working for iCloud Keychain passkeys on iOS 18+ (stable from 18.4) and for Google Password Manager passkeys on Android Chrome. It is not available in Chrome's local profile authenticator or in Firefox on iOS. Browsers can't report PRF support in advance, so the app checks for a PRF result at creation and falls back if it's missing. These are third-party compatibility tables (Corbado and others, 2026); we'll measure on Godwin's phone at Gate 5.
- At account creation: create a passkey requesting
- Backup file (always offered, required when PRF is missing):
- JSON containing
{ version, credentialId?, prfWrapped?, passWrapped }. passWrapped = AES-256-GCM(scrypt(passphrase, salt 16B, N=2^17, r=8, p=1), seed).- It's exported through the phone's share sheet or a download to Files or Drive. No QR codes and no laptop steps.
- Restore on a new phone: use the synced passkey, whose PRF output matches across devices because the passkey syncs, together with
prfWrapped. Or use the passphrase withpassWrapped. - Losing both the passkey and the passphrase loses the funds. The app must say so at creation.
- JSON containing
- What leaves the device. Only
viewPub,ownerPub, and (if the user chooses) aviewKeyexport for an auditor. That export reveals incoming notes, and amounts on outgoing change, but never spend authority. Per-payment view keys are a later feature.
As built at Gate 5 (packages/sdk/src/keys.ts):
- Passphrase wrap. Uses
ad = "spp-seed-v1" ‖ "pass". The passphrase is NFKC-normalised and must be at least 12 characters. scrypt runs at N = 2^17, r = 8, p = 1, so it needs about 128 MB of memory; we'll measure it on the phone. - AES-GCM uses WebCrypto, which works the same in browsers and in Node.
- Receiving address.
batin1+ base64url(ownerPub(32 B) ‖ pack(viewPub) (32 B) ‖ keccak256(…)[0..4]). The two halves always travel together, and a bad checksum or a non-subgroupviewPubis rejected. - WebAuthn PRF helpers (
createPrfPasskey,getPrfOutput). These request a platform passkey only, with no QR or cross-device flow. Confirmed on a physical phone (unlock, and a USDC deposit, 18 Nov 2026). Phone proving time is still unmeasured.
10. Claim links and races (review issue 6)
10.1 Format [Design]
https://<app>/c#v1.<chainId>.<poolAddress>.<base64url(payload)>
payload = tokenId (1B) ‖ amount (12B) ‖ linkSecret (32B) (45 bytes → 60 chars)
paymentSpendKey = OS2IP(HKDF-SHA256(linkSecret, salt="sei-private-pay/v1/link", info="spend", L=48)) mod r
blinding = OS2IP(HKDF-SHA256(linkSecret, salt="sei-private-pay/v1/link", info="blind", L=48)) mod r
linkSecretis fresh and random for every link. It's never derived from the user's seed, so a leaked link exposes only that one payment.- The recipient recomputes
commitmentand finds its leaf by scanning commitment events. - The secret is in the fragment, which browsers never send to a server.
10.2 Race cases: required adversarial tests with expected outcomes
| # | Case | Expected on-chain outcome | Test (gate) |
|---|---|---|---|
| R1 | Sender reclaims while the recipient claims | Both proofs spend the same note, so both publish the same nullifier. The first one included wins. The second reverts with NullifierSpent. No value is created or lost, and the invariant holds. |
Forge (4) + SDK script (5) |
| R2 | Double claim: two people with the link, or one person on two devices | Same as R1. Exactly one claim succeeds. The loser's app shows "already claimed" and never shows a balance. | Forge (4) + SDK (5) |
| R3 | A relayer or observer copies a proof | If relayer ≠ 0, any other msg.sender reverts with RelayerMismatch. If relayer = 0, then fee = 0, so the copier can only submit the same transaction with identical effects (the outputs still go to the claimant) and pays the gas. Changing recipient, relayer or a ciphertext changes extDataHash, and the proof fails. Changing any public input fails verification. |
Forge (4) |
| R4 | Two different valid transactions spend the same note in the same block (front-run) | Same as R1. Sei finality is instant, so the loser sees a revert, never a reorg. | Forge (4) |
| R5 | A claim against an old root after many new insertions | It succeeds, because roots stay valid forever (section 7.1). | Forge (4) |
10.3 Link exposure guidance (in-app copy and threats doc) [Design]
- A link is cash, not escrow. Anyone who reads it can take the money until the claim proof lands. That includes the sender.
- Claim on open. The app starts proving as soon as the link opens, then strips the fragment with
history.replaceState, so browser history and the tab-restore list don't keep the secret. - Treat messaging apps as storage. WhatsApp and Telegram keep messages in cloud backups and on every linked device. A link sitting unclaimed in a chat is exposed for as long as that chat exists.
- Avoid the clipboard. Share through the OS share sheet rather than copy and paste. Clipboard history (Gboard, iOS Universal Clipboard) keeps copies.
- Screenshots. Don't screenshot links. Gallery and cloud photo backups keep them.
- Expiry nudge. After 72 hours unclaimed (configurable), the sender's app suggests a reclaim, which spends the payment note back to their own key.
- Unfurl bots. Link-preview bots fetch the URL without the fragment, so a preview never leaks the secret. The app page must not echo the fragment into any request.
- [Open, Gate 5] Optional passphrase-protected links, where the payload is encrypted under a passphrase shared through another channel. Short PINs can be brute-forced offline, so this would need a long passphrase.
11. Proof system and setup [Established tools; Design plan]
- Proof system: Groth16 over BN254.
- Circuit language: circom 2.1.9 (installed on the build box).
- Prover and verifier export: snarkjs 0.7.4.
- Verifier contract: generated by
snarkjs zkey export solidityverifier, verified through the precompiles. Pairing costs about 34k gas per pair plus a 45k base on Sei (measured in the build plan). - Size, measured at Gate 3: 22,292 constraints, which fits a 2^15 ptau.
- Phase 1: Perpetual Powers of Tau (the Hermez final ptau files). Check the file's blake2b hash against the published list before use.
- Testnet setup as actually run at Gate 3 [Design]: HACKATHON/TESTNET-ONLY.
- Phase 1 was a local 2^15 Powers of Tau: one contribution plus a fixed public beacon. The Perpetual Powers of Tau was not used.
- Phase 2 was a single contribution plus a fixed public beacon. Entropy came from
/dev/urandomand was never stored or printed. - It's reproducible with
packages/circuits/setup/run-setup.sh. The transcript logs and artifact hashes are inpackages/circuits/setup/TRANSCRIPT.md. snarkjs powersoftau verifyandzkey verifyboth pass.- The operator of this setup could forge proofs. It's fine for testnet only.
- Phase 2, mainnet [Open, pre-mainnet]:
- A public ceremony with independent contributors (target at least 10). Each contribution is verified with
snarkjs zkey verify. - The final beacon is a drand round number committed publicly in advance.
- The transcript is published, and the verifier is generated from the final zkey.
- The verifier is immutable, so a new ceremony means a new pool.
- A public ceremony with independent contributors (target at least 10). Each contribution is verified with
12. Privacy limits (what is NOT hidden)
| Event | What anyone sees |
|---|---|
| Shield | Depositor address, asset, exact amount, time. The pending record links the depositor to both output commitments, and so to their asset. |
| Unshield | Recipient address, asset, exact amount, fee, relayer, time. Its change commitment is asset-labelled. |
| Transfer or claim | Two nullifiers, two commitments, two 113-byte ciphertexts, the root used, and the submitter (self or sponsor). No amount and no asset. |
| Ragequit | Depositor, asset and amount, as public as the shield it undoes. |
- Timing and amount correlation. A shield of 37.12 USDC followed by an unshield of 37.12 USDC is linkable by an observer, whatever the cryptography does. The app adds round-amount presets, split and delay suggestions, and an honest anonymity-set meter.
- Anonymity set. It's only as large as the pool's real usage. Sei DeFi TVL is about $20M (from the build plan), so expect a small set early on.
- Self-submission links your public account to "made a private transaction".
- Old roots reveal an upper bound on when a note was inserted (section 7.1).
- USDC issuer risk. Circle can blacklist the vault and freeze every USDC note. This can't be fixed, and native SEI isn't affected.
13. Threat model summary (expanded in threats.md at Gate 4)
- The sender: can reclaim a link until the claim lands.
- Anyone who reads a link: can claim it until the claim lands.
- The relayer or sponsor: can censor or delay, and sees IP and timing. It can't redirect funds or change outputs (R3). It can't take a fee on a private transfer.
- The ASP poster: can refuse approvals. It can't move funds or block a refund.
- Circle: can freeze USDC held by the vault.
- There is no owner. An upgrade key would be a drain key, so none exists.
- The trusted setup: testnet keys are single-operator and forgeable by that operator. Mainnet needs section 11's ceremony.
- Client compromise: a malware-infected phone with an unlocked seed can spend. Passkey-gated unwrapping narrows the window but doesn't remove it.
14. Licences
| Component | Licence | How we use it |
|---|---|---|
| poseidon-lite 0.3.0 | MIT | TypeScript runtime hashing |
poseidon-solidity 0.0.5 (PoseidonT3.sol) |
MIT | Vendored unmodified, with its SPDX header kept |
| @noble/hashes 2.4.0 | MIT | keccak, HKDF, SHA-256 |
| circomlibjs 0.1.7 | GPL-3.0 | Dev dependency, used only in tests as an independent cross-check. Never imported by shipped code. |
| circomlib 2.0.5 (licence note) | GPL-3.0 | Correction: the build plan lists it as LGPL-3.0, but npm and the repository say GPL-3.0. |
| circom 2.1.9 / snarkjs 0.7.4 | GPL-3.0 | Build tools only |
| circomlib 2.0.5 (circuits) | GPL-3.0 | Provisional (Gate 3): included in the circuits through one seam file, lib.circom, so packages/circuits is GPL-3.0-only for now. |
snarkjs-exported Solidity verifier (packages/contracts/src/JoinSplitVerifier.sol) |
GPL-3.0 (checked: generated header SPDX-License-Identifier: GPL-3.0, "Copyright 2021 0KIMS association") |
Generated and committed unmodified. A deployed vault that includes it ships GPL-3.0 code. |
| forge-std v1.17.0 | MIT/Apache-2.0 | Tests only |
- [Provisional, pending Godwin] The circuits use circomlib (GPL-3.0). To swap, replace the three includes in
lib.circomwith our own Poseidon, Num2Bits, IsZero, IsEqual and ForceEqualIfEnabled templates written from the MIT constants. Then recompile, rerun the setup and regenerate the verifier. The tests are template-agnostic. - Because the verifier is GPL-3.0 whatever we do with circomlib, the contracts that embed it will likely need a GPL-compatible licence when published. Godwin's call.
- [Decided, 18 Nov 2026]
packages/sdkis Apache-2.0. It does not contain the prover or the circuit, so the GPL on those does not apply to it. Apache-2.0 lets another project ship the client, including a patent grant, without forcing that project to use the GPL. - [Open] The rest of the repository (app, relayer, and the contracts apart from the GPL verifier) stays
UNLICENSED, all rights reserved, and the repo stays private, until Godwin chooses. The circuits stay GPL-3.0.
15. Gate status
| Gate | Status | Evidence |
|---|---|---|
| 1 (this spec) | Draft v2.1 written; needs Godwin's approval | This file |
| 2 (hasher and tree) | Passed | Below |
| 3 (circuit) | Passed | Below |
| 4 (vault on 1328) | Passed (testnet) | Below; deployments/atlantic-2.json |
| 5 (SDK, links, recovery) | Passed (testnet). Phone PRF confirmed; proving time still open | Below |
Gate 5 evidence (18 Nov 2026, WAT):
- SDK (
@batin/sdk):- keys, seed wrapping and backup file
- note encryption with the mandatory self-check (Spec 8.2)
- links
- a view-key scanner over pool events
- a transaction builder: coin selection, encrypt, self-check, then witness
- an injectable prover; the SDK doesn't bundle snarkjs (GPL)
BatinWallet: sync, shield, pay by address or by link, claim or reclaim with R1–R5 handling, unshield
- Tests:
- SDK: 35 (Gate 2/3: 20; Gate 5: 15).
- Relayer: 4, covering policy, the token bucket, the daily budget, and the HTTP refusals for double claims, rate limits and budget.
- Vectors:
test-vectors/note-encryption.json(4 positive including a link note, 10 negative, plus the self-check mismatch case),keys.jsonandlinks.json. Regeneration is byte-identical.
- On-chain e2e (
packages/e2e/scripts/e2e-gate5.ts, real SDK encryption,packages/e2e/e2e-results/gate5-atlantic-2.json):- Shield 1.5 USDC. The scanner sees our own pending deposit.
- ASP approval.
- Pay 1 USDC via a link, with the gas sponsored by the relayer.
- Claim from a fresh key that has no gas, sponsored.
- The client pre-check returns "already-claimed" for a second claimer (R2) and for the sender's reclaim (R1). The relayer refuses a claim proof built anyway with HTTP 409
NullifierSpent, before spending any gas. - Both users restore from passphrase backup files plus a scan: Bob finds 1 USDC; Alice finds 0.5 USDC and sees her link as claimed.
- Bob unshields 0.9 USDC plus a 0.1 fee to the relayer. Alice unshields 0.5 USDC herself.
- 1.5 USDC returns and both shielded balances are 0.
- Gas on Sei: about 1.26M per private transfer or claim, about 1.29M per unshield, 728k per USDC shield, and 833k for approving one deposit.
- Scan cost: restore plus scan took about 1.2 s for 22 leaves and 32 ciphertexts. Sei's RPC limits
eth_getLogsto 2,000 blocks, so a full-history scan needs an indexer as the pool ages. [Open] - Lost in a failed first run: 1.5 USDC (deposit id 3). The run approved it, but a lagging load-balanced RPC returned stale logs, and the in-memory seed was gone when the script aborted. That note can never be spent. Fixes:
sync()now waits for the receipt block and fornextIndexcoverage, and e2e backup files go to the keys directory outside the repo. - Not proven:
- Phone proving time. Passkey PRF on a physical phone is confirmed (unlock, and a USDC deposit, 18 Nov 2026).
- the browser app UX (claim on open,
replaceState, share sheet) - the in-circuit encryption relation (v3)
Gate 4 evidence (18 Nov 2026, WAT):
- Deployed on Atlantic-2 (1328), NOT FOR PRODUCTION:
BatinPool0x5cCd205EED235d74f31A3c350Ece94AF11E07E72,Groth16Verifier0x7dd09F80AF704A475caaDB45cB723C1F944B44F1,PoseidonT30x7E2364aF14A317EdCc107ECbC64C6BeD10A62614. ASP poster = deployer. The deployed verifier runtime bytecode equals the local build byte for byte. - Foundry: 48 tests pass.
BatinPool.t.sol(23) uses the real verifier and real proofs fromtest-vectors/pool-flow.json: the full flow, batch approval writing one root, approval and refund state machine, R1–R5, binding checks (unknown root, duplicate or non-canonical nullifier, tampered amount, ciphertext length, wrong chain), caps, fee without relayer, failed native send, reentrancy, and the USDC balance-delta check. - Invariant (
BatinPoolInvariant.t.sol, accept-all verifier and a ghost note ledger; circuit soundness is Gate 3's job): per asset,vault balance == Σ unspent approved notes + Σ PENDING, ghost ledger = pool, current root always known. 256 runs × depth 64 = 16,384 calls, 0 reverts. Fuzz: 3 × 512 runs (batch insert = sequential insert, shield caps and kinds, extAmount range). - On-chain smoke test (
packages/e2e/scripts/smoke-testnet.ts, results inpackages/e2e/smoke-results/atlantic-2.json): shield 0.2 SEI and 2 USDC, a third 0.5 USDC deposit, batch ASP approval, private USDC transfer to a claim-link note, private SEI transfer, claim against an old root (R5), reclaim then fails withNullifierSpent(eth_call), unshield USDC with a relayer fee, unshield SEI, ragequit of the third deposit. The on-chain root equalled the SDK model root. Final pool: 0.15 SEI + 1 USDC (the change notes), 0 pending. - Gas on Sei (receipts): shield SEI 764k, shield USDC 802k, batch approve of 2 deposits 2.85M, private transfer about 1.26M, unshield USDC with fee 1.29M, unshield SEI 1.27M, refund 59k. At 51 gwei a private transfer costs about 0.064 SEI. Foundry's Ethereum-schedule numbers are about 150k lower per tx (Sei's 72k new-slot price).
- Main cost is Poseidon: each
insertPairclimbs 19 levels with library calls. The section 17 optimisation is still open.
Gate 3 evidence:
- Circuit: 22,292 constraints and 12 public inputs.
- Proving time:
snarkjs groth16.fullProvetakes 1.04 to 1.32 s in Node on the 8-core build box. This is not a phone; phone timing is Gate 5. - Verifier gas:
verifyProofcosts 269,409 gas in Foundry (Ethereum schedule, which has the same precompile prices as Sei). - Valid proofs: shield, transfer (to a claim-link note), claim and unshield (negative
extAmountplus a relayer fee) all prove and verify. Their 12 public signals equal the TypeScript-computed root, nullifiers, commitments and extDataHash, in spec order. - Rejected tampering: changing any one of the 12 signals fails verification, both in snarkjs and on-chain. A non-canonical (
+r) signal is also rejected on-chain. - Constraint violations caught at the intended line:
- inflated output (conservation)
- USDC note spent as SEI
- USDC and SEI inputs under one tokenId
- field wraparound
- amount = 2^96
- wrong root
- wrong ASP root
- bad path
- duplicate nullifier
- nullifier for the wrong leafIndex
- commitment mismatch
fee > 0withpublicAssetId = 0extAmount ≠ 0(both signs) withpublicAssetId = 0publicAssetId ≠ tokenIdleafIndex ≥ 2^20
- Accepted edge cases: a zero-amount dummy input with a garbage path is accepted, and so is a SEI shield of 2^96 − 1 wei.
- extDataHash: the TypeScript value equals Solidity's
keccak256(abi.encode(...)) mod ron all four vectors. - Static analysis: circomspect v0.9.0 reports 5 warnings, all triaged as non-issues in
packages/circuits/CIRCOMSPECT.md: three intentional binding squares, and twoNum2Bits(20)aliasing notes that don't apply below 254 bits. - Limitation: negative tests run through the witness calculator, which asserts every
===. That catches violations of the intended constraints. It does not prove the R1CS is free of under-constrained signals. circomspect lowers that risk, but the Gate 6 independent review is still required.
Gate 2 evidence:
- Shared vectors:
test-vectors/poseidon-t3.json(16 vectors) andtest-vectors/merkle.json(33 leaves, zeros 0..32, per-insert roots, pair roots, 3 paths, and a full depth-3 tree).- Generated by
packages/sdk/scripts/gen-vectors.ts. - Consumed unchanged by the Foundry test suite (
vm.readFile).
- Generated by
- Matching roots, identical in TypeScript and Solidity:
- Empty, depth 20:
0x13c5576a29f3443513d5bc31baf9e74ac2947abaccf5e3199c4d3843d08468e1 - After 32 leaves (single inserts, and also after 16 pair inserts):
0x139a3b133a85ee4767e4f96e245991fef6156104b897efed7fb429c4ba1511d1 - After 33 leaves:
0x2c04edf4390bbda45f040ef289613605a3d10a8d02ab2107e843fbb094ef058e
- Empty, depth 20:
- Gas, measured in Foundry on the Ethereum schedule:
insertPairat depth 20 costs about 761k gas.- One
PoseidonT3.hashcall costs about 32.5k gas (the build plan assumed 21k). - On Sei, add about 50k for the root slot (72k there versus 22k on Ethereum).
- [Open, Gate 4] Optimisation: an inlined Poseidon to avoid the library-call overhead.
16. Prior art (neutral; we claim no new primitive)
- Tornado Cash Nova:
- 2-in-2-out join-split with a signed
extAmount. extDataHashbinding recipient, relayer, fee and encrypted outputs.- On-chain encrypted outputs for recovery.
- A Poseidon incremental tree with a bounded root history (100 roots in its
MerkleTreeWithHistory). - Our note and transaction shape follows this lineage.
- 2-in-2-out join-split with a signed
- Privacy Pools (0xbow):
- An association-set provider (ASP) and ragequit for unapproved deposits.
- v1 core is Apache-2.0. v2 (Oct 2026: transfers, payment requests) is BUSL-1.1, so we don't fork it.
- Our pending, approved and refunded design is a simplified variant: insertion is gated instead of using an association subset.
- Railgun:
- A multi-token shielded pool where the token is committed inside the note and isn't revealed in private transfers.
- Any historical Merkle root is accepted.
- Contracts are UNLICENSED, so we read them and don't reuse them.
- Aztec Connect:
- A join-split where
public_asset_idequals the note asset when value is deposited or withdrawn, and is 0 for private sends. - The asset type stays private in sends.
- Section 5 rule 3 is the same rule.
- A join-split where
- Zcash Sapling/Orchard: in-band note encryption with an ephemeral DH key, a KDF and ChaCha20-Poly1305. Section 8's construction has the same shape on BabyJubJub.
- Bearer claim links: these exist in prior work too, for example Tornado deposit notes as bearer secrets and Privacy Pools v2 payment requests.
16.1 Products in the same category (checked 17–18 Nov 2026, neutral)
Each entry is one line on what it is, then one line on how Batin differs. These are differences in design or deployment, not claims of novelty.
- Styx (styx.cash): private SOL payments on Solana devnet, with STARK proofs made on the device (no trusted setup) and hybrid post-quantum note encryption (ML-KEM-768 + X25519).
- Batin is on Sei EVM with Groth16 (it needs a setup), BabyJubJub encryption, and a deposit-approval (ASP) step that Styx doesn't describe.
- Nyx Privacy (nyxprivacy.tech): a Solana shielded pool (Groth16, BN254, Poseidon, ChaCha20 notes, depth-20 tree) plus Nyx Pay for x402 payments. Its site lists Sei among its x402 payment networks, but not as a pool chain.
- Batin's pool is on Sei itself, with asset-private SEI/USDC transfers, claim links and gated-insertion ragequit.
- nyx.money: a passkey wallet on Aztec, an L2 with privacy built in.
- Batin adds privacy through a contract on a public EVM chain, and uses passkeys only to wrap a random seed (section 9).
- murk.finance: a private pool on Monad whose deposits are screened/certified before use. It's the closest prior art to our ASP approval step.
- Batin differs in chain (Sei), in pending/approved/refunded records with a depositor-only refund, and in the cross-asset transfer rule (section 5).
- Murk (murk.one): a private wallet live on Solana mainnet.
- Batin is on a different chain and stack (circom/Groth16 on Sei EVM).
- Privacy Pools v2 (privacypools.com, 0xbow): an ASP-screened pool with private transfers and payment requests, on several EVM chains but not Sei. It's BUSL-1.1, so we don't fork it.
- Batin's ragequit and approval are a simplified gated-insertion variant, and its claim links are bearer links with defined races, not requests.
- Shield (Aleo, shield.app / shield.fi): a private wallet on a privacy-native L1, with Hyperlane bridges for entry and exit and USDCx via Circle xReserve.
- Batin is on an ordinary EVM chain, with no bridge in the foundation.
- Hinkal: shielded accounts and stealth addresses on several EVM chains (the build plan's check: not Sei).
- Batin is on Sei, with asset-private SEI/USDC transfers and claim links.
- Opaque (opaque.credit, testnet): fixed-denomination notes spent as "1 of 8" ring proofs through 3-hop relays, with post-quantum keys, on Ethereum, Arc and the XRP Ledger.
- Batin uses arbitrary-amount join-split notes and a Merkle-tree anonymity set rather than rings of 8, and runs on Sei.
- Brume (brume.cash): a Solana wallet with a "shielded balance" in mainnet beta. Its own disclosure says balances and amounts aren't hidden yet, and private transfers are on its roadmap.
- Batin hides amounts and assets in transfers by design, and is testnet-only so far.
What we add is an engineering and product combination rather than a cryptographic novelty:
- To the build plan's knowledge (not re-verified in this revision), no shielded pool is deployed on Sei.
- Phone-first PRF-wrapped keys.
- Chain-and-pool-bound claim links with defined race semantics.
- Gated-insertion ragequit.
- Asset-private transfers across SEI and USDC.
17. Open questions (owner and deadline)
- Keep or drop
aspRoot(section 7.2). Godwin. The Gate 4 testnet pool is deployed with it; dropping it now means a new circuit, setup, verifier and pool. - Licence for circuits and contracts (section 14). Godwin. circomlib is in use provisionally.
- Sponsor abuse: handled at Gate 5 by off-chain relayer limits (
packages/relayer/README.md). Still open for mainnet: per-account quotas and/or anin0+in1>0constraint. - The Poseidon gas optimisation (section 15): about 1.26M gas per private transfer on Sei, mostly tree hashing. Before mainnet (moved from Gate 4).
- The mainnet ASP poster (multisig or timelock), lineage-aware exclusion, and the public Phase-2 ceremony. Before mainnet.
- Proving time on Godwin's phone (Gate 5b). Passkey PRF is confirmed: unlock, and a USDC deposit, 18 Nov 2026.
- An event indexer for scanning (the RPC caps
eth_getLogsat 2,000 blocks). Before a public beta. - Explorer source verification on Sourcify (
packages/contracts/script/verify-sourcify.sh): done 2026-11-18 on Godwin's go-ahead. PoseidonT3 and Groth16Verifier are exact (full) matches, BatinPool is a partial match (bytecode matches, metadata hash differs). Seiscan shows all three verified. Record:deployments/atlantic-2-verification.json. The superseded pool was not verified. - An independent circuit review (circomspect is done, see section 15). Gate 6.
Source: spec/Spec-v2.1.md