forked from BuidlGuidl/buidlguidl-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindexOld.js
1428 lines (1270 loc) · 39.4 KB
/
indexOld.js
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
import { exec, execSync, spawn } from "child_process";
import os from "os";
import fs from "fs";
import path from "path";
import si from "systeminformation";
import blessed from "blessed";
import contrib from "blessed-contrib";
import minimist from "minimist";
import pty from "node-pty";
import WebSocket from "ws";
import { createPublicClient, http } from "viem";
import { mainnet } from "viem/chains";
import macaddress from "macaddress";
import { fileURLToPath } from "url";
import { dirname } from "path";
// import { createDiskGauge } from "./monitor_components/diskGauge";
// import { createMemGauge } from "./monitor_components/memGauge";
// import { createCpuLine } from "./monitor_components/cpuLine";
// import { createNetworkLine } from "./monitor_components/networkLine";
import { createDiskGauge } from "./monitor_components/diskGauge";
import { createMemGauge } from "./monitor_components/memGauge";
import { createCpuLine } from "./monitor_components/cpuLine";
import { createNetworkLine } from "./monitor_components/networkLine";
import {
updateBandwidthBox,
setBandwidthBox,
startBandwidthMonitoring,
} from "./monitor_components/bandwidthGauge";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Set default command line option values
let executionClient = "geth";
let consensusClient = "prysm";
let installDir = os.homedir();
// Set client versions. Note: Prsym version works differently and is parsed from logs
const gethVer = "1.14.3";
const rethVer = "1.0.0";
let prysmVer = "";
const lighthouseVer = "5.1.3";
function showHelp() {
console.log("Usage: node script.js [options]");
console.log("");
console.log("Options:");
// console.log(" -e <client> Specify the execution client ('geth' or 'reth')");
console.log(" -e <client> Specify the execution client ('geth')");
// console.log(
// " -c <client> Specify the consensus client ('prysm' or 'lighthouse')"
// );
console.log(" -c <client> Specify the consensus client ('prysm')");
console.log(" -d <path> Specify the install directory (defaults to ~)");
console.log(" -h Display this help message and exit");
console.log("");
}
function isValidPath(p) {
try {
return fs.existsSync(p) && fs.statSync(p).isDirectory();
} catch (err) {
return false;
}
}
// Process command-line arguments
const argv = minimist(process.argv.slice(2));
if (argv.e) {
executionClient = argv.e;
if (executionClient !== "geth") {
console.log("Invalid option for -e. Use 'geth'.");
process.exit(1);
}
}
if (argv.c) {
consensusClient = argv.c;
if (consensusClient !== "prysm") {
console.log("Invalid option for -c. Use 'prysm'.");
process.exit(1);
}
}
// if (argv.e) {
// executionClient = argv.e;
// if (executionClient !== "geth" && executionClient !== "reth") {
// console.log("Invalid option for -e. Use 'geth' or 'reth'.");
// process.exit(1);
// }
// }
//
// if (argv.c) {
// consensusClient = argv.c;
// if (consensusClient !== "prysm" && consensusClient !== "lighthouse") {
// console.log("Invalid option for -c. Use 'prysm' or 'lighthouse'.");
// process.exit(1);
// }
// }
if (argv.d) {
installDir = argv.d;
if (!isValidPath(installDir)) {
console.log(`Invalid option for -d. '${installDir}' is not a valid path.`);
process.exit(1);
}
}
if (argv.h) {
showHelp();
process.exit(0);
}
function debugToFile(data, callback) {
const filePath = path.join(installDir, "bgnode", "debug.log");
const now = new Date();
const timestamp = `${now.toLocaleDateString()} ${now.toLocaleTimeString()}`;
const content =
typeof data === "object"
? `${timestamp} - ${JSON.stringify(data, null, 2)}\n`
: `${timestamp} - ${data}\n`;
fs.writeFile(filePath, content, { flag: "a" }, (err) => {
if (err) {
console.error("Failed to write to file:", err);
} else {
if (callback) callback();
}
});
}
function getFormattedDateTime() {
const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, "0");
const day = now.getDate().toString().padStart(2, "0");
const hour = now.getHours().toString().padStart(2, "0");
const minute = now.getMinutes().toString().padStart(2, "0");
const second = now.getSeconds().toString().padStart(2, "0");
return `${year}_${month}_${day}_${hour}_${minute}_${second}`;
}
function createJwtSecret(jwtDir) {
if (!fs.existsSync(jwtDir)) {
console.log(`\nCreating '${jwtDir}'`);
fs.mkdirSync(jwtDir, { recursive: true });
}
if (!fs.existsSync(`${jwtDir}/jwt.hex`)) {
console.log("Generating JWT.hex file.");
execSync(`cd "${jwtDir}" && openssl rand -hex 32 > jwt.hex`, {
stdio: "inherit",
});
}
}
function downloadRethSnapshot(rethDir, platform) {
const snapshotDate = "2024-05-14";
if (
!fs.existsSync(
path.join(installDir, "bgnode", "reth", "database", "db", "mdbx.dat")
) ||
!fs.existsSync(
path.join(installDir, "bgnode", "reth", "database", "blobstore")
)
) {
console.log("\nDownloading Reth snapshot.");
if (platform === "darwin") {
execSync(
`cd "${rethDir}/database" && wget -O - https://downloads.merkle.io/reth-${snapshotDate}.tar.lz4 | lz4 -dc | tar -xvf -`,
{ stdio: "inherit" }
);
} else if (platform === "linux") {
execSync(
`cd "${rethDir}/database" && wget -O - https://downloads.merkle.io/reth-${snapshotDate}.tar.lz4 | tar -I lz4 -xvf -`,
{ stdio: "inherit" }
);
} else if (platform === "win32") {
// TODO: Add code for downloading snapshot on windows
}
} else {
console.log("\nReth snapshot already downloaded.");
}
}
function installMacLinuxExecutionClient(
executionClient,
platform,
gethVer,
rethVer
) {
const arch = os.arch();
const configs = {
darwin: {
x64: {
gethFileName: `geth-darwin-amd64-${gethVer}-ab48ba42`,
rethFileName: `reth-v${rethVer}-rc.2-x86_64-apple-darwin`,
},
arm64: {
gethFileName: `geth-darwin-arm64-${gethVer}-ab48ba42`,
rethFileName: `reth-v${rethVer}-rc.2-aarch64-apple-darwin`,
},
},
linux: {
x64: {
gethFileName: `geth-linux-amd64-${gethVer}-ab48ba42`,
rethFileName: `reth-v${rethVer}-rc.2-x86_64-unknown-linux-gnu`,
},
arm64: {
gethFileName: `geth-linux-arm64-${gethVer}-ab48ba42`,
rethFileName: `reth-v${rethVer}-rc.2-aarch64-unknown-linux-gnu`,
},
},
};
const { gethFileName, rethFileName } = configs[platform][arch];
if (executionClient === "geth") {
const gethDir = path.join(installDir, "bgnode", "geth");
const gethScript = path.join(gethDir, "geth");
if (!fs.existsSync(gethScript)) {
console.log("\nInstalling Geth.");
if (!fs.existsSync(gethDir)) {
console.log(`Creating '${gethDir}'`);
fs.mkdirSync(`${gethDir}/database`, { recursive: true });
fs.mkdirSync(`${gethDir}/logs`, { recursive: true });
}
console.log("Downloading Geth.");
execSync(
`cd "${gethDir}" && curl -L -O -# https://gethstore.blob.core.windows.net/builds/${gethFileName}.tar.gz`,
{ stdio: "inherit" }
);
console.log("Uncompressing Geth.");
execSync(`cd "${gethDir}" && tar -xzvf "${gethFileName}.tar.gz"`, {
stdio: "inherit",
});
execSync(`cd "${gethDir}/${gethFileName}" && mv geth ..`, {
stdio: "inherit",
});
console.log("Cleaning up Geth directory.");
execSync(
`cd "${gethDir}" && rm -r "${gethFileName}" && rm "${gethFileName}.tar.gz"`,
{ stdio: "inherit" }
);
} else {
console.log("Geth is already installed.");
}
} else if (executionClient === "reth") {
const rethDir = path.join(installDir, "bgnode", "reth");
const rethScript = path.join(rethDir, "reth");
if (!fs.existsSync(rethScript)) {
console.log("\nInstalling Reth.");
if (!fs.existsSync(rethDir)) {
console.log(`Creating '${rethDir}'`);
fs.mkdirSync(`${rethDir}/database`, { recursive: true });
fs.mkdirSync(`${rethDir}/logs`, { recursive: true });
}
console.log("Downloading Reth.");
execSync(
`cd "${rethDir}" && curl -L -O -# https://github.com/paradigmxyz/reth/releases/download/v${rethVer}-rc.2/${rethFileName}.tar.gz`,
{ stdio: "inherit" }
);
console.log("Uncompressing Reth.");
execSync(`cd "${rethDir}" && tar -xzvf "${rethFileName}.tar.gz"`, {
stdio: "inherit",
});
console.log("Cleaning up Reth directory.");
execSync(`cd "${rethDir}" && rm "${rethFileName}.tar.gz"`, {
stdio: "inherit",
});
// downloadRethSnapshot(rethDir, platform);
} else {
console.log("Reth is already installed.");
}
}
}
function installMacLinuxConsensusClient(
consensusClient,
platform,
lighthouseVer
) {
const arch = os.arch();
const configs = {
darwin: {
x64: {
lighthouseFileName: `lighthouse-v${lighthouseVer}-x86_64-apple-darwin`,
},
arm64: {
lighthouseFileName: `lighthouse-v${lighthouseVer}-x86_64-apple-darwin-portable`,
},
},
linux: {
x64: {
lighthouseFileName: `lighthouse-v${lighthouseVer}-x86_64-unknown-linux-gnu`,
},
arm64: {
lighthouseFileName: `lighthouse-v${lighthouseVer}-aarch64-unknown-linux-gnu`,
},
},
};
const prysmFileName = "prysm";
const { lighthouseFileName } = configs[platform][arch];
if (consensusClient === "prysm") {
const prysmDir = path.join(installDir, "bgnode", "prysm");
const prysmScript = path.join(prysmDir, "prysm.sh");
if (!fs.existsSync(prysmScript)) {
console.log("\nInstalling Prysm.");
if (!fs.existsSync(prysmDir)) {
console.log(`Creating '${prysmDir}'`);
fs.mkdirSync(`${prysmDir}/database`, { recursive: true });
fs.mkdirSync(`${prysmDir}/logs`, { recursive: true });
}
console.log("Downloading Prysm.");
execSync(
`cd "${prysmDir}" && curl -L -O -# https://raw.githubusercontent.com/prysmaticlabs/prysm/master/${prysmFileName}.sh && chmod +x prysm.sh`,
{ stdio: "inherit" }
);
} else {
console.log("Prysm is already installed.");
}
} else if (consensusClient === "lighthouse") {
const lighthouseDir = path.join(installDir, "bgnode", "lighthouse");
const lighthouseScript = path.join(lighthouseDir, "lighthouse");
if (!fs.existsSync(lighthouseScript)) {
console.log("\nInstalling Lighthouse.");
if (!fs.existsSync(lighthouseDir)) {
console.log(`Creating '${lighthouseDir}'`);
fs.mkdirSync(`${lighthouseDir}/database`, { recursive: true });
fs.mkdirSync(`${lighthouseDir}/logs`, { recursive: true });
}
console.log("Downloading Lighthouse.");
execSync(
`cd "${lighthouseDir}" && curl -L -O -# https://github.com/sigp/lighthouse/releases/download/v${lighthouseVer}/${lighthouseFileName}.tar.gz`,
{ stdio: "inherit" }
);
console.log("Uncompressing Lighthouse.");
execSync(
`cd "${lighthouseDir}" && tar -xzvf ${lighthouseFileName}.tar.gz`,
{
stdio: "inherit",
}
);
console.log("Cleaning up Lighthouse directory.");
execSync(`cd "${lighthouseDir}" && rm ${lighthouseFileName}.tar.gz`, {
stdio: "inherit",
});
} else {
console.log("Lighthouse is already installed.");
}
}
}
function installWindowsExecutionClient(executionClient) {
if (executionClient === "geth") {
const gethDir = path.join(installDir, "bgnode", "geth");
const gethScript = path.join(gethDir, "geth.exe");
if (!fs.existsSync(gethScript)) {
console.log("\nInstalling Geth.");
if (!fs.existsSync(gethDir)) {
console.log(`Creating '${gethDir}'`);
fs.mkdirSync(`${gethDir}/database`, { recursive: true });
fs.mkdirSync(`${gethDir}/logs`, { recursive: true });
}
execSync(
`cd "${gethDir}" && curl https://gethstore.blob.core.windows.net/builds/geth-windows-amd64-1.14.3-ab48ba42.zip --output geth.zip`,
{ stdio: "inherit" }
);
execSync(`cd "${gethDir}" && tar -xf geth.zip`, {
stdio: "inherit",
});
execSync(
`cd "${gethDir}/geth-windows-amd64-1.14.3-ab48ba42" && move geth.exe ..`,
{
stdio: "inherit",
}
);
execSync(
`cd "${gethDir}" && del geth.zip && rd /S /Q geth-windows-amd64-1.14.3-ab48ba42`,
{ stdio: "inherit" }
);
} else {
console.log("Geth is already installed.");
}
} else if (executionClient === "reth") {
const rethDir = path.join(installDir, "bgnode", "reth");
const rethScript = path.join(rethDir, "reth.exe");
if (!fs.existsSync(rethScript)) {
console.log("\nInstalling Reth.");
if (!fs.existsSync(rethDir)) {
console.log(`Creating '${rethDir}'`);
fs.mkdirSync(`${rethDir}/database`, { recursive: true });
fs.mkdirSync(`${rethDir}/logs`, { recursive: true });
}
execSync(
`cd "${rethDir}" && curl -LO https://github.com/paradigmxyz/reth/releases/download/v0.2.0-beta.6/reth-v0.2.0-beta.6-x86_64-pc-windows-gnu.tar.gz`,
{ stdio: "inherit" }
);
execSync(
`cd "${rethDir}" && tar -xzf reth-v0.2.0-beta.6-x86_64-pc-windows-gnu.tar.gz`,
{
stdio: "inherit",
}
);
execSync(
`cd "${rethDir}" && del reth-v0.2.0-beta.6-x86_64-pc-windows-gnu.tar.gz`,
{
stdio: "inherit",
}
);
} else {
console.log("Reth is already installed.");
}
}
}
function installWindowsConsensusClient(consensusClient) {
if (consensusClient === "prysm") {
const prysmDir = path.join(installDir, "bgnode", "prysm");
const prysmScript = path.join(prysmDir, "prysm.bat");
if (!fs.existsSync(prysmScript)) {
console.log("Installing Prysm.");
if (!fs.existsSync(prysmDir)) {
console.log(`Creating '${prysmDir}'`);
fs.mkdirSync(`${prysmDir}/database`, { recursive: true });
fs.mkdirSync(`${prysmDir}/logs`, { recursive: true });
}
execSync(
`cd "${prysmDir}" && curl https://raw.githubusercontent.com/prysmaticlabs/prysm/master/prysm.bat --output prysm.bat`,
{ stdio: "inherit" }
);
execSync(
"reg add HKCU\\Console /v VirtualTerminalLevel /t REG_DWORD /d 1",
{ stdio: "inherit" }
);
} else {
console.log("Prysm is already installed.");
}
} else if (consensusClient === "lighthouse") {
const lighthouseDir = path.join(installDir, "bgnode", "lighthouse");
const lighthouseScript = path.join(lighthouseDir, "lighthouse.exe");
if (!fs.existsSync(lighthouseScript)) {
console.log("Installing Lighthouse.");
if (!fs.existsSync(lighthouseDir)) {
console.log(`Creating '${lighthouseDir}'`);
fs.mkdirSync(`${lighthouseDir}/database`, { recursive: true });
fs.mkdirSync(`${lighthouseDir}/logs`, { recursive: true });
}
execSync(
`cd "${lighthouseDir}" && curl -LO https://github.com/sigp/lighthouse/releases/download/v5.1.3/lighthouse-v5.1.3-x86_64-windows.tar.gz`,
{ stdio: "inherit" }
);
execSync(
`cd "${lighthouseDir}" && tar -xzf lighthouse-v5.1.3-x86_64-windows.tar.gz`,
{
stdio: "inherit",
}
);
execSync(
`cd "${lighthouseDir}" && del lighthouse-v5.1.3-x86_64-windows.tar.gz`,
{
stdio: "inherit",
}
);
} else {
console.log("Lighthouse is already installed.");
}
}
}
function stripAnsiCodes(input) {
return input.replace(
/[\u001b\u009b][[()#;?]*(?:(?:[a-zA-Z\d]*(?:;[a-zA-Z\d]*)*)?\u0007|(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nq-uy=><~])/g,
""
);
}
function parseExecutionLogs(line) {
line = stripAnsiCodes(line);
if (line.includes("Looking for peers")) {
// const peerCountMatch = line.match(/peercount=(\d+)/);
// const peerCount = parseInt(peerCountMatch[1], 10);
// updatePeerCountLcd(peerCount);
} else if (line.includes("Syncing beacon headers")) {
const headerDlMatch = line.match(
/downloaded=([\d,]+)\s+left=([\d,]+)\s+eta=([^\s]+)/
);
const headerDlDownloaded = parseInt(headerDlMatch[1].replace(/,/g, ""), 10);
const headerDlLeft = parseInt(headerDlMatch[2].replace(/,/g, ""), 10);
const headerDlEta = headerDlMatch[3];
const headerDlProgress =
headerDlDownloaded / (headerDlDownloaded + headerDlLeft);
updateHeaderDlGauge(headerDlProgress);
} else if (line.includes("Syncing: chain download in progress")) {
const chainSyncMatch = line.match(/synced=([\d.]+)%/);
const chainDlProgress = parseFloat(chainSyncMatch[1]) / 100;
updateChainDlGauge(chainDlProgress);
} else if (line.includes("Syncing: state download in progress")) {
const stateSyncMatch = line.match(/synced=([\d.]+)%/);
const stateDlProgress = parseFloat(stateSyncMatch[1]) / 100;
updateStateDlGauge(stateDlProgress);
} else if (line.includes("Chain head was updated")) {
updateStatusBox(localClient);
checkIn();
}
}
function parseConsensusLogs(line) {
line = stripAnsiCodes(line);
if (line.includes("Latest Prysm version is")) {
const prysmVerMatch = line.match(/version is v(\d+\.\d+\.\d+)/);
prysmVer = prysmVerMatch[1];
consensusLog.setLabel(`Prysm v${prysmVer}`);
screen.render();
}
}
let executionChild;
let consensusChild;
let executionExited = false;
let consensusExited = false;
function handleExit(signal) {
if (executionChild) {
executionChild.kill("SIGINT");
}
if (consensusChild) {
consensusChild.kill("SIGINT");
}
// Check if both child processes have exited
const checkExit = () => {
if (executionExited && consensusExited) {
process.exit(0);
}
};
// Listen for exit events
if (executionChild) {
executionChild.on("exit", (code) => {
executionExited = true;
checkExit();
});
} else {
executionExited = true;
}
if (consensusChild) {
consensusChild.on("exit", (code) => {
consensusExited = true;
checkExit();
});
} else {
consensusExited = true;
}
// Initial check in case both children are already not running
checkExit();
}
process.on("SIGINT", handleExit);
process.on("SIGTERM", handleExit);
function startClient(clientName, installDir, logBox) {
let clientCommand, clientArgs;
if (clientName === "geth") {
clientCommand = path.join(__dirname, "node_clients/geth.js");
clientArgs = [];
} else if (clientName === "reth") {
clientCommand = path.join(__dirname, "node_clients/reth.js");
clientArgs = [];
} else if (clientName === "prysm") {
clientCommand = path.join(__dirname, "node_clients/prysm.js");
clientArgs = [];
} else if (clientName === "lighthouse") {
clientCommand = path.join(__dirname, "node_clients/lighthouse.js");
clientArgs = [];
} else {
clientCommand = path.join(installDir, "bgnode", clientName, clientName);
clientArgs = [];
}
const child = spawn("node", [clientCommand, ...clientArgs], {
stdio: ["inherit", "pipe", "inherit"],
cwd: process.env.HOME,
env: { ...process.env, INSTALL_DIR: installDir },
});
if (clientName === "geth") {
executionChild = child;
} else if (clientName === "reth") {
consensusChild = child;
} else if (clientName === "prysm") {
consensusChild = child;
} else if (clientName === "lighthouse") {
consensusChild = child;
}
child.stdout.on("data", (data) => {
logBox.log(data.toString());
if (clientName === "geth") {
parseExecutionLogs(data.toString());
} else if (clientName === "prysm") {
parseConsensusLogs(data.toString());
}
});
child.on("exit", (code) => {
logBox.log(`${clientName} process exited with code ${code}`);
});
child.on("error", (err) => {
logBox.log(`Error: ${err.message}`);
});
}
module.exports = { startClient };
let lastStats = {
totalSent: 0,
totalReceived: 0,
timestamp: Date.now(),
};
let screen;
let networkLine;
let networkDataX = [];
let dataSentY = [];
let dataReceivedY = [];
let cpuLine;
let cpuDataX = [];
let dataCpuUsage;
let headerDlGauge;
let stateDlGauge;
let chainDlGauge;
// let peerCountLcd;
let statusBox;
let memGauge;
let storageGauge;
function getCpuUsage() {
return new Promise((resolve, reject) => {
si.currentLoad()
.then((load) => {
const currentLoad = load.currentLoad;
resolve(currentLoad);
})
.catch((error) => {
debugToFile(
`getCpuUsage() Error fetching CPU usage stats: ${error}`,
() => {}
);
reject(error);
});
});
}
async function updateCpuLinePlot() {
try {
const currentLoad = await getCpuUsage(); // Get the overall CPU load
if (currentLoad === undefined || currentLoad === null) {
throw new Error("Failed to fetch CPU usage data or data is empty");
}
const now = new Date();
const timeLabel = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
if (!Array.isArray(cpuDataX)) {
cpuDataX = [];
}
if (!Array.isArray(dataCpuUsage)) {
dataCpuUsage = [];
}
cpuDataX.push(timeLabel);
dataCpuUsage.push(currentLoad);
// Prepare series data for the overall CPU load
const series = [
{
title: "", // Use an empty string for the title
x: cpuDataX,
y: dataCpuUsage,
style: { line: "cyan" }, // Use the first color
},
];
cpuLine.setData(series);
screen.render();
// Limit data history to the last 60 points
if (cpuDataX.length > 60) {
cpuDataX.shift();
dataCpuUsage.shift();
}
} catch (error) {
debugToFile(
`updateCpuLineChart() Failed to update CPU usage line chart: ${error}`,
() => {}
);
}
}
function getNetworkStats() {
return new Promise((resolve, reject) => {
si.networkStats()
.then((interfaces) => {
let currentTotalSent = 0;
let currentTotalReceived = 0;
interfaces.forEach((iface) => {
currentTotalSent += iface.tx_bytes;
currentTotalReceived += iface.rx_bytes;
});
// Calculate time difference in seconds
const currentTime = Date.now();
const timeDiff = (currentTime - lastStats.timestamp) / 1000;
// Calculate bytes per second
const sentPerSecond =
(currentTotalSent - lastStats.totalSent) / timeDiff;
const receivedPerSecond =
(currentTotalReceived - lastStats.totalReceived) / timeDiff;
// Update last stats for next calculation
lastStats = {
totalSent: currentTotalSent,
totalReceived: currentTotalReceived,
timestamp: currentTime,
};
resolve({
sentPerSecond: sentPerSecond / 1000000,
receivedPerSecond: receivedPerSecond / 1000000,
});
})
.catch((error) => {
debugToFile(
`getNetworkStats() Error fetching network stats: ${error}`,
() => {}
);
reject(error);
});
});
}
async function updateNetworkLinePlot() {
try {
const stats = await getNetworkStats();
const now = new Date();
networkDataX.push(
now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds()
);
dataSentY.push(stats.sentPerSecond);
dataReceivedY.push(stats.receivedPerSecond);
var seriesNetworkSent = {
title: "Sent",
x: networkDataX,
y: dataSentY,
style: { line: "red" },
};
var seriesNetworkReceived = {
title: "Received",
x: networkDataX,
y: dataReceivedY,
style: { line: "blue" },
};
networkLine.setData([seriesNetworkSent, seriesNetworkReceived]);
screen.render();
// Keep the data arrays from growing indefinitely
if (networkDataX.length > 60) {
networkDataX.shift();
dataSentY.shift();
dataReceivedY.shift();
}
} catch (error) {
debugToFile(`updateNetworkPlot(): ${error}`, () => {});
}
}
// async function updatePeerCountLcd(peerCount) {
// try {
// if (peerCountLcd) {
// peerCountLcd.setDisplay(peerCount.toString());
// screen.render();
// }
// } catch (error) {
// debugToFile(`updatePeerCountLcd(): ${error}`, () => {});
// }
// }
const progressFilePath = path.join(installDir, "bgnode", "progress.json");
function saveProgress(progress) {
fs.writeFileSync(
progressFilePath,
JSON.stringify(progress, null, 2),
"utf-8"
);
}
function loadProgress() {
if (fs.existsSync(progressFilePath)) {
const data = fs.readFileSync(progressFilePath, "utf-8");
return JSON.parse(data);
}
return {
headerDlProgress: 0,
chainDlProgress: 0,
stateDlProgress: 0,
};
}
const progress = loadProgress();
async function updateHeaderDlGauge(headerDlProgress) {
try {
if (headerDlGauge) {
headerDlGauge.setPercent(headerDlProgress);
progress.headerDlProgress = headerDlProgress;
saveProgress(progress);
screen.render();
}
} catch (error) {
debugToFile(`updateHeaderDlGauge(): ${error}`, () => {});
}
}
async function updateChainDlGauge(chainDlProgress) {
try {
if (chainDlGauge) {
chainDlGauge.setPercent(chainDlProgress);
progress.chainDlProgress = chainDlProgress;
saveProgress(progress);
screen.render();
}
} catch (error) {
debugToFile(`updateChainDlGauge(): ${error}`, () => {});
}
}
async function updateStateDlGauge(stateDlProgress) {
try {
if (stateDlGauge) {
stateDlGauge.setPercent(stateDlProgress);
progress.stateDlProgress = stateDlProgress;
saveProgress(progress);
screen.render();
}
} catch (error) {
debugToFile(`updateStateDlGauge(): ${error}`, () => {});
}
}
// async function updateSyncProgressGauge(client, gauge) {
// try {
// const syncingStatus = await isSyncing(client);
// if (syncingStatus) {
// const currentBlock = parseInt(syncingStatus.currentBlock, 16);
// const highestBlock = parseInt(syncingStatus.highestBlock, 16);
// if (highestBlock > 0) {
// const progress = ((currentBlock / highestBlock) * 100).toFixed(1); // Calculate sync progress
// gauge.setPercent(progress);
// }
// } else {
// gauge.setPercent(100); // If not syncing, assume fully synced
// }
// screen.render();
// } catch (error) {
// console.error();
// debugToFile(
// `updateSyncProgressGauge() Failed to update sync progress gauge: ${error}`,
// () => {}
// );
// }
// }
async function isSyncing(client) {
try {
const syncingStatus = await client.request({
method: "eth_syncing",
params: [],
});
return syncingStatus;
} catch (error) {
throw new Error(`Failed to fetch syncing status: ${error.message}`);
}
}
async function updateStatusBox(client) {
try {
const syncingStatus = await isSyncing(client);
if (syncingStatus) {
const currentBlock = parseInt(syncingStatus.currentBlock, 16);
const highestBlock = parseInt(syncingStatus.highestBlock, 16);
statusBox.setContent(
`INITIAL SYNC IN PROGRESS\nCurrent Block: ${currentBlock.toFixed(
0
)}\nHighest Block: ${highestBlock.toFixed(0)}`
);
} else {
const blockNumber = await localClient.getBlockNumber();
statusBox.setContent(
`FOLLOWING CHAIN HEAD\nCurrent Block: ${blockNumber}`
);
}
screen.render();
} catch (error) {
console.error();
debugToFile(
`updateStatusBox() Failed to update sync progress gauge: ${error}`,
() => {}
);
}
}
function getDiskUsage(installDir) {
return new Promise((resolve, reject) => {
si.fsSize()
.then((drives) => {
let diskUsagePercent = 0;
// Find the drive where the OS is installed. This is often the drive mounted at "/".
const osDrive = drives.find((drive) => {
return drive.mount === "/" || drive.mount === "C:/";
});
if (osDrive) {
diskFreePercent = 100 - (osDrive.available / osDrive.size) * 100;
} else {
debugToFile(`OS Drive not found.`, () => {});
}
resolve(diskFreePercent.toFixed(1));
})
.catch((error) => {
debugToFile(
`getDiskUsage() Error fetching disk usage stats: ${error}`,
() => {}
);
reject(error);
});
});
}
async function updateDiskGauge(installDir) {
try {
const diskUsagePercent = await getDiskUsage(installDir); // Wait for disk usage stats
// storageGauge.setData([{ label: "% Used", percent: diskUsagePercent }]);
storageGauge.setPercent(diskUsagePercent);
screen.render();
} catch (error) {
debugToFile(
`updateDiskGauge() Failed to update disk usage donut: ${error}`,
() => {}
);
}
}
function getMemoryUsage() {
return new Promise((resolve, reject) => {
si.mem()
.then((memory) => {
const totalMemory = memory.total;
const usedMemory = memory.active; // 'active' is usually what's actually used