privacycash 1.0.6

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 (56) hide show
  1. package/.github/workflows/npm-publish.yml +67 -0
  2. package/README.md +22 -0
  3. package/__tests__/e2e.test.ts +52 -0
  4. package/__tests__/encryption.test.ts +1635 -0
  5. package/circuit2/transaction2.wasm +0 -0
  6. package/circuit2/transaction2.zkey +0 -0
  7. package/dist/config.d.ts +7 -0
  8. package/dist/config.js +16 -0
  9. package/dist/deposit.d.ts +18 -0
  10. package/dist/deposit.js +402 -0
  11. package/dist/exportUtils.d.ts +6 -0
  12. package/dist/exportUtils.js +6 -0
  13. package/dist/getUtxos.d.ts +27 -0
  14. package/dist/getUtxos.js +352 -0
  15. package/dist/index.d.ts +61 -0
  16. package/dist/index.js +169 -0
  17. package/dist/models/keypair.d.ts +26 -0
  18. package/dist/models/keypair.js +43 -0
  19. package/dist/models/utxo.d.ts +49 -0
  20. package/dist/models/utxo.js +76 -0
  21. package/dist/utils/address_lookup_table.d.ts +8 -0
  22. package/dist/utils/address_lookup_table.js +21 -0
  23. package/dist/utils/constants.d.ts +14 -0
  24. package/dist/utils/constants.js +15 -0
  25. package/dist/utils/encryption.d.ts +107 -0
  26. package/dist/utils/encryption.js +374 -0
  27. package/dist/utils/logger.d.ts +9 -0
  28. package/dist/utils/logger.js +35 -0
  29. package/dist/utils/merkle_tree.d.ts +92 -0
  30. package/dist/utils/merkle_tree.js +186 -0
  31. package/dist/utils/node-shim.d.ts +5 -0
  32. package/dist/utils/node-shim.js +5 -0
  33. package/dist/utils/prover.d.ts +33 -0
  34. package/dist/utils/prover.js +123 -0
  35. package/dist/utils/utils.d.ts +67 -0
  36. package/dist/utils/utils.js +151 -0
  37. package/dist/withdraw.d.ts +21 -0
  38. package/dist/withdraw.js +270 -0
  39. package/package.json +48 -0
  40. package/src/config.ts +28 -0
  41. package/src/deposit.ts +496 -0
  42. package/src/exportUtils.ts +6 -0
  43. package/src/getUtxos.ts +466 -0
  44. package/src/index.ts +191 -0
  45. package/src/models/keypair.ts +52 -0
  46. package/src/models/utxo.ts +97 -0
  47. package/src/utils/address_lookup_table.ts +29 -0
  48. package/src/utils/constants.ts +26 -0
  49. package/src/utils/encryption.ts +461 -0
  50. package/src/utils/logger.ts +42 -0
  51. package/src/utils/merkle_tree.ts +207 -0
  52. package/src/utils/node-shim.ts +6 -0
  53. package/src/utils/prover.ts +189 -0
  54. package/src/utils/utils.ts +213 -0
  55. package/src/withdraw.ts +334 -0
  56. package/tsconfig.json +28 -0
