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.
- package/.github/workflows/npm-publish.yml +67 -0
- package/README.md +22 -0
- package/__tests__/e2e.test.ts +52 -0
- package/__tests__/encryption.test.ts +1635 -0
- package/circuit2/transaction2.wasm +0 -0
- package/circuit2/transaction2.zkey +0 -0
- package/dist/config.d.ts +7 -0
- package/dist/config.js +16 -0
- package/dist/deposit.d.ts +18 -0
- package/dist/deposit.js +402 -0
- package/dist/exportUtils.d.ts +6 -0
- package/dist/exportUtils.js +6 -0
- package/dist/getUtxos.d.ts +27 -0
- package/dist/getUtxos.js +352 -0
- package/dist/index.d.ts +61 -0
- package/dist/index.js +169 -0
- package/dist/models/keypair.d.ts +26 -0
- package/dist/models/keypair.js +43 -0
- package/dist/models/utxo.d.ts +49 -0
- package/dist/models/utxo.js +76 -0
- package/dist/utils/address_lookup_table.d.ts +8 -0
- package/dist/utils/address_lookup_table.js +21 -0
- package/dist/utils/constants.d.ts +14 -0
- package/dist/utils/constants.js +15 -0
- package/dist/utils/encryption.d.ts +107 -0
- package/dist/utils/encryption.js +374 -0
- package/dist/utils/logger.d.ts +9 -0
- package/dist/utils/logger.js +35 -0
- package/dist/utils/merkle_tree.d.ts +92 -0
- package/dist/utils/merkle_tree.js +186 -0
- package/dist/utils/node-shim.d.ts +5 -0
- package/dist/utils/node-shim.js +5 -0
- package/dist/utils/prover.d.ts +33 -0
- package/dist/utils/prover.js +123 -0
- package/dist/utils/utils.d.ts +67 -0
- package/dist/utils/utils.js +151 -0
- package/dist/withdraw.d.ts +21 -0
- package/dist/withdraw.js +270 -0
- package/package.json +48 -0
- package/src/config.ts +28 -0
- package/src/deposit.ts +496 -0
- package/src/exportUtils.ts +6 -0
- package/src/getUtxos.ts +466 -0
- package/src/index.ts +191 -0
- package/src/models/keypair.ts +52 -0
- package/src/models/utxo.ts +97 -0
- package/src/utils/address_lookup_table.ts +29 -0
- package/src/utils/constants.ts +26 -0
- package/src/utils/encryption.ts +461 -0
- package/src/utils/logger.ts +42 -0
- package/src/utils/merkle_tree.ts +207 -0
- package/src/utils/node-shim.ts +6 -0
- package/src/utils/prover.ts +189 -0
- package/src/utils/utils.ts +213 -0
- package/src/withdraw.ts +334 -0
- package/tsconfig.json +28 -0
package/src/getUtxos.ts
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';
|
|
2
|
+
import BN from 'bn.js';
|
|
3
|
+
import { Keypair as UtxoKeypair } from './models/keypair.js';
|
|
4
|
+
import { Utxo } from './models/utxo.js';
|
|
5
|
+
import { EncryptionService } from './utils/encryption.js';
|
|
6
|
+
import { WasmFactory } from '@lightprotocol/hasher.rs';
|
|
7
|
+
//@ts-ignore
|
|
8
|
+
import * as ffjavascript from 'ffjavascript';
|
|
9
|
+
import { FETCH_UTXOS_GROUP_SIZE, INDEXER_API_URL, LSK_ENCRYPTED_OUTPUTS, LSK_FETCH_OFFSET, PROGRAM_ID } from './utils/constants.js';
|
|
10
|
+
import { logger } from './utils/logger.js';
|
|
11
|
+
|
|
12
|
+
// Use type assertion for the utility functions (same pattern as in get_verification_keys.ts)
|
|
13
|
+
const utils = ffjavascript.utils as any;
|
|
14
|
+
const { unstringifyBigInts, leInt2Buff } = utils;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Interface for the UTXO data returned from the API
|
|
18
|
+
*/
|
|
19
|
+
interface ApiUtxo {
|
|
20
|
+
commitment: string;
|
|
21
|
+
encrypted_output: string; // Hex-encoded encrypted UTXO data
|
|
22
|
+
index: number;
|
|
23
|
+
nullifier?: string; // Optional, might not be present for all UTXOs
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Interface for the API response format that includes count and encrypted_outputs
|
|
28
|
+
*/
|
|
29
|
+
interface ApiResponse {
|
|
30
|
+
count: number;
|
|
31
|
+
encrypted_outputs: string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function sleep(ms: number): Promise<string> {
|
|
35
|
+
return new Promise(resolve => setTimeout(() => {
|
|
36
|
+
resolve('ok')
|
|
37
|
+
}, ms))
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function localstorageKey(key: PublicKey) {
|
|
41
|
+
return PROGRAM_ID.toString().substring(0, 6) + key.toString()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
let getMyUtxosPromise: Promise<Utxo[]> | null = null
|
|
45
|
+
let roundStartIndex = 0
|
|
46
|
+
let decryptionTaskFinished = 0;
|
|
47
|
+
/**
|
|
48
|
+
* Fetch and decrypt all UTXOs for a user
|
|
49
|
+
* @param signed The user's signature
|
|
50
|
+
* @param connection Solana connection to fetch on-chain commitment accounts
|
|
51
|
+
* @param setStatus A global state updator. Set live status message showing on webpage
|
|
52
|
+
* @returns Array of decrypted UTXOs that belong to the user
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
export async function getUtxos({ publicKey, connection, encryptionService, storage }: {
|
|
56
|
+
publicKey: PublicKey,
|
|
57
|
+
connection: Connection,
|
|
58
|
+
encryptionService: EncryptionService,
|
|
59
|
+
storage: Storage
|
|
60
|
+
}): Promise<Utxo[]> {
|
|
61
|
+
if (!getMyUtxosPromise) {
|
|
62
|
+
getMyUtxosPromise = (async () => {
|
|
63
|
+
let valid_utxos: Utxo[] = []
|
|
64
|
+
let valid_strings: string[] = []
|
|
65
|
+
try {
|
|
66
|
+
let offsetStr = storage.getItem(LSK_FETCH_OFFSET + localstorageKey(publicKey))
|
|
67
|
+
if (offsetStr) {
|
|
68
|
+
roundStartIndex = Number(offsetStr)
|
|
69
|
+
} else {
|
|
70
|
+
roundStartIndex = 0
|
|
71
|
+
}
|
|
72
|
+
decryptionTaskFinished = 0
|
|
73
|
+
while (true) {
|
|
74
|
+
let offsetStr = storage.getItem(LSK_FETCH_OFFSET + localstorageKey(publicKey))
|
|
75
|
+
let fetch_utxo_offset = offsetStr ? Number(offsetStr) : 0
|
|
76
|
+
let fetch_utxo_end = fetch_utxo_offset + FETCH_UTXOS_GROUP_SIZE
|
|
77
|
+
let fetch_utxo_url = `${INDEXER_API_URL}/utxos/range?start=${fetch_utxo_offset}&end=${fetch_utxo_end}`
|
|
78
|
+
let fetched = await fetchUserUtxos({ publicKey, connection, url: fetch_utxo_url, encryptionService, storage })
|
|
79
|
+
let am = 0
|
|
80
|
+
|
|
81
|
+
const nonZeroUtxos: Utxo[] = [];
|
|
82
|
+
const nonZeroEncrypted: any[] = [];
|
|
83
|
+
for (let [k, utxo] of fetched.utxos.entries()) {
|
|
84
|
+
if (utxo.amount.toNumber() > 0) {
|
|
85
|
+
nonZeroUtxos.push(utxo);
|
|
86
|
+
nonZeroEncrypted.push(fetched.encryptedOutputs[k]);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (nonZeroUtxos.length > 0) {
|
|
90
|
+
const spentFlags = await areUtxosSpent(connection, nonZeroUtxos);
|
|
91
|
+
for (let i = 0; i < nonZeroUtxos.length; i++) {
|
|
92
|
+
if (!spentFlags[i]) {
|
|
93
|
+
am += nonZeroUtxos[i].amount.toNumber();
|
|
94
|
+
valid_utxos.push(nonZeroUtxos[i]);
|
|
95
|
+
valid_strings.push(nonZeroEncrypted[i]);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
storage.setItem(LSK_FETCH_OFFSET + localstorageKey(publicKey), (fetch_utxo_offset + fetched.len).toString())
|
|
100
|
+
if (!fetched.hasMore) {
|
|
101
|
+
break
|
|
102
|
+
}
|
|
103
|
+
await sleep(100)
|
|
104
|
+
}
|
|
105
|
+
} catch (e: any) {
|
|
106
|
+
throw e
|
|
107
|
+
} finally {
|
|
108
|
+
getMyUtxosPromise = null
|
|
109
|
+
}
|
|
110
|
+
// store valid strings
|
|
111
|
+
valid_strings = [...new Set(valid_strings)];
|
|
112
|
+
storage.setItem(LSK_ENCRYPTED_OUTPUTS + localstorageKey(publicKey), JSON.stringify(valid_strings))
|
|
113
|
+
return valid_utxos
|
|
114
|
+
})()
|
|
115
|
+
}
|
|
116
|
+
return getMyUtxosPromise
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function fetchUserUtxos({ publicKey, connection, url, storage, encryptionService }: {
|
|
120
|
+
publicKey: PublicKey,
|
|
121
|
+
connection: Connection,
|
|
122
|
+
url: string,
|
|
123
|
+
encryptionService: EncryptionService,
|
|
124
|
+
storage: Storage
|
|
125
|
+
}): Promise<{
|
|
126
|
+
encryptedOutputs: string[],
|
|
127
|
+
utxos: Utxo[],
|
|
128
|
+
hasMore: boolean,
|
|
129
|
+
len: number
|
|
130
|
+
}> {
|
|
131
|
+
const lightWasm = await WasmFactory.getInstance();
|
|
132
|
+
|
|
133
|
+
// Derive the UTXO keypair from the wallet keypair
|
|
134
|
+
const utxoPrivateKey = encryptionService.deriveUtxoPrivateKey();
|
|
135
|
+
const utxoKeypair = new UtxoKeypair(utxoPrivateKey, lightWasm);
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
// Fetch all UTXOs from the API
|
|
139
|
+
let encryptedOutputs: string[] = [];
|
|
140
|
+
logger.debug('fetching utxo data', url)
|
|
141
|
+
let res = await fetch(url)
|
|
142
|
+
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
|
|
143
|
+
const data: any = await res.json()
|
|
144
|
+
logger.debug('got utxo data')
|
|
145
|
+
if (!data) {
|
|
146
|
+
throw new Error('API returned empty data')
|
|
147
|
+
} else if (Array.isArray(data)) {
|
|
148
|
+
// Handle the case where the API returns an array of UTXOs
|
|
149
|
+
const utxos: ApiUtxo[] = data;
|
|
150
|
+
// Extract encrypted outputs from the array of UTXOs
|
|
151
|
+
encryptedOutputs = utxos
|
|
152
|
+
.filter(utxo => utxo.encrypted_output)
|
|
153
|
+
.map(utxo => utxo.encrypted_output);
|
|
154
|
+
} else if (typeof data === 'object' && data.encrypted_outputs) {
|
|
155
|
+
// Handle the case where the API returns an object with encrypted_outputs array
|
|
156
|
+
const apiResponse = data as ApiResponse;
|
|
157
|
+
encryptedOutputs = apiResponse.encrypted_outputs;
|
|
158
|
+
} else {
|
|
159
|
+
throw new Error(`API returned unexpected data format: ${JSON.stringify(data).substring(0, 100)}...`);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Try to decrypt each encrypted output
|
|
163
|
+
const myUtxos: Utxo[] = [];
|
|
164
|
+
const myEncryptedOutputs: string[] = [];
|
|
165
|
+
let decryptionAttempts = 0;
|
|
166
|
+
let successfulDecryptions = 0;
|
|
167
|
+
|
|
168
|
+
let cachedStringNum = 0
|
|
169
|
+
let cachedString = storage.getItem(LSK_ENCRYPTED_OUTPUTS + localstorageKey(publicKey))
|
|
170
|
+
if (cachedString) {
|
|
171
|
+
cachedStringNum = JSON.parse(cachedString).length
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
let decryptionTaskTotal = data.total + cachedStringNum - roundStartIndex;
|
|
176
|
+
let batchRes = await decrypt_outputs(encryptedOutputs, encryptionService, utxoKeypair, lightWasm)
|
|
177
|
+
decryptionTaskFinished += encryptedOutputs.length
|
|
178
|
+
logger.debug('batchReslen', batchRes.length)
|
|
179
|
+
for (let i = 0; i < batchRes.length; i++) {
|
|
180
|
+
let dres = batchRes[i]
|
|
181
|
+
if (dres.status == 'decrypted' && dres.utxo) {
|
|
182
|
+
myUtxos.push(dres.utxo)
|
|
183
|
+
myEncryptedOutputs.push(dres.encryptedOutput!)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
logger.info(`(decrypting cached utxo: ${decryptionTaskFinished + 1}/${decryptionTaskTotal}...)`)
|
|
187
|
+
// check cached string when no more fetching tasks
|
|
188
|
+
if (!data.hasMore) {
|
|
189
|
+
if (cachedString) {
|
|
190
|
+
let cachedEncryptedOutputs = JSON.parse(cachedString)
|
|
191
|
+
for (let encryptedOutput of cachedEncryptedOutputs) {
|
|
192
|
+
if (decryptionTaskFinished % 100 == 0) {
|
|
193
|
+
logger.info(`(decrypting cached utxo: ${decryptionTaskFinished + 1}/${decryptionTaskTotal}...)`)
|
|
194
|
+
}
|
|
195
|
+
let batchRes = await decrypt_outputs(cachedEncryptedOutputs, encryptionService, utxoKeypair, lightWasm)
|
|
196
|
+
decryptionTaskFinished += cachedEncryptedOutputs.length
|
|
197
|
+
logger.debug('cachedbatchReslen', batchRes.length, ' source', cachedEncryptedOutputs.length)
|
|
198
|
+
for (let i = 0; i < batchRes.length; i++) {
|
|
199
|
+
let dres = batchRes[i]
|
|
200
|
+
if (dres.status == 'decrypted' && dres.utxo) {
|
|
201
|
+
myUtxos.push(dres.utxo)
|
|
202
|
+
myEncryptedOutputs.push(dres.encryptedOutput!)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
return { encryptedOutputs: myEncryptedOutputs, utxos: myUtxos, hasMore: data.hasMore, len: encryptedOutputs.length };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Check if a UTXO has been spent
|
|
214
|
+
* @param connection Solana connection
|
|
215
|
+
* @param utxo The UTXO to check
|
|
216
|
+
* @returns Promise<boolean> true if spent, false if unspent
|
|
217
|
+
*/
|
|
218
|
+
export async function isUtxoSpent(connection: Connection, utxo: Utxo): Promise<boolean> {
|
|
219
|
+
try {
|
|
220
|
+
// Get the nullifier for this UTXO
|
|
221
|
+
const nullifier = await utxo.getNullifier();
|
|
222
|
+
logger.debug(`Checking if UTXO with nullifier ${nullifier} is spent`);
|
|
223
|
+
|
|
224
|
+
// Convert decimal nullifier string to byte array (same format as in proofs)
|
|
225
|
+
// This matches how commitments are handled and how the Rust code expects the seeds
|
|
226
|
+
const nullifierBytes = Array.from(
|
|
227
|
+
leInt2Buff(unstringifyBigInts(nullifier), 32)
|
|
228
|
+
).reverse() as number[];
|
|
229
|
+
|
|
230
|
+
// Try nullifier0 seed
|
|
231
|
+
const [nullifier0PDA] = PublicKey.findProgramAddressSync(
|
|
232
|
+
[Buffer.from("nullifier0"), Buffer.from(nullifierBytes)],
|
|
233
|
+
PROGRAM_ID
|
|
234
|
+
);
|
|
235
|
+
|
|
236
|
+
logger.debug(`Derived nullifier0 PDA: ${nullifier0PDA.toBase58()}`);
|
|
237
|
+
const nullifier0Account = await connection.getAccountInfo(nullifier0PDA);
|
|
238
|
+
if (nullifier0Account !== null) {
|
|
239
|
+
logger.debug(`UTXO is spent (nullifier0 account exists)`);
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
const [nullifier1PDA] = PublicKey.findProgramAddressSync(
|
|
245
|
+
[Buffer.from("nullifier1"), Buffer.from(nullifierBytes)],
|
|
246
|
+
PROGRAM_ID
|
|
247
|
+
);
|
|
248
|
+
|
|
249
|
+
logger.debug(`Derived nullifier1 PDA: ${nullifier1PDA.toBase58()}`);
|
|
250
|
+
const nullifier1Account = await connection.getAccountInfo(nullifier1PDA);
|
|
251
|
+
if (nullifier1Account !== null) {
|
|
252
|
+
logger.debug(`UTXO is spent (nullifier1 account exists)`);
|
|
253
|
+
return true
|
|
254
|
+
}
|
|
255
|
+
return false;
|
|
256
|
+
} catch (error: any) {
|
|
257
|
+
console.error('Error checking if UTXO is spent:', error);
|
|
258
|
+
await new Promise(resolve => setTimeout(resolve, 3000));
|
|
259
|
+
return await isUtxoSpent(connection, utxo)
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async function areUtxosSpent(
|
|
264
|
+
connection: Connection,
|
|
265
|
+
utxos: Utxo[]
|
|
266
|
+
): Promise<boolean[]> {
|
|
267
|
+
try {
|
|
268
|
+
const allPDAs: { utxoIndex: number; pda: PublicKey }[] = [];
|
|
269
|
+
|
|
270
|
+
for (let i = 0; i < utxos.length; i++) {
|
|
271
|
+
const utxo = utxos[i];
|
|
272
|
+
const nullifier = await utxo.getNullifier();
|
|
273
|
+
|
|
274
|
+
const nullifierBytes = Array.from(
|
|
275
|
+
leInt2Buff(unstringifyBigInts(nullifier), 32)
|
|
276
|
+
).reverse() as number[];
|
|
277
|
+
|
|
278
|
+
const [nullifier0PDA] = PublicKey.findProgramAddressSync(
|
|
279
|
+
[Buffer.from("nullifier0"), Buffer.from(nullifierBytes)],
|
|
280
|
+
PROGRAM_ID
|
|
281
|
+
);
|
|
282
|
+
const [nullifier1PDA] = PublicKey.findProgramAddressSync(
|
|
283
|
+
[Buffer.from("nullifier1"), Buffer.from(nullifierBytes)],
|
|
284
|
+
PROGRAM_ID
|
|
285
|
+
);
|
|
286
|
+
|
|
287
|
+
allPDAs.push({ utxoIndex: i, pda: nullifier0PDA });
|
|
288
|
+
allPDAs.push({ utxoIndex: i, pda: nullifier1PDA });
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const results: any[] =
|
|
292
|
+
await connection.getMultipleAccountsInfo(allPDAs.map((x) => x.pda));
|
|
293
|
+
|
|
294
|
+
const spentFlags = new Array(utxos.length).fill(false);
|
|
295
|
+
for (let i = 0; i < allPDAs.length; i++) {
|
|
296
|
+
if (results[i] !== null) {
|
|
297
|
+
spentFlags[allPDAs[i].utxoIndex] = true;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return spentFlags;
|
|
302
|
+
} catch (error: any) {
|
|
303
|
+
console.error("Error checking if UTXOs are spent:", error);
|
|
304
|
+
await new Promise((resolve) => setTimeout(resolve, 3000));
|
|
305
|
+
return await areUtxosSpent(connection, utxos);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Calculate total balance
|
|
310
|
+
export function getBalanceFromUtxos(utxos: Utxo[]) {
|
|
311
|
+
const totalBalance = utxos.reduce((sum, utxo) => sum.add(utxo.amount), new BN(0));
|
|
312
|
+
// const LAMPORTS_PER_SOL = new BN(1_000_000_000);
|
|
313
|
+
// const balanceInSol = totalBalance.div(LAMPORTS_PER_SOL);
|
|
314
|
+
// const remainderLamports = totalBalance.mod(LAMPORTS_PER_SOL);
|
|
315
|
+
return { lamports: totalBalance.toNumber() }
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Decrypt single output to Utxo
|
|
319
|
+
type DecryptRes = { status: 'decrypted' | 'skipped' | 'unDecrypted', utxo?: Utxo, encryptedOutput?: string }
|
|
320
|
+
async function decrypt_output(
|
|
321
|
+
encryptedOutput: string,
|
|
322
|
+
encryptionService: EncryptionService,
|
|
323
|
+
utxoKeypair: UtxoKeypair,
|
|
324
|
+
lightWasm: any,
|
|
325
|
+
connection: Connection
|
|
326
|
+
): Promise<DecryptRes> {
|
|
327
|
+
let res: DecryptRes = { status: 'unDecrypted' }
|
|
328
|
+
try {
|
|
329
|
+
if (!encryptedOutput) {
|
|
330
|
+
return { status: 'skipped' }
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Try to decrypt the UTXO
|
|
334
|
+
res.utxo = await encryptionService.decryptUtxo(
|
|
335
|
+
encryptedOutput,
|
|
336
|
+
lightWasm
|
|
337
|
+
);
|
|
338
|
+
|
|
339
|
+
// If we got here, decryption succeeded, so this UTXO belongs to the user
|
|
340
|
+
res.status = 'decrypted'
|
|
341
|
+
|
|
342
|
+
// Get the real index from the on-chain commitment account
|
|
343
|
+
try {
|
|
344
|
+
if (!res.utxo) {
|
|
345
|
+
throw new Error('res.utxo undefined')
|
|
346
|
+
}
|
|
347
|
+
const commitment = await res.utxo.getCommitment();
|
|
348
|
+
// Convert decimal commitment string to byte array (same format as in proofs)
|
|
349
|
+
const commitmentBytes = Array.from(
|
|
350
|
+
leInt2Buff(unstringifyBigInts(commitment), 32)
|
|
351
|
+
).reverse() as number[];
|
|
352
|
+
|
|
353
|
+
// Derive the commitment PDA (could be either commitment0 or commitment1)
|
|
354
|
+
// We'll try both seeds since we don't know which one it is
|
|
355
|
+
let commitmentAccount = null;
|
|
356
|
+
let realIndex = null;
|
|
357
|
+
// Try commitment0 seed
|
|
358
|
+
try {
|
|
359
|
+
const [commitment0PDA] = PublicKey.findProgramAddressSync(
|
|
360
|
+
[Buffer.from("commitment0"), Buffer.from(commitmentBytes)],
|
|
361
|
+
PROGRAM_ID
|
|
362
|
+
);
|
|
363
|
+
|
|
364
|
+
const account0Info = await connection.getAccountInfo(commitment0PDA);
|
|
365
|
+
if (account0Info) {
|
|
366
|
+
// Parse the index from the account data according to CommitmentAccount structure:
|
|
367
|
+
// 0-8: Anchor discriminator
|
|
368
|
+
// 8-40: commitment (32 bytes)
|
|
369
|
+
// 40-44: encrypted_output length (4 bytes)
|
|
370
|
+
// 44-44+len: encrypted_output data
|
|
371
|
+
// 44+len-52+len: index (8 bytes)
|
|
372
|
+
const encryptedOutputLength = account0Info.data.readUInt32LE(40);
|
|
373
|
+
const indexOffset = 44 + encryptedOutputLength;
|
|
374
|
+
const indexBytes = account0Info.data.slice(indexOffset, indexOffset + 8);
|
|
375
|
+
realIndex = new BN(indexBytes, 'le').toNumber();
|
|
376
|
+
}
|
|
377
|
+
} catch (e) {
|
|
378
|
+
// Try commitment1 seed if commitment0 fails
|
|
379
|
+
try {
|
|
380
|
+
const [commitment1PDA] = PublicKey.findProgramAddressSync(
|
|
381
|
+
[Buffer.from("commitment1"), Buffer.from(commitmentBytes)],
|
|
382
|
+
PROGRAM_ID
|
|
383
|
+
);
|
|
384
|
+
|
|
385
|
+
const account1Info = await connection.getAccountInfo(commitment1PDA);
|
|
386
|
+
if (account1Info) {
|
|
387
|
+
// Parse the index from the account data according to CommitmentAccount structure
|
|
388
|
+
const encryptedOutputLength = account1Info.data.readUInt32LE(40);
|
|
389
|
+
const indexOffset = 44 + encryptedOutputLength;
|
|
390
|
+
const indexBytes = account1Info.data.slice(indexOffset, indexOffset + 8);
|
|
391
|
+
realIndex = new BN(indexBytes, 'le').toNumber();
|
|
392
|
+
logger.debug(`Found commitment1 account with index: ${realIndex}`);
|
|
393
|
+
}
|
|
394
|
+
} catch (e2) {
|
|
395
|
+
logger.debug(`Could not find commitment account for ${commitment}, using encrypted index: ${res.utxo.index}`);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// Update the UTXO with the real index if we found it
|
|
400
|
+
if (realIndex !== null) {
|
|
401
|
+
const oldIndex = res.utxo.index;
|
|
402
|
+
res.utxo.index = realIndex;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
} catch (error: any) {
|
|
406
|
+
logger.debug(`Failed to get real index for UTXO: ${error.message}`);
|
|
407
|
+
}
|
|
408
|
+
} catch (error: any) {
|
|
409
|
+
// this UTXO doesn't belong to the user
|
|
410
|
+
}
|
|
411
|
+
return res
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function decrypt_outputs(
|
|
415
|
+
encryptedOutputs: string[],
|
|
416
|
+
encryptionService: EncryptionService,
|
|
417
|
+
utxoKeypair: UtxoKeypair,
|
|
418
|
+
lightWasm: any,
|
|
419
|
+
): Promise<DecryptRes[]> {
|
|
420
|
+
let results: DecryptRes[] = [];
|
|
421
|
+
|
|
422
|
+
// decript all UTXO
|
|
423
|
+
for (const encryptedOutput of encryptedOutputs) {
|
|
424
|
+
if (!encryptedOutput) {
|
|
425
|
+
results.push({ status: 'skipped' });
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
try {
|
|
429
|
+
const utxo = await encryptionService.decryptUtxo(
|
|
430
|
+
encryptedOutput,
|
|
431
|
+
lightWasm
|
|
432
|
+
);
|
|
433
|
+
results.push({ status: 'decrypted', utxo, encryptedOutput });
|
|
434
|
+
} catch {
|
|
435
|
+
results.push({ status: 'unDecrypted' });
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
results = results.filter(r => r.status == 'decrypted')
|
|
439
|
+
if (!results.length) {
|
|
440
|
+
return []
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// update utxo index
|
|
444
|
+
if (results.length > 0) {
|
|
445
|
+
let encrypted_outputs = results.map(r => r.encryptedOutput)
|
|
446
|
+
|
|
447
|
+
let url = INDEXER_API_URL + `/utxos/indices`
|
|
448
|
+
let res = await fetch(url, {
|
|
449
|
+
method: 'POST', headers: { "Content-Type": "application/json" },
|
|
450
|
+
body: JSON.stringify({ encrypted_outputs })
|
|
451
|
+
})
|
|
452
|
+
let j = await res.json()
|
|
453
|
+
if (!j.indices || !Array.isArray(j.indices) || j.indices.length != encrypted_outputs.length) {
|
|
454
|
+
throw new Error('failed fetching /utxos/indices')
|
|
455
|
+
}
|
|
456
|
+
for (let i = 0; i < results.length; i++) {
|
|
457
|
+
let utxo = results[i].utxo
|
|
458
|
+
if (utxo!.index !== j.indices[i] && typeof j.indices[i] == 'number') {
|
|
459
|
+
logger.debug(`Updated UTXO index from ${utxo!.index} to ${j.indices[i]}`);
|
|
460
|
+
utxo!.index = j.indices[i]
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
return results;
|
|
466
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey, VersionedTransaction } from '@solana/web3.js';
|
|
2
|
+
import { deposit } from './deposit.js';
|
|
3
|
+
import { getBalanceFromUtxos, getUtxos, localstorageKey } from './getUtxos.js';
|
|
4
|
+
|
|
5
|
+
import { LSK_ENCRYPTED_OUTPUTS, LSK_FETCH_OFFSET } from './utils/constants.js';
|
|
6
|
+
import { logger, type LoggerFn, setLogger } from './utils/logger.js';
|
|
7
|
+
import { EncryptionService } from './utils/encryption.js';
|
|
8
|
+
import { WasmFactory } from '@lightprotocol/hasher.rs';
|
|
9
|
+
import bs58 from 'bs58'
|
|
10
|
+
import { withdraw } from './withdraw.js';
|
|
11
|
+
import { LocalStorage } from "node-localstorage";
|
|
12
|
+
import path from 'node:path'
|
|
13
|
+
|
|
14
|
+
let storage = new LocalStorage(path.join(process.cwd(), "cache"));
|
|
15
|
+
|
|
16
|
+
export class PrivacyCash {
|
|
17
|
+
private connection: Connection
|
|
18
|
+
public publicKey: PublicKey
|
|
19
|
+
private encryptionService: EncryptionService
|
|
20
|
+
private keypair: Keypair
|
|
21
|
+
private isRuning?: boolean = false
|
|
22
|
+
private status: string = ''
|
|
23
|
+
constructor({ RPC_url, owner, enableDebug }: {
|
|
24
|
+
RPC_url: string,
|
|
25
|
+
owner: string | number[] | Uint8Array | Keypair,
|
|
26
|
+
enableDebug?: boolean
|
|
27
|
+
}) {
|
|
28
|
+
let keypair = getSolanaKeypair(owner)
|
|
29
|
+
if (!keypair) {
|
|
30
|
+
throw new Error('param "owner" is not a valid Private Key or Keypair')
|
|
31
|
+
}
|
|
32
|
+
this.keypair = keypair
|
|
33
|
+
this.connection = new Connection(RPC_url, 'confirmed')
|
|
34
|
+
this.publicKey = keypair.publicKey
|
|
35
|
+
this.encryptionService = new EncryptionService();
|
|
36
|
+
this.encryptionService.deriveEncryptionKeyFromWallet(this.keypair);
|
|
37
|
+
if (!enableDebug) {
|
|
38
|
+
this.startStatusRender()
|
|
39
|
+
this.setLogger((level, message) => {
|
|
40
|
+
if (level == 'info') {
|
|
41
|
+
this.status = message
|
|
42
|
+
} else if (level == 'error') {
|
|
43
|
+
console.log('error message: ', message)
|
|
44
|
+
}
|
|
45
|
+
})
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
setLogger(loger: LoggerFn) {
|
|
50
|
+
setLogger(loger)
|
|
51
|
+
return this
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Clears the cache of utxos.
|
|
56
|
+
*
|
|
57
|
+
* By default, downloaded utxos will be cached in the local storage. Thus the next time when you makes another
|
|
58
|
+
* deposit or withdraw or getPrivateBalance, the SDK only fetches the utxos that are not in the cache.
|
|
59
|
+
*
|
|
60
|
+
* This method clears the cache of utxos.
|
|
61
|
+
*/
|
|
62
|
+
async clearCache() {
|
|
63
|
+
if (!this.publicKey) {
|
|
64
|
+
return this
|
|
65
|
+
}
|
|
66
|
+
storage.removeItem(LSK_FETCH_OFFSET + localstorageKey(this.publicKey))
|
|
67
|
+
storage.removeItem(LSK_ENCRYPTED_OUTPUTS + localstorageKey(this.publicKey))
|
|
68
|
+
return this
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Deposit SOL to the Privacy Cash.
|
|
73
|
+
*
|
|
74
|
+
* Lamports is the amount of SOL in lamports. e.g. if you want to deposit 0.01 SOL (10000000 lamports), call deposit({ lamports: 10000000 })
|
|
75
|
+
*/
|
|
76
|
+
async deposit({ lamports }: {
|
|
77
|
+
lamports: number
|
|
78
|
+
}) {
|
|
79
|
+
this.isRuning = true
|
|
80
|
+
logger.info('start depositting')
|
|
81
|
+
let lightWasm = await WasmFactory.getInstance()
|
|
82
|
+
let res = await deposit({
|
|
83
|
+
lightWasm,
|
|
84
|
+
amount_in_lamports: lamports,
|
|
85
|
+
connection: this.connection,
|
|
86
|
+
encryptionService: this.encryptionService,
|
|
87
|
+
publicKey: this.publicKey,
|
|
88
|
+
transactionSigner: async (tx: VersionedTransaction) => {
|
|
89
|
+
tx.sign([this.keypair])
|
|
90
|
+
return tx
|
|
91
|
+
},
|
|
92
|
+
keyBasePath: path.join(import.meta.dirname, '..', 'circuit2', 'transaction2'),
|
|
93
|
+
storage
|
|
94
|
+
})
|
|
95
|
+
this.isRuning = false
|
|
96
|
+
return res
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Withdraw SOL from the Privacy Cash.
|
|
101
|
+
*
|
|
102
|
+
* Lamports is the amount of SOL in lamports. e.g. if you want to withdraw 0.01 SOL (10000000 lamports), call withdraw({ lamports: 10000000 })
|
|
103
|
+
*/
|
|
104
|
+
async withdraw({ lamports, recipientAddress }: {
|
|
105
|
+
lamports: number,
|
|
106
|
+
recipientAddress?: string
|
|
107
|
+
}) {
|
|
108
|
+
this.isRuning = true
|
|
109
|
+
logger.info('start withdrawing')
|
|
110
|
+
let lightWasm = await WasmFactory.getInstance()
|
|
111
|
+
let recipient = recipientAddress ? new PublicKey(recipientAddress) : this.publicKey
|
|
112
|
+
let res = await withdraw({
|
|
113
|
+
lightWasm,
|
|
114
|
+
amount_in_lamports: lamports,
|
|
115
|
+
connection: this.connection,
|
|
116
|
+
encryptionService: this.encryptionService,
|
|
117
|
+
publicKey: this.publicKey,
|
|
118
|
+
recipient,
|
|
119
|
+
keyBasePath: path.join(import.meta.dirname, '..', 'circuit2', 'transaction2'),
|
|
120
|
+
storage
|
|
121
|
+
})
|
|
122
|
+
console.log(`Withdraw successful. Recipient ${recipient} received ${res.amount_in_lamports / LAMPORTS_PER_SOL} SOL, with ${res.fee_in_lamports / LAMPORTS_PER_SOL} SOL relayers fees`)
|
|
123
|
+
this.isRuning = false
|
|
124
|
+
return res
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Returns the amount of lamports current wallet has in Privacy Cash.
|
|
129
|
+
*/
|
|
130
|
+
async getPrivateBalance() {
|
|
131
|
+
logger.info('getting private balance')
|
|
132
|
+
this.isRuning = true
|
|
133
|
+
let utxos = await getUtxos({ publicKey: this.publicKey, connection: this.connection, encryptionService: this.encryptionService, storage })
|
|
134
|
+
this.isRuning = false
|
|
135
|
+
return getBalanceFromUtxos(utxos)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Returns true if the code is running in a browser.
|
|
140
|
+
*/
|
|
141
|
+
isBrowser() {
|
|
142
|
+
return typeof window !== "undefined"
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async startStatusRender() {
|
|
146
|
+
let frames = ['-', '\\', '|', '/'];
|
|
147
|
+
let i = 0
|
|
148
|
+
while (true) {
|
|
149
|
+
if (this.isRuning) {
|
|
150
|
+
let k = i % frames.length
|
|
151
|
+
i++
|
|
152
|
+
stdWrite(this.status, frames[k])
|
|
153
|
+
}
|
|
154
|
+
await new Promise(r => setTimeout(r, 250));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function getSolanaKeypair(
|
|
160
|
+
secret: string | number[] | Uint8Array | Keypair
|
|
161
|
+
): Keypair | null {
|
|
162
|
+
try {
|
|
163
|
+
if (secret instanceof Keypair) {
|
|
164
|
+
return secret;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
let keyArray: Uint8Array;
|
|
168
|
+
|
|
169
|
+
if (typeof secret === "string") {
|
|
170
|
+
keyArray = bs58.decode(secret);
|
|
171
|
+
} else if (secret instanceof Uint8Array) {
|
|
172
|
+
keyArray = secret;
|
|
173
|
+
} else {
|
|
174
|
+
// number[]
|
|
175
|
+
keyArray = Uint8Array.from(secret);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (keyArray.length !== 32 && keyArray.length !== 64) {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
return Keypair.fromSecretKey(keyArray);
|
|
182
|
+
} catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function stdWrite(status: string, frame: string) {
|
|
188
|
+
let blue = "\x1b[34m";
|
|
189
|
+
let reset = "\x1b[0m";
|
|
190
|
+
process.stdout.write(`${frame}status: ${blue}${status}${reset}\r`);
|
|
191
|
+
}
|