applesauce-wallet 6.2.0 → 7.1.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.
- package/README.md +8 -0
- package/dist/actions/mint-recomendation.js +1 -1
- package/dist/casts/nutzap.d.ts +1 -1
- package/dist/helpers/animated-qr.js +117 -29
- package/dist/helpers/cashu.d.ts +3 -2
- package/dist/helpers/cashu.js +4 -4
- package/dist/helpers/history.js +15 -13
- package/dist/helpers/index.d.ts +3 -0
- package/dist/helpers/index.js +2 -0
- package/dist/helpers/indexed-db-couch.js +4 -2
- package/dist/helpers/key-value-couch.d.ts +45 -0
- package/dist/helpers/key-value-couch.js +140 -0
- package/dist/helpers/local-storage-couch.js +4 -2
- package/dist/helpers/mint-recovery.d.ts +106 -0
- package/dist/helpers/mint-recovery.js +388 -0
- package/dist/helpers/nutzap.d.ts +8 -4
- package/dist/helpers/nutzap.js +12 -6
- package/dist/helpers/recovery-storage.d.ts +23 -0
- package/dist/helpers/recovery-storage.js +29 -0
- package/dist/helpers/tokens.d.ts +6 -1
- package/dist/helpers/tokens.js +20 -14
- package/dist/helpers/wallet.js +11 -7
- package/dist/models/tokens.js +7 -4
- package/dist/wallet/loading.d.ts +1 -2
- package/dist/wallet/nut-wallet.d.ts +28 -5
- package/dist/wallet/nut-wallet.js +100 -42
- package/dist/wallet/types.d.ts +5 -3
- package/package.json +15 -17
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
import { Amount, OutputData, Wallet, deserializeProofs, serializeProofs, sumProofs, } from "@cashu/cashu-ts";
|
|
2
|
+
import { WalletTokenFactory } from "../factories/tokens.js";
|
|
3
|
+
import { WalletHistoryFactory } from "../factories/history.js";
|
|
4
|
+
import { NutzapFactory } from "../factories/nutzap.js";
|
|
5
|
+
import { saveRecovery, withRecoveryLock } from "./recovery-storage.js";
|
|
6
|
+
import { tokenIdentity } from "./key-value-couch.js";
|
|
7
|
+
import { WALLET_TOKEN_KIND } from "./tokens.js";
|
|
8
|
+
import { WALLET_HISTORY_KIND } from "./history.js";
|
|
9
|
+
import { NUTZAP_KIND } from "./nutzap.js";
|
|
10
|
+
function storeQuote(quote) {
|
|
11
|
+
return { ...quote, amount: Amount.from(quote.amount).toString() };
|
|
12
|
+
}
|
|
13
|
+
function restoreQuote(quote) {
|
|
14
|
+
return { ...quote, amount: Amount.from(quote.amount) };
|
|
15
|
+
}
|
|
16
|
+
function validateMintInput(input) {
|
|
17
|
+
if (!Number.isSafeInteger(input.amount) || input.amount <= 0)
|
|
18
|
+
throw new Error("Mint amount must be a positive integer in sats");
|
|
19
|
+
if (input.nutzap?.event && input.nutzap.event.pubkey !== input.nutzap.recipient)
|
|
20
|
+
throw new Error("The nutzap event does not belong to the recipient");
|
|
21
|
+
// Validate the lock before exposing an invoice that the user could pay.
|
|
22
|
+
if (input.nutzap)
|
|
23
|
+
OutputData.createSingleP2PKData({ pubkey: input.nutzap.p2pk }, 1, "deedbeef");
|
|
24
|
+
}
|
|
25
|
+
function waitForPoll(signal) {
|
|
26
|
+
return new Promise((resolve, reject) => {
|
|
27
|
+
const abort = () => {
|
|
28
|
+
clearTimeout(timer);
|
|
29
|
+
signal?.removeEventListener("abort", abort);
|
|
30
|
+
reject(signal?.reason);
|
|
31
|
+
};
|
|
32
|
+
const timer = setTimeout(() => {
|
|
33
|
+
signal?.removeEventListener("abort", abort);
|
|
34
|
+
resolve();
|
|
35
|
+
}, 3000);
|
|
36
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
37
|
+
if (signal?.aborted)
|
|
38
|
+
abort();
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/** Persists exact mint outputs and signed events so interrupted minting can be resumed safely */
|
|
42
|
+
export class MintRecovery {
|
|
43
|
+
options;
|
|
44
|
+
prefix;
|
|
45
|
+
/** Creates a recovery journal without reading storage, signing, or publishing */
|
|
46
|
+
constructor(options) {
|
|
47
|
+
this.options = options;
|
|
48
|
+
this.prefix = `applesauce-mint:${options.owner}:`;
|
|
49
|
+
}
|
|
50
|
+
key(id) {
|
|
51
|
+
return this.prefix + encodeURIComponent(id);
|
|
52
|
+
}
|
|
53
|
+
async wallet(mint) {
|
|
54
|
+
if (this.options.getCashuWallet)
|
|
55
|
+
return this.options.getCashuWallet(mint);
|
|
56
|
+
const wallet = new Wallet(mint);
|
|
57
|
+
await wallet.loadMint();
|
|
58
|
+
return wallet;
|
|
59
|
+
}
|
|
60
|
+
async waitForQuote(wallet, record, options) {
|
|
61
|
+
if (this.options.waitForQuote)
|
|
62
|
+
return this.options.waitForQuote(record.mint, record.quote.quote, options);
|
|
63
|
+
if (wallet.getMintInfo().isSupported(17).supported)
|
|
64
|
+
return wallet.on.onceMintPaid(record.quote.quote, {
|
|
65
|
+
signal: options.signal,
|
|
66
|
+
timeoutMs: options.timeoutMs ?? 60_000,
|
|
67
|
+
});
|
|
68
|
+
const deadline = Date.now() + (options.timeoutMs ?? 60_000);
|
|
69
|
+
while (Date.now() < deadline) {
|
|
70
|
+
options.signal?.throwIfAborted();
|
|
71
|
+
const quote = await wallet.checkMintQuoteBolt11(record.quote.quote);
|
|
72
|
+
if (quote.state === "PAID" || quote.state === "ISSUED")
|
|
73
|
+
return;
|
|
74
|
+
await waitForPoll(options.signal);
|
|
75
|
+
}
|
|
76
|
+
throw new Error("Timed out waiting for mint payment");
|
|
77
|
+
}
|
|
78
|
+
read(value, id) {
|
|
79
|
+
const record = JSON.parse(value);
|
|
80
|
+
if (record.version !== 1 ||
|
|
81
|
+
record.owner !== this.options.owner ||
|
|
82
|
+
record.id !== id ||
|
|
83
|
+
!record.mint ||
|
|
84
|
+
!Number.isSafeInteger(record.amount) ||
|
|
85
|
+
record.amount <= 0 ||
|
|
86
|
+
!record.quote?.quote ||
|
|
87
|
+
record.quote.unit !== "sat" ||
|
|
88
|
+
!Amount.from(record.quote.amount).equals(record.amount) ||
|
|
89
|
+
(record.events && (!record.token || record.events.length !== (record.nutzap ? 1 : 2)))) {
|
|
90
|
+
throw new Error("Invalid recovery record; preserve the stored value");
|
|
91
|
+
}
|
|
92
|
+
if (record.token) {
|
|
93
|
+
const proofs = deserializeProofs(record.token.proofs);
|
|
94
|
+
if (record.token.mint !== record.mint || record.token.unit !== "sat" || !sumProofs(proofs).equals(record.amount))
|
|
95
|
+
throw new Error("Saved proofs do not match the mint operation; preserve recovery state");
|
|
96
|
+
}
|
|
97
|
+
if (record.events) {
|
|
98
|
+
const ids = new Set(record.events.map((event) => event.id));
|
|
99
|
+
const kinds = record.nutzap ? [NUTZAP_KIND] : [WALLET_TOKEN_KIND, WALLET_HISTORY_KIND];
|
|
100
|
+
if (ids.size !== kinds.length ||
|
|
101
|
+
record.events.some((event, index) => !event.id || event.pubkey !== record.owner || event.kind !== kinds[index]) ||
|
|
102
|
+
record.accepted?.some((accepted) => !ids.has(accepted)))
|
|
103
|
+
throw new Error("Invalid saved publication events; preserve recovery state");
|
|
104
|
+
}
|
|
105
|
+
return record;
|
|
106
|
+
}
|
|
107
|
+
metadata(record) {
|
|
108
|
+
return {
|
|
109
|
+
id: record.id,
|
|
110
|
+
owner: record.owner,
|
|
111
|
+
mint: record.mint,
|
|
112
|
+
amount: record.amount,
|
|
113
|
+
description: record.description,
|
|
114
|
+
nutzap: record.nutzap,
|
|
115
|
+
quote: restoreQuote(record.quote),
|
|
116
|
+
stage: record.events ? "events" : record.token ? "proofs" : record.preview ? "outputs" : "quote",
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Lists this owner's pending operations without signing or resuming them
|
|
121
|
+
* @throws if storage is unavailable or a saved record is invalid
|
|
122
|
+
*/
|
|
123
|
+
async getPending() {
|
|
124
|
+
const records = [];
|
|
125
|
+
for (const key of await this.options.storage.keys()) {
|
|
126
|
+
if (!key.startsWith(this.prefix))
|
|
127
|
+
continue;
|
|
128
|
+
const value = await this.options.storage.getItem(key);
|
|
129
|
+
if (value !== null)
|
|
130
|
+
records.push(this.metadata(this.read(value, decodeURIComponent(key.slice(this.prefix.length)))));
|
|
131
|
+
}
|
|
132
|
+
return records;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Creates and durably stores a quote before returning its invoice
|
|
136
|
+
* @throws if the amount or destination is invalid, recovery is unsupported, or persistence fails
|
|
137
|
+
*/
|
|
138
|
+
async prepare(input) {
|
|
139
|
+
validateMintInput(input);
|
|
140
|
+
// Check storage accessibility before contacting the mint, even when no records exist.
|
|
141
|
+
await this.options.storage.getItem(this.prefix + "probe");
|
|
142
|
+
const wallet = await this.wallet(input.mint);
|
|
143
|
+
if (!wallet.getMintInfo().isSupported(9).supported)
|
|
144
|
+
throw new Error("Mint does not support NUT-09 signature recovery");
|
|
145
|
+
const quote = await wallet.createMintQuoteBolt11(input.amount, input.description);
|
|
146
|
+
if (quote.unit !== "sat" || !Amount.from(quote.amount).equals(input.amount))
|
|
147
|
+
throw new Error("Mint quote amount or unit mismatch");
|
|
148
|
+
return this.adoptQuote(input, quote);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Persists an externally created quote before redemption; issued quotes still require saved outputs
|
|
152
|
+
* @throws if the quote conflicts with its operation or cannot be persisted
|
|
153
|
+
*/
|
|
154
|
+
async adoptQuote(input, quote) {
|
|
155
|
+
validateMintInput(input);
|
|
156
|
+
if (quote.unit !== "sat" || !Amount.from(quote.amount).equals(input.amount))
|
|
157
|
+
throw new Error("Mint quote amount or unit mismatch");
|
|
158
|
+
const id = JSON.stringify([input.mint.replace(/\/+$/, ""), quote.quote]);
|
|
159
|
+
return withRecoveryLock(this.options.storage, this.key(id), async () => {
|
|
160
|
+
const saved = await this.options.storage.getItem(this.key(id));
|
|
161
|
+
if (saved !== null) {
|
|
162
|
+
const record = this.read(saved, id);
|
|
163
|
+
if (record.amount !== input.amount || JSON.stringify(record.nutzap) !== JSON.stringify(input.nutzap))
|
|
164
|
+
throw new Error("Quote is already associated with another mint operation");
|
|
165
|
+
return this.metadata(record);
|
|
166
|
+
}
|
|
167
|
+
const record = {
|
|
168
|
+
mint: input.mint,
|
|
169
|
+
amount: input.amount,
|
|
170
|
+
description: input.description,
|
|
171
|
+
nutzap: input.nutzap,
|
|
172
|
+
version: 1,
|
|
173
|
+
owner: this.options.owner,
|
|
174
|
+
id,
|
|
175
|
+
quote: storeQuote(quote),
|
|
176
|
+
};
|
|
177
|
+
await saveRecovery(this.options.storage, this.key(record.id), record);
|
|
178
|
+
return this.metadata(record);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Imports an owner-tagged deposit from the earlier example journal without discarding its saved outputs
|
|
183
|
+
* @throws if ownership, saved state, storage, or couch cleanup cannot be verified
|
|
184
|
+
*/
|
|
185
|
+
async importLegacyDeposit(key, couch, source = this.options.storage) {
|
|
186
|
+
return withRecoveryLock(source, `legacy:${key}`, async () => {
|
|
187
|
+
const value = await source.getItem(key);
|
|
188
|
+
if (value === null)
|
|
189
|
+
return undefined;
|
|
190
|
+
const legacy = JSON.parse(value);
|
|
191
|
+
if (legacy.owner !== this.options.owner || legacy.nutzap)
|
|
192
|
+
throw new Error("Legacy deposit belongs to another owner");
|
|
193
|
+
const id = JSON.stringify([legacy.mint.replace(/\/+$/, ""), legacy.quote.quote]);
|
|
194
|
+
const record = this.read(JSON.stringify({ ...legacy, id, version: 1 }), id);
|
|
195
|
+
return withRecoveryLock(this.options.storage, this.key(id), async () => {
|
|
196
|
+
// Remove duplicate couch copies while the legacy record still durably owns the proofs.
|
|
197
|
+
if (record.token) {
|
|
198
|
+
const identity = tokenIdentity({ ...record.token, proofs: deserializeProofs(record.token.proofs) });
|
|
199
|
+
for (const token of await couch.getAll())
|
|
200
|
+
if (tokenIdentity(token) === identity)
|
|
201
|
+
await couch.remove(token);
|
|
202
|
+
if ((await couch.getAll()).some((token) => tokenIdentity(token) === identity))
|
|
203
|
+
throw new Error("Could not remove legacy couch duplicates");
|
|
204
|
+
}
|
|
205
|
+
const saved = await this.options.storage.getItem(this.key(id));
|
|
206
|
+
if (saved === null)
|
|
207
|
+
await saveRecovery(this.options.storage, this.key(id), record);
|
|
208
|
+
await source.removeItem(key);
|
|
209
|
+
return this.metadata(saved === null ? record : this.read(saved, id));
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Imports an unowned legacy nutzap only after the consumer explicitly selects its owner and delivery relays
|
|
215
|
+
* @throws if the legacy record is invalid or relay discovery or persistence fails
|
|
216
|
+
*/
|
|
217
|
+
async importLegacyNutzap(key, getRelays, source = this.options.storage) {
|
|
218
|
+
return withRecoveryLock(source, `legacy:${key}`, async () => {
|
|
219
|
+
const value = await source.getItem(key);
|
|
220
|
+
if (value === null)
|
|
221
|
+
return undefined;
|
|
222
|
+
const legacy = JSON.parse(value);
|
|
223
|
+
if (!legacy.recipient || !legacy.p2pk)
|
|
224
|
+
throw new Error("Invalid legacy nutzap");
|
|
225
|
+
const relays = await getRelays(legacy.recipient);
|
|
226
|
+
const id = JSON.stringify([legacy.mint.replace(/\/+$/, ""), legacy.quote.quote]);
|
|
227
|
+
const record = this.read(JSON.stringify({
|
|
228
|
+
version: 1,
|
|
229
|
+
id,
|
|
230
|
+
owner: this.options.owner,
|
|
231
|
+
mint: legacy.mint,
|
|
232
|
+
amount: legacy.amount,
|
|
233
|
+
quote: storeQuote(restoreQuote(legacy.quote)),
|
|
234
|
+
preview: legacy.preview && {
|
|
235
|
+
...legacy.preview,
|
|
236
|
+
quote: storeQuote(restoreQuote(legacy.preview.quote)),
|
|
237
|
+
},
|
|
238
|
+
token: legacy.token && {
|
|
239
|
+
...legacy.token,
|
|
240
|
+
proofs: serializeProofs(deserializeProofs(JSON.stringify(legacy.token.proofs))),
|
|
241
|
+
},
|
|
242
|
+
nutzap: { recipient: legacy.recipient, p2pk: legacy.p2pk, comment: legacy.comment, relays },
|
|
243
|
+
}), id);
|
|
244
|
+
return withRecoveryLock(this.options.storage, this.key(id), async () => {
|
|
245
|
+
const saved = await this.options.storage.getItem(this.key(id));
|
|
246
|
+
if (saved === null)
|
|
247
|
+
await saveRecovery(this.options.storage, this.key(id), record);
|
|
248
|
+
await source.removeItem(key);
|
|
249
|
+
return this.metadata(saved === null ? record : this.read(saved, id));
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Resumes a saved operation, retaining its state on cancellation or any failure
|
|
255
|
+
* @throws if cancelled, already running, invalid, or unable to mint, sign, persist, or publish
|
|
256
|
+
*/
|
|
257
|
+
async resume(id, options = {}) {
|
|
258
|
+
const key = this.key(id);
|
|
259
|
+
await withRecoveryLock(this.options.storage, key, async () => {
|
|
260
|
+
const check = () => options.signal?.throwIfAborted();
|
|
261
|
+
check();
|
|
262
|
+
const value = await this.options.storage.getItem(key);
|
|
263
|
+
if (value === null)
|
|
264
|
+
throw new Error("No pending mint to resume");
|
|
265
|
+
const record = this.read(value, id);
|
|
266
|
+
const save = () => saveRecovery(this.options.storage, key, record);
|
|
267
|
+
await options.onQuote?.(restoreQuote(record.quote));
|
|
268
|
+
check();
|
|
269
|
+
if (!record.token) {
|
|
270
|
+
const wallet = await this.wallet(record.mint);
|
|
271
|
+
if (!wallet.getMintInfo().isSupported(9).supported)
|
|
272
|
+
throw new Error("Mint does not support NUT-09 signature recovery");
|
|
273
|
+
let quote = await wallet.checkMintQuoteBolt11(record.quote.quote);
|
|
274
|
+
if (quote.state === "UNPAID") {
|
|
275
|
+
await this.waitForQuote(wallet, record, options);
|
|
276
|
+
quote = await wallet.checkMintQuoteBolt11(record.quote.quote);
|
|
277
|
+
}
|
|
278
|
+
check();
|
|
279
|
+
if (quote.quote !== record.quote.quote ||
|
|
280
|
+
quote.unit !== "sat" ||
|
|
281
|
+
!Amount.from(quote.amount).equals(record.amount))
|
|
282
|
+
throw new Error("Mint quote does not match the saved operation");
|
|
283
|
+
if (quote.state !== "PAID" && quote.state !== "ISSUED")
|
|
284
|
+
throw new Error("Mint quote is not paid");
|
|
285
|
+
if (!record.preview) {
|
|
286
|
+
if (quote.state === "ISSUED")
|
|
287
|
+
throw new Error("Quote issued without saved outputs; preserve recovery state");
|
|
288
|
+
const operation = wallet.ops.mintBolt11(record.amount, quote);
|
|
289
|
+
const preview = await (record.nutzap ? operation.asP2PK({ pubkey: record.nutzap.p2pk }) : operation).prepare();
|
|
290
|
+
const { outputs: _outputs, ...payload } = preview.payload;
|
|
291
|
+
record.preview = {
|
|
292
|
+
...preview,
|
|
293
|
+
quote: storeQuote(preview.quote),
|
|
294
|
+
payload,
|
|
295
|
+
outputData: preview.outputData.map(OutputData.serialize),
|
|
296
|
+
};
|
|
297
|
+
await save();
|
|
298
|
+
}
|
|
299
|
+
const outputData = record.preview.outputData.map(OutputData.deserialize);
|
|
300
|
+
if (record.preview.method !== "bolt11" ||
|
|
301
|
+
record.preview.quote.quote !== record.quote.quote ||
|
|
302
|
+
record.preview.payload.quote !== record.quote.quote ||
|
|
303
|
+
!outputData.length ||
|
|
304
|
+
new Set(outputData.map((output) => output.blindedMessage.B_)).size !== outputData.length ||
|
|
305
|
+
outputData.some((output) => output.blindedMessage.id !== record.preview.keysetId) ||
|
|
306
|
+
!sumProofs(outputData.map((output) => output.blindedMessage)).equals(record.amount))
|
|
307
|
+
throw new Error("Saved outputs do not match the mint operation; preserve recovery state");
|
|
308
|
+
const preview = {
|
|
309
|
+
...record.preview,
|
|
310
|
+
quote: restoreQuote(record.preview.quote),
|
|
311
|
+
outputData,
|
|
312
|
+
payload: { ...record.preview.payload, outputs: outputData.map((output) => output.blindedMessage) },
|
|
313
|
+
};
|
|
314
|
+
check();
|
|
315
|
+
let proofs;
|
|
316
|
+
if (quote.state === "ISSUED") {
|
|
317
|
+
const restored = await wallet.mint.restore({ outputs: preview.payload.outputs });
|
|
318
|
+
if (restored.outputs.length !== outputData.length || restored.signatures.length !== outputData.length)
|
|
319
|
+
throw new Error("Mint did not restore all saved outputs");
|
|
320
|
+
const seen = new Set();
|
|
321
|
+
// A saved quote may refer to a keyset that became inactive while the client was offline.
|
|
322
|
+
await wallet.ensureOperableKeysets([preview.keysetId]);
|
|
323
|
+
const keys = wallet.getKeyset(preview.keysetId);
|
|
324
|
+
proofs = restored.outputs.map((output, index) => {
|
|
325
|
+
const original = outputData.find((candidate) => candidate.blindedMessage.B_ === output.B_);
|
|
326
|
+
if (!original || seen.has(output.B_))
|
|
327
|
+
throw new Error("Mint returned an unknown or repeated recovery output");
|
|
328
|
+
seen.add(output.B_);
|
|
329
|
+
const signature = restored.signatures[index];
|
|
330
|
+
if (signature.id !== preview.keysetId ||
|
|
331
|
+
!Amount.from(signature.amount).equals(original.blindedMessage.amount))
|
|
332
|
+
throw new Error("Mint returned mismatched recovery signatures");
|
|
333
|
+
return original.toProof(signature, keys);
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
else {
|
|
337
|
+
proofs = await wallet.completeMint(preview);
|
|
338
|
+
}
|
|
339
|
+
if (!sumProofs(proofs).equals(record.amount))
|
|
340
|
+
throw new Error("Mint issued an unexpected amount");
|
|
341
|
+
record.token = { mint: record.mint, unit: "sat", proofs: serializeProofs(proofs) };
|
|
342
|
+
// Never put these proofs in the ordinary couch: couch recovery could swap them before publication.
|
|
343
|
+
await save();
|
|
344
|
+
}
|
|
345
|
+
check();
|
|
346
|
+
if (!record.events) {
|
|
347
|
+
if ((await this.options.signer.getPublicKey()) !== record.owner)
|
|
348
|
+
throw new Error("The signer does not own this operation");
|
|
349
|
+
const token = { ...record.token, proofs: deserializeProofs(record.token.proofs) };
|
|
350
|
+
if (record.nutzap) {
|
|
351
|
+
const { event, recipient, comment } = record.nutzap;
|
|
352
|
+
const factory = event
|
|
353
|
+
? NutzapFactory.forEvent(event, token, comment)
|
|
354
|
+
: NutzapFactory.forProfile(recipient, token, comment);
|
|
355
|
+
record.events = [await factory.sign(this.options.signer)];
|
|
356
|
+
}
|
|
357
|
+
else {
|
|
358
|
+
const tokenEvent = await WalletTokenFactory.create(token).sign(this.options.signer);
|
|
359
|
+
const history = await WalletHistoryFactory.create({
|
|
360
|
+
direction: "in",
|
|
361
|
+
amount: record.amount,
|
|
362
|
+
mint: record.mint,
|
|
363
|
+
created: [tokenEvent.id],
|
|
364
|
+
}).sign(this.options.signer);
|
|
365
|
+
record.events = [tokenEvent, history];
|
|
366
|
+
}
|
|
367
|
+
if (record.events.some((event) => event.pubkey !== record.owner))
|
|
368
|
+
throw new Error("The active signer changed during mint recovery");
|
|
369
|
+
record.accepted = [];
|
|
370
|
+
await save();
|
|
371
|
+
}
|
|
372
|
+
for (const event of record.events) {
|
|
373
|
+
check();
|
|
374
|
+
if (event.pubkey !== record.owner)
|
|
375
|
+
throw new Error("A saved event belongs to another owner");
|
|
376
|
+
if (record.accepted?.includes(event.id)) {
|
|
377
|
+
this.options.onAccepted?.(event);
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
await this.options.publish(event, record.nutzap?.relays);
|
|
381
|
+
this.options.onAccepted?.(event);
|
|
382
|
+
record.accepted = [...(record.accepted ?? []), event.id];
|
|
383
|
+
await save();
|
|
384
|
+
}
|
|
385
|
+
await this.options.storage.removeItem(key);
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
}
|
package/dist/helpers/nutzap.d.ts
CHANGED
|
@@ -34,15 +34,19 @@ export declare function isNutzapRedeemed(nutzapId: string, history: NostrEvent[]
|
|
|
34
34
|
/**
|
|
35
35
|
* Extracts the P2PK locking pubkey from proofs in a nutzap event
|
|
36
36
|
* @param nutzap the nutzap event containing P2PK-locked proofs
|
|
37
|
-
* @returns the pubkey
|
|
38
|
-
*
|
|
37
|
+
* @returns the single pubkey every proof is locked to, or undefined if there is no such pubkey —
|
|
38
|
+
* no proofs, a proof that is not P2PK locked, or proofs locked to more than one pubkey. A nutzap
|
|
39
|
+
* arrives from a stranger, so all three are hostile input rather than programmer errors, and none
|
|
40
|
+
* of them throw. This matches getProofP2PKPubkey one level down, which already returns undefined
|
|
41
|
+
* for every failure.
|
|
39
42
|
*/
|
|
40
43
|
export declare function getNutzapP2PKPubkey(nutzap: NostrEvent): string | undefined;
|
|
41
44
|
/**
|
|
42
45
|
* Finds the matching private key for the P2PK lock in a nutzap event's proofs
|
|
43
46
|
* @param nutzap the nutzap event containing P2PK-locked proofs
|
|
44
47
|
* @param privateKeys array of private keys to search through
|
|
45
|
-
* @returns the matching private key, or undefined if none match
|
|
46
|
-
*
|
|
48
|
+
* @returns the matching private key, or undefined if none match — including when the nutzap has no
|
|
49
|
+
* single P2PK pubkey to match against, which getNutzapP2PKPubkey now reports as undefined rather
|
|
50
|
+
* than by throwing
|
|
47
51
|
*/
|
|
48
52
|
export declare function findMatchingPrivateKeyForNutzap(nutzap: NostrEvent, privateKeys: Uint8Array[]): Uint8Array | undefined;
|
package/dist/helpers/nutzap.js
CHANGED
|
@@ -70,8 +70,11 @@ export function isNutzapRedeemed(nutzapId, history) {
|
|
|
70
70
|
/**
|
|
71
71
|
* Extracts the P2PK locking pubkey from proofs in a nutzap event
|
|
72
72
|
* @param nutzap the nutzap event containing P2PK-locked proofs
|
|
73
|
-
* @returns the pubkey
|
|
74
|
-
*
|
|
73
|
+
* @returns the single pubkey every proof is locked to, or undefined if there is no such pubkey —
|
|
74
|
+
* no proofs, a proof that is not P2PK locked, or proofs locked to more than one pubkey. A nutzap
|
|
75
|
+
* arrives from a stranger, so all three are hostile input rather than programmer errors, and none
|
|
76
|
+
* of them throw. This matches getProofP2PKPubkey one level down, which already returns undefined
|
|
77
|
+
* for every failure.
|
|
75
78
|
*/
|
|
76
79
|
export function getNutzapP2PKPubkey(nutzap) {
|
|
77
80
|
const proofs = getNutzapProofs(nutzap);
|
|
@@ -81,12 +84,14 @@ export function getNutzapP2PKPubkey(nutzap) {
|
|
|
81
84
|
for (const proof of proofs) {
|
|
82
85
|
const proofPubkey = getProofP2PKPubkey(proof);
|
|
83
86
|
if (!proofPubkey)
|
|
84
|
-
|
|
87
|
+
return undefined;
|
|
85
88
|
if (!p2pkPubkey) {
|
|
86
89
|
p2pkPubkey = proofPubkey;
|
|
87
90
|
}
|
|
88
91
|
else if (p2pkPubkey !== proofPubkey) {
|
|
89
|
-
|
|
92
|
+
// Mixed locks mean there is no single pubkey to report, so the answer is undefined rather
|
|
93
|
+
// than the first one seen — returning p2pkPubkey here would silently hide the mismatch.
|
|
94
|
+
return undefined;
|
|
90
95
|
}
|
|
91
96
|
}
|
|
92
97
|
return p2pkPubkey;
|
|
@@ -95,8 +100,9 @@ export function getNutzapP2PKPubkey(nutzap) {
|
|
|
95
100
|
* Finds the matching private key for the P2PK lock in a nutzap event's proofs
|
|
96
101
|
* @param nutzap the nutzap event containing P2PK-locked proofs
|
|
97
102
|
* @param privateKeys array of private keys to search through
|
|
98
|
-
* @returns the matching private key, or undefined if none match
|
|
99
|
-
*
|
|
103
|
+
* @returns the matching private key, or undefined if none match — including when the nutzap has no
|
|
104
|
+
* single P2PK pubkey to match against, which getNutzapP2PKPubkey now reports as undefined rather
|
|
105
|
+
* than by throwing
|
|
100
106
|
*/
|
|
101
107
|
export function findMatchingPrivateKeyForNutzap(nutzap, privateKeys) {
|
|
102
108
|
const p2pkPubkey = getNutzapP2PKPubkey(nutzap);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** An app-scoped durable string store; missing values return null and failed reads or mutations must reject */
|
|
2
|
+
export interface RecoveryStorage {
|
|
3
|
+
/** Returns the stored value, or null only when the key does not exist */
|
|
4
|
+
getItem(key: string): Promise<string | null>;
|
|
5
|
+
/** Persists a value before resolving; false is also treated as a failed write */
|
|
6
|
+
setItem(key: string, value: string): Promise<unknown>;
|
|
7
|
+
/** Removes a value durably before resolving */
|
|
8
|
+
removeItem(key: string): Promise<void>;
|
|
9
|
+
/** Returns all keys, including keys written in previous sessions */
|
|
10
|
+
keys(): Promise<string[]>;
|
|
11
|
+
/** Runs an exclusive operation using locks scoped to this storage backend */
|
|
12
|
+
withLock?<T>(key: string, operation: () => Promise<T>): Promise<T>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Runs a recovery mutation exclusively within a storage instance and delegates backend locking to the adapter
|
|
16
|
+
* @throws if the operation is already running or the lock provider fails
|
|
17
|
+
*/
|
|
18
|
+
export declare function withRecoveryLock<T>(storage: RecoveryStorage, key: string, operation: () => Promise<T>): Promise<T>;
|
|
19
|
+
/**
|
|
20
|
+
* Persists a recovery value and rejects storage adapters that report failure without throwing
|
|
21
|
+
* @throws if serialization or persistence fails
|
|
22
|
+
*/
|
|
23
|
+
export declare function saveRecovery(storage: RecoveryStorage, key: string, value: unknown): Promise<void>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
const active = new WeakMap();
|
|
2
|
+
/**
|
|
3
|
+
* Runs a recovery mutation exclusively within a storage instance and delegates backend locking to the adapter
|
|
4
|
+
* @throws if the operation is already running or the lock provider fails
|
|
5
|
+
*/
|
|
6
|
+
export async function withRecoveryLock(storage, key, operation) {
|
|
7
|
+
let keys = active.get(storage);
|
|
8
|
+
if (!keys)
|
|
9
|
+
active.set(storage, (keys = new Set()));
|
|
10
|
+
if (keys.has(key))
|
|
11
|
+
throw new Error("A recovery operation is already running");
|
|
12
|
+
keys.add(key);
|
|
13
|
+
try {
|
|
14
|
+
if (storage.withLock)
|
|
15
|
+
return await storage.withLock(key, operation);
|
|
16
|
+
return await operation();
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
keys.delete(key);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Persists a recovery value and rejects storage adapters that report failure without throwing
|
|
24
|
+
* @throws if serialization or persistence fails
|
|
25
|
+
*/
|
|
26
|
+
export async function saveRecovery(storage, key, value) {
|
|
27
|
+
if ((await storage.setItem(key, JSON.stringify(value))) === false)
|
|
28
|
+
throw new Error("Could not persist recovery state");
|
|
29
|
+
}
|
package/dist/helpers/tokens.d.ts
CHANGED
|
@@ -38,7 +38,12 @@ export type UnlockedTokenContent = UnlockedHiddenContent & {
|
|
|
38
38
|
export declare function isTokenContentUnlocked<T extends NostrEvent>(token: T): token is T & UnlockedTokenContent;
|
|
39
39
|
/**
|
|
40
40
|
* Returns the decrypted and parsed details of a 7375 token event
|
|
41
|
-
*
|
|
41
|
+
*
|
|
42
|
+
* Returns undefined for anything that does not yield usable content — still locked, not valid
|
|
43
|
+
* JSON, not an object, or missing `mint`/`proofs`. None of these throw: this getter is read from
|
|
44
|
+
* inside RxJS pipes (see WalletToken's `meta$`), where a throw errors the observable and is
|
|
45
|
+
* terminal, killing the wallet's token stream rather than skipping one malformed event.
|
|
46
|
+
* `unlockTokenContent` is the imperative counterpart that does throw.
|
|
42
47
|
*/
|
|
43
48
|
export declare function getTokenContent(token: UnlockedTokenContent): TokenContent;
|
|
44
49
|
export declare function getTokenContent(token: NostrEvent): TokenContent | undefined;
|
package/dist/helpers/tokens.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getHiddenContent, isHiddenContentUnlocked, lockHiddenContent, notifyEventUpdate, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers";
|
|
1
|
+
import { getHiddenContent, isHiddenContentUnlocked, lockHiddenContent, notifyEventUpdate, safeParse, setCachedValue, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers";
|
|
2
2
|
import { ignoreDuplicateProofs } from "./cashu.js";
|
|
3
3
|
export const WALLET_TOKEN_KIND = 7375;
|
|
4
4
|
/** Checks if an event is a valid wallet token event */
|
|
@@ -21,12 +21,11 @@ setHiddenContentEncryptionMethod(WALLET_TOKEN_KIND, "nip44");
|
|
|
21
21
|
export const TokenContentSymbol = Symbol.for("token-content");
|
|
22
22
|
/** Returns if token details are locked */
|
|
23
23
|
export function isTokenContentUnlocked(token) {
|
|
24
|
-
//
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
return false;
|
|
24
|
+
// No try/catch needed: `token` is typed so the `in` test cannot throw, and neither
|
|
25
|
+
// isHiddenContentUnlocked nor getTokenContent throws — getTokenContent returns undefined for
|
|
26
|
+
// malformed content rather than raising. The defensive catch this used to carry was masking
|
|
27
|
+
// that throw and silently reporting a malformed token as merely locked.
|
|
28
|
+
return TokenContentSymbol in token || (isHiddenContentUnlocked(token) && getTokenContent(token) !== undefined);
|
|
30
29
|
}
|
|
31
30
|
export function getTokenContent(token) {
|
|
32
31
|
if (TokenContentSymbol in token)
|
|
@@ -35,17 +34,24 @@ export function getTokenContent(token) {
|
|
|
35
34
|
const plaintext = getHiddenContent(token);
|
|
36
35
|
if (!plaintext)
|
|
37
36
|
return undefined;
|
|
38
|
-
// Parse the content as a token content
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
// Parse the content as a token content. safeParse (not JSON.parse) so malformed content
|
|
38
|
+
// returns undefined instead of throwing out of a getter.
|
|
39
|
+
const details = safeParse(plaintext);
|
|
40
|
+
// Shape guard BEFORE any property read: safeParse("null") yields null and `null.mint` throws a
|
|
41
|
+
// TypeError, which would just swap one throw for another.
|
|
42
|
+
if (!details || typeof details !== "object")
|
|
43
|
+
return undefined;
|
|
44
|
+
// Content missing its required fields is unusable. Returning undefined (rather than throwing)
|
|
45
|
+
// keeps this consistent with the locked and unparseable cases above, and the rejection is
|
|
46
|
+
// deliberately not cached — a token stays readable if correct content is decrypted in later.
|
|
41
47
|
if (!details.mint)
|
|
42
|
-
|
|
48
|
+
return undefined;
|
|
43
49
|
if (!details.proofs)
|
|
44
|
-
|
|
50
|
+
return undefined;
|
|
45
51
|
if (!details.del)
|
|
46
52
|
details.del = [];
|
|
47
|
-
// Set the cached value
|
|
48
|
-
|
|
53
|
+
// Set the cached value (identity memo, non-enumerable so a spread drops it)
|
|
54
|
+
setCachedValue(token, TokenContentSymbol, details);
|
|
49
55
|
return details;
|
|
50
56
|
}
|
|
51
57
|
/** Decrypts a k:7375 token event */
|
package/dist/helpers/wallet.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getHiddenTags, hasHiddenTags, isHiddenTagsUnlocked, lockHiddenTags, notifyEventUpdate, relaySet, setHiddenTagsEncryptionMethod, unlockHiddenTags, } from "applesauce-core/helpers";
|
|
1
|
+
import { getHiddenTags, hasHiddenTags, isHiddenTagsUnlocked, lockHiddenTags, notifyEventUpdate, relaySet, setCachedValue, setHiddenTagsEncryptionMethod, unlockHiddenTags, } from "applesauce-core/helpers";
|
|
2
2
|
import { hexToBytes } from "applesauce-core/helpers/event";
|
|
3
3
|
export const WALLET_KIND = 17375;
|
|
4
4
|
export const WALLET_BACKUP_KIND = 375;
|
|
@@ -27,8 +27,8 @@ export function getWalletMints(wallet) {
|
|
|
27
27
|
return undefined;
|
|
28
28
|
// Get mints
|
|
29
29
|
const mints = tags.filter((t) => t[0] === "mint").map((t) => t[1]);
|
|
30
|
-
// Set the cached value
|
|
31
|
-
|
|
30
|
+
// Set the cached value (identity memo, non-enumerable so a spread drops it)
|
|
31
|
+
setCachedValue(wallet, WalletMintsSymbol, mints);
|
|
32
32
|
return mints;
|
|
33
33
|
}
|
|
34
34
|
export function getWalletPrivateKey(wallet) {
|
|
@@ -41,8 +41,11 @@ export function getWalletPrivateKey(wallet) {
|
|
|
41
41
|
// Parse private key
|
|
42
42
|
const privkey = tags.find((t) => t[0] === "privkey" && t[1])?.[1];
|
|
43
43
|
const key = privkey ? hexToBytes(privkey) : null;
|
|
44
|
-
// Set the cached value
|
|
45
|
-
|
|
44
|
+
// Set the cached value (identity memo, non-enumerable so a spread drops it). This is a V8
|
|
45
|
+
// improvement: the decrypted private key no longer rides along on an unrelated plain-object
|
|
46
|
+
// spread of the wallet event. The key itself is still held in memory for this wallet
|
|
47
|
+
// instance's lifetime -- no lock primitive is added here, that stays out of this phase's scope.
|
|
48
|
+
setCachedValue(wallet, WalletPrivateKeySymbol, key);
|
|
46
49
|
return key;
|
|
47
50
|
}
|
|
48
51
|
export function getWalletRelays(wallet) {
|
|
@@ -56,8 +59,8 @@ export function getWalletRelays(wallet) {
|
|
|
56
59
|
// Get relays
|
|
57
60
|
const urls = tags.filter((t) => t[0] === "relay" && t[1]).map((t) => t[1]);
|
|
58
61
|
const relays = relaySet(urls);
|
|
59
|
-
// Set the cached value
|
|
60
|
-
|
|
62
|
+
// Set the cached value (identity memo, non-enumerable so a spread drops it)
|
|
63
|
+
setCachedValue(wallet, WalletRelaysSymbol, relays);
|
|
61
64
|
return relays;
|
|
62
65
|
}
|
|
63
66
|
/** Unlocks a wallet and returns the hidden tags */
|
|
@@ -86,5 +89,6 @@ export async function unlockWallet(wallet, signer) {
|
|
|
86
89
|
export function lockWallet(wallet) {
|
|
87
90
|
Reflect.deleteProperty(wallet, WalletPrivateKeySymbol);
|
|
88
91
|
Reflect.deleteProperty(wallet, WalletMintsSymbol);
|
|
92
|
+
Reflect.deleteProperty(wallet, WalletRelaysSymbol);
|
|
89
93
|
lockHiddenTags(wallet);
|
|
90
94
|
}
|