This repository has been archived by the owner on Jun 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 70
/
liskApi.js
731 lines (620 loc) · 17.1 KB
/
liskApi.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
/*
* Copyright © 2017 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*
*/
/**
* LiskAPI module provides functions for interfacing with the Lisk network. Providing mechanisms for:
*
* - Retrieval of blockchain data: accounts, blocks, transactions.
* - Enhancing Lisk security by local signing of transactions and immediate network transmission.
* - Connecting to Lisk peers or to localhost instance of Lisk core.
* - Configurable network settings to work in different Lisk environments.
*
* var options = {
* ssl: false,
* node: '',
* randomPeer: true,
* testnet: true,
* port: '7000',
* bannedPeers: [],
* nethash: ''
* };
*
* var lisk = require('lisk-js');
* var LSK = lisk.api(options);
*
* @class lisk.api()
* @main lisk
*/
var LiskJS = {};
LiskJS.crypto = require('../transactions/crypto');
var parseOfflineRequest = require('./parseTransaction');
var popsicle = require('popsicle');
function LiskAPI (options) {
if (!(this instanceof LiskAPI)) {
return new LiskAPI(options);
}
options = options || {};
this.defaultPeers = [
'node01.lisk.io',
'node02.lisk.io',
'node03.lisk.io',
'node04.lisk.io',
'node05.lisk.io',
'node06.lisk.io',
'node07.lisk.io',
'node08.lisk.io'
];
this.defaultSSLPeers = this.defaultPeers;
this.defaultTestnetPeers = [
'testnet.lisk.io'
];
this.options = options;
this.ssl = options.ssl || false;
// Random peer can be set by settings with randomPeer: true | false
// Random peer is automatically enabled when no options.node has been entered. Else will be set to false
// If the desired behaviour is to have an own node and automatic peer discovery, randomPeer should be set to true explicitly
this.randomPeer = (typeof options.randomPeer === 'boolean') ? options.randomPeer : !(options.node);
this.testnet = options.testnet || false;
this.bannedPeers = [];
this.currentPeer = options.node || this.selectNode();
this.port = (options.port === '' || options.port) ? options.port : (options.testnet) ? 7000 : 8000;
this.parseOfflineRequests = parseOfflineRequest;
this.nethash = this.getNethash(options.nethash);
}
/**
* @method netHashOptions
* @return {object}
*/
LiskAPI.prototype.netHashOptions = function () {
return {
testnet: {
'Content-Type': 'application/json',
'nethash': 'da3ed6a45429278bac2666961289ca17ad86595d33b31037615d4b8e8f158bba',
'broadhash': 'da3ed6a45429278bac2666961289ca17ad86595d33b31037615d4b8e8f158bba',
'os': 'lisk-js-api',
'version': '1.0.0',
'minVersion': '>=0.5.0',
'port': this.port
},
mainnet: {
'Content-Type': 'application/json',
'nethash': 'ed14889723f24ecc54871d058d98ce91ff2f973192075c0155ba2b7b70ad2511',
'broadhash': 'ed14889723f24ecc54871d058d98ce91ff2f973192075c0155ba2b7b70ad2511',
'os': 'lisk-js-api',
'version': '1.0.0',
'minVersion': '>=0.5.0',
'port': this.port
}
};
};
/**
* @method getNethash
* @return {object}
*/
LiskAPI.prototype.getNethash = function (providedNethash) {
var NetHash = (this.testnet) ? this.netHashOptions().testnet : this.netHashOptions().mainnet;
if (providedNethash) {
NetHash.nethash = providedNethash;
NetHash.version = '0.0.0a';
}
return NetHash;
};
/**
* @method listPeers
* @return {object}
*/
LiskAPI.prototype.listPeers = function () {
return {
official: this.defaultPeers.map(function (node) { return {node: node};}),
ssl: this.defaultSSLPeers.map(function (node) { return {node: node, ssl: true, port: 443};}),
testnet: this.defaultTestnetPeers.map(function (node) { return {node: node, testnet: true, port: 7000};}),
};
};
/**
* @method setNode
* @param node string
* @return {object}
*/
LiskAPI.prototype.setNode = function (node) {
this.currentPeer = node || this.selectNode();
return this.currentPeer;
};
/**
* @method setTestnet
* @param testnet boolean
*/
LiskAPI.prototype.setTestnet = function (testnet) {
if (this.testnet !== testnet) {
this.testnet = testnet;
this.bannedPeers = [];
this.port = 7000;
this.selectNode();
} else {
this.testnet = false;
this.bannedPeers = [];
this.port = 8000;
this.selectNode();
}
};
/**
* @method setSSL
* @param ssl boolean
*/
LiskAPI.prototype.setSSL = function (ssl) {
if (this.ssl !== ssl) {
this.ssl = ssl;
this.bannedPeers = [];
this.selectNode();
}
};
/**
* @method getFullUrl
* @return url string
*/
LiskAPI.prototype.getFullUrl = function () {
var nodeUrl = this.currentPeer;
if (this.port) {
nodeUrl += ':'+this.port;
}
return this.getURLPrefix() + '://' + nodeUrl;
};
/**
* @method getURLPrefix
* @return prefix string
*/
LiskAPI.prototype.getURLPrefix = function () {
if (this.ssl) {
return 'https';
} else {
return 'http';
}
};
/**
* @method selectNode
* @return peer string
*/
LiskAPI.prototype.selectNode = function () {
var currentRandomPeer;
if (this.options.node) {
currentRandomPeer = this.currentPeer;
}
if (this.randomPeer) {
currentRandomPeer = this.getRandomPeer();
var peers = (this.ssl) ? this.defaultSSLPeers : this.defaultPeers;
if (this.testnet) peers = this.defaultTestnetPeers;
for (var x = 0; x< peers.length; x++) {
if (this.bannedPeers.indexOf(currentRandomPeer) === -1) break;
currentRandomPeer = this.getRandomPeer();
}
}
return currentRandomPeer;
};
/**
* @method getRandomPeer
* @return peer string
*/
LiskAPI.prototype.getRandomPeer = function () {
var peers = (this.ssl) ? this.defaultSSLPeers : this.defaultPeers;
if (this.testnet) peers = this.defaultTestnetPeers;
var getRandomNumberForPeer = Math.floor((Math.random() * peers.length));
return peers[getRandomNumberForPeer];
};
/**
* @method banNode
*/
LiskAPI.prototype.banNode = function () {
if (this.bannedPeers.indexOf(this.currentPeer) === -1) this.bannedPeers.push(this.currentPeer);
this.selectNode();
};
/**
* @method checkReDial
* @return reDial boolean
*/
LiskAPI.prototype.checkReDial = function () {
var peers = (this.ssl) ? this.defaultSSLPeers : this.defaultPeers;
if (this.testnet) peers = this.defaultTestnetPeers;
var reconnect = true;
// RandomPeer discovery explicitly set
if (this.randomPeer === true) {
// A nethash has been set by the user. This influences internal redirection
if (this.options.nethash) {
// Nethash is equal to testnet nethash, we can proceed to get testnet peers
if (this.options.nethash === this.netHashOptions().testnet.nethash) {
this.setTestnet(true);
reconnect = true;
// Nethash is equal to mainnet nethash, we can proceed to get mainnet peers
} else if (this.options.nethash === this.netHashOptions().mainnet.nethash) {
this.setTestnet(false);
reconnect = true;
// Nethash is neither mainnet nor testnet, do not proceed to get peers
} else {
reconnect = false;
}
// No nethash set, we can take the usual approach, just when there are not-banned peers, take one
} else {
reconnect = (peers.length !== this.bannedPeers.length);
}
// RandomPeer is not explicitly set, no peer discovery
} else {
reconnect = false;
}
return reconnect;
};
/**
* @method checkOptions
* @return options object
*/
LiskAPI.prototype.checkOptions = function (options) {
Object.keys(options).forEach(function (optionKey) {
if (options[optionKey] === undefined || options[optionKey] !== options[optionKey]) {
throw { message: 'parameter value "'+optionKey+'" should not be '+ options[optionKey] };
}
});
return options;
};
/**
* @method sendRequest
* @param requestType
* @param options
* @param callback
*
* @return APIanswer Object
*/
LiskAPI.prototype.sendRequest = function (requestType, options, callback) {
callback = callback || options;
options = typeof options !== 'function' && typeof options !== 'undefined' ? this.checkOptions(options) : {};
var that = this;
return this.sendRequestPromise(requestType, options).then(function (requestSuccess) {
var returnAnswer = (parseOfflineRequest(requestType, options).requestMethod === 'GET') ? requestSuccess.body : parseOfflineRequest(requestType, options).transactionOutputAfter(requestSuccess.body);
if (!callback || (typeof callback !== 'function')) {
return Promise.resolve(returnAnswer);
} else {
return callback(returnAnswer);
}
}).then(function (API) {
return API;
}, function (error) {
return Promise.reject(error);
}).catch(function (error) {
if (that.checkReDial()) {
setTimeout(function () {
that.banNode();
that.setNode();
that.sendRequest(requestType, options, callback);
}, 1000);
} else {
var rejectAnswer = { success: false, error: error, message: 'could not create http request to any of the given peers' };
if (!callback || (typeof callback !== 'function')) {
return rejectAnswer;
} else {
return callback(rejectAnswer);
}
}
});
};
/**
* @method sendRequestPromise
* @param requestType
* @param options
*
* @return APIcall Promise
*/
LiskAPI.prototype.sendRequestPromise = function (requestType, options) {
if (this.checkRequest(requestType, options) !== 'NOACTION') {
var requestValues = this.changeRequest(requestType, options);
return this.doPopsicleRequest(requestValues);
} else {
return new Promise(function (resolve) {
resolve({ done: 'done'});
});
}
};
/**
* @method doPopsicleRequest
* @param requestValue
*
* @return APIcall Promise
*/
LiskAPI.prototype.doPopsicleRequest = function (requestValue) {
return popsicle.request({
method: requestValue.requestMethod,
url: requestValue.requestUrl,
headers: requestValue.nethash,
body: requestValue.requestMethod !== 'GET' ? requestValue.requestParams : ''
}).use(popsicle.plugins.parse(['json', 'urlencoded']));
};
/**
* @method doPopsicleRequest
* @param requestType
* @param options
*
* @return httpRequest object
*/
LiskAPI.prototype.changeRequest = function (requestType, options) {
var returnValue = {
requestMethod: '',
requestUrl: '',
nethash: '',
requestParams: ''
};
var that = this;
switch(this.checkRequest(requestType, options)) {
case 'GET':
returnValue.requestMethod = 'GET';
returnValue.requestUrl = this.getFullUrl() + '/api/' + requestType;
if (Object.keys(options).length > 0) {
returnValue.requestUrl = returnValue.requestUrl + that.serialiseHttpData(options, returnValue.requestMethod);
}
returnValue.requestParams = options;
break;
case 'PUT':
case 'POST':
var transformRequest = parseOfflineRequest(requestType, options).checkOfflineRequestBefore();
if (transformRequest.requestUrl === 'transactions' || transformRequest.requestUrl === 'signatures') {
returnValue.requestUrl = that.getFullUrl() + '/peer/'+ transformRequest.requestUrl;
returnValue.nethash = that.nethash;
returnValue.requestMethod = 'POST';
returnValue.requestParams = transformRequest.params;
} else {
returnValue.requestUrl = that.getFullUrl() + '/api/'+ transformRequest.requestUrl;
returnValue.requestMethod = transformRequest.requestMethod;
returnValue.requestParams = options;
}
break;
default:
break;
}
return returnValue;
};
/**
* @method checkRequest
* @param requestType
* @param options
*
* @return method string
*/
LiskAPI.prototype.checkRequest = function (requestType, options) {
return parseOfflineRequest(requestType, options).requestMethod;
};
/**
* @method serialiseHttpData
* @param data
*
* @return serialisedData string
*/
LiskAPI.prototype.serialiseHttpData = function (data) {
var serialised;
serialised = this.trimObj(data);
serialised = this.toQueryString(serialised);
serialised = encodeURI(serialised);
return '?'+serialised;
};
/**
* @method trimObj
* @param obj
*
* @return trimmed string
*/
LiskAPI.prototype.trimObj = function (obj) {
if (!Array.isArray(obj) && typeof obj !== 'object') return obj;
return Object.keys(obj).reduce(function (acc, key) {
acc[key.trim()] = (typeof obj[key] === 'string') ? obj[key].trim() : (Number.isInteger(obj[key])) ? obj[key].toString() : this.trimObj(obj[key]);
return acc;
}, Array.isArray(obj)? []:{});
};
/**
* @method toQueryString
* @param obj
*
* @return query string
*/
LiskAPI.prototype.toQueryString = function (obj) {
var parts = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
parts.push(encodeURIComponent(i) + '=' + encodeURI(obj[i]));
}
}
return parts.join('&');
};
/**
* @method getAddressFromSecret
* @param secret
*
* @return keys object
*/
LiskAPI.prototype.getAddressFromSecret = function (secret) {
var accountKeys = LiskJS.crypto.getKeys(secret);
var accountAddress = LiskJS.crypto.getAddress(accountKeys.publicKey);
return {
address: accountAddress,
publicKey: accountKeys.publicKey
};
};
/**
* @method getAccount
* @param address
* @param callback
*
* @return API object
*/
LiskAPI.prototype.getAccount = function (address, callback) {
this.sendRequest('accounts', { address: address }, function (result) {
return callback(result);
});
};
/**
* @method listActiveDelegates
* @param limit
* @param callback
*
* @return API object
*/
LiskAPI.prototype.listActiveDelegates = function (limit, callback) {
this.sendRequest('delegates/', { limit: limit}, function (result) {
return callback(result);
});
};
/**
* @method listStandbyDelegates
* @param limit
* @param callback
*
* @return API object
*/
LiskAPI.prototype.listStandbyDelegates = function (limit, callback) {
var standByOffset = 101;
this.sendRequest('delegates/', { limit: limit, orderBy: 'rate:asc', offset: standByOffset}, function (result) {
return callback(result);
});
};
/**
* @method searchDelegateByUsername
* @param username
* @param callback
*
* @return API object
*/
LiskAPI.prototype.searchDelegateByUsername = function (username, callback) {
this.sendRequest('delegates/search/', { q: username }, function (result) {
return callback(result);
});
};
/**
* @method listBlocks
* @param amount
* @param callback
*
* @return API object
*/
LiskAPI.prototype.listBlocks = function (amount, callback) {
this.sendRequest('blocks', { limit: amount }, function (result) {
return callback(result);
});
};
/**
* @method listForgedBlocks
* @param publicKey
* @param callback
*
* @return API object
*/
LiskAPI.prototype.listForgedBlocks = function (publicKey, callback) {
this.sendRequest('blocks', { generatorPublicKey: publicKey }, function (result) {
return callback(result);
});
};
/**
* @method getBlock
* @param block
* @param callback
*
* @return API object
*/
LiskAPI.prototype.getBlock = function (block, callback) {
this.sendRequest('blocks', { height: block }, function (result) {
return callback(result);
});
};
/**
* @method listTransactions
* @param address
* @param limit
* @param offset
* @param callback
*
* @return API object
*/
LiskAPI.prototype.listTransactions = function (address, limit, offset, callback) {
offset = offset || '0';
limit = limit || '20';
this.sendRequest('transactions', { senderId: address, recipientId: address, limit: limit, offset: offset, orderBy: 'timestamp:desc' }, function (result) {
return callback(result);
});
};
/**
* @method getTransaction
* @param transactionId
* @param callback
*
* @return API object
*/
LiskAPI.prototype.getTransaction = function (transactionId, callback) {
this.sendRequest('transactions/get', { id: transactionId }, function (result) {
return callback(result);
});
};
/**
* @method listVotes
* @param address
* @param callback
*
* @return API object
*/
LiskAPI.prototype.listVotes = function (address, callback) {
this.sendRequest('accounts/delegates', { address: address }, function (result) {
return callback(result);
});
};
/**
* @method listVoters
* @param publicKey
* @param callback
*
* @return API object
*/
LiskAPI.prototype.listVoters = function (publicKey, callback) {
this.sendRequest('delegates/voters', { publicKey: publicKey }, function (result) {
return callback(result);
});
};
/**
* @method sendLSK
* @param recipient
* @param amount
* @param secret
* @param secondSecret
* @param callback
*
* @return API object
*/
LiskAPI.prototype.sendLSK = function (recipient, amount, secret, secondSecret, callback) {
this.sendRequest('transactions', { recipientId: recipient, amount: amount, secret: secret, secondSecret: secondSecret }, function (response) {
return callback(response);
});
};
/**
* @method listMultisignatureTransactions
* @param callback
*
* @return API object
*/
LiskAPI.prototype.listMultisignatureTransactions = function (callback) {
this.sendRequest('transactions/multisignatures', function (result) {
return callback(result);
});
};
/**
* @method getMultisignatureTransaction
* @param transactionId
* @param callback
*
* @return API object
*/
LiskAPI.prototype.getMultisignatureTransaction = function (transactionId, callback) {
this.sendRequest('transactions/multisignatures/get', { id: transactionId }, function (result) {
return callback(result);
});
};
module.exports = LiskAPI;