This repository has been archived by the owner on Sep 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 287
/
api.js
1997 lines (1486 loc) · 57.9 KB
/
api.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
var apiCommands = require('./apiCommands')
var errors = require('../errors/inputErrors');
var inputValidator = require('../utils/inputValidator');
var HMAC = require("../crypto/hmac/hmac");
var Converter = require("../crypto/converter/converter");
var Signing = require("../crypto/signing/signing");
var Bundle = require("../crypto/bundle/bundle");
var Utils = require("../utils/utils");
var async = require("async");
'use strict';
var nullHashTrytes = (new Array(244).join('9'));
/**
* Making API requests, including generalized wrapper functions
**/
function api(provider, isSandbox) {
this._makeRequest = provider;
this.sandbox = isSandbox;
}
/**
* General function that makes an HTTP request to the local node
*
* @method sendCommand
* @param {object} command
* @param {function} callback
* @returns {object} success
**/
api.prototype.sendCommand = function(command, callback) {
var commandsToBatch = ['findTransactions', 'getBalances', 'getInclusionStates', 'getTrytes']
var commandKeys = ['addresses', 'bundles', 'hashes', 'tags', 'transactions', 'approvees']
var batchSize = 1000
if (commandsToBatch.indexOf(command.command) > -1) {
var keysToBatch = Object.keys(command)
.filter(function (key) {
return commandKeys.indexOf(key) > -1 && command[key].length > batchSize
})
if (keysToBatch.length) {
return this._makeRequest.batchedSend(command, keysToBatch, batchSize, callback)
}
}
return this._makeRequest.send(command, callback);
}
/**
* @method attachToTangle
* @param {string} trunkTransaction
* @param {string} branchTransaction
* @param {integer} minWeightMagnitude
* @param {array} trytes
* @returns {function} callback
* @returns {object} success
**/
api.prototype.attachToTangle = function(trunkTransaction, branchTransaction, minWeightMagnitude, trytes, callback) {
// inputValidator: Check if correct hash
if (!inputValidator.isHash(trunkTransaction)) {
return callback(errors.invalidTrunkOrBranch(trunkTransaction));
}
// inputValidator: Check if correct hash
if (!inputValidator.isHash(branchTransaction)) {
return callback(errors.invalidTrunkOrBranch(branchTransaction));
}
// inputValidator: Check if int
if (!inputValidator.isValue(minWeightMagnitude)) {
return callback(errors.notInt());
}
// inputValidator: Check if array of trytes
if (!inputValidator.isArrayOfTrytes(trytes)) {
return callback(errors.invalidTrytes());
}
var command = apiCommands.attachToTangle(trunkTransaction, branchTransaction, minWeightMagnitude, trytes)
return this.sendCommand(command, callback)
}
/**
* @method findTransactions
* @param {object} searchValues
* @returns {function} callback
* @returns {object} success
**/
api.prototype.findTransactions = function(searchValues, callback) {
// If not an object, return error
if (!inputValidator.isObject(searchValues)) {
return callback(errors.invalidKey());
}
// Get search key from input object
var searchKeys = Object.keys(searchValues);
var availableKeys = ['bundles', 'addresses', 'tags', 'approvees'];
var keyError = false;
searchKeys.forEach(function(key) {
if (availableKeys.indexOf(key) === -1) {
keyError = errors.invalidKey();
return
}
if (key === 'addresses') {
searchValues.addresses = searchValues.addresses.map(function(address) {
return Utils.noChecksum(address)
});
}
var hashes = searchValues[key];
// If tags, append to 27 trytes
if (key === 'tags') {
searchValues.tags = hashes.map(function(hash) {
// Simple padding to 27 trytes
while (hash.length < 27) {
hash += '9';
}
// validate hash
if (!inputValidator.isTrytes(hash, 27)) {
keyError = errors.invalidTrytes();
return
}
return hash;
})
} else {
// Check if correct array of hashes
if (!inputValidator.isArrayOfHashes(hashes)) {
keyError = errors.invalidTrytes();
return
}
}
})
// If invalid key found, return
if (keyError) {
callback(keyError);
return
}
var command = apiCommands.findTransactions(searchValues);
return this.sendCommand(command, callback)
}
/**
* @method getBalances
* @param {array} addresses
* @param {int} threshold
* @returns {function} callback
* @returns {object} success
**/
api.prototype.getBalances = function(addresses, threshold, callback) {
// Check if correct transaction hashes
if (!inputValidator.isArrayOfHashes(addresses)) {
return callback(errors.invalidTrytes());
}
var command = apiCommands.getBalances(addresses.map(function(address) {
return Utils.noChecksum(address)
}), threshold);
return this.sendCommand(command, callback)
}
/**
* @method getInclusionStates
* @param {array} transactions
* @param {array} tips
* @returns {function} callback
* @returns {object} success
**/
api.prototype.getInclusionStates = function(transactions, tips, callback) {
// Check if correct transaction hashes
if (!inputValidator.isArrayOfHashes(transactions)) {
return callback(errors.invalidTrytes());
}
// Check if correct tips
if (!inputValidator.isArrayOfHashes(tips)) {
return callback(errors.invalidTrytes());
}
var command = apiCommands.getInclusionStates(transactions, tips);
return this.sendCommand(command, callback)
}
/**
* @method getNodeInfo
* @returns {function} callback
* @returns {object} success
**/
api.prototype.getNodeInfo = function(callback) {
var command = apiCommands.getNodeInfo();
return this.sendCommand(command, callback)
}
/**
* @method getNeighbors
* @returns {function} callback
* @returns {object} success
**/
api.prototype.getNeighbors = function(callback) {
var command = apiCommands.getNeighbors();
return this.sendCommand(command, callback)
}
/**
* @method addNeighbors
* @param {Array} uris List of URI's
* @returns {function} callback
* @returns {object} success
**/
api.prototype.addNeighbors = function(uris, callback) {
// Validate URIs
for (var i = 0; i < uris.length; i++) {
if (!inputValidator.isUri(uris[i])) return callback(errors.invalidUri(uris[i]));
}
var command = apiCommands.addNeighbors(uris);
return this.sendCommand(command, callback)
}
/**
* @method removeNeighbors
* @param {Array} uris List of URI's
* @returns {function} callback
* @returns {object} success
**/
api.prototype.removeNeighbors = function(uris, callback) {
// Validate URIs
for (var i = 0; i < uris.length; i++) {
if (!inputValidator.isUri(uris[i])) return callback(errors.invalidUri(uris[i]));
}
var command = apiCommands.removeNeighbors(uris);
return this.sendCommand(command, callback)
}
/**
* @method getTips
* @returns {function} callback
* @returns {object} success
**/
api.prototype.getTips = function(callback) {
var command = apiCommands.getTips();
return this.sendCommand(command, callback)
}
/**
* @method getTransactionsToApprove
* @param {int} depth
* @param {string} reference
* @returns {function} callback
* @returns {object} success
**/
api.prototype.getTransactionsToApprove = function(depth, reference, callback) {
// Check if correct depth
if (!inputValidator.isValue(depth)) {
return callback(errors.invalidInputs());
}
var command = apiCommands.getTransactionsToApprove(depth, reference);
return this.sendCommand(command, callback)
}
/**
* @method getTrytes
* @param {array} hashes
* @returns {function} callback
* @returns {object} success
**/
api.prototype.getTrytes = function(hashes, callback) {
if (!inputValidator.isArrayOfHashes(hashes)) {
return callback(errors.invalidTrytes());
}
var command = apiCommands.getTrytes(hashes);
return this.sendCommand(command, callback)
}
/**
* @method interruptAttachingToTangle
* @returns {function} callback
* @returns {object} success
**/
api.prototype.interruptAttachingToTangle = function(callback) {
var command = apiCommands.interruptAttachingToTangle();
return this.sendCommand(command, callback)
}
/**
* @method broadcastTransactions
* @param {array} trytes
* @returns {function} callback
* @returns {object} success
**/
api.prototype.broadcastTransactions = function(trytes, callback) {
if (!inputValidator.isArrayOfAttachedTrytes(trytes)) {
return callback(errors.invalidAttachedTrytes());
}
var command = apiCommands.broadcastTransactions(trytes);
return this.sendCommand(command, callback)
}
/**
* @method storeTransactions
* @param {array} trytes
* @returns {function} callback
* @returns {object} success
**/
api.prototype.storeTransactions = function(trytes, callback) {
if (!inputValidator.isArrayOfAttachedTrytes(trytes)) {
return callback(errors.invalidAttachedTrytes());
}
var command = apiCommands.storeTransactions(trytes);
return this.sendCommand(command, callback)
}
/*************************************
WRAPPER AND CUSTOM FUNCTIONS
**************************************/
/**
* Wrapper function for getTrytes and transactionObjects
* gets the trytes and transaction object from a list of transaction hashes
*
* @method getTransactionsObjects
* @param {array} hashes
* @returns {function} callback
* @returns {object} success
**/
api.prototype.getTransactionsObjects = function(hashes, callback) {
// If not array of hashes, return error
if (!inputValidator.isArrayOfHashes(hashes)) {
return callback(errors.invalidInputs());
}
// get the trytes of the transaction hashes
this.getTrytes(hashes, function(error, trytes) {
if (error) return callback(error);
var transactionObjects = [];
// call transactionObjects for each trytes
trytes.forEach(function(thisTrytes) {
// If no trytes returned, simply push null as placeholder
if (!thisTrytes) {
transactionObjects.push(null);
} else {
transactionObjects.push(Utils.transactionObject(thisTrytes));
}
})
return callback(null, transactionObjects);
})
}
/**
* Wrapper function for findTransactions, getTrytes and transactionObjects
* Returns the transactionObject of a transaction hash. The input can be a valid
* findTransactions input
*
* @method getTransactionsObjects
* @param {object} input
* @returns {function} callback
* @returns {object} success
**/
api.prototype.findTransactionObjects = function(input, callback) {
var self = this;
self.findTransactions(input, function(error, transactions) {
if (error) return callback(error);
// get the transaction objects of the transactions
self.getTransactionsObjects(transactions, callback);
})
}
/**
* Wrapper function for getNodeInfo and getInclusionStates
*
* @method getLatestInclusion
* @param {array} hashes
* @returns {function} callback
* @returns {object} success
**/
api.prototype.getLatestInclusion = function(hashes, callback) {
var self = this;
self.getNodeInfo(function(e, nodeInfo) {
if (e) return callback(e);
var latestMilestone = nodeInfo.latestSolidSubtangleMilestone;
return self.getInclusionStates(hashes, Array(latestMilestone), callback);
})
}
/**
* Broadcasts and stores transaction trytes
*
* @method storeAndBroadcast
* @param {array} trytes
* @returns {function} callback
* @returns {object} success
**/
api.prototype.storeAndBroadcast = function(trytes, callback) {
var self = this;
self.storeTransactions(trytes, function(error, success) {
if (error) return callback(error);
// If no error
return self.broadcastTransactions(trytes, callback)
})
}
/**
* Gets transactions to approve, attaches to Tangle, broadcasts and stores
*
* @method sendTrytes
* @param {array} trytes
* @param {int} depth
* @param {int} minWeightMagnitude
* @param {object} options
* @param {function} callback
* @returns {object} analyzed Transaction objects
**/
api.prototype.sendTrytes = function(trytes, depth, minWeightMagnitude, options, callback) {
var self = this;
// If no options provided, switch arguments
if (arguments.length === 4 && Object.prototype.toString.call(options) === "[object Function]") {
callback = options;
options = {};
}
// Check if correct depth and minWeightMagnitude
if (!inputValidator.isValue(depth) || !inputValidator.isValue(minWeightMagnitude)) {
return callback(errors.invalidInputs());
}
// Get branch and trunk
self.getTransactionsToApprove(depth, options.reference, function(error, toApprove) {
if (error) {
return callback(error)
}
// attach to tangle - do pow
self.attachToTangle(toApprove.trunkTransaction, toApprove.branchTransaction, minWeightMagnitude, trytes, function(error, attached) {
if (error) {
return callback(error)
}
// If the user is connected to the sandbox, we have to monitor the POW queue
// to check if the POW job was completed
if (self.sandbox) {
var job = self.sandbox + '/jobs/' + attached.id;
// Do the Sandbox send function
self._makeRequest.sandboxSend(job, function(e, attachedTrytes) {
if (e) {
return callback(e);
}
self.storeAndBroadcast(attachedTrytes, function(error, success) {
if (error) {
return callback(error);
}
var finalTxs = [];
attachedTrytes.forEach(function(trytes) {
finalTxs.push(Utils.transactionObject(trytes));
})
return callback(null, finalTxs);
})
})
} else {
// Broadcast and store tx
self.storeAndBroadcast(attached, function(error, success) {
if (error) {
return callback(error);
}
var finalTxs = [];
attached.forEach(function(trytes) {
finalTxs.push(Utils.transactionObject(trytes));
})
return callback(null, finalTxs);
})
}
})
})
}
/**
* Prepares Transfer, gets transactions to approve
* attaches to Tangle, broadcasts and stores
*
* @method sendTransfer
* @param {string} seed
* @param {int} depth
* @param {int} minWeightMagnitude
* @param {array} transfers
* @param {object} options
* @property {array} inputs List of inputs used for funding the transfer
* @property {string} address if defined, this address wil be used for sending the remainder value to
* @param {function} callback
* @returns {object} analyzed Transaction objects
**/
api.prototype.sendTransfer = function(seed, depth, minWeightMagnitude, transfers, options, callback) {
var self = this;
// Validity check for number of arguments
if (arguments.length < 5) {
return callback(new Error("Invalid number of arguments"));
}
// If no options provided, switch arguments
if (arguments.length === 5 && Object.prototype.toString.call(options) === "[object Function]") {
callback = options;
options = {};
}
// Check if correct depth and minWeightMagnitude
if (!inputValidator.isValue(depth) || !inputValidator.isValue(minWeightMagnitude)) {
return callback(errors.invalidInputs());
}
self.prepareTransfers(seed, transfers, options, function(error, trytes) {
if (error) {
return callback(error)
}
self.sendTrytes(trytes, depth, minWeightMagnitude, options, callback);
})
}
/**
* Promotes a transaction by adding spam on top of it.
* Will promote {maximum} transfers on top of the current one with {delay} interval.
*
* @Param {string} tail
* @param {int} depth
* @param {int} minWeightMagnitude
* @param {array} transfer
* @param {object} params
* @param callback
*
* @returns {array} transaction objects
*/
api.prototype.promoteTransaction = function(tail, depth, minWeightMagnitude, transfer, params, callback) {
var self = this;
if (!inputValidator.isHash(tail)) {
return callback(errors.invalidTrytes());
}
self.isPromotable(tail).then(function (isPromotable) {
if (!isPromotable) {
return callback(errors.inconsistentSubtangle(tail));
}
if (params.interrupt === true || (typeof(params.interrupt) === 'function' && params.interrupt()))
return callback(null, tail);
self.sendTransfer(transfer[0].address, depth, minWeightMagnitude, transfer, {reference: tail}, function(err, res) {
if (err == null && params.delay > 0) {
setTimeout (function() {
self.promoteTransaction(tail, depth, minWeightMagnitude, transfer, params, callback);
}, params.delay);
} else {
return callback(err, res);
}
});
}).catch(function (err) {
callback(err)
})
}
/**
* Replays a transfer by doing Proof of Work again
*
* @method replayBundle
* @param {string} tail
* @param {int} depth
* @param {int} minWeightMagnitude
* @param {function} callback
* @returns {object} analyzed Transaction objects
**/
api.prototype.replayBundle = function(tail, depth, minWeightMagnitude, callback) {
var self = this;
// Check if correct tail hash
if (!inputValidator.isHash(tail)) {
return callback(errors.invalidTrytes());
}
// Check if correct depth and minWeightMagnitude
if (!inputValidator.isValue(depth) || !inputValidator.isValue(minWeightMagnitude)) {
return callback(errors.invalidInputs());
}
self.getBundle(tail, function(error, bundle) {
if (error) return callback(error);
// Get the trytes of all the bundle objects
var bundleTrytes = [];
bundle.forEach(function(bundleTx) {
bundleTrytes.push(Utils.transactionTrytes(bundleTx));
})
return self.sendTrytes(bundleTrytes.reverse(), depth, minWeightMagnitude, callback);
})
}
/**
* Re-Broadcasts a transfer
*
* @method broadcastBundle
* @param {string} tail
* @param {function} callback
* @returns {object} analyzed Transaction objects
**/
api.prototype.broadcastBundle = function(tail, callback) {
var self = this;
// Check if correct tail hash
if (!inputValidator.isHash(tail)) {
return callback(errors.invalidTrytes());
}
self.getBundle(tail, function(error, bundle) {
if (error) return callback(error);
// Get the trytes of all the bundle objects
var bundleTrytes = [];
bundle.forEach(function(bundleTx) {
bundleTrytes.push(Utils.transactionTrytes(bundleTx));
})
return self.broadcastTransactions(bundleTrytes.reverse(), callback);
})
}
/**
* Generates a new address
*
* @method newAddress
* @param {string} seed
* @param {int} index
* @param {int} security Security level of the private key
* @param {bool} checksum
* @returns {string} address Transaction objects
**/
api.prototype._newAddress = function(seed, index, security, checksum) {
var key = Signing.key(Converter.trits(seed), index, security);
var digests = Signing.digests(key);
var addressTrits = Signing.address(digests);
var address = Converter.trytes(addressTrits)
if (checksum) {
address = Utils.addChecksum(address);
}
return address;
}
/**
* Generates a new address either deterministically or index-based
*
* @method getNewAddress
* @param {string} seed
* @param {object} options
* @property {int} index Key index to start search from
* @property {bool} checksum add 9-tryte checksum
* @property {int} total Total number of addresses to return
* @property {int} security Security level to be used for the private key / address. Can be 1, 2 or 3
* @property {bool} returnAll return all searched addresses
* @param {function} callback
* @returns {string | array} address List of addresses
**/
api.prototype.getNewAddress = function(seed, options, callback) {
var self = this;
// If no options provided, switch arguments
if (arguments.length === 2 && Object.prototype.toString.call(options) === "[object Function]") {
callback = options;
options = {};
}
// validate the seed
if (!inputValidator.isTrytes(seed)) {
return callback(errors.invalidSeed());
}
// default index value
var index = 0;
if ('index' in options) {
index = options.index;
// validate the index option
if (!inputValidator.isValue(index) || index < 0) {
return callback(errors.invalidIndex());
}
}
var checksum = options.checksum || false;
var total = options.total || null;
// If no user defined security, use the standard value of 2
var security = 2;
if ('security' in options) {
security = options.security;
// validate the security option
if (!inputValidator.isValue(security) || security < 1 || security > 3) {
return callback(errors.invalidSecurity());
}
}
var allAddresses = [];
// Case 1: total
//
// If total number of addresses to generate is supplied, simply generate
// and return the list of all addresses
if (total) {
// Increase index with each iteration
for (var i = 0; i < total; i++, index++) {
var address = self._newAddress(seed, index, security, checksum);
allAddresses.push(address);
}
return callback(null, allAddresses);
}
// Case 2: no total provided
//
// Continue calling wasAddressSpenFrom & findTransactions to see if address was already created
// if null, return list of addresses
//
else {
async.doWhilst(function(callback) {
// Iteratee function
var newAddress = self._newAddress(seed, index, security, checksum)
if (options.returnAll) {
allAddresses.push(newAddress)
}
// Increase the index
index += 1
self.wereAddressesSpentFrom(newAddress, function (err, res) {
if (err) {
return callback(err)
}
// Validity check
if (res[0]) {
callback(null, newAddress, true)
} else { // Check for txs if address isn't spent
self.findTransactions({'addresses': [newAddress]}, function (err, transactions) {
if (err) {
return callback(err)
}
callback(err, newAddress, transactions.length > 0)
})
}
})
}, function (address, isUsed) {
return isUsed
}, function(err, address) {
// Final callback
if (err) {
return callback(err);
} else {
// If returnAll, return list of allAddresses
// else return the last address that was generated
var addressToReturn = options.returnAll ? allAddresses : address;
return callback(null, addressToReturn);
}
})
}
}
/**
* Gets the inputs of a seed
*
* @method getInputs
* @param {string} seed
* @param {object} options
* @property {int} start Starting key index
* @property {int} end Ending key index
* @property {int} threshold Min balance required
* @property {int} security secuirty level of private key / seed
* @param {function} callback
**/
api.prototype.getInputs = function(seed, options, callback) {
var self = this;
// If no options provided, switch arguments
if (arguments.length === 2 && Object.prototype.toString.call(options) === "[object Function]") {
callback = options;
options = {};
}
// validate the seed
if (!inputValidator.isTrytes(seed)) {
return callback(errors.invalidSeed());
}
var start = options.start || 0;
var end = options.end || null;
var threshold = options.threshold || null;
// If no user defined security, use the standard value of 2
var security = options.security || 2;
// If start value bigger than end, return error
// or if difference between end and start is bigger than 500 keys
if (options.end && (start > end || end > (start + 500))) {
return callback(new Error("Invalid inputs provided"))
}
// Case 1: start and end
//
// If start and end is defined by the user, simply iterate through the keys
// and call getBalances
if (end) {
var allAddresses = [];
for (var i = start; i < end; i++) {
var address = self._newAddress(seed, i, security, false);
allAddresses.push(address);
}
getBalanceAndFormat(allAddresses);
}
// Case 2: iterate till threshold || end
//
// Either start from index: 0 or start (if defined) until threshold is reached.
// Calls getNewAddress and deterministically generates and returns all addresses
// We then do getBalance, format the output and return it
else {
self.getNewAddress(seed, {'index': start, 'returnAll': true, 'security': security}, function(error, addresses) {
if (error) {
return callback(error);
} else {
getBalanceAndFormat(addresses);
}
})
}
// Calls getBalances and formats the output
// returns the final inputsObject then
function getBalanceAndFormat(addresses) {
self.getBalances(addresses, 100, function(error, balances) {
if (error) {
return callback(error);
} else {
var inputsObject = {
'inputs': [],
'totalBalance': 0
}
// If threshold defined, keep track of whether reached or not
// else set default to true
var thresholdReached = threshold ? false : true;
for (var i = 0; i < addresses.length; i++) {