Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions DESIGN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Laurelin — Design Decisions

This document explains the key design choices and the tradeoffs behind them. The README covers *what* the system does; this covers *why* it works the way it does.

---

## Proof system: Groth16 over BN254

**Why Groth16?**
Groth16 produces constant-size proofs (192 bytes: A, B, C) regardless of circuit complexity, and verification is a fixed-cost operation: one linear combination over the public inputs followed by 3–4 pairing checks. This makes on-chain verification cost predictable and bounded.

**Why BN254?**
Solana has a native precompile (`alt_bn128`) for BN254 point operations and pairings. Without it, verifying a Groth16 proof on-chain would be impossible within any reasonable compute budget. BN254 is the only curve with this first-class support on Solana.

**The compute budget constraint**
The ring transfer instruction hits 1.4M compute units — the transaction maximum. This is driven primarily by the Groth16 linear combination over 129 public inputs (one G1 scalar mul per input) plus the pairings. The large public input count is inherent to the DEROHE design: all four accounts' old and new ciphertexts must be public so the on-chain program can update state. If the ring size were doubled from 2 to 4, the instruction would exceed the budget entirely.

---

## Why gnark for the circuit?

gnark is the best-maintained Go library for Groth16 over BN254. The prover runs off-chain as a subprocess (the Go binary `laurelin-prover`), called by the Rust wallet client via JSON over stdin/stdout. This keeps the Rust wallet thin and avoids pulling gnark's large dependency tree into the Rust build.

---

## Emulated fields: the cost of same-curve construction

Groth16 over BN254 means the constraint system (R1CS) does all arithmetic natively over BN254's **scalar field Fr**. This is the "free" field inside the circuit.

BN254 G1 points have coordinates in BN254's **base field Fp**, which is a different prime from Fr. Since the circuit can only do arithmetic natively over Fr, any operation involving point coordinates (additions, scalar multiplications, equality checks) must simulate Fp arithmetic using Fr operations — representing each Fp element as four 64-bit Fr limbs and re-implementing field multiplication and reduction from scratch. This is called *emulated arithmetic* and is the dominant cost of the 30-second proving time.

The root cause is that we use BN254 for both the proof system (outer curve) and the ElGamal encryption (inner curve). Using a different outer curve whose scalar field equalled BN254's base field would eliminate the emulation overhead — this is the idea behind *curve cycles* like Pallas/Vesta. But BN254 is the only curve with native Solana precompile support, so there is no viable alternative outer curve for this deployment target.

---

## Balance range: 32-bit (max ~4.3 SOL)

All balance and amount values are range-checked to 32 bits in the circuit (`ToBinary(x, 32)`). This caps the maximum confidential balance at 2³² lamports ≈ 4.3 SOL.

This is an intentional tradeoff: extending to 64 bits would roughly double proving time for the three scalar multiplications that use balance-derived scalars (`B×G`, `V×G`, `(B−V)×G`). At 30 seconds per proof, doubling even part of that cost is significant.

The BSGS decryption table (used client-side to recover balances from ciphertexts) also scales as O(√range): the current 2³² range uses 2¹⁶ baby steps (~2s build time). Moving to 2⁴⁰ would require 2²⁰ steps (~32s) and is not viable without caching or a redesigned algorithm.

The 32-bit limit is acceptable for the current use case. When it needs to change, the right approach is:
1. Extend the circuit range checks to the target bit width
2. Cache the BSGS table to disk (it is deterministic; build once, load on subsequent runs)
3. Re-run trusted setup (circuit change requires new proving/verification keys and program redeployment)

---

## Ring size: 2+2

The transfer ring uses 2 senders and 2 receivers. This is the minimum ring size that provides any anonymity (the real sender is hidden among 2 candidates, as is the real receiver).

Ring size is constrained from above by the compute budget: each additional ring member adds 8 more G1 points to the public input set (16 field elements × 4 limbs = more scalar muls in the linear combination) and 2 more constraints in the circuit. At ring size 2, we are already at the compute budget ceiling.

---

## ElGamal encryption and the DEROHE protocol

Balances are stored as ElGamal ciphertexts under the user's BN254 public key:

```
C1 = r × G
C2 = r × pk + v × G
```

Transfers use *homomorphic addition*: the receiver's balance ciphertext is updated by adding a delta ciphertext (encrypting the transfer amount) component-wise. The sender's new ciphertext re-encrypts the reduced balance. Neither the amount nor the identities of sender or receiver are revealed on-chain.

