@veilo/sdk-core 0.1.17 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1257 -272
- package/dist/cjs/client.d.ts +407 -0
- package/dist/cjs/client.js +914 -0
- package/dist/cjs/config.d.ts +82 -0
- package/dist/cjs/config.js +57 -0
- package/dist/cjs/events.d.ts +77 -0
- package/dist/cjs/events.js +167 -0
- package/dist/cjs/idl/privacy_pool.json +10313 -0
- package/dist/cjs/index.d.ts +13 -0
- package/dist/cjs/index.js +57 -0
- package/dist/cjs/merkle.d.ts +64 -0
- package/dist/cjs/merkle.js +133 -0
- package/dist/cjs/poseidon.d.ts +29 -0
- package/dist/cjs/poseidon.js +100 -0
- package/dist/cjs/program.d.ts +26 -0
- package/dist/cjs/program.js +38 -0
- package/dist/cjs/proof.d.ts +183 -0
- package/dist/cjs/proof.js +292 -0
- package/dist/cjs/prover.d.ts +54 -0
- package/dist/cjs/prover.js +112 -0
- package/dist/cjs/relayer.d.ts +295 -0
- package/dist/cjs/relayer.js +246 -0
- package/dist/cjs/retry.d.ts +32 -0
- package/dist/cjs/retry.js +75 -0
- package/dist/cjs/utxo.d.ts +215 -0
- package/dist/cjs/utxo.js +394 -0
- package/dist/esm/client.js +887 -0
- package/dist/esm/config.js +51 -0
- package/dist/esm/events.js +129 -0
- package/dist/esm/idl/privacy_pool.json +10313 -0
- package/dist/esm/index.js +22 -0
- package/dist/esm/merkle.js +129 -0
- package/dist/esm/poseidon.js +87 -0
- package/dist/esm/program.js +31 -0
- package/dist/esm/proof.js +281 -0
- package/dist/esm/prover.js +75 -0
- package/dist/esm/relayer.js +238 -0
- package/dist/esm/retry.js +71 -0
- package/dist/esm/utxo.js +372 -0
- package/package.json +47 -11
- package/src/client.ts +0 -352
- package/src/config.ts +0 -13
- package/src/index.ts +0 -6
- package/src/merkle.ts +0 -178
- package/src/note.ts +0 -193
- package/src/poseidon.ts +0 -62
- package/src/proof.ts +0 -170
- package/test/script.js +0 -0
- package/test-tsconfig.json +0 -19
- package/tests/note.test.ts +0 -50
- package/tests/sdk.integration.test.ts +0 -210
- package/tsconfig.json +0 -18
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import nacl from "tweetnacl";
|
|
2
|
+
// =============================================================================
|
|
3
|
+
// Structured Error
|
|
4
|
+
// =============================================================================
|
|
5
|
+
/** Structured error thrown by VeiloRelayerClient on API failures. */
|
|
6
|
+
export class VeiloApiError extends Error {
|
|
7
|
+
constructor(code, message, status) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "VeiloApiError";
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.status = status;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
const DEFAULT_RETRY = {
|
|
15
|
+
maxRetries: 3,
|
|
16
|
+
baseDelayMs: 1000,
|
|
17
|
+
retryableStatuses: [429, 502, 503, 504],
|
|
18
|
+
};
|
|
19
|
+
// =============================================================================
|
|
20
|
+
// Base64 helpers (no dependency on tweetnacl-util)
|
|
21
|
+
// =============================================================================
|
|
22
|
+
function toBase64(bytes) {
|
|
23
|
+
if (typeof Buffer !== "undefined") {
|
|
24
|
+
return Buffer.from(bytes).toString("base64");
|
|
25
|
+
}
|
|
26
|
+
return btoa(String.fromCharCode(...bytes));
|
|
27
|
+
}
|
|
28
|
+
function fromBase64(str) {
|
|
29
|
+
if (typeof Buffer !== "undefined") {
|
|
30
|
+
return new Uint8Array(Buffer.from(str, "base64"));
|
|
31
|
+
}
|
|
32
|
+
const binary = atob(str);
|
|
33
|
+
const bytes = new Uint8Array(binary.length);
|
|
34
|
+
for (let i = 0; i < binary.length; i++)
|
|
35
|
+
bytes[i] = binary.charCodeAt(i);
|
|
36
|
+
return bytes;
|
|
37
|
+
}
|
|
38
|
+
// =============================================================================
|
|
39
|
+
// Encryption
|
|
40
|
+
// =============================================================================
|
|
41
|
+
/**
|
|
42
|
+
* Encrypt a JSON-serializable payload for the relayer using NaCl box.
|
|
43
|
+
* Layout: [ephemeralPubKey (32)] [nonce (24)] [ciphertext (...)]
|
|
44
|
+
*/
|
|
45
|
+
function encryptForRelayer(data, relayerPublicKey) {
|
|
46
|
+
const ephemeral = nacl.box.keyPair();
|
|
47
|
+
const message = new TextEncoder().encode(JSON.stringify(data));
|
|
48
|
+
const nonce = nacl.randomBytes(nacl.box.nonceLength);
|
|
49
|
+
const ciphertext = nacl.box(message, nonce, relayerPublicKey, ephemeral.secretKey);
|
|
50
|
+
const payload = new Uint8Array(ephemeral.publicKey.length + nonce.length + ciphertext.length);
|
|
51
|
+
payload.set(ephemeral.publicKey, 0);
|
|
52
|
+
payload.set(nonce, ephemeral.publicKey.length);
|
|
53
|
+
payload.set(ciphertext, ephemeral.publicKey.length + nonce.length);
|
|
54
|
+
return toBase64(payload);
|
|
55
|
+
}
|
|
56
|
+
// =============================================================================
|
|
57
|
+
// Relayer Client
|
|
58
|
+
// =============================================================================
|
|
59
|
+
/**
|
|
60
|
+
* HTTP client for the Veilo relayer API.
|
|
61
|
+
*
|
|
62
|
+
* Handles auth, notes, merkle, and encrypted transact endpoints with
|
|
63
|
+
* automatic retry on transient failures and NaCl box payload encryption.
|
|
64
|
+
*
|
|
65
|
+
* @example
|
|
66
|
+
* ```ts
|
|
67
|
+
* const client = new VeiloRelayerClient({
|
|
68
|
+
* relayerUrl: "https://relayer.veilo.io",
|
|
69
|
+
* apiKey: "your-api-key",
|
|
70
|
+
* relayerPublicKey: "<base64 NaCl public key>",
|
|
71
|
+
* });
|
|
72
|
+
* const root = await client.getMerkleRoot("So111...");
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export class VeiloRelayerClient {
|
|
76
|
+
constructor(config, retry) {
|
|
77
|
+
this.baseUrl = config.relayerUrl.replace(/\/+$/, "");
|
|
78
|
+
this.apiKey = config.apiKey;
|
|
79
|
+
this.relayerPubKey = fromBase64(config.relayerPublicKey);
|
|
80
|
+
this.authToken = config.authToken;
|
|
81
|
+
this.retry = { ...DEFAULT_RETRY, ...retry };
|
|
82
|
+
}
|
|
83
|
+
/** Update the auth token (e.g. after register/restore). */
|
|
84
|
+
setAuthToken(token) {
|
|
85
|
+
this.authToken = token;
|
|
86
|
+
}
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
// Internal helpers
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
headers(authenticated) {
|
|
91
|
+
const h = {
|
|
92
|
+
"Content-Type": "application/json",
|
|
93
|
+
"x-api-key": this.apiKey,
|
|
94
|
+
};
|
|
95
|
+
if (authenticated && this.authToken) {
|
|
96
|
+
h["Authorization"] = `Bearer ${this.authToken}`;
|
|
97
|
+
}
|
|
98
|
+
return h;
|
|
99
|
+
}
|
|
100
|
+
async request(method, path, opts = {}) {
|
|
101
|
+
const url = `${this.baseUrl}/api${path}`;
|
|
102
|
+
const { body, authenticated = false, retryable = true } = opts;
|
|
103
|
+
const maxAttempts = retryable ? this.retry.maxRetries + 1 : 1;
|
|
104
|
+
let lastError;
|
|
105
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
106
|
+
if (attempt > 0) {
|
|
107
|
+
const delay = this.retry.baseDelayMs * Math.pow(2, attempt - 1) +
|
|
108
|
+
Math.random() * 200;
|
|
109
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
110
|
+
}
|
|
111
|
+
let res;
|
|
112
|
+
try {
|
|
113
|
+
res = await fetch(url, {
|
|
114
|
+
method,
|
|
115
|
+
headers: this.headers(authenticated),
|
|
116
|
+
body: body != null ? JSON.stringify(body) : undefined,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
lastError = new VeiloApiError("NETWORK_ERROR", err.message || "Network request failed", 0);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const data = await res.json().catch(() => ({}));
|
|
124
|
+
if (res.ok && data.success !== false) {
|
|
125
|
+
return data;
|
|
126
|
+
}
|
|
127
|
+
lastError = new VeiloApiError(data.error || "UNKNOWN", data.message || data.error || `Request failed: ${res.status}`, res.status);
|
|
128
|
+
// Only retry on transient statuses
|
|
129
|
+
if (!this.retry.retryableStatuses.includes(res.status)) {
|
|
130
|
+
throw lastError;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
throw lastError;
|
|
134
|
+
}
|
|
135
|
+
encrypt(data) {
|
|
136
|
+
return encryptForRelayer({
|
|
137
|
+
...data,
|
|
138
|
+
timestamp: Date.now(),
|
|
139
|
+
nonce: toBase64(nacl.randomBytes(32)),
|
|
140
|
+
}, this.relayerPubKey);
|
|
141
|
+
}
|
|
142
|
+
// ---------------------------------------------------------------------------
|
|
143
|
+
// Auth
|
|
144
|
+
// ---------------------------------------------------------------------------
|
|
145
|
+
/** Request a signature challenge for wallet authentication. */
|
|
146
|
+
async getChallenge(walletPublicKey) {
|
|
147
|
+
return this.request("POST", "/auth/challenge", {
|
|
148
|
+
body: { walletPublicKey },
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/** Register a new account with a signed challenge. Returns a JWT auth token. */
|
|
152
|
+
async register(data) {
|
|
153
|
+
return this.request("POST", "/auth/register", { body: data });
|
|
154
|
+
}
|
|
155
|
+
/** Restore an existing account using a signed challenge. Returns a JWT auth token. */
|
|
156
|
+
async restore(data) {
|
|
157
|
+
return this.request("POST", "/auth/restore", { body: data });
|
|
158
|
+
}
|
|
159
|
+
/** Check whether a username is available for registration. */
|
|
160
|
+
async checkUsername(username) {
|
|
161
|
+
return this.request("GET", `/auth/checkUsername?username=${encodeURIComponent(username)}`);
|
|
162
|
+
}
|
|
163
|
+
/** Look up a user's Veilo public key by username or wallet public key. */
|
|
164
|
+
async getVeiloPublicKey(params) {
|
|
165
|
+
const query = "username" in params && params.username
|
|
166
|
+
? `username=${encodeURIComponent(params.username)}`
|
|
167
|
+
: `publicKey=${encodeURIComponent(params.publicKey)}`;
|
|
168
|
+
return this.request("GET", `/auth/veiloPublicKey?${query}`);
|
|
169
|
+
}
|
|
170
|
+
// ---------------------------------------------------------------------------
|
|
171
|
+
// Notes
|
|
172
|
+
// ---------------------------------------------------------------------------
|
|
173
|
+
/** Save an encrypted note to the relayer's database. */
|
|
174
|
+
async saveEncryptedNote(data) {
|
|
175
|
+
return this.request("POST", "/notes/save", { body: data });
|
|
176
|
+
}
|
|
177
|
+
/** Query encrypted notes for the authenticated user. Requires auth token. */
|
|
178
|
+
async queryEncryptedNotes(params = {}) {
|
|
179
|
+
return this.request("POST", "/notes/query", {
|
|
180
|
+
body: params,
|
|
181
|
+
authenticated: true,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
/** Delete all stored data for the authenticated user. Requires auth token. */
|
|
185
|
+
async deleteUserData() {
|
|
186
|
+
return this.request("POST", "/notes/delete", { authenticated: true });
|
|
187
|
+
}
|
|
188
|
+
// ---------------------------------------------------------------------------
|
|
189
|
+
// Merkle
|
|
190
|
+
// ---------------------------------------------------------------------------
|
|
191
|
+
/** Fetch the current Merkle root for a pool, optionally filtered by mint and tree ID. */
|
|
192
|
+
async getMerkleRoot(mintAddress, treeId) {
|
|
193
|
+
const params = new URLSearchParams();
|
|
194
|
+
if (mintAddress)
|
|
195
|
+
params.append("mintAddress", mintAddress);
|
|
196
|
+
if (treeId !== undefined)
|
|
197
|
+
params.append("treeId", treeId.toString());
|
|
198
|
+
const qs = params.toString();
|
|
199
|
+
return this.request("GET", `/merkle/root${qs ? `?${qs}` : ""}`);
|
|
200
|
+
}
|
|
201
|
+
/** Fetch the full Merkle tree (all leaves) for a pool. */
|
|
202
|
+
async getMerkleTree(mintAddress, treeId) {
|
|
203
|
+
const params = new URLSearchParams();
|
|
204
|
+
if (mintAddress)
|
|
205
|
+
params.append("mintAddress", mintAddress);
|
|
206
|
+
if (treeId !== undefined)
|
|
207
|
+
params.append("treeId", treeId.toString());
|
|
208
|
+
const qs = params.toString();
|
|
209
|
+
return this.request("GET", `/merkle/tree${qs ? `?${qs}` : ""}`);
|
|
210
|
+
}
|
|
211
|
+
// ---------------------------------------------------------------------------
|
|
212
|
+
// Transact (encrypted payloads)
|
|
213
|
+
// ---------------------------------------------------------------------------
|
|
214
|
+
/** Submit an encrypted withdrawal request to the relayer. Not retried on failure. */
|
|
215
|
+
async submitWithdraw(data) {
|
|
216
|
+
const encryptedPayload = this.encrypt(data);
|
|
217
|
+
return this.request("POST", "/transact/withdra", {
|
|
218
|
+
body: { encryptedPayload },
|
|
219
|
+
retryable: false,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
/** Submit an encrypted private transfer request. Not retried on failure. */
|
|
223
|
+
async submitPrivateTransfer(data) {
|
|
224
|
+
const encryptedPayload = this.encrypt(data);
|
|
225
|
+
return this.request("POST", "/transact/private-transfer", {
|
|
226
|
+
body: { encryptedPayload },
|
|
227
|
+
retryable: false,
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** Submit an encrypted private swap request. Not retried on failure. */
|
|
231
|
+
async submitPrivateSwap(data) {
|
|
232
|
+
const encryptedPayload = this.encrypt(data);
|
|
233
|
+
return this.request("POST", "/transact/private-swap", {
|
|
234
|
+
body: { encryptedPayload },
|
|
235
|
+
retryable: false,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// -----------------------------------------------------------------------------
|
|
2
|
+
// RPC Retry / Resilience
|
|
3
|
+
// -----------------------------------------------------------------------------
|
|
4
|
+
export const DEFAULT_RPC_RETRY = {
|
|
5
|
+
maxRetries: 3,
|
|
6
|
+
baseDelayMs: 1000,
|
|
7
|
+
maxDelayMs: 10000,
|
|
8
|
+
};
|
|
9
|
+
/** Error messages / patterns that indicate a transient RPC failure worth retrying. */
|
|
10
|
+
const RETRYABLE_PATTERNS = [
|
|
11
|
+
"blockhash not found",
|
|
12
|
+
"block height exceeded",
|
|
13
|
+
"blockhash already expired",
|
|
14
|
+
"node is behind",
|
|
15
|
+
"service unavailable",
|
|
16
|
+
"too many requests",
|
|
17
|
+
"429",
|
|
18
|
+
"502",
|
|
19
|
+
"503",
|
|
20
|
+
"504",
|
|
21
|
+
"timeout",
|
|
22
|
+
"timed out",
|
|
23
|
+
"econnreset",
|
|
24
|
+
"econnrefused",
|
|
25
|
+
"socket hang up",
|
|
26
|
+
"fetch failed",
|
|
27
|
+
];
|
|
28
|
+
function isRetryableError(error) {
|
|
29
|
+
const msg = (error instanceof Error ? error.message : String(error)).toLowerCase();
|
|
30
|
+
return RETRYABLE_PATTERNS.some((p) => msg.includes(p));
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Execute an async function with retries on transient RPC failures.
|
|
34
|
+
*
|
|
35
|
+
* Retries on: BlockhashNotFound, HTTP 429/502/503/504, timeouts, connection resets.
|
|
36
|
+
* Does NOT retry on: program errors (6xxx), signature verification failures, or other
|
|
37
|
+
* deterministic errors that would fail again.
|
|
38
|
+
*
|
|
39
|
+
* @param fn The async operation to execute
|
|
40
|
+
* @param policy Retry configuration (uses sensible defaults if omitted)
|
|
41
|
+
* @returns The result of the async operation
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* const txSig = await withRpcRetry(
|
|
46
|
+
* () => program.methods.transact(...).accounts({...}).signers([...]).rpc(),
|
|
47
|
+
* { maxRetries: 5 },
|
|
48
|
+
* );
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
export async function withRpcRetry(fn, policy) {
|
|
52
|
+
const { maxRetries, baseDelayMs, maxDelayMs } = {
|
|
53
|
+
...DEFAULT_RPC_RETRY,
|
|
54
|
+
...policy,
|
|
55
|
+
};
|
|
56
|
+
let lastError;
|
|
57
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
58
|
+
try {
|
|
59
|
+
return await fn();
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
lastError = error;
|
|
63
|
+
if (attempt >= maxRetries || !isRetryableError(error)) {
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
const delay = Math.min(baseDelayMs * Math.pow(2, attempt) + Math.random() * 200, maxDelayMs);
|
|
67
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
throw lastError;
|
|
71
|
+
}
|
package/dist/esm/utxo.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { randomBytes } from "crypto";
|
|
2
|
+
import nacl from "tweetnacl";
|
|
3
|
+
import { sha256 } from "@noble/hashes/sha256";
|
|
4
|
+
import { BN254_FR_MODULUS, bigIntToBytesBE, bytesToBigIntBE, poseidon1, poseidon3, poseidon4, pubkeyToField, } from "./poseidon";
|
|
5
|
+
// -----------------------------------------------------------------------------
|
|
6
|
+
// Keypair Functions
|
|
7
|
+
// -----------------------------------------------------------------------------
|
|
8
|
+
/**
|
|
9
|
+
* Generate a random keypair.
|
|
10
|
+
* Private key is a random 32-byte scalar.
|
|
11
|
+
* Public key is derived via Poseidon: pubkey = Poseidon(privateKey)
|
|
12
|
+
*/
|
|
13
|
+
export function generateKeypair() {
|
|
14
|
+
const privateKeyBytes = new Uint8Array(randomBytes(32));
|
|
15
|
+
const privateKey = bytesToBigIntBE(privateKeyBytes) % BN254_FR_MODULUS;
|
|
16
|
+
const publicKey = derivePublicKey(privateKey);
|
|
17
|
+
return { privateKey, publicKey };
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Derive public key from private key.
|
|
21
|
+
* Matches circuit's Keypair template: publicKey = Poseidon(privateKey)
|
|
22
|
+
*/
|
|
23
|
+
export function derivePublicKey(privateKey) {
|
|
24
|
+
return poseidon1(privateKey);
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Create keypair from a known private key.
|
|
28
|
+
*/
|
|
29
|
+
export function keypairFromPrivateKey(privateKey) {
|
|
30
|
+
return {
|
|
31
|
+
privateKey: privateKey % BN254_FR_MODULUS,
|
|
32
|
+
publicKey: derivePublicKey(privateKey % BN254_FR_MODULUS),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
// -----------------------------------------------------------------------------
|
|
36
|
+
// UTXO Commitment Functions
|
|
37
|
+
// -----------------------------------------------------------------------------
|
|
38
|
+
/**
|
|
39
|
+
* Compute UTXO commitment.
|
|
40
|
+
* Matches circuit's UTXOCommitment template:
|
|
41
|
+
* commitment = Poseidon(amount, pubkey, blinding, mintAddress)
|
|
42
|
+
*/
|
|
43
|
+
export function commitUTXO(utxo) {
|
|
44
|
+
const commitment = poseidon4(utxo.amount, utxo.pubkey, utxo.blinding, utxo.mintAddress);
|
|
45
|
+
return bigIntToBytesBE(commitment);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Create a random UTXO with the given parameters.
|
|
49
|
+
*/
|
|
50
|
+
export function createUTXO(params) {
|
|
51
|
+
const blindingBytes = new Uint8Array(randomBytes(32));
|
|
52
|
+
const blinding = bytesToBigIntBE(blindingBytes) % BN254_FR_MODULUS;
|
|
53
|
+
const utxo = {
|
|
54
|
+
amount: params.amount,
|
|
55
|
+
pubkey: params.pubkey,
|
|
56
|
+
blinding,
|
|
57
|
+
mintAddress: pubkeyToField(params.mintAddress),
|
|
58
|
+
};
|
|
59
|
+
const commitment = commitUTXO(utxo);
|
|
60
|
+
return {
|
|
61
|
+
...utxo,
|
|
62
|
+
commitment,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Create a UTXO with a specified private key (for owned UTXOs).
|
|
67
|
+
*/
|
|
68
|
+
export function createOwnedUTXO(params) {
|
|
69
|
+
const keypair = keypairFromPrivateKey(params.privateKey);
|
|
70
|
+
const utxo = createUTXO({
|
|
71
|
+
amount: params.amount,
|
|
72
|
+
pubkey: keypair.publicKey,
|
|
73
|
+
mintAddress: params.mintAddress,
|
|
74
|
+
});
|
|
75
|
+
return {
|
|
76
|
+
...utxo,
|
|
77
|
+
privateKey: keypair.privateKey,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Create a zero UTXO (for deposits where no input exists).
|
|
82
|
+
* Zero UTXOs have amount=0 and are used as placeholders in 2-in-2-out transactions.
|
|
83
|
+
*/
|
|
84
|
+
export function createZeroUTXO(pubkey, mintAddress) {
|
|
85
|
+
return createUTXO({
|
|
86
|
+
amount: 0n,
|
|
87
|
+
pubkey,
|
|
88
|
+
mintAddress,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Create a zero UTXO with private key (for owned zero UTXOs).
|
|
93
|
+
*/
|
|
94
|
+
export function createOwnedZeroUTXO(privateKey, mintAddress) {
|
|
95
|
+
const keypair = keypairFromPrivateKey(privateKey);
|
|
96
|
+
const utxo = createZeroUTXO(keypair.publicKey, mintAddress);
|
|
97
|
+
return {
|
|
98
|
+
...utxo,
|
|
99
|
+
privateKey: keypair.privateKey,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
// -----------------------------------------------------------------------------
|
|
103
|
+
// Nullifier Functions
|
|
104
|
+
// -----------------------------------------------------------------------------
|
|
105
|
+
/**
|
|
106
|
+
* Compute signature for nullifier derivation.
|
|
107
|
+
* Matches circuit's Signature template:
|
|
108
|
+
* signature = Poseidon(privateKey, commitment, pathIndex)
|
|
109
|
+
*/
|
|
110
|
+
export function computeSignature(privateKey, commitment, pathIndex) {
|
|
111
|
+
return poseidon3(privateKey, commitment, pathIndex);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Derive nullifier for a UTXO.
|
|
115
|
+
* Matches circuit's UTXONullifier template:
|
|
116
|
+
* signature = Poseidon(privateKey, commitment, pathIndex)
|
|
117
|
+
* nullifier = Poseidon(commitment, pathIndex, signature)
|
|
118
|
+
*
|
|
119
|
+
* The signature-based nullifier ensures only the private key holder can spend.
|
|
120
|
+
*/
|
|
121
|
+
export function deriveNullifier(utxo, pathIndex, privateKey) {
|
|
122
|
+
const commitment = bytesToBigIntBE(utxo.commitment) % BN254_FR_MODULUS;
|
|
123
|
+
const pathIndexField = BigInt(pathIndex) % BN254_FR_MODULUS;
|
|
124
|
+
const signature = computeSignature(privateKey, commitment, pathIndexField);
|
|
125
|
+
const nullifier = poseidon3(commitment, pathIndexField, signature);
|
|
126
|
+
return bigIntToBytesBE(nullifier);
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Convert InputUTXO to the format expected by the circuit.
|
|
130
|
+
*/
|
|
131
|
+
export function inputUTXOToCircuitFormat(input) {
|
|
132
|
+
return {
|
|
133
|
+
amount: input.amount,
|
|
134
|
+
pubkey: input.pubkey,
|
|
135
|
+
blinding: input.blinding,
|
|
136
|
+
pathElements: input.pathElements.map((e) => bytesToBigIntBE(e) % BN254_FR_MODULUS),
|
|
137
|
+
pathIndex: input.pathIndex,
|
|
138
|
+
privateKey: input.privateKey,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Derive a NaCl X25519 encryption keypair from a UTXO private key.
|
|
143
|
+
* The keypair is deterministic: same privateKey always yields the same pair.
|
|
144
|
+
*/
|
|
145
|
+
export function deriveEncryptionKeypair(privateKey) {
|
|
146
|
+
const seed = sha256(bigIntToBytesBE(privateKey));
|
|
147
|
+
return nacl.box.keyPair.fromSecretKey(seed);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Encrypt a UTXO so the recipient can recover it from on-chain events.
|
|
151
|
+
*
|
|
152
|
+
* Plaintext layout (72 bytes):
|
|
153
|
+
* [0..8] amount — 8-byte little-endian u64
|
|
154
|
+
* [8..40] blinding — 32-byte big-endian field element
|
|
155
|
+
* [40..72] privateKey — 32-byte big-endian field element
|
|
156
|
+
*
|
|
157
|
+
* Uses ephemeral-key NaCl box so the sender key is single-use.
|
|
158
|
+
*/
|
|
159
|
+
export function encryptUTXONote(utxo, recipientEncPubkey) {
|
|
160
|
+
const nonce = nacl.randomBytes(nacl.box.nonceLength); // 24 bytes
|
|
161
|
+
const ephemeral = nacl.box.keyPair();
|
|
162
|
+
const amountBuf = new Uint8Array(8);
|
|
163
|
+
let v = utxo.amount;
|
|
164
|
+
for (let i = 0; i < 8; i++) {
|
|
165
|
+
amountBuf[i] = Number(v & 0xffn);
|
|
166
|
+
v >>= 8n;
|
|
167
|
+
}
|
|
168
|
+
const plaintext = new Uint8Array(72);
|
|
169
|
+
plaintext.set(amountBuf, 0);
|
|
170
|
+
plaintext.set(bigIntToBytesBE(utxo.blinding), 8);
|
|
171
|
+
plaintext.set(bigIntToBytesBE(utxo.privateKey), 40);
|
|
172
|
+
const sharedKey = nacl.box.before(recipientEncPubkey, ephemeral.secretKey);
|
|
173
|
+
const ciphertext = nacl.box.after(plaintext, nonce, sharedKey);
|
|
174
|
+
return { nonce, ciphertext, senderEphemeralPubkey: ephemeral.publicKey };
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Try to decrypt an encrypted UTXO note using the recipient's private key.
|
|
178
|
+
* Returns the SerializedUTXO if decryption succeeds and the commitment
|
|
179
|
+
* matches, or `null` if the note was not intended for this key.
|
|
180
|
+
*/
|
|
181
|
+
export function decryptUTXONote(note, recipientPrivateKey, commitment, mintAddress) {
|
|
182
|
+
const { secretKey } = deriveEncryptionKeypair(recipientPrivateKey);
|
|
183
|
+
const sharedKey = nacl.box.before(note.senderEphemeralPubkey, secretKey);
|
|
184
|
+
const plaintext = nacl.box.open.after(note.ciphertext, note.nonce, sharedKey);
|
|
185
|
+
if (!plaintext || plaintext.length < 72)
|
|
186
|
+
return null;
|
|
187
|
+
let amount = 0n;
|
|
188
|
+
for (let i = 7; i >= 0; i--)
|
|
189
|
+
amount = (amount << 8n) | BigInt(plaintext[i]);
|
|
190
|
+
const blinding = bytesToBigIntBE(plaintext.slice(8, 40)) % BN254_FR_MODULUS;
|
|
191
|
+
const privateKey = bytesToBigIntBE(plaintext.slice(40, 72)) % BN254_FR_MODULUS;
|
|
192
|
+
const pubkey = derivePublicKey(privateKey);
|
|
193
|
+
const utxo = {
|
|
194
|
+
amount,
|
|
195
|
+
pubkey,
|
|
196
|
+
blinding,
|
|
197
|
+
mintAddress: pubkeyToField(mintAddress),
|
|
198
|
+
};
|
|
199
|
+
const expectedCommitment = commitUTXO(utxo);
|
|
200
|
+
if (!expectedCommitment.every((b, i) => b === commitment[i]))
|
|
201
|
+
return null;
|
|
202
|
+
return { ...utxo, commitment, privateKey };
|
|
203
|
+
}
|
|
204
|
+
// -- Internal crypto helpers (no extra dependencies) --------------------------
|
|
205
|
+
/** Derive 32-byte encryption key from a shared secret using SHA-512 truncated.
|
|
206
|
+
* Must match the production "sha256" helper which uses nacl.hash (SHA-512) [0:32]. */
|
|
207
|
+
function kdfSHA512_256(secret) {
|
|
208
|
+
return nacl.hash(secret).slice(0, 32);
|
|
209
|
+
}
|
|
210
|
+
/** Convert an Ed25519 private seed (32 bytes) to an X25519 scalar.
|
|
211
|
+
* Equivalent to ed2curve.convertSecretKey(seed). */
|
|
212
|
+
function ed25519SeedToX25519Private(seed) {
|
|
213
|
+
const h = nacl.hash(seed); // SHA-512
|
|
214
|
+
const scalar = h.slice(0, 32);
|
|
215
|
+
scalar[0] &= 248;
|
|
216
|
+
scalar[31] &= 127;
|
|
217
|
+
scalar[31] |= 64;
|
|
218
|
+
return scalar;
|
|
219
|
+
}
|
|
220
|
+
const P25519 = (1n << 255n) - 19n;
|
|
221
|
+
function modpow25519(b, e) {
|
|
222
|
+
let r = 1n;
|
|
223
|
+
b = b % P25519;
|
|
224
|
+
while (e > 0n) {
|
|
225
|
+
if (e & 1n)
|
|
226
|
+
r = (r * b) % P25519;
|
|
227
|
+
e >>= 1n;
|
|
228
|
+
b = (b * b) % P25519;
|
|
229
|
+
}
|
|
230
|
+
return r;
|
|
231
|
+
}
|
|
232
|
+
/** Convert an Ed25519 compressed public key (32 bytes) to X25519.
|
|
233
|
+
* Equivalent to ed2curve.convertPublicKey(pubkey).
|
|
234
|
+
* Edwards y-coord → Montgomery u via: u = (1 + y) / (1 - y) (mod p). */
|
|
235
|
+
function ed25519PublicKeyToX25519(pubkey) {
|
|
236
|
+
const pk = new Uint8Array(pubkey);
|
|
237
|
+
pk[31] &= 0x7f; // clear sign bit to get y as LE integer
|
|
238
|
+
// Decode little-endian y
|
|
239
|
+
let y = 0n;
|
|
240
|
+
for (let i = 31; i >= 0; i--)
|
|
241
|
+
y = (y << 8n) | BigInt(pk[i]);
|
|
242
|
+
// u = (1 + y) / (1 - y) mod p
|
|
243
|
+
const num = (1n + y) % P25519;
|
|
244
|
+
const den = (((1n - y) % P25519) + P25519) % P25519;
|
|
245
|
+
const u = (num * modpow25519(den, P25519 - 2n)) % P25519;
|
|
246
|
+
// Encode as 32-byte LE
|
|
247
|
+
const out = new Uint8Array(32);
|
|
248
|
+
let v = u;
|
|
249
|
+
for (let i = 0; i < 32; i++) {
|
|
250
|
+
out[i] = Number(v & 0xffn);
|
|
251
|
+
v >>= 8n;
|
|
252
|
+
}
|
|
253
|
+
return out;
|
|
254
|
+
}
|
|
255
|
+
// -- Public API ---------------------------------------------------------------
|
|
256
|
+
/**
|
|
257
|
+
* Encrypt a UTXO note for a recipient identified by their Solana wallet public key.
|
|
258
|
+
* Produces a blob the relayer will store and serve via POST /notes/save.
|
|
259
|
+
*
|
|
260
|
+
* @param recipientWalletPubkey 32-byte Ed25519 public key (wallet.publicKey.toBytes())
|
|
261
|
+
* @param noteData UTXO details to encrypt
|
|
262
|
+
*/
|
|
263
|
+
export function encryptBlindMailboxNote(recipientWalletPubkey, noteData) {
|
|
264
|
+
// 1. Generate ephemeral Ed25519 keypair seed
|
|
265
|
+
const ephemeralSeed = randomBytes(32);
|
|
266
|
+
// Ed25519 public key stored by relayer; dapp recovers X25519 via ed2curve.convertPublicKey()
|
|
267
|
+
const ephemeralEdPublicKey = nacl.sign.keyPair.fromSeed(new Uint8Array(ephemeralSeed)).publicKey;
|
|
268
|
+
// X25519 scalar (ed2curve.convertSecretKey equivalent)
|
|
269
|
+
const ephemeralX25519Private = ed25519SeedToX25519Private(new Uint8Array(ephemeralSeed));
|
|
270
|
+
// X25519 public key (ed2curve.convertPublicKey equivalent)
|
|
271
|
+
const recipientX25519Public = ed25519PublicKeyToX25519(recipientWalletPubkey);
|
|
272
|
+
const sharedSecret = nacl.scalarMult(ephemeralX25519Private, recipientX25519Public);
|
|
273
|
+
const key = kdfSHA512_256(sharedSecret);
|
|
274
|
+
// JSON format matches production relayer notes schema
|
|
275
|
+
const hexArr = (b) => Array.from(b)
|
|
276
|
+
.map((x) => x.toString(16).padStart(2, "0"))
|
|
277
|
+
.join("");
|
|
278
|
+
const noteJson = JSON.stringify({
|
|
279
|
+
blinding: hexArr(noteData.blinding),
|
|
280
|
+
leafIndex: noteData.leafIndex,
|
|
281
|
+
commitment: hexArr(noteData.commitment),
|
|
282
|
+
amount: noteData.amount.toString(),
|
|
283
|
+
mintAddress: noteData.mintAddress,
|
|
284
|
+
timestamp: Date.now(),
|
|
285
|
+
treeId: noteData.treeId,
|
|
286
|
+
});
|
|
287
|
+
const nonce = nacl.randomBytes(24);
|
|
288
|
+
const plaintext = new TextEncoder().encode(noteJson);
|
|
289
|
+
const encrypted = nacl.secretbox(plaintext, nonce, key);
|
|
290
|
+
const combined = new Uint8Array(nonce.length + encrypted.length);
|
|
291
|
+
combined.set(nonce);
|
|
292
|
+
combined.set(encrypted, nonce.length);
|
|
293
|
+
const encryptedBlob = Buffer.from(combined).toString("base64");
|
|
294
|
+
// Return Ed25519 public key (dapp calls ed2curve.convertPublicKey() to recover X25519)
|
|
295
|
+
return { ephemeralPublicKey: ephemeralEdPublicKey, encryptedBlob };
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Decrypt a Blind Mailbox note using the recipient's Solana wallet private seed.
|
|
299
|
+
*
|
|
300
|
+
* @param walletSecretKey Full 64-byte wallet.secretKey — the first 32 bytes are the seed
|
|
301
|
+
* @param ephemeralPublicKey 32-byte raw public key stored alongside the encrypted blob.
|
|
302
|
+
* This may be either an Ed25519 pubkey (from Keypair.generate())
|
|
303
|
+
* or a raw X25519 pubkey — the decryption path handles both:
|
|
304
|
+
* if it is an Ed25519 key it is converted; otherwise used directly.
|
|
305
|
+
* @param encryptedBlob Base64 string as stored by the relayer
|
|
306
|
+
*/
|
|
307
|
+
export function decryptBlindMailboxNote(walletSecretKey, ephemeralPublicKey, encryptedBlob) {
|
|
308
|
+
// 1. Derive recipient X25519 from Ed25519 seed
|
|
309
|
+
const seed = walletSecretKey.slice(0, 32);
|
|
310
|
+
const myX25519Private = ed25519SeedToX25519Private(seed);
|
|
311
|
+
// ephemeralPublicKey may be an Ed25519 pubkey (dapp's Keypair.generate()) or raw X25519;
|
|
312
|
+
// try Ed25519→X25519 conversion first, fall back to using it directly.
|
|
313
|
+
let theirPublic;
|
|
314
|
+
try {
|
|
315
|
+
theirPublic = ed25519PublicKeyToX25519(ephemeralPublicKey);
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
theirPublic = ephemeralPublicKey; // already X25519
|
|
319
|
+
}
|
|
320
|
+
const sharedSecret = nacl.scalarMult(myX25519Private, theirPublic);
|
|
321
|
+
const key = kdfSHA512_256(sharedSecret);
|
|
322
|
+
const combined = Buffer.from(encryptedBlob, "base64");
|
|
323
|
+
const nonce = combined.slice(0, 24);
|
|
324
|
+
const ciphertext = combined.slice(24);
|
|
325
|
+
const decrypted = nacl.secretbox.open(new Uint8Array(ciphertext), new Uint8Array(nonce), key);
|
|
326
|
+
if (!decrypted) {
|
|
327
|
+
throw new Error("decryptBlindMailboxNote: decryption failed — wrong key or corrupted blob");
|
|
328
|
+
}
|
|
329
|
+
const parsed = JSON.parse(new TextDecoder().decode(decrypted));
|
|
330
|
+
const hexToBytes = (hex) => {
|
|
331
|
+
const out = new Uint8Array(hex.length / 2);
|
|
332
|
+
for (let i = 0; i < hex.length; i += 2)
|
|
333
|
+
out[i / 2] = parseInt(hex.slice(i, i + 2), 16);
|
|
334
|
+
return out;
|
|
335
|
+
};
|
|
336
|
+
return {
|
|
337
|
+
blinding: hexToBytes(parsed.blinding),
|
|
338
|
+
leafIndex: parsed.leafIndex,
|
|
339
|
+
commitment: hexToBytes(parsed.commitment),
|
|
340
|
+
amount: BigInt(parsed.amount),
|
|
341
|
+
timestamp: parsed.timestamp ?? 0,
|
|
342
|
+
mintAddress: parsed.mintAddress,
|
|
343
|
+
treeId: parsed.treeId,
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Fetch all encrypted notes for a wallet from the relayer's Blind Mailbox endpoint
|
|
348
|
+
* and decrypt them using the wallet's secret key.
|
|
349
|
+
*
|
|
350
|
+
* @param walletPublicKey Base58 wallet address used to query the relayer
|
|
351
|
+
* @param walletSecretKey Full 64-byte keypair.secretKey for decryption
|
|
352
|
+
* @param relayerUrl Relayer base URL (e.g. "https://relay.veilo.app")
|
|
353
|
+
*/
|
|
354
|
+
export async function fetchAndDecryptNotes(walletPublicKey, walletSecretKey, relayerUrl) {
|
|
355
|
+
const resp = await fetch(`${relayerUrl}/api/notes?recipientPublicKey=${walletPublicKey}`);
|
|
356
|
+
if (!resp.ok) {
|
|
357
|
+
throw new Error(`fetchAndDecryptNotes: ${resp.status} ${resp.statusText}`);
|
|
358
|
+
}
|
|
359
|
+
const { notes } = (await resp.json());
|
|
360
|
+
const results = [];
|
|
361
|
+
for (const note of notes) {
|
|
362
|
+
try {
|
|
363
|
+
const epk = Buffer.from(note.ephemeralPublicKey, "base64");
|
|
364
|
+
const decrypted = decryptBlindMailboxNote(walletSecretKey, new Uint8Array(epk), note.encryptedBlob);
|
|
365
|
+
results.push(decrypted);
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
// Note not for this key or corrupted — skip silently
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return results;
|
|
372
|
+
}
|