forked from byteball/headless-obyte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstart.js
776 lines (709 loc) · 26.1 KB
/
start.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
/*jslint node: true */
"use strict";
var fs = require('fs');
var crypto = require('crypto');
var util = require('util');
var constants = require('ocore/constants.js');
var desktopApp = require('ocore/desktop_app.js');
var appDataDir = desktopApp.getAppDataDir();
var path = require('path');
if (require.main === module && !fs.existsSync(appDataDir) && fs.existsSync(path.dirname(appDataDir)+'/headless-byteball')){
console.log('=== will rename old data dir');
fs.renameSync(path.dirname(appDataDir)+'/headless-byteball', appDataDir);
}
var conf = require('ocore/conf.js');
var objectHash = require('ocore/object_hash.js');
var db = require('ocore/db.js');
var eventBus = require('ocore/event_bus.js');
var ecdsaSig = require('ocore/signature.js');
var storage = require('ocore/storage.js');
var Mnemonic = require('bitcore-mnemonic');
var Bitcore = require('bitcore-lib');
var readline = require('readline');
var KEYS_FILENAME = appDataDir + '/' + (conf.KEYS_FILENAME || 'keys.json');
var wallet_id;
var xPrivKey;
function replaceConsoleLog(){
var log_filename = conf.LOG_FILENAME || (appDataDir + '/log.txt');
var writeStream = fs.createWriteStream(log_filename);
console.log('---------------');
console.log('From this point, output will be redirected to '+log_filename);
console.log("To release the terminal, type Ctrl-Z, then 'bg'");
console.log = function(){
writeStream.write(Date().toString()+': ');
writeStream.write(util.format.apply(null, arguments) + '\n');
};
console.warn = console.log;
console.info = console.log;
}
function readKeys(onDone){
console.log('-----------------------');
if (conf.control_addresses)
console.log("remote access allowed from devices: "+conf.control_addresses.join(', '));
if (conf.payout_address)
console.log("payouts allowed to address: "+conf.payout_address);
console.log('-----------------------');
fs.readFile(KEYS_FILENAME, 'utf8', function(err, data){
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
//terminal: true
});
if (err){ // first start
console.log('failed to read keys, will gen');
initConfJson(rl, function(){
rl.question('Passphrase for your private keys: ', function(passphrase){
rl.close();
if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1);
if (process.stdout.clearLine) process.stdout.clearLine();
var deviceTempPrivKey = crypto.randomBytes(32);
var devicePrevTempPrivKey = crypto.randomBytes(32);
var mnemonic = new Mnemonic(); // generates new mnemonic
while (!Mnemonic.isValid(mnemonic.toString()))
mnemonic = new Mnemonic();
writeKeys(mnemonic.phrase, deviceTempPrivKey, devicePrevTempPrivKey, function(){
console.log('keys created');
var xPrivKey = mnemonic.toHDPrivateKey(passphrase);
createWallet(xPrivKey, function(){
onDone(mnemonic.phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey);
});
});
});
});
}
else{ // 2nd or later start
rl.question("Passphrase: ", function(passphrase){
rl.close();
if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1);
if (process.stdout.clearLine) process.stdout.clearLine();
var keys = JSON.parse(data);
var deviceTempPrivKey = Buffer.from(keys.temp_priv_key, 'base64');
var devicePrevTempPrivKey = Buffer.from(keys.prev_temp_priv_key, 'base64');
determineIfWalletExists(function(bWalletExists){
if (bWalletExists)
onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey);
else{
var mnemonic = new Mnemonic(keys.mnemonic_phrase);
var xPrivKey = mnemonic.toHDPrivateKey(passphrase);
createWallet(xPrivKey, function(){
onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey);
});
}
});
});
}
});
}
function initConfJson(rl, onDone){
var userConfFile = appDataDir + '/conf.json';
var confJson = null;
try {
confJson = require(userConfFile);
}
catch(e){
}
if (conf.deviceName && conf.deviceName !== 'Headless') // already set in conf.js or conf.json
return confJson ? onDone() : writeJson(userConfFile, {}, onDone);
// continue if device name not set
if (!confJson)
confJson = {};
var suggestedDeviceName = require('os').hostname() || 'Headless';
rl.question("Please name this device ["+suggestedDeviceName+"]: ", function(deviceName){
if (!deviceName)
deviceName = suggestedDeviceName;
confJson.deviceName = deviceName;
writeJson(userConfFile, confJson, function(){
console.log('Device name saved to '+userConfFile+', you can edit it later if you like.\n');
onDone();
});
});
}
function writeJson(filename, json, onDone){
fs.writeFile(filename, JSON.stringify(json, null, '\t'), 'utf8', function(err){
if (err)
throw Error('failed to write conf.json: '+err);
onDone();
});
}
function writeKeys(mnemonic_phrase, deviceTempPrivKey, devicePrevTempPrivKey, onDone){
var keys = {
mnemonic_phrase: mnemonic_phrase,
temp_priv_key: deviceTempPrivKey.toString('base64'),
prev_temp_priv_key: devicePrevTempPrivKey.toString('base64')
};
fs.writeFile(KEYS_FILENAME, JSON.stringify(keys, null, '\t'), 'utf8', function(err){
if (err)
throw Error("failed to write keys file");
if (onDone)
onDone();
});
}
function createWallet(xPrivKey, onDone){
var devicePrivKey = xPrivKey.derive("m/1'").privateKey.bn.toBuffer({size:32});
var device = require('ocore/device.js');
device.setDevicePrivateKey(devicePrivKey); // we need device address before creating a wallet
var strXPubKey = Bitcore.HDPublicKey(xPrivKey.derive("m/44'/0'/0'")).toString();
var walletDefinedByKeys = require('ocore/wallet_defined_by_keys.js');
// we pass isSingleAddress=false because this flag is meant to be forwarded to cosigners and headless wallet doesn't support multidevice
walletDefinedByKeys.createWalletByDevices(strXPubKey, 0, 1, [], 'any walletName', false, function(wallet_id){
walletDefinedByKeys.issueNextAddress(wallet_id, 0, function(addressInfo){
onDone();
});
});
}
function isControlAddress(device_address){
return (conf.control_addresses && conf.control_addresses.indexOf(device_address) >= 0);
}
function readSingleAddress(handleAddress){
db.query("SELECT address FROM my_addresses WHERE wallet=?", [wallet_id], function(rows){
if (rows.length === 0)
throw Error("no addresses");
if (rows.length > 1)
throw Error("more than 1 address");
handleAddress(rows[0].address);
});
}
function readFirstAddress(handleAddress){
db.query("SELECT address FROM my_addresses WHERE wallet=? AND address_index=0 AND is_change=0", [wallet_id], function(rows){
if (rows.length === 0)
throw Error("no addresses");
if (rows.length > 1)
throw Error("more than 1 address");
handleAddress(rows[0].address);
});
}
function prepareBalanceText(handleBalanceText){
var Wallet = require('ocore/wallet.js');
Wallet.readBalance(wallet_id, function(assocBalances){
var arrLines = [];
for (var asset in assocBalances){
var total = assocBalances[asset].stable + assocBalances[asset].pending;
var units = (asset === 'base') ? ' bytes' : (' of ' + asset);
var line = total + units;
if (assocBalances[asset].pending)
line += ' (' + assocBalances[asset].pending + ' pending)';
arrLines.push(line);
}
handleBalanceText(arrLines.join("\n"));
});
}
function readSingleWallet(handleWallet){
db.query("SELECT wallet FROM wallets", function(rows){
if (rows.length === 0)
throw Error("no wallets");
if (rows.length > 1)
throw Error("more than 1 wallet");
handleWallet(rows[0].wallet);
});
}
function determineIfWalletExists(handleResult){
db.query("SELECT wallet FROM wallets", function(rows){
if (rows.length > 1)
throw Error("more than 1 wallet");
handleResult(rows.length > 0);
});
}
function signWithLocalPrivateKey(wallet_id, account, is_change, address_index, text_to_sign, handleSig){
var path = "m/44'/0'/" + account + "'/"+is_change+"/"+address_index;
var privateKey = xPrivKey.derive(path).privateKey;
var privKeyBuf = privateKey.bn.toBuffer({size:32}); // https://github.com/bitpay/bitcore-lib/issues/47
handleSig(ecdsaSig.sign(text_to_sign, privKeyBuf));
}
var signer = {
readSigningPaths: function(conn, address, handleLengthsBySigningPaths){
handleLengthsBySigningPaths({r: constants.SIG_LENGTH});
},
readDefinition: function(conn, address, handleDefinition){
conn.query("SELECT definition FROM my_addresses WHERE address=?", [address], function(rows){
if (rows.length !== 1)
throw Error("definition not found");
handleDefinition(null, JSON.parse(rows[0].definition));
});
},
sign: function(objUnsignedUnit, assocPrivatePayloads, address, signing_path, handleSignature){
var buf_to_sign = objectHash.getUnitHashToSign(objUnsignedUnit);
db.query(
"SELECT wallet, account, is_change, address_index \n\
FROM my_addresses JOIN wallets USING(wallet) JOIN wallet_signing_paths USING(wallet) \n\
WHERE address=? AND signing_path=?",
[address, signing_path],
function(rows){
if (rows.length !== 1)
throw Error(rows.length+" indexes for address "+address+" and signing path "+signing_path);
var row = rows[0];
signWithLocalPrivateKey(row.wallet, row.account, row.is_change, row.address_index, buf_to_sign, function(sig){
handleSignature(null, sig);
});
}
);
}
};
if (conf.permanent_pairing_secret)
db.query(
"INSERT "+db.getIgnore()+" INTO pairing_secrets (pairing_secret, is_permanent, expiry_date) VALUES (?, 1, '2038-01-01')",
[conf.permanent_pairing_secret]
);
setTimeout(function(){
readKeys(function(mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey){
var saveTempKeys = function(new_temp_key, new_prev_temp_key, onDone){
writeKeys(mnemonic_phrase, new_temp_key, new_prev_temp_key, onDone);
};
var mnemonic = new Mnemonic(mnemonic_phrase);
// global
xPrivKey = mnemonic.toHDPrivateKey(passphrase);
var devicePrivKey = xPrivKey.derive("m/1'").privateKey.bn.toBuffer({size:32});
// read the id of the only wallet
readSingleWallet(function(wallet){
// global
wallet_id = wallet;
require('ocore/wallet.js'); // we don't need any of its functions but it listens for hub/* messages
var device = require('ocore/device.js');
device.setDevicePrivateKey(devicePrivKey);
let my_device_address = device.getMyDeviceAddress();
db.query("SELECT 1 FROM extended_pubkeys WHERE device_address=?", [my_device_address], function(rows){
if (rows.length > 1)
throw Error("more than 1 extended_pubkey?");
if (rows.length === 0)
return setTimeout(function(){
console.log('passphrase is incorrect');
process.exit(0);
}, 1000);
device.setTempKeys(deviceTempPrivKey, devicePrevTempPrivKey, saveTempKeys);
device.setDeviceName(conf.deviceName);
device.setDeviceHub(conf.hub);
let my_device_pubkey = device.getMyDevicePubKey();
console.log("====== my device address: "+my_device_address);
console.log("====== my device pubkey: "+my_device_pubkey);
if (conf.bSingleAddress)
readSingleAddress(function(address){
console.log("====== my single address: "+address);
});
else
readFirstAddress(function(address){
console.log("====== my first address: "+address);
});
if (conf.permanent_pairing_secret)
console.log("====== my pairing code: "+my_device_pubkey+"@"+conf.hub+"#"+conf.permanent_pairing_secret);
if (conf.bLight){
var light_wallet = require('ocore/light_wallet.js');
light_wallet.setLightVendorHost(conf.hub);
}
eventBus.emit('headless_wallet_ready');
setTimeout(replaceConsoleLog, 1000);
if (conf.MAX_UNSPENT_OUTPUTS && conf.CONSOLIDATION_INTERVAL){
var consolidation = require('./consolidation.js');
consolidation.scheduleConsolidation(wallet_id, signer, conf.MAX_UNSPENT_OUTPUTS, conf.CONSOLIDATION_INTERVAL);
}
});
});
});
}, 1000);
function handlePairing(from_address){
var device = require('ocore/device.js');
prepareBalanceText(function(balance_text){
device.sendMessageToDevice(from_address, 'text', balance_text);
});
}
function sendPayment(asset, amount, to_address, change_address, device_address, onDone){
if(!onDone) {
return new Promise((resolve, reject) => {
sendPayment(asset, amount, to_address, change_address, device_address, (err, unit, assocMnemonics) => {
if (err) return reject(new Error(err));
return resolve({unit, assocMnemonics});
});
});
}
var device = require('ocore/device.js');
var Wallet = require('ocore/wallet.js');
Wallet.sendPaymentFromWallet(
asset, wallet_id, to_address, amount, change_address,
[], device_address,
signWithLocalPrivateKey,
function(err, unit, assocMnemonics){
if (device_address) {
if (err)
device.sendMessageToDevice(device_address, 'text', "Failed to pay: " + err);
// else
// if successful, the peer will also receive a payment notification
// device.sendMessageToDevice(device_address, 'text', "paid");
}
if (onDone)
onDone(err, unit, assocMnemonics);
}
);
}
function sendMultiPayment(opts, onDone){
if(!onDone) {
return new Promise((resolve, reject) => {
sendMultiPayment(opts, (err, unit, assocMnemonics) => {
if (err) return reject(new Error(err));
return resolve({unit, assocMnemonics});
});
});
}
var device = require('ocore/device.js');
var Wallet = require('ocore/wallet.js');
if (!opts.paying_addresses)
opts.wallet = wallet_id;
if (!opts.change_address)
throw Error("no change address");
opts.arrSigningDeviceAddresses = [device.getMyDeviceAddress()];
opts.signWithLocalPrivateKey = signWithLocalPrivateKey;
Wallet.sendMultiPayment(opts, (err, unit, assocMnemonics) => {
if (onDone)
onDone(err, unit, assocMnemonics);
});
}
function sendPaymentUsingOutputs(asset, outputs, change_address, onDone) {
if(!onDone) {
return new Promise((resolve, reject) => {
sendPaymentUsingOutputs(asset, outputs, change_address, (err, unit, assocMnemonics) => {
if (err) return reject(new Error(err));
return resolve({unit, assocMnemonics});
});
});
}
var device = require('ocore/device.js');
var Wallet = require('ocore/wallet.js');
var opt = {
asset: asset,
wallet: wallet_id,
change_address: change_address,
arrSigningDeviceAddresses: [device.getMyDeviceAddress()],
recipient_device_address: null,
signWithLocalPrivateKey: signWithLocalPrivateKey
};
if(asset === 'base' || asset === null){
opt.base_outputs = outputs;
}else{
opt.asset_outputs = outputs;
}
Wallet.sendMultiPayment(opt, (err, unit, assocMnemonics) => {
if (onDone)
onDone(err, unit, assocMnemonics);
});
}
function sendAllBytes(to_address, recipient_device_address, onDone) {
if(!onDone) {
return new Promise((resolve, reject) => {
sendAllBytes(to_address, recipient_device_address, (err, unit, assocMnemonics) => {
if (err) return reject(new Error(err));
return resolve({unit, assocMnemonics});
});
});
}
var device = require('ocore/device.js');
var Wallet = require('ocore/wallet.js');
Wallet.sendMultiPayment({
asset: null,
to_address: to_address,
send_all: true,
wallet: wallet_id,
arrSigningDeviceAddresses: [device.getMyDeviceAddress()],
recipient_device_address: recipient_device_address,
signWithLocalPrivateKey: signWithLocalPrivateKey
}, (err, unit, assocMnemonics) => {
if (onDone)
onDone(err, unit, assocMnemonics);
});
}
function sendAllBytesFromAddress(from_address, to_address, recipient_device_address, onDone) {
if(!onDone) {
return new Promise((resolve, reject) => {
sendAllBytesFromAddress(from_address, to_address, recipient_device_address, (err, unit, assocMnemonics) => {
if (err) return reject(new Error(err));
return resolve({unit, assocMnemonics});
});
});
}
var device = require('ocore/device.js');
var Wallet = require('ocore/wallet.js');
Wallet.sendMultiPayment({
asset: null,
to_address: to_address,
send_all: true,
paying_addresses: [from_address],
arrSigningDeviceAddresses: [device.getMyDeviceAddress()],
recipient_device_address: recipient_device_address,
signWithLocalPrivateKey: signWithLocalPrivateKey
}, (err, unit, assocMnemonics) => {
if(onDone)
onDone(err, unit, assocMnemonics);
});
}
function sendAssetFromAddress(asset, amount, from_address, to_address, recipient_device_address, onDone) {
if(!onDone) {
return new Promise((resolve, reject) => {
sendAssetFromAddress(asset, amount, from_address, to_address, recipient_device_address, (err, unit, assocMnemonics) => {
if (err) return reject(new Error(err));
return resolve({unit, assocMnemonics});
});
});
}
var device = require('ocore/device.js');
var Wallet = require('ocore/wallet.js');
Wallet.sendMultiPayment({
fee_paying_wallet: wallet_id,
asset: asset,
to_address: to_address,
amount: amount,
paying_addresses: [from_address],
change_address: from_address,
arrSigningDeviceAddresses: [device.getMyDeviceAddress()],
recipient_device_address: recipient_device_address,
signWithLocalPrivateKey: signWithLocalPrivateKey
}, (err, unit, assocMnemonics) => {
if (onDone)
onDone(err, unit, assocMnemonics);
});
}
function issueChangeAddressAndSendPayment(asset, amount, to_address, device_address, onDone){
if(!onDone) {
return new Promise((resolve, reject) => {
issueChangeAddressAndSendPayment(asset, amount, to_address, device_address, (err, unit, assocMnemonics) => {
if (err) return reject(new Error(err));
return resolve({unit, assocMnemonics});
});
});
}
issueChangeAddress(function(change_address){
sendPayment(asset, amount, to_address, change_address, device_address, onDone);
});
}
function issueChangeAddressAndSendMultiPayment(opts, onDone){
if(!onDone) {
return new Promise((resolve, reject) => {
issueChangeAddressAndSendMultiPayment(opts, (err, unit, assocMnemonics) => {
if (err) return reject(new Error(err));
return resolve({unit, assocMnemonics});
});
});
}
issueChangeAddress(function(change_address){
opts.change_address = change_address;
sendMultiPayment(opts, onDone);
});
}
function issueOrSelectNextMainAddress(handleAddress){
var walletDefinedByKeys = require('ocore/wallet_defined_by_keys.js');
walletDefinedByKeys.issueOrSelectNextAddress(wallet_id, 0, function(objAddr){
handleAddress(objAddr.address);
});
}
function issueNextMainAddress(handleAddress){
var walletDefinedByKeys = require('ocore/wallet_defined_by_keys.js');
walletDefinedByKeys.issueNextAddress(wallet_id, 0, function(objAddr){
handleAddress(objAddr.address);
});
}
function issueOrSelectAddressByIndex(is_change, address_index, handleAddress){
var walletDefinedByKeys = require('ocore/wallet_defined_by_keys.js');
walletDefinedByKeys.readAddressByIndex(wallet_id, is_change, address_index, function(objAddr){
if (objAddr)
return handleAddress(objAddr.address);
walletDefinedByKeys.issueAddress(wallet_id, is_change, address_index, function(objAddr){
handleAddress(objAddr.address);
});
});
}
function issueOrSelectStaticChangeAddress(handleAddress){
issueOrSelectAddressByIndex(1, 0, handleAddress);
}
function issueChangeAddress(handleAddress){
if (conf.bSingleAddress)
readSingleAddress(handleAddress);
else if (conf.bStaticChangeAddress)
issueOrSelectStaticChangeAddress(handleAddress);
else{
var walletDefinedByKeys = require('ocore/wallet_defined_by_keys.js');
walletDefinedByKeys.issueOrSelectNextChangeAddress(wallet_id, function(objAddr){
handleAddress(objAddr.address);
});
}
}
function signMessage(signing_address, message, cb) {
var device = require('ocore/device.js');
var Wallet = require('ocore/wallet.js');
Wallet.signMessage(signing_address, message, [device.getMyDeviceAddress()], signWithLocalPrivateKey, cb);
}
function handleText(from_address, text, onUnknown){
text = text.trim();
var fields = text.split(/ /);
var command = fields[0].trim().toLowerCase();
var params =['',''];
if (fields.length > 1) params[0] = fields[1].trim();
if (fields.length > 2) params[1] = fields[2].trim();
var walletDefinedByKeys = require('ocore/wallet_defined_by_keys.js');
var device = require('ocore/device.js');
switch(command){
case 'address':
if (conf.bSingleAddress)
readSingleAddress(function(address){
device.sendMessageToDevice(from_address, 'text', address);
});
else
walletDefinedByKeys.issueOrSelectNextAddress(wallet_id, 0, function(addressInfo){
device.sendMessageToDevice(from_address, 'text', addressInfo.address);
});
break;
case 'balance':
prepareBalanceText(function(balance_text){
device.sendMessageToDevice(from_address, 'text', balance_text);
});
break;
case 'pay':
analyzePayParams(params[0], params[1], function(asset, amount){
if(asset===null && amount===null){
var msg = "syntax: pay [amount] [asset]";
msg += "\namount: digits only";
msg += "\nasset: one of '', 'bytes', 'blackbytes', ASSET_ID";
msg += "\n";
msg += "\nExample 1: 'pay 12345' pays 12345 bytes";
msg += "\nExample 2: 'pay 12345 bytes' pays 12345 bytes";
msg += "\nExample 3: 'pay 12345 blackbytes' pays 12345 blackbytes";
msg += "\nExample 4: 'pay 12345 qO2JsiuDMh/j+pqJYZw3u82O71WjCDf0vTNvsnntr8o=' pays 12345 blackbytes";
msg += "\nExample 5: 'pay 12345 ASSET_ID' pays 12345 of asset with ID ASSET_ID";
return device.sendMessageToDevice(from_address, 'text', msg);
}
if (!conf.payout_address)
return device.sendMessageToDevice(from_address, 'text', "payout address not defined");
function payout(amount, asset){
if (conf.bSingleAddress)
readSingleAddress(function(address){
sendPayment(asset, amount, conf.payout_address, address, from_address);
});
else
// create a new change address or select first unused one
issueChangeAddressAndSendPayment(asset, amount, conf.payout_address, from_address);
};
if(asset!==null){
db.query("SELECT unit FROM assets WHERE unit=?", [asset], function(rows){
if(rows.length===1){
// asset exists
payout(amount, asset);
}else{
// unknown asset
device.sendMessageToDevice(from_address, 'text', 'unknown asset: '+asset);
}
});
}else{
payout(amount, asset);
}
});
break;
case 'mci':
storage.readLastMainChainIndex(function(last_mci){
device.sendMessageToDevice(from_address, 'text', last_mci.toString());
});
break;
case 'space':
getFileSizes(appDataDir, function(data) {
var total_space = 0;
var response = '';
Object.keys(data).forEach(function(key) {
total_space += data[key];
response += key +' '+ niceBytes(data[key]) +"\n";
});
response += 'Total: '+ niceBytes(total_space);
device.sendMessageToDevice(from_address, 'text', response);
});
break;
default:
if (onUnknown)
onUnknown(from_address, text);
else if (require.main === module)
device.sendMessageToDevice(from_address, 'text', "unrecognized command");
break;
}
}
function niceBytes(x){
// source: https://stackoverflow.com/a/39906526
const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
let l = 0, n = parseInt(x, 10) || 0;
while(n >= 1024 && ++l)
n = n/1024;
//include a decimal point and a tenths-place digit if presenting
//less than ten of KB or greater units
return(n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}
function getFileSizes(rootDir, cb) {
fs.readdir(rootDir, function(err, files) {
var fileSizes = {};
for (var index = 0; index < files.length; ++index) {
var file = files[index];
if (file[0] !== '.') {
var filePath = rootDir + '/' + file;
fs.stat(filePath, function(err, stat) {
if (stat.isFile()) {
fileSizes[this.file] = stat['size'];
}
if (files.length === (this.index + 1)) {
return cb(fileSizes);
}
}.bind({index: index, file: file}));
}
}
});
}
function analyzePayParams(amountText, assetText, cb){
// expected:
// amountText = amount; only digits
// assetText = asset; '' -> whitebytes, 'bytes' -> whitebytes, 'blackbytes' -> blackbytes, '{asset-ID}' -> any asset
if (amountText===''&&assetText==='') return cb(null, null);
var pattern = /^\d+$/;
if(pattern.test(amountText)){
var amount = parseInt(amountText);
var asset = assetText.toLowerCase();
switch(asset){
case '':
case 'bytes':
return cb(null, amount);
case 'blackbytes':
return cb(constants.BLACKBYTES_ASSET, amount);
default:
// return original assetText string because asset ID it is case sensitive
return cb(assetText, amount);
}
}else{
return cb(null, null);
}
}
// The below events can arrive only after we read the keys and connect to the hub.
// The event handlers depend on the global var wallet_id being set, which is set after reading the keys
function setupChatEventHandlers(){
eventBus.on('paired', function(from_address){
console.log('paired '+from_address);
if (!isControlAddress(from_address))
return console.log('ignoring pairing from non-control address');
handlePairing(from_address);
});
eventBus.on('text', function(from_address, text){
console.log('text from '+from_address+': '+text);
if (!isControlAddress(from_address))
return console.log('ignoring text from non-control address');
handleText(from_address, text);
});
}
exports.readSingleWallet = readSingleWallet;
exports.readSingleAddress = readSingleAddress;
exports.readFirstAddress = readFirstAddress;
exports.signer = signer;
exports.isControlAddress = isControlAddress;
exports.issueOrSelectNextMainAddress = issueOrSelectNextMainAddress;
exports.issueNextMainAddress = issueNextMainAddress;
exports.issueOrSelectAddressByIndex = issueOrSelectAddressByIndex;
exports.issueOrSelectStaticChangeAddress = issueOrSelectStaticChangeAddress;
exports.issueChangeAddressAndSendPayment = issueChangeAddressAndSendPayment;
exports.signMessage = signMessage;
exports.signWithLocalPrivateKey = signWithLocalPrivateKey;
exports.setupChatEventHandlers = setupChatEventHandlers;
exports.handlePairing = handlePairing;
exports.handleText = handleText;
exports.sendAllBytesFromAddress = sendAllBytesFromAddress;
exports.sendAssetFromAddress = sendAssetFromAddress;
exports.sendAllBytes = sendAllBytes;
exports.sendPaymentUsingOutputs = sendPaymentUsingOutputs;
exports.sendMultiPayment = sendMultiPayment;
exports.issueChangeAddressAndSendMultiPayment = issueChangeAddressAndSendMultiPayment;
if (require.main === module)
setupChatEventHandlers();