This follows the [DEROHE](https://github.com/deroproject/derohe) protocol, adapted from its original Monero-style chain to Solana's account model.

**Why not commit-reveal or Tornado-style nullifiers?**
Nullifier schemes require storing a growing set of spent commitments on-chain. The DEROHE approach instead updates ciphertext state in place, keeping per-account storage constant at 192 bytes regardless of transaction history.

---

## Keypair design: two separate keys per wallet

Each wallet holds two independent keypairs:

- **Solana keypair** (Ed25519): signs transactions, pays fees, holds native SOL
- **Laurelin keypair** (BN254): the ElGamal key used for confidential balance encryption

These are intentionally unlinked. The Laurelin public key (the X coordinate of `sk × G`) is the identifier in the confidential system; the Solana public key is the identifier in the base layer. This means on-chain observers cannot correlate a user's confidential activity with their Solana address.

The Solana public key is stored unencrypted in the wallet file (for read-only operations like checking SOL balance and transaction history). The Ed25519 seed and BN254 scalar are each encrypted separately with AES-256-GCM under an Argon2id-derived key.

---

## SOL backing: vault PDA

Native SOL deposited into the confidential system is held in a single program-derived vault account (`seeds = [b"vault"]`). All deposits add to the vault; all withdrawals subtract from it. The on-chain program enforces that withdrawals cannot exceed the vault balance.

This is a simple custodial model. The vault holds the aggregate of all users' confidential balances, not individual allocations — individual balances are tracked only through the ciphertext state.

---

## BSGS decryption

Recovering a balance from a ciphertext requires solving the discrete logarithm: given `v × G`, find `v`. This is done with baby-step giant-step (BSGS) with M = 2¹⁶, covering the range [0, 2³²) in O(M) time and space. The table is built once per process invocation and reused for all decrypt operations in that session.

Pollard's kangaroo algorithm has the same O(√N) asymptotic cost and lower memory usage, but offers no wall-clock advantage over BSGS for this range — both algorithms pay the same per-step cost (a BN254 affine point conversion). The primary benefit of kangaroo would be working over arbitrary ranges without a fixed precomputed table, which is only relevant if the balance range is extended.
71 changes: 71 additions & 0 deletions SECURITY_AUDIT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Security Audit — Laurelin

Conducted 2026-03-29, pre-mainnet hardening pass.

---

## Must Verify (Open Questions)

### C1. Ring transfer sender authorization in-circuit

Does the `transfer` circuit include a constraint proving the prover knows `sk` for one of the sender ring members? If not, anyone could construct a valid-looking proof without owning an account.

The ZK proof is intended to be the authorization mechanism — a valid proof implies knowledge of the secret key. But this needs explicit verification in the circuit code before it can be relied upon.

**Response (2026-03-30):** Verified. `selectG1(api, fpField, cond, a, b)` correctly returns `a` when `cond==0` and `b` when `cond==1`. The suspicious comment was documenting gnark's counterintuitive true-value-first `Select` API, not a bug — it has been updated to describe `selectG1`'s own semantics. Step 6 (`SenderPk[senderIdx] = Sk * G`) correctly enforces that the prover knows `sk` for the selected ring member. **No issue.**

### C2. Withdraw destination not bound to signer

The on-chain withdraw handler may allow an arbitrary destination account to be passed. If the program does not verify that destination == signer's Solana pubkey, a malicious RPC or MITM could substitute a different destination address.

**Response (2026-03-30):** False positive. Solana transactions are signed with the payer's Ed25519 key over the entire instruction including all account addresses — a MITM cannot alter the destination without invalidating the signature. The legitimate concern (a compromised wallet client constructing the instruction with a wrong destination before signing) is out of scope for on-chain validation. **No issue.**

---

## Real Issues to Fix

### H1. 32-bit balance cap (~4.3 SOL maximum per account)

ZK circuits range-check amounts with `ToBinary(x, 32)`, capping the maximum confidential balance at 2^32 lamports ≈ **4.3 SOL**. Depositing more than this will corrupt the balance. Must be extended to at least 40–50 bits before mainnet.

**Affected files:** `circuit/transfer.go`, `circuit/deposit.go`, `circuit/withdraw.go`

**Response (2026-04-03):** Accepted as a known limitation for initial launch. 4.3 SOL (~$400) is appropriate for the current use case. The wallet now validates all amounts against `MAX_CONFIDENTIAL_LAMPORTS` (2³² − 1) before attempting to prove, returning a clear error message rather than failing inside the prover. If this check were somehow bypassed, the ZK circuit itself enforces the 32-bit range constraint — a proof for an out-of-range value cannot be generated, making silent balance corruption impossible. Extending the range requires: (1) updating `ToBinary` bit width in all three circuits, (2) caching the BSGS table to disk to keep decryption fast, (3) re-running trusted setup and redeploying the program. Will revisit if users hit the limit.

### L1. Wallet file permissions not enforced

`~/.laurelin/wallet.json` is written without explicitly setting `0600` permissions. On systems with a permissive umask, the file may be group- or world-readable.

**Fix:** After writing in `wallet/src/wallet.rs`:
```rust
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
```

**Response (2026-04-03):** Fixed in `write_wallet()` in `wallet/src/wallet.rs`. **Resolved.**

### L2. Use `OsRng` for cryptographic key material in wallet

`rand::thread_rng()` is used to generate Argon2 salts and AES-GCM nonces in `wallet/src/wallet.rs`. While `thread_rng()` is seeded from OS entropy and is cryptographically acceptable, explicitly using `rand::rngs::OsRng` makes the intent clear and removes any ambiguity.

**Response (2026-04-03):** Switched to `rand::rngs::OsRng` in `aes_encrypt()`. **Resolved.**

---

## Likely False Positives

These were flagged during review but appear safe by design:

- **Proof replay:** Each operation updates the on-chain ciphertext state. A replayed proof will fail verification because the old ciphertext public inputs no longer match the account's current state.
- **Deposit authorization:** Any address can deposit into a PDA without the owner's signature. This is intentional — same semantics as receiving SOL.
- **Vault PDA ownership:** The vault is a program-derived address. It cannot be pre-empted by an attacker.

---

## Remediation Order

1. ~~Verify `transfer` circuit enforces prover knowledge of sender `sk`~~ — **C1 resolved**
2. ~~Verify / fix withdraw destination validation on-chain~~ — **C2 resolved (false positive)**
3. ~~Extend balance range checks from 32-bit to 40+ bits~~ — **H1 deferred (accepted limitation)**
4. ~~Enforce `0600` permissions on wallet file~~ — **L1 resolved**
5. ~~Switch salt/nonce generation to `OsRng`~~ — **L2 resolved**
2 changes: 1 addition & 1 deletion circuit/transfer.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ func (c *RingTransferCircuit) Define(api frontend.API) error {
bmvScalar := scalarField.FromBits(bmvBits...)

// ── 5. Select real / decoy sender points ───────────────────────────────
// Select(cond, b, a): returns a when cond==0, b when cond==1.
// selectG1(cond, a, b): returns a when cond==0, b when cond==1.
realSenderPk := selectG1(api, fpField, c.SenderIdx, c.SenderPk0, c.SenderPk1)
decoySenderPk := selectG1(api, fpField, c.SenderIdx, c.SenderPk1, c.SenderPk0)
realSenderOldC1 := selectG1(api, fpField, c.SenderIdx, c.SenderOldC10, c.SenderOldC11)
Expand Down
5 changes: 5 additions & 0 deletions wallet/src/bn254.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ use ark_ec::{AffineRepr, CurveGroup};
use ark_ff::{BigInteger, PrimeField};
use ark_std::UniformRand;

/// Maximum confidential balance / amount: 2^32 − 1 lamports (~4.3 SOL).
/// The ZK circuits range-check all values to 32 bits; exceeding this will
/// cause the prover to fail. Commands validate against this before proving.
pub const MAX_CONFIDENTIAL_LAMPORTS: u64 = u32::MAX as u64;

// ── Serialisation ─────────────────────────────────────────────────────────────

/// Serialise a Fq element as a 32-byte big-endian array.
Expand Down
8 changes: 7 additions & 1 deletion wallet/src/commands/deposit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use solana_sdk::{pubkey::Pubkey, signature::Signer};

use crate::{
bn254::{elgamal_encrypt, g1_to_bytes},
bn254::{elgamal_encrypt, g1_to_bytes, MAX_CONFIDENTIAL_LAMPORTS},
config::ResolvedConfig,
instructions::{deposit, set_compute_unit_limit, vault_pda},
prover::prove_deposit,
Expand All @@ -12,6 +12,12 @@ use crate::{
};

pub fn run(wallet: &Wallet, cfg: &ResolvedConfig, lamports: u64) -> anyhow::Result<()> {
anyhow::ensure!(
lamports <= MAX_CONFIDENTIAL_LAMPORTS,
"amount {} lamports exceeds the maximum confidential balance ({} lamports, ~4.3 SOL)",
lamports,
MAX_CONFIDENTIAL_LAMPORTS,
);
let client = new_client(&cfg.rpc_url);
let kp = wallet.solana_keypair()?;
let program_id: Pubkey = cfg.program_id.parse()?;
Expand Down
9 changes: 8 additions & 1 deletion wallet/src/commands/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use ark_std::UniformRand;
use solana_sdk::pubkey::Pubkey;

use crate::{
bn254::{bsgs_decrypt, g1_to_bytes, generator, point_add, scalar_mul, BsgsTable},
bn254::{bsgs_decrypt, g1_to_bytes, generator, point_add, scalar_mul, BsgsTable, MAX_CONFIDENTIAL_LAMPORTS},
config::ResolvedConfig,
instructions::{ring_transfer, set_compute_unit_limit},
prover::prove_transfer,
Expand All @@ -31,6 +31,13 @@ pub fn run(
let my_pda = wallet.pda(&program_id);
let sk = wallet.laurelin_sk_fr();

anyhow::ensure!(
lamports <= MAX_CONFIDENTIAL_LAMPORTS,
"amount {} lamports exceeds the maximum confidential balance ({} lamports, ~4.3 SOL)",
lamports,
MAX_CONFIDENTIAL_LAMPORTS,
);

// Parse receiver Laurelin pubkey (base58-encoded 32-byte X coordinate)
let recv_pk_x: [u8; 32] = bs58::decode(to)
.into_vec()
Expand Down
8 changes: 7 additions & 1 deletion wallet/src/commands/withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use ark_std::UniformRand;
use solana_sdk::{pubkey::Pubkey, signature::Signer};

use crate::{
bn254::{bsgs_decrypt, g1_to_bytes, generator, point_add, scalar_mul, BsgsTable},
bn254::{bsgs_decrypt, g1_to_bytes, generator, point_add, scalar_mul, BsgsTable, MAX_CONFIDENTIAL_LAMPORTS},
config::ResolvedConfig,
instructions::{set_compute_unit_limit, vault_pda, withdraw},
prover::prove_withdraw,
Expand All @@ -14,6 +14,12 @@ use crate::{
};

pub fn run(wallet: &Wallet, cfg: &ResolvedConfig, lamports: u64) -> anyhow::Result<()> {
anyhow::ensure!(
lamports <= MAX_CONFIDENTIAL_LAMPORTS,
"amount {} lamports exceeds the maximum confidential balance ({} lamports, ~4.3 SOL)",
lamports,
MAX_CONFIDENTIAL_LAMPORTS,
);
let client = new_client(&cfg.rpc_url);
let kp = wallet.solana_keypair()?;
let program_id: Pubkey = cfg.program_id.parse()?;
Expand Down
14 changes: 8 additions & 6 deletions wallet/src/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
//! All in-memory key material lives in `Zeroizing` wrappers and is
//! overwritten with zeros on drop.

use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use aes_gcm::{
Expand All @@ -24,6 +25,7 @@ use anyhow::Context;
use argon2::{Algorithm, Argon2, Params, Version};
use ark_bn254::{Fr, G1Affine};
use rand::RngCore;
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};
use solana_sdk::{
pubkey::Pubkey,
Expand Down Expand Up @@ -109,14 +111,12 @@ fn aes_encrypt(
password: &[u8],
solana_pubkey: &Pubkey,
) -> anyhow::Result<WalletV2> {
let mut rng = rand::thread_rng();

let mut salt = [0u8; ARGON2_SALT_LEN];
let mut solana_nonce_bytes = [0u8; AES_NONCE_LEN];
let mut laurelin_nonce_bytes = [0u8; AES_NONCE_LEN];
rng.fill_bytes(&mut salt);
rng.fill_bytes(&mut solana_nonce_bytes);
rng.fill_bytes(&mut laurelin_nonce_bytes);
OsRng.fill_bytes(&mut salt);
OsRng.fill_bytes(&mut solana_nonce_bytes);
OsRng.fill_bytes(&mut laurelin_nonce_bytes);

let key = argon2_derive(password, &salt)?;
let cipher = Aes256Gcm::new_from_slice(&key[..])
Expand Down Expand Up @@ -335,7 +335,9 @@ fn write_wallet(path: &Path, json: &str) -> anyhow::Result<()> {
std::fs::create_dir_all(parent)
.with_context(|| format!("create dir {}", parent.display()))?;
}
std::fs::write(path, json).with_context(|| format!("write wallet {}", path.display()))
std::fs::write(path, json).with_context(|| format!("write wallet {}", path.display()))?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
.with_context(|| format!("set permissions on {}", path.display()))
}

/// Return the default wallet file path: ~/.laurelin/wallet.json.
Expand Down
Loading