forked from wadadawadada/blackbox_node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
5593 lines (5110 loc) · 205 KB
/
server.js
File metadata and controls
5593 lines (5110 loc) · 205 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
const http = require("http");
const fs = require("fs");
const path = require("path");
const zlib = require("zlib");
const { spawnSync, spawn } = require("child_process");
const { webcrypto } = require("crypto");
// cashu-ts expects Web Crypto APIs on globalThis.
// Older Node runtimes may not expose them there by default.
if ((!globalThis.crypto || typeof globalThis.crypto.getRandomValues !== "function") && webcrypto) {
Object.defineProperty(globalThis, "crypto", {
value: webcrypto,
configurable: true,
writable: true,
});
}
const HOST = "127.0.0.1";
const DEFAULT_PORT = 7860;
const parsedPort = Number.parseInt(process.env.PORT || "", 10);
const PORT = Number.isInteger(parsedPort) && parsedPort > 0 ? parsedPort : DEFAULT_PORT;
const STATIC_DIR = path.join(__dirname, "static");
const DATA_DIR = path.join(__dirname, "data");
const TAK_CAPTURE_DIR = path.join(DATA_DIR, "tak_capture");
const DB_FILE = path.join(DATA_DIR, "messages.json");
const NODES_FILE = path.join(DATA_DIR, "nodes.json");
const SETTINGS_FILE = path.join(DATA_DIR, "settings.json");
const WALLET_FILE = path.join(DATA_DIR, "wallet.json");
const CASHU_FILE = path.join(DATA_DIR, "cashu.json");
const TEST_WALLET_FILE = path.join(DATA_DIR, "test_wallet.json");
const TEST_CASHU_FILE = path.join(DATA_DIR, "test_cashu.json");
const TEST_CASHU_DEFAULT_MINT = "https://cashu.mutinynet.com";
const MUTINYNET_FAUCET_URL = "https://faucet.mutinynet.com";
const SWAPS_FILE = path.join(DATA_DIR, "swaps.json");
const PYDEPS_DIR = path.join(__dirname, "pydeps");
const LLAMA_DIR = path.join(__dirname, "llama");
const LLAMA_EXE = process.platform === "win32"
? path.join(LLAMA_DIR, "llama-server.exe")
: (() => { try { return require("child_process").execSync("which llama-server", { encoding: "utf8" }).trim(); } catch { return path.join(LLAMA_DIR, "llama-server"); } })();
const MODELS_DIR = path.join(__dirname, "models");
const LLM_HOST = "127.0.0.1";
const LLM_PORT = (() => {
const env = parseInt(process.env.LLM_PORT, 10);
return Number.isInteger(env) && env > 0 ? env : 8080;
})();
const LLM_BASE_URL = `http://${LLM_HOST}:${LLM_PORT}`;
const DEFAULT_MODEL_NAME = "Qwen2.5-0.5B-Instruct-Q3_K_M.gguf";
const CURATED_MODELS = [
{
id: "qwen25-05b-q3km",
name: "Qwen2.5 0.5B Instruct Q3_K_M",
filename: "Qwen2.5-0.5B-Instruct-Q3_K_M.gguf",
url: "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q3_k_m.gguf?download=true",
sizeBytes: 318000000,
family: "Qwen",
notes: "Smallest practical Qwen chat option.",
},
{
id: "qwen25-05b-q4km",
name: "Qwen2.5 0.5B Instruct Q4_K_M",
filename: "Qwen2.5-0.5B-Instruct-Q4_K_M.gguf",
url: "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf?download=true",
sizeBytes: 397808192,
family: "Qwen",
notes: "Fastest small local chat model.",
},
{
id: "qwen25-05b-q5km",
name: "Qwen2.5 0.5B Instruct Q5_K_M",
filename: "Qwen2.5-0.5B-Instruct-Q5_K_M.gguf",
url: "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q5_k_m.gguf?download=true",
sizeBytes: 447000000,
family: "Qwen",
notes: "Small model with slightly better quality than Q4_K_M.",
},
{
id: "qwen25-15b-q5km",
name: "Qwen2.5 1.5B Instruct Q5_K_M",
filename: "Qwen2.5-1.5B-Instruct-Q5_K_M.gguf",
url: "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q5_k_m.gguf?download=true",
sizeBytes: 1270000000,
family: "Qwen",
notes: "Balanced small model with better quality than 0.5B.",
},
{
id: "qwen25-15b-q4km",
name: "Qwen2.5 1.5B Instruct Q4_K_M",
filename: "Qwen2.5-1.5B-Instruct-Q4_K_M.gguf",
url: "https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF/resolve/main/qwen2.5-1.5b-instruct-q4_k_m.gguf?download=true",
sizeBytes: 1010000000,
family: "Qwen",
notes: "Smaller disk and RAM footprint than the Q5 build.",
},
{
id: "qwen25-3b-q5km",
name: "Qwen2.5 3B Instruct Q5_K_M",
filename: "Qwen2.5-3B-Instruct-Q5_K_M.gguf",
url: "https://huggingface.co/Qwen/Qwen2.5-3B-Instruct-GGUF/resolve/main/qwen2.5-3b-instruct-q5_k_m.gguf?download=true",
sizeBytes: 2438740384,
family: "Qwen",
notes: "Current recommended general-purpose local model.",
},
{
id: "qwen25-3b-q4km",
name: "Qwen2.5 3B Instruct Q4_K_M",
filename: "Qwen2.5-3B-Instruct-Q4_K_M.gguf",
url: "https://huggingface.co/Qwen/Qwen2.5-3B-Instruct-GGUF/resolve/main/qwen2.5-3b-instruct-q4_k_m.gguf?download=true",
sizeBytes: 2120000000,
family: "Qwen",
notes: "Compact 3B option if Q5 is too heavy.",
},
{
id: "qwen25-coder-05b-q4km",
name: "Qwen2.5 Coder 0.5B Instruct Q4_K_M",
filename: "qwen2.5-0.5b-coder-instruct-q4_k_m.gguf",
url: "https://huggingface.co/Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-coder-instruct-q4_k_m.gguf?download=true",
sizeBytes: 491000000,
family: "Qwen Coder",
notes: "Tiny coding-focused model for weak machines.",
},
{
id: "qwen25-coder-15b-q5km",
name: "Qwen2.5 Coder 1.5B Instruct Q5_K_M",
filename: "Qwen2.5-Coder-1.5B-Instruct.Q5_K_M.gguf",
url: "https://huggingface.co/MaziyarPanahi/Qwen2.5-Coder-1.5B-Instruct-GGUF/resolve/main/Qwen2.5-Coder-1.5B-Instruct.Q5_K_M.gguf?download=true",
sizeBytes: 1130000000,
family: "Qwen Coder",
notes: "Compact coding model with better reasoning than 0.5B.",
},
{
id: "qwen25-coder-3b-q4km",
name: "Qwen2.5 Coder 3B Instruct Q4_K_M",
filename: "qwen2.5-3b-coder-instruct-q4_k_m.gguf",
url: "https://huggingface.co/Qwen/Qwen2.5-Coder-3B-Instruct-GGUF/resolve/main/qwen2.5-3b-coder-instruct-q4_k_m.gguf?download=true",
sizeBytes: 2100000000,
family: "Qwen Coder",
notes: "Better fit for code-heavy local chat and debugging.",
},
{
id: "smollm2-135m-iq4xs",
name: "SmolLM2 135M Instruct IQ4_XS",
filename: "SmolLM2-135M-Instruct-IQ4_XS.gguf",
url: "https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-IQ4_XS.gguf?download=true",
sizeBytes: 90897760,
family: "SmolLM",
notes: "Ultra-small fallback model.",
},
{
id: "smollm2-135m-q3km",
name: "SmolLM2 135M Instruct Q3_K_M",
filename: "SmolLM2-135M-Instruct-Q3_K_M.gguf",
url: "https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q3_K_M.gguf?download=true",
sizeBytes: 94000000,
family: "SmolLM",
notes: "Absolute minimum-size chat model in the catalog.",
},
{
id: "smollm2-360m-q4km",
name: "SmolLM2 360M Instruct Q4_K_M",
filename: "SmolLM2-360M-Instruct-Q4_K_M.gguf",
url: "https://huggingface.co/HuggingFaceTB/SmolLM2-360M-Instruct-GGUF/resolve/main/SmolLM2-360M-Instruct-Q4_K_M.gguf?download=true",
sizeBytes: 244000000,
family: "SmolLM",
notes: "Still lightweight, but much more usable than 135M.",
},
{
id: "tinyllama-11b-q4km",
name: "TinyLlama 1.1B Chat v1.0 Q4_K_M",
filename: "tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf",
url: "https://huggingface.co/TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf?download=true",
sizeBytes: 670000000,
family: "TinyLlama",
notes: "Very small general chat model that is still reasonably usable.",
},
{
id: "deepseek-coder-13b-q4km",
name: "DeepSeek Coder 1.3B Instruct Q4_K_M",
filename: "deepseek-coder-1.3b-instruct.Q4_K_M.gguf",
url: "https://huggingface.co/TheBloke/deepseek-coder-1.3b-instruct-GGUF/resolve/main/deepseek-coder-1.3b-instruct.Q4_K_M.gguf?download=true",
sizeBytes: 813000000,
family: "DeepSeek Coder",
notes: "Small dedicated code model with solid code completion quality.",
},
{
id: "stable-code-3b-q4km",
name: "Stable Code 3B Q4_K_M",
filename: "stable-code-3b.Q4_K_M.gguf",
url: "https://huggingface.co/TheBloke/stable-code-3b-GGUF/resolve/main/stable-code-3b.Q4_K_M.gguf?download=true",
sizeBytes: 1710000000,
family: "Stable Code",
notes: "Code-specialized 3B model for programming tasks.",
},
{
id: "mistral-7b-v03-q4km",
name: "Mistral 7B Instruct v0.3 Q4_K_M",
filename: "mistral-7b-instruct-v0.3.Q4_K_M.gguf",
url: "https://huggingface.co/SanctumAI/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/mistral-7b-instruct-v0.3.Q4_K_M.gguf?download=true",
sizeBytes: 4370000000,
family: "Mistral",
notes: "Heavier but stronger instruction model.",
},
{
id: "mistral-7b-v03-q5km",
name: "Mistral 7B Instruct v0.3 Q5_K_M",
filename: "mistral-7b-instruct-v0.3.Q5_K_M.gguf",
url: "https://huggingface.co/SanctumAI/Mistral-7B-Instruct-v0.3-GGUF/resolve/main/mistral-7b-instruct-v0.3.Q5_K_M.gguf?download=true",
sizeBytes: 5140000000,
family: "Mistral",
notes: "Higher-quality Mistral build if you can spare the RAM.",
},
];
const HISTORY_LIMIT = 8;
const RESPONSE_CHAR_LIMIT = 900;
const LOCAL_CHAT_MAX_TOKENS = 384;
const DEFAULT_AI_SETTINGS = Object.freeze({
sendCustomInstructions: false,
customInstructions: "",
localTemperature: 0.1,
localTopP: 0.7,
localMaxTokens: LOCAL_CHAT_MAX_TOKENS,
meshTemperature: 0.1,
meshTopP: 0.6,
meshMaxTokens: 120,
});
const MESH_PACKET_MAX_BYTES = 120;
const MESH_PACKET_MAX_BYTES_CASHU = 72;
const MESH_PACKET_BATCH_DELAY_MS = 3200;
const MESH_PACKET_BATCH_DELAY_MS_CASHU = 6000;
const MESH_ACK_RETRY_COUNT = 1;
const MESH_ACK_RETRY_DELAY_MS = 1800;
const WEATHER_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
const NODE_ONLINE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
const MIN_VALID_MODEL_BYTES = 1024 * 1024;
const sessions = new Map();
const clients = new Set();
const latestTakFeatures = new Map(); // uid -> feature
let nodesRefreshInterval = null;
let messages = [];
let knownNodes = {};
let appSettings = {};
let walletData = null;
let cashuData = { mintUrl: "", proofs: [], pendingInvoices: [], pendingSwapProofs: [], receivedSecrets: [], offgridSecrets: [], offgridPackets: [], history: [] };
let testWalletData = null;
let testCashuData = { mintUrl: TEST_CASHU_DEFAULT_MINT, proofs: [], pendingInvoices: [], pendingSwapProofs: [], receivedSecrets: [], offgridSecrets: [], offgridPackets: [], history: [] };
let swaps = [];
let meshtasticStatus = { connected: false, mode: "starting", error: null };
let localMeshNodeId = null;
// Observed mesh links from relayNode field in packets: key = "fromMeshNum|viaMeshNum"
const MESH_LINK_TTL_MS = 30 * 60 * 1000; // 30 min
let meshLinks = {};
let currentModelName = DEFAULT_MODEL_NAME;
let llmStatus = { connected: false, mode: "starting", model: currentModelName, error: null, switching: false };
let meshSendQueue = Promise.resolve();
// Map clientMsgId -> message.id (for linking sent event to outgoing message)
const pendingMsgByClientId = new Map();
// Map packetId -> message.id (for linking routing ack to outgoing message)
const pendingMsgByPacketId = new Map();
let modelManagerOperation = {
active: false,
action: null,
modelId: null,
modelName: null,
error: null,
progress: 0,
bytesDownloaded: 0,
bytesTotal: 0,
};
let modelDownloadAbortController = null;
fs.mkdirSync(DATA_DIR, { recursive: true });
fs.mkdirSync(TAK_CAPTURE_DIR, { recursive: true });
if (fs.existsSync(DB_FILE)) {
try {
messages = JSON.parse(fs.readFileSync(DB_FILE, "utf8"));
} catch {
messages = [];
}
}
if (fs.existsSync(NODES_FILE)) {
try {
knownNodes = JSON.parse(fs.readFileSync(NODES_FILE, "utf8"));
} catch {
knownNodes = {};
}
}
if (fs.existsSync(SETTINGS_FILE)) {
try {
appSettings = JSON.parse(fs.readFileSync(SETTINGS_FILE, "utf8"));
} catch {
appSettings = {};
}
}
if (fs.existsSync(WALLET_FILE)) {
try {
walletData = JSON.parse(fs.readFileSync(WALLET_FILE, "utf8"));
} catch {
walletData = null;
}
}
if (fs.existsSync(CASHU_FILE)) {
try {
const loaded = JSON.parse(fs.readFileSync(CASHU_FILE, "utf8"));
cashuData = { mintUrl: "", proofs: [], pendingInvoices: [], pendingSwapProofs: [], receivedSecrets: [], offgridSecrets: [], offgridPackets: [], history: [], ...loaded };
if (!Array.isArray(cashuData.offgridSecrets)) {
cashuData.offgridSecrets = (cashuData.proofs || []).map((proof) => String(proof?.secret || "")).filter(Boolean);
}
} catch { /* keep defaults */ }
}
if (fs.existsSync(TEST_WALLET_FILE)) {
try {
testWalletData = JSON.parse(fs.readFileSync(TEST_WALLET_FILE, "utf8"));
} catch {
testWalletData = null;
}
}
if (fs.existsSync(TEST_CASHU_FILE)) {
try {
const loaded = JSON.parse(fs.readFileSync(TEST_CASHU_FILE, "utf8"));
testCashuData = { mintUrl: TEST_CASHU_DEFAULT_MINT, proofs: [], pendingInvoices: [], pendingSwapProofs: [], receivedSecrets: [], offgridSecrets: [], offgridPackets: [], history: [], ...loaded };
if (!Array.isArray(testCashuData.offgridSecrets)) {
testCashuData.offgridSecrets = (testCashuData.proofs || []).map((proof) => String(proof?.secret || "")).filter(Boolean);
}
// Always enforce signet mint for test mode — never allow mainnet mint in test mode
if (!testCashuData.mintUrl || getMintNetwork(testCashuData.mintUrl) === "mainnet") {
testCashuData.mintUrl = TEST_CASHU_DEFAULT_MINT;
}
} catch { /* keep defaults */ }
}
if (fs.existsSync(SWAPS_FILE)) {
try { swaps = JSON.parse(fs.readFileSync(SWAPS_FILE, "utf8")); } catch { swaps = []; }
}
if (typeof appSettings.lastModelName === "string" && appSettings.lastModelName.trim()) {
currentModelName = appSettings.lastModelName.trim();
llmStatus = { ...llmStatus, model: currentModelName };
}
appSettings.aiSettings = normalizeAiSettings(appSettings.aiSettings);
function getConfiguredMeshtasticPort() {
return typeof appSettings.meshtasticPort === "string" && appSettings.meshtasticPort.trim()
? appSettings.meshtasticPort.trim()
: "";
}
function getConfiguredTakChannel() {
return normalizeChannelIndex(appSettings.takMeshtasticChannel, 0);
}
function setConfiguredTakChannel(channel) {
appSettings.takMeshtasticChannel = normalizeChannelIndex(channel, 0);
persistSettings();
}
function normalizeChannelIndex(value, fallback = 0) {
const parsed = Number.parseInt(String(value ?? fallback), 10);
return Number.isInteger(parsed) && parsed >= 0 && parsed <= 7 ? parsed : fallback;
}
function getConfiguredTakHopLimit() {
const value = Number.parseInt(String(appSettings.takHopLimit ?? "3"), 10);
return Number.isInteger(value) && value >= 0 && value <= 7 ? value : 3;
}
function setConfiguredTakHopLimit(hopLimit) {
const value = Number.parseInt(String(hopLimit ?? "3"), 10);
appSettings.takHopLimit = Number.isInteger(value) && value >= 0 && value <= 7 ? value : 3;
persistSettings();
}
function setConfiguredMeshtasticPort(port) {
const value = String(port || "").trim();
if (value) {
appSettings.meshtasticPort = value;
} else {
delete appSettings.meshtasticPort;
}
persistSettings();
}
function getMeshtasticStatusPayload(overrides = {}) {
return {
...meshtasticStatus,
selectedPort: getConfiguredMeshtasticPort() || null,
takChannel: getConfiguredTakChannel(),
takHopLimit: getConfiguredTakHopLimit(),
...overrides,
};
}
function updateMeshtasticStatus(patch = {}, broadcastNow = true) {
meshtasticStatus = getMeshtasticStatusPayload(patch);
if (broadcastNow) {
broadcast("status", { meshtastic: meshtasticStatus });
}
return meshtasticStatus;
}
meshtasticStatus = getMeshtasticStatusPayload();
function persistMessages() {
fs.writeFileSync(DB_FILE, JSON.stringify(messages.slice(-300), null, 2));
}
function persistNodes() {
fs.writeFileSync(NODES_FILE, JSON.stringify(knownNodes, null, 2));
}
function persistSettings() {
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(appSettings, null, 2));
}
// ─── Wallet ──────────────────────────────────────────────────────────────────
function isTestMode() {
return typeof appSettings.walletTestMode === "boolean" ? appSettings.walletTestMode : true;
}
function isMeshAiReplyEnabled() {
return Boolean(appSettings.meshAiReply);
}
function getActiveWalletData() {
return isTestMode() ? testWalletData : walletData;
}
function getActiveCashuData() {
return isTestMode() ? testCashuData : cashuData;
}
function persistActiveCashu() {
if (isTestMode()) {
fs.writeFileSync(TEST_CASHU_FILE, JSON.stringify(testCashuData, null, 2), "utf8");
} else {
fs.writeFileSync(CASHU_FILE, JSON.stringify(cashuData, null, 2), "utf8");
}
}
const _cashuOpLocks = new Map();
function getCashuLockKey() {
return isTestMode() ? "test" : "prod";
}
async function withCashuLock(fn) {
const key = getCashuLockKey();
const previous = _cashuOpLocks.get(key) || Promise.resolve();
let release;
const current = new Promise((resolve) => { release = resolve; });
const queued = previous.finally(() => current);
_cashuOpLocks.set(key, queued);
await previous;
try {
return await fn();
} finally {
release();
if (_cashuOpLocks.get(key) === queued) {
_cashuOpLocks.delete(key);
}
}
}
function normalizeCashuError(error) {
const message = String(error?.message || error || "Cashu operation failed");
if (message.toLowerCase().includes("token already spent")) {
return "Cashu proofs were already spent. This usually means the same send/payment was submitted twice or the local wallet state is stale.";
}
return message;
}
function persistWallet() {
if (walletData) {
fs.writeFileSync(WALLET_FILE, JSON.stringify(walletData, null, 2), "utf8");
} else if (fs.existsSync(WALLET_FILE)) {
fs.unlinkSync(WALLET_FILE);
}
}
function persistTestWallet() {
if (testWalletData) {
fs.writeFileSync(TEST_WALLET_FILE, JSON.stringify(testWalletData, null, 2), "utf8");
} else if (fs.existsSync(TEST_WALLET_FILE)) {
fs.unlinkSync(TEST_WALLET_FILE);
}
}
function createWallet() {
const { generateMnemonic, mnemonicToSeedSync } = require("@scure/bip39");
const { wordlist } = require("@scure/bip39/wordlists/english");
const { HDKey } = require("@scure/bip32");
const { sha256 } = require("@noble/hashes/sha256");
const { ripemd160 } = require("@noble/hashes/ripemd160");
const { bech32 } = require("@scure/base");
const mnemonic = generateMnemonic(wordlist, 128);
const seed = mnemonicToSeedSync(mnemonic);
const root = HDKey.fromMasterSeed(seed);
const addresses = [];
for (let i = 0; i < 5; i++) {
const child = root.derive(`m/84'/0'/0'/0/${i}`);
const pubkey = child.publicKey;
const pubkeyHash = ripemd160(sha256(pubkey));
const words5 = bech32.toWords(pubkeyHash);
addresses.push(bech32.encode("bc", [0, ...words5]));
}
walletData = {
address: addresses[0],
addresses,
derivationPath: "m/84'/0'/0'/0/0",
network: "mainnet",
type: "P2WPKH",
createdAt: new Date().toISOString(),
mnemonic,
};
persistWallet();
return { address: addresses[0], mnemonic, addresses };
}
function createTestWallet() {
const { generateMnemonic, mnemonicToSeedSync } = require("@scure/bip39");
const { wordlist } = require("@scure/bip39/wordlists/english");
const { HDKey } = require("@scure/bip32");
const { sha256 } = require("@noble/hashes/sha256");
const { ripemd160 } = require("@noble/hashes/ripemd160");
const { bech32 } = require("@scure/base");
const mnemonic = generateMnemonic(wordlist, 128);
const seed = mnemonicToSeedSync(mnemonic);
const root = HDKey.fromMasterSeed(seed);
const addresses = [];
for (let i = 0; i < 5; i++) {
const child = root.derive(`m/84'/1'/0'/0/${i}`);
const pubkey = child.publicKey;
const pubkeyHash = ripemd160(sha256(pubkey));
const words5 = bech32.toWords(pubkeyHash);
addresses.push(bech32.encode("tb", [0, ...words5]));
}
testWalletData = {
address: addresses[0],
addresses,
derivationPath: "m/84'/1'/0'/0/0",
network: "testnet",
type: "P2WPKH",
createdAt: new Date().toISOString(),
mnemonic,
};
persistTestWallet();
return { address: addresses[0], mnemonic, addresses };
}
function getWalletPayload() {
const data = getActiveWalletData();
if (!data) {
return {
configured: false,
testMode: isTestMode(),
};
}
return {
configured: true,
testMode: isTestMode(),
address: data.address,
addresses: data.addresses || [data.address],
derivationPath: data.derivationPath,
network: data.network,
type: data.type,
createdAt: data.createdAt,
mnemonic: data.mnemonic || null,
};
}
function getMempoolBase() {
return isTestMode() ? "https://mutinynet.com/api" : "https://mempool.space/api";
}
async function fetchBtcBalance(address) {
const https = require("https");
return new Promise((resolve) => {
const url = `${getMempoolBase()}/address/${encodeURIComponent(address)}`;
const req = https.get(url, { timeout: 8000 }, (res) => {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
try {
const data = JSON.parse(body);
const chain = data.chain_stats || {};
const mem = data.mempool_stats || {};
const confirmed = (chain.funded_txo_sum || 0) - (chain.spent_txo_sum || 0);
const unconfirmed = (mem.funded_txo_sum || 0) - (mem.spent_txo_sum || 0);
resolve({ confirmed, unconfirmed, total: confirmed + unconfirmed, txCount: (chain.tx_count || 0) + (mem.tx_count || 0) });
} catch {
resolve(null);
}
});
});
req.on("error", () => resolve(null));
req.on("timeout", () => { req.destroy(); resolve(null); });
});
}
async function fetchBtcTransactions(address) {
const https = require("https");
return new Promise((resolve) => {
const url = `${getMempoolBase()}/address/${encodeURIComponent(address)}/txs`;
const req = https.get(url, { timeout: 10000 }, (res) => {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
try {
const txs = JSON.parse(body);
if (!Array.isArray(txs)) { resolve([]); return; }
const result = txs.slice(0, 20).map((tx) => {
const myVouts = (tx.vout || []).filter((v) => v.scriptpubkey_address === address);
const myVins = (tx.vin || []).filter((v) => v.prevout && v.prevout.scriptpubkey_address === address);
const received = myVouts.reduce((s, v) => s + (v.value || 0), 0);
const spent = myVins.reduce((s, v) => s + (v.prevout.value || 0), 0);
const net = received - spent;
return {
txid: tx.txid,
direction: net >= 0 ? "Received" : "Sent",
amount: Math.abs(net),
confirmed: tx.status && tx.status.confirmed,
blockTime: tx.status && tx.status.block_time ? new Date(tx.status.block_time * 1000).toLocaleString() : "Pending",
};
});
resolve(result);
} catch {
resolve([]);
}
});
});
req.on("error", () => resolve([]));
req.on("timeout", () => { req.destroy(); resolve([]); });
});
}
async function generateWalletQr(address) {
const QRCode = require("qrcode");
return QRCode.toDataURL(`bitcoin:${address}`, { width: 180, margin: 1, color: { dark: "#f2f8ff", light: "#151d27" } });
}
async function fetchBtcUtxos(address) {
const https = require("https");
return new Promise((resolve) => {
const url = `${getMempoolBase()}/address/${encodeURIComponent(address)}/utxo`;
const req = https.get(url, { timeout: 8000 }, (res) => {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
try { resolve(JSON.parse(body)); } catch { resolve([]); }
});
});
req.on("error", () => resolve([]));
req.on("timeout", () => { req.destroy(); resolve([]); });
});
}
async function fetchFeeEstimate() {
const https = require("https");
return new Promise((resolve) => {
const url = `${getMempoolBase()}/v1/fees/recommended`;
const req = https.get(url, { timeout: 8000 }, (res) => {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
try { resolve(JSON.parse(body)); } catch { resolve({ fastestFee: 10, halfHourFee: 5, hourFee: 3, minimumFee: 1 }); }
});
});
req.on("error", () => resolve({ fastestFee: 10, halfHourFee: 5, hourFee: 3, minimumFee: 1 }));
req.on("timeout", () => { req.destroy(); resolve({ fastestFee: 10, halfHourFee: 5, hourFee: 3, minimumFee: 1 }); });
});
}
function deriveWalletKey() {
const { mnemonicToSeedSync } = require("@scure/bip39");
const { HDKey } = require("@scure/bip32");
const wd = getActiveWalletData();
const seed = mnemonicToSeedSync(wd.mnemonic);
return HDKey.fromMasterSeed(seed).derive(wd.derivationPath);
}
async function buildAndBroadcastBtcTx(toAddress, amountSats, feeRateSatPerVb) {
const { Transaction, p2wpkh } = require("@scure/btc-signer");
const btcNet = isTestMode() ? require("@scure/btc-signer").TEST_NETWORK : undefined;
const https = require("https");
const key = deriveWalletKey();
const myAddress = getActiveWalletData().address;
const script = p2wpkh(key.publicKey, btcNet).script;
const utxos = await fetchBtcUtxos(myAddress);
const confirmedUtxos = utxos.filter((u) => u.status && u.status.confirmed);
if (!confirmedUtxos.length) throw new Error("No confirmed UTXOs — wallet has no spendable funds");
// vbyte estimates for P2WPKH: overhead=10, input=68, output=31
// Select UTXOs greedily
const selected = [];
let inputTotal = 0n;
for (const utxo of confirmedUtxos) {
selected.push(utxo);
inputTotal += BigInt(utxo.value);
const estVbytes = 10 + selected.length * 68 + 31 * 2;
const estFee = BigInt(Math.ceil(estVbytes * feeRateSatPerVb));
if (inputTotal >= BigInt(amountSats) + estFee) break;
}
const estVbytes = 10 + selected.length * 68 + 31 * 2;
const fee = BigInt(Math.ceil(estVbytes * feeRateSatPerVb));
const changeAmount = inputTotal - BigInt(amountSats) - fee;
if (changeAmount < 0n) throw new Error(`Insufficient funds: need ${amountSats + Number(fee)} sats, have ${Number(inputTotal)}`);
const tx = new Transaction();
for (const utxo of selected) {
tx.addInput({
txid: utxo.txid,
index: utxo.vout,
witnessUtxo: { script, amount: BigInt(utxo.value) },
});
}
tx.addOutputAddress(toAddress, BigInt(amountSats), btcNet);
if (changeAmount >= 546n) {
tx.addOutputAddress(myAddress, changeAmount, btcNet);
}
tx.sign(key.privateKey);
tx.finalize();
const rawHex = tx.hex;
// Broadcast
return new Promise((resolve, reject) => {
const mempoolBase = getMempoolBase();
const url = new URL(`${mempoolBase}/tx`);
const options = {
hostname: url.hostname,
path: url.pathname,
method: "POST",
headers: { "Content-Type": "text/plain", "Content-Length": Buffer.byteLength(rawHex) },
timeout: 15000,
};
const req = https.request(options, (res) => {
let body = "";
res.on("data", (d) => { body += d; });
res.on("end", () => {
if (res.statusCode === 200) { resolve({ txid: body.trim(), fee: Number(fee) }); }
else { reject(new Error(`Broadcast failed (${res.statusCode}): ${body.trim().slice(0, 200)}`)); }
});
});
req.on("error", reject);
req.on("timeout", () => { req.destroy(); reject(new Error("Broadcast timeout")); });
req.write(rawHex);
req.end();
});
}
// ─── End Wallet ───────────────────────────────────────────────────────────────
// ─── Cashu ────────────────────────────────────────────────────────────────────
function persistCashu() {
fs.writeFileSync(CASHU_FILE, JSON.stringify(cashuData, null, 2), "utf8");
}
function getProofsBalance(proofs) {
return (Array.isArray(proofs) ? proofs : []).reduce((sum, p) => sum + (p.amount || 0), 0);
}
function getCashuBalance() {
return getProofsBalance(getActiveCashuData().proofs || []);
}
function getCashuPendingBalance() {
return getProofsBalance(getActiveCashuData().pendingSwapProofs || []);
}
function createCashuOffgridPacket(proofs, amountOverride = null) {
const secrets = [...new Set((Array.isArray(proofs) ? proofs : [])
.map((proof) => String(proof?.secret || "").trim())
.filter(Boolean))];
return {
id: `pkt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`,
amount: Math.max(0, Number(amountOverride ?? getProofsBalance(proofs)) || 0),
secrets,
};
}
function syncCashuOffgridState(cd = getActiveCashuData()) {
const proofMap = new Map();
for (const proof of Array.isArray(cd.proofs) ? cd.proofs : []) {
const secret = String(proof?.secret || "").trim();
if (secret) proofMap.set(secret, proof);
}
const normalizedPackets = [];
const assignedSecrets = new Set();
const hasPacketArray = Array.isArray(cd.offgridPackets);
const sourcePackets = hasPacketArray ? cd.offgridPackets : null;
const hasLegacySecrets = Array.isArray(cd.offgridSecrets) && cd.offgridSecrets.length > 0;
if (hasPacketArray && (sourcePackets.length > 0 || !hasLegacySecrets)) {
for (const packet of sourcePackets) {
const packetSecrets = [];
for (const rawSecret of Array.isArray(packet?.secrets) ? packet.secrets : []) {
const secret = String(rawSecret || "").trim();
if (!secret || assignedSecrets.has(secret) || !proofMap.has(secret)) continue;
assignedSecrets.add(secret);
packetSecrets.push(secret);
}
if (!packetSecrets.length) continue;
const amount = packetSecrets.reduce((sum, secret) => sum + Number(proofMap.get(secret)?.amount || 0), 0);
normalizedPackets.push({
id: String(packet?.id || createCashuOffgridPacket([], 0).id),
amount,
secrets: packetSecrets,
});
}
} else {
const legacySecrets = [...new Set((Array.isArray(cd.offgridSecrets) ? cd.offgridSecrets : [])
.map((secret) => String(secret || "").trim())
.filter(Boolean))];
for (const secret of legacySecrets) {
if (assignedSecrets.has(secret)) continue;
const proof = proofMap.get(secret);
if (!proof) continue;
assignedSecrets.add(secret);
normalizedPackets.push(createCashuOffgridPacket([proof]));
}
}
cd.offgridPackets = normalizedPackets;
cd.offgridSecrets = [...normalizedPackets.flatMap((packet) => packet.secrets)];
return { packets: cd.offgridPackets, secrets: cd.offgridSecrets };
}
function syncCashuOffgridSecrets(cd = getActiveCashuData()) {
return syncCashuOffgridState(cd).secrets;
}
function getCashuOffgridPackets(cd = getActiveCashuData()) {
return syncCashuOffgridState(cd).packets.map((packet) => ({
id: packet.id,
amount: Number(packet.amount || 0),
secrets: [...packet.secrets],
}));
}
function getCashuOffgridProofs(cd = getActiveCashuData()) {
const offgridSecrets = new Set(syncCashuOffgridSecrets(cd));
return (cd.proofs || []).filter((proof) => offgridSecrets.has(String(proof?.secret || "")));
}
function getCashuGeneralProofs(cd = getActiveCashuData()) {
const offgridSecrets = new Set(syncCashuOffgridSecrets(cd));
return (cd.proofs || []).filter((proof) => !offgridSecrets.has(String(proof?.secret || "")));
}
function getCashuOffgridBalance() {
return getCashuOffgridPackets().reduce((sum, packet) => sum + Number(packet.amount || 0), 0);
}
function getCashuGeneralBalance() {
return getProofsBalance(getCashuGeneralProofs());
}
function selectProofsByCounts(selection, proofs) {
const normalized = new Map();
for (const item of Array.isArray(selection) ? selection : []) {
const amount = Math.floor(Number(item?.amount || 0));
const count = Math.floor(Number(item?.count || 0));
if (!(amount > 0) || !(count > 0)) continue;
normalized.set(amount, (normalized.get(amount) || 0) + count);
}
if (!normalized.size) return null;
const buckets = new Map();
for (const proof of Array.isArray(proofs) ? proofs : []) {
const amount = Math.floor(Number(proof?.amount || 0));
if (!(amount > 0)) continue;
if (!buckets.has(amount)) buckets.set(amount, []);
buckets.get(amount).push(proof);
}
const send = [];
for (const [amount, count] of normalized.entries()) {
const bucket = buckets.get(amount) || [];
if (bucket.length < count) {
throw new Error(`Not enough ready ${amount} sats units.`);
}
for (let i = 0; i < count; i += 1) {
send.push(bucket.pop());
}
}
const sendSecrets = new Set(send.map((proof) => String(proof?.secret || "")).filter(Boolean));
const keep = (Array.isArray(proofs) ? proofs : []).filter((proof) => !sendSecrets.has(String(proof?.secret || "")));
return { send, returnChange: keep };
}
function selectOffgridPacketsByCounts(selection, packets) {
const normalized = new Map();
for (const item of Array.isArray(selection) ? selection : []) {
const amount = Math.floor(Number(item?.amount || 0));
const count = Math.floor(Number(item?.count || 0));
if (!(amount > 0) || !(count > 0)) continue;
normalized.set(amount, (normalized.get(amount) || 0) + count);
}
if (!normalized.size) return null;
const buckets = new Map();
for (const packet of Array.isArray(packets) ? packets : []) {
const amount = Math.floor(Number(packet?.amount || 0));
if (!(amount > 0)) continue;
if (!buckets.has(amount)) buckets.set(amount, []);
buckets.get(amount).push(packet);
}
const selectedPackets = [];
for (const [amount, count] of normalized.entries()) {
const bucket = buckets.get(amount) || [];
if (bucket.length < count) {
throw new Error(`Not enough ready ${amount} sats amounts.`);
}
for (let i = 0; i < count; i += 1) {
selectedPackets.push(bucket.pop());
}
}
const selectedIds = new Set(selectedPackets.map((packet) => String(packet?.id || "")).filter(Boolean));
const remainingPackets = (Array.isArray(packets) ? packets : []).filter((packet) => !selectedIds.has(String(packet?.id || "")));
return { selectedPackets, remainingPackets };
}
function groupCashuProofInventory(proofs, status = "confirmed") {
const buckets = new Map();
for (const proof of Array.isArray(proofs) ? proofs : []) {
const amount = Number(proof?.amount || 0);
if (!(amount > 0)) continue;
if (!buckets.has(amount)) {
buckets.set(amount, { amount, count: 0, total: 0, status });
}
const bucket = buckets.get(amount);
bucket.count += 1;
bucket.total += amount;
}
return [...buckets.values()].sort((a, b) => a.amount - b.amount);
}
function groupCashuPacketInventory(packets, status = "offgrid") {
const buckets = new Map();
for (const packet of Array.isArray(packets) ? packets : []) {
const amount = Number(packet?.amount || 0);
if (!(amount > 0)) continue;
if (!buckets.has(amount)) {
buckets.set(amount, { amount, count: 0, total: 0, status });
}
const bucket = buckets.get(amount);
bucket.count += 1;
bucket.total += amount;
}
return [...buckets.values()].sort((a, b) => a.amount - b.amount);
}
function getCashuInventoryPayload() {
const cd = getActiveCashuData();
const generalProofs = getCashuGeneralProofs(cd);
const offgridProofs = getCashuOffgridProofs(cd);
const offgridPackets = getCashuOffgridPackets(cd);
return {
confirmed: groupCashuProofInventory(cd.proofs || [], "confirmed"),
general: groupCashuProofInventory(generalProofs, "general"),
offgrid: groupCashuPacketInventory(offgridPackets, "offgrid"),
pending: groupCashuProofInventory(cd.pendingSwapProofs || [], "pending"),
confirmedProofCount: (cd.proofs || []).length,
generalProofCount: generalProofs.length,
offgridProofCount: offgridProofs.length,
offgridPacketCount: offgridPackets.length,
pendingProofCount: (cd.pendingSwapProofs || []).length,
};
}
function getCashuPayload() {
const cd = getActiveCashuData();
syncCashuOffgridState(cd);
return {
configured: Boolean(cd.mintUrl),
mintUrl: cd.mintUrl || null,
balance: getCashuBalance(),
generalBalance: getCashuGeneralBalance(),
offgridBalance: getCashuOffgridBalance(),
pendingBalance: getCashuPendingBalance(),