-
Notifications
You must be signed in to change notification settings - Fork 44
/
transaction.c
3171 lines (3023 loc) · 123 KB
/
transaction.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 transaction.c
*
* \brief Contains functions specific to Bitcoin transactions.
*
* There are two main things which are dealt with in this file.
* The first is the parsing of Bitcoin transactions. During the parsing
* process, useful stuff (such as output addresses and amounts) is
* extracted. See the code of parseTransactionInternal() for the guts.
*
* The second is the generation of Bitcoin-compatible signatures. Bitcoin
* uses OpenSSL to generate signatures, and OpenSSL insists on encapsulating
* the "r" and "s" values (see ecdsaSign()) in DER format. See the code of
* signTransaction() for the guts.
*
* This file is licensed as described by the file LICENCE.
*/
#ifdef TEST
#include <stdlib.h>
#include <stdio.h>
#endif // #ifdef TEST
#ifdef TEST_TRANSACTION
#include "test_helpers.h"
#include "stream_comm.h"
#include "wallet.h"
#endif // #ifdef TEST_TRANSACTION
#include "common.h"
#include "endian.h"
#include "ecdsa.h"
#include "baseconv.h"
#include "sha256.h"
#include "bignum256.h"
#include "prandom.h"
#include "hwinterface.h"
#include "transaction.h"
/** The maximum size of a transaction (in bytes) which parseTransaction()
* is prepared to handle. */
#define MAX_TRANSACTION_SIZE 2000000
/** The maximum number of inputs that the transaction parser is prepared
* to handle. This should be small enough that a transaction with the
* maximum number of inputs is still less than #MAX_TRANSACTION_SIZE bytes in
* size.
* \warning This must be < 65536, otherwise an integer overflow may occur.
*/
#define MAX_INPUTS 5000
/** The maximum number of outputs that the transaction parser is prepared
* to handle. This should be small enough that a transaction with the
* maximum number of outputs is still less than #MAX_TRANSACTION_SIZE bytes
* in size.
* \warning This must be < 65536, otherwise an integer overflow may occur.
*/
#define MAX_OUTPUTS 2000
/** The maximum amount that can appear in an output, stored as a little-endian
* multi-precision integer. This represents 21 million BTC. */
static const uint8_t max_money[] = {
0x00, 0x40, 0x07, 0x5A, 0xF0, 0x75, 0x07, 0x00};
/** The transaction fee amount, calculated as output amounts subtracted from
* input amounts. */
static uint8_t transaction_fee_amount[8];
/** Where the transaction parser is within a transaction. 0 = first byte,
* 1 = second byte etc. */
static uint32_t transaction_data_index;
/** The total length of the transaction being parsed, in number of bytes. */
static uint32_t transaction_length;
/** If this is true, then as the transaction contents are read from the
* stream device, they will not be included in the calculation of the
* transaction hash (see parseTransaction() for what this is all about).
* If this is false, then they will be included. */
static bool suppress_transaction_hash;
/** If this is false, then as the transaction contents are read from the
* stream device, they will not be included in the calculation of the
* transaction hash or the signature hash. If this is true, then they
* will be included. This is used to stop #sig_hash_hs_ptr
* and #transaction_hash_hs_ptr from being written to if they don't point
* to a valid hash state. */
static bool hs_ptr_valid;
/** Pointer to hash state used to calculate the signature
* hash (see parseTransaction() for what this is all about).
* \warning If this does not point to a valid hash state structure, ensure
* that #hs_ptr_valid is false to
* stop getTransactionBytes() from attempting to dereference this.
*/
static HashState *sig_hash_hs_ptr;
/** Pointer to hash state used to calculate the transaction
* hash (see parseTransaction() for what this is all about).
* \warning If this does not point to a valid hash state structure, ensure
* that #hs_ptr_valid is false to
* stop getTransactionBytes() from attempting to dereference this.
*/
static HashState *transaction_hash_hs_ptr;
/** Get transaction data by reading from the stream device, checking that
* the read operation won't go beyond the end of the transaction data.
*
* Since all transaction data is read using this function, the updating
* of #sig_hash_hs_ptr and #transaction_hash_hs_ptr is also done.
* \param buffer An array of bytes which will be filled with the transaction
* data (if everything goes well). It must have space for
* length bytes.
* \param length The number of bytes to read from the stream device.
* \return false on success, true if a stream read error occurred or if the
* read would go beyond the end of the transaction data.
*/
static bool getTransactionBytes(uint8_t *buffer, uint8_t length)
{
uint8_t i;
uint8_t one_byte;
if (transaction_data_index > (0xffffffff - (uint32_t)length))
{
// transaction_data_index + (uint32_t)length will overflow.
// Since transaction_length <= 0xffffffff, this implies that the read
// will go past the end of the transaction.
return true; // trying to read past end of transaction
}
if (transaction_data_index + (uint32_t)length > transaction_length)
{
return true; // trying to read past end of transaction
}
else
{
for (i = 0; i < length; i++)
{
one_byte = streamGetOneByte();
buffer[i] = one_byte;
if (hs_ptr_valid)
{
sha256WriteByte(sig_hash_hs_ptr, one_byte);
if (!suppress_transaction_hash)
{
sha256WriteByte(transaction_hash_hs_ptr, one_byte);
}
}
transaction_data_index++;
}
return false;
}
}
/** Checks whether the transaction parser is at the end of the transaction
* data.
* \return false if not at the end of the transaction data, true if at the
* end of the transaction data.
*/
static bool isEndOfTransactionData(void)
{
if (transaction_data_index >= transaction_length)
{
return true;
}
else
{
return false;
}
}
/** Parse a variable-sized integer within a transaction. Variable sized
* integers are commonly used to represent counts or sizes in Bitcoin
* transactions.
* This only supports unsigned variable-sized integers up to a maximum
* value of 2 ^ 32 - 1.
* \param out The value of the integer will be written to here.
* \return false on success, true to indicate an error occurred (unexpected
* end of transaction data or the value of the integer is too large).
*/
static bool getVarInt(uint32_t *out)
{
uint8_t temp[4];
if (getTransactionBytes(temp, 1))
{
return true; // unexpected end of transaction data
}
if (temp[0] < 0xfd)
{
*out = temp[0];
}
else if (temp[0] == 0xfd)
{
if (getTransactionBytes(temp, 2))
{
return true; // unexpected end of transaction data
}
*out = (uint32_t)(temp[0]) | ((uint32_t)(temp[1]) << 8);
}
else if (temp[0] == 0xfe)
{
if (getTransactionBytes(temp, 4))
{
return true; // unexpected end of transaction data
}
*out = readU32LittleEndian(temp);
}
else
{
return true; // varint is too large
}
return false; // success
}
/** See comments for parseTransaction() for description of what this does
* and return values. However, the guts of the transaction parser are in
* the code to this function.
*
* This is called once for each input transaction and once for the spending
* transaction.
* \param sig_hash See parseTransaction().
* \param transaction_hash See parseTransaction().
* \param is_ref_out On success, this will be written with true
* if the transaction parser parsed an input (i.e.
* referenced by input of spending) transaction. This will
* be written with false if the transaction parser parsed
* the main (i.e. spending) transaction.
* \param ref_compare_hs Reference compare hash. This is used to check that
* the input transactions match the references in the
* main transaction.
* \return See parseTransaction().
*/
static TransactionErrors parseTransactionInternal(BigNum256 sig_hash, BigNum256 transaction_hash, bool *is_ref_out, HashState *ref_compare_hs)
{
uint8_t temp[32];
uint8_t ref_compare_hash[32];
uint32_t num_inputs;
uint32_t num_outputs;
uint32_t script_length;
uint8_t input_reference_num_buffer[4];
uint16_t i;
uint8_t j;
uint32_t k;
uint32_t output_num_select;
bool is_ref;
char text_amount[TEXT_AMOUNT_LENGTH];
char text_address[TEXT_ADDRESS_LENGTH];
if (transaction_length > MAX_TRANSACTION_SIZE)
{
return TRANSACTION_TOO_LARGE; // transaction too large
}
// Suppress hashing of input stream, otherwise the is_ref byte and
// output number (which are not part of the transaction data) will
// be included in the signature/transaction hash.
hs_ptr_valid = false;
if (getTransactionBytes(temp, 1))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if (temp[0] != 0)
{
is_ref = true;
}
else
{
is_ref = false;
}
*is_ref_out = is_ref;
output_num_select = 0;
if (is_ref)
{
// Get output number to add to total amount.
if (getTransactionBytes(temp, 4))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
for (j = 0; j < 4; j++)
{
sha256WriteByte(ref_compare_hs, temp[j]);
}
output_num_select = readU32LittleEndian(temp);
}
else
{
// Generate hash of input transaction references for comparison.
sha256FinishDouble(ref_compare_hs);
writeHashToByteArray(ref_compare_hash, ref_compare_hs, false);
sha256Begin(ref_compare_hs);
}
sha256Begin(sig_hash_hs_ptr);
sha256Begin(transaction_hash_hs_ptr);
hs_ptr_valid = true;
suppress_transaction_hash = false;
// Check version.
if (getTransactionBytes(temp, 4))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if (readU32LittleEndian(temp) != 0x00000001)
{
return TRANSACTION_NON_STANDARD; // unsupported transaction version
}
// Get number of inputs.
if (getVarInt(&num_inputs))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated or varint too big
}
if (num_inputs == 0)
{
return TRANSACTION_INVALID_FORMAT; // invalid transaction
}
if (num_inputs > MAX_INPUTS)
{
return TRANSACTION_TOO_MANY_INPUTS; // too many inputs
}
// Process each input.
for (i = 0; i < num_inputs; i++)
{
// Get input transaction reference hash.
if (getTransactionBytes(temp, 32))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
// Get input transaction reference number.
if (getTransactionBytes(input_reference_num_buffer, 4))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if (!is_ref)
{
for (j = 0; j < 4; j++)
{
sha256WriteByte(ref_compare_hs, input_reference_num_buffer[j]);
}
for (j = 0; j < 32; j++)
{
sha256WriteByte(ref_compare_hs, temp[j]);
}
}
// The Bitcoin protocol for signing a transaction involves replacing
// the corresponding input script with the output script that
// the input references. This means that the transaction data parsed
// here will be different depending on which input is being signed
// for. The transaction hash is supposed to be the same regardless of
// which input is being signed for, so the calculation of the
// transaction hash ignores input scripts.
suppress_transaction_hash = true;
// Get input script length.
if (getVarInt(&script_length))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated or varint too big
}
// Skip the script because it's useless here.
for (k = 0; k < script_length; k++)
{
if (getTransactionBytes(temp, 1))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
}
suppress_transaction_hash = false;
// Check sequence. Since locktime is checked below, this check
// is probably superfluous. But it's better to be safe than sorry.
if (getTransactionBytes(temp, 4))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if (readU32LittleEndian(temp) != 0xFFFFFFFF)
{
return TRANSACTION_NON_STANDARD; // replacement not supported
}
} // end for (i = 0; i < num_inputs; i++)
if (!is_ref)
{
// Compare input references with input transactions.
sha256FinishDouble(ref_compare_hs);
writeHashToByteArray(temp, ref_compare_hs, false);
if (memcmp(temp, ref_compare_hash, 32))
{
return TRANSACTION_INVALID_REFERENCE; // references don't match input transactions
}
}
// Get number of outputs.
if (getVarInt(&num_outputs))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated or varint too big
}
if (num_outputs == 0)
{
return TRANSACTION_INVALID_FORMAT; // invalid transaction
}
if (num_outputs > MAX_OUTPUTS)
{
return TRANSACTION_TOO_MANY_OUTPUTS; // too many outputs
}
if (is_ref)
{
if (output_num_select >= num_outputs)
{
return TRANSACTION_INVALID_REFERENCE; // bad reference number
}
}
// Process each output.
for (i = 0; i < num_outputs; i++)
{
// Get output amount.
if (getTransactionBytes(temp, 8))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if (bigCompareVariableSize(temp, (uint8_t *)max_money, 8) == BIGCMP_GREATER)
{
return TRANSACTION_INVALID_AMOUNT; // amount too high
}
if (is_ref)
{
if (i == output_num_select)
{
if (bigAddVariableSizeNoModulo(transaction_fee_amount, transaction_fee_amount, temp, 8))
{
return TRANSACTION_INVALID_AMOUNT; // overflow occurred (carry occurred)
}
}
}
else
{
if (bigSubtractVariableSizeNoModulo(transaction_fee_amount, transaction_fee_amount, temp, 8))
{
return TRANSACTION_INVALID_AMOUNT; // overflow occurred (borrow occurred)
}
amountToText(text_amount, temp);
}
// Get output script length.
if (getVarInt(&script_length))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated or varint too big
}
if (is_ref)
{
// The actual output scripts of input transactions don't need to
// be parsed (only the amount matters), so skip the script.
for (k = 0; k < script_length; k++)
{
if (getTransactionBytes(temp, 1))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
}
}
else
{
// Parsing a spending transaction; output scripts need to be
// matched to a template.
if (script_length == 0x19)
{
// Expect a standard, pay to public key hash output script.
// Look for: OP_DUP, OP_HASH160, (20 bytes of data).
if (getTransactionBytes(temp, 3))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if ((temp[0] != 0x76) || (temp[1] != 0xa9) || (temp[2] != 0x14))
{
return TRANSACTION_NON_STANDARD; // nonstandard transaction
}
if (getTransactionBytes(temp, 20))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
hashToAddr(text_address, temp, ADDRESS_VERSION_PUBKEY);
// Look for: OP_EQUALVERIFY OP_CHECKSIG.
if (getTransactionBytes(temp, 2))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if ((temp[0] != 0x88) || (temp[1] != 0xac))
{
return TRANSACTION_NON_STANDARD; // nonstandard transaction
}
} // end if (script_length == 0x19)
else if (script_length == 0x17)
{
// Expect a standard, pay to script hash output script.
// Look for: OP_HASH160, (20 bytes of data).
if (getTransactionBytes(temp, 2))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if ((temp[0] != 0xa9) || (temp[1] != 0x14))
{
return TRANSACTION_NON_STANDARD; // nonstandard transaction
}
if (getTransactionBytes(temp, 20))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
hashToAddr(text_address, temp, ADDRESS_VERSION_P2SH);
// Look for: OP_EQUAL.
if (getTransactionBytes(temp, 1))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if (temp[0] != 0x87)
{
return TRANSACTION_NON_STANDARD; // nonstandard transaction
}
} // end if (script_length == 0x17)
else
{
return TRANSACTION_NON_STANDARD; // nonstandard transaction
}
if (newOutputSeen(text_amount, text_address))
{
return TRANSACTION_TOO_MANY_OUTPUTS; // too many outputs
}
} // end if (is_ref)
} // end for (i = 0; i < num_outputs; i++)
// Check locktime.
if (getTransactionBytes(temp, 4))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if (readU32LittleEndian(temp) != 0x00000000)
{
return TRANSACTION_NON_STANDARD; // replacement not supported
}
if (!is_ref)
{
// Check hashtype.
if (getTransactionBytes(temp, 4))
{
return TRANSACTION_INVALID_FORMAT; // transaction truncated
}
if (readU32LittleEndian(temp) != 0x00000001)
{
return TRANSACTION_NON_STANDARD; // nonstandard transaction
}
// Is there junk at the end of the transaction data?
if (!isEndOfTransactionData())
{
return TRANSACTION_INVALID_FORMAT; // junk at end of transaction data
}
if (!bigIsZeroVariableSize(transaction_fee_amount, sizeof(transaction_fee_amount)))
{
amountToText(text_amount, transaction_fee_amount);
setTransactionFee(text_amount);
}
}
sha256FinishDouble(sig_hash_hs_ptr);
// The signature hash is written in a little-endian format because it
// is used as a little-endian multi-precision integer in
// signTransaction().
writeHashToByteArray(sig_hash, sig_hash_hs_ptr, false);
sha256FinishDouble(transaction_hash_hs_ptr);
writeHashToByteArray(transaction_hash, transaction_hash_hs_ptr, false);
if (is_ref)
{
// Why backwards? Because Bitcoin serialises the input reference
// hashes that way.
for (j = 32; j--; )
{
sha256WriteByte(ref_compare_hs, sig_hash[j]);
}
}
return TRANSACTION_NO_ERROR;
}
/** Parse a Bitcoin transaction, extracting the output amounts/addresses,
* validating the transaction (ensuring that it is "standard") and computing
* a double SHA-256 hash of the transaction. This double SHA-256 hash is the
* "signature hash" because it is the hash which is passed on to the signing
* function signTransaction().
*
* The Bitcoin protocol for signing a transaction involves replacing
* the corresponding input script with the output script that
* the input references. This means that for a transaction with n
* inputs, there will be n different signature hashes - one for each input.
* Requiring the user to approve a transaction n times would be very
* annoying, so there needs to be a way to determine whether a bunch of
* transactions are actually "the same".
* So in addition to the signature hash, a "transaction hash" will be
* computed. The transaction hash is just like the signature hash, except
* input scripts are not included.
*
* This expects the input stream to contain many concatenated transactions;
* it should contain each input transaction (of the spending transaction)
* followed by the spending transaction. This is necessary
* to calculate the transaction fee. A transaction does directly contain the
* output amounts, but not the input amounts. The only way to get input
* amounts is to look at the output amounts of the transactions the inputs
* refer to.
*
* \param sig_hash The signature hash will be written here (if everything
* goes well), as a 32 byte little-endian multi-precision
* number.
* \param transaction_hash The transaction hash will be written here (if
* everything goes well), as a 32 byte little-endian
* multi-precision number.
* \param length The total length of the transaction. If no stream read
* errors occured, then exactly length bytes will be read from
* the stream, even if the transaction was not parsed
* correctly.
* \return One of the values in #TransactionErrorsEnum.
*/
TransactionErrors parseTransaction(BigNum256 sig_hash, BigNum256 transaction_hash, uint32_t length)
{
TransactionErrors r;
uint8_t junk;
bool is_ref;
HashState sig_hash_hs;
HashState transaction_hash_hs;
HashState ref_compare_hs;
hs_ptr_valid = false;
transaction_data_index = 0;
transaction_length = length;
memset(transaction_fee_amount, 0, sizeof(transaction_fee_amount));
sig_hash_hs_ptr = &sig_hash_hs;
transaction_hash_hs_ptr = &transaction_hash_hs;
sha256Begin(&ref_compare_hs);
hs_ptr_valid = true;
do
{
r = parseTransactionInternal(sig_hash, transaction_hash, &is_ref, &ref_compare_hs);
} while ((r == TRANSACTION_NO_ERROR) && is_ref);
hs_ptr_valid = false;
// Always try to consume the entire stream.
while (!isEndOfTransactionData())
{
if (getTransactionBytes(&junk, 1))
{
break;
}
}
return r;
}
/**
* \defgroup DEROffsets Offsets for DER signature encapsulation.
*
* @{
*/
/** Initial offset of r in signature. It's 4 because 4 bytes are needed for
* the SEQUENCE/length and INTEGER/length bytes. */
#define R_OFFSET 4
/** Initial offset of s in signature. It's 39 because: r is initially 33
* bytes long, and 2 bytes are needed for INTEGER/length. 4 + 33 + 2 = 39. */
#define S_OFFSET 39
/**@}*/
/** Encapsulate an ECDSA signature in the DER format which OpenSSL uses.
* This function does not fail.
* \param signature This must be a byte array with space for at
* least #MAX_SIGNATURE_LENGTH bytes. On exit, the
* encapsulated signature will be written here.
* \param r The r value of the ECDSA signature. This should be a 32 byte
* little-endian multi-precision integer.
* \param s The s value of the ECDSA signature. This should be a 32 byte
* little-endian multi-precision integer.
* \return The length of the signature, in number of bytes.
*/
static uint8_t encapsulateSignature(uint8_t *signature, BigNum256 r, BigNum256 s)
{
uint8_t sequence_length;
uint8_t i;
memcpy(&(signature[R_OFFSET + 1]), r, 32);
memcpy(&(signature[S_OFFSET + 1]), s, 32);
// Place an extra leading zero in front of r and s, just in case their
// most significant bit is 1.
// Integers in DER are always 2s-complement signed, but r and s are
// non-negative. Thus if the most significant bit of r or s is 1,
// a leading zero must be placed in front of the integer to signify that
// it is non-negative.
// If the most significant bit is not 1, the extraneous leading zero will
// be removed in a check below.
signature[R_OFFSET] = 0x00;
signature[S_OFFSET] = 0x00;
// Integers in DER are big-endian.
swapEndian256(&(signature[R_OFFSET + 1]));
swapEndian256(&(signature[S_OFFSET + 1]));
sequence_length = 0x46; // 2 + 33 + 2 + 33
signature[R_OFFSET - 2] = 0x02; // INTEGER
signature[R_OFFSET - 1] = 0x21; // length of INTEGER
signature[S_OFFSET - 2] = 0x02; // INTEGER
signature[S_OFFSET - 1] = 0x21; // length of INTEGER
signature[S_OFFSET + 33] = 0x01; // hashtype
// According to DER, integers should be represented using the shortest
// possible representation. This implies that leading zeroes should
// always be removed. The exception to this is that if removing the
// leading zero would cause the value of the integer to change (eg.
// positive to negative), the leading zero should remain.
// Remove unncecessary leading zeroes from s. s is pruned first
// because pruning r will modify the offset where s begins.
while ((signature[S_OFFSET] == 0) && ((signature[S_OFFSET + 1] & 0x80) == 0))
{
for (i = S_OFFSET; i < 72; i++)
{
signature[i] = signature[i + 1];
}
sequence_length--;
signature[S_OFFSET - 1]--;
if (signature[S_OFFSET - 1] == 1)
{
break;
}
}
// Remove unnecessary leading zeroes from r.
while ((signature[R_OFFSET] == 0) && ((signature[R_OFFSET + 1] & 0x80) == 0))
{
for (i = R_OFFSET; i < 72; i++)
{
signature[i] = signature[i + 1];
}
sequence_length--;
signature[R_OFFSET - 1]--;
if (signature[R_OFFSET - 1] == 1)
{
break;
}
}
signature[0] = 0x30; // SEQUENCE
signature[1] = sequence_length; // length of SEQUENCE
// 3 extra bytes: SEQUENCE/length and hashtype
return (uint8_t)(sequence_length + 3);
}
/** Sign a transaction. This should be called after the transaction is parsed
* and a signature hash has been computed. The primary purpose of this
* function is to call ecdsaSign() and encapsulate the ECDSA signature in
* the DER format which OpenSSL uses.
* \param signature The encapsulated signature will be written here. This
* must be a byte array with space for
* at least #MAX_SIGNATURE_LENGTH bytes.
* \param out_length The length of the signature, in number of bytes, will be
* written here (on success). This length includes the hash
* type byte.
* \param sig_hash The signature hash of the transaction (see
* parseTransaction()).
* \param private_key The private key to sign the transaction with. This must
* be a 32 byte little-endian multi-precision integer.
* \return false on success, or true if an error occurred while trying to
* obtain a random number.
*/
void signTransaction(uint8_t *signature, uint8_t *out_length, BigNum256 sig_hash, BigNum256 private_key)
{
uint8_t r[32];
uint8_t s[32];
*out_length = 0;
ecdsaSign(r, s, sig_hash, private_key);
*out_length = encapsulateSignature(signature, r, s);
}
#ifdef TEST
/** Number of outputs seen. */
static int num_outputs_seen;
bool newOutputSeen(char *text_amount, char *text_address)
{
printf("Amount: %s\n", text_amount);
printf("Address: %s\n", text_address);
num_outputs_seen++;
return false; // success
}
void setTransactionFee(char *text_amount)
{
printf("Transaction fee: %s\n", text_amount);
}
void clearOutputsSeen(void)
{
num_outputs_seen = 0;
}
#endif // #ifdef TEST
#ifdef TEST_TRANSACTION
/** A known good test transaction. This one was intercepted from the original
* Bitcoin client during the signing of a live transaction. The input
* references and addresses have been changed to protect privacy. */
static const uint8_t good_full_transaction[] = {
// The first (and only) input transaction.
// This isn't part of the intercepted transaction; it was obtained from
// blockexplorer.com.
0x01, // is_ref = 1 (input)
0x01, 0x00, 0x00, 0x00, // output number to examine
0x01, 0x00, 0x00, 0x00, // version
0x01, // number of inputs
0xdf, 0x08, 0xf9, 0xa3, 0x7c, 0x6d, 0x71, 0x3c, // previous output
0x6a, 0x99, 0x2e, 0x88, 0x29, 0x8e, 0x0b, 0x4c,
0x8f, 0xb5, 0xf9, 0x0e, 0x11, 0xf0, 0x2c, 0xa7,
0x36, 0x72, 0xeb, 0x58, 0xb3, 0x04, 0xef, 0xc0,
0x01, 0x00, 0x00, 0x00, // number in previous output
0x8a, // script length
0x47, // 71 bytes of data follows
0x30, 0x44, 0x02, 0x20, 0x1b, 0xf4, 0xef, 0x3c, 0x34, 0x96, 0x02, 0x9b, 0x1a,
0xb1, 0xc8, 0x49, 0xbf, 0x18, 0x55, 0xcc, 0x16, 0xbc, 0x52, 0x6d, 0xcc, 0x20,
0xfb, 0x7c, 0x0a, 0x1d, 0x48, 0xd6, 0xe9, 0xbd, 0xd7, 0xb1, 0x02, 0x20, 0x53,
0xb1, 0xa3, 0xaa, 0xbf, 0xd3, 0x87, 0x84, 0xdc, 0xf3, 0x10, 0xe5, 0xd2, 0x09,
0xa4, 0xba, 0xb0, 0x01, 0x62, 0xe5, 0xbc, 0x09, 0x75, 0x9d, 0x4f, 0x74, 0x2c,
0xb4, 0x6b, 0x32, 0x37, 0x2c, 0x01,
0x41, // 65 bytes of data follows
0x04, 0x05, 0x4d, 0xb5, 0xe0, 0x8e, 0x2a, 0x33, 0x89, 0x2c, 0xf3, 0x4b, 0x7e,
0xbc, 0x18, 0x3b, 0xa5, 0xf5, 0x54, 0xc6, 0x9d, 0x6d, 0x21, 0x65, 0x60, 0x89,
0xf5, 0x5e, 0x2d, 0x0f, 0x3a, 0x68, 0x08, 0x23, 0x83, 0x19, 0xcd, 0x89, 0xba,
0xda, 0x09, 0x9b, 0xc6, 0xef, 0x3f, 0xdc, 0x80, 0xd8, 0x7a, 0xb2, 0xbf, 0x2b,
0x37, 0x18, 0xdd, 0x4a, 0x4e, 0x36, 0x09, 0x60, 0x28, 0x6e, 0x2e, 0x77, 0x57,
0xFF, 0xFF, 0xFF, 0xFF, // sequence
0x02, // number of outputs
0xc0, 0xa4, 0x70, 0x57, 0x00, 0x00, 0x00, 0x00, // 14.67 BTC
0x19, // script length
0x76, // OP_DUP
0xA9, // OP_HASH160
0x14, // 20 bytes of data follows
// 1Q6W8HTPdwccCkLRMLJpYkGvweKhpsKKjE
0xfd, 0x55, 0x49, 0x20, 0x22, 0xa0, 0x3f, 0xf7, 0x7a, 0x9d,
0xe0, 0x0d, 0xa2, 0x18, 0x08, 0x0c, 0xa9, 0x51, 0xde, 0xef,
0x88, // OP_EQUALVERIFY
0xAC, // OP_CHECKSIG
0x40, 0x54, 0x92, 0x3d, 0x00, 0x00, 0x00, 0x00, // 10.33 BTC
0x19, // script length
0x76, // OP_DUP
0xA9, // OP_HASH160
0x14, // 20 bytes of data follows
// 16E7VhudyU3iXNddNazG8sChjQwfWcrHNw
0x39, 0x53, 0x75, 0x46, 0x88, 0x84, 0x3d, 0xe5, 0x50, 0x0b,
0x79, 0x91, 0x33, 0x7f, 0x96, 0xf5, 0x41, 0x71, 0x48, 0xa1,
0x88, // OP_EQUALVERIFY
0xAC, // OP_CHECKSIG
0x00, 0x00, 0x00, 0x00, // locktime
// The main (spending) transaction.
0x00, // is_ref = 0 (main)
0x01, 0x00, 0x00, 0x00, // version
0x01, // number of inputs
0xee, 0xce, 0xae, 0x86, 0xf5, 0x70, 0x4d, 0x76, // previous output
0xb8, 0x54, 0x5e, 0x6d, 0xcf, 0x21, 0xf1, 0x75,
0x35, 0x7f, 0x83, 0xbd, 0xa4, 0x96, 0x43, 0x83,
0xd6, 0xdd, 0x7e, 0x41, 0x68, 0x1b, 0x5e, 0x1a,
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
};
/** The input transaction from #good_full_transaction. */
static const uint8_t good_input_transaction[] = {
0x01, 0x00, 0x00, 0x00, // output number to examine
0x01, 0x00, 0x00, 0x00, // version
0x01, // number of inputs
0xdf, 0x08, 0xf9, 0xa3, 0x7c, 0x6d, 0x71, 0x3c, // previous output
0x6a, 0x99, 0x2e, 0x88, 0x29, 0x8e, 0x0b, 0x4c,
0x8f, 0xb5, 0xf9, 0x0e, 0x11, 0xf0, 0x2c, 0xa7,
0x36, 0x72, 0xeb, 0x58, 0xb3, 0x04, 0xef, 0xc0,
0x01, 0x00, 0x00, 0x00, // number in previous output
0x8a, // script length
0x47, // 71 bytes of data follows
0x30, 0x44, 0x02, 0x20, 0x1b, 0xf4, 0xef, 0x3c, 0x34, 0x96, 0x02, 0x9b, 0x1a,
0xb1, 0xc8, 0x49, 0xbf, 0x18, 0x55, 0xcc, 0x16, 0xbc, 0x52, 0x6d, 0xcc, 0x20,
0xfb, 0x7c, 0x0a, 0x1d, 0x48, 0xd6, 0xe9, 0xbd, 0xd7, 0xb1, 0x02, 0x20, 0x53,
0xb1, 0xa3, 0xaa, 0xbf, 0xd3, 0x87, 0x84, 0xdc, 0xf3, 0x10, 0xe5, 0xd2, 0x09,
0xa4, 0xba, 0xb0, 0x01, 0x62, 0xe5, 0xbc, 0x09, 0x75, 0x9d, 0x4f, 0x74, 0x2c,
0xb4, 0x6b, 0x32, 0x37, 0x2c, 0x01,
0x41, // 65 bytes of data follows
0x04, 0x05, 0x4d, 0xb5, 0xe0, 0x8e, 0x2a, 0x33, 0x89, 0x2c, 0xf3, 0x4b, 0x7e,
0xbc, 0x18, 0x3b, 0xa5, 0xf5, 0x54, 0xc6, 0x9d, 0x6d, 0x21, 0x65, 0x60, 0x89,
0xf5, 0x5e, 0x2d, 0x0f, 0x3a, 0x68, 0x08, 0x23, 0x83, 0x19, 0xcd, 0x89, 0xba,
0xda, 0x09, 0x9b, 0xc6, 0xef, 0x3f, 0xdc, 0x80, 0xd8, 0x7a, 0xb2, 0xbf, 0x2b,
0x37, 0x18, 0xdd, 0x4a, 0x4e, 0x36, 0x09, 0x60, 0x28, 0x6e, 0x2e, 0x77, 0x57,
0xFF, 0xFF, 0xFF, 0xFF, // sequence
0x02, // number of outputs
0xc0, 0xa4, 0x70, 0x57, 0x00, 0x00, 0x00, 0x00, // 14.67 BTC
0x19, // script length
0x76, // OP_DUP
0xA9, // OP_HASH160
0x14, // 20 bytes of data follows
// 1Q6W8HTPdwccCkLRMLJpYkGvweKhpsKKjE
0xfd, 0x55, 0x49, 0x20, 0x22, 0xa0, 0x3f, 0xf7, 0x7a, 0x9d,
0xe0, 0x0d, 0xa2, 0x18, 0x08, 0x0c, 0xa9, 0x51, 0xde, 0xef,
0x88, // OP_EQUALVERIFY
0xAC, // OP_CHECKSIG
0x40, 0x54, 0x92, 0x3d, 0x00, 0x00, 0x00, 0x00, // 10.33 BTC
0x19, // script length
0x76, // OP_DUP
0xA9, // OP_HASH160
0x14, // 20 bytes of data follows
// 16E7VhudyU3iXNddNazG8sChjQwfWcrHNw
0x39, 0x53, 0x75, 0x46, 0x88, 0x84, 0x3d, 0xe5, 0x50, 0x0b,
0x79, 0x91, 0x33, 0x7f, 0x96, 0xf5, 0x41, 0x71, 0x48, 0xa1,
0x88, // OP_EQUALVERIFY
0xAC, // OP_CHECKSIG
0x00, 0x00, 0x00, 0x00, // locktime
};
/** The main transaction from #good_full_transaction. This must actually be
* the main transaction from #good_full_transaction, otherwise some tests
* will complain about hashes not being calculated properly. */
static const uint8_t good_main_transaction[] = {
0x01, 0x00, 0x00, 0x00, // version
0x01, // number of inputs
0xee, 0xce, 0xae, 0x86, 0xf5, 0x70, 0x4d, 0x76, // previous output
0xb8, 0x54, 0x5e, 0x6d, 0xcf, 0x21, 0xf1, 0x75,
0x35, 0x7f, 0x83, 0xbd, 0xa4, 0x96, 0x43, 0x83,
0xd6, 0xdd, 0x7e, 0x41, 0x68, 0x1b, 0x5e, 0x1a,
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
};
/** The main transaction from #good_full_transaction, with the inputs
* removed. */
static const uint8_t inputs_removed_transaction[] = {
0x01, 0x00, 0x00, 0x00, // version
0x01, // number of inputs
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