-
Notifications
You must be signed in to change notification settings - Fork 4
/
siegeInitialization.js
372 lines (317 loc) · 10.4 KB
/
siegeInitialization.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
'use strict';
//const API_END_POINT = 'https://api.ost.com/testnet/v2/',
const API_END_POINT = 'http://localhost:7001/testnet/v2/',
BATCH_SIZE = 25,
POLLING_INTERVAL = 5000, //5 secs
NUMBER_OF_USERS = 4,
CREDENTIALS_ARRAY = [
{
apiKey: 'c63fca36943bfc84b66a4d9b967b6eed',
apiSecret: '68b01ee2d77cdb45be83ba28a37161d7c13bd183c341a4b25ed274e3a9797ebd',
apiEndPoint: API_END_POINT
}
];
const rootPrefix = '.',
OSTSDK = require('@ostdotcom/ost-sdk-js'),
GetTokenDetails = require(rootPrefix + '/tools/seige/userFlow/GetTokenDetails'),
CreateUsers = require(rootPrefix + '/tools/seige/userFlow/CreateUsers'),
GenerateRequiredAddresses = require(rootPrefix + '/tools/seige/userFlow/GenerateRequiredAddresses'),
GetUser = require(rootPrefix + '/tools/seige/userFlow/GetUser'),
ActivateUser = require(rootPrefix + '/tools/seige/userFlow/ActivateUser'),
RegisterDevice = require(rootPrefix + '/tools/seige/userFlow/RegisterDevice'),
SiegeUsersModel = require(rootPrefix + '/app/models/mysql/SiegeUser'),
responseHelper = require(rootPrefix + '/lib/formatter/response');
class SiegeInitialization {
/**
*
* @param params
*/
constructor() {
const oThis = this;
oThis.userIdsArray = [];
}
/**
* params array of hashes
* [{ apikey: 'ghjhghj',
* apiSecret: 'hjghjhjh',
* apiEndPoint: 'www.s6-stagingost.com:7000'
* },
* { apikey: 'ghjhghj',
* apiSecret: 'hjghjhjh',
* apiEndPoint: 'www.s6-stagingost.com:7000'
* }
* ]
* @param params
*/
perform(params) {
const oThis = this;
return oThis._asyncPerform(params).catch(function(err) {
console.log(' In catch block', err);
return Promise.resolve(err);
});
}
async _asyncPerform(params) {
const oThis = this;
for (let index = 0; index < params.length; index++) {
let apiKey = params[index].apiKey,
apiSecret = params[index].apiSecret,
apiEndPoint = params[index].apiEndPoint;
oThis.ostObj = new OSTSDK({
apiKey: apiKey,
apiSecret: apiSecret,
apiEndpoint: apiEndPoint
});
}
console.log('-------------------->Fetching token data');
await oThis._getTokenData();
//create users
console.log('-------------------->Creating users');
await oThis._createUsers();
//Generates required addresses and private key
console.log('-------------------->Generating required addresses');
await oThis._generateRequiredAddress();
//Clear all old entries for given token id
//await oThis._clearOldEntries(); //Todo: Temp
//Inserting userUuids and respective addresses in db
console.log('-------------------->Inserting data in db');
await oThis._insertAddressesInDB();
//Start Siege
console.log('-------------------->Starting siege');
await oThis._startSiege();
console.log('-------------------->Clear improper entries');
await oThis._clearImproperEntries();
}
async _getTokenData() {
let oThis = this,
getTokenDetailsObj = new GetTokenDetails({ ostObj: oThis.ostObj }),
tokenDetailsRsp = await getTokenDetailsObj.perform();
if (tokenDetailsRsp.isFailure()) {
console.log('Error in Get token details API', tokenDetailsRsp);
return Promise.reject(tokenDetailsRsp);
}
let tokenDetails = tokenDetailsRsp.data;
oThis.tokenId = tokenDetails.token.id;
}
/**
*
* @returns {Promise<void>}
* @private
*/
async _createUsers() {
let oThis = this,
createUsersObj = new CreateUsers({ ostObj: oThis.ostObj, numberOfUsers: NUMBER_OF_USERS });
oThis.userIdsArray = await createUsersObj.perform();
}
/**
*
* @returns {Promise<void>}
* @private
*/
async _generateRequiredAddress() {
let oThis = this,
generateRequiredAddressObj = new GenerateRequiredAddresses({ userIdsArray: oThis.userIdsArray });
oThis.requiredAddressesHash = await generateRequiredAddressObj.perform();
}
/**
*
* @returns {Promise<void>}
* @private
*/
async _clearOldEntries() {
let oThis = this,
siegeUsersObj = new SiegeUsersModel(),
deleteRsp = await siegeUsersObj
.delete()
.where(['id > 0 AND token_id = ?', oThis.tokenId])
.fire();
return Promise.resolve();
}
/**
*
* @returns {Promise<void>}
* @private
*/
async _insertAddressesInDB() {
let oThis = this,
siegeUsersObj = new SiegeUsersModel(),
insertColumns = ['token_id', 'user_uuid', 'device_address', 'device_pk', 'session_address', 'session_pk'],
insertMultipleValues = [];
for (let i = 0; i < oThis.userIdsArray.length; i++) {
let userUuid = oThis.userIdsArray[i],
addressesDetails = oThis.requiredAddressesHash[userUuid],
insertValueArray = [];
insertValueArray[0] = oThis.tokenId;
insertValueArray[1] = userUuid;
insertValueArray[2] = addressesDetails.deviceAddress;
insertValueArray[3] = addressesDetails.deviceAddressPrivateKey;
insertValueArray[4] = addressesDetails.sessionAddress;
insertValueArray[5] = addressesDetails.sessionPrivateKey;
insertMultipleValues.push(insertValueArray);
}
await siegeUsersObj.insertMultiple(insertColumns, insertMultipleValues).fire();
}
/**
*
* @returns {Promise<void>}
* @private
*/
async _startSiege() {
let oThis = this,
promiseArray = [];
for (let index = 0; index < oThis.userIdsArray.length; index++) {
let userUuid = oThis.userIdsArray[index],
addressesDetails = oThis.requiredAddressesHash[userUuid];
promiseArray.push(oThis._performOperationsForSingleUser(userUuid, addressesDetails));
if (promiseArray.length >= BATCH_SIZE || oThis.userIdsArray.length === index + 1) {
await Promise.all(promiseArray);
promiseArray = [];
}
}
}
/**
*
* @param {string} userUuid
* @param {hash} addressesData
* @returns {Promise<void>}
* @private
*/
async _performOperationsForSingleUser(userUuid, addressesData) {
let oThis = this,
deviceAddress = addressesData.deviceAddress,
deviceAddressPrivateKey = addressesData.deviceAddressPrivateKey,
sessionAddress = addressesData.sessionAddress;
//Register Device
console.log('****Registering Device****');
await oThis._registerDevice(userUuid, deviceAddress);
//Activate User
let paramsForActivateUser = {
tokenId: oThis.tokenId,
userUuid: userUuid,
deviceAddress: deviceAddress,
apiSignerPrivateKey: deviceAddressPrivateKey,
sessionAddress: sessionAddress
};
console.log('****Activating User****');
await oThis._activateUser(paramsForActivateUser);
//Start Polling to fetch user status
console.log('****Initiated Poll****');
let userDataRsp = await oThis._pollForUserStatus(userUuid, 'ACTIVATED');
if (userDataRsp.isFailure()) {
return Promise.resolve(userDataRsp);
}
let userData = userDataRsp.data;
let tokenHolderAddress = userData.user.token_holder_address;
//Save token holder in db
let siegeUsersObj = new SiegeUsersModel(),
insertRsp = siegeUsersObj
.update({ token_holder_contract_address: tokenHolderAddress })
.where(['user_uuid = ?', userUuid])
.fire();
return Promise.resolve();
}
/**
*
* @param uuid
* @param deviceAddress
* @returns {Promise<void>}
* @private
*/
async _registerDevice(uuid, deviceAddress) {
let oThis = this,
registerDeviceObj = new RegisterDevice({
userUuid: uuid,
deviceAddress: deviceAddress,
ostObj: oThis.ostObj
}),
deviceData = await registerDeviceObj.perform();
}
/**
*
* @param params
* @returns {Promise<void>}
* @private
*/
async _activateUser(params) {
let oThis = this,
activateUserObj = new ActivateUser({
tokenId: params.tokenId,
userUuid: params.userUuid,
deviceAddress: params.deviceAddress,
apiSignerPrivateKey: params.apiSignerPrivateKey,
sessionAddress: params.sessionAddress,
expirationHeight: '1000000000000',
spendingLimit: '100000000000000000000',
apiEndPoint: API_END_POINT
}),
activateUserRsp = await activateUserObj.perform();
}
/**
*
* @param userUuid
* @param status
* @returns {Promise<*>}
* @private
*/
async _pollForUserStatus(userUuid, status) {
let oThis = this;
return new Promise(async function(onResolve, onReject) {
const _getUserData = async function(userUuid) {
let getUserDataObj = new GetUser({ ostObj: oThis.ostObj, userUuid: userUuid }),
userDataRsp = await getUserDataObj.perform();
if (userDataRsp.isFailure()) {
console.log('Failure:', userDataRsp);
return onResolve(userDataRsp);
}
let userData = userDataRsp.data;
console.log('.');
console.log('userData', userData);
if (userData.user.status == status) {
return onResolve(responseHelper.successWithData(userData));
} else {
setTimeout(async function() {
_getUserData(userUuid).catch(function(err) {
console.log(' In catch block of _getUserData 1', err);
return onResolve(
responseHelper.error({
internal_error_identifier: 'r_si_1',
api_error_identifier: 'something_went_wrong',
debug_options: { err: err }
})
);
});
}, POLLING_INTERVAL);
}
};
_getUserData(userUuid).catch(function(err) {
console.log(' In catch block of _getUserData 2', err);
return onResolve(
responseHelper.error({
internal_error_identifier: 'r_si_2',
api_error_identifier: 'something_went_wrong',
debug_options: { err: err }
})
);
});
});
}
/**
* Deletes entries whose token holder address is NULL
* @returns {Promise<void>}
* @private
*/
async _clearImproperEntries() {
let oThis = this,
siegeUsersObj = new SiegeUsersModel(),
deleteRsp = await siegeUsersObj
.delete()
.where(['token_id = ? AND token_holder_contract_address IS NULL', oThis.tokenId])
.fire();
return Promise.resolve();
}
}
new SiegeInitialization().perform(CREDENTIALS_ARRAY).then(function() {
setTimeout(function() {
console.log('********** DONE ************');
process.exit(0);
}, 5000);
});