-
Notifications
You must be signed in to change notification settings - Fork 67
/
Blockchain.js
1349 lines (1229 loc) · 50.5 KB
/
Blockchain.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
const Ethereum = require('./Blockchain/Ethereum/index.js');
const uuidv4 = require('uuid/v4');
const Op = require('sequelize/lib/operators');
const deepExtend = require('deep-extend');
const Utilities = require('./Utilities');
const Models = require('../models');
const configjson = require('../config/config.json');
const defaultBlockchainConfig = Utilities.copyObject(configjson[
process.env.NODE_ENV &&
['development', 'testnet', 'mainnet'].indexOf(process.env.NODE_ENV) >= 0 ?
process.env.NODE_ENV : 'development'].blockchain);
class Blockchain {
/**
* Default constructor
* @param ctx IoC context
*/
constructor(ctx) {
this.log = ctx.logger;
this.emitter = ctx.emitter;
this.config = ctx.config.blockchain;
this.pluginService = ctx.blockchainPluginService;
this.gasStationService = ctx.gasStationService;
this.tracPriceService = ctx.tracPriceService;
this.appState = ctx.appState;
this.blockchain = [];
this.config = Blockchain.attachDefaultConfig(this.config, defaultBlockchainConfig);
for (let i = 0; i < this.config.implementations.length; i += 1) {
const implementation_configuration = this.config.implementations[i];
switch (implementation_configuration.blockchain_title) {
case 'Ethereum':
this.blockchain[i] = new Ethereum(ctx, implementation_configuration);
break;
default:
this.log.error('Unsupported blockchain', implementation_configuration.blockchain_title);
}
}
this.pluginService.bootstrap();
}
/**
* Initialize Blockchain provider
* @returns {Promise<void>}
*/
async loadContracts() {
try {
const promises = [];
for (let i = 0; i < this.blockchain.length; i += 1) {
promises.push(this.blockchain[i].loadContracts());
}
await Promise.all(promises);
} catch (e) {
this.log.warn(`Failed to load contracts on all blockchain implementations. ${e}`);
throw e;
}
if (!this.initalized) {
this.initalized = true;
this.subscribeToEventPermanentWithCallback([
'ContractsChanged',
], async (eventData) => {
this.log.notify('Contracts changed, refreshing information.');
await this.loadContracts();
});
}
}
initialize(blockchain_id) {
if (!blockchain_id) {
throw new Error('Cannot initialize blockchain implementation without blockchain_id');
}
const implementation = this._getImplementationFromId(blockchain_id, true);
implementation.initialize();
}
/**
* Attaches the default configuration for each blockchain implementation
* because the user defined blockchain configuration overwrites it on node startup
* @param config {Object} - The running blockchain configuration, with user defined values
* @param defaultConfig {Object} - The default blockchain configuration for current environment
* @returns {Object} - The new blockchain configuration
*/
static attachDefaultConfig(config, defaultConfig) {
const result = Object.assign({}, config);
if (config.implementations && defaultConfig.implementations
&& Array.isArray(config.implementations) && Array.isArray(defaultConfig.implementations)) {
const defaults = defaultConfig.implementations;
result.implementations = [];
for (const implUserConfig of config.implementations) {
if (!implUserConfig.blockchain_title) {
throw Error(`Blockchain implementation missing title.\nGiven config: ${JSON.stringify(implUserConfig, null, 4)}`);
}
const implDefaultConfig =
defaults.find(cfg => cfg.blockchain_title === implUserConfig.blockchain_title);
if (!implDefaultConfig) {
throw Error(`Unsupported blockchain ${implUserConfig.blockchain_title}`);
}
result.implementations.push(deepExtend({}, implDefaultConfig, implUserConfig));
}
}
return result;
}
/**
* Retrieves an implementation based on the given blockchain_id
* @param {String} blockchain_id - Blockchain implementation identifier string
* @param {Boolean} showUninitialized - Return implementations even if they aren't initialized
*/
_getImplementationFromId(blockchain_id, showUninitialized = false) {
if (!blockchain_id) {
return this._getDefaultImplementation(showUninitialized);
}
const implementation = this.blockchain.find(e => e.getBlockchainId() === blockchain_id);
if (implementation && (implementation.initialized || showUninitialized)) {
return implementation;
} else if (implementation) {
throw new Error(`Cannot return implementation for blockchain_id ${blockchain_id}. Implementation is not initialized.`);
} else {
throw new Error(`Cannot return implementation for blockchain_id ${blockchain_id}. Implementation not found.`);
}
}
/**
* Retrieves the default blockchain implementation
* @param {Boolean} showUninitialized - Return implementations even if they aren't initialized
*/
_getDefaultImplementation(showUninitialized = false) {
for (const implementation of this.blockchain) {
if (implementation.initialized || showUninitialized) return implementation;
}
throw new Error('Cannot return implementation. No implementation is initialized.');
}
/**
* Returns the blockchain id of every blockchain implementation
* @param {Boolean} showUninitialized - Return implementations even if they aren't initialized
* @returns {String} The identifier string of the default blockchain implementation
*/
getAllBlockchainIds(showUninitialized = false) {
const blockchainIds = [];
for (let i = 0; i < this.blockchain.length; i += 1) {
const implementation = this.blockchain[i];
if (implementation.initialized || showUninitialized) {
blockchainIds.push(implementation.getBlockchainId());
}
}
return blockchainIds;
}
/**
* Returns the blockchain id of the default blockchain implementation
* @param {Boolean} showUninitialized - Return implementations even if they aren't initialized
* @returns {String} The identifier string of the default blockchain implementation
*/
getDefaultBlockchainId(showUninitialized = false) {
const implementation = this._getDefaultImplementation(showUninitialized);
return implementation.getBlockchainId();
}
/**
* Executes specific plugin
* @param name - Plugin name
* @param data - Plugin data
* @return {Promise<void>}
*/
async executePlugin(name, data) {
return this.pluginService.execute(name, data);
}
/**
* Gets profile by wallet
* @param identity
* @param blockchain_id
* @param {Boolean} showUninitialized - Return all implementations, not only initialized ones
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
getProfile(identity, blockchain_id, showUninitialized = false) {
const implementation = this._getImplementationFromId(blockchain_id, showUninitialized);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getProfile(identity),
};
}
/**
* Set node ID
* @param identity
* @param nodeId
* @param blockchain_id
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
setNodeId(identity, nodeId, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.setNodeId(identity, nodeId),
};
}
/**
* Creates node profile on the Bidding contract
* @param managementWallet - Management wallet
* @param profileNodeId - Network node ID
* @param initialBalance - Initial profile balance
* @param isSender725 - Is sender ERC 725?
* @param blockchainIdentity - ERC 725 identity (empty if there is none)
* @param blockchain_id - Blockchain implementation to use
* @param {Boolean} showUninitialized - Return implementations even if they aren't initialized
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
createProfile(
managementWallet,
profileNodeId,
initialBalance,
isSender725,
blockchainIdentity,
blockchain_id,
showUninitialized = false,
) {
const implementation = this._getImplementationFromId(blockchain_id, showUninitialized);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.createProfile(
managementWallet,
profileNodeId, initialBalance, isSender725,
blockchainIdentity,
),
};
}
/**
* Gets minimum stake for creating a profile
* @param {String} blockchain_id - Blockchain implementation to use
* @param {Boolean} showUninitialized - Return implementations even if they aren't initialized
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
getProfileMinimumStake(blockchain_id, showUninitialized = false) {
const implementation = this._getImplementationFromId(blockchain_id, showUninitialized);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getProfileMinimumStake(),
};
}
/**
* Increase token approval for escrow contract
* @param {Number} tokenAmountIncrease - The amount of approval to increase in Abrashkin (mTRAC)
* @param {String} blockchain_id - Blockchain implementation to use
* @param {Boolean} showUninitialized - Return implementations even if they aren't initialized
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
increaseProfileApproval(tokenAmountIncrease, blockchain_id, showUninitialized = false) {
const implementation = this._getImplementationFromId(blockchain_id, showUninitialized);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.increaseProfileApproval(tokenAmountIncrease),
};
}
/**
* Initiate litigation for the particular DH
* @param offerId - Offer ID
* @param holderIdentity - DH identity
* @param litigatorIdentity - Litigator identity
* @param requestedObjectIndex - Order number of the object from the OT-dataset
* @param requestedBlockIndex - Order number of the block inside the sorted object
* @param hashArray - Merkle proof
* @param {string} blockchain_id - Blockchain implementation to use
* @return {Promise<any>}
*/
initiateLitigation(
offerId, holderIdentity, litigatorIdentity,
requestedObjectIndex, requestedBlockIndex, hashArray, blockchain_id,
) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.initiateLitigation(
offerId, holderIdentity, litigatorIdentity,
requestedObjectIndex, requestedBlockIndex, hashArray,
),
};
}
/**
* Completes litigation for the particular DH
* @param offerId - Offer ID
* @param holderIdentity - DH identity
* @param challengerIdentity - DC identity
* @param proofData - answer
* @param leafIndex - the number of the block in the lowest level of the merkle tree
* @param urgent - Whether max gas price should or not
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
completeLitigation(
offerId,
holderIdentity,
challengerIdentity,
proofData,
leafIndex,
urgent,
blockchain_id,
) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.completeLitigation(
offerId, holderIdentity,
challengerIdentity, proofData, leafIndex, urgent,
),
};
}
/**
* Answers litigation from DH side
* @param offerId
* @param holderIdentity
* @param answer
* @param urgent - Whether maximum gas price should be used
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
answerLitigation(offerId, holderIdentity, answer, urgent, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.answerLitigation(offerId, holderIdentity, answer, urgent),
};
}
/**
* Pay out tokens
* @param blockchainIdentity
* @param offerId
* @param urgent
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
payOut(blockchainIdentity, offerId, urgent, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.payOut(blockchainIdentity, offerId, urgent),
};
}
/**
* PayOut for multiple offers.
* @param {string} blockchainIdentity - Blockchain identity to use
* @param {string} offerIds - Offers to payOut
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
payOutMultiple(
blockchainIdentity,
offerIds,
blockchain_id,
) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.payOutMultiple(blockchainIdentity, offerIds),
};
}
/**
* Creates offer for the data storing on the Ethereum blockchain.
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
createOffer(
blockchainIdentity,
dataSetId,
dataRootHash,
redLitigationHash,
greenLitigationHash,
blueLitigationHash,
dcNodeId,
holdingTimeInMinutes,
tokenAmountPerHolder,
dataSizeInBytes,
litigationIntervalInMinutes,
urgent,
blockchain_id,
) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.createOffer(
blockchainIdentity,
dataSetId,
dataRootHash,
redLitigationHash,
greenLitigationHash,
blueLitigationHash,
dcNodeId,
holdingTimeInMinutes,
tokenAmountPerHolder,
dataSizeInBytes,
litigationIntervalInMinutes,
urgent,
),
};
}
/**
* Finalizes offer on Blockchain
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
finalizeOffer(
blockchainIdentity,
offerId,
shift,
confirmation1,
confirmation2,
confirmation3,
encryptionType,
holders,
parentIdentity,
urgent,
blockchain_id,
) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.finalizeOffer(
blockchainIdentity, offerId, shift, confirmation1,
confirmation2, confirmation3, encryptionType, holders, parentIdentity, urgent,
),
};
}
/**
* Subscribe to a particular event
* @param event
* @param importId
* @param endMs
* @param endCallback
* @param filterFn
* @param {string} blockchain_id - Blockchain implementation to use
*/
subscribeToEvent(event, importId, endMs = 5 * 60 * 1000, endCallback, filterFn, blockchain_id) {
return new Promise((resolve, reject) => {
let clearToken;
const token = setInterval(() => {
const where = {
event,
finished: 0,
};
if (importId) {
where.import_id = importId;
}
if (blockchain_id) {
where.blockchain_id = blockchain_id;
}
Models.events.findAll({
where,
}).then((events) => {
for (const eventData of events) {
const parsedData = JSON.parse(eventData.dataValues.data);
let ok = true;
if (filterFn) {
ok = filterFn(parsedData);
}
if (!ok) {
// eslint-disable-next-line
continue;
}
eventData.finished = true;
// eslint-disable-next-line no-loop-func
eventData.save().then(() => {
clearTimeout(clearToken);
clearInterval(token);
resolve(parsedData);
}).catch((err) => {
this.logger.error(`Failed to update event ${event}. ${err}`);
reject(err);
});
break;
}
});
}, 2000);
clearToken = setTimeout(() => {
if (endCallback) {
endCallback();
}
clearInterval(token);
resolve(null);
}, endMs);
});
}
/**
* Subscribes to Blockchain event
*
* Calling this method will subscribe to Blockchain's event which will be
* emitted globally using globalEmitter.
* @param event Event to listen to
* @param {string} blockchain_id - Blockchain implementation to listen to
* @returns {number | Object} Event handle
*/
async subscribeToEventPermanent(event, blockchain_id) {
const blockStartConditions = [];
if (blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
const startBlockNumber = await implementation.getCurrentBlock();
blockStartConditions.push({
blockchain_id,
block: { [Op.gte]: startBlockNumber },
});
} else {
const promises = [];
for (let i = 0; i < this.blockchain.length; i += 1) {
const implementation = this.blockchain[i];
promises.push(implementation.getCurrentBlock());
}
const currentBlocks = await Promise.all(promises);
for (let i = 0; i < currentBlocks.length; i += 1) {
const implementation = this.blockchain[i];
blockStartConditions.push({
blockchain_id: implementation.getBlockchainId(),
block: { [Op.gte]: currentBlocks[i] },
});
}
}
const that = this;
const handle = setInterval(async () => {
if (!that.appState.started) {
return;
}
const where = {
event,
finished: 0,
[Op.or]: blockStartConditions,
};
const eventData = await Models.events.findAll({ where });
if (eventData) {
eventData.forEach(async (data) => {
const dataToSend = JSON.parse(data.dataValues.data);
dataToSend.blockchain_id = data.dataValues.blockchain_id;
this.emitter.emit(`eth-${data.event}`, dataToSend);
data.finished = true;
await data.save();
});
}
}, 2000);
return handle;
}
/**
* Subscribes to Blockchain event with a callback specified
*
* Calling this method will subscribe to Blockchain's event which will be
* emitted globally using globalEmitter.
* Callback function will be executed when the event is emitted.
* @param event - Name of event to listen to
* @param callback - Function to be executed
* @param {string} blockchain_id - Blockchain implementation to listen to
* @returns {number | Object} Event handle
*/
async subscribeToEventPermanentWithCallback(event, callback, blockchain_id) {
const blockStartConditions = [];
if (blockchain_id) {
const implementation = this.blockchain.find(e => e.config.network_id === blockchain_id);
const startBlockNumber = await implementation.getCurrentBlock();
blockStartConditions.push({
blockchain_id,
block: { [Op.gte]: startBlockNumber },
});
} else {
const promises = [];
for (let i = 0; i < this.blockchain.length; i += 1) {
const implementation = this.blockchain[i];
promises.push(implementation.getCurrentBlock());
}
const currentBlocks = await Promise.all(promises);
for (let i = 0; i < currentBlocks.length; i += 1) {
const implementation = this.blockchain[i];
blockStartConditions.push({
blockchain_id: implementation.config.network_id,
block: { [Op.gte]: currentBlocks[i] },
});
}
}
const handle = setInterval(async () => {
const where = {
event,
finished: 0,
[Op.or]: blockStartConditions,
};
const eventData = await Models.events.findAll({ where });
if (eventData) {
eventData.forEach(async (data) => {
try {
callback({
name: `eth-${data.event}`,
value: JSON.parse(data.dataValues.data),
blockchain_id: data.blockchain_id,
});
data.finished = true;
await data.save();
} catch (error) {
this.logger.error(error);
}
});
}
}, 2000);
return handle;
}
/**
* Gets all past events for the contract
* @param contractName
*/
async getAllPastEvents(contractName) {
const promises = [];
for (let i = 0; i < this.blockchain.length; i += 1) {
const implementation = this.blockchain[i];
const blockchain_id = this.blockchain[i].config.network_id;
promises.push(this
.getEventsFromImplementation(implementation, blockchain_id, contractName)
.then((result) => {
this.handleReceivedEvents(result, contractName, blockchain_id);
}));
}
await Promise.all(promises);
}
async getEventsFromImplementation(implementation, blockchain_id, contractName) {
let fromBlock = 0;
// Find last queried block if any.
const lastEvent = await Models.events.findOne({
where: {
contract: contractName,
blockchain_id,
},
order: [
['block', 'DESC'],
],
});
const currentBlock = await implementation.getCurrentBlock();
if (lastEvent) {
fromBlock = Math.max(currentBlock - 2000, lastEvent.block + 1);
} else {
fromBlock = Math.max(currentBlock - 100, 0);
}
return implementation.getAllPastEvents(contractName, fromBlock);
}
async handleReceivedEvents(events, contractName, blockchain_id) {
for (let i = 0; events && i < events.length; i += 1) {
const event = events[i];
const timestamp = Date.now();
if (event.returnValues.DH_wallet) {
event.returnValues.DH_wallet = event.returnValues.DH_wallet.toLowerCase();
}
/* eslint-disable-next-line */
await Models.events.create({
id: uuidv4(),
contract: contractName,
event: event.event,
data: JSON.stringify(event.returnValues),
data_set_id: Utilities.normalizeHex(event.returnValues.dataSetId),
block: event.blockNumber,
blockchain_id,
timestamp,
finished: 0,
});
}
const twoWeeksAgo = new Date();
twoWeeksAgo.setDate(twoWeeksAgo.getDate() - 14);
// Delete old events
await Models.events.destroy({
where: {
timestamp: {
[Op.lt]: twoWeeksAgo.getTime(),
},
finished: 1,
},
});
}
/**
* Total amount of tokens paid out for node
* @param {string} identity
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
getTotalPayouts(identity, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getTotalPayouts(identity),
};
}
/**
* Gets token balance of a particular wallet
* @param {string} wallet
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
getWalletTokenBalance(wallet, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getWalletTokenBalance(wallet),
};
}
/**
* Gets base (eg ETH) balance of a particular wallet
* @param {string} wallet
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
getWalletBaseBalance(wallet, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getWalletBaseBalance(wallet),
};
}
/**
* Deposits tokens to the profile
* @param blockchainIdentity
* @param amount
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
depositTokens(blockchainIdentity, amount, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.depositTokens(blockchainIdentity, amount),
};
}
/**
* Gets the root hash (fingerprint) written in the blockchain for a given dataset
* @param {string} dataSetId - Data set ID
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
getRootHash(dataSetId, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getRootHash(dataSetId),
};
}
/**
* Gets purchase object from blockchain
* @param {string} purchaseId
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
getPurchase(purchaseId, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getPurchase(purchaseId),
};
}
/**
* Gets purchase status from blockchain
* @param {string} purchaseId
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
getPurchaseStatus(purchaseId, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getPurchaseStatus(purchaseId),
};
}
/**
* Gets the duration of a purchase stage from blockchain
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
getPaymentStageInterval(blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getPaymentStageInterval(),
};
}
/**
* Gets the duration of a purchase stage from blockchain
* @param {string} sellerIdentity - Seller's blockchain identity
* @param {string} buyerIdentity - Buyer's blockchain identity
* @param {string} tokenAmount - The token amount for purchase
* @param {string} originalDataRootHash - The root hash of the data in its original form
* @param {string} encodedDataRootHash - The root hash of the data in its encoded form
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/
initiatePurchase(
sellerIdentity, buyerIdentity,
tokenAmount, originalDataRootHash, encodedDataRootHash, blockchain_id,
) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.initiatePurchase(
sellerIdentity, buyerIdentity,
tokenAmount, originalDataRootHash, encodedDataRootHash,
),
};
}
/**
* Decodes offer task event data from offer creation event
* @param result Blockchain transaction receipt
* @param {string} blockchain_id - Blockchain implementation to use
* @returns {Promise<any>}
*/
decodePurchaseInitiatedEventFromTransaction(result, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.decodePurchaseInitiatedEventFromTransaction(result),
};
}
depositKey(purchaseId, key, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.depositKey(purchaseId, key),
};
}
takePayment(purchaseId, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.takePayment(purchaseId),
};
}
complainAboutNode(
purchaseId, outputIndex, inputIndexLeft, encodedOutput, encodedInputLeft,
proofOfEncodedOutput, proofOfEncodedInputLeft, urgent, blockchain_id,
) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.complainAboutNode(
purchaseId, outputIndex, inputIndexLeft, encodedOutput, encodedInputLeft,
proofOfEncodedOutput, proofOfEncodedInputLeft, urgent,
),
};
}
complainAboutRoot(
purchaseId, encodedRootHash, proofOfEncodedRootHash, rootHashIndex,
urgent, blockchain_id,
) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.complainAboutRoot(
purchaseId, encodedRootHash, proofOfEncodedRootHash, rootHashIndex,
urgent,
),
};
}
/**
* Start token withdrawal operation
* @param blockchainIdentity
* @param amount
* @param {string} blockchain_id - Blockchain implementation to use
* @return {Promise<any>}
*/
startTokenWithdrawal(blockchainIdentity, amount, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.startTokenWithdrawal(blockchainIdentity, amount),
};
}
/**
* Start token withdrawal operation
* @param blockchainIdentity
* @param {string} blockchain_id - Blockchain implementation to use
* @return {Promise<any>}
*/
withdrawTokens(blockchainIdentity, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.withdrawTokens(blockchainIdentity),
};
}
/**
* Get difficulty for the particular offer
* @param {string} offerId, Offer id to get difficulty for
* @param {string} blockchain_id - Blockchain implementation to use
*/
getOfferDifficulty(offerId, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getOfferDifficulty(offerId),
};
}
/**
* Token contract address getter
* @param {string} blockchain_id - Blockchain implementation to use
* @return {any|*}
*/
getTokenContractAddress(blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getTokenContractAddress(),
};
}
/**
* Returns purposes of the wallet for a given identity.
* @param {String} erc725Identity - The identity contract to check
* @param {String} wallet - The wallet whose purposes will be checked
* @param {String} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
* which resolves to an array of numbers
*/
getWalletPurposes(erc725Identity, wallet, blockchain_id) {
const implementation = this._getImplementationFromId(blockchain_id);
return {
blockchain_id: implementation.getBlockchainId(),
response: implementation.getWalletPurposes(erc725Identity, wallet),
};
}
/**
* Get offer by ID
* @param {String} offerId - OfferId hex string
* @param {String} blockchain_id - Blockchain implementation to use
* @returns {Object} - An object containing the blockchain_id string and the response promise
*/