-
Notifications
You must be signed in to change notification settings - Fork 0
/
single_file_pastel_inference_client.txt
12928 lines (11839 loc) · 445 KB
/
single_file_pastel_inference_client.txt
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
./create_promotional_packs.js
---
const fs = require('fs');
const path = require('path');
const {
createAndRegisterNewPastelID,
getLocalRPCSettings,
initializeRPCConnection,
dumpPrivKey,
getPastelIDDirectory,
getCurrentPastelBlockHeight,
isPastelIDRegistered,
isCreditPackConfirmed,
getTransactionDetails,
checkSupernodeList,
filterSupernodes
} = require('./rpc_functions');
const { handleCreditPackTicketEndToEnd } = require('./end_to_end_functions');
const { logger, safeStringify } = require('./logger');
const axios = require('axios');
const { promisify } = require('util');
const sleep = promisify(setTimeout);
const CONFIRMATION_BLOCKS = 1;
const MAX_WAIT_TIME = 900000; // 15 minutes
const CONCURRENT_CREDIT_PACK_CREATIONS = 3;
const INTERMEDIATE_PROMO_PACK_RESULTS_FILE = 'intermediate_promo_pack_results.json';
const TIMEOUT_PERIOD = 5000; // 5 seconds timeout
const MINIMUM_RESPONSE_SIZE = 1024; // 1 KB minimum response size
async function checkSupernodeResponsiveness(supernodeURL) {
const startTime = Date.now();
try {
const response = await axios.get(`${supernodeURL}/get_inference_model_menu`, {
timeout: TIMEOUT_PERIOD,
});
const responseTime = Date.now() - startTime;
if (response.status === 200 && JSON.stringify(response.data).length >= MINIMUM_RESPONSE_SIZE) {
return { url: supernodeURL, responseTime };
}
} catch (error) {
logger.debug(`Error checking supernode ${supernodeURL}: ${error.message}`);
}
return null;
}
async function selectResponsiveSupernodes(count = 12) {
try {
const { validMasternodeListFullDF } = await checkSupernodeList();
const filteredSupernodes = await filterSupernodes(validMasternodeListFullDF);
const checkPromises = filteredSupernodes.map(supernode =>
checkSupernodeResponsiveness(supernode.url)
);
const results = await Promise.allSettled(checkPromises);
const validResponses = results
.filter(res => res.status === 'fulfilled' && res.value !== null)
.map(res => res.value);
const sortedResponses = validResponses.sort((a, b) => a.responseTime - b.responseTime);
return sortedResponses.slice(0, count);
} catch (error) {
logger.error(`Failed to select responsive supernodes: ${error.message}`);
throw error;
}
}
function loadIntermediateResults() {
try {
if (fs.existsSync(INTERMEDIATE_PROMO_PACK_RESULTS_FILE)) {
return JSON.parse(fs.readFileSync(INTERMEDIATE_PROMO_PACK_RESULTS_FILE, 'utf8'));
}
} catch (error) {
logger.error(`Error loading intermediate results: ${error.message}`);
}
return { registeredPastelIDs: [], completedPacks: [], pendingCreditPacks: [] };
}
function saveIntermediateResults(results) {
try {
fs.writeFileSync(INTERMEDIATE_PROMO_PACK_RESULTS_FILE, JSON.stringify(results, null, 2));
} catch (error) {
logger.error(`Error saving intermediate results: ${error.message}`);
}
}
async function waitForConfirmation(checkFunction, ...args) {
const startTime = Date.now();
logger.info(`Starting confirmation wait for ${checkFunction.name} with args: ${safeStringify(args)}`);
while (Date.now() - startTime < MAX_WAIT_TIME) {
if (await checkFunction(...args)) {
logger.info(`Confirmation successful for ${checkFunction.name}`);
return true;
}
logger.debug(`Waiting for confirmation of ${checkFunction.name}. Elapsed time: ${(Date.now() - startTime) / 1000} seconds`);
await new Promise(resolve => setTimeout(resolve, 10000));
}
logger.error(`Confirmation timed out for ${checkFunction.name} after ${MAX_WAIT_TIME / 1000} seconds`);
throw new Error('Confirmation timed out');
}
async function createPastelIDs(count) {
logger.info(`Starting creation of ${count} PastelIDs...`);
const intermediateResults = loadIntermediateResults();
const pastelIDs = [...intermediateResults.registeredPastelIDs];
logger.info(`Loaded ${pastelIDs.length} existing PastelIDs from intermediate results`);
for (let i = pastelIDs.length; i < count; i++) {
const passphrase = `testpass`;
logger.info(`Attempting to create PastelID ${i + 1}/${count} with passphrase: ${passphrase}`);
try {
logger.debug(`Initiating PastelID creation request for attempt ${i + 1}/${count}`);
const result = await createAndRegisterNewPastelID(passphrase);
if (result.success) {
const newPastelID = { pastelID: result.PastelID, passphrase };
pastelIDs.push(newPastelID);
intermediateResults.registeredPastelIDs.push(newPastelID);
saveIntermediateResults(intermediateResults);
logger.info(`Successfully created and registered PastelID ${i + 1}/${count}: ${result.PastelID}`);
logger.debug(`Updated intermediate results with new PastelID: ${result.PastelID}`);
} else {
logger.error(`Failed to create PastelID ${i + 1}/${count}: ${result.message}`);
logger.debug(`Detailed error for PastelID creation attempt ${i + 1}/${count}: ${JSON.stringify(result)}`);
}
// Sleep for 2 seconds before creating a new PastelID
await sleep(2000);
} catch (error) {
logger.error(`Unexpected error during PastelID creation attempt ${i + 1}/${count}: ${error.message}`);
logger.debug(`Stack trace: ${error.stack}`);
}
// Log progress after each attempt
logger.info(`Progress: ${pastelIDs.length}/${count} PastelIDs created`);
}
logger.info(`Completed creation of PastelIDs. Total successful: ${pastelIDs.length}/${count}`);
logger.debug(`Final PastelID list: ${JSON.stringify(pastelIDs.map(p => p.pastelID))}`);
return pastelIDs;
}
async function waitForPastelIDRegistrations(pastelIDs) {
logger.info(`Starting to wait for ${pastelIDs.length} PastelID registrations...`);
const registrationPromises = pastelIDs.map(({ pastelID }) => {
logger.debug(`Waiting for registration of PastelID: ${pastelID}`);
return waitForConfirmation(isPastelIDRegistered, pastelID);
});
await Promise.all(registrationPromises);
logger.info('All PastelIDs confirmed in blockchain');
}
async function createCreditPack(pastelID, passphrase, creditsPerPack) {
const maximumTotalCreditPackPriceInPSL = 1000000;
const maximumPerCreditPriceInPSL = 2000;
logger.info(`Starting credit pack creation for PastelID: ${pastelID} with ${creditsPerPack} credits`);
const responsiveSupernodes = await selectResponsiveSupernodes(5); // Select top 5 responsive supernodes
for (const supernode of responsiveSupernodes) {
try {
const creditPackResult = await handleCreditPackTicketEndToEnd(
creditsPerPack,
null,
'PtpasteLBurnAddressXXXXXXXXXXbJ5ndd',
maximumTotalCreditPackPriceInPSL,
maximumPerCreditPriceInPSL,
supernode.url
);
if (!creditPackResult || !creditPackResult.txid) {
throw new Error('Failed to create credit pack ticket');
}
logger.info(`Credit pack ticket created. TXID: ${creditPackResult.txid}`);
await waitForConfirmation(isCreditPackConfirmed, creditPackResult.txid);
logger.info(`Credit pack ticket ${creditPackResult.txid} confirmed in blockchain`);
const trackingAddressPrivateKey = await dumpPrivKey(creditPackResult.trackingAddress);
logger.info(`Private key retrieved successfully for tracking address: ${creditPackResult.trackingAddress}`);
const { rpcport } = await getLocalRPCSettings();
const network = rpcport === '9932' ? 'mainnet' : rpcport === '19932' ? 'testnet' : 'devnet';
logger.debug(`Determined network: ${network}`);
const pastelIDDir = getPastelIDDirectory(network);
const secureContainerPath = path.join(pastelIDDir, pastelID);
logger.debug(`Reading secure container file from: ${secureContainerPath}`);
const secureContainerContent = fs.readFileSync(secureContainerPath, 'base64');
logger.info(`Secure container file retrieved successfully for PastelID: ${pastelID}`);
logger.info(`Completed credit pack creation for PastelID: ${pastelID}`);
return {
pastelID,
passphrase,
secureContainer: secureContainerContent,
creditPackTicket: creditPackResult,
trackingAddress: {
address: creditPackResult.trackingAddress,
privateKey: trackingAddressPrivateKey
},
fundingTxid: creditPackResult.txid
};
} catch (error) {
logger.error(`Error creating credit pack with supernode ${supernode.url}: ${error.message}`);
}
}
throw new Error(`Failed to create credit pack for PastelID: ${pastelID} after trying all responsive supernodes`);
}
async function createPromotionalPacks(count, creditsPerPack) {
logger.info(`Starting generation of ${count} promotional packs with ${creditsPerPack} credits each`);
await initializeRPCConnection();
logger.info('RPC connection initialized successfully');
const intermediateResults = loadIntermediateResults();
let pastelIDs = intermediateResults.registeredPastelIDs;
if (pastelIDs.length < count) {
pastelIDs = await createPastelIDs(count);
}
logger.info(`Created ${pastelIDs.length} PastelIDs successfully`);
logger.info('Waiting for all PastelID registrations to be confirmed...');
await waitForPastelIDRegistrations(pastelIDs);
logger.info(`Starting credit pack creation for ${pastelIDs.length} PastelIDs`);
const promotionalPacks = [...intermediateResults.completedPacks];
const pendingCreditPacks = [...intermediateResults.pendingCreditPacks];
// First, try to complete any pending credit packs
for (const pendingPack of pendingCreditPacks) {
try {
const completedPack = await createCreditPack(pendingPack.pastelID, pendingPack.passphrase, creditsPerPack);
promotionalPacks.push(completedPack);
intermediateResults.completedPacks.push(completedPack);
intermediateResults.pendingCreditPacks = intermediateResults.pendingCreditPacks.filter(
pack => pack.pastelID !== pendingPack.pastelID
);
saveIntermediateResults(intermediateResults);
} catch (error) {
logger.error(`Failed to complete pending credit pack for PastelID ${pendingPack.pastelID}: ${error.message}`);
}
}
// Then, create new credit packs for remaining PastelIDs
const remainingPastelIDs = pastelIDs.filter(
pastelID => !promotionalPacks.some(pack => pack.pastelID === pastelID.pastelID) &&
!pendingCreditPacks.some(pack => pack.pastelID === pastelID.pastelID)
);
for (let i = 0; i < remainingPastelIDs.length; i += CONCURRENT_CREDIT_PACK_CREATIONS) {
const batch = remainingPastelIDs.slice(i, i + CONCURRENT_CREDIT_PACK_CREATIONS);
logger.info(`Processing batch ${Math.floor(i / CONCURRENT_CREDIT_PACK_CREATIONS) + 1}: Creating ${batch.length} credit packs concurrently`);
const batchPromises = batch.map(({ pastelID, passphrase }) =>
createCreditPack(pastelID, passphrase, creditsPerPack)
);
const batchResults = await Promise.allSettled(batchPromises);
batchResults.forEach((result, index) => {
if (result.status === 'fulfilled') {
promotionalPacks.push(result.value);
intermediateResults.completedPacks.push(result.value);
intermediateResults.registeredPastelIDs = intermediateResults.registeredPastelIDs.filter(
id => id.pastelID !== result.value.pastelID
);
} else {
logger.error(`Failed to create credit pack for PastelID ${batch[index].pastelID}: ${result.reason}`);
intermediateResults.pendingCreditPacks.push(batch[index]);
}
saveIntermediateResults(intermediateResults);
});
logger.info(`Completed batch ${Math.floor(i / CONCURRENT_CREDIT_PACK_CREATIONS) + 1}. Total packs created: ${promotionalPacks.length}`);
}
logger.info(`Completed creation of all ${promotionalPacks.length} promotional packs`);
return promotionalPacks;
}
async function generatePromotionalPacks(numberOfPacks, creditsPerPack) {
logger.info(`Starting generation of ${numberOfPacks} promotional packs with ${creditsPerPack} credits each`);
const folderPath = path.join(__dirname, 'generated_promo_packs');
if (!fs.existsSync(folderPath)) {
logger.info(`Creating folder for promotional packs: ${folderPath}`);
fs.mkdirSync(folderPath);
}
logger.info('Initiating creation of promotional packs...');
const promotionalPacks = await createPromotionalPacks(numberOfPacks, creditsPerPack);
const serializedPacks = JSON.stringify(promotionalPacks, null, 2);
const fileName = path.join(folderPath, `promotional_packs_${Date.now()}.json`);
logger.info(`Saving ${promotionalPacks.length} promotional packs to file: ${fileName}`);
fs.writeFileSync(fileName, serializedPacks);
logger.info(`Successfully saved promotional packs to file`);
// Update intermediate results to remove completed packs
const intermediateResults = loadIntermediateResults();
intermediateResults.completedPacks = intermediateResults.completedPacks.filter(
pack => !promotionalPacks.some(p => p.pastelID === pack.pastelID)
);
saveIntermediateResults(intermediateResults);
logger.info(`Generation complete. ${promotionalPacks.length} promotional packs created and saved to ${fileName}`);
return { fileName, packCount: promotionalPacks.length };
}
module.exports = { generatePromotionalPacks };
---
./end_to_end_functions.js
---
// end_to_end_functions.js
require("dotenv").config();
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const {
UserMessage,
CreditPackPurchaseRequest,
CreditPackPurchaseRequestResponseTermination,
CreditPackPurchaseRequestResponse,
CreditPackPurchaseRequestConfirmation,
CreditPackPurchaseRequestConfirmationResponse,
CreditPackStorageRetryRequest,
InferenceAPIUsageRequest,
InferenceConfirmation,
} = require("./sequelize_data_models");
const {
userMessageSchema,
creditPackPurchaseRequestResponseSchema,
creditPackPurchaseRequestConfirmationSchema,
creditPackPurchaseRequestConfirmationResponseSchema,
creditPackPurchaseRequestStatusSchema,
creditPackStorageRetryRequestSchema,
creditPackStorageRetryRequestResponseSchema,
inferenceAPIUsageRequestSchema,
inferenceAPIUsageResponseSchema,
inferenceAPIOutputResultSchema,
inferenceConfirmationSchema,
} = require("./validation_schemas");
const { logger, safeStringify } = require("./logger");
const {
signMessageWithPastelID,
checkSupernodeList,
getCurrentPastelBlockHeight,
sendToAddress,
sendTrackingAmountFromControlAddressToBurnAddressToConfirmInferenceRequest,
checkPSLAddressBalanceAlternative,
} = require("./rpc_functions");
const { PastelInferenceClient } = require("./pastel_inference_client");
const {
prettyJSON,
filterSupernodes,
getNClosestSupernodesToPastelIDURLs,
validateCreditPackTicketMessageData,
validateInferenceData,
computeSHA3256HashOfSQLModelResponseFields,
checkIfPastelIDIsValid,
getSupernodeUrlFromPastelID,
getClosestSupernodePastelIDFromList,
getClosestSupernodeToPastelIDURL,
} = require("./utility_functions");
const globals = require("./globals");
async function checkForNewIncomingMessages() {
try {
const pastelID = globals.getPastelId();
const passphrase = globals.getPassphrase();
const inferenceClient = new PastelInferenceClient(pastelID, passphrase);
if (!pastelID || !passphrase) {
logger.error("PastelID or passphrase is not set");
return [];
}
const { validMasternodeListFullDF } = await checkSupernodeList();
logger.info("Retrieving incoming user messages...");
logger.info(`My local pastelid: ${inferenceClient.pastelID}`);
const closestSupernodesToLocal = await getNClosestSupernodesToPastelIDURLs(
3,
inferenceClient.pastelID,
validMasternodeListFullDF
);
logger.info(
`Closest Supernodes to local pastelid: ${closestSupernodesToLocal
.map((sn) => `PastelID: ${sn.pastelID}, URL: ${sn.url}`)
.join(", ")}`
);
const messageRetrievalTasks = closestSupernodesToLocal.map(({ url }) =>
inferenceClient.getUserMessages(url).catch((error) => {
logger.warn(
`Failed to retrieve messages from supernode ${url}: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
return []; // Return an empty array on error
})
);
const messageLists = await Promise.all(messageRetrievalTasks);
const uniqueMessages = [];
const messageIDs = new Set();
for (const messageList of messageLists) {
for (const message of messageList) {
if (!messageIDs.has(message.id)) {
uniqueMessages.push(message);
messageIDs.add(message.id);
}
}
}
logger.info(
`Retrieved unique user messages: ${safeStringify(uniqueMessages)}`
);
return uniqueMessages;
} catch (error) {
logger.error(`Error in checkForNewIncomingMessages: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
throw error;
}
}
async function sendMessageAndCheckForNewIncomingMessages(
toPastelID,
messageBody
) {
try {
const pastelID = globals.getPastelId();
const passphrase = globals.getPassphrase();
const inferenceClient = new PastelInferenceClient(pastelID, passphrase);
const { validMasternodeListFullDF } = await checkSupernodeList();
if (!pastelID || !passphrase) {
throw new Error("PastelID or passphrase is not set");
}
logger.info("Sending user message...");
logger.info(`Recipient pastelid: ${toPastelID}`);
const closestSupernodesToRecipient =
await getNClosestSupernodesToPastelIDURLs(
3,
toPastelID,
validMasternodeListFullDF
);
logger.info(
`Closest Supernodes to recipient pastelid: ${closestSupernodesToRecipient.map(
(sn) => sn.pastelID
)}`
);
const userMessage = UserMessage.build({
from_pastelid: pastelID,
to_pastelid: toPastelID,
message_body: safeStringify(messageBody),
message_signature: await signMessageWithPastelID(
pastelID,
messageBody,
passphrase
),
});
const { error } = userMessageSchema.validate(userMessage.toJSON());
if (error) {
throw new Error(`Invalid user message: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
}
const sendTasks = closestSupernodesToRecipient.map(({ url }) =>
inferenceClient.sendUserMessage(url, userMessage)
);
const sendResults = await Promise.all(sendTasks);
logger.info(`Sent user messages: ${safeStringify(sendResults)}`);
const receivedMessages = await checkForNewIncomingMessages();
const messageDict = {
sent_messages: sendResults,
received_messages: receivedMessages,
};
return messageDict;
} catch (error) {
logger.error(
`Error in sendMessageAndCheckForNewIncomingMessages: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
throw error;
}
}
function getIsoStringWithMicroseconds() {
const now = new Date();
const isoString = now.toISOString().replace("Z", "+00:00").replace(/\s/g, "");
return isoString;
}
async function handleCreditPackTicketEndToEnd(
numberOfCredits,
creditUsageTrackingPSLAddress,
burnAddress,
maximumTotalCreditPackPriceInPSL,
maximumPerCreditPriceInPSL
) {
const pastelID = globals.getPastelId();
const passphrase = globals.getPassphrase();
if (!pastelID || !passphrase) {
throw new Error("PastelID or passphrase is not set");
}
const inferenceClient = new PastelInferenceClient(pastelID, passphrase);
const { validMasternodeListFullDF } = await checkSupernodeList();
const requestTimestamp = getIsoStringWithMicroseconds();
const creditPackRequest = CreditPackPurchaseRequest.build({
requesting_end_user_pastelid: pastelID,
requested_initial_credits_in_credit_pack: parseInt(numberOfCredits, 10),
list_of_authorized_pastelids_allowed_to_use_credit_pack: JSON.stringify([pastelID]),
credit_usage_tracking_psl_address: creditUsageTrackingPSLAddress,
request_timestamp_utc_iso_string: requestTimestamp,
request_pastel_block_height: parseInt(await getCurrentPastelBlockHeight(), 10),
credit_purchase_request_message_version_string: "1.0",
sha3_256_hash_of_credit_pack_purchase_request_fields: "",
requesting_end_user_pastelid_signature_on_request_hash: "",
});
creditPackRequest.sha3_256_hash_of_credit_pack_purchase_request_fields =
await computeSHA3256HashOfSQLModelResponseFields(creditPackRequest);
creditPackRequest.requesting_end_user_pastelid_signature_on_request_hash =
await signMessageWithPastelID(
pastelID,
creditPackRequest.sha3_256_hash_of_credit_pack_purchase_request_fields,
passphrase
);
const closestSupernodes = await getNClosestSupernodesToPastelIDURLs(12, pastelID, validMasternodeListFullDF);
if (closestSupernodes.length === 0) {
throw new Error("No responsive supernodes found.");
}
const randomIndex = Math.floor(Math.random() * closestSupernodes.length);
const selectedSupernode = closestSupernodes[randomIndex];
const highestRankedSupernodeURL = selectedSupernode.url;
logger.info(`Selected supernode URL for credit pack request: ${highestRankedSupernodeURL}`);
try {
const preliminaryPriceQuote = await inferenceClient.creditPackTicketInitialPurchaseRequest(
highestRankedSupernodeURL,
creditPackRequest
);
const signedCreditPackTicketOrRejection = await inferenceClient.creditPackTicketPreliminaryPriceQuoteResponse(
highestRankedSupernodeURL,
creditPackRequest,
preliminaryPriceQuote,
maximumTotalCreditPackPriceInPSL,
maximumPerCreditPriceInPSL
);
if (signedCreditPackTicketOrRejection instanceof CreditPackPurchaseRequestResponseTermination) {
logger.info(`Credit pack purchase request terminated: ${signedCreditPackTicketOrRejection.termination_reason_string}`);
return null;
}
const signedCreditPackTicket = signedCreditPackTicketOrRejection;
const burnTransactionResponse = await sendToAddress(
burnAddress,
Math.round(signedCreditPackTicket.proposed_total_cost_of_credit_pack_in_psl * 100000) / 100000,
"Burn transaction for credit pack ticket"
);
if (!burnTransactionResponse.success) {
throw new Error(`Error sending PSL to burn address: ${burnTransactionResponse.message}`);
}
const burnTransactionTxid = burnTransactionResponse.result;
const creditPackPurchaseRequestConfirmation = await buildCreditPackPurchaseRequestConfirmation(
creditPackRequest,
signedCreditPackTicket,
burnTransactionTxid,
pastelID,
passphrase
);
await CreditPackPurchaseRequestConfirmation.create(creditPackPurchaseRequestConfirmation.toJSON());
const creditPackPurchaseRequestConfirmationResponse = await inferenceClient.confirmCreditPurchaseRequest(
highestRankedSupernodeURL,
creditPackPurchaseRequestConfirmation
);
if (!creditPackPurchaseRequestConfirmationResponse) {
throw new Error("Credit pack ticket storage failed");
}
let creditPackPurchaseRequestStatus = await checkCreditPackPurchaseRequestStatus(
inferenceClient,
highestRankedSupernodeURL,
creditPackRequest,
closestSupernodes
);
if (creditPackPurchaseRequestStatus.status !== "completed") {
const creditPackStorageRetryRequestResponse = await initiateStorageRetry(
inferenceClient,
creditPackRequest,
signedCreditPackTicket,
validMasternodeListFullDF,
pastelID,
passphrase
);
return creditPackStorageRetryRequestResponse;
} else {
return creditPackPurchaseRequestConfirmationResponse;
}
} catch (error) {
logger.error(`Error in handleCreditPackTicketEndToEnd: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
throw new Error("An unexpected error occurred while processing your credit pack purchase. Please try again later.");
}
}
async function buildCreditPackPurchaseRequestConfirmation(creditPackRequest, signedCreditPackTicket, burnTransactionTxid, pastelID, passphrase) {
const confirmation = CreditPackPurchaseRequestConfirmation.build({
sha3_256_hash_of_credit_pack_purchase_request_fields:
creditPackRequest.sha3_256_hash_of_credit_pack_purchase_request_fields,
sha3_256_hash_of_credit_pack_purchase_request_response_fields:
signedCreditPackTicket.sha3_256_hash_of_credit_pack_purchase_request_response_fields,
credit_pack_purchase_request_fields_json_b64:
signedCreditPackTicket.credit_pack_purchase_request_fields_json_b64,
requesting_end_user_pastelid: pastelID,
txid_of_credit_purchase_burn_transaction: burnTransactionTxid,
credit_purchase_request_confirmation_utc_iso_string: new Date().toISOString(),
credit_purchase_request_confirmation_pastel_block_height: await getCurrentPastelBlockHeight(),
credit_purchase_request_confirmation_message_version_string: "1.0",
sha3_256_hash_of_credit_pack_purchase_request_confirmation_fields: "",
requesting_end_user_pastelid_signature_on_sha3_256_hash_of_credit_pack_purchase_request_confirmation_fields: "",
});
confirmation.sha3_256_hash_of_credit_pack_purchase_request_confirmation_fields =
await computeSHA3256HashOfSQLModelResponseFields(confirmation);
confirmation.requesting_end_user_pastelid_signature_on_sha3_256_hash_of_credit_pack_purchase_request_confirmation_fields =
await signMessageWithPastelID(
pastelID,
confirmation.sha3_256_hash_of_credit_pack_purchase_request_confirmation_fields,
passphrase
);
const { error: confirmationValidationError } = creditPackPurchaseRequestConfirmationSchema.validate(confirmation.toJSON());
if (confirmationValidationError) {
throw new Error(`Invalid credit pack purchase request confirmation: ${confirmationValidationError.message}`);
}
return confirmation;
}
async function checkCreditPackPurchaseRequestStatus(inferenceClient, highestRankedSupernodeURL, creditPackRequest, closestSupernodes) {
try {
const status = await inferenceClient.checkStatusOfCreditPurchaseRequest(
highestRankedSupernodeURL,
creditPackRequest.sha3_256_hash_of_credit_pack_purchase_request_fields
);
logger.info(`Credit pack purchase request status from the original supernode: ${JSON.stringify(status)}`);
return status;
} catch (error) {
logger.debug(`Error checking status with original supernode: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}. Trying other supernodes.`);
for (const supernode of closestSupernodes) {
try {
const status = await inferenceClient.checkStatusOfCreditPurchaseRequest(
supernode.url,
creditPackRequest.sha3_256_hash_of_credit_pack_purchase_request_fields
);
logger.info(`Credit pack purchase request status: ${JSON.stringify(status)}`);
return status;
} catch (retryError) {
logger.debug(`Error checking status with supernode ${supernode.url}: ${retryError.message}`);
}
}
throw new Error("Failed to check status of credit purchase request with all Supernodes");
}
}
async function initiateStorageRetry(inferenceClient, creditPackRequest, signedCreditPackTicket, validMasternodeListFullDF, pastelID, passphrase) {
const closestAgreeingSupernodePastelID = await getClosestSupernodePastelIDFromList(
pastelID,
signedCreditPackTicket.list_of_supernode_pastelids_agreeing_to_credit_pack_purchase_terms
);
const creditPackStorageRetryRequest = await buildCreditPackStorageRetryRequest(
creditPackRequest,
signedCreditPackTicket,
closestAgreeingSupernodePastelID,
pastelID,
passphrase
);
await CreditPackStorageRetryRequest.create(creditPackStorageRetryRequest.toJSON());
const closestAgreeingSupernodeURL = await getSupernodeUrlFromPastelID(
closestAgreeingSupernodePastelID,
validMasternodeListFullDF
);
const creditPackStorageRetryRequestResponse = await inferenceClient.creditPackStorageRetryRequest(
closestAgreeingSupernodeURL,
creditPackStorageRetryRequest
);
const { error: storageRetryResponseValidationError } = creditPackStorageRetryRequestResponseSchema.validate(
creditPackStorageRetryRequestResponse.toJSON()
);
if (storageRetryResponseValidationError) {
throw new Error(`Invalid credit pack storage retry request response: ${storageRetryResponseValidationError.message}`);
}
// Silently attempt to announce completion to all agreeing supernodes
const announcementPromises = signedCreditPackTicket.list_of_supernode_pastelids_agreeing_to_credit_pack_purchase_terms.map(
async (supernodePastelID) => {
if (checkIfPastelIDIsValid(supernodePastelID)) {
try {
const supernodeURL = await getSupernodeUrlFromPastelID(supernodePastelID, validMasternodeListFullDF);
await inferenceClient.creditPackPurchaseCompletionAnnouncement(
supernodeURL,
creditPackStorageRetryRequestResponse
);
} catch (error) {
// Silently ignore errors in completion announcements
}
}
}
);
await Promise.allSettled(announcementPromises);
return creditPackStorageRetryRequestResponse;
}
async function buildCreditPackStorageRetryRequest(creditPackRequest, signedCreditPackTicket, closestAgreeingSupernodePastelID, pastelID, passphrase) {
const storageRetryRequest = CreditPackStorageRetryRequest.build({
sha3_256_hash_of_credit_pack_purchase_request_response_fields:
signedCreditPackTicket.sha3_256_hash_of_credit_pack_purchase_request_response_fields,
credit_pack_purchase_request_fields_json_b64:
signedCreditPackTicket.credit_pack_purchase_request_fields_json_b64,
requesting_end_user_pastelid: pastelID,
closest_agreeing_supernode_to_retry_storage_pastelid: closestAgreeingSupernodePastelID,
credit_pack_storage_retry_request_timestamp_utc_iso_string: new Date().toISOString(),
credit_pack_storage_retry_request_pastel_block_height: await getCurrentPastelBlockHeight(),
credit_pack_storage_retry_request_message_version_string: "1.0",
sha3_256_hash_of_credit_pack_storage_retry_request_fields: "",
requesting_end_user_pastelid_signature_on_credit_pack_storage_retry_request_hash: "",
});
storageRetryRequest.sha3_256_hash_of_credit_pack_storage_retry_request_fields =
await computeSHA3256HashOfSQLModelResponseFields(storageRetryRequest);
storageRetryRequest.requesting_end_user_pastelid_signature_on_credit_pack_storage_retry_request_hash =
await signMessageWithPastelID(
pastelID,
storageRetryRequest.sha3_256_hash_of_credit_pack_storage_retry_request_fields,
passphrase
);
const { error: storageRetryRequestValidationError } = creditPackStorageRetryRequestSchema.validate(storageRetryRequest.toJSON());
if (storageRetryRequestValidationError) {
throw new Error(`Invalid credit pack storage retry request: ${storageRetryRequestValidationError.message}`);
}
return storageRetryRequest;
}
async function getCreditPackTicketInfoEndToEnd(creditPackTicketPastelTxid) {
try {
const pastelID = globals.getPastelId();
const passphrase = globals.getPassphrase();
if (!pastelID || !passphrase) {
throw new Error("PastelID or passphrase is not set");
}
const inferenceClient = new PastelInferenceClient(pastelID, passphrase);
const { validMasternodeListFullDF } = await checkSupernodeList();
const { url: supernodeURL } = await getClosestSupernodeToPastelIDURL(
pastelID,
validMasternodeListFullDF
);
if (!supernodeURL) {
throw new Error("Supernode URL is undefined");
}
logger.info(
`Getting credit pack ticket data from Supernode URL: ${supernodeURL}...`
);
const {
creditPackPurchaseRequestResponse,
creditPackPurchaseRequestConfirmation,
} = await inferenceClient.getCreditPackTicketFromTxid(
supernodeURL,
creditPackTicketPastelTxid
);
const balanceInfo = await inferenceClient.checkCreditPackBalance(
supernodeURL,
creditPackTicketPastelTxid
);
return {
requestResponse: creditPackPurchaseRequestResponse,
requestConfirmation: creditPackPurchaseRequestConfirmation,
balanceInfo,
};
} catch (error) {
logger.error(`Error in getCreditPackTicketInfoEndToEnd: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
throw error;
}
}
async function getMyValidCreditPackTicketsEndToEnd() {
const initialMinimumNonEmptyResponses = 5;
const maxTotalResponsesIfAllEmpty = 20;
const retryLimit = 1;
try {
const pastelID = globals.getPastelId();
const passphrase = globals.getPassphrase();
if (!pastelID || !passphrase) {
throw new Error("PastelID or passphrase is not set");
}
const inferenceClient = new PastelInferenceClient(pastelID, passphrase);
const { validMasternodeListFullDF } = await checkSupernodeList();
const closestSupernodes = await getNClosestSupernodesToPastelIDURLs(
120,
pastelID,
validMasternodeListFullDF
);
let allResponses = [];
let nonEmptyResponses = [];
let isResolved = false;
await new Promise((resolve, reject) => {
let completedRequests = 0;
const handleResponse = () => {
if (isResolved) return;
if (nonEmptyResponses.length >= initialMinimumNonEmptyResponses) {
logger.info(
`Received ${nonEmptyResponses.length} non-empty responses out of ${allResponses.length} total responses`
);
isResolved = true;
resolve();
} else if (allResponses.length >= maxTotalResponsesIfAllEmpty) {
logger.info(
`Reached maximum total responses (${maxTotalResponsesIfAllEmpty}) with ${nonEmptyResponses.length} non-empty responses`
);
isResolved = true;
resolve();
} else if (completedRequests >= closestSupernodes.length) {
logger.warn(
`Queried all available supernodes. Got ${nonEmptyResponses.length} non-empty responses out of ${allResponses.length} total responses`
);
isResolved = true;
resolve();
}
};
closestSupernodes.forEach(({ url }) => {
if (isResolved) return;
retryPromise(
() => inferenceClient.getValidCreditPackTicketsForPastelID(url),
retryLimit
)
.then((response) => {
if (isResolved) return;
logger.info(
`Response received from supernode at ${url}; response length: ${response.length}`
);
allResponses.push({ response, url });
if (response.length > 0) {
nonEmptyResponses.push({ response, url });
}
completedRequests++;
handleResponse();
})
.catch((error) => {
if (isResolved) return;
logger.error(
`Error querying supernode at ${url}: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
completedRequests++;
handleResponse();
});
});
});
if (nonEmptyResponses.length > 0) {
// Return the longest non-empty response
const longestResponse = nonEmptyResponses.reduce((prev, current) => {
return current.response.length > prev.response.length ? current : prev;
}).response;
logger.info(
`Returning longest non-empty response with length: ${longestResponse.length}`
);
return longestResponse;
} else {
logger.info("All responses were empty. Returning empty list.");
return [];
}
} catch (error) {
logger.error(
`Error in getMyValidCreditPackTicketsEndToEnd: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
return [];
}
}
async function retryPromise(promiseFunc, limit, count = 0) {
try {
return await promiseFunc();
} catch (error) {
if (count < limit) {
return retryPromise(promiseFunc, limit, count + 1);
} else {
throw error;
}
}
}
async function estimateCreditPackCostEndToEnd(
desiredNumberOfCredits,
creditPriceCushionPercentage
) {
try {
const pastelID = globals.getPastelId();
const passphrase = globals.getPassphrase();
if (!pastelID || !passphrase) {
throw new Error("PastelID or passphrase is not set");
}
const inferenceClient = new PastelInferenceClient(pastelID, passphrase);
const estimatedTotalCostOfTicket =
await inferenceClient.internalEstimateOfCreditPackTicketCostInPSL(
desiredNumberOfCredits,
creditPriceCushionPercentage
);
return estimatedTotalCostOfTicket;
} catch (error) {
logger.error(`Error in estimateCreditPackCostEndToEnd: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
throw error;
}
}
async function handleInferenceRequestEndToEnd(
creditPackTicketPastelTxid,
modelInputData,
requestedModelCanonicalString,
modelInferenceTypeString,
modelParameters,
maximumInferenceCostInCredits,
burnAddress
) {
try {
const pastelID = globals.getPastelId();
const passphrase = globals.getPassphrase();
if (!pastelID || !passphrase) {
throw new Error("PastelID or passphrase is not set");
}
const inferenceClient = new PastelInferenceClient(pastelID, passphrase);
const modelParametersJSON = safeStringify(modelParameters);
// Get the closest N supernode URLs that support the desired model, ordered by response time
const supernodeURLs = await inferenceClient.getClosestSupernodeURLsThatSupportsDesiredModel(
requestedModelCanonicalString,
modelInferenceTypeString,
modelParametersJSON,
12 // Limit to the closest 12 supernodes
);
if (!supernodeURLs || supernodeURLs.length === 0) {
logger.error(
`No supporting supernode found with adequate performance for the desired model: ${requestedModelCanonicalString} with inference type: ${modelInferenceTypeString}`
);
return null;
}
let inferenceResultDict = null;
let auditResults = null;