This repository has been archived by the owner on Dec 9, 2024. It is now read-only.
forked from koii-network/task-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coreLogic.js
304 lines (260 loc) · 9.95 KB
/
coreLogic.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
const { namespaceWrapper } = require('./namespaceWrapper');
const crypto = require('crypto');
const db = require('./database/db');
class CoreLogic {
async task() {
// this is where you need to populate the proofs database
// rough format of what you need to store:
/*
proofs_for_round : {
files : [ [ cid1, sizeOfCID1 ],
[ cid2, sizeOfCID2 ]
... ],
hash : String (sha256 over file list) -> this is what is submitted to k2,
totalSize : Number (megabytes you're storing)
}
*/
try {
const files = db.getFile()
const hash = calculateHash(files);
const totalSize = calculateFileSize(files.content);
const proofs = {
hash,
totalSize
};
console.log('Proofs stored successfully', proofs);
} catch (error) {
console.error('Error in populating proofs database', error);
}
function calculateHash(data) {
const hash = crypto.createHash('sha256');
hash.update(JSON.stringify(data));
const hashDigest = hash.digest('hex');
return hashDigest;
}
function calculateFileSize(content) {
const fileSizeInBytes = Buffer.byteLength(content, 'utf8');
return fileSizeInBytes;
}
}
async fetchSubmission() {
console.log('IN FETCH SUBMISSION');
let roundId = namespaceWrapper.getRound();
const proofs = await db.getProofs(roundId);
if (proofs) {
const submission = proofs.hash + '__' + proofs.totalSize;
console.log('proofs for ' + roundId, submission);
return submission;
} else {
console.log('No proofs found for ' + roundId);
return null;
}
}
async generateDistributionList(round, _dummyTaskState) {
try {
console.log('GenerateDistributionList called');
console.log('I am selected node');
// Write the logic to generate the distribution list here by introducing the rules of your choice
/* **** SAMPLE LOGIC FOR GENERATING DISTRIBUTION LIST ******/
let distributionList = {};
let distributionCandidates = [];
let taskAccountDataJSON = await namespaceWrapper.getTaskState();
if (taskAccountDataJSON == null) taskAccountDataJSON = _dummyTaskState;
const submissions = taskAccountDataJSON.submissions[round];
const submissions_audit_trigger =
taskAccountDataJSON.submissions_audit_trigger[round];
if (submissions == null) {
console.log('No submisssions found in N-2 round');
return distributionList;
} else {
const keys = Object.keys(submissions);
const values = Object.values(submissions);
const size = values.length;
console.log('Submissions from last round: ', keys, values, size);
// Logic for slashing the stake of the candidate who has been audited and found to be false
for (let i = 0; i < size; i++) {
const candidatePublicKey = keys[i];
if (
submissions_audit_trigger &&
submissions_audit_trigger[candidatePublicKey]
) {
console.log(
'distributions_audit_trigger votes ',
submissions_audit_trigger[candidatePublicKey].votes,
);
const votes = submissions_audit_trigger[candidatePublicKey].votes;
if (votes.length === 0) {
// slash 70% of the stake as still the audit is triggered but no votes are casted
// Note that the votes are on the basis of the submission value
// to do so we need to fetch the stakes of the candidate from the task state
const stake_list = taskAccountDataJSON.stake_list;
const candidateStake = stake_list[candidatePublicKey];
const slashedStake = candidateStake * 0.7;
distributionList[candidatePublicKey] = -slashedStake;
console.log('Candidate Stake', candidateStake);
} else {
let numOfVotes = 0;
for (let index = 0; index < votes.length; index++) {
if (votes[index].is_valid) numOfVotes++;
else numOfVotes--;
}
if (numOfVotes < 0) {
// slash 70% of the stake as the number of false votes are more than the number of true votes
// Note that the votes are on the basis of the submission value
// to do so we need to fetch the stakes of the candidate from the task state
const stake_list = taskAccountDataJSON.stake_list;
const candidateStake = stake_list[candidatePublicKey];
const slashedStake = candidateStake * 0.7;
distributionList[candidatePublicKey] = -slashedStake;
console.log('Candidate Stake', candidateStake);
}
if (numOfVotes > 0) {
distributionCandidates.push(candidatePublicKey);
}
}
} else {
distributionCandidates.push(candidatePublicKey);
}
}
}
// now distribute the rewards based on the valid submissions
// Here it is assumed that all the nodes doing valid submission gets the same reward
const reward =
taskAccountDataJSON.bounty_amount_per_round /
distributionCandidates.length;
console.log('REWARD RECEIVED BY EACH NODE', reward);
for (let i = 0; i < distributionCandidates.length; i++) {
distributionList[distributionCandidates[i]] = reward;
}
console.log('Distribution List', distributionList);
return distributionList;
} catch (err) {
console.log('ERROR IN GENERATING DISTRIBUTION LIST', err);
}
}
async submitDistributionList(round) {
// This function just upload your generated dustribution List and do the transaction for that
console.log('SubmitDistributionList called');
try {
const distributionList = await this.generateDistributionList(round);
const decider = await namespaceWrapper.uploadDistributionList(
distributionList,
round,
);
console.log('DECIDER', decider);
if (decider) {
const response =
await namespaceWrapper.distributionListSubmissionOnChain(round);
console.log('RESPONSE FROM DISTRIBUTION LIST', response);
}
} catch (err) {
console.log('ERROR IN SUBMIT DISTRIBUTION', err);
}
}
async validateNode(submission_value, round) {
console.log('Received submission_value', submission_value, round);
// TODO - implement an audit flow for the submissions
// Submissions look like proof_data_for_round.hash + "__" + proof_data_for_round.totalSize;
// You need to
/**
* 1. Axios call to the node's IP address to check the proofs api
* 2. Verify the hash matches the CID list
* 3. Verify that the CIDs add up to the total size
* 4. Retrieve some CIDs and verify that they are being stored, and have the correct size
*/
return true;
}
async shallowEqual(object1, object2) {
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
for (let key of keys1) {
if (object1[key] !== object2[key]) {
return false;
}
}
return true;
}
validateDistribution = async (
distributionListSubmitter,
round,
_dummyDistributionList,
_dummyTaskState,
) => {
// Write your logic for the validation of submission value here and return a boolean value in response
// this logic can be same as generation of distribution list function and based on the comparision will final object , decision can be made
try {
console.log('Distribution list Submitter', distributionListSubmitter);
const rawDistributionList = await namespaceWrapper.getDistributionList(
distributionListSubmitter,
round,
);
let fetchedDistributionList;
if (rawDistributionList == null) {
fetchedDistributionList = _dummyDistributionList;
} else {
fetchedDistributionList = JSON.parse(rawDistributionList);
}
console.log('FETCHED DISTRIBUTION LIST', fetchedDistributionList);
const generateDistributionList = await this.generateDistributionList(
round,
_dummyTaskState,
);
// compare distribution list
const parsed = fetchedDistributionList;
console.log(
'compare distribution list',
parsed,
generateDistributionList,
);
const result = await this.shallowEqual(parsed, generateDistributionList);
console.log('RESULT', result);
return result;
} catch (err) {
console.log('ERROR IN VALIDATING DISTRIBUTION', err);
return false;
}
};
// Submit Address with distributioon list to K2
async submitTask(roundNumber) {
console.log('submitTask called with round', roundNumber);
try {
console.log('inside try');
console.log(
await namespaceWrapper.getSlot(),
'current slot while calling submit',
);
const submission = await this.fetchSubmission();
console.log('SUBMISSION', submission);
await namespaceWrapper.checkSubmissionAndUpdateRound(
submission,
roundNumber,
);
console.log('after the submission call');
} catch (error) {
console.log('error in submission', error);
}
}
async auditTask(roundNumber) {
console.log('auditTask called with round', roundNumber);
console.log(
await namespaceWrapper.getSlot(),
'current slot while calling auditTask',
);
await namespaceWrapper.validateAndVoteOnNodes(
this.validateNode,
roundNumber,
);
}
async auditDistribution(roundNumber) {
console.log('auditDistribution called with round', roundNumber);
await namespaceWrapper.validateAndVoteOnDistributionList(
this.validateDistribution,
roundNumber,
);
}
}
const coreLogic = new CoreLogic();
module.exports = { coreLogic };