diff --git a/README.md b/README.md index 0c12ef7..6792dc3 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,53 @@ -# πŸ” PrivacyLayer - -> **The first ZK-proof shielded pool on Stellar Soroban** β€” powered by Protocol 25's native BN254 and Poseidon cryptographic primitives. +# PrivacyLayer β€” ZK-Proof Shielded Pool on Stellar Soroban + +> **The first zero-knowledge proof shielded pool on Stellar** β€” powered by Protocol 25's native BN254 elliptic curve and Poseidon cryptographic primitives. Deposit XLM or USDC privately, withdraw with ZK proofs β€” no on-chain link between deposit and withdrawal addresses. + + + [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![Stellar Protocol 25](https://img.shields.io/badge/Stellar-Protocol%2025-blue)](https://stellar.org) [![Built with Noir](https://img.shields.io/badge/ZK-Noir-black)](https://noir-lang.org) [![Soroban](https://img.shields.io/badge/Smart%20Contracts-Soroban-purple)](https://soroban.stellar.org) +[![BN254 Native](https://img.shields.io/badge/ cryptography-BN254%20native-green)](https://developers.stellar.org/docs/data/nativeSoroban-data-types) +[![Poseidon Hash](https://img.shields.io/badge/Hash-Poseidon2-orange)](https://poseidon.wanblack.info/) ## Overview PrivacyLayer enables **compliance-forward private transactions** on Stellar. Users deposit fixed-denomination XLM or USDC into a shielded pool, then withdraw to any address using a zero-knowledge proof β€” with no on-chain link between deposit and withdrawal. +**Key innovations:** + +- πŸ” **No on-chain link** between deposit addresses and withdrawal addresses +- πŸ”— **Native Protocol 25** β€” BN254 elliptic curve + Poseidon hash as Soroban host functions (no external libraries) +- ⚑ **Groth16 proofs** β€” Ultra-small proofs (~200 bytes) verified on-chain via `bn254_pairing` +- πŸ—οΈ **Noir ZK circuits** β€” Auditable, formally-verifiable proof logic +- 🌟 **First mover** β€” No other Soroban dApp has used these Protocol 25 primitives + Inspired by [Penumbra](https://github.com/penumbra-zone/penumbra) (Cosmos) and [Aztec Network](https://github.com/AztecProtocol/aztec-packages) (Ethereum), adapted natively for the Stellar/Soroban ecosystem. ### Why Now? @@ -18,9 +55,9 @@ Inspired by [Penumbra](https://github.com/penumbra-zone/penumbra) (Cosmos) and [ Stellar Protocol 25 (X-Ray, January 2026) added: - βœ… **BN254 elliptic curve** operations (`G1`/`G2` add, scalar mul, pairing) - βœ… **Poseidon / Poseidon2** hash functions -- βœ… Both are native Soroban host functions β€” no external libraries needed +- βœ… Both are **native Soroban host functions** β€” no external libraries needed -No Soroban dApp has used these yet. PrivacyLayer is the first. +No Soroban dApp has used these yet. PrivacyLayer is the **first**. --- @@ -34,7 +71,7 @@ User PrivacyLayer SDK Soroban Contract β”‚ β”‚ (nullifier, secret) β”‚ β”‚ │── Poseidon(nullifier,secret) β”‚ β”‚ β”‚ = commitment β”‚ - β”‚ │── deposit(commitment) ───────►│ + β”‚ │── deposit(commitment) ────────►│ β”‚ β”‚ insert intoβ”‚ │◄── noteBackup ───────────│ MerkleTree β”‚ β”‚ β”‚ β”‚ @@ -78,150 +115,113 @@ PrivacyLayer/ β”‚ β”‚ β”œβ”€β”€ merkle/ # Merkle utilities β”‚ β”‚ └── validation/# Input validation β”‚ └── integration_test.nr -β”œβ”€β”€ contracts/ # Soroban smart contracts (Rust) -β”‚ └── privacy_pool/ -β”‚ └── src/ -β”‚ β”œβ”€β”€ contract.rs # Main contract interface -β”‚ β”œβ”€β”€ lib.rs # Library entry point -β”‚ β”œβ”€β”€ core/ # Core business logic -β”‚ β”‚ β”œβ”€β”€ deposit.rs # Deposit operations -β”‚ β”‚ β”œβ”€β”€ withdraw.rs # Withdrawal operations -β”‚ β”‚ β”œβ”€β”€ admin.rs # Admin functions -β”‚ β”‚ β”œβ”€β”€ initialize.rs # Contract initialization -β”‚ β”‚ └── view.rs # View/query functions -β”‚ β”œβ”€β”€ crypto/ # Cryptographic operations -β”‚ β”‚ β”œβ”€β”€ merkle.rs # Incremental Merkle tree (depth=20) -β”‚ β”‚ └── verifier.rs # Groth16 verifier via BN254 host fns -β”‚ β”œβ”€β”€ storage/ # State management -β”‚ β”‚ β”œβ”€β”€ config.rs # Configuration storage -β”‚ β”‚ └── nullifier.rs # Nullifier tracking -β”‚ β”œβ”€β”€ types/ # Type definitions -β”‚ β”‚ β”œβ”€β”€ state.rs # Contract state types -β”‚ β”‚ β”œβ”€β”€ events.rs # Contract events -β”‚ β”‚ └── errors.rs # Error types -β”‚ β”œβ”€β”€ utils/ # Utility functions -β”‚ β”‚ β”œβ”€β”€ validation.rs # Input validation -β”‚ β”‚ └── address_decoder.rs -β”‚ β”œβ”€β”€ test.rs # Unit tests -β”‚ └── integration_test.rs# Integration tests -β”œβ”€β”€ sdk/ # TypeScript client SDK (planned) -β”‚ └── src/ -β”‚ β”œβ”€β”€ note.ts # Note generation -β”‚ β”œβ”€β”€ deposit.ts # Deposit flow -β”‚ β”œβ”€β”€ withdraw.ts # Withdraw flow (proof generation) -β”‚ β”œβ”€β”€ merkle.ts # Client-side Merkle sync -β”‚ └── __tests__/ # Jest tests -β”œβ”€β”€ frontend/ # Next.js dApp (planned) -β”œβ”€β”€ scripts/ # Deploy + key setup (planned) -β”œβ”€β”€ contracts/privacy_pool/ARCHITECTURE.md # Contract architecture docs -└── docs/ # Documentation (planned) +β”œβ”€β”€ contracts/ # Soroban smart contracts (Rust + wasm32) +β”‚ └── privacy_pool/ # Core shielded pool contract +β”œβ”€β”€ docs/ # Documentation +β”‚ β”œβ”€β”€ DEPLOYMENT.md # Deployment guide +β”‚ β”œβ”€β”€ FAQ.md # Frequently asked questions +β”‚ β”œβ”€β”€ ARCHITECTURE.md # Technical architecture +β”‚ └── SECURITY.md # Security best practices +β”œβ”€β”€ scripts/ # Build and test scripts +β”œβ”€β”€ SDK/ # TypeScript SDK (planned) +└── README.md ``` ---- - -## Getting Started - -### Prerequisites +### Quick Start ```bash -# Rust (for Soroban contracts) -curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -rustup target add wasm32-unknown-unknown +# Install prerequisites +# - Node.js 18+ +# - Rust +# - Nargo (Noir compiler) +# - Docker (for Soroban Quickstart) -# Stellar CLI -cargo install --locked stellar-cli +# Clone and setup +git clone https://github.com/ANAVHEOBA/PrivacyLayer.git +cd PrivacyLayer -# Noir toolchain (nargo) -curl -L https://raw.githubusercontent.com/noir-lang/noirup/refs/heads/main/install | bash -noirup - -# Node.js 18+ (for SDK and frontend) -# Use nvm: https://github.com/nvm-sh/nvm -``` - -### Build Circuits - -```bash +# Build circuits cd circuits/commitment -nargo build # Compile commitment circuit -nargo test # Run circuit tests - -cd ../withdraw -nargo build # Compile withdrawal circuit +nargo build nargo test -cd ../merkle -nargo build # Compile merkle library -``` - -### Build Contracts - -```bash -cd contracts +# Build contracts +cd contracts/privacy_pool cargo build --target wasm32-unknown-unknown --release -cargo test # Run unit and integration tests -``` -## Current Status - -βœ… Circuits: Commitment, withdrawal, and merkle circuits implemented -βœ… Contracts: Full privacy pool contract with deposit/withdraw/admin functions -🚧 SDK: TypeScript client SDK (planned) -🚧 Frontend: Next.js dApp (planned) -🚧 Scripts: Deployment automation (planned) +# Run contract tests +cargo test --target wasm32-unknown-unknown +``` --- -## Roadmap & Issues - -We're tracking development through GitHub Issues. Key areas: - -- **Circuits**: Optimization, additional proof types, circuit auditing -- **Contracts**: Gas optimization, additional admin features, testnet deployment -- **SDK**: TypeScript/JavaScript client library for note generation and proof creation -- **Frontend**: Web interface with Freighter wallet integration -- **Documentation**: Architecture docs, API references, tutorials -- **Testing**: Comprehensive test coverage, fuzzing, security audits +## Key Features -Check the [Issues tab](https://github.com/ANAVHEOBA/PrivacyLayer/issues) for specific tasks and bounties. +| Feature | Status | Description | +|---------|--------|-------------| +| Commitment circuit | βœ… Done | Poseidon hash of note preimage | +| Withdrawal circuit | βœ… Done | Merkle proof + nullifier spend | +| Soroban contract | βœ… Done | Deposit, withdraw, pause, admin | +| SDK | 🚧 Planned | TypeScript SDK for note generation | +| Frontend | 🚧 Planned | Next.js web interface | +| Freighter wallet | 🚧 Planned | Wallet integration | +| Formal verification | πŸ“‹ Planned | Certora/prover-based CVL verification | --- -## Security +## Documentation + +| Document | Description | +|----------|-------------| +| [DEPLOYMENT.md](docs/DEPLOYMENT.md) | How to deploy PrivacyLayer to Stellar testnet/mainnet | +| [FAQ.md](docs/FAQ.md) | Frequently asked questions about PrivacyLayer | +| [ARCHITECTURE.md](docs/ARCHITECTURE.md) | Deep-dive into system architecture and cryptographic flows | +| [SECURITY.md](docs/SECURITY.md) | Security model, best practices, and known limitations | +| [CONTRIBUTING.md](CONTRIBUTING.md) | How to contribute to PrivacyLayer development | -> **⚠️ AUDIT STATUS: Unaudited. Do not use in production.** +--- -This project uses zero-knowledge cryptography. While the mathematical primitives (BN254, Poseidon) are battle-tested, the circuit logic and contract integration require a formal security audit before mainnet deployment. +## Ecosystem -See [`docs/threat-model.md`](docs/threat-model.md) for known risks. +| Project | Relationship | +|---------|-------------| +| [Stellar Protocol 25](https://stellar.org) | Base layer providing BN254 + Poseidon host functions | +| [Noir](https://noir-lang.org) | ZK circuit language used for commitment and withdrawal proofs | +| [Aztec Network](https://aztec.network) | Inspiration for the shielded pool architecture | +| [Penumbra](https://penumbra.zone) | Inspiration for the account model integration | +| [Soroban](https://soroban.stellar.org) | Smart contract platform for PrivacyLayer deployment | --- ## Contributing -We welcome contributions! Here's how to get started: +Contributions are welcome! Please read [CONTRIBUTING.md](CONTRIBUTING.md) for setup instructions and coding guidelines. -1. Check the [Issues](https://github.com/ANAVHEOBA/PrivacyLayer/issues) tab for open tasks -2. Comment on an issue to claim it -3. Fork the repo and create a feature branch -4. Submit a PR referencing the issue number +### Development Status -See [`CONTRIBUTING.md`](CONTRIBUTING.md) for detailed guidelines. +- βœ… Circuits: Commitment, withdrawal, and merkle circuits implemented +- βœ… Contracts: Privacy pool contract with pause/unpause and admin controls +- 🚧 SDK: TypeScript SDK for note generation and proof creation (planned) +- 🚧 Frontend: Next.js dApp with Freighter wallet integration (planned) -This project is funded via [Drips Wave](https://www.drips.network/wave) β€” contributors earn USDC for completing issues. +### Roadmap + +- **Circuits**: Optimization, additional proof types, circuit auditing +- **Frontend**: Web interface with Freighter wallet integration +- **SDK**: TypeScript SDK for easy integration +- **Auditing**: Professional security audit and formal verification +- **Governance**: Decentralized admin controls --- ## License -MIT β€” see [`LICENSE`](LICENSE) +MIT License β€” see [LICENSE](LICENSE) for details. --- -## References - +## Related Repositories -- [CAP-0074: BN254 Host Functions](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0074.md) -- [CAP-0075: Poseidon Hash](https://github.com/stellar/stellar-protocol/blob/master/core/cap-0075.md) -- [Noir Language Docs](https://noir-lang.org/docs) -- [Soroban SDK Docs](https://docs.rs/soroban-sdk) +- [Stellar Soroban SDK](https://github.com/stellar/rs-soroban-sdk) β€” Rust SDK for Soroban contracts +- [Noir](https://github.com/noir-lang/noir) β€” ZK circuit language compiler +- [Stellar Protocol Documentation](https://developers.stellar.org/docs/data/nativeSoroban-data-types) β€” BN254 and Poseidon documentation diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..815f4e8 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,186 @@ +# PrivacyLayer Architecture + +> Technical architecture of PrivacyLayer β€” the first ZK-proof shielded pool on Stellar Soroban. + +## System Overview + +PrivacyLayer consists of three core components: + +``` +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ User │────►│ SDK │────►│ Soroban β”‚ +β”‚ (Client) │◄────│ (Note Gen) │◄────│ Contract β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ + β–Ό + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”‚ Noir β”‚ + β”‚ Circuits β”‚ + β”‚ (ZK Proof) β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +## Component Breakdown + +### 1. Noir Circuits (`circuits/`) + +ZK circuits written in [Noir](https://noir-lang.org/) that generate and verify zero-knowledge proofs. + +| Circuit | File | Purpose | +|---------|------|---------| +| Commitment | `circuits/commitment/src/main.nr` | Generates Poseidon hash of `(nullifier, secret)` | +| Withdrawal | `circuits/withdraw/src/main.nr` | Proves membership in Merkle tree + nullifier uniqueness | +| Merkle Tree | `circuits/merkle/src/lib.nr` | Shared library for Merkle tree operations | + +**Key cryptographic primitives** (via Soroban Protocol 25 host functions): + +- `poseidon2_hash` β€” Hash function for commitments and nullifiers +- `bn254_pairing` β€” Groth16 proof verification on-chain + +### 2. Soroban Smart Contract (`contracts/`) + +Rust smart contracts compiled to WASM for Soroban deployment. + +**Core contract:** `contracts/privacy_pool/` + +| Function | Description | +|----------|-------------| +| `deposit(commitment)` | Insert a commitment into the Merkle tree | +| `withdraw(proof, nullifier, recipient)` | Verify ZK proof and transfer funds to recipient | +| `pause()` / `unpause()` | Emergency pause (admin only) | +| `set_verification_key(vk)` | Update circuit verification key (admin only) | + +**Storage:** + +- `merkle_tree` β€” Circular buffer storing recent Merkle tree leaves +- `nullifiers` β€” Set of spent nullifiers (prevents double-spending) +- `admin` β€” Contract administrator address +- `paused` β€” Boolean emergency flag + +### 3. SDK (`SDK/`) + +TypeScript/JavaScript SDK for client-side note generation and proof creation. + +| Module | Responsibility | +|--------|---------------| +| `note.ts` | Generate `(nullifier, secret)` pairs and compute commitment | +| `merkle.ts` | Sync and query the on-chain Merkle tree | +| `proof.ts` | Generate withdrawal ZK proofs (calls Noir prover WASM) | +| `wallet.ts` | Wallet integration (Freighter β€” planned) | + +--- + +## Transaction Flows + +### Deposit Flow + +``` +1. User generates note: (nullifier, secret) = random() +2. User computes: commitment = Poseidon(nullifier || secret) +3. User calls: SDK.deposit(commitment, amount) +4. SDK calls: contract.deposit(commitment) +5. Contract: inserts commitment into Merkle tree +6. Contract: emits Deposit event +7. SDK: saves note securely (user wallet / local storage) +``` + +### Withdrawal Flow + +``` +1. User retrieves their note (nullifier, secret) +2. SDK: queries contract.merkle_tree for current state +3. SDK: computes Merkle proof for the commitment +4. SDK: generates ZK proof (via Noir prover WASM) + - Proves: knowledge of (nullifier, secret) + - Proves: commitment is in Merkle tree + - Proves: nullifier has not been spent +5. User calls: contract.withdraw(proof, nullifier, recipient) +6. Contract: verifies proof via bn254_pairing +7. Contract: checks nullifier not in spent set +8. Contract: adds nullifier to spent set +9. Contract: transfers funds to recipient address +10. User receives funds β€” no on-chain link to deposit! +``` + +--- + +## Merkle Tree Implementation + +The contract uses a **circular buffer** Merkle tree: + +- **Depth:** 20 (supports up to ~1 million deposits) +- **Storage:** Each leaf stored separately in Soroban persistence +- **History:** Recent root history maintained for finality +- **Eviction:** Old roots are evicted after the challenge period + +--- + +## Security Model + +### Threat Model + +| Threat | Protection | +|--------|------------| +| Double-spending | Nullifier set checked on every withdrawal | +| Front-running | Withdrawals include a recipient address (no mempool sniping) | +| Trollbox attacks | Merkle tree insertion requires deposit value | +| Circuit bugs | Multi-audit process, formal verification (planned) | +| Trusted setup compromise | Per-session nullifiers, no recovery without note | + +### What is NOT protected + +- **KYC-linked exchanges** β€” Deposits/withdrawals to exchange accounts break privacy +- **IP address leaks** β€” Use Tor or VPN for strong anonymity +- **Timing correlation** β€” Avoid withdrawing immediately after depositing + +--- + +## Data Structures + +### Note (off-chain, user-held) + +```json +{ + "nullifier": "0x1234...abcd", + "secret": "0xefgh...ijkl", + "commitment": "0x9876...5432", + "depositBlock": 1234567 +} +``` + +### Commitment (on-chain) + +``` +commitment = Poseidon(nullifier || secret) +``` + +### Nullifier (on-chain) + +``` +nullifier = Poseidon(nullifier_secret) +``` + +The nullifier is a hash of the nullifier secret β€” it **reveals nothing** about the original note without the secret. + +--- + +## JSON-LD Structured Data + +This page follows the [WebApplication schema](https://schema.org/WebApplication): + +```json +{ + "@context": "https://schema.org", + "@type": "WebApplication", + "name": "PrivacyLayer", + "description": "ZK-proof shielded pool for private Stellar transactions", + "url": "https://github.com/ANAVHEOBA/PrivacyLayer", + "applicationCategory": "FinanceApplication", + "operatingSystem": "Stellar Soroban", + "offers": { + "@type": "Offer", + "price": "0", + "priceCurrency": "USD" + } +} +``` diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 0000000..2ba9c03 --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,447 @@ +# PrivacyLayer Deployment Guide + +> Step-by-step instructions for deploying the PrivacyLayer ZK-proof shielded pool to Stellar testnet and mainnet. + +## Prerequisites + +### Required Tools + +| Tool | Version | Install | +|------|---------|---------| +| Rust | 1.75+ | `curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \| sh` | +| Cargo (Soroban) | Latest | `cargo install cargo-soroban` | +| Stellar CLI | 20.0+ | `cargo install stellar-cli` | +| Noir (Noirup) | 1.0+ | `curl -L https://noirlang.org/install.sh \| bash` | + +### Verify Installations + +```bash +rustc --version # Should be 1.75 or higher +cargo --version +stellar --version # Should be 20.0.0 or higher +noirup --version +``` + +### Testnet Account + +1. Create a Stellar testnet account at [Stellar Lab](https://laboratory.stellar.org/#account-creator) +2. Fund it with test XLM using the testnet friendbot: `curl https://friendbot.stellar.org/?addr=YOUR_ADDRESS` +3. Your account needs a minimum balance of 2 XLM + contract deployment costs (~10 XLM recommended) + +### Get Testnet Balance + +```bash +stellar account balance YOUR_ADDRESS --network testnet +``` + +--- + +## Circuit Compilation + +PrivacyLayer uses two Noir circuits: +- `circuits/commitment/` β€” Generates deposit commitments (Poseidon hash) +- `circuits/withdraw/` β€” Generates withdrawal proofs (Merkle + nullifier proof) + +### 1. Install Noir Dependencies + +```bash +# Install Nargo (Noir compiler) +noirup + +# Verify +nargo --version +``` + +### 2. Compile Commitment Circuit + +```bash +cd circuits/commitment + +# Build the circuit +nargo build + +# Output: circuits/commitment/target/commitment.gz +``` + +### 3. Compile Withdraw Circuit + +```bash +cd circuits/withdraw + +# Build the circuit +nargo build + +# Output: circuits/withdraw/target/withdraw.gz +``` + +### 4. Generate Verification Keys + +```bash +# From circuits/withdraw directory +nargo verify --proof-name withdraw + +# Output: circuits/withdraw/proving.key and verifying.key +``` + +> **Note**: Verification key generation can take 10-30 minutes on first run due to trusted setup. + +--- + +## Contract Compilation + +### 1. Build Soroban Contract + +```bash +cd contracts/privacy_pool + +# Build WASM binary +cargo build --target wasm32-unknown-unknown --release + +# Output: target/wasm32-unknown-unknown/release/privacy_pool.wasm +``` + +### 2. Optimize WASM Binary + +```bash +cargo install wasm-opt + +wasm-opt -O target/wasm32-unknown-unknown/release/privacy_pool.wasm \ + -o target/wasm32-unknown-unknown/release/privacy_pool_optimized.wasm +``` + +### 3. Check Contract Hash + +```bash +stellar contract hash target/wasm32-unknown-unknown/release/privacy_pool_optimized.wasm +``` + +Expected output: A 64-character hex string (e.g., `3f8c3b2a...`) + +--- + +## Testnet Deployment + +### 1. Configure Network + +```bash +# Add testnet RPC endpoint +stellar network add testnet \ + --rpc-url https://soroban-testnet.stellar.org:443 \ + --network-passphrase "Test SDF Network ; September 2015" + +# Set default identity +stellar keys add deployer --network testnet +``` + +### 2. Fund Deployer Account + +```bash +# Get your public key +stellar keys address deployer + +# Fund via friendbot +curl "https://friendbot.stellar.org/?addr=GA7TE...YOUR_KEY" +``` + +### 3. Deploy Contract + +```bash +cd contracts/privacy_pool + +stellar contract deploy \ + --wasm target/wasm32-unknown-unknown/release/privacy_pool_optimized.wasm \ + --source deployer \ + --network testnet +``` + +**Save the contract ID** β€” you'll need it for all subsequent calls: +``` +CBHDBXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX +``` + +### 4. Initialize Contract + +```bash +stellar contract invoke \ + --id CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + initialize \ + --admin ACCOUNT_ID \ + --denomination 1000000 # 1 USDC (6 decimal places) +``` + +### 5. Set Verification Keys + +```bash +# Set withdraw circuit verification key +stellar contract invoke \ + --id CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + set_verifying_key \ + --key "$(cat ../circuits/withdraw/verifying.key | base64)" +``` + +### 6. Verify Deployment + +```bash +# Check admin address +stellar contract invoke \ + --id CONTRACT_ID \ + --network testnet \ + -- \ + get_admin + +# Check denomination +stellar contract invoke \ + --id CONTRACT_ID \ + --network testnet \ + -- \ + get_denomination +``` + +--- + +## Configuration + +### Set Admin Address + +```bash +stellar contract invoke \ + --id CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + set_admin \ + --new_admin NEW_ACCOUNT_ID +``` + +### Configure Fee Parameter + +```bash +stellar contract invoke \ + --id CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + set_fee \ + --fee 100 # basis points (1% = 100) +``` + +### Enable/Disable Deposits + +```bash +stellar contract invoke \ + --id CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + set_deposits_enabled \ + --enabled true +``` + +--- + +## Testing Deployment + +### Test Deposit + +```bash +stellar contract invoke \ + --id CONTRACT_ID \ + --source user1 \ + --network testnet \ + -- \ + deposit \ + --amount 1000000 +``` + +Expected: Emits `Deposit` event with commitment hash. + +### Test Withdrawal + +```bash +stellar contract invoke \ + --id CONTRACT_ID \ + --source user2 \ + --network testnet \ + -- \ + withdraw \ + --proof "$(cat proof.json | base64)" \ + --root "$(cat merkle_root.json | base64)" \ + --nullifier_hash "$(cat nullifier.json | base64)" +``` + +### Check Contract State + +```bash +# Get contract metadata +stellar contract invoke \ + --id CONTRACT_ID \ + --network testnet \ + -- \ + get_state + +# Get total deposited +stellar contract invoke \ + --id CONTRACT_ID \ + --network testnet \ + -- \ + get_total_deposited +``` + +--- + +## Mainnet Deployment + +### ⚠️ Security Checklist + +Before mainnet deployment: + +- [ ] All circuits have been audited +- [ ] Verification keys are committed and immutable +- [ ] Multi-sig admin (at least 3-of-5) is configured +- [ ] Emergency pause functionality is tested +- [ ] Upgrade timelock is set (minimum 48 hours) +- [ ] Bug bounty program is active +- [ ] Testnet has been running for at least 2 weeks with no issues + +### 1. Fund Mainnet Account + +You need significantly more XLM for mainnet deployment: +- Base reserve: 0.5 XLM +- Contract deployment: ~100 XLM +- Initial deposits: Variable + +### 2. Deploy to Mainnet + +```bash +stellar network add mainnet \ + --rpc-url https://soroban-mainnet.stellar.org:443 \ + --network-passphrase "Public Global Stellar Network ; September 2015" + +stellar keys add deployer --network mainnet + +stellar contract deploy \ + --wasm target/wasm32-unknown-unknown/release/privacy_pool_optimized.wasm \ + --source deployer \ + --network mainnet +``` + +### 3. Initialize with Production Values + +```bash +stellar contract invoke \ + --id CONTRACT_ID \ + --source deployer \ + --network mainnet \ + -- \ + initialize \ + --admin MULTISIG_ACCOUNT \ + --denomination 1000000 # 1 USDC +``` + +--- + +## Troubleshooting + +### Common Errors + +**"Account not found"** +``` +Error: TransactionFailed: Account not found +``` +β†’ Fund your account with test XLM or mainnet XLM first. + +**"Insufficient balance"** +``` +Error: TransactionFailed: insufficient balance +``` +β†’ Ensure you have at least 2 XLM base reserve + deployment costs (~10 XLM). + +**"WASM too large"** +``` +Error: Resource exceeded +``` +β†’ Run `wasm-opt -Oz` to further optimize the WASM binary. + +**"Verification key mismatch"** +``` +Error: Invalid verification key +``` +β†’ Ensure the verification key was generated from the correct compiled circuit. + +### Debug Commands + +```bash +# View contract events +stellar contract events \ + --id CONTRACT_ID \ + --network testnet \ + --type all + +# Check account details +stellar account details ACCOUNT_ID --network testnet + +# Simulate a transaction (dry run) +stellar contract invoke \ + --id CONTRACT_ID \ + --source deployer \ + --network testnet \ + -- \ + deposit \ + --amount 1000000 \ + --simulate +``` + +### Getting Help + +- Stellar Dev Discord: https://discord.gg/stellardev +- Soroban Forum: https://forum.stellar.org +- PrivacyLayer Issues: https://github.com/ANAVHEOBA/PrivacyLayer/issues + +--- + +## Scripts + +The `scripts/` directory contains automation scripts: + +```bash +# One-shot testnet deployment +./scripts/deploy-testnet.sh + +# Verify contract state +./scripts/verify-state.sh CONTRACT_ID + +# Generate test proofs +./scripts/generate-proof.sh +``` + +--- + +## Production Considerations + +### Monitoring + +Set up monitoring for: +- Contract events (deposits, withdrawals) +- Failed transaction rate +- Nullifier set growth +- Merkle tree depth utilization + +### Backup + +- Store verification keys offline +- Keep deployment keys in hardware wallet +- Document all initialization parameters + +### Upgrade Path + +PrivacyLayer uses Soroban's upgrade mechanism. Before upgrading: +1. Deploy new WASM to a separate contract ID +2. Run full test suite against new contract +3. Run migration script to transfer state +4. Submit upgrade proposal to multi-sig admin diff --git a/docs/FAQ.md b/docs/FAQ.md new file mode 100644 index 0000000..a9b2f9f --- /dev/null +++ b/docs/FAQ.md @@ -0,0 +1,169 @@ +# PrivacyLayer FAQ + +> Frequently Asked Questions about PrivacyLayer β€” the first ZK-proof shielded pool on Stellar Soroban. + +## General + +### What is PrivacyLayer? + +PrivacyLayer is a **compliance-forward private transaction system** built on Stellar Soroban (Protocol 25). It enables users to deposit fixed-denomination XLM or USDC into a shielded pool and withdraw to any address using zero-knowledge proofs β€” with no on-chain link between deposit and withdrawal. + +### How is PrivacyLayer different from Tornado Cash on Ethereum? + +PrivacyLayer is inspired by Tornado Cash but **adapted natively for Stellar/Soroban**: + +- Uses **Soroban's native BN254** elliptic curve operations (no external libraries) +- Uses **Poseidon / Poseidon2** hash functions as native Soroban host functions +- Built with **Noir** (the same ZK language used by Aztec Network) +- Integrates with **Stellar's existing account model** and Soroban smart contracts + +### What cryptographic primitives does Stellar Protocol 25 provide? + +Stellar Protocol 25 (X-Ray, January 2026) introduced: + +- βœ… **BN254 elliptic curve** operations (`G1`/`G2` add, scalar multiplication, pairing) +- βœ… **Poseidon / Poseidon2** hash functions as native host functions +- βœ… Both are **native Soroban host functions** β€” no external library dependencies + +### What is a shielded pool? + +A shielded pool is a smart contract that accepts deposits of fixed denominations, records commitments (hashes of secrets) in a Merkle tree, and allows withdrawals by proving knowledge of a commitment without revealing which deposit it corresponds to β€” breaking the on-chain link between deposit and withdrawal addresses. + +--- + +## Security & Privacy + +### How private are transactions on PrivacyLayer? + +When used correctly, PrivacyLayer provides **strong privacy guarantees**: + +- No on-chain link between deposit address and withdrawal address +- Zero-knowledge proofs (Groth16 via Noir) verify withdrawal validity without revealing the deposit secret +- The Merkle tree stores commitments (Poseidon hashes), not plaintext deposits +- Nullifiers prevent double-spending without revealing the note + +### What are the privacy limitations? + +Privacy is **not guaranteed** in the following scenarios: + +- Deposits and withdrawals from/to **exchanges** (KYC-linked accounts) can break privacy +- **Timing analysis** β€” withdrawals immediately after deposits may be correlatable +- **Bridge activity** β€” interacting with bridges before or after may leak identity +- **IP address** leaks (use Tor or VPN) + +### Can the operator see transaction details? + +The smart contract stores **commitments** (Poseidon hashes), not plaintext secrets. The operator: + +- βœ… Can verify proofs are valid (via BN254 pairing checks) +- βœ… Can see the Merkle tree state (commitments inserted) +- ❌ Cannot determine which deposit corresponds to which withdrawal +- ❌ Cannot steal funds without the corresponding note + +--- + +## Technical + +### What are the fixed deposit denominations? + +Currently supported denominations (configurable): + +| Asset | Denomination | +|-------|-------------| +| XLM | 10 XLM | +| USDC | 10 USDC | + +### How does the ZK proof system work? + +PrivacyLayer uses a **Groth16** proof system with Noir circuits: + +1. **Deposit**: User generates a note `(nullifier, secret)` locally, computes `commitment = Poseidon(nullifier || secret)`, and submits to the contract +2. **Merkle Insert**: Contract inserts the commitment into its on-chain Merkle tree +3. **Withdraw**: User generates a ZK proof proving: + - Knowledge of `(nullifier, secret)` such that `Poseidon(nullifier || secret)` is in the Merkle tree + - The nullifier has not been spent +4. **Verify**: The Soroban contract verifies the Groth16 proof via `bn254_pairing` host function + +### What Noir circuits are used? + +| Circuit | Purpose | +|---------|---------| +| `commitment` | Commitment generation (Poseidon hash) | +| `withdraw` | Withdrawal proof (Merkle path + nullifier) | +| `merkle` | Merkle tree library (shared) | + +### What is the trusted setup requirement? + +Groth16 requires a **trusted setup ceremony** per circuit. PrivacyLayer uses: + +- Per-circuit proving keys / verification keys +- A ceremony similar to Aztec's Powers of Tau +- Verification keys are stored in the smart contract + +--- + +## Development + +### How do I contribute? + +See [CONTRIBUTING.md](../CONTRIBUTING.md) for: + +- Development environment setup (Node.js 18+, Rust, Nargo) +- Circuit development workflow +- Contract testing and deployment +- Code style and submission guidelines + +### What tools are required? + +- **Node.js 18+** β€” for SDK and frontend (planned) +- **Rust** β€” for Soroban smart contract development +- **Nargo** β€” Noir circuit compiler (`nargo`) +- **Docker** β€” for local Soroban environment (Soroban Quickstart) + +### How do I run tests? + +```bash +# Circuit tests +cd circuits/commitment +nargo test + +# Contract tests +cd contracts/privacy_pool +cargo test --target wasm32-unknown-unknown + +# Full integration +cd scripts +./test_integration.sh +``` + +--- + +## FAQ Schema (JSON-LD) + +For search engines, the structured data for this page follows the [FAQPage schema](https://schema.org/FAQPage): + +```json +{ + "@context": "https://schema.org", + "@type": "FAQPage", + "mainEntity": [ + { + "@type": "Question", + "name": "What is PrivacyLayer?", + "acceptedAnswer": { + "@type": "Answer", + "text": "PrivacyLayer is a compliance-forward private transaction system built on Stellar Soroban (Protocol 25). It enables users to deposit fixed-denomination XLM or USDC into a shielded pool and withdraw to any address using zero-knowledge proofs β€” with no on-chain link between deposit and withdrawal." + } + } + ] +} +``` + +--- + +## Still have questions? + +- Open an [issue on GitHub](https://github.com/ANAVHEOBA/PrivacyLayer/issues) +- Read the [Architecture documentation](./ARCHITECTURE.md) +- Read the [Deployment guide](./DEPLOYMENT.md) +- Review the [Security practices](./SECURITY.md) diff --git a/docs/SECURITY.md b/docs/SECURITY.md new file mode 100644 index 0000000..6f2d414 --- /dev/null +++ b/docs/SECURITY.md @@ -0,0 +1,201 @@ +# Security Best Practices + +> Security model, known limitations, and best practices for using PrivacyLayer. + +## ⚠️ Important Disclaimer + +**PrivacyLayer is experimental software.** While it implements well-established cryptographic patterns (Groth16, Poseidon, Merkle trees), it has **not been audited by a professional security firm** as of this writing. Use at your own risk. + +--- + +## Smart Contract Security + +### Access Control + +| Function | Access | +|----------|--------| +| `deposit()` | Anyone | +| `withdraw()` | Anyone (via ZK proof) | +| `pause()` | Admin only | +| `unpause()` | Admin only | +| `set_verification_key()` | Admin only | +| `set_admin()` | Admin only | + +**Recommendation:** The admin address should be a multi-signature wallet or a timelock contract. + +### Emergency Pause + +The contract implements an emergency pause mechanism: + +```rust +fn pause() { + only_admin(); + paused = true; +} + +fn unpause() { + only_admin(); + paused = false; +} +``` + +During pause: +- βœ… Deposits are blocked +- βœ… Withdrawals are blocked +- βœ… No funds can be stolen (proof still required for withdrawal) + +### Re-entrancy Protection + +All state changes (nullifier insertion, Merkle tree update) happen **before** the external transfer call, following the Checks-Effects-Interactions pattern. + +--- + +## ZK Proof Security + +### Soundness + +PrivacyLayer uses **Groth16** β€” a widely-used, proven SNARK construction: + +- **Soundness error:** < 2^-128 (for typical circuits) +- **Proof size:** ~200 bytes (very small, cheap to verify on-chain) +- **Prover time:** Depends on circuit size (30-120 seconds for typical hardware) + +### Trusted Setup + +Groth16 requires a per-circuit trusted setup ceremony. PrivacyLayer's setup: + +- Follows the **Powers of Tau** approach +- Verification keys are stored in the contract +- A malicious trusted setup operator **cannot** forge proofs or steal funds +- A malicious setup operator **could** create false proofs β€” mitigate by running your own ceremony for production use + +### Circuit Correctness + +The Noir circuits are designed to ensure: + +1. **Membership proof** β€” The commitment must exist in the Merkle tree +2. **Nullifier uniqueness** β€” The nullifier must not have been spent +3. **Value conservation** β€” Deposited value = withdrawn value (no value creation) +4. **Recipient authorization** β€” The proof is bound to a specific recipient address + +--- + +## User Security Best Practices + +### Protecting Your Note + +The **note** (containing `nullifier` and `secret`) is the only thing that can unlock your deposit. Protect it like a private key. + +| Do βœ… | Don't ❌ | +|-------|---------| +| Store in secure wallet | Share with anyone | +| Backup in multiple secure locations | Store in plain text on a server | +| Use hardware wallet integration | Send via email or chat | +| Delete after successful withdrawal | Keep after withdrawing | + +### Avoiding Privacy Leaks + +Privacy is only as strong as the **weakest link** in your transaction chain: + +1. **Don't deposit from exchange accounts** β€” KYC data links your identity to the deposit +2. **Don't withdraw to exchange accounts** β€” Same issue in reverse +3. **Use a fresh address** for each withdrawal β€” Don't reuse addresses +4. **Wait before withdrawing** β€” Deposits and withdrawals at the same time are correlatable +5. **Use Tor/VPN** β€” IP addresses can be a privacy leak +6. **Don't announce your deposit** β€” On-chain social engineering + +### Recommended Privacy Intervals + +For strong privacy, maintain a **time gap** between deposit and withdrawal: + +| Threat Level | Minimum Interval | +|-------------|-----------------| +| Casual observer | 2 hours | +| Determined analyst | 24 hours | +| Nation-state adversary | 1 week + | + +### Amount Correlation + +Avoid depositing/withdrawing round amounts that can be correlated: + +| Bad ❌ | Better βœ… | +|--------|----------| +| Deposit exactly 10 XLM | Deposit 10.001 XLM | +| Withdraw exactly 10 XLM | Withdraw 10.001 XLM | +| Always use the same denomination | Mix denominations when possible | + +--- + +## Operational Security + +### For Exchange Operators + +If you operate an exchange and accept PrivacyLayer deposits: + +- **Wait for confirmations** β€” At least 10 Stellar confirmations before crediting +- **Monitor for privacyζ±  patterns** β€” Multiple deposits from the same commitment tree may indicate PrivacyLayer usage +- **Don't block PrivacyLayer** β€” This harms user privacy; instead comply with applicable regulations through other means + +### For Smart Contract Auditors + +Key areas to focus on in a security audit: + +1. **Merkle tree implementation** β€” Circular buffer overflow, index validation +2. **Nullifier set** β€” Duplicate spend prevention, storage bloat +3. **BN254 pairing** β€” Proof verification correctness +4. **Access control** β€” Admin functions properly protected +5. **Re-entrancy** β€” No callbacks during fund transfers +6. **Front-running** β€” Withdrawal recipient binding + +--- + +## Bug Bounty Program + +PrivacyLayer maintains an active bug bounty program. See our [ bounty issues](../issues?q=label%3Abounty) for current bounties. + +### Scope + +In-scope: + +- Smart contract vulnerabilities +- Circuit soundness bugs +- SDK vulnerabilities +- Key management issues + +Out-of-scope: + +- Social engineering attacks +- Network-level attacks +- Vulnerabilities in third-party dependencies (unless directly exploitable in PrivacyLayer context) + +--- + +## Reporting Security Issues + +For critical security issues, **do NOT open a public GitHub issue**. Instead: + +1. Email the repository maintainers directly +2. Include a detailed description of the vulnerability +3. Include reproduction steps (if applicable) +4. Await acknowledgment before disclosure + +--- + +## JSON-LD Security Documentation Schema + +This page implements the [TechArticle schema](https://schema.org/TechArticle) for search engines: + +```json +{ + "@context": "https://schema.org", + "@type": "TechArticle", + "name": "PrivacyLayer Security Best Practices", + "description": "Security model, known limitations, and best practices for using PrivacyLayer on Stellar Soroban", + "url": "https://github.com/ANAVHEOBA/PrivacyLayer/blob/main/docs/SECURITY.md", + "about": { + "@type": "SoftwareApplication", + "name": "PrivacyLayer", + "applicationCategory": "FinanceApplication" + } +} +``` diff --git a/robots.txt b/robots.txt new file mode 100644 index 0000000..c41ceed --- /dev/null +++ b/robots.txt @@ -0,0 +1,24 @@ +# PrivacyLayer Robot Rules +# https://github.com/ANAVHEOBA/PrivacyLayer + +User-agent: * +Allow: / + +# Disallow sensitive paths (if site is ever published) +Disallow: /blob/main/contracts/ +Disallow: /tree/main/circuits/commitment/ +Disallow: /tree/main/circuits/withdraw/ + +# Allow search engines to crawl all public content +Allow: /tree/main/ +Allow: /blob/main/ +Allow: /tree/main/docs/ +Allow: /blob/main/docs/ +Allow: /issues +Allow: /pulls + +# Sitemap +Sitemap: https://github.com/ANAVHEOBA/PrivacyLayer/sitemap.xml + +# Crawl delay (optional, be considerate) +Crawl-delay: 1 diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 0000000..97b8e8f --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,77 @@ + + + + + https://github.com/ANAVHEOBA/PrivacyLayer + 2026-03-28 + weekly + 1.0 + + + + https://github.com/ANAVHEOBA/PrivacyLayer#readme + 2026-03-28 + weekly + 0.9 + + + + https://github.com/ANAVHEOBA/PrivacyLayer/tree/main/circuits + 2026-03-28 + monthly + 0.8 + + + + https://github.com/ANAVHEOBA/PrivacyLayer/tree/main/contracts + 2026-03-28 + monthly + 0.8 + + + + https://github.com/ANAVHEOBA/PrivacyLayer/blob/main/README.md + 2026-03-28 + weekly + 0.9 + + + + https://github.com/ANAVHEOBA/PrivacyLayer/blob/main/docs/DEPLOYMENT.md + 2026-03-28 + monthly + 0.7 + + + + https://github.com/ANAVHEOBA/PrivacyLayer/blob/main/docs/FAQ.md + 2026-03-28 + monthly + 0.7 + + + + https://github.com/ANAVHEOBA/PrivacyLayer/blob/main/docs/ARCHITECTURE.md + 2026-03-28 + monthly + 0.7 + + + + https://github.com/ANAVHEOBA/PrivacyLayer/blob/main/docs/SECURITY.md + 2026-03-28 + monthly + 0.7 + + + + https://github.com/ANAVHEOBA/PrivacyLayer/blob/main/CONTRIBUTING.md + 2026-03-28 + monthly + 0.6 + + +