-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnamespaceWrapper.js
1116 lines (1050 loc) · 33.5 KB
/
namespaceWrapper.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
/**
* namespaceWrapper.js
* @description This file contains the namespace wrapper class
* which is used to interact with the namespace
* and the task node
*
* Note: Generally, it is not necessary to modify this file
*
* @version 1.0.0
*/
const { default: axios } = require('axios');
const { TASK_ID, SECRET_KEY, TASK_NODE_PORT } = require('./init');
const { Connection, PublicKey, Keypair } = require('@_koi/web3.js');
const Datastore = require('nedb-promises');
const { createHash } = require('crypto');
const semver = require('semver');
const taskNodeAdministered = !!TASK_ID;
const BASE_ROOT_URL = `http://localhost:${TASK_NODE_PORT}/namespace-wrapper`;
let connection;
class NamespaceWrapper {
#db;
#testingMainSystemAccount;
#testingStakingSystemAccount;
#testingTaskState;
#testingDistributionList;
constructor() {
if (taskNodeAdministered) {
this.initializeDB();
} else {
this.#db = Datastore.create('./localKOIIDB.db');
this.defaultTaskSetup();
}
}
async initializeDB() {
if (this.#db) return;
try {
if (taskNodeAdministered) {
const path = await this.getTaskLevelDBPath();
this.#db = Datastore.create(path);
} else {
this.#db = Datastore.create('./localKOIIDB.db');
}
} catch (e) {
this.#db = Datastore.create(`../namespace/${TASK_ID}/KOIILevelDB.db`);
}
}
async getDb() {
if (this.#db) return this.#db;
await this.initializeDB();
return this.#db;
}
/**
* Namespace wrapper of storeGetAsync
* @param {string} key // Path to get
*/
async storeGet(key) {
try {
await this.initializeDB();
const resp = await this.#db.findOne({ key: key });
if (resp) {
return resp[key];
} else {
return null;
}
} catch (e) {
console.error(e);
return null;
}
}
/**
* Namespace wrapper over storeSetAsync
* @param {string} key Path to set
* @param {*} value Data to set
*/
async storeSet(key, value) {
try {
await this.initializeDB();
await this.#db.update(
{ key: key },
{ [key]: value, key },
{ upsert: true },
);
} catch (e) {
console.error(e);
return undefined;
}
}
/**
* Namespace wrapper over fsPromises methods
* @param {*} method The fsPromise method to call
* @param {*} path Path for the express call
* @param {...any} args Remaining parameters for the FS call
*/
async fs(method, path, ...args) {
if (taskNodeAdministered) {
return await genericHandler('fs', method, path, ...args);
} else {
return fsPromises[method](`${path}`, ...args);
}
}
async fsStaking(method, path, ...args) {
if (taskNodeAdministered) {
return await genericHandler('fsStaking', method, path, ...args);
} else {
return fsPromises[method](`${path}`, ...args);
}
}
async fsWriteStream(imagepath) {
if (taskNodeAdministered) {
return await genericHandler('fsWriteStream', imagepath);
} else {
const writer = createWriteStream(imagepath);
return writer;
}
}
async fsReadStream(imagepath) {
if (taskNodeAdministered) {
return await genericHandler('fsReadStream', imagepath);
} else {
const file = readFileSync(imagepath);
return file;
}
}
/**
* Namespace wrapper for getting current slots
*/
async getSlot() {
if (taskNodeAdministered) {
return await genericHandler('getCurrentSlot');
} else {
return 100;
}
}
async payloadSigning(body) {
if (taskNodeAdministered) {
return await genericHandler('signData', body);
} else {
const msg = new TextEncoder().encode(JSON.stringify(body));
const signedMessage = nacl.sign(
msg,
this.#testingMainSystemAccount.secretKey,
);
return await this.bs58Encode(signedMessage);
}
}
async bs58Encode(data) {
return bs58.encode(
Buffer.from(data.buffer, data.byteOffset, data.byteLength),
);
}
async bs58Decode(data) {
return new Uint8Array(bs58.decode(data));
}
decodePayload(payload) {
return new TextDecoder().decode(payload);
}
/**
* Namespace wrapper of storeGetAsync
* @param {string} signedMessage r // Path to get
*/
async verifySignature(signedMessage, pubKey) {
if (taskNodeAdministered) {
return await genericHandler('verifySignedData', signedMessage, pubKey);
} else {
try {
const payload = nacl.sign.open(
await this.bs58Decode(signedMessage),
await this.bs58Decode(pubKey),
);
if (!payload) return { error: 'Invalid signature' };
return { data: this.decodePayload(payload) };
} catch (e) {
console.error(e);
return { error: `Verification failed: ${e}` };
}
}
}
// async submissionOnChain(submitterKeypair, submission) {
// return await genericHandler(
// 'submissionOnChain',
// submitterKeypair,
// submission,
// );
// }
async stakeOnChain(
taskStateInfoPublicKey,
stakingAccKeypair,
stakePotAccount,
stakeAmount,
) {
if (taskNodeAdministered) {
return await genericHandler(
'stakeOnChain',
taskStateInfoPublicKey,
stakingAccKeypair,
stakePotAccount,
stakeAmount,
);
} else {
this.#testingTaskState.stake_list[
this.#testingStakingSystemAccount.publicKey.toBase58()
] = stakeAmount;
}
}
async claimReward(stakePotAccount, beneficiaryAccount, claimerKeypair) {
if (!taskNodeAdministered) {
console.log('Cannot call sendTransaction in testing mode');
return;
}
return await genericHandler(
'claimReward',
stakePotAccount,
beneficiaryAccount,
claimerKeypair,
);
}
async sendTransaction(serviceNodeAccount, beneficiaryAccount, amount) {
if (!taskNodeAdministered) {
console.log('Cannot call sendTransaction in testing mode');
return;
}
return await genericHandler(
'sendTransaction',
serviceNodeAccount,
beneficiaryAccount,
amount,
);
}
async getSubmitterAccount() {
if (taskNodeAdministered) {
const submitterAccountResp = await genericHandler('getSubmitterAccount');
return Keypair.fromSecretKey(
Uint8Array.from(Object.values(submitterAccountResp._keypair.secretKey)),
);
} else {
return this.#testingStakingSystemAccount;
}
}
/**
* sendAndConfirmTransaction wrapper that injects mainSystemWallet as the first signer for paying the tx fees
* @param {connection} method // Receive method ["get", "post", "put", "delete"]
* @param {transaction} path // Endpoint path appended to namespace
* @param {Function} callback // Callback function on traffic receive
*/
async sendAndConfirmTransactionWrapper(transaction, signers) {
if (!taskNodeAdministered) {
console.log('Cannot call sendTransaction in testing mode');
return;
}
const blockhash = (await connection.getRecentBlockhash('finalized'))
.blockhash;
transaction.recentBlockhash = blockhash;
transaction.feePayer = new PublicKey(MAIN_ACCOUNT_PUBKEY);
return await genericHandler(
'sendAndConfirmTransactionWrapper',
transaction.serialize({
requireAllSignatures: false,
verifySignatures: false,
}),
signers,
);
}
// async signArweave(transaction) {
// let tx = await genericHandler('signArweave', transaction.toJSON());
// return arweave.transactions.fromRaw(tx);
// }
// async signEth(transaction) {
// return await genericHandler('signEth', transaction);
// }
async getTaskState(options) {
if (taskNodeAdministered) {
const response = await genericHandler('getTaskState', options);
if (response.error) {
console.log('Error in getting task state', response.error);
return null;
}
return response;
} else {
return this.#testingTaskState;
}
}
async logMessage(level, message) {
switch (level) {
case LogLevel.Log:
console.log(message);
break;
case LogLevel.Warn:
console.warn(message);
break;
case LogLevel.Error:
console.error(message);
break;
default:
console.log(
`Invalid log level: ${level}. The log levels can be log, warn or error`,
);
return false;
}
return true;
}
/**
* This logger function is used to log the task erros , warnings and logs on desktop-node
* @param {level} enum // Receive method ["Log", "Warn", "Error"]
enum LogLevel {
Log = 'log',
Warn = 'warn',
Error = 'error',
}
* @param {message} string // log, error or warning message
* @returns {boolean} // true if the message is logged successfully otherwise false
*/
async logger(level, message) {
if (taskNodeAdministered) {
return await genericHandler('logger', level, message);
} else {
return await this.logMessage(level, message);
}
}
async auditSubmission(candidatePubkey, isValid, voterKeypair, round) {
if (taskNodeAdministered) {
return await genericHandler(
'auditSubmission',
candidatePubkey,
isValid,
round,
);
} else {
if (
this.#testingTaskState.submissions_audit_trigger[round] &&
this.#testingTaskState.submissions_audit_trigger[round][candidatePubkey]
) {
this.#testingTaskState.submissions_audit_trigger[round][
candidatePubkey
].votes.push({
is_valid: isValid,
voter: voterKeypair.pubKey.toBase58(),
slot: 100,
});
} else {
this.#testingTaskState.submissions_audit_trigger[round] = {
[candidatePubkey]: {
trigger_by: this.#testingStakingSystemAccount.publicKey.toBase58(),
slot: 100,
votes: [],
},
};
}
}
}
async distributionListAuditSubmission(
candidatePubkey,
isValid,
voterKeypair,
round,
) {
if (taskNodeAdministered) {
return await genericHandler(
'distributionListAuditSubmission',
candidatePubkey,
isValid,
round,
);
} else {
if (
this.#testingTaskState.distributions_audit_trigger[round] &&
this.#testingTaskState.distributions_audit_trigger[round][
candidatePubkey
]
) {
this.#testingTaskState.distributions_audit_trigger[round][
candidatePubkey
].votes.push({
is_valid: isValid,
voter: voterKeypair.pubKey.toBase58(),
slot: 100,
});
} else {
this.#testingTaskState.distributions_audit_trigger[round] = {
[candidatePubkey]: {
trigger_by: this.#testingStakingSystemAccount.publicKey.toBase58(),
slot: 100,
votes: [],
},
};
}
}
}
async getRound() {
if (taskNodeAdministered) {
return await genericHandler('getRound');
} else {
return 1;
}
}
async payoutTrigger(round) {
if (taskNodeAdministered) {
return await genericHandler('payloadTrigger', round);
} else {
console.log(
'Payout Trigger only handles possitive flows (Without audits)',
);
let round = 1;
const submissionValAcc =
this.#testingDistributionList[round][
this.#testingStakingSystemAccount.toBase58()
].submission_value;
this.#testingTaskState.available_balances =
this.#testingDistributionList[round][submissionValAcc];
}
}
async uploadDistributionList(distributionList, round) {
if (taskNodeAdministered) {
return await genericHandler(
'uploadDistributionList',
distributionList,
round,
);
} else {
if (!this.#testingDistributionList[round])
this.#testingDistributionList[round] = {};
this.#testingDistributionList[round][
this.#testingStakingSystemAccount.publicKey.toBase58()
] = Buffer.from(JSON.stringify(distributionList));
return true;
}
}
async distributionListSubmissionOnChain(round) {
if (taskNodeAdministered) {
return await genericHandler('distributionListSubmissionOnChain', round);
} else {
if (!this.#testingTaskState.distribution_rewards_submission[round])
this.#testingTaskState.distribution_rewards_submission[round] = {};
this.#testingTaskState.distribution_rewards_submission[round][
this.#testingStakingSystemAccount.publicKey.toBase58()
] = {
submission_value:
this.#testingStakingSystemAccount.publicKey.toBase58(),
slot: 200,
round: 1,
};
}
}
async checkSubmissionAndUpdateRound(submissionValue = 'default', round) {
if (taskNodeAdministered) {
return await genericHandler(
'checkSubmissionAndUpdateRound',
submissionValue,
round,
);
} else {
if (!this.#testingTaskState.submissions[round])
this.#testingTaskState.submissions[round] = {};
this.#testingTaskState.submissions[round][
this.#testingStakingSystemAccount.publicKey.toBase58()
] = {
submission_value: submissionValue,
slot: 100,
round: 1,
};
}
}
async getProgramAccounts() {
if (taskNodeAdministered) {
return await genericHandler('getProgramAccounts');
} else {
console.log('Cannot call getProgramAccounts in testing mode');
}
}
async defaultTaskSetup() {
if (taskNodeAdministered) {
return await genericHandler('defaultTaskSetup');
} else {
if (this.#testingTaskState) return;
this.#testingMainSystemAccount = new Keypair();
this.#testingStakingSystemAccount = new Keypair();
this.#testingDistributionList = {};
this.#testingTaskState = {
task_name: 'DummyTestState',
task_description: 'Dummy Task state for testing flow',
submissions: {
2: {
'12NCN3sS1LP8C53rSzqvt7CvqMZ7H2Da42NxuDU19J2B':{
submission_value:"bafybeie6rxstaqxrecbhh5gaklqpufnrzphoywtp74wzjfuv6y5gnhmf3y",
slot:27056008
}
},
3: {
'12NCN3sS1LP8C53rSzqvt7CvqMZ7H2Da42NxuDU19J2B':{
submission_value:"bafybeie6rxstaqxrecbhh5gaklqpufnrzphoywtp74wzjfuv6y5gnhmf3y",
slot:27056008
}
}
},
submissions_audit_trigger: {},
total_bounty_amount: 10000000000,
bounty_amount_per_round: 1000000000,
total_stake_amount: 50000000000,
minimum_stake_amount: 5000000000,
available_balances: {},
stake_list: {},
round_time: 600,
starting_slot: 0,
audit_window: 200,
submission_window: 200,
distribution_rewards_submission: {},
distributions_audit_trigger: {},
};
}
}
async getRpcUrl() {
if (taskNodeAdministered) {
return await genericHandler('getRpcUrl');
} else {
console.log('Cannot call getNodes in testing mode');
}
}
async getNodes(url) {
if (taskNodeAdministered) {
return await genericHandler('getNodes', url);
} else {
console.log('Cannot call getNodes in testing mode');
}
}
async getDistributionList(publicKey, round) {
if (taskNodeAdministered) {
const response = await genericHandler(
'getDistributionList',
publicKey,
round,
);
if (response.error) {
return null;
}
return response;
} else {
const submissionValAcc =
this.#testingTaskState.distribution_rewards_submission[round][
this.#testingStakingSystemAccount.publicKey.toBase58()
].submission_value;
return this.#testingDistributionList[round][submissionValAcc];
}
}
async getTaskSubmissionInfo(round, forcefetch = false) {
if (taskNodeAdministered) {
const taskSubmissionInfo = await genericHandler(
'getTaskSubmissionInfo',
round,
forcefetch,
);
if (!taskSubmissionInfo || taskSubmissionInfo.error) {
return null;
}
return taskSubmissionInfo;
} else {
return this.#testingTaskState;
}
}
async validateAndVoteOnNodes(validate, round) {
console.log('******/ IN VOTING /******');
let taskAccountDataJSON = null;
try {
taskAccountDataJSON = await this.getTaskSubmissionInfo(round);
} catch (error) {
console.error('Error in getting submissions for the round', error);
}
if (taskAccountDataJSON == null) {
console.log('No submissions found for the round', round);
return;
}
console.log(`Fetching the submissions of round ${round}`);
const submissions = taskAccountDataJSON.submissions[round];
if (submissions == null) {
console.log(`No submisssions found in round ${round}`);
return `No submisssions found in round ${round}`;
} else {
const keys = Object.keys(submissions);
const values = Object.values(submissions);
const size = values.length;
// console.log('Submissions from last round: ', keys, values, size);
const numberOfChecks = Math.min(5, size);
let uniqueIndices = new Set();
// Populate uniqueIndices with unique random numbers
while (uniqueIndices.size < numberOfChecks) {
const randomIndex = Math.floor(Math.random() * size);
uniqueIndices.add(randomIndex);
}
let isValid;
const submitterAccountKeyPair = await this.getSubmitterAccount();
const submitterPubkey = submitterAccountKeyPair.publicKey.toBase58();
for (let index of uniqueIndices) {
let candidatePublicKey = keys[index];
// console.log('FOR CANDIDATE KEY', candidatePublicKey);
let candidateKeyPairPublicKey = new PublicKey(keys[index]);
if (candidatePublicKey == submitterPubkey) {
console.log('YOU CANNOT VOTE ON YOUR OWN SUBMISSIONS');
} else {
try {
console.log(
'SUBMISSION VALUE TO CHECK',
values[index].submission_value,
);
isValid = await validate(values[index].submission_value, round);
if (isValid) {
// check for the submissions_audit_trigger , if it exists then vote true on that otherwise do nothing
const submissions_audit_trigger =
taskAccountDataJSON.submissions_audit_trigger[round];
console.log('SUBMIT AUDIT TRIGGER', submissions_audit_trigger);
// console.log(
// "CANDIDATE PUBKEY CHECK IN AUDIT TRIGGER",
// submissions_audit_trigger[candidatePublicKey]
// );
if (
submissions_audit_trigger &&
submissions_audit_trigger[candidatePublicKey]
) {
console.log('VOTING TRUE ON AUDIT');
const response = await this.auditSubmission(
candidateKeyPairPublicKey,
isValid,
submitterAccountKeyPair,
round,
);
console.log('RESPONSE FROM AUDIT FUNCTION', response);
}
} else if (isValid == false) {
// Call auditSubmission function and isValid is passed as false
console.log('RAISING AUDIT / VOTING FALSE');
const response = await this.auditSubmission(
candidateKeyPairPublicKey,
isValid,
submitterAccountKeyPair,
round,
);
console.log('RESPONSE FROM AUDIT FUNCTION', response);
}
} catch (err) {
console.log('ERROR IN ELSE CONDITION', err);
}
}
}
}
}
async getTaskDistributionInfo(round) {
if (taskNodeAdministered) {
const taskDistributionInfo = await genericHandler(
'getTaskDistributionInfo',
round,
);
if (!taskDistributionInfo || taskDistributionInfo.error) {
return null;
}
return taskDistributionInfo;
} else {
return this.#testingTaskState.distribution_rewards_submission[round];
}
}
async validateAndVoteOnDistributionList(
validateDistribution,
round,
isPreviousRoundFailed = false,
) {
// await this.checkVoteStatus();
console.log('******/ IN VOTING OF DISTRIBUTION LIST /******');
let tasknodeVersionSatisfied = false;
const taskNodeVersion = await this.getTaskNodeVersion();
if (semver.gte(taskNodeVersion, '1.11.19')) {
tasknodeVersionSatisfied = true;
}
let taskAccountDataJSON = null;
try {
taskAccountDataJSON = await this.getTaskDistributionInfo(round);
} catch (error) {
console.error('Error in getting distributions for the round', error);
}
if (taskAccountDataJSON == null) {
console.log('No distribution submissions found for the round', round);
return;
}
console.log(
`Fetching the Distribution submissions of round ${round}`,
taskAccountDataJSON.distribution_rewards_submission[round],
);
const submissions =
taskAccountDataJSON.distribution_rewards_submission[round];
if (submissions == null) {
console.log(`No submisssions found in round ${round}`);
return `No submisssions found in round ${round}`;
} else {
const keys = Object.keys(submissions);
const values = Object.values(submissions);
const size = values.length;
// console.log(
// 'Distribution Submissions from last round: ',
// keys,
// values,
// size,
// );
let isValid;
const submitterAccountKeyPair = await this.getSubmitterAccount();
const submitterPubkey = submitterAccountKeyPair.publicKey.toBase58();
const selectedNode = await this.nodeSelectionDistributionList(
round,
isPreviousRoundFailed,
);
// console.log('SELECTED NODE FOR AUDIT', selectedNode);
if (selectedNode == submitterPubkey) {
console.log('YOU CANNOT VOTE ON YOUR OWN DISTRIBUTION SUBMISSIONS');
return;
}
for (let i = 0; i < size; i++) {
let candidatePublicKey = keys[i];
console.log('FOR CANDIDATE KEY', candidatePublicKey);
let candidateKeyPairPublicKey = new PublicKey(keys[i]);
try {
// console.log(
// 'DISTRIBUTION SUBMISSION VALUE TO CHECK',
// values[i].submission_value,
// );
isValid = await validateDistribution(
values[i].submission_value,
round,
);
if (isValid) {
// check for the submissions_audit_trigger , if it exists then vote true on that otherwise do nothing
const distributions_audit_trigger =
taskAccountDataJSON.distributions_audit_trigger[round];
console.log(
'SUBMIT DISTRIBUTION AUDIT TRIGGER',
distributions_audit_trigger,
);
// console.log(
// "CANDIDATE PUBKEY CHECK IN AUDIT TRIGGER",
// distributions_audit_trigger[candidatePublicKey]
// );
if (
distributions_audit_trigger &&
distributions_audit_trigger[candidatePublicKey]
) {
console.log('VOTING TRUE ON DISTRIBUTION AUDIT');
const response = await this.distributionListAuditSubmission(
candidateKeyPairPublicKey,
isValid,
submitterAccountKeyPair,
round,
);
console.log(
'RESPONSE FROM DISTRIBUTION AUDIT FUNCTION',
response,
);
}
} else if (isValid == false && tasknodeVersionSatisfied) {
// Call auditSubmission function and isValid is passed as false
console.log('RAISING AUDIT / VOTING FALSE ON DISTRIBUTION');
const response = await this.distributionListAuditSubmission(
candidateKeyPairPublicKey,
isValid,
submitterAccountKeyPair,
round,
);
console.log('RESPONSE FROM DISTRIBUTION AUDIT FUNCTION', response);
}
} catch (err) {
console.log('ERROR IN ELSE CONDITION FOR DISTRIBUTION', err);
}
}
}
}
async getTaskNodeVersion() {
if (taskNodeAdministered) {
try {
return await genericHandler('getTaskNodeVersion');
} catch (error) {
console.error('Error getting task node version', error);
return;
}
} else {
return '1.11.19';
}
}
async getTaskLevelDBPath() {
if (taskNodeAdministered) {
return await genericHandler('getTaskLevelDBPath');
} else {
return './KOIIDB';
}
}
async getBasePath() {
if (taskNodeAdministered) {
const basePath = (await namespaceWrapper.getTaskLevelDBPath()).replace(
'/KOIIDB',
'',
);
return basePath;
} else {
return './';
}
}
async getAverageSlotTime() {
if (taskNodeAdministered) {
try {
return await genericHandler('getAverageSlotTime');
} catch (error) {
console.error('Error getting average slot time', error);
return 400;
}
} else {
return 400;
}
}
async nodeSelectionDistributionList(round, isPreviousFailed) {
let taskAccountDataJSON = null;
try {
taskAccountDataJSON = await this.getTaskSubmissionInfo(round, true);
} catch (error) {
console.error('Task submission not found', error);
return;
}
if (taskAccountDataJSON == null) {
console.error('Task state not found');
return;
}
// console.log('EXPECTED ROUND', round);
const submissions = taskAccountDataJSON.submissions[round];
if (submissions == null) {
console.log('No submisssions found in N-1 round');
return 'No submisssions found in N-1 round';
} else {
// getting last 3 submissions for the rounds
let keys;
const latestRounds = [round, round - 1, round - 2].filter(r => r >= 0);
const promises = latestRounds.map(async r => {
if (r == round) {
return new Set(Object.keys(submissions));
} else {
let roundSubmissions = null;
try {
roundSubmissions = await this.getTaskSubmissionInfo(r, true);
if (roundSubmissions && roundSubmissions.submissions[r]) {
return new Set(Object.keys(roundSubmissions.submissions[r]));
}
} catch (error) {
console.error('Error in getting submissions for the round', error);
}
return new Set();
}
});
const keySets = await Promise.all(promises);
// Find the keys present in all the rounds
keys =
keySets.length > 0
? [...keySets[0]].filter(key => keySets.every(set => set.has(key)))
: [];
if (keys.length == 0) {
console.log('No common keys found in last 3 rounds');
keys = Object.keys(submissions);
}
// console.log('KEYS', keys.length);
const values = keys.map(key => submissions[key]);
let size = keys.length;
console.log('Submissions from N-2 round: ', size);
// Check the keys i.e if the submitter shall be excluded or not
try {
const distributionData = await this.getTaskDistributionInfo(round);
const audit_record = distributionData?.distributions_audit_record;
if (audit_record && audit_record[round] == 'PayoutFailed') {
// console.log('ROUND DATA', audit_record[round]);
// console.log(
// 'SUBMITTER LIST',
// distributionData.distribution_rewards_submission[round],
// );
const submitterList =
distributionData.distribution_rewards_submission[round];
const submitterKeys = Object.keys(submitterList);
// console.log('SUBMITTER KEYS', submitterKeys);
const submitterSize = submitterKeys.length;
// console.log('SUBMITTER SIZE', submitterSize);
for (let j = 0; j < submitterSize; j++) {
// console.log('SUBMITTER KEY CANDIDATE', submitterKeys[j]);
const id = keys.indexOf(submitterKeys[j]);
// console.log('ID', id);
if (id != -1) {
keys.splice(id, 1);
values.splice(id, 1);
size--;
}
}
// console.log('KEYS FOR HASH CALC', keys.length);
}
} catch (error) {
console.log('Error in getting distribution data', error);
}
// calculating the digest
const ValuesString = JSON.stringify(values);
const hashDigest = createHash('sha256')
.update(ValuesString)
.digest('hex');
console.log('HASH DIGEST', hashDigest);
// function to calculate the score
const calculateScore = (str = '') => {
return str.split('').reduce((acc, val) => {
return acc + val.charCodeAt(0);
}, 0);
};
// function to compare the ASCII values
const compareASCII = (str1, str2) => {
const firstScore = calculateScore(str1);
const secondScore = calculateScore(str2);
return Math.abs(firstScore - secondScore);
};
// loop through the keys and select the one with higest score
const selectedNode = {
score: 0,
pubkey: '',
};
let score = 0;
if (isPreviousFailed) {
let leastScore = -Infinity;
let secondLeastScore = -Infinity;
for (let i = 0; i < size; i++) {
const candidateSubmissionJson = {};
candidateSubmissionJson[keys[i]] = values[i];
const candidateSubmissionString = JSON.stringify(
candidateSubmissionJson,
);
const candidateSubmissionHash = createHash('sha256')
.update(candidateSubmissionString)
.digest('hex');
const candidateScore = compareASCII(
hashDigest,
candidateSubmissionHash,
);
if (candidateScore > leastScore) {
secondLeastScore = leastScore;
leastScore = candidateScore;
} else if (candidateScore > secondLeastScore) {
secondLeastScore = candidateScore;
selectedNode.score = candidateScore;
selectedNode.pubkey = keys[i];
}