-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuserCLI.js
1668 lines (1526 loc) · 70.8 KB
/
userCLI.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
/*
This is the CLI file for user, one of two major components.
It is how the user interacts with the project by selecting choices within it.
It also gives the option to open the web page. If the web page is opened, it still makes calls to this file for functons.
Important note is that this file uses web3 with infura to make transactions on our smart contract on the Ethereum blockchain.
*/
var inquirer = require('inquirer');
var Web3 = require('web3');
var fs = require('fs');
const prompts = require('prompts');
var figlet = require('figlet');
const chalk = require('chalk');
var path = require('path');
const {exec} = require('child_process');
const {execSync} = require('child_process');
const Folder = './';
var publicIp = require("public-ip");
var hex2ascii= require("hex2ascii")
var express = require('express');
var Table = require('cli-table');
var sleep = require('sleep')
var price = require('crypto-price');
require('events').EventEmitter.prototype._maxListeners = 100;
var now = new Date();
var date = "";
var requestAssignedFlag = 0;
var validationAssignedFlag = 0;
var taskCounter = 0;
var NetworkID = 3;
var serverPort = 5000;
var ClientPort = 5000;
var ip = undefined;
var ip4 = undefined;
var ip6 = undefined;
var mode = undefined;
var requestAddr= undefined;
var filePath = undefined;
var requestIP = undefined;
var buffer = [];
var webpageUp = 0;
var executing = false;
var finished = false;
var canRate = false;
var pos = 0;
var ratings = [];
var rateProvs = [];
var validationSelectFlag = false;
var ratingsTable = new Table({
chars: { 'top': '═' , 'top-mid': '╤' , 'top-left': '╔' , 'top-right': '╗'
, 'bottom': '═' , 'bottom-mid': '╧' , 'bottom-left': '╚' , 'bottom-right': '╝'
, 'left': '║' , 'left-mid': '╟' , 'mid': '─' , 'mid-mid': '┼'
, 'right': '║' , 'right-mid': '╢' , 'middle': '│' }
});
var outChooseVal = 0;
var valEntCount = 0;
var provEntCount = 0;
var sleep = require('sleep');
///////////////////////////////////////////////////////////////////Get IP///////////////////////////////////////////////////////////////////////////////////
var UTCFileArray = [];
var UTCfile;
var userAddress;
var userAddresses = [];
//Ethereum subscribe variables
var RequestStartTime = 0
fs.readdir(Folder, (err, files) => {
files.forEach(file => {
if(file[0] === 'U' && file[1] === 'T' && file[2] === 'C')
{
UTCFileArray.push(file);
userAddresses.push("0x" + file.slice(37, file.length));
}
})
})
var ws = new Web3.providers.WebsocketProvider('wss://ropsten.infura.io/ws/v3/aa544d081b53485fb0fa8df2c9a8437e')
web3 = new Web3(ws);
var TaskContract = require('../../bcai_deploy/client/src/contracts/TaskContract.json');
var abi = TaskContract.abi;
var addr = TaskContract.networks[NetworkID].address; //align to const ID defination on top
const myContract = new web3.eth.Contract(abi, addr);
var prov = 0;
var decryptedAccount = "";
var depositAmt = 0.10;
questions = {
type : 'list',
name : 'whatToDo',
message: 'What would you like to do?',
choices : ['start request', 'show pools', 'create new address','show addresses', 'help', 'show provider ratings', 'USD to ETH', 'quit'],
};
questions1 = {
type : 'list',
name : 'whatToDo1',
message : 'What would you like to do?',
choices : ['stop request', 'show pools', 'finalize request', 'show provider rating', 'choose provider', 'choose validator', 'show ETH balance', 'USD to ETH', 'quit'],
};
clearStat();
clearLog();
fs.appendFile('./log.txt', String(Date(Date.now())), function(err){
if(err) throw err;
})
console.log(chalk.cyan(" _ ____ _ _ \n(_)/ ___| |__ __ _(_)_ __ \n| | | | '_ \\ / _` | | '_ \\ \n| | |___| | | | (_| | | | | |\n|_|\\____|_| |_|\\__,_|_|_| |_|\n\n"))
console.log(chalk.cyan("Thank you for using iChain user CLI! The Peer to Peer Blockchain Machine \nLearning Application. Select 'start request' to get started or 'help' \nto get more information about the application.\n"))
process.on('SIGINT', async () => {
try{
console.log("\n");
const response = await prompts({
type: 'text',
name: 'val',
message: 'You must choose the "quit" option before exiting appliation. Type "quit" here if you would like to quit or "back" to go to main menu...\n'
});
if(response.val.toLowerCase() == "quit")
{
if(prov == 1)
{
stopTask(questions.choices[5]);
}
else
{
process.exit(-1);
}
}
if(response.val.toLowerCase() == "back"){
askUser();
}
}
catch(err){
console.log("\n", chalk.red("Error: you didn't choose 'quit' or 'back' so we are quitting the application for you..."), "\n");
if(prov == 1)
{
stopTask(questions.choices[5]);
}
else
{
process.exit(-1);
}
}
});
setRatingVars();
cliOrSite();
function cliOrSite(){
inquirer.prompt([
{
type: 'list',
name: 'interface',
choices: ['Continue with CLI', 'Open Site'],
message: 'Choose an interface'
}
])
.then (answers => {
if(answers.interface == 'Continue with CLI'){
console.log("\n\n");
askUser();
}
else{
listenWebsite();
}
})
}
function setRatingVars(){
ratingsTable = new Table({
chars: { 'top': '═' , 'top-mid': '╤' , 'top-left': '╔' , 'top-right': '╗'
, 'bottom': '═' , 'bottom-mid': '╧' , 'bottom-left': '╚' , 'bottom-right': '╝'
, 'left': '║' , 'left-mid': '╟' , 'mid': '─' , 'mid-mid': '┼'
, 'right': '║' , 'right-mid': '╢' , 'middle': '│' }
});
myContract.methods.getProviderPool().call().then(function(provPool){
return provPool
})
.then((provPool) => {
ratingsTable.push(["Rating", "Provider"])
ratings.length = 0;
rateProvs.length = 0;
provPool.forEach(prov =>{
myContract.methods.getAvgRating(prov).call().then(function(rating){
pos+=1;
ratings.push(rating);
rateProvs.push(prov);
return [rating, pos, prov];
})
.then((arr) => {
ratingsTable.push([arr[0].toString(), arr[2].toString()]);
return arr[1];
})
})
})
.catch((err) => console.log(err));
}
//////////////////////////////////////////////////////CLI FUNCTIONS//////////////////////////////////////////////////////////////////
//Asks for reputation rating
function validateRating(rating){
return rating >= 1 && rating <= 100;
}
function giveRating(){
canRate = false;
inquirer.prompt([
{
type: 'list',
name: 'askToRate',
choices: ['Yes', 'No'],
message: 'Would you like to give a rating for your provider?'
}
])
.then (answers =>{
if(answers.askToRate == 'Yes'){
console.log(chalk.cyan("\nYou have chosen to give a rating\n"));
inquirer.prompt([
{
type: 'number',
name: 'rating',
message: 'Give a rating between 1 and 100',
validate: validateRating
}
])
.then(answers =>{
var ABIfinalizeRequest; //prepare abi for a function call
ABIfinalizeRequest = myContract.methods.finalizeRequest(userAddress, true, answers.rating).encodeABI();
const rawTransaction = {
"from": userAddress,
"to": addr,
"value": 0, //web3.utils.toHex(web3.utils.toWei("0.001", "ether")),
"gasPrice": web3.utils.toHex(web3.utils.toWei("30", "GWei")),
"gas": 5000000,
"chainId": 3,
"data": ABIfinalizeRequest
}
decryptedAccount.signTransaction(rawTransaction)
.then(signedTx => web3.eth.sendSignedTransaction(signedTx.rawTransaction))
.then(receipt => {
//console.log(chalk.cyan("\n\nTransaction receipt: "), receipt)
console.log(chalk.cyan("\n\nYour rating has gone through. Your task is now complete...\n"))
})
.then(()=>{
askUser();
})
})
}
else{
console.log(chalk.cyan("\nYou have elected to not give rating\n"));
//go back to main menu
var ABIfinalizeRequest; //prepare abi for a function call
ABIfinalizeRequest = myContract.methods.finalizeRequest(userAddress, false, 0).encodeABI();
const rawTransaction = {
"from": userAddress,
"to": addr,
"value": 0, //web3.utils.toHex(web3.utils.toWei("0.001", "ether")),
"gasPrice": web3.utils.toHex(web3.utils.toWei("30", "GWei")),
"gas": 5000000,
"chainId": 3,
"data": ABIfinalizeRequest
}
decryptedAccount.signTransaction(rawTransaction)
.then(signedTx => web3.eth.sendSignedTransaction(signedTx.rawTransaction))
.then(receipt => {
//console.log(chalk.cyan("\n\nTransaction receipt: "), receipt)
console.log(chalk.cyan("\n\nYour task is now complete...\n"))
})
.then(()=>{
askUser();
})
}
})
}
function promptProviderChoices(){
setRatingVars();
var displayProvList = [];
var displayString = "";
for(var i = 0; i<rateProvs.length; i++){
displayString = rateProvs[i] + "- Rating: " + ratings[i];
displayProvList.push(displayString);
}
inquirer.prompt([
{
type: 'list',
name: 'provChoice',
choices: displayProvList,
message: 'Choose provider:'
}
])
.then(choice => {
console.log(chalk.cyan("\nYou have chosen ", choice.provChoice, " as your provider\n"));
fs.appendFile('./log.txt', "\n" + String(Date(Date.now())) + " Request has been assigned to provider\n", function (err){
if (err) throw err;
})
//address is chars 0-41
var chooseProvAddr = choice.provChoice.slice(0, 42).toLowerCase();
var ABIChooseProvider; //prepare abi for a function call
ABIChooseProvider = myContract.methods.chooseProvider(chooseProvAddr).encodeABI();
const rawTransaction = {
"from": userAddress,
"to": addr,
"value": 0, //web3.utils.toHex(web3.utils.toWei("0.001", "ether")),
"gasPrice": web3.utils.toHex(web3.utils.toWei("30", "GWei")),
"gas": 5000000,
"chainId": 3,
"data": ABIChooseProvider
}
decryptedAccount.signTransaction(rawTransaction)
.then(signedTx => web3.eth.sendSignedTransaction(signedTx.rawTransaction))
.then(receipt => {
console.log(chalk.cyan("\n\nYour request has been submitted... \n\n"));
prov = 1;
})
.then(()=>{
askUser();
})
})
}
function chooseValidator(){
setRatingVars();
validationSelectFlag = false;
var displayValidatorList = [];
var displayString = "";
for(var i = 0; i<rateProvs.length; i++){
displayString = rateProvs[i] + "- Rating: " + ratings[i];
displayValidatorList.push(displayString);
}
inquirer.prompt([
{
type: 'list',
name: 'provChoice',
choices: displayValidatorList,
message: 'Choose validator:'
}
])
.then(choice => {
console.log(chalk.cyan("\nYou have chosen ", choice.provChoice, " as your validator\n"));
fs.appendFile('./log.txt', "\n" + String(Date(Date.now())) + " Request has been assigned to validator\n", function (err){
if (err) throw err;
})
//address is chars 0-41
var chooseProvAddr = choice.provChoice.slice(0, 42).toLowerCase();
var ABIChooseProvider; //prepare abi for a function call
ABIChooseProvider = myContract.methods.chooseProvider(chooseProvAddr).encodeABI();
const rawTransaction = {
"from": userAddress,
"to": addr,
"value": 0, //web3.utils.toHex(web3.utils.toWei("0.001", "ether")),
"gasPrice": web3.utils.toHex(web3.utils.toWei("30", "GWei")),
"gas": 5000000,
"chainId": 3,
"data": ABIChooseProvider
}
decryptedAccount.signTransaction(rawTransaction)
.then(signedTx => web3.eth.sendSignedTransaction(signedTx.rawTransaction))
.then(receipt => {
console.log(chalk.cyan("\n\nYour request has been submitted for validation... \n\n"));
prov = 1;
})
.then(()=>{
askUser();
})
})
}
//Gives the user a starting menu of choices
function askUser(){
setRatingVars();
checkEvents();
if(outChooseVal == 1){
console.log(chalk.cyan("\nYour task has been completed. Select the a validator to continue...\n"));
}
if(canRate == true){
giveRating();
}
else{
if(prov == 0)
inquirer.prompt([questions]).then(answers => {choiceMade(answers.whatToDo)});
else
inquirer.prompt([questions1]).then(answers => {choiceMade(answers.whatToDo1)});
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function receiveResult(){
fs.readFile('./stat.txt', function read(err, data){
if (err) throw err;
fileContent = data;
//console.log(fileContent.toString('utf8'));
if(fileContent.toString('utf8') === 'Ready')
{
clearStat();
fs.appendFile('./stat.txt', String(requestIP)+"\n"+"0", function (err){
if (err) throw err;
})
}
else if(fileContent.toString('utf8') !== 'Executing' && finished === false){
finished = true;
clearStat();
fs.appendFile('./stat.txt', String(requestIP)+"\n"+"0", function (err){
if (err) throw err;
})
}
})
}
function clearStat() {
fs.truncate('./stat.txt', 0, function(err){
if (err) throw err
})
}
function clearLog(){
fs.truncate('./log.txt', 0, function(err){
if(err) throw err;
})
}
//Takes choice made by prompt and controls where to go
function choiceMade(choice){
if(prov == 0 && choice == questions.choices[0])
{
startTask();
}
else if(prov == 1 && choice == questions1.choices[0])
{
stopTask();
}
else if (choice == questions.choices[1] || choice == questions1.choices[1])
{
showPools();
}
else if(choice == questions1.choices[2]){
giveRating();
}
else if(choice == questions.choices[2]){
inquirer.prompt([
{
name : 'net',
message: 'Enter MainNet or Ropsten: ',
},
{
type: 'password',
name : 'pass',
message: 'Enter your password: ',
},
{
type: 'password',
name : 'passVeri',
message: 'Enter your password: ',
}
])
.then(settings => {
return [settings.net, settings.pass, settings.passVeri];
})
.then(newSettings => {
var net = newSettings[0];
var pass = newSettings[1];
var passV = newSettings[2];
if(pass === passV){
if(net.toLowerCase() === 'mainnet'){
newAcc(1, pass)
}
else if(net.toLowerCase() === 'ropsten')
newAcc(0, pass)
else {
console.log("network entry not recognized");
askUser();
}
}
if(pass !== passV){
console.log("entered passwords do not match");
askUser();
}
})
.catch( err => {
console.log("\n", chalk.red(err), "\n");
askUser();
});
}
else if(choice == questions.choices[3]){
console.log('\n\n'); console.log("\n")
for(var i = 0; i < userAddresses.length; i++){
console.log(userAddresses[i]);
}
console.log('\n\n');
askUser();
}
else if(choice == questions.choices[4])
{
//Need to update user help
console.log(chalk.cyan("\niChain is an application that allows users to send machine learning tasks to"))
console.log(chalk.cyan("providers who have high computational power to spare. To get started make sure"))
console.log(chalk.cyan("your UTC keystore files are located in the same directory as this CLI. You can"))
console.log(chalk.cyan("put multiple keystore files in the directory and will be allowed to choose from"))
console.log(chalk.cyan("any of these accounts. Next select 'start request' and you will be asked to"))
console.log(chalk.cyan("choose an account from the available accounts. You will then be asked to enter"))
console.log(chalk.cyan("a password. This is the password associated with the selected keystore account."))
console.log(chalk.cyan("You will thenbe asked to input your user settings that will be used to pair you "))
console.log(chalk.cyan("with a provider. These can be changed at a later time once the request is "))
console.log(chalk.cyan("submitted. After successfully entering all of the required input a new prompt "))
console.log(chalk.cyan("will be displayed. By selecting 'update request' you can change the user input "))
console.log(chalk.cyan("settings you entered earlier. 'Stop Request' will stop the current request."))
console.log(chalk.cyan("Lastly, show pools will display the current state of the pools. Here you can "))
console.log(chalk.cyan("check how many providers are available at a given moment. If it is taking a"))
console.log(chalk.cyan("while for your request to be assigned you may want to consider changing your "))
console.log(chalk.cyan("user input settings. Thank you for using iChain!\n\n"))
askUser();
}
else if(choice == questions.choices[5] || choice == questions1.choices[3]){
console.log("\n");
console.log(ratingsTable.toString(), "\n\n")
askUser();
}
else if(choice == questions1.choices[4]){
promptProviderChoices();
}
else if(choice == questions1.choices[5]){
if(validationSelectFlag == true){
chooseValidator();
}
else{
console.log(chalk.cyan("\nRequest has not been completed yet. You are unable to select a validator.\n"))
askUser();
}
}
else if(choice == questions1.choices[6]){
web3.eth.getBalance(userAddress)
.then((balance) => {console.log("\n\n", web3.utils.fromWei(String(balance), 'ether'), "Ether \n")})
.then(()=>{askUser()})
.catch((err)=>{console.log(err)});
}
else if(choice == questions.choices[6] || choice == questions1.choices[7]){
price.getCryptoPrice('USD', 'ETH').then(obj => {
console.log(chalk.cyan("\nThe current amount of 1 ETH in USD is $", obj.price, "\n"));
askUser();
})
.catch(err =>{
console.log(chalk.red("\n", err, "\n"))
})
}
else
{
if(prov == 1)
{
stopTask(choice);
}
else{
process.exit(-1);
}
}
}
function newAcc(mainNet, pass){
mess = '';
fs.truncate('./pass.txt', 0, function(err){
if (err) throw err
})
if(mainNet === 1)
mess = 'geth account new --datadir . --password pass.txt';
else
mess = 'geth --testnet account new --datadir . --password pass.txt';
fs.appendFile('./pass.txt', String(pass)+"\n", function (err){
if (err) throw err;
exec(mess, (err, stdout, stderr) => {
if (err) throw err;
fs.truncate('./pass.txt', 0, function(err){
if (err) throw err;
exec('cp keystore/* .',(err,stdout,stderr)=>{
if(err) throw err;
exec('rm -r keystore',(err,stdout,stderr)=>{
if(err) throw err;
console.log("Congrats! New address constructed.")
console.log("To use add ether using your favorite exchange");
//add new keystore to the arrayUnhandledPromiseRejectionWarning: Error: Transaction has been reverted by the EVM:
fs.readdir(Folder, (err, files) => {
userAddresses = []
files.forEach(file => {
if(file[0] === 'U' && file[1] === 'T' && file[2] === 'C' )
{
UTCFileArray.push(file);
userAddresses.push("0x" + file.slice(37, file.length));
}
})
askUser();
})
});
});
})
});
})
}
function startTask(){
console.log(chalk.cyan("\nPut your keystore file in the directory with the CLI ...\n\n"));
if(userAddresses.length == 0)
{
console.log(chalk.red("Error: You have no keystore files in the directory of this CLI... to get started with an account put your keystore files in here..."), "\n")
askUser();
}
else{
inquirer.prompt([
{
type: 'list',
name: 'userAddr',
choices: userAddresses
}
])
.then(answers =>
{
for(i = 0; i<userAddresses.length; i++)
{
if(answers.userAddr == userAddresses[i])
{
userAddress = userAddresses[i];
UTCfile = UTCFileArray[i];
break;
}
}
console.log(chalk.cyan("\nYou chose account: "+userAddress));
}
)
.then( () => {
//Getting password from CLI
if(decryptedAccount == "")
{
console.log("\n");
price.getCryptoPrice('USD', 'ETH').then(obj => {
var calculatedPrice = depositAmt * obj.price;
inquirer.prompt([{
name: 'confirmation',
type: 'confirm',
message: 'You are about to be charged ' + depositAmt + ' ETH. This is ' + calculatedPrice.toFixed(2) + ' in USD, is this okay?',
}])
.then(response =>{
console.log("\n");
if(response.confirmation == true){
inquirer.prompt([
{
type: 'password',
name: 'keystorePswd',
message: 'Enter your keystore file password: ',
},
])
.then(answers => {return answers.keystorePswd})
.then((password)=>{
//retrieving keystore file and decrypting with password
var keystore;
var contents = fs.readFileSync(UTCfile, 'utf8')
keystore = contents;
decryptedAccount = web3.eth.accounts.decrypt(keystore, password);
return decryptedAccount;
}
)
.then((decryptedAccount) =>{
console.log("\n");
inquirer.prompt([
{
name : 'filePath',
message: 'Enter file path: ',
}
])
.then(settings => {
return settings.filePath;
})
.then(path => {
console.log(chalk.cyan("\nWe are sending transaction to the blockchain... \n"));
var ABIstartRequest; //prepare abi for a function call
var filePath = path;
if(filePath.slice(filePath.length-4, filePath.length) != ".zip")
{
console.log("\n", chalk.red("Error: You must provide the task as a .zip file... Select 'start request' to try again..."), "\n")
askUser();
}
else{
fs.open(filePath, 'r', (err, fd)=>{
if(fd != undefined){
function readChunk(){
chunkSize = 10*1024*1024;
var holdBuff = Buffer.alloc(chunkSize);
fs.read(fd, holdBuff, 0, chunkSize, null, function(err, nread){
if(nread === 0){
fs.close(fd, function(err){
});
return;
}
if(nread < chunkSize){
try{
buffer.push(holdBuff.slice(0, nread));
}
catch(err){
console.log("You failed to select correct file path")
}
}
else{
buffer.push(holdBuff);
readChunk();
}
})
}
readChunk();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
while(!(fs.existsSync('./totalOrderAddress.txt'))){
sleep.sleep(5);
}
fs.readFile('./totalOrderAddress.txt', 'utf8', function(err, ip){
console.log(ip);
console.log(web3.utils.asciiToHex(ip));
ABIstartRequest = myContract.methods.startRequest(web3.utils.asciiToHex(ip)).encodeABI();
const rawTransaction = {
"from": userAddress,
"to": addr,
"value": web3.utils.toHex(web3.utils.toWei("0.01", "ether")),
"gasPrice": web3.utils.toHex(web3.utils.toWei("30", "GWei")),
"gas": 5000000,
"chainId": 3,
"data": ABIstartRequest
}
decryptedAccount.signTransaction(rawTransaction)
.catch(err =>{
if(err == "Error: Not enough ether"){
console.log(chalk.red("\nThere is not enough ether in this account to start a request. You must have at least 0.01 ETH to start a request...\n"));
}
else{
console.log(chalk.red("\n", err, "\n"));
}
})
.then(signedTx => web3.eth.sendSignedTransaction(signedTx.rawTransaction))
.then(receipt => {
//console.log(chalk.cyan("\n\nTransaction receipt: "));
//console.log(receipt);
console.log(chalk.cyan("\n\nYour request has been submitted. You must choose a provider now to continue... \n\n"));
prov = 1;
})
.then(() => {
askUser();
//call subscribe here
try{
web3.eth.subscribe('newBlockHeaders', (err, result) => {
if(err) console.log(chalk.red(err), result);
checkEvents();
})
}
catch(error){
alert(
`Failed to load web3, accounts, or contract. Check console for details.`
);
console.log("\n", chalk.red(err), "\n");
}
})
.catch(err => {
if(String(err).slice(0, 41) == "Error: Returned error: insufficient funds")
{
console.log(chalk.red("\nError: This keystore account doesn't have enough Ether... Add funds or try a different account...\n"))
askUser();
}
else{
console.log(chalk.red("\nError: ", chalk.red(err), "\n"))
askUser();
}
});
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else{
console.log("\n", chalk.red("Error: No file found with file path..."), "\n")
askUser();
}
});
}
})
.catch( err => {
console.log("\n", chalk.red(err), "\n");
askUser();
});
})
.catch(err =>{
if (String(err).slice(0, 28) == "Error: Key derivation failed")
{
console.log(chalk.red("\nError: You have entered the wrong keystore password... Please try again...\n"))
askUser();
}
else{
console.log("\nError: ", chalk.red(err), "\n");
askUser();
}
})
}
else{
askUser();
}
})
.catch(err =>console.log(err));
})
.catch(err => console.log(err));
}
else{
console.log("\n");
price.getCryptoPrice('USD', 'ETH').then(obj=>{
var calculatedPrice = depositAmt * obj.price;
inquirer.prompt([{
name: 'confirmation',
type: 'confirm',
message: 'You are about to be charged ' + deposit + ' ETH. This is ' + calculatedPrice.toFixed(2) + ' in USD, is this okay?',
}])
.then(response =>{
console.log("\n");
if(response.confirmation == true){
inquirer.prompt([
{
name : 'filePath',
message: 'Enter file path: ',
}
])
.then(settings => {
return settings.filePath;
})
.then(path => {
console.log(chalk.cyan("\nWe are sending transaction to the blockchain... \n"));
var ABIstartRequest; //prepare abi for a function call
var filePath = path;
if(filePath.slice(filePath.length-4, filePath.length) != ".zip")
{
console.log("\n", chalk.red("Error: You must provide the task as a .zip file... Select 'start request' to try again..."), "\n")
askUser();
}
else{
fs.open(filePath, 'r', (err, fd)=>{
if(fd != undefined){
function readChunk(){
chunkSize = 10*1024*1024;
var holdBuff = Buffer.alloc(chunkSize);
fs.read(fd, holdBuff, 0, chunkSize, null, function(err, nread){
if(nread === 0){
fs.close(fd, function(err){
});
return;
}
if(nread < chunkSize){
try{
buffer.push(holdBuff.slice(0, nread));
}
catch(err){
console.log("You failed to select correct file path")
}
}
else{
buffer.push(holdBuff);
readChunk();
}
})
}
readChunk();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
while(!(fs.exists('./totalOrderAddress.txt'))){
sleep.sleep(5);
}
fs.readFile('./totalOrderAddress.txt', 'utf8', function(err, ip){
ABIstartRequest = myContract.methods.startRequest(web3.utils.asciiToHex(ip)).encodeABI();
const rawTransaction = {
"from": userAddress,
"to": addr,
"value": web3.utils.toHex(web3.utils.toWei("0.01", "ether")),
"gasPrice": web3.utils.toHex(web3.utils.toWei("30", "GWei")),
"gas": 5000000,
"chainId": 3,
"data": ABIstartRequest
}
decryptedAccount.signTransaction(rawTransaction)
.then(signedTx => web3.eth.sendSignedTransaction(signedTx.rawTransaction))
.then(receipt => {
console.log(chalk.cyan("\n\nYour request has been submitted... \n\n"));
prov = 1;
})
.then(() => {
askUser();
//call subscribe here
try{
web3.eth.subscribe('newBlockHeaders', (err, result) => {
if(err) console.log(chalk.red(err), result);
checkEvents();
})
}
catch(error){
alert(
`Failed to load web3, accounts, or contract. Check console for details.`
);
console.log("\n", chalk.red(err), "\n");
}
})
.catch(err => {
if(String(err).slice(0, 41) == "Error: Returned error: insufficient funds")
{
console.log(chalk.red("\nError: This keystore account doesn't have enough Ether... Add funds or try a different account...\n"))
askUser();
}
else{
console.log(chalk.red("\nError: ", chalk.red(err), "\n"))
askUser();
}
});
});
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else{
console.log("\n", chalk.red("Error: No file found with file path..."), "\n")
askUser();
}
});
}
})
.catch( err => {
console.log(chalk.red("\nError: ", chalk.red(err), "\n"))
askUser();
});
}
else{
askUser();
}
})
.catch(err => console.log(err));
})
.catch(err =>console.log(err));
}
})
}
}
function stopTask(choice){
if(choice == questions.choices[3] || choice == questions1.choices[3])
{
console.log(chalk.cyan("\nProvide keystore password to quit CLI... \n"));
}
else{
console.log(chalk.cyan("\nProvide keystore password to stop request... \n"));
}
inquirer.prompt([