forked from ArkEcosystemArchive/javascript-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·714 lines (666 loc) · 20.7 KB
/
index.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
#!/usr/bin/env node
var arkjs = require("arkjs");
var crypto = require("crypto");
var figlet = require("figlet");
var colors = require("colors");
var request = require("request");
var asciichart = require ('asciichart');
var chart = require ('chart');
var cliSpinners = require('cli-spinners');
var Table = require('ascii-table');
var ora = require('ora');
var cowsay = require('cowsay');
var async = require('async');
var vorpal = require('vorpal')();
var cluster = require('cluster');
var child_process = require('child_process');
var blessed = require('blessed');
var contrib = require('blessed-contrib');
var server;
var network;
var arkticker = {};
var currencies = ["USD","AUD", "BRL", "CAD", "CHF", "CNY", "EUR", "GBP", "HKD", "IDR", "INR", "JPY", "KRW", "MXN", "RUB"]
var networks = {
devnet: {
nethash: "578e820911f24e039733b45e4882b73e301f813a0d2c31330dafda84534ffa23",
peers: [
"167.114.29.51:4002",
"167.114.29.52:4002",
"167.114.29.53:4002",
"167.114.29.54:4002",
"167.114.29.55:4002"
]
},
mainnet: {
nethash: "6e84d08bd299ed97c212c886c98a57e36545c8f5d645ca7eeae63a8bd62d8988",
peers: [
"5.39.9.240:4001",
"5.39.9.241:4001",
"5.39.9.242:4001",
"5.39.9.243:4001",
"5.39.9.244:4001",
"5.39.9.250:4001",
"5.39.9.251:4001",
"5.39.9.252:4001",
"5.39.9.253:4001",
"5.39.9.254:4001",
"5.39.9.255:4001",
"5.39.53.48:4001",
"5.39.53.49:4001",
"5.39.53.50:4001",
"5.39.53.51:4001",
"5.39.53.52:4001",
"5.39.53.53:4001",
"5.39.53.54:4001",
"5.39.53.55:4001",
"37.59.129.160:4001",
"37.59.129.161:4001",
"37.59.129.162:4001",
"37.59.129.163:4001",
"37.59.129.164:4001",
"37.59.129.165:4001",
"37.59.129.166:4001",
"37.59.129.167:4001",
"37.59.129.168:4001",
"37.59.129.169:4001",
"37.59.129.170:4001",
"37.59.129.171:4001",
"37.59.129.172:4001",
"37.59.129.173:4001",
"37.59.129.174:4001",
"37.59.129.175:4001",
"193.70.72.80:4001",
"193.70.72.81:4001",
"193.70.72.82:4001",
"193.70.72.83:4001",
"193.70.72.84:4001",
"193.70.72.85:4001",
"193.70.72.86:4001",
"193.70.72.87:4001",
"193.70.72.88:4001",
"193.70.72.89:4001",
"193.70.72.90:4001"
]
}
};
function getNetworkFromNethash(nethash){
for(var n in networks){
if(networks[n].nethash == nethash){
return n;
}
}
return "unknown";
}
function findEnabledPeers(cb){
var peers=[];
getFromNode('http://'+server+'/peer/list', function(err, response, body){
if(err){
vorpal.log(colors.red("Can't get peers from network: " + err));
return cb(peers);
}
else {
var respeers = JSON.parse(body).peers.map(function(peer){
return peer.ip+":"+peer.port;
}).filter(function(peer){
return peer.status=="OK";
});
async.each(respeers, function(peer, cb){
getFromNode('http://'+peer+'/api/blocks/getHeight', function(err, response, body){
if(body != "Forbidden"){
peers.push(peer);
}
cb();
});
},function(err){
return cb(peers);
});
}
});
}
function postTransaction(transaction, cb){
request(
{
url: 'http://'+server+'/peer/transactions',
headers: {
nethash: network.nethash,
version: '1.0.0',
port:1
},
method: 'POST',
json: true,
body: {transactions:[transaction]}
},
cb
);
}
function getFromNode(url, cb){
nethash=network?network.nethash:"";
request(
{
url: url,
headers: {
nethash: nethash,
version: '1.0.0',
port:1
},
timeout: 5000
},
cb
);
}
function getARKTicker(currency){
request({url: "https://api.coinmarketcap.com/v1/ticker/ark/?convert="+currency}, function(err, response, body){
arkticker[currency]=JSON.parse(body)[0];
});
}
vorpal
.command('connect <network>', 'Connect to network. Network is devnet or mainnet')
.action(function(args, callback) {
var self = this;
network = networks[args.network];
if(!network){
self.log("Network not found");
return callback();
}
server = network.peers[Math.floor(Math.random()*1000)%network.peers.length];
findEnabledPeers(function(peers){
if(peers.length>0){
server=peers[0];
network.peers=peers;
}
});
getFromNode('http://'+server+'/api/loader/autoconfigure', function(err, response, body){
network.config = JSON.parse(body).network;
console.log(network.config);
});
getFromNode('http://'+server+'/peer/status', function(err, response, body){
self.log("Node: " + server + ", height: " + JSON.parse(body).height);
self.delimiter('ark '+args.network+'>');
callback();
});
});
vorpal
.command('connect node <url>', 'Connect to a server. For example "connect node 5.39.9.251:4000"')
.action(function(args, callback) {
var self = this;
server=args.url;
getFromNode('http://'+server+'/api/blocks/getNethash', function(err, response, body){
if(err){
self.log(colors.red("Public API unreacheable on this server "+server+" - "+err));
server=null;
self.delimiter('ark>');
return callback();
}
try {
var nethash = JSON.parse(body).nethash;
}
catch (error){
self.log(colors.red("API is not returning expected result:"));
self.log(body);
server=null;
self.delimiter('ark>');
return callback();
}
var networkname = getNetworkFromNethash(nethash);
network = networks[networkname];
if(!network){
network = {
nethash: nethash,
peers:[server]
}
networks[nethash]=network;
}
getFromNode('http://'+server+'/api/loader/autoconfigure', function(err, response, body){
network.config = JSON.parse(body).network;
console.log(network.config);
});
self.log("Connected to network " + nethash + colors.green(" ("+networkname+")"));
self.delimiter('ark '+server+'>');
getFromNode('http://'+server+'/peer/status', function(err, response, body){
self.log("Node height ", JSON.parse(body).height);
});
callback();
});
});
vorpal
.command('disconnect', 'Disconnect from server or network')
.action(function(args, callback) {
var self = this;
self.log("Disconnected from "+server);
self.delimiter('ark>');
server=null;
network=null;
callback();
});
vorpal
.command('network stats', 'Get stats from network')
.action(function(args, callback) {
var self = this;
if(!server){
self.log("Please connect to node or network before");
return callback();
}
getFromNode('http://'+server+'/peer/list', function(err, response, body){
if(err){
self.log(colors.red("Can't get peers from network: " + err));
return callback();
}
else {
var peers = JSON.parse(body).peers.map(function(peer){
return peer.ip+":"+peer.port;
});
self.log("Checking "+peers.length+" peers");
var spinner = ora({text:"0%",spinner:"shark"}).start();
var heights={};
var delays={};
var count=0;
async.each(peers, function(peer, cb){
var delay=new Date().getTime();
getFromNode('http://'+peer+'/peer/status', function(err, response, hbody){
delay=new Date().getTime()-delay;
if(delays[10*Math.floor(delay/10)]){
delays[10*Math.floor(delay/10)]++;
}
else{
delays[10*Math.floor(delay/10)]=1;
}
count++;
spinner.text=Math.floor(100*count/peers.length)+"%";
if(err){
return cb();
}
else{
var height=JSON.parse(hbody).height;
if(!height){
return cb();
}
if(heights[height]){
heights[height]++;
}
else{
heights[height]=1;
}
return cb();
}
return cb();
});
},function(err){
spinner.stop();
var screen = blessed.screen();
var grid = new contrib.grid({rows: 12, cols: 12, screen: screen})
var line = grid.set(0, 0, 6, 6, contrib.line,
{ style:
{ line: "yellow"
, text: "green"
, baseline: "black"}
, xLabelPadding: 3
, xPadding: 5
, label: 'Delays'});
var data = {
x: Object.keys(delays).map(function(d){return d+"ms"}),
y: Object.values(delays)
};
screen.append(line); //must append before setting data
line.setData([data]);
var bar = grid.set(6, 0, 6, 12, contrib.bar, { label: 'Network Height', barWidth: 4, barSpacing: 6, xOffset: 0, maxHeight: 9})
screen.append(bar); //must append before setting data
bar.setData({titles: Object.keys(heights), data: Object.values(heights)});
screen.onceKey(['escape'], function(ch, key) {
screen.destroy();
});
screen.render();
});
}
});
});
vorpal
.command('account status <address>', 'Get account status')
.action(function(args, callback) {
var self = this;
if(!server){
self.log("please connect to node or network before");
return callback();
}
var address=args.address;
getFromNode('http://'+server+'/api/accounts?address='+address, function(err, response, body){
var a = JSON.parse(body).account;
if(!a){
self.log("Unknown on the blockchain");
return callback();
}
for(var i in a){
if(!a[i] || a[i].length==0) delete a[i];
}
delete a.address;
var table = new Table();
table.setHeading(Object.keys(a));
table.addRow(Object.values(a));
self.log(table.toString());
getFromNode('http://'+server+'/api/delegates/get/?publicKey='+a.publicKey, function(err, response, body){
var body = JSON.parse(body);
if(body.success){
var delegate=body.delegate;
delete delegate.address;
delete delegate.publicKey;
table = new Table("Delegate");
table.setHeading(Object.keys(delegate));
table.addRow(Object.values(delegate));
self.log(table.toString());
}
callback();
});
});
});
vorpal
.command('account vote <name>', 'Vote for delegate <name>. Remove previous vote if needed. Leave empty to clear vote')
.action(function(args, callback) {
var self = this;
async.waterfall([
function(seriesCb){
self.prompt({
type: 'password',
name: 'passphrase',
message: 'passphrase: ',
}, function(result){
if (result.passphrase) {
return seriesCb(null, result.passphrase);
}
else{
return seriesCb("Aborted.");
}
});
},
function(passphrase, seriesCb){
var delegate = args.name;
var transaction = arkjs.delegates.createVote(passphrase);
self.prompt({
type: 'confirm',
name: 'continue',
default: false,
message: 'Sending '+arkamount/100000000+'ARK '+(currency?'('+currency+args.amount+') ':'')+'to '+args.recipient+' now',
}, function(result){
if (result.continue) {
return seriesCb(null, transaction);
}
else {
return seriesCb("Aborted.")
}
});
},
function(transaction, seriesCb){
postTransaction(transaction, function(err, response, body){
if(err){
seriesCb("Failed to send transaction: " + err);
}
else if(body.success){
seriesCb(null, transaction);
}
else {
seriesCb("Failed to send transaction: " + body.error);
}
});
}
], function(err, transaction){
if(err){
self.log(colors.red(err));
}
else{
self.log(colors.green("Transaction sent successfully with id "+transaction.id));
}
return callback();
});
});
vorpal
.command('account send <amount> <recipient>', 'Send <amount> ark to <recipient>. <amount> format examples: 10, USD10.4, EUR100')
.action(function(args, callback) {
var self = this;
if(!server){
self.log("please connect to node or network before");
return callback();
}
var currency;
var found = false;
if(typeof args.amount != "number")
{
for(var i in currencies)
{
if(args.amount.startsWith(currencies[i]))
{
currency=currencies[i];
args.amount = Number(args.amount.replace(currency,""));
getARKTicker(currency);
found = true;
break;
}
}
if(!found)
{
self.log("Invalid Currency Format");
return callback();
}
}
async.waterfall([
function(seriesCb){
self.prompt({
type: 'password',
name: 'passphrase',
message: 'passphrase: ',
}, function(result){
if (result.passphrase) {
return seriesCb(null, result.passphrase);
}
else{
return seriesCb("Aborted.");
}
});
},
function(passphrase, seriesCb){
var arkamount = args.amount;
var arkAmountString = args.amount;
if(currency){
if(!arkticker[currency]){
return seriesCb("Can't get price from market. Aborted.");
}
arkamount = parseInt(args.amount * 100000000 / Number(arkticker[currency]["price_"+currency.toLowerCase()]))
arkAmountString = arkamount/100000000;
}
var transaction = arkjs.transaction.createTransaction(args.recipient, arkamount, null, passphrase);
self.prompt({
type: 'confirm',
name: 'continue',
default: false,
message: 'Sending '+arkAmountString+'ARK '+(currency?'('+currency+args.amount+') ':'')+'to '+args.recipient+' now',
}, function(result){
if (result.continue) {
return seriesCb(null, transaction);
}
else {
return seriesCb("Aborted.")
}
});
},
function(transaction, seriesCb){
postTransaction(transaction, function(err, response, body){
if(err){
seriesCb("Failed to send transaction: " + err);
}
else if(body.success){
seriesCb(null, transaction);
}
else {
seriesCb("Failed to send transaction: " + body.error);
}
});
}
], function(err, transaction){
if(err){
self.log(colors.red(err));
}
else{
self.log(colors.green("Transaction sent successfully with id "+transaction.id));
}
return callback();
});
});
vorpal
.command('account delegate <username>', 'Register new delegate with <username> ')
.action(function(args, callback) {
var self = this;
if(!server){
self.log("please connect to node or network before");
return callback();
}
return this.prompt({
type: 'password',
name: 'passphrase',
message: 'passphrase: ',
}, function(result){
if (result.passphrase) {
var transaction = arkjs.delegate.createDelegate(result.passphrase, args.username);
postTransaction(transaction, function(err, response, body){
if(body.success){
self.log(colors.green("Transaction sent successfully with id "+body.transactionIds[0]));
}
else{
self.log(colors.red("Failed to send transaction: "+body.error));
}
return callback();
});
} else {
self.log('Aborted.');
return callback();
}
});
});
vorpal
.command('account create', 'Generate a new random cold account')
.action(function(args, callback) {
var self = this;
if(!server){
self.log("please connect to node or network before, in order to retrieve necessery information about address prefixing");
return callback();
}
arkjs.crypto.setNetworkVersion(network.config.version);
var passphrase = require("bip39").generateMnemonic();
self.log("Seed - private:",passphrase);
self.log("WIF - private:",arkjs.crypto.getKeys(passphrase).toWIF());
self.log("Address - public :",arkjs.crypto.getAddress(arkjs.crypto.getKeys(passphrase).publicKey));
callback();
});
vorpal
.command('account vanity <string>', 'Generate an address containing lowercased <string> (WARNING you could wait for long)')
.action(function(args, callback) {
var self=this;
if(!server){
self.log("please connect to node or network before, in order to retrieve necessery information about address prefixing");
return callback();
}
arkjs.crypto.setNetworkVersion(network.config.version);
var count=0;
var numCPUs = require('os').cpus().length;
var cps=[];
self.log("Spawning process to "+numCPUs+" cpus");
var spinner = ora({text:"passphrases tested: 0",spinner:"shark"}).start();
for (var i = 0; i < numCPUs; i++) {
var cp=child_process.fork(__dirname+"/vanity.js");
cps.push(cp);
cp.on('message', function(message){
if(message.passphrase){
spinner.stop();
var passphrase = message.passphrase;
self.log("Found after",count,"passphrases tested");
self.log("Seed - private:",passphrase);
self.log("WIF - private:",arkjs.crypto.getKeys(passphrase).toWIF());
self.log("Address - public :",arkjs.crypto.getAddress(arkjs.crypto.getKeys(passphrase).publicKey));
for(var killid in cps){
cps[killid].kill();
}
callback();
}
if(message.count){
count += message.count;
spinner.text="passphrases tested: "+count;
}
});
cp.send({string:args.string.toLowerCase(), version:network.config.version});
}
});
vorpal
.command('message sign <message>', 'Sign a message')
.action(function(args, callback) {
var self = this;
return this.prompt({
type: 'password',
name: 'passphrase',
message: 'passphrase: ',
}, function(result){
if (result.passphrase) {
var hash = crypto.createHash('sha256');
hash = hash.update(new Buffer(args.message,"utf-8")).digest();
self.log("public key: ",arkjs.crypto.getKeys(result.passphrase).publicKey);
self.log("address : ",arkjs.crypto.getAddress(arkjs.crypto.getKeys(result.passphrase).publicKey));
self.log("signature : ",arkjs.crypto.getKeys(result.passphrase).sign(hash).toDER().toString("hex"));
} else {
self.log('Aborted.');
callback();
}
});
});
vorpal
.command('message verify <message> <publickey>', 'Verify the <message> signed by the owner of <publickey> (you will be prompted to provide the signature)')
.action(function(args, callback) {
var self = this;
return this.prompt({
type: 'input',
name: 'signature',
message: 'signature: ',
}, function(result){
if (result.signature) {
try{
var hash = crypto.createHash('sha256');
hash = hash.update(new Buffer(args.message,"utf-8")).digest();
var signature = new Buffer(result.signature, "hex");
var publickey= new Buffer(args.publickey, "hex");
var ecpair = arkjs.ECPair.fromPublicKeyBuffer(publickey);
var ecsignature = arkjs.ECSignature.fromDER(signature);
var res = ecpair.verify(hash, ecsignature);
self.log(res);
}
catch(error){
self.log("Failed: ", error);
}
callback();
} else {
self.log('Aborted.');
callback();
}
});
});
var sharkspinner;
vorpal
.command("shARK", "No you don't want to use this command")
.action(function(args, callback) {
var self = this;
self.log(colors.red(figlet.textSync("shARK")));
sharkspinner = ora({text:"Watch out, the shARK attack!",spinner:"shark"}).start();
callback();
});
vorpal
.command("spARKaaaaa!")
.hidden()
.action(function(args, callback) {
var time = 0;
var self=this;
sharkspinner && sharkspinner.stop();
["tux","meow","bunny","cower","dragon-and-cow"].forEach(function(spark){
setTimeout(function(){
self.log(cowsay.say({text:"SPAAAAARKKKAAAAAAA!", f:spark}));
}, time++*1000);
});
callback();
});
vorpal.history('ark-client');
vorpal.log(colors.cyan(figlet.textSync("Ark Client","Slant")));
vorpal
.delimiter('ark>')
.show();