-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.js
More file actions
2660 lines (2346 loc) · 112 KB
/
Copy pathmonitor.js
File metadata and controls
2660 lines (2346 loc) · 112 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
/**
* BitTrack Monitor v5 — Electrum Server
*
* Fluxo:
* 1. Derive addresses via descriptor (BIP380/BIP389/Miniscript)
* 2. Convert each address to scripthash (reversed SHA256 of scriptPubKey)
* 3. blockchain.scripthash.subscribe → push em tempo real
* 4. On change: get_history → transaction.get → classifyTx
* 5. Classify: received / sent / sent+change / consolidation
* 6. Notify Telegram — single message per TXID (deduplication)
* 7. Automatic gap limit for external and change (no duplicates)
*/
'use strict';
const { analyzeDescriptor, scriptToScriptHash } = require('./descriptor-parser');
const net = require('net');
const tls = require('tls');
const https = require('https');
const fs = require('fs');
const path = require('path');
const { createHash } = require('crypto');
const dataDir = path.join(__dirname, 'data');
fs.mkdirSync(dataDir, { recursive: true });
// ─── CONFIG ───────────────────────────────────────────────────────────────────
// Complete config structure with all default values.
// Used both to create the file from scratch and to fill in missing fields.
const CONFIG_DEFAULTS = {
electrum: {
name: 'Emzy.de',
host: 'electrum.emzy.de',
port: 50002,
tls: true,
},
telegram: {
enabled: false,
token: '',
chatId: '',
},
ntfy: {
enabled: false,
url: '',
token: '',
},
general: {
mempoolExplorer: 'https://mempool.emzy.de/',
currency: 'USD',
timezone: 'UTC',
dateLocale: 'en-US',
language: 'en-US',
panelPort: 8585,
},
monitor: {
gapLimit: 10,
maxIndex: 1000,
pingIntervalSec: 60,
subscribeDelayMs: 3,
priceApis: ['coingecko', 'binance', 'blockchain.info'],
priceCheckIntervalSec: 300,
priceRefMaxDeviationPct: 20, // maximum allowed deviation for priceReference (%)
priceThresholdMinPct: 0.5, // minimum threshold % of current price
priceThresholdMaxPct: 50, // maximum threshold % of current price
},
notifications: {
mempoolPending: true,
txConfirmed: true,
everyBlock: false,
blockIntervalMin: 0,
priceChange: false,
priceThresholdPct: 1, // price change threshold % of current price
priceReference: null, // null = uses current price as reference
},
};
// Deep merge: fills missing fields in `target` with values from `defaults`.
// Never overwrites existing values — only adds what is missing.
function deepMergeDefaults(target, defaults) {
const result = { ...target };
for (const [key, val] of Object.entries(defaults)) {
if (!(key in result)) {
result[key] = val;
} else if (val !== null && typeof val === 'object' && !Array.isArray(val)
&& typeof result[key] === 'object' && result[key] !== null) {
result[key] = deepMergeDefaults(result[key], val);
}
}
return result;
}
// Reads config.json, fills missing fields with defaults and rewrites if needed.
// Called once at boot via ensureConfig() and then read on demand via getCFG().
function ensureConfig() {
const cfgFile = path.join(dataDir, 'config.json');
let fc = {};
let existed = true;
try {
fc = JSON.parse(fs.readFileSync(cfgFile, 'utf8'));
} catch {
existed = false;
}
const merged = deepMergeDefaults(fc, CONFIG_DEFAULTS);
const mergedStr = JSON.stringify(merged, null, 2);
const originalStr = JSON.stringify(fc, null, 2);
if (!existed || mergedStr !== originalStr) {
fs.writeFileSync(cfgFile, mergedStr);
if (!existed) {
log.info('config.json created with default values — fill in electrum and telegram before starting');
} else {
log.info('config.json updated — missing fields filled with default values');
}
}
}
// Last valid config read from disk — used as fallback if file is corrupted
let _lastValidConfig = null;
// Reads config.json from disk — called whenever updated values are needed.
// Does not use in-memory cache so changes made via the panel are
// reflected immediately without restarting the process.
function loadConfig() {
const cfgFile = path.join(dataDir, 'config.json');
let fc = {};
try {
const raw = fs.readFileSync(cfgFile, 'utf8');
fc = JSON.parse(raw);
_lastValidConfig = fc; // save last valid
} catch {
// Invalid JSON (file being written) — silently use last valid config
if (_lastValidConfig) fc = _lastValidConfig;
}
const g = fc.general || CONFIG_DEFAULTS.general;
const m = fc.monitor || CONFIG_DEFAULTS.monitor;
const n = fc.notifications || CONFIG_DEFAULTS.notifications;
return {
electrum: fc.electrum || CONFIG_DEFAULTS.electrum,
telegram: fc.telegram || CONFIG_DEFAULTS.telegram,
// general
mempoolExplorer: g.mempoolExplorer,
dateLocale: g.dateLocale,
currency: g.currency,
timezone: g.timezone,
language: g.language || 'en-US',
// monitor
gapLimit: m.gapLimit ?? CONFIG_DEFAULTS.monitor.gapLimit,
maxIndex: m.maxIndex ?? CONFIG_DEFAULTS.monitor.maxIndex,
pingInterval: (m.pingIntervalSec ?? CONFIG_DEFAULTS.monitor.pingIntervalSec) * 1000,
subscribeDelayMs: m.subscribeDelayMs ?? CONFIG_DEFAULTS.monitor.subscribeDelayMs,
priceApis: m.priceApis ?? CONFIG_DEFAULTS.monitor.priceApis,
priceCheckIntervalSec: m.priceCheckIntervalSec ?? CONFIG_DEFAULTS.monitor.priceCheckIntervalSec,
priceRefMaxDeviationPct: m.priceRefMaxDeviationPct ?? CONFIG_DEFAULTS.monitor.priceRefMaxDeviationPct,
priceThresholdMinPct: m.priceThresholdMinPct ?? CONFIG_DEFAULTS.monitor.priceThresholdMinPct,
priceThresholdMaxPct: m.priceThresholdMaxPct ?? CONFIG_DEFAULTS.monitor.priceThresholdMaxPct,
notifications: n,
ntfy: fc.ntfy || CONFIG_DEFAULTS.ntfy || {},
reconnectDelay: 10000,
stateFile: path.join(dataDir, 'state.json'),
walletsFile: path.join(dataDir, 'wallets.json'),
};
}
// CFG is read from disk on demand — use getCFG() instead of CFG directly
// to ensure values are always up to date.
function getCFG() { return loadConfig(); }
// Keeps a copy of the active electrum for server-change detection
let _activeElectrumKey = '';
function electrumKey(e) { return `${e.host}:${e.port}:${e.tls}`; }
const CFG = getCFG(); // used only for initialization
// ─── I18N ─────────────────────────────────────────────────────────────────────
// Loads language/{lang}.json on demand and caches per locale.
// The panel loads the same files via /api/i18n/{lang} and handles UI translation.
const _i18nCache = {};
function loadLang(lang) {
if (_i18nCache[lang]) return _i18nCache[lang];
try {
const file = path.join(__dirname, 'language', `${lang}.json`);
_i18nCache[lang] = JSON.parse(fs.readFileSync(file, 'utf8'));
} catch {
_i18nCache[lang] = null; // mark as missing so we don't retry every call
}
return _i18nCache[lang];
}
// Returns the translated string for key, interpolating {var} placeholders.
// Falls back to en-US, then to the raw key if nothing is found.
function t(key, vars = {}) {
const lang = getCFG().language || 'en-US';
const dict = loadLang(lang) || loadLang('en-US') || {};
let str = dict[key] ?? (loadLang('en-US') || {})[key] ?? key;
for (const [k, v] of Object.entries(vars)) {
str = str.replaceAll(`{${k}}`, v ?? '');
}
return str;
}
const RUNTIME_FILE = path.join(dataDir, 'runtime.json');
const PRICE_HISTORY_FILE = path.join(dataDir, 'historicalprice.json');
const TX_HISTORY_FILE = path.join(dataDir, 'txhistory.json');
// runtime.json — volatile data written by the monitor in real time.
// Never watched by fs.watchFile, so it does not cause restarts.
// Current structure: { price: { usd, updatedAt }, ... }
function readRuntime() {
try { return JSON.parse(fs.readFileSync(RUNTIME_FILE, 'utf8')); }
catch { return {}; }
}
// ─── PRICE HISTORY ──────────────────────────────────────────────────────
// Writes each price point to data/historicalprice.json
// Format: array of { t: timestamp_ms, p: price }
// Capped at 8640 points (30 days × 288 points/day at 5 min intervals)
const PRICE_HISTORY_MAX = 8640;
function appendPriceHistory(price) {
try {
const currency = getCFG().currency || 'USD';
let history = [];
try { history = JSON.parse(fs.readFileSync(PRICE_HISTORY_FILE, 'utf8')); }
catch { history = []; }
if (!Array.isArray(history)) history = [];
history.push({ t: Date.now(), p: price, c: currency });
if (history.length > PRICE_HISTORY_MAX) history = history.slice(-PRICE_HISTORY_MAX);
fs.writeFileSync(PRICE_HISTORY_FILE, JSON.stringify(history));
} catch(e) { log.warn(`appendPriceHistory: ${e.message}`); }
}
// ─── TRANSACTION HISTORY ──────────────────────────────────────────────────
// Writes each classified transaction to data/txhistory.json
// Structure: { [walletName]: { txids: { [txid]: { type, valueSat, feeSat, height, ts, mempool, addresses } } } }
// Deduplication via O(1) lookup on the txids object — never reprocesses existing entries.
// Maximum of 500 txids per wallet (oldest removed first).
const TX_HISTORY_MAX = 500;
function readTxHistory() {
try { return JSON.parse(fs.readFileSync(TX_HISTORY_FILE, 'utf8')); }
catch { return {}; }
}
function writeTxHistory(data) {
try { fs.writeFileSync(TX_HISTORY_FILE, JSON.stringify(data, null, 2)); }
catch(e) { log.warn(`writeTxHistory: ${e.message}`); }
}
// Returns true if the txid is already recorded for that wallet
function txHistoryHas(walletName, txid) {
try {
const h = readTxHistory();
return !!(h[walletName]?.txids?.[txid]);
} catch { return false; }
}
// Records a classified transaction in history.
// classification, txid: required
// height: block number (null = mempool)
// isPending: bool
// histEntry: getHistory entry (may have .time for real timestamp)
function appendTxHistory(classification, txid, height, isPending, histEntry) {
try {
const { type, walletName } = classification;
const h = readTxHistory();
if (!h[walletName]) h[walletName] = { txids: {} };
if (!h[walletName].txids) h[walletName].txids = {};
// Deduplication — never reprocesses
if (h[walletName].txids[txid]) {
// Update only if it was mempool and is now confirmed
if (h[walletName].txids[txid].mempool && !isPending && height) {
h[walletName].txids[txid].mempool = false;
h[walletName].txids[txid].height = height;
writeTxHistory(h);
}
return;
}
let valueSat = 0, feeSat = 0, addresses = [];
if (type === 'received') {
valueSat = classification.valueSat || 0;
addresses = (classification.destinations || []).map(d => d.address);
} else if (type === 'sent') {
feeSat = classification.feeSats || 0;
valueSat = -(classification.sentSats || 0) - feeSat;
addresses = (classification.destinations || []).map(d => d.address);
} else if (type === 'sent_with_change') {
feeSat = classification.feeSats || 0;
valueSat = -(classification.sentSats || 0) - feeSat;
addresses = (classification.destinations || []).map(d => d.address);
} else if (type === 'consolidation') {
valueSat = classification.outputSats || 0;
addresses = (classification.destinations || []).map(d => d.address);
}
// Timestamp: prefers .time from Electrum (unix seconds), otherwise Date.now()
const ts = histEntry?.time ? histEntry.time * 1000 : (isPending ? Date.now() : null);
h[walletName].txids[txid] = {
type,
valueSat,
feeSat,
height: height || null,
ts,
mempool: !!isPending,
addresses,
};
// Cap at TX_HISTORY_MAX per wallet (remove oldest by height/ts)
const entries = Object.entries(h[walletName].txids);
if (entries.length > TX_HISTORY_MAX) {
entries.sort(([, a], [, b]) => {
const ha = a.height || 9999999, hb = b.height || 9999999;
if (ha !== hb) return ha - hb;
return (a.ts || 0) - (b.ts || 0);
});
const toRemove = entries.slice(0, entries.length - TX_HISTORY_MAX);
for (const [id] of toRemove) delete h[walletName].txids[id];
}
writeTxHistory(h);
} catch(e) { log.warn(`appendTxHistory: ${e.message}`); }
}
// Saves price reference to notifications.priceReference in config.json
// without overwriting the rest — fs.watchFile will detect but hotReloadConfig
// will ignore it since only priceReference changed (not a server change).
function saveThresholdPct(pct) {
try {
const cfgFile = path.join(dataDir, 'config.json');
const data = JSON.parse(fs.readFileSync(cfgFile, 'utf8'));
if (!data.notifications) data.notifications = {};
data.notifications.priceThresholdPct = pct;
fs.writeFileSync(cfgFile, JSON.stringify(data, null, 2));
} catch(e) { log.warn(`saveThresholdPct: ${e.message}`); }
}
function savePriceReference(price) {
try {
const cfgFile = path.join(dataDir, 'config.json');
const data = JSON.parse(fs.readFileSync(cfgFile, 'utf8'));
if (!data.notifications) data.notifications = {};
data.notifications.priceReference = price;
fs.writeFileSync(cfgFile, JSON.stringify(data, null, 2));
} catch(e) { log.warn(`savePriceReference: ${e.message}`); }
}
function writeRuntime(patch) {
const data = readRuntime();
const merged = { ...data, ...patch };
try { fs.writeFileSync(RUNTIME_FILE, JSON.stringify(merged, null, 2)); }
catch(e) { log.warn(`writeRuntime: ${e.message}`); }
}
// Updates only the lock message without touching active/timeoutAt
// Used during indexing loops to show progress on the panel overlay
function updateLockMsg(msg) {
const data = readRuntime();
if (!data.lock?.active) return; // only update if lock is still active
data.lock.msg = msg;
try { fs.writeFileSync(RUNTIME_FILE, JSON.stringify(data, null, 2)); }
catch(e) { log.warn(`updateLockMsg: ${e.message}`); }
}
// ─── FEES VIA ELECTRUM ───────────────────────────────────────────────────────
// Fetches fee histogram from Electrum and computes fast/medium/slow estimates.
// The histogram is an array of [feeRate, vsize] sorted by feeRate descending.
// Strategy: accumulate vsize until 25% (fast), 50% (medium), 75% (slow)
// of total. feeRate in sat/vB (already in Electrum's correct format).
async function fetchAndSaveFees(electrum) {
try {
// 1. Fetch official Bitcoin Core fee estimates (via Electrum)
// n=2 (~20 min), n=5 (~50 min), n=10 (~1h 40min)
const [f2, f5, f10] = await Promise.all([
electrum.call('blockchain.estimatefee', [2]),
electrum.call('blockchain.estimatefee', [5]),
electrum.call('blockchain.estimatefee', [10])
]);
const toSatVb = (btcKb) => (btcKb && btcKb > 0) ? Math.ceil(btcKb * 100000) : null;
let fast = toSatVb(f2);
let med = toSatVb(f5);
let slow = toSatVb(f10);
// 2. Fallback: if estimatefee fails (-1), use the histogram as plan B
if (!fast || !med || !slow) {
const histogram = await electrum.getFeeHistogram();
if (Array.isArray(histogram) && histogram.length > 0) {
const total = histogram.reduce((s, [, v]) => s + v, 0);
let acc = 0;
for (const [fee, vsize] of histogram) {
acc += vsize;
if (fast === null && acc >= total * 0.25) fast = Math.round(fee);
if (med === null && acc >= total * 0.50) med = Math.round(fee);
if (slow === null && acc >= total * 0.75) slow = Math.round(fee);
}
}
}
// 3. Final sanity check
// If all fail, assume 1 sat/vB. If values exist, enforce the hierarchy.
fast = Math.max(1, fast ?? 1);
med = Math.max(1, med ?? fast);
slow = Math.max(1, slow ?? med);
// Logical ordering: fast >= med >= slow
const fastestFee = Math.max(fast, med, slow);
const halfHourFee = Math.max(med, slow);
const hourFee = slow;
writeRuntime({
fees: {
fastestFee,
halfHourFee,
hourFee,
updatedAt: Date.now(),
}
});
log.info(` [fees] fast=${fastestFee} medium=${halfHourFee} slow=${hourFee} sat/vB`);
} catch(e) {
log.warn(` [fees] erro ao atualizar: ${e.message}`);
}
}
// ─── NOTIFICATION PREFERENCES ─────────────────────────────────────────────
// Always reads from disk — so any changes made via the panel are reflected
// immediately, without restarting the monitor.
// config.json is small; a one-off synchronous read is negligible.
// Defaults: mempoolPending and txConfirmed = true by default;
// everyBlock and priceChange = false by default.
function getNotifications() {
return getCFG().notifications || {};
}
// Returns whether a notification type is enabled.
// Two-level logic for mempoolPending and txConfirmed:
// - Global OFF → nobody receives, regardless of per-wallet setting
// - Global ON → per-wallet wallet.notify[key] decides (falls back to true if not set)
// everyBlock and priceChange have no per-wallet override.
function notifEnabled(key, wallet) {
const n = getNotifications();
if (key === 'mempoolPending') {
if (n.mempoolPending === false) return false; // global off → skip everyone
if (wallet?.notify && typeof wallet.notify.mempoolPending === 'boolean')
return wallet.notify.mempoolPending; // per-wallet setting
return true;
}
if (key === 'txConfirmed') {
if (n.txConfirmed === false) return false; // global off → skip everyone
if (wallet?.notify && typeof wallet.notify.txConfirmed === 'boolean')
return wallet.notify.txConfirmed; // per-wallet setting
return true;
}
if (key === 'everyBlock') return n.everyBlock === true;
if (key === 'priceChange') return n.priceChange === true;
return true;
}
// Read a numeric value from notifications without depending on frozen CFG
function getNotifValue(key, fallback) {
return getNotifications()[key] ?? fallback;
}
// ─── LOGGER ───────────────────────────────────────────────────────────────────
const ts = () => {
const tz = getCFG()?.timezone || 'UTC';
const fmt = new Intl.DateTimeFormat([], {
timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false,
});
const parts = Object.fromEntries(
fmt.formatToParts(new Date()).filter(p => p.type !== 'literal').map(p => [p.type, p.value])
);
return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}:${parts.second}`;
};
const log = {
info: (...a) => console.log(`[${ts()}] ℹ️ `, ...a),
ok: (...a) => console.log(`[${ts()}] ✅ `, ...a),
warn: (...a) => console.warn(`[${ts()}] ⚠️ `, ...a),
error: (...a) => console.error(`[${ts()}] ❌ `, ...a),
};
ensureConfig(); // ensure config.json exists and is complete
const sleep = ms => new Promise(r => setTimeout(r, ms));
const sats = s => (s / 1e8).toFixed(8);
// Format monetary value using the currency configured in general.currency
function fmtPrice(value) {
const cur = getCFG().currency;
const lang = getCFG().language;
const dict = loadLang(lang) || loadLang('en-US') || {};
const sym = cur === 'USD' ? '$' : cur === 'EUR' ? '€' : cur === 'GBP' ? '£' : cur === 'JPY' ? '¥' :
cur === 'BRL' ? 'R$' : cur === 'CHF' ? 'CHF' : cur === 'CNY' ? '¥' : cur === 'INR' ? '₹' :
cur === 'KRW' ? '₩' : cur === 'RUB' ? '₽' : cur === 'ARS' ? '$' : cur === 'ILS' ? '₪' :
cur === 'AED' ? 'د.إ' : cur === 'SAR' ? '﷼' : cur + ' ';
return `${sym}${value.toLocaleString('en-US', { maximumFractionDigits: 2 })}`;
}
const now = () => {
const cfg = getCFG();
return new Date().toLocaleString(cfg.dateLocale, { timeZone: cfg.timezone });
};
function mempoolLink(txid) {
const exp = getCFG().mempoolExplorer;
if (!exp) return null;
return `${exp.replace(/\/$/, '')}/tx/${txid}`;
}
function mempoolLinkLabel() {
const exp = getCFG().mempoolExplorer;
try { return new URL(exp).hostname; }
catch { return exp; }
}
// ─── STATE ────────────────────────────────────────────────────────────────────
let state = {};
// In-memory cache of notifications already sent this session.
// Key: "txid|walletName" — allows the same txid to be notified
// from different perspectives (send from Wallet A, receive in Wallet B).
const notifiedTxids = new Set();
// Flag indicating whether the initial subscribeAll has completed.
// While false, ensureGap is not called (subscribeAll does the full scan).
let initialScanDone = false;
// Timestamp of the last block notification sent (module-level — survives reconnects)
let _lastBlockNotifAt = 0;
// Buffer of blocks accumulated during the interval
let _pendingBlocks = [];
let _blockFlushTimer = null;
// Reference to the active Electrum client — used by hot-reload
let _activeElectrum = null;
// Signals that the main loop should reconnect (server switch)
let _reconnectRequested = false;
let _reconnectTimer = null;
// Prevents polling from triggering multiple reconnects while one is already in progress
let _serverChangePending = false;
// Module-level reference to the price timer — allows hotReloadConfig to cancel it
// and schedule an immediate fetch when currency changes.
let _priceTimerRef = null;
let _priceRunning = false;
let _lastNotifiedPrice = null;
let _appliedCfgRef = null;
let _threshWarnLogged = false;
// ─── CONFIRMED NOTIFICATIONS BUFFER ──────────────────────────────────────
// Groups confirmed txs by (block, wallet) before sending
// a single consolidated message to Telegram.
//
// Key: "walletName:height"
// Value: { walletName, height, entries: [{ txid, classification }], timer }
const _confirmedBuffer = new Map();
const CONFIRMED_FLUSH_DELAY = 3000; // ms — waits 3s after last item before sending
async function flushConfirmedBuffer(key) {
const buf = _confirmedBuffer.get(key);
if (!buf || !buf.entries.length) { _confirmedBuffer.delete(key); return; }
_confirmedBuffer.delete(key);
const { walletName, height, entries } = buf;
// ── Single tx → individual message as normal ────────────────────────────
if (entries.length === 1) {
const { txid, classification } = entries[0];
const msg = buildTelegramMsg(classification, txid, height, false);
if (msg) await sendNotification(msg);
return;
}
// ── Multiple txs → consolidated message ─────────────────────────────────
const _wallet = wallets.find(w => w.name === walletName);
if (notifEnabled('txConfirmed', _wallet)) {
const totalReceived = entries
.filter(e => e.classification.type === 'received')
.reduce((s, e) => s + (e.classification.valueSat || 0), 0);
const totalSent = entries
.filter(e => e.classification.type === 'sent' || e.classification.type === 'sent_with_change')
.reduce((s, e) => s + (e.classification.sentSats || 0), 0);
const lines = entries.map(e => {
const c = e.classification;
if (c.type === 'received') return t('multi_tx_line_received', { value: sats(c.valueSat) });
if (c.type === 'sent') return t('multi_tx_line_sent', { value: sats(c.sentSats) });
if (c.type === 'sent_with_change') return t('multi_tx_line_sent_change', { value: sats(c.sentSats) });
if (c.type === 'consolidation') return t('multi_tx_line_consolidation', { value: sats(c.outputSats) });
return ` • ${c.type}`;
});
const txidList = entries.map(e => ` 🔗 <code>${e.txid}</code>`).join('\n');
let summary = '';
if (totalReceived > 0) summary += t('multi_tx_total_received', { value: sats(totalReceived) });
if (totalSent > 0) summary += t('multi_tx_total_sent', { value: sats(totalSent) });
const msg = t('multi_tx_confirmed', {
count: entries.length,
wallet: walletName,
height,
summary,
lines: lines.join('\n'),
txids: txidList,
time: now(),
});
await sendNotification(msg);
}
}
function loadState() {
// Load the persisted state from the previous session.
// subscribeAll compares the statusHash returned by the Electrum Server with the saved one:
// if equal, history did not change offline and getHistory/getBalance are skipped.
// If the file does not exist or is corrupted, start from scratch.
try {
const raw = fs.readFileSync(getCFG().stateFile, 'utf8');
state = JSON.parse(raw);
const count = Object.values(state).reduce((n, w) => {
if (typeof w !== 'object') return n;
return n + Object.values(w).reduce((m, l) => m + (typeof l === 'object' ? Object.keys(l).length : 0), 0);
}, 0);
log.info(`State loaded — ${count} known addresses (smart boot active)`);
} catch {
state = {};
log.info('State not found — full scan on boot');
}
}
function saveState() {
try {
// Rebuild state sorting addresses by BIP44 index
const sorted = {};
for (const walletName of Object.keys(state).sort()) {
sorted[walletName] = {};
for (const label of ['externo', 'change']) {
const labelData = state[walletName]?.[label];
if (!labelData) continue;
// Sort addresses by index registered in addrMap
const entries = Object.entries(labelData).sort(([addrA], [addrB]) => {
const idxA = addrMap.get(addrA + '|' + walletName)?.index ?? 0;
const idxB = addrMap.get(addrB + '|' + walletName)?.index ?? 0;
return idxA - idxB;
});
if (entries.length) {
sorted[walletName][label] = Object.fromEntries(entries);
}
}
if (!Object.keys(sorted[walletName]).length) delete sorted[walletName];
}
// Persist the active gapLimit with state to detect offline changes
sorted._meta = { gapLimit: getCFG().gapLimit };
fs.writeFileSync(getCFG().stateFile, JSON.stringify(sorted, null, 2));
} catch(e) { log.error('saveState:', e.message); }
}
// Reconcile gapLimit offline: if gapLimit was reduced while the script
// was offline, purge from state and wallet.addresses the empty addresses
// beyond the new cutoff — exactly as rebalanceGap would do live.
// Called after loadState() and loadWallets(), before connecting to the Electrum Server.
function reconcileGapOnBoot() {
const currentGap = getCFG().gapLimit;
const savedGap = state._meta?.gapLimit ?? currentGap;
delete state._meta; // remove metadata from in-memory state (not address data)
if (currentGap >= savedGap) {
// Increase or equal: subscribeAll will naturally derive the new addresses
if (currentGap > savedGap)
log.info(`[boot] gapLimit increased offline (${savedGap} → ${currentGap}) — subscribeAll will derive new addresses`);
return;
}
log.info(`[boot] gapLimit reduced offline (${savedGap} → ${currentGap}) — purging excess addresses from state`);
let totalPurged = 0;
for (const wallet of wallets) {
if (!wallet.descriptor || wallet.descriptor.startsWith('addr(')) continue;
for (const chain of [0, 1]) {
const label = chain === 0 ? 'ext' : 'chg';
const stLabel = chain === 0 ? 'externo' : 'change';
const addrs = (wallet.addresses || []).filter(a => a.chain === chain)
.sort((a, b) => a.index - b.index);
if (!addrs.length) continue;
// Index of last address with history
let lastUsed = -1;
for (const a of addrs) {
const st = state[wallet.name]?.[stLabel]?.[a.address];
if (!st) continue;
if ((st.balanceSat || 0) > 0 || (st.txids?.length || 0) > 0 || (st.mempoolTxids?.length || 0) > 0)
lastUsed = a.index;
}
const startIdx = wallet.startIndex ?? 0;
const base = lastUsed >= 0 ? lastUsed : startIdx - 1;
const cutoff = base + currentGap;
let purged = 0;
for (const a of [...addrs]) {
if (a.index <= cutoff) continue;
const st = state[wallet.name]?.[stLabel]?.[a.address];
const hasHistory = st && ((st.balanceSat || 0) > 0 || (st.txids?.length || 0) > 0 || (st.mempoolTxids?.length || 0) > 0);
if (hasHistory) continue; // never remove an address with history
// Remove de addrMap e shMap
addrMap.delete(a.address + '|' + wallet.name);
const shList = shMap.get(a.scriptHash);
if (shList) {
const filtered = shList.filter(e => e.wallet.name !== wallet.name || e.address !== a.address);
if (filtered.length) shMap.set(a.scriptHash, filtered);
else shMap.delete(a.scriptHash);
}
// Remove de wallet.addresses
const wIdx = wallet.addresses.indexOf(a);
if (wIdx !== -1) wallet.addresses.splice(wIdx, 1);
// Remove from in-memory state
if (state[wallet.name]?.[stLabel])
delete state[wallet.name][stLabel][a.address];
purged++;
}
if (purged > 0)
log.info(` [boot] ${wallet.name} [${label}]: ${purged} addresses purged (cutoff idx ${cutoff})`);
}
}
if (totalPurged > 0 || true) saveState(); // rewrite state.json with new gapLimit
}
function getAddrState(addr, walletName) {
const info = addrMap.get(addr + '|' + walletName);
if (!info) return { balanceSat: null, txids: [], mempoolTxids: [], statusHash: null };
const label = info.chain === 0 ? 'externo' : 'change';
return state[walletName]?.[label]?.[addr] || { balanceSat: null, txids: [], mempoolTxids: [], statusHash: null };
}
function setAddrState(addr, data, walletName) {
const info = addrMap.get(addr + '|' + walletName);
if (!info) return;
const label = info.chain === 0 ? 'externo' : 'change';
if (!state[walletName]) state[walletName] = {};
if (!state[walletName][label]) state[walletName][label] = {};
const prev = getAddrState(addr, walletName);
state[walletName][label][addr] = { addressIndex: info.index, ...prev, ...data, lastUpdate: Date.now() };
saveState();
}
// ─── WALLETS & DERIVATION ──────────────────────────────────────────────────────
let wallets = [];
const addrMap = new Map(); // "address|walletName" → { wallet, chain, index, scriptHash, scriptHex }
const shMap = new Map(); // scriptHash → [{ address, wallet, chain, index }]
function walletHrp(w) {
if (w.network === 'signet' || w.network === 'testnet') return 'tb';
if (w.network === 'regtest') return 'bcrt';
return 'bc';
}
function deriveOne(descriptor, hrp, index, chain) {
try {
const r = analyzeDescriptor(descriptor, { hrp, deriveSpec: [{ index, chain }] });
const a = r.addresses[0];
if (!a || !a.scriptHex) return null;
return { ...a, scriptHash: scriptToScriptHash(a.scriptHex) };
} catch { return null; }
}
function registerAddress(entry, wallet, chain, index) {
const key = entry.address + '|' + wallet.name;
addrMap.set(key, { wallet, chain, index, scriptHash: entry.scriptHash, scriptHex: entry.scriptHex });
const list = shMap.get(entry.scriptHash) || [];
if (!list.some(e => e.address === entry.address && e.wallet.name === wallet.name)) {
list.push({ address: entry.address, wallet, chain, index });
}
shMap.set(entry.scriptHash, list);
}
function ensureGap(wallet, chain, usedIndex, electrum) {
const hrp = walletHrp(wallet);
const cfg = getCFG();
const needed = usedIndex + cfg.gapLimit;
const desc = (chain === 1 && wallet.descriptorChange) ? wallet.descriptorChange : wallet.descriptor;
// Highest index already derived for this chain
const existing = (wallet.addresses || []).filter(a => a.chain === chain);
const lastIdx = existing.length ? Math.max(...existing.map(a => a.index)) : -1;
if (lastIdx >= needed) return [];
const newEntries = [];
for (let i = lastIdx + 1; i <= Math.min(needed, cfg.maxIndex); i++) {
// Avoid deriving already-present index (protection against concurrent calls)
if (wallet.addresses.some(a => a.chain === chain && a.index === i)) continue;
const entry = deriveOne(desc, hrp, i, chain);
if (!entry) continue;
wallet.addresses.push({ ...entry, chain, index: i });
registerAddress(entry, wallet, chain, i);
newEntries.push(entry);
}
if (newEntries.length > 0) {
const label = chain === 0 ? 'externos' : 'change';
log.info(` Gap [${wallet.name}]: +${newEntries.length} ${label} (idx ${lastIdx + 1}..${Math.min(needed, cfg.maxIndex)})`);
if (electrum?.connected) {
for (const e of newEntries) {
electrum.subscribe(e.scriptHash).then(async status => {
if (status) {
await processChange(electrum, e.scriptHash, status).catch(() => {});
} else {
setAddrState(e.address, { balanceSat: 0, txids: [], mempoolTxids: [], statusHash: null }, wallet.name);
}
}).catch(err => log.warn(` subscribe ${e.address.slice(0,16)}…: ${err.message}`));
}
}
}
return newEntries;
}
function loadWallets() {
try {
if (fs.existsSync(getCFG().walletsFile)) {
wallets = JSON.parse(fs.readFileSync(getCFG().walletsFile, 'utf8'));
} else {
fs.writeFileSync(getCFG().walletsFile, JSON.stringify([], null, 2));
log.info('wallets.json created — add wallets via the panel');
wallets = [];
}
} catch { wallets = []; }
if (!wallets.length) {
log.warn('No wallets configured — add descriptors via the panel');
}
addrMap.clear(); shMap.clear();
for (const wallet of wallets) {
if (!wallet.descriptor) continue;
wallet.addresses = wallet.addresses || [];
const hrp = walletHrp(wallet);
const startIdx = wallet.startIndex ?? 0;
// Derive and register only already-known addresses (from previous boots).
// subscribeAll will derive more as needed by querying the Electrum Server.
const isSingleAddress = wallet.descriptor.startsWith('addr(');
const chains = isSingleAddress ? [0] : [0, 1];
for (const chain of chains) {
const desc = (chain === 1 && wallet.descriptorChange) ? wallet.descriptorChange : wallet.descriptor;
// Ensure each entry has chain and index filled in
for (const entry of wallet.addresses.filter(a => a.chain === chain)) {
const sh = entry.scriptHash || (entry.scriptHex ? scriptToScriptHash(entry.scriptHex) : null);
if (sh) registerAddress({ ...entry, scriptHash: sh }, wallet, chain, entry.index ?? 0);
}
// Derive at least the first gapLimit addresses as a starting point.
// For addr() there is no real derivation — derive only index 0 and stop.
const existing = wallet.addresses.filter(a => a.chain === chain);
const lastIdx = existing.length ? Math.max(...existing.map(a => a.index ?? 0)) : startIdx - 1;
const minDerive = isSingleAddress ? startIdx : Math.max(startIdx + getCFG().gapLimit - 1, lastIdx);
for (let i = startIdx; i <= minDerive; i++) {
if (wallet.addresses.some(a => a.chain === chain && a.index === i)) continue;
const entry = deriveOne(desc, hrp, i, chain);
if (entry) {
wallet.addresses.push({ ...entry, chain, index: i });
registerAddress(entry, wallet, chain, i);
}
if (isSingleAddress) break;
}
}
const ext = wallet.addresses.filter(a => a.chain === 0).length;
const chg = wallet.addresses.filter(a => a.chain === 1).length;
log.info(` ${wallet.name}: ${ext} ext, ${chg} chg pre-derived`);
}
}
// ─── NOTIFICATIONS ────────────────────────────────────────────────────────────
function sendTelegram(text) {
const { enabled, token, chatId } = getCFG().telegram;
if (!enabled || !token || !chatId) return Promise.resolve();
const body = JSON.stringify({ chat_id: chatId, text, parse_mode: 'HTML' });
return new Promise(resolve => {
const req = https.request({
hostname: 'api.telegram.org',
path: `/bot${token}/sendMessage`,
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
}, res => { res.resume(); res.on('end', resolve); });
req.on('error', () => resolve());
req.write(body); req.end();
});
}
function sendNtfy(text) {
const { enabled, url, token } = getCFG().ntfy || {};
if (!enabled || !url) return Promise.resolve();
// Convert Telegram HTML tags to ntfy Markdown
const clean = text
.replace(/<b>(.*?)<\/b>/gi, '**$1**') // negrito
.replace(/<i>(.*?)<\/i>/gi, '*$1*') // italic
.replace(/<code>(.*?)<\/code>/gi, '`$1`') // inline code
.replace(/<a\b[^>]*href="([^"]*)"[^>]*>(.*?)<\/a>/gi, '[$2]($1)') // link
.replace(/<[^>]+>/g, ''); // tags restantes
const body = Buffer.from(clean, 'utf8');
const u = new URL(url);
const lib = u.protocol === 'https:' ? require('https') : require('http');
const headers = {
'Content-Type': 'text/plain',
'Content-Length': body.length,
'Markdown': 'yes',
};
if (token) headers['Authorization'] = `Bearer ${token}`;
return new Promise(resolve => {
const req = lib.request({
hostname: u.hostname,
port: u.port || (u.protocol === 'https:' ? 443 : 80),
path: u.pathname,
method: 'POST',
headers,
}, res => { res.resume(); res.on('end', resolve); });
req.on('error', () => resolve());
req.write(body); req.end();
});
}
function sendNotification(text) {
return Promise.all([sendTelegram(text), sendNtfy(text)]);
}
// ─── TRANSACTION CLASSIFICATION ─────────────────────────────────────────────
//
// Analyzes a complete tx and determines:
// - if any vin belongs to our state → outgoing/consolidation
// - if no vin belongs to our state → external receive
//
// Types:
// 'received' — external origin, value entered one of our addresses
// 'sent' — outgoing without change to our addresses
// 'sent_with_change' — outgoing with change returning to our address
// 'consolidation' — all output goes to our own addresses
//
// electrum is optional: if provided, used as fallback to fetch prevouts
// when the server does not include them in verbose tx (Electrum Server < 1.9).
async function classifyTx(txData, walletName, network, electrum) {
const vins = txData.vin || [];
const vouts = txData.vout || [];
// ── Map each vout to its scriptHash ──────────────────────────────────────
const voutScriptHashes = vouts.map(out => {
const hex = out.scriptPubKey?.hex || '';
return hex ? scriptHexToScriptHash(hex) : null;
});
// ── Detect our inputs ──────────────────────────────────────────────────
// Strategy 1: vin.prevout.scriptPubKey.hex (Electrum Server >= 1.9, verbose=true)
// Strategy 2: fallback — fetch the previous tx and get vout[vin.vout]
let myInputSats = 0;
const inputAddrs = new Set();
for (const vin of vins) {
if (vin.coinbase) continue; // coinbase tx has no real prevout
let prevScript = vin.prevout?.scriptPubKey?.hex || '';
let prevValue = vin.prevout?.value ?? null;
// Fallback: fetch the input tx to get scriptPubKey and/or value when
// the Electrum Server does not include full prevout (common on Signet/Testnet mempool)
if ((!prevScript || prevValue === null) && electrum && vin.txid) {
try {
const prevTx = await electrum.getTransaction(vin.txid);
const prevOut = (prevTx.vout || [])[vin.vout];
if (!prevScript) prevScript = prevOut?.scriptPubKey?.hex || '';
if (prevValue === null) prevValue = prevOut?.value ?? null;
} catch { /* ignora falha de lookup — assume externo */ }
}
if (!prevScript) continue;
const prevSh = scriptHexToScriptHash(prevScript);
// Only count as our input if it belongs to the SAME wallet being analyzed
const prevEntry = (shMap.get(prevSh) || []).find(e => e.wallet.name === walletName);
const addr = prevEntry?.address;
if (addr && addrMap.has(addr + '|' + walletName)) {
const val = prevValue ?? 0;
myInputSats += Math.round(val * 1e8);
inputAddrs.add(addr);
}
}