forked from petertodd/hardware-bitcoin-wallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stream_comm.c
1034 lines (949 loc) · 30.5 KB
/
stream_comm.c
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
/** \file stream_comm.c
*
* \brief Deals with packets sent over the stream device.
*
* The most important function in this file is processPacket(). It decodes
* packets from the stream and calls the relevant functions from wallet.c or
* transaction.c. Some validation of the received data is also handled in
* this file. Here is a general rule for what validation is done: if the
* validation can be done without knowing the internal details of how wallets
* are stored or how transactions are parsed, then the validation is done
* in this file. Finally, the functions in this file translate the return
* values from wallet.c and transaction.c into response packets which are
* sent over the stream device.
*
* This file is licensed as described by the file LICENCE.
*/
#ifdef TEST
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#endif // #ifdef TEST
#ifdef TEST_STREAM_COMM
#include <string.h>
#include "test_helpers.h"
#endif // #ifdef TEST_STREAM_COMM
#include "common.h"
#include "endian.h"
#include "hwinterface.h"
#include "wallet.h"
#include "bignum256.h"
#include "stream_comm.h"
#include "prandom.h"
#include "xex.h"
#include "ecdsa.h"
/** Because stdlib.h might not be included, NULL might be undefined. NULL
* is only used as a placeholder pointer for translateWalletError() if
* there is no appropriate pointer. */
#ifndef NULL
#define NULL ((void *)0)
#endif // #ifndef NULL
/** The transaction hash of the most recently approved transaction. This is
* stored so that if a transaction needs to be signed multiple times (eg.
* if it has more than one input), the user doesn't have to approve every
* one. */
static uint8_t prev_transaction_hash[32];
/** 0 means disregard #prev_transaction_hash, non-zero means
* that #prev_transaction_hash is valid for prev_transaction_hash_valid more
* transactions (eg. if prev_transaction_hash_valid is 2,
* then #prev_transaction_hash can be considered valid for the approval of 2
* more transactions). */
static uint16_t prev_transaction_hash_valid;
/** Length of current packet's payload. */
static uint32_t payload_length;
/** Write a number of bytes to the output stream.
* \param buffer The array of bytes to be written.
* \param length The number of bytes to write.
*/
static void writeBytesToStream(uint8_t *buffer, uint16_t length)
{
uint16_t i;
for (i = 0; i < length; i++)
{
streamPutOneByte(buffer[i]);
}
}
/** Sends a packet with a string as payload.
* \param set See getString().
* \param spec See getString().
* \param command The type of the packet, as defined in the file PROTOCOL.
*/
static void writeString(StringSet set, uint8_t spec, uint8_t command)
{
uint8_t buffer[4];
uint8_t one_char;
uint16_t length;
uint16_t i;
streamPutOneByte(command); // type
length = getStringLength(set, spec);
writeU32LittleEndian(buffer, length);
writeBytesToStream(buffer, 4); // length
for (i = 0; i < length; i++)
{
one_char = (uint8_t)getString(set, spec, i);
streamPutOneByte(one_char); // value
}
}
/** Translates a return value from one of the wallet functions into a response
* packet to be written to the stream. If the wallet return value indicates
* success, a payload can be included with the packet. Otherwise, if the
* wallet return value indicates failure, the payload is a text error message
* describing how the wallet function failed.
* \param r The return value from the wallet function.
* \param length The length of the success payload (use 0 for no payload) in
* number of bytes.
* \param data A byte array holding the data of the success payload.
* Use #NULL for no payload.
*/
static void translateWalletError(WalletErrors r, uint8_t length, uint8_t *data)
{
uint8_t buffer[4];
if (r == WALLET_NO_ERROR)
{
streamPutOneByte(PACKET_TYPE_SUCCESS); // type
writeU32LittleEndian(buffer, length);
writeBytesToStream(buffer, 4); // length
writeBytesToStream(data, length); // value
}
else
{
writeString(STRINGSET_WALLET, (uint8_t)r, PACKET_TYPE_FAILURE);
}
}
/** Read bytes from the stream.
* \param buffer The byte array where the bytes will be placed. This must
* have enough space to store length bytes.
* \param length The number of bytes to read.
*/
static void getBytesFromStream(uint8_t *buffer, uint8_t length)
{
uint8_t i;
for (i = 0; i < length; i++)
{
buffer[i] = streamGetOneByte();
}
payload_length -= length;
}
/** Sign a transaction and (if everything goes well) send the signature in a
* response packet.
* \param ah The address handle whose corresponding private key will be used
* to sign the transaction.
* \param sig_hash The signature hash of the transaction, as calculated by
* parseTransaction(). This must be an array of 32 bytes.
*/
static NOINLINE void signTransactionByAddressHandle(AddressHandle ah, uint8_t *sig_hash)
{
uint8_t signature[MAX_SIGNATURE_LENGTH];
uint8_t private_key[32];
uint8_t signature_length;
WalletErrors wallet_return;
signature_length = 0;
if (getPrivateKey(private_key, ah) == WALLET_NO_ERROR)
{
// Note: signTransaction() cannot fail.
signature_length = signTransaction(signature, sig_hash, private_key);
}
wallet_return = walletGetLastError();
translateWalletError(wallet_return, signature_length, signature);
}
/** Read a transaction from the stream, parse it and ask the user
* if they approve it.
* \param out_approved A non-zero value will be written to here if the
* user approved the transaction, otherwise a zero value
* will be written.
* \param sig_hash The signature hash of the transaction will be written to
* here by parseTransaction(). This must be an array of 32
* bytes.
* \param transaction_length The length of the transaction, in number of
* bytes. This can be derived from the payload
* length of a packet.
*/
static NOINLINE void parseTransactionAndAsk(uint8_t *out_approved, uint8_t *sig_hash, uint32_t transaction_length)
{
TransactionErrors r;
uint8_t transaction_hash[32];
// Validate transaction and calculate hashes of it.
*out_approved = 0;
clearOutputsSeen();
r = parseTransaction(sig_hash, transaction_hash, transaction_length);
if (r != TRANSACTION_NO_ERROR)
{
// Transaction parse error.
writeString(STRINGSET_TRANSACTION, (uint8_t)r, PACKET_TYPE_FAILURE);
return;
}
// Get permission from user.
*out_approved = 0;
// Does transaction_hash match previous approved transaction?
if (prev_transaction_hash_valid)
{
if (bigCompare(transaction_hash, prev_transaction_hash) == BIGCMP_EQUAL)
{
*out_approved = 1;
prev_transaction_hash_valid--;
}
}
if (!(*out_approved))
{
// Need to explicitly get permission from user.
// The call to parseTransaction() should have logged all the outputs
// to the user interface.
if (askUser(ASKUSER_SIGN_TRANSACTION))
{
writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
}
else
{
// User approved transaction.
*out_approved = 1;
memcpy(prev_transaction_hash, transaction_hash, 32);
// The transaction hash can only be reused another
// (number of inputs) - 1 times. This is to prevent an exploit
// where an attacker crafts a lot of copies (with differing inputs
// but identical outputs) of a genuine transaction. With unlimited
// reuse of the transaction hash, acceptance of the original
// genuine transaction would also allow all the copies to be
// automatically accepted, causing the user to spend more than
// they intended.
prev_transaction_hash_valid = getTransactionNumInputs();
if (prev_transaction_hash_valid)
{
prev_transaction_hash_valid--;
}
}
} // if (!(*out_approved))
}
/** Validate and sign a transaction. This basically calls
* parseTransactionAndAsk() and signTransactionByAddressHandle() in sequence.
* Why do that? For the same reason generateDeterministic256() was split into
* two parts - more efficient use of stack space.
*
* This function will always consume transaction_length bytes from the input
* stream, except when a stream read error occurs.
* \param ah The address handle whose corresponding private key will be used
* to sign the transaction.
* \param transaction_length The length of the transaction, in number of
* bytes. This can be derived from the payload
* length of a packet.
*/
static NOINLINE void validateAndSignTransaction(AddressHandle ah, uint32_t transaction_length)
{
uint8_t approved;
uint8_t sig_hash[32];
approved = 0;
parseTransactionAndAsk(&approved, sig_hash, transaction_length);
if (approved)
{
// Okay to sign transaction.
signTransactionByAddressHandle(ah, sig_hash);
}
}
/** Send a packet containing an address and its corresponding public key.
* This can generate new addresses as well as obtain old addresses. Both
* use cases were combined into one function because they involve similar
* processes.
* \param generate_new If this is non-zero, a new address will be generated
* and the address handle of the generated address will
* be prepended to the output packet.
* If this is zero, the address handle will be read from
* the input stream. No address handle will be prepended
* to the output packet.
*/
static NOINLINE void getAndSendAddressAndPublicKey(uint8_t generate_new)
{
AddressHandle ah;
PointAffine public_key;
uint8_t address[20];
uint8_t buffer[4];
WalletErrors r;
if (generate_new)
{
// Generate new address handle.
r = WALLET_NO_ERROR;
ah = makeNewAddress(address, &public_key);
if (ah == BAD_ADDRESS_HANDLE)
{
r = walletGetLastError();
}
}
else
{
// Read address handle from input stream.
getBytesFromStream(buffer, 4);
ah = readU32LittleEndian(buffer);
r = getAddressAndPublicKey(address, &public_key, ah);
}
if (r == WALLET_NO_ERROR)
{
streamPutOneByte(PACKET_TYPE_SUCCESS); // type
if (generate_new)
{
// 4 (address handle) + 20 (address) + 65 (public key)
writeU32LittleEndian(buffer, 89);
}
else
{
// 20 (address) + 65 (public key)
writeU32LittleEndian(buffer, 85);
}
writeBytesToStream(buffer, 4); // length
if (generate_new)
{
writeU32LittleEndian(buffer, ah);
writeBytesToStream(buffer, 4);
}
writeBytesToStream(address, 20);
// The format of public keys sent is compatible with
// "SEC 1: Elliptic Curve Cryptography" by Certicom research, obtained
// 15-August-2011 from: http://www.secg.org/collateral/sec1_final.pdf
// section 2.3 ("Data Types and Conversions"). The document basically
// says that integers should be represented big-endian and that a 0x04
// should be prepended to indicate that the public key is
// uncompressed.
streamPutOneByte(0x04);
swapEndian256(public_key.x);
swapEndian256(public_key.y);
writeBytesToStream(public_key.x, 32);
writeBytesToStream(public_key.y, 32);
}
else
{
translateWalletError(r, 0, NULL);
} // end if (r == WALLET_NO_ERROR)
}
/** Send a packet containing a list of wallets.
*/
static NOINLINE void listWallets(void)
{
uint8_t version[4];
uint8_t name[NAME_LENGTH];
uint8_t buffer[4];
WalletErrors wallet_return;
if (getWalletInfo(version, name) != WALLET_NO_ERROR)
{
wallet_return = walletGetLastError();
translateWalletError(wallet_return, 0, NULL);
}
else
{
streamPutOneByte(PACKET_TYPE_SUCCESS); // type
writeU32LittleEndian(buffer, 4 + NAME_LENGTH); // length
writeBytesToStream(buffer, 4);
writeBytesToStream(version, 4);
writeBytesToStream(name, NAME_LENGTH);
}
}
/** Read but ignore #payload_length bytes from input stream. This will also
* set #payload_length to 0 (if everything goes well). This function is
* useful for ensuring that the entire payload of a packet is read from the
* stream device.
*/
static void readAndIgnoreInput(void)
{
if (payload_length)
{
for (; payload_length--; )
{
streamGetOneByte();
}
}
}
/** Expect the payload length of a packet to be equal to desired_length, and
* send an error message (and read but ignore #payload_length bytes from the
* stream) if that is not the case. This function is used to enforce the
* payload length of packets to be compliant with the protocol described in
* the file PROTOCOL.
* \param desired_length The expected payload length (in bytes) of the packet
* currently being received from the stream device.
* \return 0 for success, 1 for payload length != desired_length.
*/
static uint8_t expectLength(const uint8_t desired_length)
{
if (payload_length != desired_length)
{
readAndIgnoreInput();
writeString(STRINGSET_MISC, MISCSTR_INVALID_PACKET, PACKET_TYPE_FAILURE);
return 1; // mismatched length
}
else
{
return 0; // success
}
}
/** Get packet from stream and deal with it. This basically implements the
* protocol described in the file PROTOCOL.
*
* This function will always completely
* read a packet before sending a response packet. As long as the host
* does the same thing, deadlocks cannot occur. Thus a productive
* communication session between the hardware Bitcoin wallet and a host
* should consist of the wallet and host alternating between sending a
* packet and receiving a packet.
*/
void processPacket(void)
{
uint8_t command;
// Technically, the length of buffer should also be >= 4, since it is used
// in a couple of places to obtain 32 bit values. This is guaranteed by
// the reference to WALLET_ENCRYPTION_KEY_LENGTH, since no-one in their
// right mind would use encryption with smaller than 32 bit keys.
uint8_t buffer[MAX(NAME_LENGTH, WALLET_ENCRYPTION_KEY_LENGTH)];
uint32_t num_addresses;
AddressHandle ah;
WalletErrors wallet_return;
command = streamGetOneByte();
getBytesFromStream(buffer, 4);
payload_length = readU32LittleEndian(buffer);
// Checklist for each case:
// 1. Have you checked or dealt with length?
// 2. Have you fully read the input stream before writing (to avoid
// deadlocks)?
// 3. Have you asked permission from the user (for potentially dangerous
// operations)?
// 4. Have you checked for errors from wallet functions?
// 5. Have you used the right check for the wallet functions?
switch (command)
{
case PACKET_TYPE_PING:
// Ping request.
// Just throw away the data and then send response.
readAndIgnoreInput();
writeString(STRINGSET_MISC, MISCSTR_VERSION, PACKET_TYPE_PING_REPLY);
break;
// Commands PACKET_TYPE_PING_REPLY, PACKET_TYPE_SUCCESS and
// PACKET_TYPE_FAILURE should never be received; they are only sent.
case PACKET_TYPE_NEW_WALLET:
// Create new wallet.
if (!expectLength(WALLET_ENCRYPTION_KEY_LENGTH + NAME_LENGTH))
{
getBytesFromStream(buffer, WALLET_ENCRYPTION_KEY_LENGTH);
setEncryptionKey(buffer);
getBytesFromStream(buffer, NAME_LENGTH);
if (askUser(ASKUSER_NUKE_WALLET))
{
writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
}
else
{
wallet_return = newWallet(buffer);
translateWalletError(wallet_return, 0, NULL);
}
}
break;
case PACKET_TYPE_NEW_ADDRESS:
// Create new address in wallet.
if (!expectLength(0))
{
if (askUser(ASKUSER_NEW_ADDRESS))
{
writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
}
else
{
getAndSendAddressAndPublicKey(1);
}
}
break;
case PACKET_TYPE_GET_NUM_ADDRESSES:
// Get number of addresses in wallet.
if (!expectLength(0))
{
num_addresses = getNumAddresses();
writeU32LittleEndian(buffer, num_addresses);
wallet_return = walletGetLastError();
translateWalletError(wallet_return, 4, buffer);
}
break;
case PACKET_TYPE_GET_ADDRESS_PUBKEY:
// Get address and public key corresponding to an address handle.
if (!expectLength(4))
{
getAndSendAddressAndPublicKey(0);
}
break;
case PACKET_TYPE_SIGN_TRANSACTION:
// Sign a transaction.
if (payload_length <= 4)
{
readAndIgnoreInput();
writeString(STRINGSET_MISC, MISCSTR_INVALID_PACKET, PACKET_TYPE_FAILURE);
}
else
{
getBytesFromStream(buffer, 4);
ah = readU32LittleEndian(buffer);
// Don't need to subtract 4 off payload_length because
// getBytesFromStream() has already done so.
validateAndSignTransaction(ah, payload_length);
payload_length = 0;
}
break;
case PACKET_TYPE_LOAD_WALLET:
// Load wallet.
if (!expectLength(WALLET_ENCRYPTION_KEY_LENGTH))
{
getBytesFromStream(buffer, WALLET_ENCRYPTION_KEY_LENGTH);
setEncryptionKey(buffer);
wallet_return = initWallet();
translateWalletError(wallet_return, 0, NULL);
}
break;
case PACKET_TYPE_UNLOAD_WALLET:
// Unload wallet.
if (!expectLength(0))
{
clearEncryptionKey();
sanitiseRam();
memset(buffer, 0xff, sizeof(buffer));
memset(buffer, 0, sizeof(buffer));
wallet_return = uninitWallet();
translateWalletError(wallet_return, 0, NULL);
}
break;
case PACKET_TYPE_FORMAT:
// Format storage.
if (!expectLength(0))
{
if (askUser(ASKUSER_FORMAT))
{
writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
}
else
{
wallet_return = sanitiseNonVolatileStorage(0, 0xffffffff);
translateWalletError(wallet_return, 0, NULL);
uninitWallet(); // force wallet to unload
}
}
break;
case PACKET_TYPE_CHANGE_KEY:
// Change wallet encryption key.
if (!expectLength(WALLET_ENCRYPTION_KEY_LENGTH))
{
getBytesFromStream(buffer, WALLET_ENCRYPTION_KEY_LENGTH);
wallet_return = changeEncryptionKey(buffer);
translateWalletError(wallet_return, 0, NULL);
}
break;
case PACKET_TYPE_CHANGE_NAME:
// Change wallet name.
if (!expectLength(NAME_LENGTH))
{
getBytesFromStream(buffer, NAME_LENGTH);
if (askUser(ASKUSER_CHANGE_NAME))
{
writeString(STRINGSET_MISC, MISCSTR_PERMISSION_DENIED, PACKET_TYPE_FAILURE);
}
else
{
wallet_return = changeWalletName(buffer);
translateWalletError(wallet_return, 0, NULL);
}
}
break;
case PACKET_TYPE_LIST_WALLETS:
// List wallets.
if (!expectLength(0))
{
listWallets();
}
break;
default:
// Unknown command.
readAndIgnoreInput();
writeString(STRINGSET_MISC, MISCSTR_INVALID_PACKET, PACKET_TYPE_FAILURE);
break;
}
#ifdef TEST_STREAM_COMM
assert(payload_length == 0);
#endif
}
#ifdef TEST
/** Contents of a test stream (to read from). */
static uint8_t *stream;
/** 0-based index into #stream specifying which byte will be read next. */
static unsigned int stream_ptr;
/** Length of the test stream, in number of bytes. */
static unsigned int stream_length;
/** Sets input stream (what will be read by streamGetOneByte()) to the
* contents of a buffer.
* \param buffer The test stream data. Each call to streamGetOneByte() will
* return successive bytes from this buffer.
* \param length The length of the buffer, in number of bytes.
*/
void setTestInputStream(const uint8_t *buffer, unsigned int length)
{
if (stream != NULL)
{
free(stream);
}
stream = malloc(length);
memcpy(stream, buffer, length);
stream_length = length;
stream_ptr = 0;
}
/** Get one byte from the contents of the buffer set by setTestInputStream().
* \return The next byte from the test stream buffer.
*/
uint8_t streamGetOneByte(void)
{
if (stream == NULL)
{
printf("ERROR: Tried to read a stream whose contents weren't set.\n");
exit(1);
}
if (stream_ptr >= stream_length)
{
printf("ERROR: Tried to read past end of stream\n");
exit(1);
}
return stream[stream_ptr++];
}
/** Simulate the sending of a byte by displaying its value.
* \param one_byte The byte to send.
*/
void streamPutOneByte(uint8_t one_byte)
{
printf(" %02x", (int)one_byte);
}
/** Helper for getString().
* \param set See getString().
* \param spec See getString().
* \return A pointer to the actual string.
*/
static const char *getStringInternal(StringSet set, uint8_t spec)
{
if (set == STRINGSET_MISC)
{
switch (spec)
{
case MISCSTR_VERSION:
return "Hello world v0.1";
break;
case MISCSTR_PERMISSION_DENIED:
return "Permission denied by user";
break;
case MISCSTR_INVALID_PACKET:
return "Unrecognised command";
break;
default:
assert(0);
}
}
else if (set == STRINGSET_WALLET)
{
switch (spec)
{
case WALLET_FULL:
return "Wallet has run out of space";
break;
case WALLET_EMPTY:
return "Wallet has nothing in it";
break;
case WALLET_READ_ERROR:
return "Read error";
break;
case WALLET_WRITE_ERROR:
return "Write error";
break;
case WALLET_ADDRESS_NOT_FOUND:
return "Address not in wallet";
break;
case WALLET_NOT_THERE:
return "Wallet doesn't exist";
break;
case WALLET_END_OF_LIST:
return "End of address list";
break;
case WALLET_INVALID_HANDLE:
return "Invalid address handle";
break;
default:
assert(0);
}
}
else if (set == STRINGSET_TRANSACTION)
{
switch (spec)
{
case TRANSACTION_INVALID_FORMAT:
return "Format of transaction is unknown or invalid";
break;
case TRANSACTION_TOO_MANY_INPUTS:
return "Too many inputs in transaction";
break;
case TRANSACTION_TOO_MANY_OUTPUTS:
return "Too many outputs in transaction";
break;
case TRANSACTION_TOO_LARGE:
return "Transaction's size is too large";
break;
case TRANSACTION_NON_STANDARD:
return "Transaction is non-standard";
break;
default:
assert(0);
}
}
else
{
assert(0);
}
// GCC is smart enough to realise that the following line will never
// be executed.
#ifndef __GNUC__
return NULL;
#endif // #ifndef __GNUC__
}
/** Get the length of one of the device's strings.
* \param set Specifies which set of strings to use; should be
* one of #StringSetEnum.
* \param spec Specifies which string to get the character from. The
* interpretation of this depends on the value of set;
* see #StringSetEnum for clarification.
* \return The length of the string, in number of characters.
*/
uint16_t getStringLength(StringSet set, uint8_t spec)
{
return (uint16_t)strlen(getStringInternal(set, spec));
}
/** Obtain one character from one of the device's strings.
* \param set Specifies which set of strings to use; should be
* one of #StringSetEnum.
* \param spec Specifies which string to get the character from. The
* interpretation of this depends on the value of set;
* see #StringSetEnum for clarification.
* \param pos The position of the character within the string; 0 means first,
* 1 means second etc.
* \return The character from the specified string.
*/
char getString(StringSet set, uint8_t spec, uint16_t pos)
{
assert(pos < getStringLength(set, spec));
return getStringInternal(set, spec)[pos];
}
/** Ask user if they want to allow some action.
* \param command The action to ask the user about. See #AskUserCommandEnum.
* \return 0 if the user accepted, non-zero if the user denied.
*/
uint8_t askUser(AskUserCommand command)
{
int c;
switch (command)
{
case ASKUSER_NUKE_WALLET:
printf("Nuke your wallet and start a new one? ");
break;
case ASKUSER_NEW_ADDRESS:
printf("Create new address? ");
break;
case ASKUSER_SIGN_TRANSACTION:
printf("Sign transaction? ");
break;
case ASKUSER_FORMAT:
printf("Format storage area? ");
break;
case ASKUSER_CHANGE_NAME:
printf("Change wallet name? ");
break;
default:
assert(0);
// GCC is smart enough to realise that the following line will never
// be executed.
#ifndef __GNUC__
return 1;
#endif // #ifndef __GNUC__
}
printf("y/[n]: ");
do
{
c = getchar();
} while ((c == '\n') || (c == '\r'));
if ((c == 'y') || (c == 'Y'))
{
return 0;
}
else
{
return 1;
}
}
#endif // #ifdef TEST
#ifdef TEST_STREAM_COMM
/** Test stream data for: create new wallet. */
static const uint8_t test_stream_new_wallet[] = {
0x04, 0x48, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x65, 0x20,
0x66, 0x66, 0x20, 0x20, 0x20, 0x6F, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20};
/** Test stream data for: create new address. */
static const uint8_t test_stream_new_address[] = {
0x05, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: get number of addresses. */
static const uint8_t test_stream_get_num_addresses[] = {
0x06, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: get address 1. */
static const uint8_t test_stream_get_address1[] = {
0x09, 0x04, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: get address 0 (which is an invalid address
* handle). */
static const uint8_t test_stream_get_address0[] = {
0x09, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: sign something. */
static uint8_t test_stream_sign_tx[] = {
0x0a, 0x98, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00,
// transaction data is below
0x01, 0x00, 0x00, 0x00, // version
0x01, // number of inputs
0xde, 0xad, 0xbe, 0xef, 0xc0, 0xff, 0xee, 0xee, // previous output
0xde, 0xad, 0xbe, 0xef, 0xc0, 0xff, 0xee, 0xee,
0xde, 0xad, 0xbe, 0xef, 0xc0, 0xff, 0xee, 0xee,
0xde, 0xad, 0xbe, 0xef, 0xc0, 0xff, 0xee, 0xee,
0x01, 0x00, 0x00, 0x00, // number in previous output
0x19, // script length
0x76, // OP_DUP
0xA9, // OP_HASH160
0x14, // 20 bytes of data follows
0xde, 0xad, 0xbe, 0xef, 0xc0, 0xff, 0xee, 0xee, 0x00, 0x00,
0xde, 0xad, 0xbe, 0xef, 0xc0, 0xff, 0xee, 0xee, 0x00, 0x00,
0x88, // OP_EQUALVERIFY
0xAC, // OP_CHECKSIG
0xFF, 0xFF, 0xFF, 0xFF, // sequence
0x02, // number of outputs
0x00, 0x46, 0xc3, 0x23, 0x00, 0x00, 0x00, 0x00, // 6 BTC
0x19, // script length
0x76, // OP_DUP
0xA9, // OP_HASH160
0x14, // 20 bytes of data follows
// 11MXTrefsj1ZS3Q5e9D6DxGzZKHWALyo9
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11, 0x22, 0x33,
0x88, // OP_EQUALVERIFY
0xAC, // OP_CHECKSIG
0x87, 0xd6, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, // 0.01234567 BTC
0x19, // script length
0x76, // OP_DUP
0xA9, // OP_HASH160
0x14, // 20 bytes of data follows
// 16eCeyy63xi5yde9VrX4XCcRrCKZwtUZK
0x01, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x00, 0x11, 0x22, 0x33,
0x88, // OP_EQUALVERIFY
0xAC, // OP_CHECKSIG
0x00, 0x00, 0x00, 0x00, // locktime
0x01, 0x00, 0x00, 0x00 // hashtype
};
/** Test stream data for: format storage. */
static const uint8_t test_stream_format[] = {
0x0d, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: load wallet using correct key. */
static const uint8_t test_stream_load_correct[] = {
0x0b, 0x20, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: load wallet using incorrect key. */
static const uint8_t test_stream_load_incorrect[] = {
0x0b, 0x20, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: unload wallet. */
static const uint8_t test_stream_unload[] = {
0x0c, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: change encryption key. */
static const uint8_t test_stream_change_key[] = {
0x0e, 0x20, 0x00, 0x00, 0x00,
0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: load with new encryption key. */
static const uint8_t test_stream_load_with_changed_key[] = {
0x0b, 0x20, 0x00, 0x00, 0x00,
0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: list wallets. */
static const uint8_t test_stream_list_wallets[] = {
0x10, 0x00, 0x00, 0x00, 0x00};
/** Test stream data for: change wallet name. */
static const uint8_t test_stream_change_name[] = {
0x0f, 0x28, 0x00, 0x00, 0x00,
0x71, 0x71, 0x71, 0x72, 0x70, 0x74, 0x20, 0x20,
0x68, 0x68, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20};
/** Test response of processPacket() for a given test stream.
* \param test_stream The test stream data to use.
* \param size The length of the test stream, in bytes.
*/
static void sendOneTestStream(const uint8_t *test_stream, unsigned int size)
{
setTestInputStream(test_stream, size);
processPacket();
printf("\n");
}
/** Wrapper around sendOneTestStream() that covers its most common use
* case (use of a constant byte array). */
#define SEND_ONE_TEST_STREAM(x) sendOneTestStream(x, sizeof(x));
int main(void)
{
int i;
initTests(__FILE__);
initWalletTest();
initWallet();
printf("Listing wallets...\n");
SEND_ONE_TEST_STREAM(test_stream_list_wallets);
printf("Creating new wallet...\n");
SEND_ONE_TEST_STREAM(test_stream_new_wallet);
printf("Listing wallets...\n");
SEND_ONE_TEST_STREAM(test_stream_list_wallets);
for(i = 0; i < 4; i++)
{
printf("Creating new address...\n");
SEND_ONE_TEST_STREAM(test_stream_new_address);