@veilo/sdk-core 0.1.17 → 0.4.0

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.
Files changed (218) hide show
  1. package/README.md +1296 -272
  2. package/SHIELD_INTEGRATION.md +143 -0
  3. package/config.d.ts +2 -0
  4. package/config.js +4 -0
  5. package/dist/cjs/client.d.ts +407 -0
  6. package/dist/cjs/client.js +951 -0
  7. package/dist/cjs/compactNote.d.ts +107 -0
  8. package/dist/cjs/compactNote.js +167 -0
  9. package/dist/cjs/config.d.ts +82 -0
  10. package/dist/cjs/config.js +57 -0
  11. package/dist/cjs/events.d.ts +77 -0
  12. package/dist/cjs/events.js +167 -0
  13. package/dist/cjs/idl/privacy_pool.d.ts +5 -0
  14. package/dist/cjs/idl/privacy_pool.js +15218 -0
  15. package/dist/cjs/idl/privacy_pool.json +10313 -0
  16. package/dist/cjs/index.d.ts +16 -0
  17. package/dist/cjs/index.js +67 -0
  18. package/dist/cjs/merkle.d.ts +77 -0
  19. package/dist/cjs/merkle.js +156 -0
  20. package/dist/cjs/poseidon.d.ts +29 -0
  21. package/dist/cjs/poseidon.js +100 -0
  22. package/dist/cjs/program.d.ts +37 -0
  23. package/dist/cjs/program.js +61 -0
  24. package/dist/cjs/proof.d.ts +183 -0
  25. package/dist/cjs/proof.js +292 -0
  26. package/dist/cjs/prover.d.ts +54 -0
  27. package/dist/cjs/prover.js +112 -0
  28. package/dist/cjs/random.d.ts +16 -0
  29. package/dist/cjs/random.js +28 -0
  30. package/dist/cjs/relayer.d.ts +318 -0
  31. package/dist/cjs/relayer.js +257 -0
  32. package/dist/cjs/retry.d.ts +32 -0
  33. package/dist/cjs/retry.js +75 -0
  34. package/dist/cjs/shield/alt.d.ts +87 -0
  35. package/dist/cjs/shield/alt.js +194 -0
  36. package/dist/cjs/shield/computeBudget.d.ts +61 -0
  37. package/dist/cjs/shield/computeBudget.js +64 -0
  38. package/dist/cjs/shield/errors.d.ts +58 -0
  39. package/dist/cjs/shield/errors.js +121 -0
  40. package/dist/cjs/shield/finalize.d.ts +45 -0
  41. package/dist/cjs/shield/finalize.js +119 -0
  42. package/dist/cjs/shield/index.d.ts +35 -0
  43. package/dist/cjs/shield/index.js +68 -0
  44. package/dist/cjs/shield/ix.d.ts +54 -0
  45. package/dist/cjs/shield/ix.js +119 -0
  46. package/dist/cjs/shield/owner.d.ts +36 -0
  47. package/dist/cjs/shield/owner.js +126 -0
  48. package/dist/cjs/shield/ports.d.ts +43 -0
  49. package/dist/cjs/shield/ports.js +153 -0
  50. package/dist/cjs/shield/preflight.d.ts +30 -0
  51. package/dist/cjs/shield/preflight.js +154 -0
  52. package/dist/cjs/shield/shield.d.ts +68 -0
  53. package/dist/cjs/shield/shield.js +499 -0
  54. package/dist/cjs/shield/types.d.ts +202 -0
  55. package/dist/cjs/shield/types.js +2 -0
  56. package/dist/cjs/utxo.d.ts +235 -0
  57. package/dist/cjs/utxo.js +407 -0
  58. package/dist/esm/client.d.ts +407 -0
  59. package/dist/esm/client.js +891 -0
  60. package/dist/esm/compactNote.d.ts +107 -0
  61. package/dist/esm/compactNote.js +156 -0
  62. package/dist/esm/config.d.ts +82 -0
  63. package/dist/esm/config.js +51 -0
  64. package/dist/esm/events.d.ts +77 -0
  65. package/dist/esm/events.js +129 -0
  66. package/dist/esm/idl/privacy_pool.d.ts +5 -0
  67. package/dist/esm/idl/privacy_pool.js +15216 -0
  68. package/dist/esm/idl/privacy_pool.json +10313 -0
  69. package/dist/esm/index.d.ts +16 -0
  70. package/dist/esm/index.js +29 -0
  71. package/dist/esm/merkle.d.ts +77 -0
  72. package/dist/esm/merkle.js +151 -0
  73. package/dist/esm/package.json +1 -0
  74. package/dist/esm/poseidon.d.ts +29 -0
  75. package/dist/esm/poseidon.js +87 -0
  76. package/dist/esm/program.d.ts +37 -0
  77. package/dist/esm/program.js +53 -0
  78. package/dist/esm/proof.d.ts +183 -0
  79. package/dist/esm/proof.js +281 -0
  80. package/dist/esm/prover.d.ts +54 -0
  81. package/dist/esm/prover.js +75 -0
  82. package/dist/esm/random.d.ts +16 -0
  83. package/dist/esm/random.js +21 -0
  84. package/dist/esm/relayer.d.ts +318 -0
  85. package/dist/esm/relayer.js +249 -0
  86. package/dist/esm/retry.d.ts +32 -0
  87. package/dist/esm/retry.js +71 -0
  88. package/dist/esm/shield/alt.d.ts +87 -0
  89. package/dist/esm/shield/alt.js +186 -0
  90. package/dist/esm/shield/computeBudget.d.ts +61 -0
  91. package/dist/esm/shield/computeBudget.js +61 -0
  92. package/dist/esm/shield/errors.d.ts +58 -0
  93. package/dist/esm/shield/errors.js +115 -0
  94. package/dist/esm/shield/finalize.d.ts +45 -0
  95. package/dist/esm/shield/finalize.js +83 -0
  96. package/dist/esm/shield/index.d.ts +35 -0
  97. package/dist/esm/shield/index.js +32 -0
  98. package/dist/esm/shield/ix.d.ts +54 -0
  99. package/dist/esm/shield/ix.js +82 -0
  100. package/dist/esm/shield/owner.d.ts +36 -0
  101. package/dist/esm/shield/owner.js +122 -0
  102. package/dist/esm/shield/ports.d.ts +43 -0
  103. package/dist/esm/shield/ports.js +147 -0
  104. package/dist/esm/shield/preflight.d.ts +30 -0
  105. package/dist/esm/shield/preflight.js +151 -0
  106. package/dist/esm/shield/shield.d.ts +68 -0
  107. package/dist/esm/shield/shield.js +492 -0
  108. package/dist/esm/shield/types.d.ts +202 -0
  109. package/dist/esm/shield/types.js +1 -0
  110. package/dist/esm/utxo.d.ts +235 -0
  111. package/dist/esm/utxo.js +382 -0
  112. package/dist/src/client.d.ts +407 -0
  113. package/dist/src/client.js +951 -0
  114. package/dist/src/compactNote.d.ts +107 -0
  115. package/dist/src/compactNote.js +167 -0
  116. package/dist/src/config.d.ts +82 -0
  117. package/dist/src/config.js +57 -0
  118. package/dist/src/events.d.ts +77 -0
  119. package/dist/src/events.js +167 -0
  120. package/dist/src/idl/privacy_pool.d.ts +5 -0
  121. package/dist/src/idl/privacy_pool.js +15218 -0
  122. package/dist/src/index.d.ts +16 -0
  123. package/dist/src/index.js +67 -0
  124. package/dist/src/merkle.d.ts +77 -0
  125. package/dist/src/merkle.js +156 -0
  126. package/dist/src/poseidon.d.ts +29 -0
  127. package/dist/src/poseidon.js +100 -0
  128. package/dist/src/program.d.ts +37 -0
  129. package/dist/src/program.js +61 -0
  130. package/dist/src/proof.d.ts +183 -0
  131. package/dist/src/proof.js +292 -0
  132. package/dist/src/prover.d.ts +54 -0
  133. package/dist/src/prover.js +112 -0
  134. package/dist/src/random.d.ts +16 -0
  135. package/dist/src/random.js +28 -0
  136. package/dist/src/relayer.d.ts +318 -0
  137. package/dist/src/relayer.js +257 -0
  138. package/dist/src/retry.d.ts +32 -0
  139. package/dist/src/retry.js +75 -0
  140. package/dist/src/shield/alt.d.ts +87 -0
  141. package/dist/src/shield/alt.js +194 -0
  142. package/dist/src/shield/computeBudget.d.ts +61 -0
  143. package/dist/src/shield/computeBudget.js +64 -0
  144. package/dist/src/shield/errors.d.ts +58 -0
  145. package/dist/src/shield/errors.js +121 -0
  146. package/dist/src/shield/finalize.d.ts +45 -0
  147. package/dist/src/shield/finalize.js +119 -0
  148. package/dist/src/shield/index.d.ts +35 -0
  149. package/dist/src/shield/index.js +68 -0
  150. package/dist/src/shield/ix.d.ts +54 -0
  151. package/dist/src/shield/ix.js +119 -0
  152. package/dist/src/shield/owner.d.ts +36 -0
  153. package/dist/src/shield/owner.js +126 -0
  154. package/dist/src/shield/ports.d.ts +43 -0
  155. package/dist/src/shield/ports.js +153 -0
  156. package/dist/src/shield/preflight.d.ts +30 -0
  157. package/dist/src/shield/preflight.js +154 -0
  158. package/dist/src/shield/shield.d.ts +68 -0
  159. package/dist/src/shield/shield.js +499 -0
  160. package/dist/src/shield/types.d.ts +202 -0
  161. package/dist/src/shield/types.js +2 -0
  162. package/dist/src/utxo.d.ts +235 -0
  163. package/dist/src/utxo.js +407 -0
  164. package/dist/tests/compact-note.test.d.ts +1 -0
  165. package/dist/tests/compact-note.test.js +173 -0
  166. package/dist/tests/config.test.d.ts +1 -0
  167. package/dist/tests/config.test.js +102 -0
  168. package/dist/tests/edge-cases.test.d.ts +1 -0
  169. package/dist/tests/edge-cases.test.js +220 -0
  170. package/dist/tests/encryption.test.d.ts +1 -0
  171. package/dist/tests/encryption.test.js +215 -0
  172. package/dist/tests/events.test.d.ts +1 -0
  173. package/dist/tests/events.test.js +78 -0
  174. package/dist/tests/multi-tree.test.d.ts +1 -0
  175. package/dist/tests/multi-tree.test.js +405 -0
  176. package/dist/tests/pda.test.d.ts +1 -0
  177. package/dist/tests/pda.test.js +229 -0
  178. package/dist/tests/poseidon-builder-parity.test.d.ts +1 -0
  179. package/dist/tests/poseidon-builder-parity.test.js +72 -0
  180. package/dist/tests/poseidon.test.d.ts +1 -0
  181. package/dist/tests/poseidon.test.js +142 -0
  182. package/dist/tests/proof.test.d.ts +1 -0
  183. package/dist/tests/proof.test.js +296 -0
  184. package/dist/tests/relayer.test.d.ts +1 -0
  185. package/dist/tests/relayer.test.js +271 -0
  186. package/dist/tests/sdk.integration.test.d.ts +1 -0
  187. package/dist/tests/sdk.integration.test.js +330 -0
  188. package/dist/tests/shield-owner.test.d.ts +1 -0
  189. package/dist/tests/shield-owner.test.js +89 -0
  190. package/dist/tests/shield-preflight.test.d.ts +1 -0
  191. package/dist/tests/shield-preflight.test.js +87 -0
  192. package/dist/tests/shield-realproof.test.d.ts +1 -0
  193. package/dist/tests/shield-realproof.test.js +272 -0
  194. package/dist/tests/shield.test.d.ts +1 -0
  195. package/dist/tests/shield.test.js +403 -0
  196. package/dist/tests/utxo.test.d.ts +1 -0
  197. package/dist/tests/utxo.test.js +140 -0
  198. package/package.json +105 -11
  199. package/poseidon.d.ts +2 -0
  200. package/poseidon.js +4 -0
  201. package/proof.d.ts +2 -0
  202. package/proof.js +4 -0
  203. package/prover.d.ts +2 -0
  204. package/prover.js +4 -0
  205. package/shield.d.ts +2 -0
  206. package/shield.js +4 -0
  207. package/src/client.ts +0 -352
  208. package/src/config.ts +0 -13
  209. package/src/index.ts +0 -6
  210. package/src/merkle.ts +0 -178
  211. package/src/note.ts +0 -193
  212. package/src/poseidon.ts +0 -62
  213. package/src/proof.ts +0 -170
  214. package/test/script.js +0 -0
  215. package/test-tsconfig.json +0 -19
  216. package/tests/note.test.ts +0 -50
  217. package/tests/sdk.integration.test.ts +0 -210
  218. package/tsconfig.json +0 -18
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,235 @@
1
+ import { PublicKey } from "@solana/web3.js";
2
+ /**
3
+ * Keypair for UTXO ownership.
4
+ * Public key is derived via Poseidon: pubkey = Poseidon(privateKey)
5
+ */
6
+ export type Keypair = {
7
+ privateKey: bigint;
8
+ publicKey: bigint;
9
+ };
10
+ /**
11
+ * UTXO structure matching the circuit's UTXOCommitment template.
12
+ * commitment = Poseidon(amount, pubkey, blinding, mintAddress)
13
+ */
14
+ export type UTXO = {
15
+ /** Amount in lamports/token units */
16
+ amount: bigint;
17
+ /** Owner's public key (derived from private key via Poseidon) */
18
+ pubkey: bigint;
19
+ /** Random blinding factor for commitment privacy */
20
+ blinding: bigint;
21
+ /** Token mint address as field element */
22
+ mintAddress: bigint;
23
+ };
24
+ /**
25
+ * Serialized UTXO with precomputed commitment and optional ownership data.
26
+ */
27
+ export type SerializedUTXO = UTXO & {
28
+ /** 32-byte commitment: Poseidon(amount, pubkey, blinding, mintAddress) */
29
+ commitment: Uint8Array;
30
+ /** Private key for spending (only present for owned UTXOs) */
31
+ privateKey?: bigint;
32
+ /** Leaf index in the Merkle tree (set after insertion) */
33
+ pathIndex?: number;
34
+ };
35
+ /**
36
+ * Input UTXO with Merkle proof data for spending.
37
+ */
38
+ export type InputUTXO = SerializedUTXO & {
39
+ /** Leaf index in the Merkle tree */
40
+ pathIndex: number;
41
+ /** Merkle path elements (sibling hashes from leaf to root) */
42
+ pathElements: Uint8Array[];
43
+ /** Private key for nullifier derivation */
44
+ privateKey: bigint;
45
+ };
46
+ /**
47
+ * Generate a random keypair.
48
+ * Private key is a random 32-byte scalar.
49
+ * Public key is derived via Poseidon: pubkey = Poseidon(privateKey)
50
+ */
51
+ export declare function generateKeypair(): Keypair;
52
+ /**
53
+ * Derive public key from private key.
54
+ * Matches circuit's Keypair template: publicKey = Poseidon(privateKey)
55
+ */
56
+ export declare function derivePublicKey(privateKey: bigint): bigint;
57
+ /**
58
+ * Create keypair from a known private key.
59
+ */
60
+ export declare function keypairFromPrivateKey(privateKey: bigint): Keypair;
61
+ /**
62
+ * Compute UTXO commitment.
63
+ * Matches circuit's UTXOCommitment template:
64
+ * commitment = Poseidon(amount, pubkey, blinding, mintAddress)
65
+ */
66
+ export declare function commitUTXO(utxo: UTXO): Uint8Array;
67
+ /**
68
+ * Create a random UTXO with the given parameters.
69
+ */
70
+ export declare function createUTXO(params: {
71
+ amount: bigint;
72
+ pubkey: bigint;
73
+ mintAddress: PublicKey;
74
+ }): SerializedUTXO;
75
+ /**
76
+ * Create a UTXO with a specified private key (for owned UTXOs).
77
+ */
78
+ export declare function createOwnedUTXO(params: {
79
+ amount: bigint;
80
+ privateKey: bigint;
81
+ mintAddress: PublicKey;
82
+ }): SerializedUTXO;
83
+ /**
84
+ * Create a zero UTXO (for deposits where no input exists).
85
+ * Zero UTXOs have amount=0 and are used as placeholders in 2-in-2-out transactions.
86
+ */
87
+ export declare function createZeroUTXO(pubkey: bigint, mintAddress: PublicKey): SerializedUTXO;
88
+ /**
89
+ * Create a zero UTXO with private key (for owned zero UTXOs).
90
+ */
91
+ export declare function createOwnedZeroUTXO(privateKey: bigint, mintAddress: PublicKey): SerializedUTXO;
92
+ /**
93
+ * Compute signature for nullifier derivation.
94
+ * Matches circuit's Signature template:
95
+ * signature = Poseidon(privateKey, commitment, pathIndex)
96
+ */
97
+ export declare function computeSignature(privateKey: bigint, commitment: bigint, pathIndex: bigint): bigint;
98
+ /**
99
+ * Derive nullifier for a UTXO.
100
+ * Matches circuit's UTXONullifier template:
101
+ * signature = Poseidon(privateKey, commitment, pathIndex)
102
+ * nullifier = Poseidon(commitment, pathIndex, signature)
103
+ *
104
+ * The signature-based nullifier ensures only the private key holder can spend.
105
+ */
106
+ export declare function deriveNullifier(utxo: SerializedUTXO, pathIndex: number, privateKey: bigint): Uint8Array;
107
+ /**
108
+ * Convert InputUTXO to the format expected by the circuit.
109
+ */
110
+ export declare function inputUTXOToCircuitFormat(input: InputUTXO): {
111
+ amount: bigint;
112
+ pubkey: bigint;
113
+ blinding: bigint;
114
+ pathElements: bigint[];
115
+ pathIndex: number;
116
+ privateKey: bigint;
117
+ };
118
+ /**
119
+ * Encrypted UTXO note — can be broadcast alongside a transaction so the
120
+ * recipient can recover their note without a server.
121
+ */
122
+ export type EncryptedNote = {
123
+ /** 24-byte NaCl box nonce */
124
+ nonce: Uint8Array;
125
+ /** Ciphertext containing amount + blinding + privateKey */
126
+ ciphertext: Uint8Array;
127
+ /** Sender's ephemeral 32-byte X25519 public key */
128
+ senderEphemeralPubkey: Uint8Array;
129
+ };
130
+ /**
131
+ * Derive a NaCl X25519 encryption keypair from a UTXO private key.
132
+ * The keypair is deterministic: same privateKey always yields the same pair.
133
+ */
134
+ export declare function deriveEncryptionKeypair(privateKey: bigint): {
135
+ publicKey: Uint8Array;
136
+ secretKey: Uint8Array;
137
+ };
138
+ /**
139
+ * Encrypt a UTXO so the recipient can recover it from on-chain events.
140
+ *
141
+ * Plaintext layout (72 bytes):
142
+ * [0..8] amount — 8-byte little-endian u64
143
+ * [8..40] blinding — 32-byte big-endian field element
144
+ * [40..72] privateKey — 32-byte big-endian field element
145
+ *
146
+ * Uses ephemeral-key NaCl box so the sender key is single-use.
147
+ */
148
+ export declare function encryptUTXONote(utxo: SerializedUTXO & {
149
+ privateKey: bigint;
150
+ }, recipientEncPubkey: Uint8Array): EncryptedNote;
151
+ /**
152
+ * Try to decrypt an encrypted UTXO note using the recipient's private key.
153
+ * Returns the SerializedUTXO if decryption succeeds and the commitment
154
+ * matches, or `null` if the note was not intended for this key.
155
+ */
156
+ export declare function decryptUTXONote(note: EncryptedNote, recipientPrivateKey: bigint, commitment: Uint8Array, mintAddress: PublicKey): SerializedUTXO | null;
157
+ /** Note data stored inside a Blind Mailbox encrypted blob */
158
+ export type BlindMailboxNoteData = {
159
+ blinding: Uint8Array;
160
+ leafIndex: number;
161
+ commitment: Uint8Array;
162
+ amount: bigint;
163
+ mintAddress: string;
164
+ treeId: number;
165
+ };
166
+ /** Encrypted note as returned by the relayer's /api/notes endpoint */
167
+ export type BlindMailboxNote = {
168
+ commitment: string;
169
+ ephemeralPublicKey: string;
170
+ encryptedBlob: string;
171
+ timestamp?: number;
172
+ blockHeight?: number;
173
+ txSignature?: string;
174
+ };
175
+ /** Decrypted note data after calling decryptBlindMailboxNote */
176
+ export type DecryptedNote = {
177
+ blinding: Uint8Array;
178
+ leafIndex: number;
179
+ commitment: Uint8Array;
180
+ amount: bigint;
181
+ timestamp: number;
182
+ mintAddress?: string;
183
+ treeId: number;
184
+ };
185
+ /** Derive 32-byte encryption key from a shared secret using SHA-512 truncated.
186
+ * Must match the production "sha256" helper which uses nacl.hash (SHA-512) [0:32].
187
+ *
188
+ * DO NOT "fix" this to real SHA-256. The name in the sibling implementations
189
+ * (`sha256ForNotes`) is a misnomer, but the bytes are load-bearing: changing the
190
+ * KDF makes every historical note undecryptable.
191
+ *
192
+ * @internal Exported for `compactNote.ts`. Not part of the stable public API. */
193
+ export declare function kdfSHA512_256(secret: Uint8Array): Uint8Array;
194
+ /** Convert an Ed25519 private seed (32 bytes) to an X25519 scalar.
195
+ * Equivalent to ed2curve.convertSecretKey(seed).
196
+ *
197
+ * @internal Exported for `compactNote.ts`. Not part of the stable public API. */
198
+ export declare function ed25519SeedToX25519Private(seed: Uint8Array): Uint8Array;
199
+ /** Convert an Ed25519 compressed public key (32 bytes) to X25519.
200
+ * Equivalent to ed2curve.convertPublicKey(pubkey).
201
+ * Edwards y-coord → Montgomery u via: u = (1 + y) / (1 - y) (mod p).
202
+ *
203
+ * @internal Exported for `compactNote.ts`. Not part of the stable public API. */
204
+ export declare function ed25519PublicKeyToX25519(pubkey: Uint8Array): Uint8Array;
205
+ /**
206
+ * Encrypt a UTXO note for a recipient identified by their Solana wallet public key.
207
+ * Produces a blob the relayer will store and serve via POST /notes/save.
208
+ *
209
+ * @param recipientWalletPubkey 32-byte Ed25519 public key (wallet.publicKey.toBytes())
210
+ * @param noteData UTXO details to encrypt
211
+ */
212
+ export declare function encryptBlindMailboxNote(recipientWalletPubkey: Uint8Array, noteData: BlindMailboxNoteData): {
213
+ ephemeralPublicKey: Uint8Array;
214
+ encryptedBlob: string;
215
+ };
216
+ /**
217
+ * Decrypt a Blind Mailbox note using the recipient's Solana wallet private seed.
218
+ *
219
+ * @param walletSecretKey Full 64-byte wallet.secretKey — the first 32 bytes are the seed
220
+ * @param ephemeralPublicKey 32-byte raw public key stored alongside the encrypted blob.
221
+ * This may be either an Ed25519 pubkey (from Keypair.generate())
222
+ * or a raw X25519 pubkey — the decryption path handles both:
223
+ * if it is an Ed25519 key it is converted; otherwise used directly.
224
+ * @param encryptedBlob Base64 string as stored by the relayer
225
+ */
226
+ export declare function decryptBlindMailboxNote(walletSecretKey: Uint8Array, ephemeralPublicKey: Uint8Array, encryptedBlob: string): DecryptedNote;
227
+ /**
228
+ * Fetch all encrypted notes for a wallet from the relayer's Blind Mailbox endpoint
229
+ * and decrypt them using the wallet's secret key.
230
+ *
231
+ * @param walletPublicKey Base58 wallet address used to query the relayer
232
+ * @param walletSecretKey Full 64-byte keypair.secretKey for decryption
233
+ * @param relayerUrl Relayer base URL (e.g. "https://relay.veilo.app")
234
+ */
235
+ export declare function fetchAndDecryptNotes(walletPublicKey: string, walletSecretKey: Uint8Array, relayerUrl: string): Promise<DecryptedNote[]>;
@@ -0,0 +1,382 @@
1
+ import { randomBytes } from "./random.js";
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.js";
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
+ *
208
+ * DO NOT "fix" this to real SHA-256. The name in the sibling implementations
209
+ * (`sha256ForNotes`) is a misnomer, but the bytes are load-bearing: changing the
210
+ * KDF makes every historical note undecryptable.
211
+ *
212
+ * @internal Exported for `compactNote.ts`. Not part of the stable public API. */
213
+ export function kdfSHA512_256(secret) {
214
+ return nacl.hash(secret).slice(0, 32);
215
+ }
216
+ /** Convert an Ed25519 private seed (32 bytes) to an X25519 scalar.
217
+ * Equivalent to ed2curve.convertSecretKey(seed).
218
+ *
219
+ * @internal Exported for `compactNote.ts`. Not part of the stable public API. */
220
+ export function ed25519SeedToX25519Private(seed) {
221
+ const h = nacl.hash(seed); // SHA-512
222
+ const scalar = h.slice(0, 32);
223
+ scalar[0] &= 248;
224
+ scalar[31] &= 127;
225
+ scalar[31] |= 64;
226
+ return scalar;
227
+ }
228
+ const P25519 = (1n << 255n) - 19n;
229
+ function modpow25519(b, e) {
230
+ let r = 1n;
231
+ b = b % P25519;
232
+ while (e > 0n) {
233
+ if (e & 1n)
234
+ r = (r * b) % P25519;
235
+ e >>= 1n;
236
+ b = (b * b) % P25519;
237
+ }
238
+ return r;
239
+ }
240
+ /** Convert an Ed25519 compressed public key (32 bytes) to X25519.
241
+ * Equivalent to ed2curve.convertPublicKey(pubkey).
242
+ * Edwards y-coord → Montgomery u via: u = (1 + y) / (1 - y) (mod p).
243
+ *
244
+ * @internal Exported for `compactNote.ts`. Not part of the stable public API. */
245
+ export function ed25519PublicKeyToX25519(pubkey) {
246
+ const pk = new Uint8Array(pubkey);
247
+ pk[31] &= 0x7f; // clear sign bit to get y as LE integer
248
+ // Decode little-endian y
249
+ let y = 0n;
250
+ for (let i = 31; i >= 0; i--)
251
+ y = (y << 8n) | BigInt(pk[i]);
252
+ // u = (1 + y) / (1 - y) mod p
253
+ const num = (1n + y) % P25519;
254
+ const den = (((1n - y) % P25519) + P25519) % P25519;
255
+ const u = (num * modpow25519(den, P25519 - 2n)) % P25519;
256
+ // Encode as 32-byte LE
257
+ const out = new Uint8Array(32);
258
+ let v = u;
259
+ for (let i = 0; i < 32; i++) {
260
+ out[i] = Number(v & 0xffn);
261
+ v >>= 8n;
262
+ }
263
+ return out;
264
+ }
265
+ // -- Public API ---------------------------------------------------------------
266
+ /**
267
+ * Encrypt a UTXO note for a recipient identified by their Solana wallet public key.
268
+ * Produces a blob the relayer will store and serve via POST /notes/save.
269
+ *
270
+ * @param recipientWalletPubkey 32-byte Ed25519 public key (wallet.publicKey.toBytes())
271
+ * @param noteData UTXO details to encrypt
272
+ */
273
+ export function encryptBlindMailboxNote(recipientWalletPubkey, noteData) {
274
+ // 1. Generate ephemeral Ed25519 keypair seed
275
+ const ephemeralSeed = randomBytes(32);
276
+ // Ed25519 public key stored by relayer; dapp recovers X25519 via ed2curve.convertPublicKey()
277
+ const ephemeralEdPublicKey = nacl.sign.keyPair.fromSeed(new Uint8Array(ephemeralSeed)).publicKey;
278
+ // X25519 scalar (ed2curve.convertSecretKey equivalent)
279
+ const ephemeralX25519Private = ed25519SeedToX25519Private(new Uint8Array(ephemeralSeed));
280
+ // X25519 public key (ed2curve.convertPublicKey equivalent)
281
+ const recipientX25519Public = ed25519PublicKeyToX25519(recipientWalletPubkey);
282
+ const sharedSecret = nacl.scalarMult(ephemeralX25519Private, recipientX25519Public);
283
+ const key = kdfSHA512_256(sharedSecret);
284
+ // JSON format matches production relayer notes schema
285
+ const hexArr = (b) => Array.from(b)
286
+ .map((x) => x.toString(16).padStart(2, "0"))
287
+ .join("");
288
+ const noteJson = JSON.stringify({
289
+ blinding: hexArr(noteData.blinding),
290
+ leafIndex: noteData.leafIndex,
291
+ commitment: hexArr(noteData.commitment),
292
+ amount: noteData.amount.toString(),
293
+ mintAddress: noteData.mintAddress,
294
+ timestamp: Date.now(),
295
+ treeId: noteData.treeId,
296
+ });
297
+ const nonce = nacl.randomBytes(24);
298
+ const plaintext = new TextEncoder().encode(noteJson);
299
+ const encrypted = nacl.secretbox(plaintext, nonce, key);
300
+ const combined = new Uint8Array(nonce.length + encrypted.length);
301
+ combined.set(nonce);
302
+ combined.set(encrypted, nonce.length);
303
+ const encryptedBlob = Buffer.from(combined).toString("base64");
304
+ // Return Ed25519 public key (dapp calls ed2curve.convertPublicKey() to recover X25519)
305
+ return { ephemeralPublicKey: ephemeralEdPublicKey, encryptedBlob };
306
+ }
307
+ /**
308
+ * Decrypt a Blind Mailbox note using the recipient's Solana wallet private seed.
309
+ *
310
+ * @param walletSecretKey Full 64-byte wallet.secretKey — the first 32 bytes are the seed
311
+ * @param ephemeralPublicKey 32-byte raw public key stored alongside the encrypted blob.
312
+ * This may be either an Ed25519 pubkey (from Keypair.generate())
313
+ * or a raw X25519 pubkey — the decryption path handles both:
314
+ * if it is an Ed25519 key it is converted; otherwise used directly.
315
+ * @param encryptedBlob Base64 string as stored by the relayer
316
+ */
317
+ export function decryptBlindMailboxNote(walletSecretKey, ephemeralPublicKey, encryptedBlob) {
318
+ // 1. Derive recipient X25519 from Ed25519 seed
319
+ const seed = walletSecretKey.slice(0, 32);
320
+ const myX25519Private = ed25519SeedToX25519Private(seed);
321
+ // ephemeralPublicKey may be an Ed25519 pubkey (dapp's Keypair.generate()) or raw X25519;
322
+ // try Ed25519→X25519 conversion first, fall back to using it directly.
323
+ let theirPublic;
324
+ try {
325
+ theirPublic = ed25519PublicKeyToX25519(ephemeralPublicKey);
326
+ }
327
+ catch {
328
+ theirPublic = ephemeralPublicKey; // already X25519
329
+ }
330
+ const sharedSecret = nacl.scalarMult(myX25519Private, theirPublic);
331
+ const key = kdfSHA512_256(sharedSecret);
332
+ const combined = Buffer.from(encryptedBlob, "base64");
333
+ const nonce = combined.slice(0, 24);
334
+ const ciphertext = combined.slice(24);
335
+ const decrypted = nacl.secretbox.open(new Uint8Array(ciphertext), new Uint8Array(nonce), key);
336
+ if (!decrypted) {
337
+ throw new Error("decryptBlindMailboxNote: decryption failed — wrong key or corrupted blob");
338
+ }
339
+ const parsed = JSON.parse(new TextDecoder().decode(decrypted));
340
+ const hexToBytes = (hex) => {
341
+ const out = new Uint8Array(hex.length / 2);
342
+ for (let i = 0; i < hex.length; i += 2)
343
+ out[i / 2] = parseInt(hex.slice(i, i + 2), 16);
344
+ return out;
345
+ };
346
+ return {
347
+ blinding: hexToBytes(parsed.blinding),
348
+ leafIndex: parsed.leafIndex,
349
+ commitment: hexToBytes(parsed.commitment),
350
+ amount: BigInt(parsed.amount),
351
+ timestamp: parsed.timestamp ?? 0,
352
+ mintAddress: parsed.mintAddress,
353
+ treeId: parsed.treeId,
354
+ };
355
+ }
356
+ /**
357
+ * Fetch all encrypted notes for a wallet from the relayer's Blind Mailbox endpoint
358
+ * and decrypt them using the wallet's secret key.
359
+ *
360
+ * @param walletPublicKey Base58 wallet address used to query the relayer
361
+ * @param walletSecretKey Full 64-byte keypair.secretKey for decryption
362
+ * @param relayerUrl Relayer base URL (e.g. "https://relay.veilo.app")
363
+ */
364
+ export async function fetchAndDecryptNotes(walletPublicKey, walletSecretKey, relayerUrl) {
365
+ const resp = await fetch(`${relayerUrl}/api/notes?recipientPublicKey=${walletPublicKey}`);
366
+ if (!resp.ok) {
367
+ throw new Error(`fetchAndDecryptNotes: ${resp.status} ${resp.statusText}`);
368
+ }
369
+ const { notes } = (await resp.json());
370
+ const results = [];
371
+ for (const note of notes) {
372
+ try {
373
+ const epk = Buffer.from(note.ephemeralPublicKey, "base64");
374
+ const decrypted = decryptBlindMailboxNote(walletSecretKey, new Uint8Array(epk), note.encryptedBlob);
375
+ results.push(decrypted);
376
+ }
377
+ catch {
378
+ // Note not for this key or corrupted — skip silently
379
+ }
380
+ }
381
+ return results;
382
+ }