Venrable18/STELLAR-EPay

GitHub: Venrable18/STELLAR-EPay

基于Stellar Soroban平台构建的隐私保护支付协议,利用零知识证明实现交易金额与余额的链上隐藏。

Stars: 0 | Forks: 0

#Stellar-EncryptedPay [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) [![Stellar Protocol](https://img.shields.io/badge/Stellar-Protocol%2025%20(X--Ray)-0F6E56)](https://stellar.org/blog/developers/announcing-stellar-x-ray-protocol-25) [![Soroban](https://img.shields.io/badge/Soroban-Smart%20Contracts-1A3C5E)](https://soroban.stellar.org) [![ZK Stack](https://img.shields.io/badge/ZK-Groth16%20%2F%20BN254-7F77DD)](https://docs.circom.io) [![Status](https://img.shields.io/badge/Status-Active%20Development-orange)](https://github.com) #项目文档:https://docs.google.com/document/d/1PteAHLLHQlN499KjNcEHlvT6i8t1ziKS/edit?usp=sharing&ouid=105697343927857090340&rtpof=true&sd=true ## 目录 - [概述](#overview) - [工作原理](#how-it-works) - [系统架构](#system-architecture) - [项目脚手架](#project-scaffold) - [智能合约架构](#smart-contract-architecture) - [ZK 电路设计](#zk-circuit-design) - [交易流程](#transaction-flows) - [私密支付通道](#private-payment-channels) - [私密流式支付](#private-streaming-payments) - [依赖项](#dependencies) - [环境设置](#environment-setup) - [安装](#installation) - [运行项目](#running-the-project) - [测试](#testing) - [部署](#deployment) - [SDK 使用](#sdk-usage) - [功能路线图](#feature-roadmap) - [贡献](#contributing) ## 概述 Stellar-EncryptedPay 是 Stellar 的 Soroban 平台上的零知识隐私协议。它允许任何个人或企业发送、接收和流式传输私密支付——在链上完全隐藏金额、余额和元数据——同时为监管机构保持选择性合规审计能力。 它直接受到 Avalanche 的 eERC 标准的启发,但专为 Stellar 的架构量身定制,利用了 2026 年 1 月引入原生 **BN254** 椭圆曲线运算和 **Poseidon** 哈希到 Soroban 的 **Protocol 25 (X-Ray)** 升级。 ### 独特性 | 功能 | 描述 | 全球首创? | |---|---|---| | 私密转账 | 隐藏金额的 ZK 证明验证转账 | 否(Avalanche 上存在 eERC) | | **加密备注** | 附加到每笔支付的加密发票/备注 | **是** | | **私密流式支付** | 按秒计薪/订阅流,金额隐藏 | **是** | | **私密支付通道** | 具有 ZK 状态转换的链下双边通道 | **是** | | 隐身地址 | 每次支付的一次性地址,与接收者无关联 | 否(Ethereum 上存在) | | 选择性披露 | 证明“支付 > $X” 而不透露确切金额 | 超越 Avalanche eERC | | SEP-41 转换器 | 将任何 Stellar 代币包装为私密形式并转回 | Stellar 上是 | ## 工作原理 从高层次来看,Stellar-EncryptedPay 的工作方式类似于屏蔽池: 1. 用户将公共 SEP-41 代币**存入**池合约——其余额变为链上的加密承诺 2. 他们可以通过在链下生成零知识证明(通过 WASM 客户端端)来**私密转账**,该证明在不透露金额的情况下验证交易 3. Soroban 验证者合约使用 BN254 主机函数检查证明——如果有效,承诺将更新 4. 接收者可以通过证明其承诺的所有权随时**提取** ``` Public token ──deposit──► Encrypted pool ──transfer──► Encrypted pool ──withdraw──► Public token (wrap) [commitment] (ZK proof) [commitment] (ZK proof) (unwrap) ``` 任何观察链的人都无法看到:存入了多少、转账了多少、谁发送给谁,或者当前余额是多少。 ## 系统架构 ### 全栈概览 ``` graph TB subgraph Client["Client Layer (Browser / Mobile)"] UI[React dApp] SDK[TypeScript SDK] WASM[Circom WASM Prover] end subgraph Contracts["Soroban Smart Contracts (Rust)"] POOL[pool_contract] VERIFIER[groth16_verifier] ASP[asp_registry] STREAM[stream_manager] MEMO[memo_vault] CHANNEL[channel_manager] end subgraph ZKToolchain["ZK Toolchain (Off-chain)"] CIRCOM[Circom Circuits] SNARK[SnarkJS] C2S[circom2soroban] end subgraph StellarNetwork["Stellar Network (Protocol 25)"] BN254[BN254 Host Functions] POSEIDON[Poseidon Hash] SEP41[SEP-41 Token Interface] LEDGER[Stellar Ledger] end UI --> SDK SDK --> WASM WASM --> CIRCOM SDK --> POOL SDK --> STREAM SDK --> CHANNEL POOL --> VERIFIER POOL --> ASP POOL --> MEMO STREAM --> VERIFIER CHANNEL --> VERIFIER VERIFIER --> BN254 POOL --> POSEIDON POOL --> SEP41 SEP41 --> LEDGER CIRCOM --> SNARK SNARK --> C2S C2S --> VERIFIER ``` ### 层级职责 ``` graph LR subgraph L1["Layer 1 — User"] A1[Web browser] A2[Mobile wallet] end subgraph L2["Layer 2 — SDK"] B1[Key generation] B2[Proof generation] B3[Tx construction] B4[Balance decryption] end subgraph L3["Layer 3 — Contracts"] C1[Pool logic] C2[ZK verification] C3[Compliance / ASP] end subgraph L4["Layer 4 — Cryptography"] D1[Groth16 zk-SNARKs] D2[ElGamal encryption] D3[BabyJubJub curve] D4[Poseidon hash] end subgraph L5["Layer 5 — Stellar"] E1[BN254 host fns] E2[Fast finality 5s] E3[Sub-cent fees] end L1 --> L2 --> L3 --> L4 --> L5 ``` ## 项目脚手架 ``` stellar-encrypted-pay/ │ ├── contracts/ # Soroban smart contracts (Rust) │ ├── pool_contract/ │ │ ├── Cargo.toml │ │ └── src/ │ │ ├── lib.rs # Contract entry point │ │ ├── deposit.rs # Deposit instruction handler │ │ ├── transfer.rs # Private transfer handler │ │ ├── withdraw.rs # Withdrawal handler │ │ ├── commitment.rs # Commitment tree management │ │ └── types.rs # Shared types and structs │ │ │ ├── groth16_verifier/ │ │ ├── Cargo.toml │ │ └── src/ │ │ ├── lib.rs # Verifier contract entry point │ │ ├── verifier.rs # BN254 proof verification logic │ │ └── vk.rs # Embedded verification keys │ │ │ ├── asp_registry/ │ │ ├── Cargo.toml │ │ └── src/ │ │ ├── lib.rs # ASP contract entry point │ │ ├── membership.rs # Membership Merkle tree │ │ └── exclusion.rs # Exclusion / blocklist management │ │ │ ├── stream_manager/ │ │ ├── Cargo.toml │ │ └── src/ │ │ ├── lib.rs # Streaming contract entry point │ │ ├── stream.rs # Stream open/close/withdraw │ │ └── rate.rs # Rate commitment and time logic │ │ │ ├── memo_vault/ │ │ ├── Cargo.toml │ │ └── src/ │ │ ├── lib.rs # Memo vault entry point │ │ └── memo.rs # Encrypted memo storage and retrieval │ │ │ └── channel_manager/ │ ├── Cargo.toml │ └── src/ │ ├── lib.rs # Payment channel entry point │ ├── channel.rs # Channel open/close/dispute │ └── state.rs # Off-chain state transition types │ ├── circuits/ # Circom ZK circuits │ ├── transfer/ │ │ ├── transfer.circom # Main transfer validity circuit │ │ ├── balance_check.circom # Sender balance >= amount │ │ └── double_spend.circom # Nullifier uniqueness check │ │ │ ├── deposit/ │ │ └── deposit.circom # Deposit commitment circuit │ │ │ ├── withdraw/ │ │ └── withdraw.circom # Withdrawal ownership circuit │ │ │ ├── stream/ │ │ ├── stream_open.circom # Stream creation circuit │ │ └── stream_claim.circom # Vested amount claim circuit │ │ │ ├── channel/ │ │ ├── channel_open.circom # Channel opening commitment │ │ └── channel_update.circom # Off-chain state transition proof │ │ │ └── lib/ │ ├── merkle.circom # Merkle inclusion proof │ ├── poseidon.circom # Poseidon hash gadget │ └── babyjubjub.circom # BabyJubJub key operations │ ├── sdk/ # TypeScript client SDK │ ├── src/ │ │ ├── index.ts # SDK public API │ │ ├── keys/ │ │ │ ├── keygen.ts # BabyJubJub key generation │ │ │ └── register.ts # On-chain key registration │ │ ├── proofs/ │ │ │ ├── prover.ts # WASM proof generation wrapper │ │ │ ├── transfer.ts # Transfer proof builder │ │ │ ├── stream.ts # Stream proof builder │ │ │ └── channel.ts # Channel state proof builder │ │ ├── transactions/ │ │ │ ├── deposit.ts # Deposit tx constructor │ │ │ ├── transfer.ts # Transfer tx constructor │ │ │ ├── withdraw.ts # Withdraw tx constructor │ │ │ └── stream.ts # Stream tx constructors │ │ ├── balance/ │ │ │ ├── decrypt.ts # Balance decryption │ │ │ └── sync.ts # Balance state sync from chain │ │ ├── memo/ │ │ │ ├── encrypt.ts # Memo encryption │ │ │ └── decrypt.ts # Memo decryption │ │ └── compliance/ │ │ ├── selective_disclosure.ts # Selective disclosure proof gen │ │ └── audit_export.ts # Auditor key management │ │ │ ├── wasm/ # Compiled Circom WASM artifacts │ │ ├── transfer_js/ │ │ ├── stream_js/ │ │ └── channel_js/ │ │ │ ├── package.json │ └── tsconfig.json │ ├── frontend/ # React dApp (Vite) │ ├── src/ │ │ ├── App.tsx │ │ ├── pages/ │ │ │ ├── Send.tsx │ │ │ ├── Stream.tsx │ │ │ ├── Channel.tsx │ │ │ └── History.tsx │ │ ├── components/ │ │ └── hooks/ │ ├── package.json │ └── vite.config.ts │ ├── scripts/ # Build and deployment scripts │ ├── setup/ │ │ ├── trusted_setup.sh # Powers-of-Tau ceremony │ │ └── compile_circuits.sh # Compile all Circom circuits │ ├── deploy/ │ │ ├── deploy_testnet.sh # Testnet deployment │ │ └── deploy_mainnet.sh # Mainnet deployment │ └── generate_verifiers.sh # Run circom2soroban on all circuits │ ├── tests/ │ ├── contracts/ # Soroban contract unit tests │ ├── circuits/ # Circuit constraint tests │ └── integration/ # End-to-end flow tests │ ├── Cargo.toml # Workspace Cargo manifest ├── Cargo.lock ├── package.json # Root package manifest ├── .env.example # Environment variable template └── README.md ``` ## 智能合约架构 ### 合约交互图 ``` graph TD USER([User / SDK]) subgraph CoreContracts["Core Contracts"] POOL[pool_contract\nDeposit · Transfer · Withdraw] VERIFIER[groth16_verifier\nOn-chain ZK proof check] ASP[asp_registry\nCompliance Merkle trees] end subgraph FeatureContracts["Feature Contracts"] STREAM[stream_manager\nPrivate streaming] MEMO[memo_vault\nEncrypted memos] CHANNEL[channel_manager\nPayment channels] end subgraph TokenLayer["Token Layer"] WRAPPER[sep41_wrapper\nPublic to Encrypted] TOKEN[SEP-41 Token] end USER -->|deposit / transfer / withdraw| POOL POOL -->|verify_proof| VERIFIER POOL -->|check_membership| ASP POOL -->|store_memo| MEMO POOL -->|wrap / unwrap| WRAPPER WRAPPER --> TOKEN USER -->|open_stream / claim_stream| STREAM STREAM -->|verify_proof| VERIFIER USER -->|open / close / dispute channel| CHANNEL CHANNEL -->|verify_proof| VERIFIER CHANNEL -->|release_funds| POOL ``` ### 池合约状态机 ``` stateDiagram-v2 [*] --> Unregistered Unregistered --> Registered : register_pubkey(babyjubjub_pk) Registered --> HasBalance : deposit(token, amount) HasBalance --> HasBalance : transfer(proof, nullifier, new_commitment) HasBalance --> Registered : withdraw(proof, amount) HasBalance --> Streaming : open_stream(rate_commitment, duration) Streaming --> HasBalance : claim_stream(proof, elapsed_time) Streaming --> HasBalance : cancel_stream() HasBalance --> ChannelOpen : open_channel(counterparty) ChannelOpen --> HasBalance : close_channel(final_proof) ChannelOpen --> Disputed : dispute(stale_state_proof) Disputed --> HasBalance : resolve_dispute() ``` ## ZK 电路设计 ### 电路依赖图 ``` graph TD subgraph Lib["Library circuits (shared)"] MERKLE[merkle.circom] POSEIDON[poseidon.circom] BJJ[babyjubjub.circom] ELGAMAL[elgamal.circom] NULL[nullifier.circom] end subgraph Main["Main circuits (one per instruction)"] DEP[deposit.circom] TXN[transfer.circom] WDW[withdraw.circom] STR_O[stream_open.circom] STR_C[stream_claim.circom] CH_O[channel_open.circom] CH_U[channel_update.circom] end POSEIDON --> MERKLE POSEIDON --> NULL BJJ --> ELGAMAL MERKLE --> TXN ELGAMAL --> TXN NULL --> TXN BJJ --> TXN MERKLE --> DEP POSEIDON --> DEP BJJ --> DEP MERKLE --> WDW NULL --> WDW BJJ --> WDW POSEIDON --> STR_O ELGAMAL --> STR_O BJJ --> STR_O MERKLE --> STR_C NULL --> STR_C POSEIDON --> CH_O BJJ --> CH_O MERKLE --> CH_U NULL --> CH_U ELGAMAL --> CH_U ``` ### 转账电路——证明内容 ``` flowchart LR subgraph Private["Private inputs (never revealed)"] SK[sender secret key] AMT[transfer amount] BBAL[sender balance] SALT[randomness salt] end subgraph Public["Public inputs (on-chain visible)"] ROOT[Merkle root] NUL[nullifier hash] NEW_C[new commitment] REC_PK[recipient pubkey] end subgraph Constraints["Circuit constraints"] C1[balance is gte amount] C2[nullifier = Poseidon of sk and commitment] C3[commitment is in Merkle tree] C4[new_commitment = Poseidon of amount salt rec_pk] C5[ElGamal encryption correct] end SK & BBAL & AMT & SALT --> C1 SK & SALT --> C2 ROOT --> C3 AMT & SALT & REC_PK --> C4 AMT & REC_PK & SALT --> C5 C1 & C2 & C3 & C4 & C5 --> PROOF([Groth16 proof submitted on-chain]) ``` ## 交易流程 ### 完整的存款 → 转账 → 提取 ``` sequenceDiagram actor Alice actor Bob participant SDK as TypeScript SDK participant WASM as Circom WASM participant POOL as pool_contract participant VERIFIER as groth16_verifier participant LEDGER as Stellar Ledger Note over Alice,LEDGER: DEPOSIT Alice->>SDK: deposit(token=USDC, amount=100) SDK->>SDK: commitment C_A = Poseidon(amount, salt, pk_A) SDK->>POOL: invoke deposit(C_A, token, amount) POOL->>LEDGER: lock 100 USDC POOL->>LEDGER: store C_A in Merkle tree LEDGER-->>Alice: confirmed Note over Alice,LEDGER: PRIVATE TRANSFER Alice->>SDK: transfer(to=Bob, amount=40, memo="Invoice 2024") SDK->>WASM: generate_proof(sk_A, balance=100, amount=40, pk_B) WASM-->>SDK: proof, nullifier N_A, commitment C_B SDK->>SDK: encrypt_memo("Invoice 2024", pk_B) SDK->>POOL: invoke transfer(proof, N_A, C_A, C_B, encrypted_memo) POOL->>VERIFIER: verify_proof(proof, root, N_A, C_B) VERIFIER->>VERIFIER: BN254 pairing check VERIFIER-->>POOL: valid POOL->>LEDGER: mark N_A spent POOL->>LEDGER: store C_B POOL->>LEDGER: store encrypted_memo LEDGER-->>Alice: confirmed — no amounts visible Note over Alice,LEDGER: WITHDRAW Bob->>SDK: withdraw(commitment=C_B, amount=40) SDK->>WASM: generate_proof(sk_B, C_B, amount=40) WASM-->>SDK: proof, nullifier N_B SDK->>POOL: invoke withdraw(proof, N_B, C_B, amount=40) POOL->>VERIFIER: verify_proof VERIFIER-->>POOL: valid POOL->>LEDGER: release 40 USDC to Bob Bob->>SDK: decrypt_memo(C_B, sk_B) SDK-->>Bob: "Invoice 2024" ``` ## 私密支付通道 架构上最原创的功能。双方维持链下支付关系,其中运行余额是一个 ZK 承诺——只有最终结算才会上链。 ### 通道生命周期 ``` stateDiagram-v2 [*] --> Proposed : Alice calls open_channel Proposed --> Open : Bob co-signs\nFunds locked on-chain Open --> Open : Off-chain state updates\nsigned ZK proofs exchanged peer-to-peer\nzero on-chain footprint Open --> Closing : close_channel(final_state_proof) Closing --> Closed : Cooperative close\nboth parties sign\nfunds released instantly Open --> Disputed : dispute(stale_state, proof) Disputed --> Disputed : Counterparty submits\nnewer state during challenge period Disputed --> Closed : Challenge period expires\nlatest valid state enforced Closed --> [*] : Encrypted balances returned to pool ``` ### 链下状态更新协议 ``` sequenceDiagram actor Alice actor Bob participant CH as channel_manager participant VERIFIER as groth16_verifier Note over Alice,Bob: Channel open — all updates are peer-to-peer, no chain activity loop Each payment (unlimited frequency) Alice->>Alice: compute new_state (balance_A minus amount, balance_B plus amount) Alice->>Alice: generate ZK proof of valid transition Alice->>Bob: new_state_commitment + proof + Alice_signature Bob->>Bob: verify proof locally via WASM Bob->>Alice: Bob_signature on new_state Note over Alice,Bob: Both hold co-signed state N+1 end Note over Alice,VERIFIER: COOPERATIVE CLOSE Alice->>Bob: propose_close(final_state) Bob->>Alice: co-sign final_state Alice->>CH: close_channel(final_state, proof, both_signatures) CH->>VERIFIER: verify_proof VERIFIER-->>CH: valid CH->>CH: release funds to encrypted pool balances ``` ## 私密流式支付 ``` sequenceDiagram actor Employer actor Employee participant SDK participant WASM participant STREAM as stream_manager participant VERIFIER as groth16_verifier participant POOL as pool_contract Note over Employer,POOL: OPEN STREAM Employer->>SDK: open_stream(to=Employee, rate=0.001 XLM/sec, duration=30days) SDK->>SDK: rate_commitment = Poseidon(rate, salt, pk_employee) SDK->>SDK: lock_amount = rate x duration SDK->>STREAM: open_stream(rate_commitment, lock_amount, pk_employee) STREAM->>POOL: lock(lock_amount) STREAM->>STREAM: store stream_note Note over Employer,POOL: EMPLOYEE CLAIMS VESTED AMOUNT Employee->>SDK: claim_stream(stream_note, claim_amount=86.4 XLM) SDK->>WASM: generate_proof(sk_employee, rate, start_time, now, claim_amount) Note right of WASM: Proves claim_amount is lte rate x elapsed\nProves ownership of stream_note\nReveals nothing else WASM-->>SDK: proof, nullifier SDK->>STREAM: claim(proof, nullifier, claim_amount) STREAM->>VERIFIER: verify_proof VERIFIER-->>STREAM: valid STREAM->>POOL: move claim_amount to employee encrypted balance ``` ## 依赖项 ### Rust 工作空间 `Cargo.toml` ``` [workspace] members = [ "contracts/pool_contract", "contracts/groth16_verifier", "contracts/asp_registry", "contracts/stream_manager", "contracts/memo_vault", "contracts/channel_manager", ] [workspace.dependencies] soroban-sdk = { version = "21.0.0", features = ["testutils"] } soroban-token-sdk = "21.0.0" serde = { version = "1.0", default-features = false, features = ["derive"] } serde_json = { version = "1.0", default-features = false } sha2 = { version = "0.10", default-features = false } ark-bn254 = { version = "0.4", default-features = false } ark-groth16 = { version = "0.4", default-features = false } ark-serialize = { version = "0.4", default-features = false } ``` ### 根目录 `package.json` ``` { "name": "stellar-encrypted-pay", "workspaces": ["sdk", "frontend"], "devDependencies": { "circom": "^2.1.8", "snarkjs": "^0.7.4", "typescript": "^5.3.0", "ts-node": "^10.9.0", "vitest": "^1.0.0" }, "dependencies": { "@stellar/stellar-sdk": "^12.0.0", "@stellar/stellar-base": "^12.0.0", "ffjavascript": "^0.3.0", "circomlibjs": "^0.1.7", "big.js": "^6.2.1" } } ``` ### 系统工具 | 工具 | 版本 | 用途 | 安装 | |---|---|---|---| | Rust | ≥ 1.75.0 | Soroban 合约编译 | `rustup update` | | Soroban CLI | ≥ 21.0.0 | 合约部署和调用 | `cargo install --locked soroban-cli` | | Node.js | ≥ 20.0.0 | SDK 和电路工具链 | [nodejs.org](https://nodejs.org) | | npm | ≥ 10.0.0 | 包管理 | 随 Node 捆绑 | | circom | ≥ 2.1.8 | ZK 电路编译器 | `npm install -g circom` | | snarkjs | ≥ 0.7.4 | 证明生成和设置 | `npm install -g snarkjs` | | circom2soroban | latest | 将电路转换为 Soroban Rust | `cargo install circom2soroban` | ## 环境设置 ### 1. Rust 和 Soroban CLI ``` # 安装 Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env # 添加 wasm32 目标(Soroban 合约编译所必需) rustup target add wasm32-unknown-unknown # 安装 Soroban CLI cargo install --locked soroban-cli # 验证 soroban --version ``` ### 2. Node.js 工具链 ``` # 通过 nvm 安装 Node.js(推荐) curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash nvm install 20 nvm use 20 # 安装全局 ZK 工具 npm install -g circom snarkjs # 验证 circom --version snarkjs --version ``` ### 3. circom2soroban ``` # 安装 SDF 电路桥接工具 cargo install circom2soroban # 验证 circom2soroban --help ``` ### 4. 环境变量 将 `.env.example` 复制为 `.env` 并填写您的值: ``` cp .env.example .env ``` ``` # .env # Stellar 网络 STELLAR_NETWORK=testnet STELLAR_RPC_URL=https://soroban-testnet.stellar.org STELLAR_NETWORK_PASSPHRASE="Test SDF Network ; September 2015" # 对于 mainnet 使用: # STELLAR_RPC_URL=https://soroban-mainnet.stellar.org # STELLAR_NETWORK_PASSPHRASE="Public Global Stellar Network ; September 2015" # 部署者密钥对(使用以下命令生成:soroban keys generate deployer) DEPLOYER_SECRET_KEY=S... # 已部署的合约 ID(部署后填充) POOL_CONTRACT_ID= VERIFIER_CONTRACT_ID= ASP_CONTRACT_ID= STREAM_CONTRACT_ID= MEMO_VAULT_CONTRACT_ID= CHANNEL_CONTRACT_ID= # 要包装的 Token(testnet 上的 USDC) TOKEN_CONTRACT_ID=CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA # Powers-of-Tau 仪式文件路径 PTAU_FILE=./circuits/setup/pot18_final.ptau ``` ## 安装 ``` # 1. 克隆仓库 git clone https://github.com/your-org/stellar-encrypted-pay.git cd stellar-encrypted-pay # 2. 安装所有 Node.js 依赖(SDK + 前端) npm install # 3. 构建 Soroban 合约 cargo build --release --target wasm32-unknown-unknown # 4. 下载 Powers-of-Tau 仪式文件(Groth16 可信设置) # 这是一次性约 72MB 的现有仪式下载 mkdir -p circuits/setup curl -L https://hermez.s3-eu-west-1.amazonaws.com/powersOfTau28_hez_final_18.ptau \ -o circuits/setup/pot18_final.ptau # 5. 编译所有 Circom 电路并生成证明密钥 chmod +x scripts/setup/compile_circuits.sh ./scripts/setup/compile_circuits.sh # 6. 从电路输出生成 Soroban 验证器 Rust chmod +x scripts/generate_verifiers.sh ./scripts/generate_verifiers.sh # 7. 构建 TypeScript SDK cd sdk && npm run build && cd .. ``` ### `compile_circuits.sh` 的作用 ``` #!/bin/bash # scripts/setup/compile_circuits.sh set -e CIRCUITS=(transfer deposit withdraw stream_open stream_claim channel_open channel_update) for circuit in "${CIRCUITS[@]}"; do echo "Compiling $circuit..." # Compile circuit to R1CS and WASM circom circuits/$circuit/$circuit.circom \ --r1cs --wasm --sym \ -o circuits/build/$circuit/ # Generate Groth16 proving and verification keys snarkjs groth16 setup \ circuits/build/$circuit/$circuit.r1cs \ circuits/setup/pot18_final.ptau \ circuits/build/$circuit/${circuit}_final.zkey # Export verification key as JSON snarkjs zkey export verificationkey \ circuits/build/$circuit/${circuit}_final.zkey \ circuits/build/$circuit/verification_key.json echo " $circuit done" done ``` ### `generate_verifiers.sh` 的作用 ``` #!/bin/bash # scripts/generate_verifiers.sh set -e CIRCUITS=(transfer deposit withdraw stream_open stream_claim channel_open channel_update) for circuit in "${CIRCUITS[@]}"; do circom2soroban vk circuits/build/$circuit/verification_key.json \ > contracts/groth16_verifier/src/vk_${circuit}.rs echo " vk_${circuit}.rs generated" done ``` ## 运行项目 ### 启动本地 Stellar 节点 ``` # 运行支持 Soroban 的 Stellar Quickstart docker run --rm -it \ -p 8000:8000 \ --name stellar \ stellar/quickstart:latest \ --local --enable-soroban-rpc # 为本地环境配置 Soroban CLI soroban config network add local \ --rpc-url http://localhost:8000/soroban/rpc \ --network-passphrase "Standalone Network ; February 2017" ``` ### 部署合约 ``` # 生成部署者密钥对并为其注资 soroban keys generate deployer --network local soroban keys fund deployer --network local # 部署所有合约(先部署验证器 —— pool 依赖于它) ./scripts/deploy/deploy_testnet.sh # 将输出的合约 ID 复制到你的 .env 文件中 ``` ### 在监视模式下运行 SDK ``` cd sdk npm run dev ``` ### 运行前端 ``` cd frontend npm run dev # 在 http://localhost:5173 打开 ``` ### 并发运行所有内容 ``` # 从项目根目录 npm run dev # 启动:Stellar 本地节点 + SDK 监视器 + 前端开发服务器 ``` ## 测试 ### 合约单元测试 ``` # 所有合约 cargo test # 特定合约 cargo test -p pool_contract cargo test -p groth16_verifier cargo test -p stream_manager cargo test -p channel_manager ``` ### 电路测试(生成并验证证明) ``` cd circuits/transfer # 生成 witness node generate_witness.js transfer_js/transfer.wasm input.json witness.wtns # 生成证明 snarkjs groth16 prove \ ../build/transfer/transfer_final.zkey witness.wtns \ proof.json public.json # 验证证明 snarkjs groth16 verify \ ../build/transfer/verification_key.json public.json proof.json ``` ### SDK 测试 ``` cd sdk npm test # 运行 Vitest —— 涵盖密钥生成、证明构建、tx 构建 ``` ### 端到端集成测试 ``` # 需要本地 Stellar 节点运行 npm run test:e2e # 涵盖: # deposit → transfer → withdraw 循环 # open_stream → claim_stream 循环 # open_channel → update states → cooperative close 循环 # dispute → challenge period → resolve 循环 ``` ## 部署 ### 测试网 ``` # 通过 Friendbot 为部署者注资 soroban keys fund deployer --network testnet # 部署 ./scripts/deploy/deploy_testnet.sh # 验证 pool 是否在线 soroban contract invoke \ --id $POOL_CONTRACT_ID \ --network testnet \ -- version ``` ### 主网 ``` # Protocol 25 自 2026 年 1 月 22 日起在 Mainnet 上线 # 确保部署者有足够的 XLM 用于支付费用 # 首先对所有合约和电路进行正式的安全审计 ./scripts/deploy/deploy_mainnet.sh ``` ## SDK 使用 ### 初始化 ``` import { StellarEncryptedPay } from "@stellar-encrypted-pay/sdk"; const sep = new StellarEncryptedPay({ network: "testnet", poolContractId: process.env.POOL_CONTRACT_ID, verifierContractId: process.env.VERIFIER_CONTRACT_ID, streamContractId: process.env.STREAM_CONTRACT_ID, channelContractId: process.env.CHANNEL_CONTRACT_ID, }); // Generate a privacy keypair (separate from your Stellar keypair) const privacyKey = await sep.keys.generate(); // Register your public key on-chain (one-time per wallet) await sep.keys.register(stellarKeypair, privacyKey.publicKey); ``` ### 存款 ``` const receipt = await sep.deposit({ tokenId: "CBIELTK6...", amount: "100", senderKeypair: stellarKeypair, privacyKey, }); // receipt.commitment — your encrypted balance handle ``` ### 带加密备注的私密转账 ``` await sep.transfer({ to: recipientPublicKey, amount: "40", memo: "Invoice #2024-Q1", // encrypted — only recipient can read commitment: receipt.commitment, privacyKey, senderKeypair: stellarKeypair, }); ``` ### 开启支付流 ``` // Employer streams salary at 0.001 XLM per second for 30 days const stream = await sep.stream.open({ to: employeePrivacyKey, ratePerSecond: "0.001", durationSeconds: 30 * 24 * 60 * 60, tokenId: "CBIELTK6...", senderKeypair: stellarKeypair, privacyKey, }); // Employee claims vested amount at any time await sep.stream.claim({ streamNote: stream.note, privacyKey: employeePrivacyKey, recipientKeypair: employeeStellarKeypair, }); ``` ### 开启私密支付通道 ``` // Open a channel with a business counterparty const channel = await sep.channel.open({ counterpartyPublicKey: partnerPrivacyKey, myDeposit: "1000", counterpartyDeposit: "1000", tokenId: "CBIELTK6...", myKeypair: stellarKeypair, privacyKey, }); // Make payments off-chain — zero on-chain footprint const updatedState = await sep.channel.update({ channel, payAmount: "15", privacyKey, }); // Cooperatively close — one on-chain transaction settles everything await sep.channel.close({ channel, finalState: updatedState, myKeypair: stellarKeypair, privacyKey, }); ``` ## 功能路线图 ``` gantt title Stellar-EncryptedPay — Development Roadmap dateFormat YYYY-MM section v1.0 Core Protocol Pool contract deposit transfer withdraw :2026-04, 6w Groth16 verifier contract :2026-04, 4w SEP-41 wrapper wrap and unwrap :2026-05, 3w Encrypted memos :2026-05, 3w Selective disclosure proofs :2026-05, 3w TypeScript SDK v1 :2026-05, 5w Testnet deployment and audit :2026-06, 3w section v1.1 Differentiation Private streaming payments :2026-07, 5w Stealth address system :2026-07, 4w Encrypted escrow with time-locks :2026-08, 4w Private invoices and payment requests :2026-08, 3w Developer docs and SDK v1.1 release :2026-09, 2w section v1.2 Vertical Products Private payroll module :2026-10, 4w Proof-of-payment NFT receipts :2026-10, 3w Scheduled recurring transfers :2026-11, 3w Private split payments :2026-11, 3w section v2.0 Infrastructure Private payment channels :2026-12, 8w ZK identity and credential layer :2027-02, 8w Private DEX dark pool :2027-04, 10w Cross-chain private bridge :2027-06, 10w ``` ## 贡献 欢迎贡献。在开始重要工作之前,请先提出 issue。 ``` # Fork 并克隆 git clone https://github.com/your-org/stellar-encrypted-pay.git # 创建功能分支 git checkout -b feature/your-feature-name # 提交前运行测试 cargo test && npm test # 针对 main 提交 PR ``` 代码标准:Rust 合约必须通过 `cargo clippy` 且无警告。TypeScript 必须通过 `tsc --noEmit`。所有新的 ZK 电路必须包含单元测试和记录在案的示例输入/输出。 ## 许可证 MIT — 见 [LICENSE](LICENSE)
标签:BN254, DeFi, Groth16, Soroban, Stellar, Web3, X-Ray, ZKP, 加密支付, 区块链, 协议25, 可审计性, 可视化界面, 支付通道, 智能合约, 机密交易, 椭圆曲线密码学, 流支付, 监管合规, 网络安全, 隐私保护, 隐私支付协议, 零知识证明