-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_functions.js
1597 lines (1509 loc) · 50.5 KB
/
rpc_functions.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
// rpc_functions.js
require("dotenv").config();
const http = require("http");
const https = require("https");
const fs = require("fs");
const os = require("os");
const path = require("path");
const readline = require("readline");
const { URL } = require("url");
const axios = require("axios");
const Joi = require("joi");
const { SupernodeList } = require("./sequelize_data_models");
const { messageSchema, supernodeListSchema } = require("./validation_schemas");
const { logger, safeStringify } = require("./logger");
const { execSync, spawn } = require("child_process");
const storage = require("node-persist");
const { setPastelIdAndPassphrase } = require("./storage");
let rpc_connection;
const globals = require("./globals");
// Initialize the storage
storage.init();
async function searchBinaryRecursively(directory, binaryName) {
try {
const result = execSync(
`sudo find ${directory} -type f -name ${binaryName} -size +7M`,
{ encoding: "utf-8" }
);
return result.trim().split("\n").filter(Boolean);
} catch (error) {
return [];
}
}
async function getMostRecentBinary(binaries) {
const stats = await Promise.all(
binaries.map(async (binary) => {
const stat = await fs.promises.stat(binary);
return { binary, mtime: stat.mtime };
})
);
return stats.sort((a, b) => b.mtime - a.mtime)[0]?.binary;
}
async function locatePasteldBinary() {
await storage.init();
let pasteldBinaryPath = await storage.getItem("pasteldBinaryPath");
if (!pasteldBinaryPath || !fs.existsSync(pasteldBinaryPath)) {
const searchDirectories = ["/home", "/usr/local/bin", "/usr/bin"];
if (process.platform === "win32") {
searchDirectories.push(process.env.ProgramFiles);
} else if (process.platform === "darwin") {
searchDirectories.push("/Users");
} else {
searchDirectories.push("/home", "/etc");
}
const foundBinaries = (
await Promise.all(
searchDirectories.map((dir) => searchBinaryRecursively(dir, "pasteld"))
)
).flat();
pasteldBinaryPath = await getMostRecentBinary(foundBinaries);
if (!pasteldBinaryPath) {
throw new Error("pasteld binary not found on the system.");
}
await storage.setItem("pasteldBinaryPath", pasteldBinaryPath);
}
return pasteldBinaryPath;
}
async function startPastelDaemon() {
try {
const pasteldPath = await locatePasteldBinary();
console.log(`Starting pasteld from path: ${pasteldPath}`);
const pastelDaemon = spawn(pasteldPath, [], { stdio: "inherit" });
pastelDaemon.on("close", (code) => {
console.log(`pasteld process exited with code ${code}`);
});
pastelDaemon.on("error", (err) => {
console.error("Error starting pasteld:", err);
});
} catch (error) {
console.error("Failed to start pasteld:", error);
}
}
async function getMostRecentFile(files) {
return files
.map((file) => ({ file, mtime: fs.statSync(file).mtime }))
.sort((a, b) => b.mtime - a.mtime)[0]?.file;
}
function searchFileRecursively(directory, filename) {
try {
const result = execSync(`sudo find ${directory} -name ${filename}`, {
encoding: "utf-8",
});
return result.trim().split("\n").filter(Boolean);
} catch (error) {
return [];
}
}
async function getLocalRPCSettings(
directoryWithPastelConf = path.join(os.homedir(), ".pastel")
) {
let newDirectoryWithPastelConf = directoryWithPastelConf;
if (process.platform === "win32") {
newDirectoryWithPastelConf = path.join(os.homedir(), "AppData", "Roaming", "Pastel")
}
if (process.platform === "darwin") {
newDirectoryWithPastelConf = path.join(os.homedir(), "Library", "Application Support", "Pastel")
}
if (['linux'].indexOf(process.platform) !== -1) {
newDirectoryWithPastelConf = newDirectoryWithPastelConf.replace(/ /g, '\\ ')
}
await storage.init();
let pastelConfPath =
(await storage.getItem("pastelConfPath")) ||
path.join(newDirectoryWithPastelConf, "pastel.conf");
if (!fs.existsSync(pastelConfPath)) {
console.log(
`pastel.conf not found in stored path or default directory, scanning the system...`
);
const searchDirectories = ["/home"];
if (process.platform === "win32") {
searchDirectories.push(process.env.ProgramData);
} else if (process.platform === "darwin") {
searchDirectories.push("/Users");
} else {
searchDirectories.push("/home", "/etc");
}
const foundFiles = searchDirectories.flatMap((dir) =>
searchFileRecursively(dir, "pastel.conf")
);
pastelConfPath = await getMostRecentFile(foundFiles);
if (!pastelConfPath) {
throw new Error("pastel.conf file not found on the system.");
}
await storage.setItem("pastelConfPath", pastelConfPath);
}
const lines = fs.readFileSync(pastelConfPath, "utf-8").split("\n");
const otherFlags = {};
let rpchost = "127.0.0.1";
let rpcport = "19932";
let rpcuser = "";
let rpcpassword = "";
for (const line of lines) {
const trimmedLine = line.trim();
if (!trimmedLine || trimmedLine.startsWith("#")) {
continue; // Ignore blank lines and comments
}
if (trimmedLine.includes("=")) {
const [key, value] = trimmedLine.split("=", 2);
const trimmedKey = key.trim();
const trimmedValue = value.trim();
if (trimmedKey === "rpcport") {
rpcport = trimmedValue;
} else if (trimmedKey === "rpcuser") {
rpcuser = trimmedValue;
} else if (trimmedKey === "rpcpassword") {
rpcpassword = trimmedValue;
} else if (trimmedKey === "rpchost") {
rpchost = trimmedValue;
} else {
otherFlags[trimmedKey] = trimmedValue;
}
}
}
return { rpchost, rpcport, rpcuser, rpcpassword, otherFlags };
}
class JSONRPCException extends Error {
constructor(rpcError) {
super(rpcError.message);
this.error = rpcError;
this.code = rpcError.code || null;
this.message = rpcError.message || null;
}
toString() {
return `${this.code}: ${this.message}`;
}
}
class Semaphore {
constructor(maxConcurrent) {
this.maxConcurrent = maxConcurrent;
this.counter = maxConcurrent;
this.waiting = [];
}
async acquire() {
if (this.counter <= 0) {
await new Promise((resolve) => this.waiting.push(resolve));
}
this.counter--;
}
release() {
this.counter++;
if (this.waiting.length > 0) {
const resolve = this.waiting.shift();
resolve();
}
}
}
class AsyncAuthServiceProxy {
static maxConcurrentRequests = 5000;
static semaphore = new Semaphore(AsyncAuthServiceProxy.maxConcurrentRequests);
constructor(
serviceUrl,
serviceName = null,
reconnectTimeout = 3,
reconnectAmount = 2,
requestTimeout = 10
) {
this.serviceUrl = serviceUrl;
this.serviceName = serviceName;
this.url = new URL(serviceUrl);
this.client = axios.create({
timeout: requestTimeout * 1000,
maxContentLength: Infinity,
maxBodyLength: Infinity,
httpAgent: new http.Agent({ keepAlive: true, maxSockets: 200 }),
httpsAgent: new https.Agent({ keepAlive: true, maxSockets: 200 }),
});
this.idCount = 0;
const { username, password } = this.url;
const authPair = `${username}:${password}`;
this.authHeader = `Basic ${Buffer.from(authPair).toString("base64")}`;
this.reconnectTimeout = reconnectTimeout;
this.reconnectAmount = reconnectAmount;
this.requestTimeout = requestTimeout;
}
async call(methodName, ...args) {
await AsyncAuthServiceProxy.semaphore.acquire();
try {
this.idCount += 1;
const postData = JSON.stringify({
jsonrpc: "2.0",
method: methodName,
params: args,
id: this.idCount,
});
const headers = {
Host: this.url.hostname,
"User-Agent": "AuthServiceProxy/0.1",
Authorization: this.authHeader,
"Content-Type": "application/json",
};
let response;
for (let i = 0; i < this.reconnectAmount; i++) {
try {
if (i > 0) {
const sleepTime = this.reconnectTimeout * 2 ** i;
logger.error(`Reconnect try #${i + 1}`);
logger.info(`Waiting for ${sleepTime} seconds before retrying.`);
await new Promise((resolve) =>
setTimeout(resolve, sleepTime * 1000)
);
}
response = await this.client.post(this.serviceUrl, postData, {
headers,
});
break;
} catch (error) {
logger.error(`Error occurred on attempt ${i + 1}: ${error}`);
if (i === this.reconnectAmount - 1) {
logger.error("Reconnect tries exceeded.");
throw error;
}
}
}
if (!response) {
throw new Error("No response from server, all retry attempts failed.");
}
const responseJson = response.data;
if (responseJson.error) {
throw new JSONRPCException(responseJson.error);
} else if (!("result" in responseJson)) {
throw new JSONRPCException({
code: -343,
message: "Missing JSON-RPC result",
});
}
return responseJson.result;
} finally {
AsyncAuthServiceProxy.semaphore.release();
}
}
// Create a proxy to handle method calls dynamically
static create(serviceUrl) {
const handler = {
get: function (target, propKey) {
if (typeof target[propKey] === "function") {
return function (...args) {
return target[propKey](...args);
};
} else {
return function (...args) {
return target.call(propKey, ...args);
};
}
},
};
return new Proxy(new AsyncAuthServiceProxy(serviceUrl), handler);
}
}
async function initializeRPCConnection() {
const { rpchost, rpcport, rpcuser, rpcpassword } =
await getLocalRPCSettings();
rpc_connection = AsyncAuthServiceProxy.create(
`http://${rpcuser}:${rpcpassword}@${rpchost}:${rpcport}`
);
}
async function waitForRPCConnection(maxRetries = 5, interval = 1000) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
if (rpc_connection) {
return true; // Connection is available
}
logger.info(
`Waiting for RPC connection... Attempt ${attempt}/${maxRetries}`
);
await new Promise((resolve) => setTimeout(resolve, interval));
}
logger.error("Failed to establish RPC connection after several attempts.");
return false; // Connection is not available after retries
}
async function checkMasternodeTop() {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const masternodeTopOutput = await rpc_connection.masternode("top");
return masternodeTopOutput;
}
async function stopPastelDaemon() {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const masternodeTopOutput = await rpc_connection.stop();
return masternodeTopOutput;
}
async function getCurrentPastelBlockHeight() {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const bestBlockHash = await rpc_connection.getbestblockhash();
const bestBlockDetails = await rpc_connection.getblock(bestBlockHash);
const currentBlockHeight = bestBlockDetails.height;
return currentBlockHeight;
}
async function getBestBlockHashAndMerkleRoot() {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const bestBlockHeight = await getCurrentPastelBlockHeight();
const bestBlockHash = await rpc_connection.getblockhash(bestBlockHeight);
const bestBlockDetails = await rpc_connection.getblock(bestBlockHash);
const bestBlockMerkleRoot = bestBlockDetails.merkleroot;
return [bestBlockHash, bestBlockMerkleRoot, bestBlockHeight];
}
async function verifyMessageWithPastelID(
pastelid,
messageToVerify,
pastelIDSignatureOnMessage
) {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const verificationResult = await rpc_connection.pastelid(
"verify",
messageToVerify,
pastelIDSignatureOnMessage,
pastelid,
"ed448"
);
return verificationResult.verification; // Return the verification result
}
async function sendToAddress(
address,
amount,
comment = "",
) {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return { success: false, message: "RPC connection is not available" };
}
try {
// Check available balance
const balance = await getBalance();
if (balance < amount) {
const message = `Insufficient balance. Available: ${balance}, Required: ${amount}`;
logger.error(message);
return { success: false, message };
}
// Proceed with sending the amount
const result = await rpc_connection.sendtoaddress(
address,
amount,
comment,
);
return { success: true, result };
} catch (error) {
logger.error(`Error in sendToAddress: ${safeStringify(error).slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
return {
success: false,
message: `Error in sendToAddress: ${safeStringify(error).slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`,
};
}
}
async function sendMany(
amounts,
minConf = 1,
comment = "",
changeAddress = ""
) {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
try {
const fromAccount = "";
const result = await rpc_connection.sendmany(
fromAccount,
amounts,
minConf,
comment,
[""],
changeAddress
);
return result;
} catch (error) {
logger.error(`Error in sendMany: ${safeStringify(error).slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
return null;
}
}
async function checkPSLAddressBalance(addressToCheck) {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const balance = await rpc_connection.z_getbalance(addressToCheck);
return balance;
}
async function checkIfAddressIsAlreadyImportedInLocalWallet(addressToCheck) {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const addressAmounts = await rpc_connection.listaddressamounts();
const addressAmountsArray = Object.entries(addressAmounts).map(
([address, amount]) => ({ address, amount })
);
const filteredAddressAmounts = addressAmountsArray.filter(
(entry) => entry.address === addressToCheck
);
return filteredAddressAmounts.length > 0;
}
async function getAndDecodeRawTransaction(txid, blockhash = null) {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
try {
const rawTxData = await rpc_connection.getrawtransaction(
txid,
0,
blockhash
);
if (!rawTxData) {
logger.error(`Failed to retrieve raw transaction data for ${txid}`);
return {};
}
const decodedTxData = await rpc_connection.decoderawtransaction(rawTxData);
if (!decodedTxData) {
logger.error(`Failed to decode raw transaction data for ${txid}`);
return {};
}
logger.debug(
`Decoded transaction details for ${txid}:`,
safeStringify(decodedTxData)
);
return decodedTxData;
} catch (error) {
logger.error(
`Error in getAndDecodeRawTransaction for ${txid}:`,
safeStringify(error)
);
return {};
}
}
async function getTransactionDetails(txid, includeWatchonly = false) {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
try {
const transactionDetails = await rpc_connection.gettransaction(
txid,
includeWatchonly
);
logger.debug(
`Retrieved transaction details for ${txid}:`,
safeStringify(transactionDetails)
);
return transactionDetails;
} catch (error) {
logger.error(
`Error retrieving transaction details for ${txid}:`,
safeStringify(error)
);
return {};
}
}
async function sendTrackingAmountFromControlAddressToBurnAddressToConfirmInferenceRequest(
inferenceRequestId,
creditUsageTrackingPSLAddress,
creditUsageTrackingAmountInPSL,
burnAddress
) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const amounts = {
[burnAddress]: creditUsageTrackingAmountInPSL,
};
const txid = await sendMany(
amounts,
0,
"Confirmation tracking transaction for inference request with request_id " +
inferenceRequestId,
creditUsageTrackingPSLAddress
);
if (txid) {
logger.info(
`Sent ${creditUsageTrackingAmountInPSL} PSL from ${creditUsageTrackingPSLAddress} to ${burnAddress} to confirm inference request ${inferenceRequestId}. TXID: ${txid}`
);
const transactionInfo = await rpc_connection.gettransaction(txid);
if (transactionInfo) {
return txid;
} else {
logger.error(
`No transaction info found for TXID: ${txid} to confirm inference request ${inferenceRequestId}`
);
}
return null;
} else {
logger.error(
`Failed to send ${creditUsageTrackingAmountInPSL} PSL from ${creditUsageTrackingPSLAddress} to ${burnAddress} to confirm inference request ${inferenceRequestId}`
);
return null;
}
} catch (error) {
logger.error(
"Error in sendTrackingAmountFromControlAddressToBurnAddressToConfirmInferenceRequest:",
error
);
throw error;
}
}
async function importAddress(address, label = "", rescan = false) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
await rpc_connection.importaddress(address, label, rescan);
logger.info(`Imported address: ${address}`);
} catch (error) {
logger.error(
`Error importing address: ${address}. Error:`,
safeStringify(error)
);
}
}
async function getBlockHash(blockHeight) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const blockHash = await rpc_connection.getblockhash(blockHeight);
return blockHash;
} catch (error) {
logger.error(
`Error in getBlockHash for block height ${blockHeight}:`,
error
);
return null;
}
}
async function getBlock(blockHash) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const block = await rpc_connection.getblock(blockHash);
return block;
} catch (error) {
logger.error(
`Error in getBlock for block hash ${blockHash}:`,
safeStringify(error)
);
return null;
}
}
async function signMessageWithPastelID(pastelid, messageToSign, passphrase) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
throw new Error("RPC connection is not available.");
}
const responseObj = await rpc_connection.pastelid(
"sign",
messageToSign,
pastelid,
passphrase,
"ed448"
);
const sig = await responseObj.signature;
return sig;
} catch (error) {
logger.error(`Error in signMessageWithPastelID: ${error.message}`);
if (error.message.includes("Invalid passphrase")) {
throw new Error("Invalid passphrase for PastelID");
}
throw error;
}
}
async function checkPSLAddressBalanceAlternative(addressToCheck) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const addressAmountsDict = await rpc_connection.listaddressamounts();
// Convert the object into an array of objects, each representing a row
const data = Object.entries(addressAmountsDict).map(
([address, amount]) => ({ address, amount })
);
// Filter the array for the specified address
const filteredData = data.filter((item) => item.address === addressToCheck);
// Calculate the sum of the 'amount' column for the filtered array
const balanceAtAddress = filteredData.reduce(
(acc, item) => acc + item.amount,
0
);
return balanceAtAddress;
} catch (error) {
logger.error(
`Error in checkPSLAddressBalanceAlternative: ${safeStringify(error).slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
throw error;
}
}
function formatNumberWithCommas(number) {
return new Intl.NumberFormat("en-US").format(number);
}
async function getMyPslAddressWithLargestBalance() {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
try {
const addressAmounts = await rpc_connection.listaddressamounts();
const addressWithLargestBalance = Object.keys(addressAmounts).reduce(
(maxAddress, currentAddress) => {
return addressAmounts[currentAddress] >
(addressAmounts[maxAddress] || 0)
? currentAddress
: maxAddress;
},
null
);
return addressWithLargestBalance;
} catch (error) {
logger.error(
`Error in getMyPslAddressWithLargestBalance: ${safeStringify(error).slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
throw error;
}
}
async function dumpPrivKey(tAddr) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return;
}
const result = await rpc_connection.dumpprivkey(tAddr);
logger.info(`Dumped private key for address: ${tAddr}`);
return result;
} catch (error) {
logger.error(`Error dumping private key for address ${tAddr}: ${safeStringify(error).slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
throw error;
}
}
async function createAndFundNewPSLCreditTrackingAddress(
amountOfPSLToFundAddressWith
) {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return; // Stop the function if the connection is not available
}
const extraCushion = 1.0; // Add an extra PSL to the funding address to ensure it has a minimum balance
try {
const newCreditTrackingAddress = await rpc_connection.getnewaddress();
const sendResult = await sendToAddress(
newCreditTrackingAddress,
amountOfPSLToFundAddressWith + extraCushion,
"Funding new credit tracking address",
);
if (!sendResult.success) {
logger.error(
`Error funding new credit tracking address ${newCreditTrackingAddress} with ${formatNumberWithCommas(
amountOfPSLToFundAddressWith
)} PSL. Reason: ${sendResult.message}`
);
return null; // Or handle the error accordingly
}
logger.info(
`Funded new credit tracking address ${newCreditTrackingAddress} with ${formatNumberWithCommas(
amountOfPSLToFundAddressWith
)} PSL. TXID: ${sendResult.result}`
);
return { newCreditTrackingAddress, txid: sendResult.result };
} catch (error) {
logger.error(
`Error creating and funding new PSL credit tracking address: ${safeStringify(
error
)}`
);
throw error;
}
}
async function waitForTableCreation() {
const maxRetries = 5;
const retryDelay = 1000; // 1 second
for (let i = 0; i < maxRetries; i++) {
try {
await SupernodeList.findOne();
return; // Table exists, proceed with data insertion
} catch (error) {
if (
error.name === "SequelizeDatabaseError" &&
error.original.code === "SQLITE_ERROR" &&
error.original.errno === 1
) {
// Table doesn't exist, wait and retry
await new Promise((resolve) => setTimeout(resolve, retryDelay));
} else {
throw error; // Rethrow other errors
}
}
}
throw new Error("Table creation timed out.");
}
async function checkSupernodeList() {
try {
// Ensure the table is created
await SupernodeList.sync();
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return;
}
const [
masternodeListFull,
masternodeListRank,
masternodeListPubkey,
masternodeListExtra,
] = await Promise.all([
rpc_connection.masternodelist("full"),
rpc_connection.masternodelist("rank"),
rpc_connection.masternodelist("pubkey"),
rpc_connection.masternodelist("extra"),
]);
const masternodeListFullData = Object.entries(masternodeListFull).map(
([txidVout, data]) => {
const splitData = data?.trim()?.split(/\s+/);
return {
txid_vout: txidVout,
supernode_status: splitData[0],
protocol_version: Number(splitData[1]),
supernode_psl_address: splitData[2],
lastseentime: Number(splitData[3]),
activeseconds: Number(splitData[4]),
lastpaidtime: Number(splitData[5]),
lastpaidblock: Number(splitData[6]),
ipaddress_port: splitData[7],
};
}
);
const masternodeListFullDF = masternodeListFullData.map((data) => {
const rank = masternodeListRank[data.txid_vout];
const pubkey = masternodeListPubkey[data.txid_vout];
const extra = masternodeListExtra[data.txid_vout] || {};
return {
...data,
rank: Number(rank),
pubkey,
extAddress: extra.extAddress || "NA",
extP2P: extra.extP2P || "NA",
extKey: extra.extKey || "NA", // Fill missing extKey with "NA"
activedays: data.activeseconds / 86400,
};
});
const validMasternodeListFullDF = masternodeListFullDF.filter(
(data) =>
["ENABLED", "PRE_ENABLED"].includes(data.supernode_status) &&
data["ipaddress_port"] !== "154.38.164.75:29933" &&
data.extP2P
);
if (validMasternodeListFullDF.length === 0) {
logger.error("No valid masternodes found.");
return;
}
const validationSchema = Joi.array().items(supernodeListSchema);
const validation = validationSchema.validate(validMasternodeListFullDF);
if (validation.error) {
throw new Error(`Validation error: ${validation.error.message}`);
}
// Wait for the table to be created before inserting data
await waitForTableCreation();
try {
const _ = await SupernodeList.bulkCreate(validMasternodeListFullDF, {
updateOnDuplicate: [
"supernode_status",
"protocol_version",
"supernode_psl_address",
"lastseentime",
"activeseconds",
"lastpaidtime",
"lastpaidblock",
"ipaddress_port",
"rank",
"pubkey",
"extAddress",
"extP2P",
"extKey",
],
});
} catch (error) {
logger.error("Failed to insert data:", error);
}
const masternodeListFullDFJSON = JSON.stringify(
Object.fromEntries(
validMasternodeListFullDF.map((data) => [data.txid_vout, data])
)
);
return { validMasternodeListFullDF, masternodeListFullDFJSON };
} catch (error) {
logger.error(`An error occurred: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
}
}
async function registerPastelID(pastelid, passphrase, address) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return;
}
const result = await rpc_connection.tickets(
"register",
"id",
pastelid,
passphrase,
address
);
logger.info(`Registered PastelID: ${pastelid}. TXID: ${result}`);
return result;
} catch (error) {
logger.error(
`Error registering PastelID: ${pastelid}. Error:`,
safeStringify(error)
);
throw error;
}
}
async function listPastelIDTickets(filter = "mine", minheight = null) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return;
}
if (filter !== "mine") {
const params = [filter];
if (minheight !== null) {
params.push(minheight);
}
const result = await rpc_connection.tickets("list", "id", ...params);
return result;
}
// If filter is "mine", combine results from `pastelid list` and `tickets find id <PastelID>`
const pastelIDs = await rpc_connection.pastelid("list");
const registeredTickets = [];
for (const pastelIDObj of pastelIDs) {
const pastelID = pastelIDObj.PastelID;
try {
const ticket = await rpc_connection.tickets("find", "id", pastelID);
if (ticket && ticket.ticket) {
if (minheight === null || ticket.height >= minheight) {
registeredTickets.push(ticket);
}
}
} catch (error) {
// Handle the case where the PastelID is not registered
if (error.message.includes("ticket not found")) {
continue;
} else {
throw error;
}
}
}
logger.info(`Listed registered PastelID tickets with filter: ${filter}`);
return registeredTickets;
} catch (error) {
logger.error(
`Error listing PastelID tickets with filter: ${filter}. Error:`,
safeStringify(error)
);
throw error;
}
}
async function listPastelIDTicketsOld(filter = "mine", minheight = null) {
try {
const isConnectionReady = await waitForRPCConnection();
if (!isConnectionReady) {
logger.error("RPC connection is not available. Cannot proceed.");
return;
}
const params = [filter];
if (minheight !== null) {