-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnutbits.js
More file actions
1842 lines (1655 loc) · 89.7 KB
/
Copy pathnutbits.js
File metadata and controls
1842 lines (1655 loc) · 89.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// NUTbits - Cashu ecash mint to NWC bridge
// Published by @drshift - https://drshift.dev
// Inspired by https://github.com/supertestnet/bankify
// License: AGPL-3.0 (https://www.gnu.org/licenses/agpl-3.0.html)
// WebSocket polyfill for Node.js < 21 (native WebSocket unavailable)
if (!globalThis.WebSocket) {
globalThis.WebSocket = (await import('ws')).default;
}
import {
generateSecretKey, getPublicKey,
finalizeEvent, verifyEvent,
Relay,
nip04, nip44,
bytesToHex, hexToBytes
} from 'nostr-core';
import { Wallet, sumProofs, MintQuoteState, NetworkError, HttpResponseError, MintOperationError, hasValidDleq } from '@cashu/cashu-ts';
import { createStore } from './store/index.js';
import { encryptState as encryptStateForRecovery } from './store/crypto-utils.js';
import { isRestorableNwcConnection } from './store/connection-utils.js';
import { startApiServer } from './api/server.js';
import bolt11Lib from 'bolt11';
import crypto from 'crypto';
import fs from 'fs';
import 'dotenv/config';
// ── Configuration ──────────────────────────────────────────────────────────
var config = {
mintUrls: (process.env.NUTBITS_MINT_URLS || process.env.NUTBITS_MINT_URL || 'https://mint.minibits.cash/Bitcoin').split(',').map(s => s.trim()).filter(Boolean),
relays: (process.env.NUTBITS_RELAYS || 'wss://relay.getalby.com/v1,wss://relay.8333.space').split(',').map(s => s.trim()).filter(Boolean),
stateFile: process.env.NUTBITS_STATE_FILE || './nutbits_state.enc',
statePassphrase: process.env.NUTBITS_STATE_PASSPHRASE || '',
logLevel: process.env.NUTBITS_LOG_LEVEL || 'info',
feeReservePct: Number(process.env.NUTBITS_FEE_RESERVE_PCT || 1) / 100,
maxRetries: Number(process.env.NUTBITS_INVOICE_CHECK_MAX_RETRIES || 60),
checkInterval: Number(process.env.NUTBITS_INVOICE_CHECK_INTERVAL_SECS || 20),
fetchTimeout: Number(process.env.NUTBITS_FETCH_TIMEOUT_MS || 15000),
maxPaymentSats: Number(process.env.NUTBITS_MAX_PAYMENT_SATS || 0),
dailyLimitSats: Number(process.env.NUTBITS_DAILY_LIMIT_SATS || 0),
healthCheckInterval: Number(process.env.NUTBITS_HEALTH_CHECK_INTERVAL_MS || 60000),
failoverCooldown: Number(process.env.NUTBITS_FAILOVER_COOLDOWN_MS || 10000),
stateBackend: process.env.NUTBITS_STATE_BACKEND || 'file',
sqlitePath: process.env.NUTBITS_SQLITE_PATH || null,
mysqlUrl: process.env.NUTBITS_MYSQL_URL || null,
seed: process.env.NUTBITS_SEED || null,
serviceFeePpm: Math.max(0, Math.floor(Number(process.env.NUTBITS_SERVICE_FEE_PPM || 0))),
serviceFeeBase: Math.max(0, Math.floor(Number(process.env.NUTBITS_SERVICE_FEE_BASE || 0))),
apiEnabled: process.env.NUTBITS_API_ENABLED !== 'false',
apiSocket: process.env.NUTBITS_API_SOCKET || null,
apiPort: process.env.NUTBITS_API_PORT || null,
apiToken: process.env.NUTBITS_API_TOKEN || null,
};
// Backward compat: mintUrl = first configured mint
config.mintUrl = config.mintUrls[0];
// ── Logging ────────────────────────────────────────────────────────────────
var LOG_LEVELS = { error: 0, warn: 1, info: 2, debug: 3 };
var log = {
_level: LOG_LEVELS[config.logLevel] ?? 2,
_fmt: (level, msg, data) => {
var ts = new Date().toISOString();
var line = `[${ts}] [${level.toUpperCase()}] ${msg}`;
if (data !== undefined) line += ' ' + JSON.stringify(data);
return line;
},
error: (msg, data) => { if (log._level >= 0) console.error(log._fmt('error', msg, data)); },
warn: (msg, data) => { if (log._level >= 1) console.warn(log._fmt('warn', msg, data)); },
info: (msg, data) => { if (log._level >= 2) console.log(log._fmt('info', msg, data)); },
debug: (msg, data) => { if (log._level >= 3) console.log(log._fmt('debug', msg, data)); },
};
// ── Utilities ──────────────────────────────────────────────────────────────
var wait = ms => new Promise(r => setTimeout(r, ms));
// Service fee calculation (outgoing payments only)
var calcServiceFee = (amountSats, connState) => {
var ppm = connState?.service_fee_ppm ?? config.serviceFeePpm;
var base = connState?.service_fee_base ?? config.serviceFeeBase;
if (!ppm && !base) return 0;
return Math.floor(amountSats * ppm / 1_000_000) + base;
};
var validateMintUrl = url => {
try {
var parsed = new URL(url);
if (!['http:', 'https:'].includes(parsed.protocol)) throw new Error('not http(s)');
return parsed.origin + parsed.pathname.replace(/\/+$/, '');
} catch (e) {
throw new Error('Invalid mint URL: ' + url);
}
};
// ── Security: Event Deduplication (time-windowed) ───────────────────────────
var processedEvents = new Map(); // eventId -> timestamp
var DEDUP_MAX = 10000;
var DEDUP_TTL_MS = 10 * 60 * 1000; // 10 minutes
var isDuplicate = eventId => {
if (processedEvents.has(eventId)) return true;
var now = Date.now();
processedEvents.set(eventId, now);
// Prune expired entries when map gets large
if (processedEvents.size > DEDUP_MAX) {
for (var [id, ts] of processedEvents) {
if (now - ts > DEDUP_TTL_MS) processedEvents.delete(id);
}
// Hard cap: if TTL pruning wasn't enough, drop oldest entries
if (processedEvents.size > DEDUP_MAX) {
var excess = processedEvents.size - Math.floor(DEDUP_MAX / 2);
for (var [id] of processedEvents) {
if (excess-- <= 0) break;
processedEvents.delete(id);
}
}
}
return false;
};
// ── NIP-04 / NIP-44 Encryption Layer ───────────────────────────────────────
var nwcEncrypt = async (privkeyHex, pubkeyHex, plaintext, useNip44 = true) => {
if (useNip44) {
var convKey = nip44.getConversationKey(hexToBytes(privkeyHex), pubkeyHex);
return nip44.encrypt(plaintext, convKey);
}
return await nip04.encrypt(privkeyHex, pubkeyHex, plaintext);
};
var nwcDecrypt = async (privkeyHex, pubkeyHex, ciphertext) => {
// Auto-detect: NIP-04 ciphertext contains "?iv=", NIP-44 does not
var isNip04 = ciphertext.includes('?iv=');
if (isNip04) {
return { plaintext: await nip04.decrypt(privkeyHex, pubkeyHex, ciphertext), nip44: false };
}
var convKey = nip44.getConversationKey(hexToBytes(privkeyHex), pubkeyHex);
return { plaintext: nip44.decrypt(ciphertext, convKey), nip44: true };
};
// ── Invoice Helpers ────────────────────────────────────────────────────────
var getInvoicePmthash = invoice => {
var decoded = bolt11Lib.decode(invoice);
for (var i = 0; i < decoded.tags.length; i++) {
if (decoded.tags[i].tagName == 'payment_hash') return decoded.tags[i].data.toString();
}
};
var getInvoiceDescription = invoice => {
try {
var decoded = bolt11Lib.decode(invoice);
for (var i = 0; i < decoded.tags.length; i++) {
if (decoded.tags[i].tagName == 'description') return decoded.tags[i].data.toString();
}
} catch (e) {}
return '';
};
var getInvoiceDeschash = invoice => {
try {
var decoded = bolt11Lib.decode(invoice);
for (var i = 0; i < decoded.tags.length; i++) {
if (decoded.tags[i].tagName == 'purpose_commit_hash') return decoded.tags[i].data.toString();
}
} catch (e) {}
return '';
};
// ── Multi-Mint Manager ────────────────────────────────────────────────────
var mintManager = {
wallets: new Map(), // mintUrl -> Wallet instance
activeMintUrl: null, // currently active mint URL
mintHealth: new Map(), // mintUrl -> { healthy, lastCheck, consecutiveFailures, lastError }
mintCaps: new Map(), // mintUrl -> { nut09, nut12, nut15, nut17, nut20 }
orderedMints: [], // validated mint URLs in priority order
getActiveWallet: () => mintManager.wallets.get(mintManager.activeMintUrl),
};
var isMintDownError = e => {
// MintOperationError extends HttpResponseError, so check it first - if the mint
// responded with a protocol error, it's actually up (not a connectivity issue)
if (e instanceof MintOperationError) return false;
if (e instanceof NetworkError) return true;
if (e instanceof HttpResponseError) return true;
var msg = e?.message || '';
return msg.includes('ECONNREFUSED') || msg.includes('fetch failed') || msg.includes('ETIMEDOUT') || msg.includes('ENOTFOUND');
};
var checkMintHealth = async mintUrl => {
try {
var w = mintManager.wallets.get(mintUrl);
if (!w) return false;
await w.mint.getInfo();
mintManager.mintHealth.set(mintUrl, { healthy: true, lastCheck: Date.now(), consecutiveFailures: 0, lastError: null });
return true;
} catch (e) {
var prev = mintManager.mintHealth.get(mintUrl) || { consecutiveFailures: 0 };
mintManager.mintHealth.set(mintUrl, {
healthy: false, lastCheck: Date.now(),
consecutiveFailures: prev.consecutiveFailures + 1,
lastError: e.message,
});
return false;
}
};
var failoverToNextMint = async failedMintUrl => {
log.warn('FAILOVER: mint is down, attempting switch', { failed: failedMintUrl });
mintManager.mintHealth.set(failedMintUrl, {
healthy: false, lastCheck: Date.now(), consecutiveFailures: 999, lastError: 'triggered failover',
});
for (var url of mintManager.orderedMints) {
if (url === failedMintUrl) continue;
var health = mintManager.mintHealth.get(url);
if (health && !health.healthy && (Date.now() - health.lastCheck) < config.failoverCooldown) continue;
try {
var wallet = mintManager.wallets.get(url);
if (!wallet) {
wallet = createWalletForMint(url);
mintManager.wallets.set(url, wallet);
}
await wallet.loadMint();
detectMintCaps(wallet, url);
var oldMint = mintManager.activeMintUrl;
mintManager.activeMintUrl = url;
mintManager.mintHealth.set(url, { healthy: true, lastCheck: Date.now(), consecutiveFailures: 0, lastError: null });
log.warn('FAILOVER: switched mint', { from: oldMint, to: url });
await store.setActiveMintUrl(url);
return true;
} catch (e) {
log.warn('FAILOVER: candidate mint also down', { mint: url, error: e.message });
mintManager.mintHealth.set(url, { healthy: false, lastCheck: Date.now(), consecutiveFailures: 1, lastError: e.message });
}
}
log.error('FAILOVER: ALL MINTS DOWN - no healthy mint available');
return false;
};
var withFailover = async (operation, operationName) => {
try {
return await operation();
} catch (e) {
if (isMintDownError(e) && mintManager.orderedMints.length > 1) {
log.warn(`${operationName}: mint error, attempting failover`, { error: e.message });
var switched = await failoverToNextMint(mintManager.activeMintUrl);
if (switched) return await operation();
}
throw e;
}
};
var getWalletForMint = mintUrl => {
return mintManager.wallets.get(mintUrl) || mintManager.getActiveWallet();
};
// ── NUT Helpers ───────────────────────────────────────────────────────────
// NUT-06: Detect mint capabilities after loadMint
var detectMintCaps = (wallet, mintUrl) => {
try {
var info = wallet.getMintInfo();
var caps = {
nut09: !!info.isSupported(9)?.supported,
nut12: !!info.isSupported(12)?.supported,
nut15: !!info.isSupported(15)?.supported,
nut17: !!info.isSupported(17)?.supported,
nut20: !!info.isSupported(20)?.supported,
};
mintManager.mintCaps.set(mintUrl, caps);
log.info('NUT-06: mint capabilities', { mint: mintUrl, ...caps });
if (info.motd) log.info('mint MOTD', { mint: mintUrl, motd: info.motd });
return caps;
} catch (e) {
log.debug('NUT-06: could not detect capabilities', { mint: mintUrl, error: e.message });
return {};
}
};
// NUT-12: Verify DLEQ proofs on minted/received tokens
var verifyProofsDleq = (proofs, wallet, mintUrl) => {
var caps = mintManager.mintCaps.get(mintUrl);
if (!caps?.nut12) return proofs;
var verified = [];
for (var p of proofs) {
if (!p.dleq) {
verified.push(p); // accept proofs without DLEQ (mint may omit it)
continue;
}
try {
if (hasValidDleq(p, wallet.getKeyset(p.id))) {
verified.push(p);
} else {
log.error('NUT-12: INVALID DLEQ - proof rejected', { mint: mintUrl, amount: p.amount });
}
} catch (e) {
// Verification error (not invalid DLEQ) - accept proof to avoid losing funds
log.warn('NUT-12: DLEQ check error, accepting proof', { error: e.message, mint: mintUrl, amount: p.amount });
verified.push(p);
}
}
return verified;
};
// NUT-13: Counter source for deterministic secrets (backed by store)
var createCounterSource = () => ({
reserve: async (keysetId, n) => {
var current = (await store.getCounter(keysetId)) || 0;
if (n > 0) await store.setCounter(keysetId, current + n);
return { start: current, count: n };
},
advanceToAtLeast: async (keysetId, minNext) => {
var current = (await store.getCounter(keysetId)) || 0;
if (minNext > current) await store.setCounter(keysetId, minNext);
},
snapshot: async () => ({}),
});
// NUT-13: Create wallet with seed if configured
var createWalletForMint = (mintUrl) => {
var opts = config.seed ? {
bip39seed: hexToBytes(config.seed),
secretsPolicy: 'deterministic',
counterSource: createCounterSource(),
} : {};
return new Wallet(mintUrl, opts);
};
// ── Store + Payment Lock ──────────────────────────────────────────────────
var store = null; // initialized at startup
var paymentLocks = new Map();
var withPaymentLock = async (mintUrl, fn) => {
var prev = paymentLocks.get(mintUrl) || Promise.resolve();
var release;
paymentLocks.set(mintUrl, new Promise(r => { release = r; }));
await prev;
try { return await fn(); }
finally { release(); }
};
// ── NUTbits Core ───────────────────────────────────────────────────────────
var nutbits = {
state: {
nostr_state: {
pools: {},
nwc_info: {}, // In-memory cache, synced with store
},
},
get wallet() { return mintManager.getActiveWallet(); },
// ── NWC Notifications (NIP-47) ────────────────────────────────────
broadcastToConnection: async (event, app_pubkey) => {
var relays = nutbits.state.nostr_state.pools[app_pubkey];
if (!relays || !Array.isArray(relays)) return 0;
var sent = 0;
for (var relay of relays) {
try {
if (relay.connected) { await relay.publish(event); sent++; }
} catch (e) {
log.warn('notification publish failed', { url: relay.url, error: e.message });
}
}
return sent;
},
sendNotification: async (app_pubkey, notificationType, transaction) => {
var info = nutbits.state.nostr_state.nwc_info[app_pubkey];
if (!info) return;
var payload = JSON.stringify({
notification_type: notificationType,
notification: transaction,
});
var useNip44 = info.useNip44 ?? true;
var encrypted = await nwcEncrypt(info.app_privkey, info.user_pubkey, payload, useNip44);
var event = finalizeEvent({
kind: useNip44 ? 23197 : 23196,
content: encrypted,
tags: [['p', info.user_pubkey]],
created_at: Math.floor(Date.now() / 1000),
}, hexToBytes(info.app_privkey));
var sent = await nutbits.broadcastToConnection(event, app_pubkey);
log.info('NWC notification sent', { type: notificationType, nip44: useNip44, relaysSent: sent });
},
formatTx: tx => {
var result = {
type: tx.type,
state: tx.err_msg ? 'failed' : tx.settled_at ? 'settled' : 'pending',
invoice: tx.invoice,
description: tx.description || '',
description_hash: tx.description_hash || '',
preimage: tx.preimage || '',
payment_hash: tx.payment_hash,
amount: tx.amount,
fees_paid: tx.fees_paid || 0,
created_at: tx.created_at,
expires_at: tx.expires_at,
settled_at: tx.settled_at || null,
metadata: tx.metadata || {},
};
// Optional: include service_fee if present (non-standard NIP-47 extension)
if (tx.service_fee) result.service_fee = tx.service_fee;
return result;
},
// ── Cashu Wallet (via cashu-ts SDK) ────────────────────────────────
initWallet: async () => {
mintManager.orderedMints = config.mintUrls.map(validateMintUrl);
// Ensure each mint has a store entry
for (var url of mintManager.orderedMints) {
await store.ensureMint(url);
}
// Restore activeMintUrl from store (may have been persisted)
var savedActiveMint = await store.getActiveMintUrl();
if (savedActiveMint && mintManager.orderedMints.includes(savedActiveMint)) {
mintManager.activeMintUrl = savedActiveMint;
}
// Populate in-memory NWC connection cache from store
nutbits.state.nostr_state.nwc_info = await store.getAllConnections();
// Try mints in priority order until one responds
for (var url of mintManager.orderedMints) {
try {
var wallet = createWalletForMint(url);
await wallet.loadMint();
mintManager.wallets.set(url, wallet);
mintManager.activeMintUrl = url;
mintManager.mintHealth.set(url, { healthy: true, lastCheck: Date.now(), consecutiveFailures: 0, lastError: null });
await store.setMintInfo(url, { lastHealthy: Date.now() });
await store.setActiveMintUrl(url);
var info = wallet.getMintInfo();
detectMintCaps(wallet, url);
log.info('cashu wallet initialized', { mint: url, name: info.name, version: info.version, keyset: wallet.keysetId });
break;
} catch (e) {
log.warn('mint unreachable at startup, trying next', { mint: url, error: e.message });
mintManager.mintHealth.set(url, { healthy: false, lastCheck: Date.now(), consecutiveFailures: 1, lastError: e.message });
}
}
if (!mintManager.activeMintUrl) {
log.error('ALL MINTS UNREACHABLE AT STARTUP');
process.exit(1);
}
// Pre-create remaining wallets (loaded on demand / failover)
for (var url of mintManager.orderedMints) {
if (!mintManager.wallets.has(url)) {
mintManager.wallets.set(url, createWalletForMint(url));
}
}
if (mintManager.orderedMints.length > 1) {
log.info('multi-mint failover configured', {
active: mintManager.activeMintUrl,
total: mintManager.orderedMints.length,
mints: mintManager.orderedMints,
});
}
},
getBalance: async () => sumProofs(await store.getProofs(mintManager.activeMintUrl)),
getBalanceMsat: async () => sumProofs(await store.getProofs(mintManager.activeMintUrl)) * 1000,
// Sync versions for non-async contexts (uses cached proofs from last store read)
_cachedBalance: 0,
getBalanceSync: () => nutbits._cachedBalance,
getBalanceMsatSync: () => nutbits._cachedBalance * 1000,
refreshBalance: async () => {
nutbits._cachedBalance = sumProofs(await store.getProofs(mintManager.activeMintUrl));
return nutbits._cachedBalance;
},
// Create a Lightning invoice via the mint (NUT-4)
createInvoice: async amountSats => {
var quote = await withFailover(
() => nutbits.wallet.createMintQuoteBolt11(amountSats),
'createInvoice'
);
// Tag quote with originating mint so we can check it on the right wallet
quote._mintUrl = mintManager.activeMintUrl;
log.info('mint quote created', { amount: amountSats, quote: quote.quote, mint: mintManager.activeMintUrl });
return quote;
},
// Check if a mint quote has been paid, and mint tokens if so (NUT-4)
// Uses the originating mint's wallet (not necessarily the active one)
checkAndMintTokens: async (quote, app_pubkey, maxRetries = 3) => {
var quoteMintUrl = quote._mintUrl || mintManager.activeMintUrl;
var quoteWallet = getWalletForMint(quoteMintUrl);
for (var attempt = 0; attempt < maxRetries; attempt++) {
try {
var status = await quoteWallet.checkMintQuoteBolt11(quote.quote);
if (status.state === MintQuoteState.PAID) {
var proofs = await quoteWallet.mintProofsBolt11(amountFromQuote(quote), quote.quote);
// NUT-12: verify DLEQ proofs
proofs = verifyProofsDleq(proofs, quoteWallet, quoteMintUrl);
// Store proofs under the originating mint
await store.addProofs(quoteMintUrl, proofs);
await nutbits.refreshBalance();
log.info('tokens minted', { amount: sumProofs(proofs), proofs: proofs.length, mint: quoteMintUrl });
// Update NWC balance + send payment_received notification
if (app_pubkey && nutbits.state.nostr_state.nwc_info[app_pubkey]) {
var connState = nutbits.state.nostr_state.nwc_info[app_pubkey];
var pmthash = getInvoicePmthash(quote.request);
var txEntry = connState.tx_history[pmthash];
if (txEntry) {
txEntry.settled_at = Math.floor(Date.now() / 1000);
txEntry.paid = true;
await store.updateTx(app_pubkey, pmthash, { settled_at: txEntry.settled_at, paid: true });
// NIP-47 notification: payment_received
nutbits.sendNotification(app_pubkey, 'payment_received', nutbits.formatTx(txEntry)).catch(e =>
log.debug('payment_received notification failed', { error: e.message })
);
}
// Dedicated connections credit incoming payments to their own balance
if (connState.dedicated) {
var receivedMsat = txEntry ? txEntry.amount : (sumProofs(proofs) * 1000);
connState.dedicated_balance_msat = (connState.dedicated_balance_msat || 0) + receivedMsat;
connState.balance = connState.dedicated_balance_msat;
await store.updateConnection(app_pubkey, {
dedicated_balance_msat: connState.dedicated_balance_msat,
balance: connState.dedicated_balance_msat,
});
} else {
var bal = await nutbits.getBalanceMsat();
connState.balance = bal;
await store.updateConnection(app_pubkey, { balance: bal });
}
}
return true;
}
return false;
} catch (e) {
log.error('checkAndMintTokens failed', { error: e.message, attempt: attempt + 1, mint: quoteMintUrl });
if (attempt < maxRetries - 1) await wait(3000 * (attempt + 1));
}
}
log.error('checkAndMintTokens: ALL RETRIES EXHAUSTED', { quote: quote.quote, mint: quoteMintUrl });
return false;
},
// Poll for invoice payment (NUT-4) - iterative to avoid stack overflow
pollInvoice: async (quote, app_pubkey) => {
for (var attempt = 0; attempt < config.maxRetries; attempt++) {
try {
var minted = await nutbits.checkAndMintTokens(quote, app_pubkey);
if (minted) return;
} catch (e) {
log.error('pollInvoice error', { error: e.message });
}
// Check expiry
var pmthash = getInvoicePmthash(quote.request);
var txEntry = nutbits.state.nostr_state.nwc_info[app_pubkey]?.tx_history?.[pmthash];
if (txEntry?.expires_at && Math.floor(Date.now() / 1000) >= txEntry.expires_at) {
log.info('pollInvoice: invoice expired', { pmthash });
return;
}
await wait(config.checkInterval * 1000);
}
log.warn('pollInvoice: max retries', { quote: quote.quote });
},
// NUT-17: Wait for invoice payment via WebSocket (with polling fallback)
waitForPayment: async (quote, app_pubkey) => {
var quoteMintUrl = quote._mintUrl || mintManager.activeMintUrl;
var quoteWallet = getWalletForMint(quoteMintUrl);
var caps = mintManager.mintCaps.get(quoteMintUrl);
if (caps?.nut17) {
try {
log.debug('NUT-17: subscribing to mint quote', { quote: quote.quote, mint: quoteMintUrl });
await quoteWallet.on.onceMintPaid(quote.quote, {
timeoutMs: config.maxRetries * config.checkInterval * 1000,
});
log.info('NUT-17: invoice paid (WebSocket)', { quote: quote.quote });
await nutbits.checkAndMintTokens(quote, app_pubkey, 5);
} catch (e) {
log.warn('NUT-17: WebSocket subscription failed, trying poll fallback', { error: e.message });
await nutbits.pollInvoice(quote, app_pubkey);
}
} else {
await nutbits.pollInvoice(quote, app_pubkey);
}
},
// NUT-09: Restore proofs from seed for a specific mint
restoreFromSeed: async (mintUrl) => {
if (!config.seed) return [];
var caps = mintManager.mintCaps.get(mintUrl);
if (!caps?.nut09) {
log.debug('NUT-09: mint does not support restore', { mint: mintUrl });
return [];
}
try {
var wallet = getWalletForMint(mintUrl);
var result = await wallet.batchRestore();
if (result.proofs.length > 0) {
await store.addProofs(mintUrl, result.proofs);
await nutbits.refreshBalance();
log.info('NUT-09: restored proofs from seed', { mint: mintUrl, count: result.proofs.length, sats: sumProofs(result.proofs) });
} else {
log.debug('NUT-09: no proofs to restore', { mint: mintUrl });
}
return result.proofs;
} catch (e) {
log.error('NUT-09: restore failed', { mint: mintUrl, error: e.message });
return [];
}
},
// Pay a Lightning invoice via the mint (NUT-5)
// Wrapped in per-mint payment lock to prevent concurrent proof selection
payInvoice: async (invoice, app_pubkey) => {
// Snapshot mint URL and wallet BEFORE entering lock - these must not change mid-payment
var payMintUrl = mintManager.activeMintUrl;
var payWallet = mintManager.wallets.get(payMintUrl);
if (!payWallet) throw new Error('no wallet for active mint');
return withPaymentLock(payMintUrl, async () => {
var decoded = bolt11Lib.decode(invoice);
var amountSats = decoded.satoshis;
if (!amountSats) throw new Error('amountless invoices not supported');
// Get melt quote - use snapshotted wallet, no failover mid-payment
var meltQuote;
try {
meltQuote = await payWallet.createMeltQuoteBolt11(invoice);
} catch (e) {
if (isMintDownError(e) && mintManager.orderedMints.length > 1) {
await failoverToNextMint(payMintUrl);
}
throw e; // let caller retry on new mint
}
var totalNeeded = meltQuote.amount + meltQuote.fee_reserve;
var activeProofs = await store.getProofs(payMintUrl);
var balance = sumProofs(activeProofs);
if (totalNeeded > balance) {
throw new Error(`insufficient balance: need ${totalNeeded} sats (inc. ${meltQuote.fee_reserve} fee reserve), have ${balance}`);
}
// Select proofs and pay (bound to snapshotted mint)
var { keep, send } = await payWallet.send(totalNeeded, activeProofs);
// Atomic swap: remove all original proofs, add back keep
await store.swapProofs(payMintUrl, { remove: activeProofs, add: keep });
// Helper: restore proofs on failure - MUST NEVER THROW (funds safety)
var restoreProofs = async (proofsToRestore) => {
try {
await store.addProofs(payMintUrl, proofsToRestore);
} catch (restoreErr) {
// Last resort: write proofs to an encrypted recovery file (never log secrets)
log.error('CRITICAL: failed to restore proofs after payment failure', {
error: restoreErr.message,
mint: payMintUrl,
proofCount: proofsToRestore.length,
totalSats: sumProofs(proofsToRestore),
});
try {
var recoveryPath = (config.stateFile || './nutbits_state.enc') + '.recovery-' + Date.now() + '.enc';
var recoveryBlob = encryptStateForRecovery(config.statePassphrase, JSON.stringify(proofsToRestore));
fs.writeFileSync(recoveryPath, recoveryBlob, { mode: 0o600 });
log.error('CRITICAL: proofs written to encrypted recovery file', { path: recoveryPath });
} catch (writeErr) {
log.error('CRITICAL: could not write recovery file - proofs may be lost', { error: writeErr.message });
}
}
await nutbits.refreshBalance();
};
try {
var meltResult = await payWallet.meltProofsBolt11(meltQuote, send);
if (meltResult.quote.state === 'PAID') {
if (meltResult.change && meltResult.change.length) {
var verifiedChange = verifyProofsDleq(meltResult.change, payWallet, payMintUrl);
await store.addProofs(payMintUrl, verifiedChange);
}
await nutbits.refreshBalance();
log.info('payment succeeded', { preimage: meltResult.quote.payment_preimage, paid: amountSats, mint: payMintUrl });
return {
success: true,
preimage: meltResult.quote.payment_preimage,
fees_paid: (totalNeeded - amountSats - sumProofs(meltResult.change || [])) * 1000,
};
} else {
await restoreProofs(send);
return { success: false, error: 'mint reported payment not paid' };
}
} catch (e) {
log.error('melt failed, restoring proofs', { error: e.message, stack: e.stack, name: e.name, status: e.status, code: e.code });
await restoreProofs(send);
return { success: false, error: e.message };
}
});
},
// ── NWC Connection ─────────────────────────────────────────────────────
createNWCconnection: async (mymint, permissions = ['pay_invoice', 'get_balance', 'make_invoice', 'lookup_invoice', 'list_transactions', 'get_info'], myrelays = config.relays, app_pubkey, waitForRelayReady = true, lud16 = null) => {
mymint = validateMintUrl(mymint);
var getRecipientFromNostrEvent = event => {
for (var i = 0; i < event.tags.length; i++) {
if (event.tags[i]?.[0] === 'p' && event.tags[i][1]) return event.tags[i][1];
}
};
// ── NIP-47 Response Helpers ─────────────────────────────────────
var nwcResult = (method, result) => ({ result_type: method, error: null, result });
var nwcError = (method, code, message) => ({ result_type: method, error: { code, message }, result: null });
var getTxState = tx => {
if (tx.err_msg) return 'failed';
if (tx.settled_at) return 'settled';
return 'pending';
};
var formatTransaction = tx => ({
type: tx.type,
state: getTxState(tx),
invoice: tx.invoice,
description: tx.description || '',
description_hash: tx.description_hash || '',
preimage: tx.preimage || '',
payment_hash: tx.payment_hash,
amount: tx.amount,
fees_paid: tx.fees_paid || 0,
created_at: tx.created_at,
expires_at: tx.expires_at,
settled_at: tx.settled_at || null,
metadata: tx.metadata || {},
});
// Track whether each client prefers NIP-44
var clientUsesNip44 = {};
// Cached blockheight/hash to avoid hammering mempool.space
var blockCache = { height: 0, hash: '', ts: 0 };
var sendNWCResponse = async (state, replyObj, eventPubkey, eventId, app_pubkey) => {
var reply = JSON.stringify(replyObj);
var useNip44 = clientUsesNip44[eventPubkey] ?? true;
log.info('NWC response', { method: replyObj.result_type, hasError: !!replyObj.error, nip44: useNip44 });
var encrypted = await nwcEncrypt(state['app_privkey'], eventPubkey, reply, useNip44);
var event = finalizeEvent({
kind: 23195,
content: encrypted,
tags: [['p', eventPubkey], ['e', eventId]],
created_at: Math.floor(Date.now() / 1000),
}, hexToBytes(state['app_privkey']));
var sent = await broadcastEvent(event, app_pubkey);
log.debug('NWC response published', { relaysSent: sent, responseId: event.id });
};
// ── Daily spend tracking (persisted to store) ────────────────
var trackSpend = async amountSats => {
var today = new Date().toISOString().slice(0, 10);
await store.addDailySpend(app_pubkey, today, amountSats);
};
var getDailySpend = async () => {
var today = new Date().toISOString().slice(0, 10);
return await store.getDailySpend(app_pubkey, today);
};
// ── Handle NWC Events ──────────────────────────────────────────
var handleEvent = async event => {
if (isDuplicate(event.id)) return;
var evtAppPubkey = getRecipientFromNostrEvent(event);
if (!evtAppPubkey || !(evtAppPubkey in nutbits.state.nostr_state.nwc_info)) return;
var state = nutbits.state.nostr_state.nwc_info[evtAppPubkey];
if (state.revoked) return; // revoked connections must not process events
if (event.pubkey !== state['user_pubkey']) return;
// Check NIP-40 expiration
var expirationTag = event.tags.find(t => t[0] === 'expiration');
if (expirationTag) {
var expiry = Number(expirationTag[1]);
if (expiry && expiry < Math.floor(Date.now() / 1000)) {
log.warn('expired event ignored', { eventId: event.id });
return;
}
}
var command;
try {
var { plaintext, nip44: isNip44 } = await nwcDecrypt(state['app_privkey'], event.pubkey, event.content);
clientUsesNip44[event.pubkey] = isNip44;
state.useNip44 = isNip44; // persist for notifications
command = JSON.parse(plaintext);
} catch (e) {
log.error('decrypt/parse failed', { error: e.message });
return;
}
log.info('NWC command', { method: command.method, eventId: event.id, nip44: clientUsesNip44[event.pubkey] });
log.debug('NWC command full', command);
try {
if (!state.permissions.includes(command.method)) {
return await sendNWCResponse(state,
nwcError(command.method, 'RESTRICTED', 'not allowed'),
event.pubkey, event.id, evtAppPubkey);
}
// ── get_info ───────────────────────────────────────────
if (command.method === 'get_info') {
var blockheight = blockCache.height;
var blockhash = blockCache.hash;
if (Date.now() - blockCache.ts > 120_000) { // cache 2 min
try {
var bh = await fetch('https://mempool.space/api/blocks/tip/height', { signal: AbortSignal.timeout(5000) });
blockheight = Number(await bh.text());
var bhr = await fetch(`https://mempool.space/api/block-height/${blockheight}`, { signal: AbortSignal.timeout(5000) });
blockhash = await bhr.text();
blockCache = { height: blockheight, hash: blockhash, ts: Date.now() };
} catch (e) { log.debug('blockheight fetch failed', { error: e.message }); }
}
// Build response - standard NIP-47 fields + optional service_fee metadata
var infoResult = {
alias: 'NUTbits',
color: '',
pubkey: '',
network: 'mainnet',
block_height: blockheight,
block_hash: blockhash,
methods: state.permissions,
notifications: ['payment_received', 'payment_sent'],
};
// Optional: advertise service fee policy so clients can display it
var connFeePpm = state.service_fee_ppm ?? config.serviceFeePpm;
var connFeeBase = state.service_fee_base ?? config.serviceFeeBase;
if (connFeePpm || connFeeBase) {
infoResult.service_fee = {
ppm: connFeePpm || 0,
base_msat: (connFeeBase || 0) * 1000,
applies_to: 'outgoing',
};
}
return await sendNWCResponse(state, nwcResult(command.method, infoResult),
event.pubkey, event.id, evtAppPubkey);
}
// ── get_balance ────────────────────────────────────────
if (command.method === 'get_balance') {
var bal;
if (state.dedicated) {
// Dedicated connections have their own isolated balance
bal = state.dedicated_balance_msat || 0;
} else {
// Non-dedicated connections see global balance minus dedicated allocations
var globalBal = await nutbits.getBalanceMsat();
var allocatedMsat = 0;
for (var [, connInfo] of Object.entries(nutbits.state.nostr_state.nwc_info)) {
if (connInfo.dedicated && !connInfo.revoked) allocatedMsat += (connInfo.dedicated_balance_msat || 0);
}
bal = Math.max(0, globalBal - allocatedMsat);
}
nutbits.state.nostr_state.nwc_info[evtAppPubkey].balance = bal;
return await sendNWCResponse(state,
nwcResult(command.method, { balance: bal }),
event.pubkey, event.id, evtAppPubkey);
}
// ── make_invoice ───────────────────────────────────────
if (command.method === 'make_invoice') {
var params = command.params || {};
if (!params.amount || !String(params.amount).endsWith('000')) {
return await sendNWCResponse(state,
nwcError(command.method, 'OTHER', 'amount must be in millisats and end in 000'),
event.pubkey, event.id, evtAppPubkey);
}
var amountSats = Math.floor(params.amount / 1000);
if (amountSats <= 0 || amountSats > 2_100_000_000_000_000) {
return await sendNWCResponse(state,
nwcError(command.method, 'OTHER', 'amount out of range'),
event.pubkey, event.id, evtAppPubkey);
}
var quote = await nutbits.createInvoice(amountSats);
var decoded = bolt11Lib.decode(quote.request);
var pmthash = getInvoicePmthash(quote.request);
state.tx_history[pmthash] = {
quote,
quoteMintUrl: quote._mintUrl || mintManager.activeMintUrl,
amount: params.amount,
invoice: quote.request,
type: 'incoming',
description: params.description || '',
description_hash: params.description_hash || '',
preimage: '',
payment_hash: pmthash,
fees_paid: 0,
created_at: decoded.timestamp,
expires_at: decoded.timeExpireDate,
settled_at: null,
paid: false,
metadata: {},
};
await store.setTx(evtAppPubkey, pmthash, state.tx_history[pmthash]);
nutbits.waitForPayment(quote, evtAppPubkey).catch(e =>
log.error('waitForPayment failed', { error: e.message, quote: quote.quote })
);
return await sendNWCResponse(state,
nwcResult(command.method, formatTransaction(state.tx_history[pmthash])),
event.pubkey, event.id, evtAppPubkey);
}
// ── lookup_invoice ─────────────────────────────────────
if (command.method === 'lookup_invoice') {
var params = command.params || {};
var invoice = params.invoice || params.bolt11 || null;
var pmthash = null;
if (invoice) {
try { pmthash = getInvoicePmthash(invoice); } catch (e) {}
}
if (!pmthash && params.payment_hash) pmthash = params.payment_hash;
log.debug('lookup_invoice', { hasInvoice: !!invoice, hasPmthash: !!pmthash, paramKeys: Object.keys(params), knownTxs: Object.keys(state.tx_history).length });
if (!pmthash || !(pmthash in state.tx_history)) {
return await sendNWCResponse(state,
nwcError(command.method, 'NOT_FOUND', 'invoice not found'),
event.pubkey, event.id, evtAppPubkey);
}
// Check if incoming invoice has been paid (use originating mint)
var tx = state.tx_history[pmthash];
if (tx.type === 'incoming' && !tx.settled_at && tx.quote) {
if (tx.quoteMintUrl) tx.quote._mintUrl = tx.quoteMintUrl;
await nutbits.checkAndMintTokens(tx.quote, evtAppPubkey);
tx = state.tx_history[pmthash]; // re-read after potential update
}
if (tx.err_msg) {
return await sendNWCResponse(state,
nwcError(command.method, 'OTHER', tx.err_msg),
event.pubkey, event.id, evtAppPubkey);
}
return await sendNWCResponse(state,
nwcResult(command.method, formatTransaction(tx)),
event.pubkey, event.id, evtAppPubkey);
}
// ── list_transactions ──────────────────────────────────
if (command.method === 'list_transactions') {
var params = command.params || {};
var txs = Object.values(state.tx_history);
if (!params.unpaid) txs = txs.filter(tx => tx.paid);
if (params.type === 'incoming') txs = txs.filter(tx => tx.type === 'incoming');
if (params.type === 'outgoing') txs = txs.filter(tx => tx.type === 'outgoing');
txs.sort((a, b) => b.created_at - a.created_at);
if (params.from) txs = txs.filter(tx => tx.created_at >= params.from);
if (params.until) txs = txs.filter(tx => tx.created_at <= params.until);
if (params.offset) txs = txs.slice(params.offset);
var limit = Math.min(Number(params.limit) || 50, 200);
txs = txs.slice(0, limit);
return await sendNWCResponse(state,
nwcResult(command.method, { transactions: txs.map(formatTransaction) }),
event.pubkey, event.id, evtAppPubkey);
}
// ── pay_invoice ────────────────────────────────────────
if (command.method === 'pay_invoice') {
var params = command.params || {};
var invoice = params.invoice || params.bolt11;
if (!invoice) {
return await sendNWCResponse(state,
nwcError(command.method, 'OTHER', 'missing invoice'),
event.pubkey, event.id, evtAppPubkey);
}
var decodedInvoice;
try {
decodedInvoice = bolt11Lib.decode(invoice);
} catch (e) {
return await sendNWCResponse(state,
nwcError(command.method, 'OTHER', 'cannot decode invoice'),
event.pubkey, event.id, evtAppPubkey);
}
var pmthash = getInvoicePmthash(invoice);
var invoice_amt = decodedInvoice.satoshis;
// Reject duplicate payment for same invoice
if (state.tx_history[pmthash]?.paid) {