forked from Senyoret1/hardware-wallet-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
device-wallet.js
1198 lines (1134 loc) · 42 KB
/
device-wallet.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
const HID = require('node-hid');
const messages = require('./protob/skycoin');
const bufReceiver = require('./buffer-receiver');
const dgram = require('dgram');
const scanf = require('scanf');
const os = require('os');
let deviceType = 0;
const setDeviceType = function(devType) {
deviceType = devType;
};
const dataBytesFromChunks = function(chunks) {
const dataBytes = [];
chunks.forEach((chunk, j) => {
chunk.forEach((elt, i) => {
dataBytes[(64 * j) + i] = elt;
});
});
return dataBytes;
};
// Returns a handle to usbhid device
const getDevice = function() {
const deviceInfo = HID.devices().find( function(d) {
const isTeensy = d.manufacturer == "SkycoinFoundation";
return isTeensy;
});
if( deviceInfo ) {
const device = new HID.HID( deviceInfo.path );
return device;
}
return null;
};
// Prepares buffer containing message to device
// eslint-disable-next-line max-statements
const makeTrezorMessage = function(buffer, msgId) {
const u8Array = new Uint8Array(buffer);
const trezorMsg = new ArrayBuffer(10 + u8Array.byteLength - 1);
const dv = new DataView(trezorMsg);
// Adding the '##' at the begining of the header
dv.setUint8(0, 35);
dv.setUint8(1, 35);
dv.setUint16(2, msgId);
dv.setUint32(4, u8Array.byteLength);
// Adding '\n' at the end of the header
dv.setUint8(8, 10);
const trezorMsg8 = new Uint8Array(trezorMsg);
trezorMsg8.set(u8Array.slice(1), 9);
let lengthToWrite = u8Array.byteLength + 9;
const chunks = [];
let j = 0;
do {
const u64pack = new Uint8Array(64);
u64pack[0] = 63;
u64pack.set(trezorMsg8.slice(63 * j, 63 * (j + 1)), 1);
lengthToWrite -= 63;
chunks[j] = u64pack;
j += 1;
} while (lengthToWrite > 0);
return chunks;
};
const emulatorSend = function(client, message) {
console.log("Sending data", message, message.length);
const nbChunks = message.length / 64;
for (let i = 0; i < nbChunks; i += 1) {
client.send(
message.slice(64 * i, 64 * (i + 1)), 0, 64, 21324, '127.0.0.1',
function(err, bytes) {
if (err) {
throw err;
}
console.log("Sending data", bytes);
}
);
}
};
DeviceTypeEnum = {
'EMULATOR': 1,
'USB': 2
};
class DeviceHandler {
constructor(devType) {
this.deviceType = devType;
this.devHandle = this.getDeviceHandler();
}
getDeviceHandler() {
console.log("Device Open");
switch (this.deviceType) {
case DeviceTypeEnum.USB:
{
const dev = getDevice();
if (dev === null) {
throw new Error("Device not connected");
}
return dev;
}
case DeviceTypeEnum.EMULATOR:
{
const client = dgram.createSocket('udp4');
return client;
}
default:
throw new Error("Device type not defined");
}
}
read(devReadCallback) {
const bufferReceiver = new bufReceiver.BufferReceiver();
switch (this.deviceType) {
case DeviceTypeEnum.USB:
{
const devHandle = this.devHandle;
const devHandleCallback = function(err, data) {
if (err) {
console.error(err);
return;
}
bufferReceiver.receiveBuffer(data, devReadCallback);
if (bufferReceiver.bytesToGet > 0) {
console.log("Reading one more time", devHandle);
devHandle.read(devHandleCallback);
}
};
devHandle.read(devHandleCallback);
}
break;
case DeviceTypeEnum.EMULATOR:
this.devHandle.on('message', function(data, rinfo) {
if (rinfo) {
console.log(`server got:
${data} from ${rinfo.address}:${rinfo.port}`);
}
bufferReceiver.receiveBuffer(data, devReadCallback);
});
break;
default:
throw new Error("Device type not defined");
}
}
// eslint-disable-next-line max-statements
write(dataBytes) {
switch (this.deviceType) {
case DeviceTypeEnum.USB:
{
console.log("Writing a buffer of length ", dataBytes.length, "to the device");
let j = 0;
let lengthToWrite = dataBytes.length;
do{
const u64pack = dataBytes.slice(64 * j, 64 * (j + 1));
if (os.platform() == 'win32') {
u64pack.unshift(0x00);
}
this.devHandle.write(u64pack);
j += 1;
lengthToWrite -= 64;
} while (lengthToWrite > 0);
break;
}
case DeviceTypeEnum.EMULATOR:
emulatorSend(this.devHandle, Buffer.from(dataBytes));
break;
default:
throw new Error("Device type not defined");
}
}
reopen() {
this.close();
this.devHandle = this.getDeviceHandler();
}
close() {
console.log("Device Close");
switch (this.deviceType) {
case DeviceTypeEnum.USB:
this.devHandle.close();
break;
case DeviceTypeEnum.EMULATOR:
this.devHandle.close();
break;
default:
throw new Error("Device type not defined");
}
}
}
const createInitializeRequest = function() {
const msgStructure = {};
const msg = messages.Initialize.create(msgStructure);
const buffer = messages.Initialize.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_Initialize
);
return dataBytesFromChunks(chunks);
};
const createGetFeaturesRequest = function() {
const msgStructure = {};
const msg = messages.GetFeatures.create(msgStructure);
const buffer = messages.GetFeatures.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_GetFeatures
);
return dataBytesFromChunks(chunks);
};
const createApplySettings = function(usePassphrase) {
const msgStructure = {
"label": "",
"language": "",
usePassphrase
};
const msg = messages.ApplySettings.create(msgStructure);
const buffer = messages.ApplySettings.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_ApplySettings
);
return dataBytesFromChunks(chunks);
};
const createPassphraseRequest = function(passphrase) {
const msgStructure = {
passphrase
};
const msg = messages.PassphraseAck.create(msgStructure);
const buffer = messages.PassphraseAck.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_PassphraseAck
);
return dataBytesFromChunks(chunks);
};
const createButtonAckRequest = function() {
const msgStructure = {};
const msg = messages.ButtonAck.create(msgStructure);
const buffer = messages.ButtonAck.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_ButtonAck
);
return dataBytesFromChunks(chunks);
};
const createCancelRequest = function() {
const msgStructure = {};
const msg = messages.Cancel.create(msgStructure);
const buffer = messages.Cancel.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_Cancel
);
return dataBytesFromChunks(chunks);
};
const createChangePinRequest = function(mnemonic) {
const msgStructure = {
mnemonic
};
const msg = messages.ChangePin.create(msgStructure);
const buffer = messages.ChangePin.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_ChangePin
);
return dataBytesFromChunks(chunks);
};
const createWordAckRequest = function(word) {
const msgStructure = {
word
};
const msg = messages.WordAck.create(msgStructure);
const buffer = messages.WordAck.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_WordAck
);
return dataBytesFromChunks(chunks);
};
const createSetMnemonicRequest = function(mnemonic) {
const msgStructure = {
mnemonic
};
const msg = messages.SetMnemonic.create(msgStructure);
const buffer = messages.SetMnemonic.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_SetMnemonic
);
return dataBytesFromChunks(chunks);
};
const createGenerateMnemonicRequest = function(usePassphrase) {
const msgStructure = {
"passphraseProtection": usePassphrase
};
const msg = messages.GenerateMnemonic.create(msgStructure);
const buffer = messages.GenerateMnemonic.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_GenerateMnemonic
);
return dataBytesFromChunks(chunks);
};
const createGetVersionRequest = function() {
const msgStructure = {};
const msg = messages.GetVersion.create(msgStructure);
const buffer = messages.GetVersion.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_GetVersion
);
return dataBytesFromChunks(chunks);
};
const createWipeDeviceRequest = function() {
const msgStructure = {};
const msg = messages.WipeDevice.create(msgStructure);
const buffer = messages.WipeDevice.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_WipeDevice
);
return dataBytesFromChunks(chunks);
};
const createRecoveryDeviceRequest = function(usePassphrase) {
const msgStructure = {
'dryRun': false,
'enforceWordlist': true,
"passphraseProtection": usePassphrase,
'wordCount': 12
};
const msg = messages.RecoveryDevice.create(msgStructure);
const buffer = messages.RecoveryDevice.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_RecoveryDevice
);
return dataBytesFromChunks(chunks);
};
const createBackupDeviceRequest = function() {
const msgStructure = {};
const msg = messages.BackupDevice.create(msgStructure);
const buffer = messages.BackupDevice.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_BackupDevice
);
return dataBytesFromChunks(chunks);
};
// eslint-disable-next-line max-statements
const createTransactionSignRequest = function(inputTransactions, outputTransactions) {
const transactionIn = [];
const transactionOut = [];
const nbIn = inputTransactions.length;
const nbOut = outputTransactions.length;
for (i = 0; i < nbIn; i += 1) {
transactionIn[i] = {
'hashIn': inputTransactions[i].hashIn,
'index': inputTransactions[i].index
};
console.log(
"Pushing input:",
transactionIn[i].hashIn,
"index: ",
transactionIn[i].index
);
}
for (i = 0; i < nbOut; i += 1) {
transactionOut[i] = {
'address': outputTransactions[i].address,
'addressIndex': outputTransactions[i].address_index,
'coin': outputTransactions[i].coin,
'hour': outputTransactions[i].hour
};
console.log(
"Pushing output:",
transactionOut[i].address,
"coin:", transactionOut[i].coin,
"hour:", transactionOut[i].hour,
"address_index:", transactionOut[i].addressIndex
);
}
console.log("ArrayBuffer input len: ", transactionIn.length);
console.log("ArrayBuffer output len: ", transactionOut.length);
const msgStructure = {
nbIn,
nbOut,
transactionIn,
transactionOut
};
const msg = messages.TransactionSign.create(msgStructure);
const buffer = messages.TransactionSign.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_TransactionSign
);
return dataBytesFromChunks(chunks);
};
const createSignMessageRequest = function(addressN, message) {
const msgStructure = {
addressN,
message
};
const msg = messages.SkycoinSignMessage.create(msgStructure);
const buffer = messages.SkycoinSignMessage.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_SkycoinSignMessage
);
return dataBytesFromChunks(chunks);
};
const createAddressGenRequest = function(addressN, startIndex, confirmAddress) {
const msgStructure = {
addressN,
confirmAddress,
startIndex
};
const msg = messages.SkycoinAddress.create(msgStructure);
const buffer = messages.SkycoinAddress.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_SkycoinAddress
);
return dataBytesFromChunks(chunks);
};
const createCheckMessageSignatureRequest = function(address, message, signature) {
const msgStructure = {
address,
message,
signature
};
const msg = messages.SkycoinCheckMessageSignature.create(msgStructure);
const buffer = messages.SkycoinCheckMessageSignature.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_SkycoinCheckMessageSignature
);
return dataBytesFromChunks(chunks);
};
const createFirmwareUploadRequest = function(payload, hash) {
const msgStructure = {
hash,
payload
};
const msg = messages.FirmwareUpload.create(msgStructure);
const buffer = messages.FirmwareUpload.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_FirmwareUpload
);
return dataBytesFromChunks(chunks);
};
const createFirmwareEraseRequest = function(length) {
const msgStructure = {
length
};
const msg = messages.FirmwareErase.create(msgStructure);
const buffer = messages.FirmwareErase.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_FirmwareErase
);
return dataBytesFromChunks(chunks);
};
const createSendPinCodeRequest = function(pin) {
const msgStructure = {
pin
};
const msg = messages.PinMatrixAck.create(msgStructure);
const buffer = messages.PinMatrixAck.encode(msg).finish();
const chunks = makeTrezorMessage(
buffer,
messages.MessageType.MessageType_PinMatrixAck
);
return dataBytesFromChunks(chunks);
};
const decodeFeaturesRequest = function(kind, dataBuffer) {
if (kind != messages.MessageType.MessageType_Features) {
console.error("Calling decodeFeaturesRequest with wrong message type!", messages.MessageType[kind]);
return null;
}
try {
const answer = messages.Features.decode(dataBuffer);
console.log(
"Features message:",
"vendor:", answer.vendor,
"majorVersion:", answer.majorVersion,
"minorVersion:", answer.minorVersion,
"patchVersion:", answer.patchVersion,
"bootloaderMode:", answer.bootloaderMode,
"deviceId:", answer.deviceId,
"pinProtection:", answer.pinProtection,
"passphraseProtection:", answer.passphraseProtection,
"language:", answer.language,
"label:", answer.label,
"initialized:", answer.initialized,
"bootloaderHash:", answer.bootloaderHash,
"pinCached:", answer.pinCached,
"passphraseCached:", answer.passphraseCached,
"firmwarePresent:", answer.firmwarePresent,
"needsBackup:", answer.needsBackup,
"model:", answer.model,
"fwMajor:", answer.fwMajor,
"fwMinor:", answer.fwMinor,
"fwPatch:", answer.fwPatch,
"fwVendor:", answer.fwVendor,
"fwVendorKeys:", answer.fwVendorKeys,
"unfinishedBackup:", answer.unfinishedBackup
);
return answer;
} catch (e) {
console.error("Wire format is invalid");
return null;
}
};
const decodeButtonRequest = function(kind) {
if (kind != messages.MessageType.MessageType_ButtonRequest) {
console.error("Skiping button confirmation!", messages.MessageType[kind]);
return false;
}
console.log("ButtonRequest!");
return true;
};
const decodeSuccess = function(kind, dataBuffer) {
if (kind == messages.MessageType.MessageType_Success) {
try {
const answer = messages.Success.decode(dataBuffer);
console.log(
"Success message code",
answer.code, "message: ",
answer.message
);
return answer.message;
} catch (e) {
console.error("Wire format is invalid");
}
}
return `decodeSuccess failed: ${kind}`;
};
const decodeFailureAndPinCode = function(kind, dataBuffer) {
if (kind == messages.MessageType.MessageType_Failure) {
try {
const answer = messages.Failure.decode(dataBuffer);
console.log(
"Failure message code",
answer.code, "message: ",
answer.message
);
return answer.message;
} catch (e) {
console.error("Wire format is invalid");
}
}
if (kind == messages.MessageType.MessageType_PinMatrixRequest) {
return "Pin code required";
}
return "decodeFailureAndPinCode failed";
};
const decodeTransactionSignAnswer = function(kind, dataBuffer) {
let signatures = [];
if (kind == messages.MessageType.
MessageType_ResponseTransactionSign) {
try {
console.log(dataBuffer.slice(-5), dataBuffer.length);
const answer = messages.ResponseTransactionSign.
decode(dataBuffer);
signatures = answer.signatures;
} catch (e) {
console.error("Wire format is invalid", e);
}
}
return signatures;
};
const decodeSignMessageAnswer = function(kind, dataBuffer) {
let signature = "";
decodeFailureAndPinCode(kind, dataBuffer);
if (kind == messages.MessageType.
MessageType_ResponseSkycoinSignMessage) {
try {
const answer = messages.ResponseSkycoinSignMessage.
decode(dataBuffer);
signature = answer.signedMessage;
} catch (e) {
console.error("Wire format is invalid", e);
}
}
return signature;
};
const decodeAddressGenAnswer = function(kind, dataBuffer) {
let addresses = [];
if (kind == messages.MessageType.MessageType_ResponseSkycoinAddress) {
try {
const answer = messages.ResponseSkycoinAddress.
decode(dataBuffer);
console.log("Addresses", answer.addresses);
addresses = answer.addresses;
} catch (e) {
console.error("Wire format is invalid", e);
}
} else {
return decodeFailureAndPinCode(kind, dataBuffer);
}
return addresses;
};
const devButtonRequestCallback = function(kind, data, callback) {
if (decodeButtonRequest(kind)) {
const dataBytes = createButtonAckRequest();
const deviceHandle = new DeviceHandler(deviceType);
const devReadCallback = function(datakind, dta) {
console.log("User hit a button");
deviceHandle.close();
if (callback !== null && callback !== undefined) {
// eslint-disable-next-line callback-return
callback(datakind, dta);
}
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
return;
}
if (callback !== null && callback !== undefined) {
// eslint-disable-next-line callback-return
callback(kind, data);
}
};
const devUpdateFirmware = function(data, hash) {
return new Promise((resolve, reject) => {
const dataBytes = createInitializeRequest();
const deviceHandle = new DeviceHandler(deviceType);
console.log("Firmware hash is:", hash);
const uploadFirmwareCallback = function(kind, d) {
deviceHandle.close();
devButtonRequestCallback(kind, d, (datakind) => {
if (datakind == messages.MessageType.MessageType_Success) {
resolve("Update firmware operation completed");
} else {
reject(new Error("Update firmware operation failed or refused"));
}
});
};
const eraseFirmwareCallback = function(eraseStatus, eraseMessage) {
console.log(decodeSuccess(eraseStatus, eraseMessage));
deviceHandle.reopen();
console.log(decodeSuccess(eraseStatus, eraseMessage));
const uploadDataBytes = createFirmwareUploadRequest(data, hash);
deviceHandle.read(uploadFirmwareCallback);
deviceHandle.write(uploadDataBytes);
};
const devReadCallback = function(kind, dataBuffer) {
console.log(decodeSuccess(kind, dataBuffer));
deviceHandle.reopen();
const eraseDataBytes = createFirmwareEraseRequest(data.length);
deviceHandle.read(eraseFirmwareCallback);
deviceHandle.write(eraseDataBytes);
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
});
};
const devCancelRequest = function() {
return new Promise((resolve, reject) => {
const dataBytes = createCancelRequest();
const deviceHandle = new DeviceHandler(deviceType);
const devReadCallback = function(kind, data) {
deviceHandle.close();
if (kind == messages.MessageType.MessageType_Success) {
resolve(decodeSuccess(kind, data));
return;
}
if (kind == messages.MessageType.MessageType_Failure) {
resolve(decodeFailureAndPinCode(kind, data));
return;
}
reject(new Error(`Could not recognize message of kind ${kind}`));
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
});
};
const devGetVersionDevice = function() {
return new Promise((resolve) => {
const dataBytes = createGetVersionRequest();
const deviceHandle = new DeviceHandler(deviceType);
const devReadCallback = function(kind, data) {
deviceHandle.close();
const version = decodeSuccess(kind, data);
if (version == "") {
reject(new Error("Could not get version from the device"));
} else {
resolve(version);
}
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
});
};
// eslint-disable-next-line max-params
const devSendAddressGen = function(addressN, startIndex, confirmAddress, callback) {
const dataBytes = createAddressGenRequest(addressN, startIndex, confirmAddress);
const deviceHandle = new DeviceHandler(deviceType);
const devReadCallback = function(kind, dataBuffer) {
deviceHandle.close();
callback(kind, dataBuffer);
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
};
const devSendPinCodeRequest = function(pinCodeCallback, pinCodeReader) {
const sendPinCodeRequest = function(pinCode) {
const dataBytes = createSendPinCodeRequest(pinCode);
const deviceHandle = new DeviceHandler(deviceType);
deviceHandle.read((answerKind, dataBuffer) => {
deviceHandle.close();
pinCodeCallback(answerKind, dataBuffer);
});
deviceHandle.write(dataBytes);
};
if (pinCodeReader !== null && pinCodeReader !== undefined) {
const pinCodePromise = pinCodeReader();
pinCodePromise.then(
(pinCode) => {
sendPinCodeRequest(pinCode);
},
() => {
console.log("Pin code promise rejected");
devCancelRequest();
}
);
} else {
console.log("Please input your pin code: ");
sendPinCodeRequest(scanf('%s'));
}
};
const devSendPassphraseAck = function(callback, passphraseReader) {
const sendPassphraseAck = function(passphrase) {
const dataBytes = createPassphraseRequest(passphrase);
const deviceHandle = new DeviceHandler(deviceType);
deviceHandle.read((kind, data) => {
deviceHandle.close();
callback(kind, data);
});
deviceHandle.write(dataBytes);
};
if (passphraseReader !== null && passphraseReader !== undefined) {
const passphrasePromise = passphraseReader();
passphrasePromise.then(
(passphrase) => {
sendPassphraseAck(passphrase);
},
() => {
console.log("Pin code promise rejected");
devCancelRequest();
}
);
} else {
console.log("Please input your passphrase: ");
sendPassphraseAck(scanf('%s'));
}
};
// eslint-disable-next-line max-params
const devAddressGen = function(addressN, startIndex, confirmAddress, pinCodeReader, passphraseReader) {
return new Promise((resolve, reject) => {
const addressGenHandler = function(kind, dataBuffer) {
console.log("Addresses generation received message kind: ", messages.MessageType[kind]);
switch (kind) {
case messages.MessageType.MessageType_Failure:
reject(new Error(decodeFailureAndPinCode(kind, dataBuffer)));
break;
case messages.MessageType.MessageType_ResponseSkycoinAddress:
resolve(decodeAddressGenAnswer(kind, dataBuffer));
break;
case messages.MessageType.MessageType_PinMatrixRequest:
devSendPinCodeRequest(addressGenHandler, pinCodeReader);
break;
case messages.MessageType.MessageType_PassphraseRequest:
devSendPassphraseAck(addressGenHandler, passphraseReader);
break;
case messages.MessageType.MessageType_ButtonRequest:
devButtonRequestCallback(kind, dataBuffer, addressGenHandler);
break;
default:
reject(new Error(`Unexpected answer from the device: ${kind}`));
break;
}
};
devSendAddressGen(addressN, startIndex, confirmAddress, addressGenHandler);
});
};
const devApplySettings = function(usePassphrase, pinCodeReader) {
return new Promise((resolve, reject) => {
const applySettingsCallback = function(kind, dataBuffer) {
switch (kind) {
case messages.MessageType.MessageType_Success:
resolve(decodeSuccess(kind, dataBuffer));
break;
case messages.MessageType.MessageType_Failure:
reject(new Error(decodeFailureAndPinCode(kind, dataBuffer)));
break;
case messages.MessageType.MessageType_PinMatrixRequest:
devSendPinCodeRequest(applySettingsCallback, pinCodeReader);
break;
case messages.MessageType.MessageType_ButtonRequest:
devButtonRequestCallback(kind, dataBuffer, applySettingsCallback);
break;
default:
reject(new Error(`Unexpected answer from the device: ${kind}`));
break;
}
};
const dataBytes = createApplySettings(usePassphrase);
const deviceHandle = new DeviceHandler(deviceType);
const devReadCallback = function(kind, dataBuffer) {
deviceHandle.close();
applySettingsCallback(kind, dataBuffer);
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
});
};
const devSendSkycoinTransactionSign = function(inputTransactions, outputTransactions, callback) {
const dataBytes = createTransactionSignRequest(inputTransactions, outputTransactions);
const deviceHandle = new DeviceHandler(deviceType);
const devReadCallback = function(kind, dataBuffer) {
deviceHandle.close();
callback(kind, dataBuffer);
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
};
const devSendSkycoinSignMessage = function(addressN, message, callback) {
const dataBytes = createSignMessageRequest(addressN, message);
const deviceHandle = new DeviceHandler(deviceType);
const devReadCallback = function(kind, dataBuffer) {
deviceHandle.close();
callback(kind, dataBuffer);
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
};
// eslint-disable-next-line max-params
const devSkycoinSignMessage = function(addressN, message, pinCodeReader, passphraseReader) {
return new Promise((resolve, reject) => {
const skycoinSignHander = function(kind, dataBuffer) {
console.log("Signature generation received message kind:", messages.MessageType[kind]);
switch (kind) {
case messages.MessageType.MessageType_Failure:
reject(new Error(decodeFailureAndPinCode(kind, dataBuffer)));
break;
case messages.MessageType.MessageType_ResponseSkycoinSignMessage:
resolve(decodeSignMessageAnswer(kind, dataBuffer));
break;
case messages.MessageType.MessageType_PassphraseRequest:
devSendPassphraseAck(skycoinSignHander, passphraseReader);
break;
case messages.MessageType.MessageType_PinMatrixRequest:
devSendPinCodeRequest(skycoinSignHander, pinCodeReader);
break;
default:
reject(new Error(`Unexpected answer from the device: ${kind}`));
break;
}
};
devSendSkycoinSignMessage(addressN, message, skycoinSignHander);
});
};
// eslint-disable-next-line max-params
const devSkycoinTransactionSign = function(
inputTransactions,
outputTransactions,
pinCodeReader,
passphraseReader
) {
return new Promise((resolve, reject) => {
const skycoinTransactionSignHander = function(kind, dataBuffer) {
console.log("TransactionSign received message kind:", messages.MessageType[kind]);
switch (kind) {
case messages.MessageType.MessageType_ResponseTransactionSign:
resolve(decodeTransactionSignAnswer(kind, dataBuffer));
break;
case messages.MessageType.MessageType_Success:
reject(new Error("Should end with ResponseTransactionSign request"));
break;
case messages.MessageType.MessageType_Failure:
reject(new Error(decodeFailureAndPinCode(kind, dataBuffer)));
break;
case messages.MessageType.MessageType_ButtonRequest:
devButtonRequestCallback(kind, dataBuffer, skycoinTransactionSignHander);
break;
case messages.MessageType.MessageType_PassphraseRequest:
devSendPassphraseAck(skycoinTransactionSignHander, passphraseReader);
break;
case messages.MessageType.MessageType_PinMatrixRequest:
devSendPinCodeRequest(skycoinTransactionSignHander, pinCodeReader);
break;
default:
reject(new Error(`Unexpected answer from the device: ${kind}`));
break;
}
};
devSendSkycoinTransactionSign(inputTransactions, outputTransactions, skycoinTransactionSignHander);
});
};
// eslint-disable-next-line max-params
const devCheckMessageSignature = function(address, message, signature, passphraseReader) {
return new Promise((resolve, reject) => {
const dataBytes = createCheckMessageSignatureRequest(address, message, signature);
const deviceHandle = new DeviceHandler(deviceType);
const devReadCallback = function(kind, dataBuffer) {
deviceHandle.close();
if (kind == messages.MessageType.MessageType_Success) {
try {
const answer = messages.Success.
decode(dataBuffer);
if (answer.message === address) {
resolve(`Address emiting that signature: ${answer.message}`);
} else {
reject(new Error("Wrong signature"));
}
} catch (e) {
reject(new Error("Wire format is invalid", e));
}
} else if (kind == messages.MessageType.MessageType_PassphraseRequest) {
devSendPassphraseAck(devReadCallback, passphraseReader);
} else {
reject(new Error("Wrong answer kind", kind));
}
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
});
};
const devWipeDevice = function() {
return new Promise((resolve, reject) => {
const dataBytes = createWipeDeviceRequest();
const deviceHandle = new DeviceHandler(deviceType);
const devReadCallback = function(kind, d) {
deviceHandle.close();
devButtonRequestCallback(kind, d, (datakind) => {
if (datakind == messages.MessageType.MessageType_Success) {
resolve("Wipe Device operation completed");
} else {
reject(new Error("Wipe Device operation failed or refused"));
}
});
};
deviceHandle.read(devReadCallback);
deviceHandle.write(dataBytes);
});
};
const devBackupDevice = function(pinCodeReader) {
return new Promise((resolve, reject) => {
const dataBytes = createBackupDeviceRequest();
const deviceHandle = new DeviceHandler(deviceType);