@@ -0,0 +1,334 @@
1
+ import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, Transaction, TransactionInstruction, VersionedTransaction } from '@solana/web3.js';
2
+ import BN from 'bn.js';
3
+ import { Buffer } from 'buffer';
4
+ import { Keypair as UtxoKeypair } from './models/keypair.js';
5
+ import * as hasher from '@lightprotocol/hasher.rs';
6
+ import { Utxo } from './models/utxo.js';
7
+ import { parseProofToBytesArray, parseToBytesArray, prove } from './utils/prover.js';
8
+
9
+ import { ALT_ADDRESS, DEPLOYER_ID, FEE_RECIPIENT, FIELD_SIZE, INDEXER_API_URL, MERKLE_TREE_DEPTH, PROGRAM_ID } from './utils/constants.js';
10
+ import { EncryptionService, serializeProofAndExtData } from './utils/encryption.js';
11
+ import { fetchMerkleProof, findCommitmentPDAs, findNullifierPDAs, getExtDataHash, getProgramAccounts, queryRemoteTreeState, findCrossCheckNullifierPDAs } from './utils/utils.js';
12
+
13
+ import { getUtxos, isUtxoSpent } from './getUtxos.js';
14
+ import { logger } from './utils/logger.js';
15
+ import { getConfig } from './config.js';
16
+ // Indexer API endpoint
17
+
18
+
19
+ // Function to submit withdraw request to indexer backend
20
+ async function submitWithdrawToIndexer(params: any): Promise<string> {
21
+ try {
22
+
23
+ const response = await fetch(`${INDEXER_API_URL}/withdraw`, {
24
+ method: 'POST',
25
+ headers: {
26
+ 'Content-Type': 'application/json',
27
+ },
28
+ body: JSON.stringify(params)
29
+ });
30
+
31
+ if (!response.ok) {
32
+ const errorData = await response.json() as { error?: string };
33
+ throw new Error(errorData.error)
34
+ }
35
+
36
+ const result = await response.json() as { signature: string, success: boolean };
37
+ logger.debug('Withdraw request submitted successfully!');
38
+ logger.debug('Response:', result);
39
+
40
+ return result.signature;
41
+ } catch (error) {
42
+ logger.debug('Failed to submit withdraw request to indexer:', typeof error, error);
43
+ throw error;
44
+ }
45
+ }
46
+
47
+ type WithdrawParams = {
48
+ publicKey: PublicKey,
49
+ connection: Connection,
50
+ amount_in_lamports: number,
51
+ keyBasePath: string,
52
+ encryptionService: EncryptionService,
53
+ lightWasm: hasher.LightWasm,
54
+ recipient: PublicKey,
55
+ storage: Storage
56
+ }
57
+
58
+ export async function withdraw({ recipient, lightWasm, storage, publicKey, connection, amount_in_lamports, encryptionService, keyBasePath }: WithdrawParams) {
59
+ let fee_in_lamports = amount_in_lamports * (await getConfig('withdraw_fee_rate')) + LAMPORTS_PER_SOL * (await getConfig('withdraw_rent_fee'))
60
+ amount_in_lamports -= fee_in_lamports
61
+ let isPartial = false
62
+
63
+ logger.debug('Encryption key generated from user keypair');
64
+
65
+ logger.debug(`Deployer wallet: ${DEPLOYER_ID.toString()}`);
66
+
67
+ const { treeAccount, treeTokenAccount, globalConfigAccount } = getProgramAccounts()
68
+
69
+ // Get current tree state
70
+ const { root, nextIndex: currentNextIndex } = await queryRemoteTreeState();
71
+ logger.debug(`Using tree root: ${root}`);
72
+ logger.debug(`New UTXOs will be inserted at indices: ${currentNextIndex} and ${currentNextIndex + 1}`);
73
+
74
+ // Generate a deterministic private key derived from the wallet keypair
75
+ const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
76
+
77
+ // Create a UTXO keypair that will be used for all inputs and outputs
78
+ const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
79
+ logger.debug('Using wallet-derived UTXO keypair for withdrawal');
80
+
81
+ // Generate a deterministic private key derived from the wallet keypair (V2)
82
+ const utxoPrivateKeyV2 = encryptionService.getUtxoPrivateKeyV2();
83
+ const utxoKeypairV2 = new UtxoKeypair(utxoPrivateKeyV2, lightWasm);
84
+
85
+ // Fetch existing UTXOs for this user
86
+ logger.debug('\nFetching existing UTXOs...');
87
+ const unspentUtxos = await getUtxos({ connection, publicKey, encryptionService, storage });
88
+ logger.debug(`Found ${unspentUtxos.length} total UTXOs`);
89
+
90
+ // Calculate and log total unspent UTXO balance
91
+ const totalUnspentBalance = unspentUtxos.reduce((sum, utxo) => sum.add(utxo.amount), new BN(0));
92
+ logger.debug(`Total unspent UTXO balance before: ${totalUnspentBalance.toString()} lamports (${totalUnspentBalance.toNumber() / 1e9} SOL)`);
93
+
94
+ if (unspentUtxos.length < 1) {
95
+ throw new Error('Need at least 1 unspent UTXO to perform a withdrawal');
96
+ }
97
+
98
+ // Sort UTXOs by amount in descending order to use the largest ones first
99
+ unspentUtxos.sort((a, b) => b.amount.cmp(a.amount));
100
+
101
+ // Use the largest UTXO as first input, and either second largest UTXO or dummy UTXO as second input
102
+ const firstInput = unspentUtxos[0];
103
+ const secondInput = unspentUtxos.length > 1 ? unspentUtxos[1] : new Utxo({
104
+ lightWasm,
105
+ keypair: utxoKeypair,
106
+ amount: '0'
107
+ });
108
+
109
+ const inputs = [firstInput, secondInput];
110
+ const totalInputAmount = firstInput.amount.add(secondInput.amount);
111
+ logger.debug(`Using UTXO with amount: ${firstInput.amount.toString()} and ${secondInput.amount.gt(new BN(0)) ? 'second UTXO with amount: ' + secondInput.amount.toString() : 'dummy UTXO'}`);
112
+ if (totalInputAmount.toNumber() === 0) {
113
+ throw new Error('no balance')
114
+ }
115
+ if (totalInputAmount.lt(new BN(amount_in_lamports + fee_in_lamports))) {
116
+ isPartial = true
117
+ amount_in_lamports = totalInputAmount.toNumber()
118
+ amount_in_lamports -= fee_in_lamports
119
+ }
120
+
121
+ // Calculate the change amount (what's left after withdrawal and fee)
122
+ const changeAmount = totalInputAmount.sub(new BN(amount_in_lamports)).sub(new BN(fee_in_lamports));
123
+ logger.debug(`Withdrawing ${amount_in_lamports} lamports with ${fee_in_lamports} fee, ${changeAmount.toString()} as change`);
124
+
125
+ // Get Merkle proofs for both input UTXOs
126
+ const inputMerkleProofs = await Promise.all(
127
+ inputs.map(async (utxo, index) => {
128
+ // For dummy UTXO (amount is 0), use a zero-filled proof
129
+ if (utxo.amount.eq(new BN(0))) {
130
+ return {
131
+ pathElements: [...new Array(MERKLE_TREE_DEPTH).fill("0")],
132
+ pathIndices: Array(MERKLE_TREE_DEPTH).fill(0)
133
+ };
134
+ }
135
+ // For real UTXOs, fetch the proof from API
136
+ const commitment = await utxo.getCommitment();
137
+ return fetchMerkleProof(commitment);
138
+ })
139
+ );
140
+
141
+ // Extract path elements and indices
142
+ const inputMerklePathElements = inputMerkleProofs.map(proof => proof.pathElements);
143
+ const inputMerklePathIndices = inputs.map(utxo => utxo.index || 0);
144
+
145
+ // Create outputs: first output is change, second is dummy (required by protocol)
146
+ const outputs = [
147
+ new Utxo({
148
+ lightWasm,
149
+ amount: changeAmount.toString(),
150
+ keypair: utxoKeypairV2,
151
+ index: currentNextIndex
152
+ }), // Change output
153
+ new Utxo({
154
+ lightWasm,
155
+ amount: '0',
156
+ keypair: utxoKeypairV2,
157
+ index: currentNextIndex + 1
158
+ }) // Empty UTXO
159
+ ];
160
+
161
+ // For withdrawals, extAmount is negative (funds leaving the system)
162
+ const extAmount = -amount_in_lamports;
163
+ const publicAmountForCircuit = new BN(extAmount).sub(new BN(fee_in_lamports)).add(FIELD_SIZE).mod(FIELD_SIZE);
164
+ logger.debug(`Public amount calculation: (${extAmount} - ${fee_in_lamports} + FIELD_SIZE) % FIELD_SIZE = ${publicAmountForCircuit.toString()}`);
165
+
166
+ // Verify this matches the circuit balance equation: sumIns + publicAmount = sumOuts
167
+ const sumIns = inputs.reduce((sum, input) => sum.add(input.amount), new BN(0));
168
+ const sumOuts = outputs.reduce((sum, output) => sum.add(output.amount), new BN(0));
169
+ logger.debug(`Circuit balance check: sumIns(${sumIns.toString()}) + publicAmount(${publicAmountForCircuit.toString()}) should equal sumOuts(${sumOuts.toString()})`);
170
+
171
+ // Convert to circuit-compatible format
172
+ const publicAmountCircuitResult = sumIns.add(publicAmountForCircuit).mod(FIELD_SIZE);
173
+ logger.debug(`Balance verification: ${sumIns.toString()} + ${publicAmountForCircuit.toString()} (mod FIELD_SIZE) = ${publicAmountCircuitResult.toString()}`);
174
+ logger.debug(`Expected sum of outputs: ${sumOuts.toString()}`);
175
+ logger.debug(`Balance equation satisfied: ${publicAmountCircuitResult.eq(sumOuts)}`);
176
+
177
+ // Generate nullifiers and commitments
178
+ const inputNullifiers = await Promise.all(inputs.map(x => x.getNullifier()));
179
+ const outputCommitments = await Promise.all(outputs.map(x => x.getCommitment()));
180
+
181
+ // Save original commitment and nullifier values for verification
182
+ logger.debug('\n=== UTXO VALIDATION ===');
183
+ logger.debug('Output 0 Commitment:', outputCommitments[0]);
184
+ logger.debug('Output 1 Commitment:', outputCommitments[1]);
185
+
186
+ // Encrypt the UTXO data using a compact format that includes the keypair
187
+ logger.debug('\nEncrypting UTXOs with keypair data...');
188
+ const encryptedOutput1 = encryptionService.encryptUtxo(outputs[0]);
189
+ const encryptedOutput2 = encryptionService.encryptUtxo(outputs[1]);
190
+
191
+ logger.debug(`\nOutput[0] (change):`);
192
+ await outputs[0].log();
193
+ logger.debug(`\nOutput[1] (empty):`);
194
+ await outputs[1].log();
195
+
196
+ logger.debug(`\nEncrypted output 1 size: ${encryptedOutput1.length} bytes`);
197
+ logger.debug(`Encrypted output 2 size: ${encryptedOutput2.length} bytes`);
198
+ logger.debug(`Total encrypted outputs size: ${encryptedOutput1.length + encryptedOutput2.length} bytes`);
199
+
200
+ // Test decryption to verify commitment values match
201
+ logger.debug('\n=== TESTING DECRYPTION ===');
202
+ logger.debug('Decrypting output 1 to verify commitment matches...');
203
+ const decryptedUtxo1 = await encryptionService.decryptUtxo(encryptedOutput1, lightWasm);
204
+ const decryptedCommitment1 = await decryptedUtxo1.getCommitment();
205
+ logger.debug('Original commitment:', outputCommitments[0]);
206
+ logger.debug('Decrypted commitment:', decryptedCommitment1);
207
+ logger.debug('Commitment matches:', outputCommitments[0] === decryptedCommitment1);
208
+
209
+ // Create the withdrawal ExtData with real encrypted outputs
210
+ const extData = {
211
+ // it can be any address
212
+ recipient,
213
+ extAmount: new BN(extAmount),
214
+ encryptedOutput1: encryptedOutput1,
215
+ encryptedOutput2: encryptedOutput2,
216
+ fee: new BN(fee_in_lamports),
217
+ feeRecipient: FEE_RECIPIENT,
218
+ mintAddress: inputs[0].mintAddress
219
+ };
220
+
221
+ // Calculate the extDataHash with the encrypted outputs
222
+ const calculatedExtDataHash = getExtDataHash(extData);
223
+
224
+ // Create the input for the proof generation
225
+ const input = {
226
+ // Common transaction data
227
+ root: root,
228
+ inputNullifier: inputNullifiers,
229
+ outputCommitment: outputCommitments,
230
+ publicAmount: publicAmountForCircuit.toString(),
231
+ extDataHash: calculatedExtDataHash,
232
+
233
+ // Input UTXO data (UTXOs being spent)
234
+ inAmount: inputs.map(x => x.amount.toString(10)),
235
+ inPrivateKey: inputs.map(x => x.keypair.privkey),
236
+ inBlinding: inputs.map(x => x.blinding.toString(10)),
237
+ inPathIndices: inputMerklePathIndices,
238
+ inPathElements: inputMerklePathElements,
239
+
240
+ // Output UTXO data (UTXOs being created)
241
+ outAmount: outputs.map(x => x.amount.toString(10)),
242
+ outBlinding: outputs.map(x => x.blinding.toString(10)),
243
+ outPubkey: outputs.map(x => x.keypair.pubkey),
244
+
245
+ // new mint address
246
+ mintAddress: inputs[0].mintAddress
247
+ };
248
+ logger.info('generating ZK proof...')
249
+
250
+ // Generate the zero-knowledge proof
251
+ const { proof, publicSignals } = await prove(input, keyBasePath);
252
+
253
+ // Parse the proof and public signals into byte arrays
254
+ const proofInBytes = parseProofToBytesArray(proof);
255
+ const inputsInBytes = parseToBytesArray(publicSignals);
256
+
257
+ // Create the proof object to submit to the program
258
+ const proofToSubmit = {
259
+ proofA: proofInBytes.proofA,
260
+ proofB: proofInBytes.proofB.flat(),
261
+ proofC: proofInBytes.proofC,
262
+ root: inputsInBytes[0],
263
+ publicAmount: inputsInBytes[1],
264
+ extDataHash: inputsInBytes[2],
265
+ inputNullifiers: [
266
+ inputsInBytes[3],
267
+ inputsInBytes[4]
268
+ ],
269
+ outputCommitments: [
270
+ inputsInBytes[5],
271
+ inputsInBytes[6]
272
+ ],
273
+ };
274
+
275
+ // Find PDAs for nullifiers and commitments
276
+ const { nullifier0PDA, nullifier1PDA } = findNullifierPDAs(proofToSubmit);
277
+ const { nullifier2PDA, nullifier3PDA } = findCrossCheckNullifierPDAs(proofToSubmit);
278
+ const { commitment0PDA, commitment1PDA } = findCommitmentPDAs(proofToSubmit);
279
+
280
+ // Serialize the proof and extData
281
+ const serializedProof = serializeProofAndExtData(proofToSubmit, extData);
282
+ logger.debug(`Total instruction data size: ${serializedProof.length} bytes`);
283
+
284
+ // Prepare withdraw parameters for indexer backend
285
+ const withdrawParams = {
286
+ serializedProof: serializedProof.toString('base64'),
287
+ treeAccount: treeAccount.toString(),
288
+ nullifier0PDA: nullifier0PDA.toString(),
289
+ nullifier1PDA: nullifier1PDA.toString(),
290
+ nullifier2PDA: nullifier2PDA.toString(),
291
+ nullifier3PDA: nullifier3PDA.toString(),
292
+ commitment0PDA: commitment0PDA.toString(),
293
+ commitment1PDA: commitment1PDA.toString(),
294
+ treeTokenAccount: treeTokenAccount.toString(),
295
+ globalConfigAccount: globalConfigAccount.toString(),
296
+ recipient: recipient.toString(),
297
+ feeRecipientAccount: FEE_RECIPIENT.toString(),
298
+ extAmount: extAmount,
299
+ encryptedOutput1: encryptedOutput1.toString('base64'),
300
+ encryptedOutput2: encryptedOutput2.toString('base64'),
301
+ fee: fee_in_lamports,
302
+ lookupTableAddress: ALT_ADDRESS.toString(),
303
+ senderAddress: publicKey.toString()
304
+ };
305
+
306
+
307
+ logger.debug('Prepared withdraw parameters for indexer backend');
308
+
309
+ // Submit to indexer backend instead of directly to Solana
310
+ logger.info('submitting transaction to relayer...')
311
+ const signature = await submitWithdrawToIndexer(withdrawParams);
312
+ // Wait a moment for the transaction to be confirmed
313
+ logger.info('waiting for transaction confirmation...')
314
+ let retryTimes = 0
315
+ let itv = 2
316
+ const encryptedOutputStr = Buffer.from(encryptedOutput1).toString('hex')
317
+ let start = Date.now()
318
+ while (true) {
319
+ console.log(`retryTimes: ${retryTimes}`)
320
+ await new Promise(resolve => setTimeout(resolve, itv * 1000));
321
+ console.log('Fetching updated tree state...');
322
+ let res = await fetch(INDEXER_API_URL + '/utxos/check/' + encryptedOutputStr)
323
+ let resJson = await res.json()
324
+ console.log('resJson:', resJson)
325
+ if (resJson.exists) {
326
+ return { isPartial, tx: signature, recipient: recipient.toString(), amount_in_lamports, fee_in_lamports }
327
+ }
328
+ if (retryTimes >= 10) {
329
+ throw new Error('Refresh the page to see latest balance.')
330
+ }
331
+ retryTimes++
332
+ }
333
+
334
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "es2022",
5
+ "strict": true,
6
+ "esModuleInterop": true,
7
+ "resolveJsonModule": true,
8
+ "isolatedModules": true,
9
+ "allowImportingTsExtensions": false,
10
+ "noEmit": false,
11
+ "allowSyntheticDefaultImports": true,
12
+ "forceConsistentCasingInFileNames": true,
13
+ "outDir": "dist",
14
+ "declaration": true,
15
+ "moduleResolution": "node",
16
+ "lib": [
17
+ "ES2022",
18
+ "DOM"
19
+ ],
20
+ },
21
+ "include": [
22
+ "src"
23
+ ],
24
+ "exclude": [
25
+ "node_modules",
26
+ "dist"
27
+ ]
28
+ }