-
Notifications
You must be signed in to change notification settings - Fork 16
/
HandySia.js
1232 lines (1153 loc) · 33.7 KB
/
HandySia.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
import {Wallet} from './siaAPI/Wallet.js';
import {Consensus} from './siaAPI/Consensus.js';
import {Host} from './siaAPI/Host.js';
import {Daemon} from './siaAPI/Daemon.js';
import {CommonUtils} from './CommonUtils.js';
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import url from 'url';
import {spawn} from 'child_process';
import QRCode from 'qrcode';
export class HandySia{
constructor(){
this.ioNamespaces = {};
this.siaPortsPath = process.env.HOME+'/.HandyHost/siaData/siaPorts.json';
this.redlistPortsPath = process.env.HOME+'/.HandyHost/ports.json';
this.wallet = new Wallet();
this.consensus = new Consensus();
this.host = new Host();
this.daemon = new Daemon();
this.handyUtils = new CommonUtils();
try{
fs.mkdirSync(`${process.env.HOME}/.HandyHost/siaData`,{recursive:true})
}
catch(e){
//folder already exists
}
this.trySpawningSiad();
//this.consensus.getChainStatus();
}
initHealthCheck(){
console.log('init SC health check interval')
if(typeof this.healthCheckInterval != "undefined"){
clearInterval(this.healthCheckInterval);
delete this.healthCheckInterval;
}
this.healthCheckInterval = setInterval(()=>{
//every 20 mins
checkHealth();
},1000*60*20)
const _this = this;
function checkHealth(){
//console.log('performing SC health check')
_this.daemon.getVersion().then(data=>{
//console.log('SC is alive')
}).catch(err=>{
console.log('SC health check error: siad must be down');
const didJustUpdateFileLoc = process.env.HOME+'/.HandyHost/siaData/isUpdating';
const didJustUpdate = fs.existsSync(didJustUpdateFileLoc);
if(didJustUpdate){
console.log('SC health check: looks like an update happened, hold off')
}
else{
console.log('starting healthcheck revival');
const logString = new Date()+' :: healthcheck is beginning\n';
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',logString,'utf8');
//first make sure theres not a zombie siad
const pkill = spawn('pkill',['-9','siad']);
pkill.stdout.on('data',d=>{
console.log('pkill out',d.toString());
const pkout = new Date()+' pkill stdout '+d.toString();
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',pkout,'utf8');
});
pkill.stderr.on('data',d=>{
console.log('pkill err',d.toString());
const pkout = new Date()+' pkill stderr '+d.toString();
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',pkout,'utf8');
})
pkill.on('close',()=>{
setTimeout(()=>{
const logString = new Date()+' :: pkill complete, healthcheck is restarting siad\n';
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',logString,'utf8');
_this.trySpawningSiad(true);
},120000)
})
//this.trySpawningSiad();
}
})
}
}
trySpawningSiad(wasFromHealthcheck){
const didJustUpdateFileLoc = process.env.HOME+'/.HandyHost/siaData/isUpdating';
const didJustUpdate = fs.existsSync(didJustUpdateFileLoc);
if(!fs.existsSync(this.siaPortsPath)){
//console.log('sia ports are not present yet, hold...')
return false;
}
this.daemon.getVersion().then(data=>{
console.log('fetched version',data);
this.consensus.getChainStatus().then(d=>{
//console.log('chain stats',d);
if(typeof process.env.SCAUTO != "undefined"){
const encrypted = process.env.HOME+'/.HandyHost/keystore/'+process.env.SCAUTO;
if(fs.existsSync(encrypted)){
this.handyUtils.decrypt(encrypted,true).then(pass=>{
//unlock on startup so that we can host files else lose $$$
const passHash = crypto
.createHash("sha256")
.update(pass)
.digest("hex");
this.siaPasswordHash = passHash;
this.wallet.unlockWallet(pass).then(data=>{
console.log('wallet unlock success',data);
if(didJustUpdate){
fs.unlinkSync(didJustUpdateFileLoc);
Object.keys(this.ioNamespaces).map(serverName=>{
this.ioNamespaces[serverName].namespace.to('sia').emit('postUpdateSpawnFinished');
})
}
if(fs.existsSync(encrypted)){
fs.unlinkSync(encrypted);
this.handyUtils.encrypt(pass,true,'healthcheckSC',true).then(outpath=>{
process.env.SCAUTO = 'daemon_healthcheckSC';
});
}
if(wasFromHealthcheck){
const logString = new Date()+' :: healthcheck restarted siad\n';
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',logString,'utf8');
}
this.initHealthCheck();
}).catch(error=>{
console.log('error unlocking wallet',error);
});
})
}
}
else{
console.log('no sia autostart params found');
}
if(process.platform == 'darwin'){
//macos uses keychain
this.handyUtils.getDarwinKeychainPW('HANDYHOST_SCAUTO').then(data=>{
if(data.exists){
const passHash = crypto
.createHash("sha256")
.update(data.value)
.digest("hex");
this.siaPasswordHash = passHash;
this.wallet.unlockWallet(data.value).then(data=>{
console.log('wallet unlock success',data);
if(didJustUpdate){
fs.unlinkSync(didJustUpdateFileLoc);
Object.keys(this.ioNamespaces).map(serverName=>{
this.ioNamespaces[serverName].namespace.to('sia').emit('postUpdateSpawnFinished');
})
}
if(wasFromHealthcheck){
const logString = new Date()+' :: healthcheck restarted siad\n';
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',logString,'utf8');
}
this.initHealthCheck();
}).catch(error=>{
console.log('error unlocking wallet',error);
});
}
})
}
}).catch(e=>{
console.error('ERROR FETCHING CHAIN STATUS',e);
console.log('e?',e);
});
}).catch(e=>{
console.log('no version, must be dead')
this.daemon.siadSpawn().then(()=>{
this.attemptWalletUnlock(wasFromHealthcheck);
}).catch(e=>{
console.log('error spawning siad')
})
});
}
attemptWalletUnlock(wasFromHealthcheck){
setTimeout(()=>{
const didJustUpdateFileLoc = process.env.HOME+'/.HandyHost/siaData/isUpdating';
const didJustUpdate = fs.existsSync(didJustUpdateFileLoc);
//give a little time to boot it up..
if(typeof process.env.SCAUTO != "undefined"){
const encrypted = process.env.HOME+'/.HandyHost/keystore/'+process.env.SCAUTO;
if(fs.existsSync(encrypted)){
this.handyUtils.decrypt(encrypted,true).then(pass=>{
//unlock on startup so that we can host files else lose $$$
const passHash = crypto
.createHash("sha256")
.update(pass)
.digest("hex");
this.siaPasswordHash = passHash;
console.log('tryingwallet unlock')
this.wallet.unlockWallet(pass).then(data=>{
console.log('wallet unlock success');
if(fs.existsSync(encrypted)){
fs.unlinkSync(encrypted);
this.handyUtils.encrypt(pass,true,'healthcheckSC',true).then(outpath=>{
process.env.SCAUTO = 'daemon_healthcheckSC';
});
}
if(didJustUpdate){
fs.unlinkSync(didJustUpdateFileLoc);
Object.keys(this.ioNamespaces).map(serverName=>{
this.ioNamespaces[serverName].namespace.to('sia').emit('postUpdateSpawnFinished');
})
}
if(wasFromHealthcheck){
let logString = new Date()+' :: healthcheck restarted siad\n';
logString += 'sia wallet unlock output :: '+JSON.stringify(data)+'\n';
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',logString,'utf8');
}
this.initHealthCheck();
}).catch(error=>{
console.log('error unlocking wallet',error);
if(error.toString() == '490'){
this.attemptWalletUnlock(wasFromHealthcheck);
}
});
})
}
else{
console.log('no encrypted sia credentials found')
}
}
else{
if(process.platform == 'darwin'){
//macos uses keychain
this.handyUtils.getDarwinKeychainPW('HANDYHOST_SCAUTO').then(data=>{
if(data.exists){
const passHash = crypto
.createHash("sha256")
.update(data.value)
.digest("hex");
this.siaPasswordHash = passHash;
console.log('tryingwallet unlock')
this.wallet.unlockWallet(data.value).then(data=>{
console.log('wallet unlock success');
if(wasFromHealthcheck){
const logString = new Date()+' :: healthcheck restarted siad\n';
fs.appendFileSync(process.env.HOME+'/.HandyHost/siaData/healthcheck.log',logString,'utf8');
}
this.initHealthCheck();
}).catch(error=>{
console.log('error unlocking wallet',error);
if(error.toString() == '490'){
this.attemptWalletUnlock(wasFromHealthcheck);
}
});
}
else{
console.log('no encrypted sia credentials found')
}
})
}
else{
console.log('no encrypted sia credentials found')
}
}
/*if(typeof process.env.SIA_WALLET_PASSWORD != "undefined"){
//unlock on startup so that we can host files else lose $$$
console.log('tryingwallet unlock')
this.wallet.unlockWallet(process.env.SIA_WALLET_PASSWORD).then(data=>{
console.log('wallet unlock success');
}).catch(error=>{
console.log('error unlocking wallet',error);
if(error.toString() == '490'){
this.attemptWalletUnlock();
}
});
}*/
},5000);
}
api(path,requestBody,resolve,reject){
switch(`${path[1]}`){
case 'getHostConfig':
this.host.getHostInfo().then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
});
break;
case 'updateHostConfig':
console.log('got config data',requestBody)
//todo set config data
this.updateHostConfig(requestBody).then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
})
break;
case 'getDirList':
this.getDirList(path.slice(2,path.length)).then(list=>{
resolve(list);
}).catch(error=>{
reject(error);
})
break;
case 'addNewDirectory':
this.addNewDirectory(path.slice(2,path.length)).then(list=>{
resolve(list);
}).catch(error=>{
reject(error);
})
break;
case 'getDirCapacity':
this.getDirCapacity(path.slice(2,path.length)).then(meta=>{
resolve(meta);
}).catch(error=>{
reject(error);
})
break;
case 'getWalletInfo':
this.wallet.getWalletInfo().then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
})
break;
case 'initWallet':
this.initWallet(requestBody).then(data=>{
setTimeout(()=>{
this.updateEnvironment(requestBody).then(()=>{
resolve(data);
});
},1500); //give it time to make the wallet
}).catch(error=>{
reject(error);
})
break;
case 'getWalletAddress':
this.getLatestAddress().then(data=>{
resolve(data);
}).catch(err=>{
reject(err);
});
break;
case 'getNewWalletAddress':
this.wallet.getWalletAddress().then(data=>{
resolve(data);
}).catch(error=>{
console.log('err',error);
reject(error);
})
break;
case 'getChainStatus':
this.consensus.getChainStatus().then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
})
break;
case 'getQRCode':
this.getQRCode(path[2]).then(data=>{
resolve({qr:data});
}).catch(error=>{
reject(error);
})
break;
case 'getRecentTransactions':
this.wallet.getRecentTransactions().then(data=>{
if(data.confirmedtransactions != null){
data.confirmedtransactions = data.confirmedtransactions.reverse().slice(0,20);
}
resolve(data);
}).catch(e=>{
reject(e);
})
break;
case 'sendSC':
this.sendSC(requestBody).then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
})
break;
case 'getStorage':
//returns folders
this.host.getStorage().then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
})
break;
case 'updateFolders':
this.updateFolders(requestBody).then(data=>{
this.host.getStorage().then(d=>{
console.log('got storage then',d);
resolve(d);
}).catch(e=>{
reject(e);
});
}).catch(error=>{
reject(error);
})
break;
case 'getContracts':
this.host.getContracts().then(data=>{
resolve(data);
}).catch(e=>{
reject(e);
});
break;
case 'getContractByID':
this.host.getContract(path[2]).then(data=>{
resolve(data);
}).catch(e=>{
reject(e);
})
break;
case 'getScoreEstimate':
this.host.estimateScore().then(data=>{
resolve(data);
}).catch(e=>{
reject(e);
});
break;
case 'getHostPublicKey':
this.getHostPublicKey().then(data=>{
resolve(data);
}).catch(e=>{
reject(e);
});
break;
case 'getHostMetrics':
this.getHostMetrics().then(data=>{
resolve(data);
}).catch(e=>{
reject(e);
})
break;
case 'getPorts':
this.getSiaPorts().then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
})
break;
case 'setPorts':
this.setSiaPorts(requestBody).then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
})
break;
case 'updateSia':
this.updateSia().then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
})
break;
case 'getUpdatingStatus':
this.getUpdatingStatus().then(data=>{
resolve(data);
}).catch(error=>{
reject(error);
})
break;
}
}
getUpdatingStatus(){
return new Promise((resolve,reject)=>{
const didJustUpdateFileLoc = process.env.HOME+'/.HandyHost/siaData/isUpdating';
const didJustUpdate = fs.existsSync(didJustUpdateFileLoc);
resolve({updating:didJustUpdate});
});
}
updateSia(){
return new Promise((resolve,reject)=>{
const _this = this;
console.log('starting update',new Date())
this.daemon.updateDaemon().then(done=>{
done("");
}).catch(e=>{
console.log("update done?",e);
if(e == ""){
done(e);
}
else{
reject({error:e});
}
//reject(e);
})
function done(e){
console.log('update is done',new Date());
fs.writeFileSync(process.env.HOME+'/.HandyHost/siaData/isUpdating',"true",'utf8');
resolve({message:"Update Finished. Restarting Sia (may take anywhere from ~30-45 seconds up to 20 minutes)..."})
if(process.platform == 'darwin'){
//restart things
//trySpawningSiad()
_this.daemon.haltSiad().then(d=>{
console.log('halted siad, restarting now');
_this.trySpawningSiad();
});
}
else{
//systemctl restart
_this.daemon.haltSiad().then(d=>{
console.log('halted siad');
if(typeof process.env.HANDYHOST_BOOTSTRAPPED != "undefined"){
console.log('restart handyhost bootstrap dev')
spawn('sudo',['bash','./localdev_bootstrap.sh','restart'],{env:process.env,pwd:process.env.PWD});
}
else{
console.log('systemctl restart');
spawn('sudo',['systemctl','restart','handyhost'])
}
});
}
}
})
}
getSiaPorts(){
return new Promise((resolve,reject)=>{
let ports = {};
const portsFilePath = this.siaPortsPath;
let redlist = {};
if(fs.existsSync(this.redlistPortsPath)){
redlist = JSON.parse(fs.readFileSync(this.redlistPortsPath,'utf8'));
}
if(fs.existsSync(portsFilePath)){
ports = JSON.parse(fs.readFileSync(portsFilePath));
ports.redlist = redlist;
resolve(ports);
}
else{
//if no ports defined yet we give some info about port forwarding with the local IP
let getIPCommand;
let getIPOpts;
let ipCommand;
let ipRangeOut;
if(process.platform == 'darwin'){
getIPCommand = 'ipconfig';
getIPOpts = ['getifaddr', 'en0'];
}
if(process.platform == 'linux'){
//hostname -I [0]
getIPCommand = 'hostname';
getIPOpts = ['-I'];
}
ipCommand = spawn(getIPCommand,getIPOpts);
ipCommand.stdout.on('data',d=>{
ipRangeOut = d.toString('utf8').trim();
});
ipCommand.on('close',()=>{
if(process.platform == 'linux'){
ipRangeOut = ipRangeOut.split(' ')[0];
}
ports.ip = ipRangeOut;
ports.redlist = redlist;
resolve(ports);
});
}
})
}
setSiaPorts(requestBody){
const {parsed,err} = this.parseRequestBody(requestBody);
if(typeof parsed == "undefined"){
return new Promise((resolve,reject)=>{
reject(err);
})
}
return new Promise((resolve,reject)=>{
const portsFilePath = this.siaPortsPath;
parsed.portsSet = true;
let redlist = {};
let didChange = false;
if(fs.existsSync(portsFilePath)){
const existingPorts = JSON.parse(fs.readFileSync(portsFilePath));
Object.keys(existingPorts).map(label=>{
if(typeof parsed[label] == "undefined"){
didChange = true;
}
else{
if(parsed[label] != existingPorts[label]){
didChange = true;
}
}
})
}
if(fs.existsSync(this.redlistPortsPath)){
redlist = JSON.parse(fs.readFileSync(this.redlistPortsPath,'utf8'));
Object.keys(parsed).map(type=>{
if(type != "portsSet"){
Object.keys(redlist.custom).map(port=>{
const d = redlist.custom[port];
if(d.key == type){
delete redlist.custom[port];
}
});
redlist.custom[parsed[type]] = {
"description": "Sia Custom "+type+" Port",
"service":"SC",
"key":type
}
}
});
fs.writeFileSync(this.redlistPortsPath,JSON.stringify(redlist,null,2),'utf8');
}
fs.writeFileSync(portsFilePath,JSON.stringify(parsed),'utf8');
console.log('trying siad restart');
if(didChange){
setTimeout(()=>{
//give the host time to announce the new ports before we restart siad
this.consensus.getChainStatus().then(chainD=>{
console.log('about to halt siad');
this.daemon.haltSiad().then(d=>{
console.log('halted siad, restarting now');
this.trySpawningSiad(); //todo restart siad if it's already running???
resolve(parsed);
});
}).catch(error=>{
//not running
console.log('siad was not running, starting siad')
this.trySpawningSiad(); //todo restart siad if it's already running???
resolve(parsed);
});
},2000)
}
else{
console.log('no ports were changed, try to spawn siad just in case..')
this.trySpawningSiad(); //todo restart siad if it's already running???
resolve(parsed);
}
}).catch(error=>{
console.log('caught err',error);
reject(error);
})
//write to file
}
getHostMetrics(){
return new Promise((resolve,reject)=>{
//getHostInfo
this.host.getHostInfo().then(data=>{
let out = {
registryentriestotal:0,
registryentriesleft:0,
financialmetrics:{},
storagemetrics:{}
}
if(typeof data.pricetable != "undefined"){
out.registryentriesleft = data.pricetable.registryentriesleft;
out.registryentriestotal = data.pricetable.registryentriestotal;
}
if(typeof data.financialmetrics != "undefined"){
out.financialmetrics = data.financialmetrics;
}
this.host.getStorage().then(storageData=>{
out.storagemetrics = storageData;
resolve(out);
})
//resolve(out);
}).catch(e=>{
console.log('sia: getHostMetrics err',e);
})
})
}
getHostPublicKey(){
return new Promise((resolve,reject)=>{
this.host.getHostInfo().then(d=>{
let pk = d.publickey.key;
resolve(new Buffer.from(pk,'base64').toString('hex'));
}).catch(e=>{
reject(e);
})
})
}
updateHostConfig(requestBody){
const {parsed,err} = this.parseRequestBody(requestBody);
if(typeof parsed == "undefined"){
return new Promise((resolve,reject)=>{
reject(err);
})
}
console.log('update config',parsed);
return new Promise((resolve,reject)=>{
this.host.updateHostParameters(parsed).then(data=>{
if(parsed.acceptingcontracts){
//announce the host then
this.host.announceHost(parsed.netaddress).then(res=>{
console.log('announced',res);
resolve(data);
}).catch(e=>{
reject(e);
})
}
else{
resolve(data);
}
}).catch(e=>{
reject(e);
})
})
}
getFolderTypeCounts(folders){
let newCount = 0;
let editingCount = 0;
let deletingCount = 0;
folders.map(folder=>{
const isNew = folder.isNew;
const isEdited = folder.isEdited;
const isDeleting = folder.isDeleting;
if(isEdited && !isNew){
editingCount++;
}
if(isEdited && isNew){
newCount++;
}
if(isDeleting){
deletingCount++;
}
});
return {
changeCount:(editingCount+newCount+deletingCount)
};
}
updateFolders(requestBody){
const {parsed,err} = this.parseRequestBody(requestBody);
if(typeof parsed == "undefined"){
return new Promise((resolve,reject)=>{
reject(err);
})
}
console.log('to update folders',parsed,err);
return new Promise((resolve,reject)=>{
let finishedCount = 0;
const {changeCount} = this.getFolderTypeCounts(parsed);
console.log('changecount',changeCount);
parsed.map(folder=>{
const path = folder.path;
const capacity = folder.capacity;
const isNew = folder.isNew;
const isEdited = folder.isEdited;
const isDeleting = folder.isDeleting;
if(isEdited && !isNew){
//is not new but edited
this.host.resizeStorageFolder(path,capacity).then(data=>{
finishedCount += 1;
if(finishedCount == changeCount){
resolve();
}
}).catch(e=>{
finishedCount += 1;
if(finishedCount == changeCount){
resolve();
}
});
}
if(isEdited && isNew){
//is new
this.host.addStorageFolder(path,capacity).then(data=>{
finishedCount += 1;
if(finishedCount == changeCount){
resolve();
}
}).catch(e=>{
finishedCount += 1;
if(finishedCount == changeCount){
resolve();
}
});
}
if(isDeleting){
//should be deleted
this.host.removeStorageFolder(path,true).then(data=>{
finishedCount += 1;
if(finishedCount == changeCount){
resolve();
}
}).catch(e=>{
finishedCount += 1;
if(finishedCount == changeCount){
resolve();
}
})
}
})
});
}
sendSC(requestBody){
const {parsed,err} = this.parseRequestBody(requestBody);
if(typeof parsed == "undefined"){
return new Promise((resolve,reject)=>{
reject(err);
})
}
const destination = parsed.destination;
const amountHastings = parsed.amount;
const pw = parsed.pw;
console.log('amt',amountHastings);
console.log('dest',destination);
const passHash = crypto
.createHash("sha256")
.update(pw)
.digest("hex");
if(passHash != this.siaPasswordHash){
return new Promise((resolve,reject)=>{
reject({message:"Incorrect Encryption Password"})
})
}
/*if(pw != process.env.SIA_WALLET_PASSWORD){
return new Promise((resolve,reject)=>{
reject({message:"Incorrect Encryption Password"})
});
}*/
return this.wallet.sendCoins(amountHastings,destination);
}
getQRCode(address){
if(address == "undefined"){
return new Promise((resolve,reject)=>{
//get new address
this.wallet.getLatestAddress().then(data=>{
QRCode.toDataURL(data.address).then(qrResp=>{
resolve(qrResp);
}).catch(e=>{
reject(e);
})
}).catch(error=>{
console.log('err',error);
reject(error);
})
})
}
else{
return QRCode.toDataURL(address);
}
}
getLatestAddress(){
return new Promise((resolve,reject)=>{
this.wallet.getLatestWalletAddress().then(data=>{
if(typeof data.addresses == "undefined"){
this.wallet.getWalletAddress().then(newdata=>{
resolve(newdata);
}).catch(error=>{
console.log('err',error);
reject(error);
})
}
else{
resolve({address:data.addresses[data.addresses.length-1]});
}
}).catch(error=>{
console.log('err',error);
reject(error);
})
})
this.wallet.getLatestWalletAddress().then(data=>{
if(typeof data.addresses == "undefined"){
}
resolve(data);
}).catch(error=>{
console.log('err',error);
reject(error);
})
}
checkWalletStatus(){
//check if a wallet is syncing
return new Promise((resolve,reject)=>{
this.consensus.getChainStatus().then(chainData=>{
const chainHeight = chainData.height;
const isChainSynced = chainData.synced;
this.wallet.getWalletInfo().then(walletData=>{
const walletHeight = walletData.height;
if(walletHeight == 0 && !walletData.encrypted){
resolve(true);
}
resolve(walletHeight == chainHeight && isChainSynced);
});
})
})
}
initWallet(requestBody){
/*
first check if wallet is syncing.
I noticed that if I try to force create a new wallet during
a wallet sync it crashes siad.
*/
const _this = this;
const {parsed,err} = this.parseRequestBody(requestBody);
if(typeof parsed == "undefined"){
return new Promise((resolve,reject)=>{
reject(err);
})
}
if(parsed.import){
//init from seed
return this.wallet.initWalletFromSeed(parsed.seed, parsed.pw);
}
else{
return this.wallet.initWallet(parsed.pw);
}
}
manualWalletRemove(){
return new Promise((resolve,reject)=>{
this.daemon.stop().then(()=>{
let hasError = false;
try{
fs.rmSync(`${process.env.HOME}/.HandyHost/siaData/wallet`,{recursive:true,force:true});
}
catch(e){
console.log('error removing wallet');
hasError = true;
reject(e);
}
this.daemon.siadSpawn().then(()=>{
let checkupInterval = setInterval(()=>{
//give a little time to boot it up..
this.consensus.getChainStatus().then(d=>{
//console.log('chain stats',d);
console.log('chain stats up');
clearInterval(checkupInterval);
resolve();
}).catch(e=>{
console.error('ERROR FETCHING CHAIN STATUS',e);
console.log('e?',e);
});
},2000);
}).catch(e=>{
reject(e);
console.log('error spawning siad')
})
}).catch(error=>{
reject(error);
console.log('error stopping siad',error)
})
});
}
updateEnvironment(requestBody){
//it is recommended for sia hosting to always have the wallet unlocked so that
//our host is always serving. no unlocked wallet = no serving = potential loss of revenue
//due to power losses/unexpected restarts/etc.
//so we set the wallet unlock pw as an encrypted file that root gives to us on start/restart of the app
return new Promise((resolve,reject)=>{
const {parsed,err} = this.parseRequestBody(requestBody);
/*if(typeof parsed.pw != "undefined"){
fs.writeFileSync(`${process.env.HOME}/.HandyHost/siaData/.walletEnv`,parsed.pw);
process.env.SIA_WALLET_PASSWORD = parsed.pw;
}*/
//console.log('unlocking wallet',parsed.pw);
this.wallet.unlockWallet(parsed.pw).then(()=>{
if(process.platform == 'darwin'){
//well just use keychain on mac
//no daemons on mac bc user is always logged in