-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.js
More file actions
329 lines (283 loc) · 9.32 KB
/
bootstrap.js
File metadata and controls
329 lines (283 loc) · 9.32 KB
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
import fs from 'fs';
import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
import { RSA, Crypt } from 'hybrid-crypto-js';
import axios from 'axios';
import crypto from 'crypto';
/**
* Organs (chaincode) APIs.
*/
import * as identity from '../organs/identity/api/dist/index.js';
import * as job from '../organs/job/api/dist/index.js';
import * as keypair from '../organs/keypair/api/dist/index.js';
import * as user from '../organs/user/api/dist/index.js';
/**
* __filename and __dirname are not defined in NPM modules on Node 15.
* We construct them manually. We may use babel later, which populate those variables correclty.
*/
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
/**
* Indexes to be created on the CouchDB database.
*/
const indexNextWorkers = {"index":{"fields":["lastJobAttribution","registryDate"]},"ddoc":"indexNextWorkersDoc","name":"indexNextWorkers","type":"json"};
/**
* Arbitrary usernames, used to create a bunch of users.
*/
const rawUsers = ['dani', 'dani42', 'dani420', 'dani4200'];
const usersToCreate = rawUsers.map(u => `${(Math.random() * 420).toFixed(0)}-${u}`);
/**
* A bunch of objects used to store values.
*/
var crypt = new Crypt();
var rsa = new RSA();
var sharedKeyPairs = {};
var keypairs = {};
var wallets = {};
var ids = {};
var encryptedIdentities = {};
var workersByUsername = {};
var groupIds = {};
var jobs = {};
/**
* Identity object, used later in the code.
*/
const baseIdentity = {
firstname: 'John',
lastname: 'Smith',
birthdate: '1990-10-23',
nation: 'US',
nationalId: `jd8wljd9${Math.random()*1000}`,
};
/**
* Promisified rsa.generateKeyPair function.
*/
const generateKeyPair = () => {
return new Promise((resolve) => {
rsa.generateKeyPair(resolve);
})
};
/**
* Return a string md5 hash based on specific fields of an identity.
*/
const uniqueHashFromIdentity = identity =>
crypto
.createHash('md5')
.update(`${identity.nation}-${identity.nationalId}-${identity.birthdate}`)
.digest('hex');
/**
* Send request to the CouchDB database.
* It creates indexes, which allows us to sort by those indexes.
*/
const createIndexes = async () => {
console.log('##################################');
console.log('createIndexes');
console.log('##################################');
const promises = [];
promises.push(axios.post('http://admin:adminpw@localhost:5984/mychannel_user/_index', indexNextWorkers))
promises.push(axios.post('http://admin:adminpw@localhost:7984/mychannel_user/_index', indexNextWorkers))
return Promise.all(promises).catch(console.log);
};
/**
* Send a request to the network.
* Create users and receive wallets.
*/
const createWalletsAndRegister = async (users) => {
console.log('##################################');
console.log('createWalletsAndRegister');
console.log('##################################');
let promises = [];
users.forEach(username => {
console.log(' ::: ', username);
promises.push(new Promise(async (r) => {
keypairs[username] = await generateKeyPair();
sharedKeyPairs[username] = await generateKeyPair();
user
.create({username, publicKey: keypairs[username].publicKey})
.then(({wallet, id}) => {
wallets[username] = wallet;
ids[username] = id;
r();
})
.catch(console.log)
}))
})
return Promise.all(promises).catch(console.log);
};
/**
* Send a request to the network.
* Create identities.
*/
const createIdentities = async (users) => {
console.log('##################################');
console.log('createIdentities');
console.log('##################################');
let promises = [];
users.forEach((u, i) => {
promises.push(new Promise((r) => {
var myIdentity = { ...baseIdentity, nationalId: `${baseIdentity.nationalId}${i}` };
var encryptedIdentity = crypt.encrypt(sharedKeyPairs[u].publicKey, myIdentity);
var uniqueHash = uniqueHashFromIdentity(myIdentity);
encryptedIdentities[u] = encryptedIdentity;
identity
.create({
encryptedIdentity,
uniqueHash,
user: {username: u, wallet: wallets[u]}
})
.then(r)
.catch(console.log)
}))
})
return Promise.all(promises).catch(console.log);
};
/**
* Send a request to the network.
* Create jobs.
* Those jobs are identity verification tasks.
* They are attributed to an array of users.
*/
const createVerificationJobs = async (users) => {
console.log('##################################');
console.log('createVerificationJobs');
console.log('##################################');
let promises = [];
users.forEach((u, i) => {
promises.push(new Promise((r) => {
setTimeout(() => {
job.create({
type: 'confirmation',
data: encryptedIdentities[u],
chaincode: 'identity',
key: ids[u],
user: {username: u, wallet: wallets[u]}
})
.then(({workersIds, jobId}) => {
console.log('Workers count: ', workersIds.length)
workersByUsername[u] = workersIds;
groupIds[u] = jobId;
r()
})
}, i * 4000)
}))
})
return Promise.all(promises).catch(console.log);
};
/**
* Send a request to the network.
* Create keypairs, and share them with a group of workers attributed to the same task.
*/
const createSharedKeypairs = async (users) => {
console.log('##################################');
console.log('createSharedKeypairs');
console.log('##################################');
let promises = [];
users.forEach(u => {
promises.push(new Promise((r) => {
let sharedWith = {};
let groupId = groupIds[u];
let myEncryptedKeyPair = crypt.encrypt(keypairs[u].publicKey, sharedKeyPairs[u]);
workersByUsername[u].forEach(worker => {
if(worker._id === u) return;
sharedWith[worker._id] = {keypair: crypt.encrypt(worker.publicKey, sharedKeyPairs[u])}
})
console.log('sharedWith count', Object.keys(sharedWith).length)
keypair.share({
sharedWith,
groupId,
myEncryptedKeyPair,
type: 'job',
user: {username: u, wallet: wallets[u]}
})
.then(r)
}))
})
return Promise.all(promises).catch(console.log);
};
/**
* Send a request to the network.
* List jobs attributed to the user.
*/
const listJobs = async (users) => {
console.log('##################################');
console.log('listJobs');
console.log('##################################');
let promises = [];
users.forEach(u => {
promises.push(new Promise((r) => {
job.list({
status: 'pending',
user: {username: u, wallet: wallets[u]}
})
.then(result => {
console.log(result);
jobs[u] = result;
r();
})
}))
})
return Promise.all(promises).catch(console.log);
};
/**
* Send a request to the network.
* Complete jobs, by sending a result.
* In that case, we arbitrary `approve` all the jobs.
*/
const completeJobs = async (user, jobs) => {
console.log('##################################');
console.log('completeJobs');
console.log('##################################');
let promises = [];
jobs.forEach(j => {
promises.push(
new Promise((r) => {
console.log({j})
job.complete({
jobId: j.jobId,
result: 1,
user
})
.then(r)
})
)
})
return Promise.all(promises).catch(console.log);
};
/**
* Send a request to the network.
* Complete all the jobs using the function above.
*/
const completeAllJobs = async (users) => {
console.log('##################################');
console.log('completeAllJobs');
console.log('##################################');
let promises = [];
users.forEach(u => {
promises.push(new Promise((r) => {
completeJobs({username: u, wallet: wallets[u]}, jobs[u])
.then(r)
}))
})
return Promise.all(promises).catch(console.log);
};
/**
* Start the Bootstrap process.
*/
export const start = async () => {
// create indexes
await createIndexes();
// create wallets and users
await createWalletsAndRegister(usersToCreate);
// create identities
await createIdentities(usersToCreate);
// Create a job for each user
await createVerificationJobs(usersToCreate);
// Create a shared key for each user
await createSharedKeypairs(usersToCreate);
// List jobs
await listJobs(usersToCreate);
// Approve and complete the verification job
await completeAllJobs(usersToCreate);
// List jobs
await listJobs(usersToCreate);
};