-
-
Notifications
You must be signed in to change notification settings - Fork 637
/
signing.c
4157 lines (3715 loc) · 135 KB
/
signing.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
/*
* This file is part of the Trezor project, https://trezor.io/
*
* Copyright (C) 2014 Pavol Rusnak <stick@satoshilabs.com>
*
* This library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "signing.h"
#include "config.h"
#include "crypto.h"
#include "ecdsa.h"
#include "fsm.h"
#include "gettext.h"
#include "layout2.h"
#include "memzero.h"
#include "messages.h"
#include "messages.pb.h"
#include "protect.h"
#include "secp256k1.h"
#include "transaction.h"
#include "zkp_bip340.h"
#if DEBUG_LINK
#include <inttypes.h>
#include <stdio.h>
#endif
static uint32_t change_count;
static const CoinInfo *coin;
static AmountUnit amount_unit;
static bool serialize;
static CONFIDENTIAL HDNode root;
static CONFIDENTIAL HDNode node;
static bool signing = false;
enum {
STAGE_REQUEST_1_INPUT,
STAGE_REQUEST_1_ORIG_META,
STAGE_REQUEST_1_ORIG_INPUT,
STAGE_REQUEST_2_OUTPUT,
STAGE_REQUEST_2_ORIG_OUTPUT,
#if !BITCOIN_ONLY
STAGE_REQUEST_2_ORIG_EXTRADATA,
#endif
STAGE_REQUEST_3_INPUT,
STAGE_REQUEST_3_PREV_META,
STAGE_REQUEST_3_PREV_INPUT,
STAGE_REQUEST_3_PREV_OUTPUT,
#if !BITCOIN_ONLY
STAGE_REQUEST_3_PREV_EXTRADATA,
#endif
STAGE_REQUEST_3_ORIG_INPUT,
STAGE_REQUEST_3_ORIG_OUTPUT,
STAGE_REQUEST_3_ORIG_NONLEGACY_INPUT,
STAGE_REQUEST_4_INPUT,
STAGE_REQUEST_4_OUTPUT,
STAGE_REQUEST_NONLEGACY_INPUT,
STAGE_REQUEST_5_OUTPUT,
STAGE_REQUEST_SEGWIT_WITNESS,
#if !BITCOIN_ONLY
STAGE_REQUEST_DECRED_WITNESS,
#endif
} signing_stage;
static bool foreign_address_confirmed; // indicates that user approved warning
static bool taproot_only; // indicates whether all internal inputs are Taproot
static bool has_unverified_external_input;
static uint32_t idx1; // The index of the input or output in the current tx
// which is being processed, signed or serialized.
static uint32_t idx2; // The index of the input or output in the original tx
// (Phase 1), in the previous tx (Phase 2) or in the
// current tx when computing the legacy digest (Phase 2).
static uint32_t external_inputs[16]; // bitfield of external input indices
static uint32_t signatures;
static TxRequest resp;
static TxInputType input;
static TxOutputType output;
static TxOutputBinType bin_output;
static TxStruct to; // Used to serialize the current transaction.
static TxStruct tp; // Used to compute TXID of original tx in Phase 1 and
// previous tx in Phase 2.
static TxStruct ti; // Used in Phase 1 to compute original legacy digest or
// Decred hashPrefix, and in Phase 2 to compute legacy
// digest or Decred witness hash.
static Hasher hasher_check;
static uint8_t CONFIDENTIAL privkey[32];
static uint8_t pubkey[33]; // Used in Phase 2 to compile scriptSig when signing
// legacy inputs.
static uint8_t sig[64]; // Used in Phase 1 to store signature of original tx
// and in Phase 2 as a temporary signature buffer.
#if !BITCOIN_ONLY
static uint8_t decred_hash_prefix[32];
#endif
static uint64_t total_in, external_in, total_out, change_out;
static uint64_t orig_total_in, orig_external_in, orig_total_out,
orig_change_out;
static uint32_t progress_step, progress_steps, progress_substep,
progress_substeps, progress_midpoint, progress_update;
static const char *progress_label;
static uint32_t tx_weight, tx_base_weight, our_weight, our_inputs_len;
PathSchema unlocked_schema;
typedef enum _MatchState {
MatchState_UNDEFINED = 0,
MatchState_MATCH = 1,
MatchState_MISMATCH = 2,
} MatchState;
typedef struct {
uint32_t inputs_count;
uint32_t outputs_count;
uint32_t segwit_count;
uint32_t next_legacy_input;
uint32_t min_sequence;
bool multisig_fp_set;
bool multisig_fp_mismatch;
uint8_t multisig_fp[32];
uint32_t in_address_n[8];
size_t in_address_n_count;
InputScriptType in_script_type;
MatchState in_script_type_state;
uint32_t version;
uint32_t lock_time;
uint32_t expiry;
uint32_t version_group_id;
uint32_t timestamp;
#if !BITCOIN_ONLY
uint32_t branch_id;
uint8_t hash_header[32];
#endif
Hasher hasher_check;
Hasher hasher_prevouts;
Hasher hasher_amounts;
Hasher hasher_scriptpubkeys;
Hasher hasher_sequences;
Hasher hasher_outputs;
uint8_t hash_inputs_check[32];
uint8_t hash_prevouts[32];
uint8_t hash_amounts[32];
uint8_t hash_scriptpubkeys[32];
uint8_t hash_sequences[32];
uint8_t hash_outputs[32];
uint8_t hash_prevouts143[32];
uint8_t hash_outputs143[32];
uint8_t hash_sequence143[32];
} TxInfo;
static TxInfo info;
/* Variables specific to replacement transactions. */
static bool is_replacement; // Is this a replacement transaction?
static TxInfo orig_info;
static uint8_t orig_hash[32]; // TXID of the original transaction.
/* Variables specific to CoinJoin transactions. */
static secbool is_coinjoin; // Is this a CoinJoin transaction?
static uint64_t coinjoin_coordination_fee_base;
static AuthorizeCoinJoin coinjoin_authorization;
static CoinJoinRequest coinjoin_request;
/* A marker for in_address_n_count to indicate a mismatch in bip32 paths in
input */
#define BIP32_NOCHANGEALLOWED 1
/* transaction header size: 4 byte version */
#define TXSIZE_HEADER 4
/* transaction footer size: 4 byte lock time */
#define TXSIZE_FOOTER 4
/* transaction segwit overhead 2 marker */
#define TXSIZE_SEGWIT_OVERHEAD 2
/* The maximum number of change-outputs allowed without user confirmation. */
#define MAX_SILENT_CHANGE_COUNT 2
/* The maximum number of inputs allowed in a transaction is limited by the
* number of external inputs that the firmware can count. */
#define MAX_INPUTS_COUNT (sizeof(external_inputs) * 8)
/* Setting nSequence to this value for every input in a transaction disables
nLockTime. */
#define SEQUENCE_FINAL 0xffffffff
/* Setting nSequence to a value greater than this for every input in a
transaction disables replace-by-fee opt-in. */
#define MAX_BIP125_RBF_SEQUENCE 0xFFFFFFFD
/* supported version of Decred script_version */
#define DECRED_SCRIPT_VERSION 0
enum {
DECRED_SERIALIZE_FULL = 0,
DECRED_SERIALIZE_NO_WITNESS = 1,
DECRED_SERIALIZE_WITNESS_SIGNING = 3,
};
/* progress_step/meta_step are fixed point numbers, giving the
* progress per input in permille with these many additional bits.
*/
#define PROGRESS_PRECISION 16
/*
clang-format off
Workflow of streamed signing
The STAGE_ constants describe the signing_stage when request is sent.
I - input
O - output
Phase1 - process inputs
- confirm outputs
- check fee and confirm totals
- check previous transactions
=========================================================
Stage 1: Get inputs and optionally get original inputs.
foreach I (idx1):
Request I STAGE_REQUEST_1_INPUT
Add I to segwit sub-hashes
Add I to Decred decred_hash_prefix
Add I to TransactionChecksum (prevout and type)
if (I has orig_hash)
Request input I2 orig_hash, orig_index STAGE_REQUEST_1_ORIG_INPUT
Check I matches I2
Add I2 to original segwit sub-hashes
Add I2 to orig_info.hash_inputs_check
if (Decred)
Return I
Stage 2: Get outputs and optionally get original outputs.
foreach O (idx1):
Request O STAGE_REQUEST_2_OUTPUT
Add O to Decred decred_hash_prefix
Add O to TransactionChecksum
if (is_replacement)
Request output O2 orig_hash, orig_index STAGE_REQUEST_2_ORIG_OUTPUT
Check O matches O2
Add O2 to orig_hash_outputs
if (Decred)
Return O
if (!is_change and !is_replacement)
Display output
Ask for confirmation
Check tx fee
Ask for confirmation
Stage 3: Check transaction.
if (taproot_only)
Skip checking of previous transactions.
foreach I (idx1):
Request I STAGE_REQUEST_3_INPUT
Request prevhash I, META STAGE_REQUEST_3_PREV_META
foreach prevhash I (idx2):
Request prevhash I STAGE_REQUEST_3_PREV_INPUT
foreach prevhash O (idx2):
Request prevhash O STAGE_REQUEST_3_PREV_OUTPUT
Add amount of prevhash O (which is amount of I)
Request prevhash extra data (if applicable) STAGE_REQUEST_3_PREV_EXTRADATA
Calculate hash of streamed tx, compare to prevhash I
if (is_replacement)
foreach orig I (idx1):
if (orig idx1 is not legacy)
Request input I, orig_hash, idx1 STAGE_REQUEST_3_ORIG_NONLEGACY_INPUT
Add I to OuterTransactionChecksum
Verify signature of I if I is internal
else
foreach orig I (idx2):
Request input I, orig_hash, idx2 STAGE_REQUEST_3_ORIG_INPUT
Add I to InnerTransactionChecksum
Add I to LegacyTransactionDigest
if idx1 == idx2
Add I to OuterTransactionChecksum
Save signature for verification
Ensure InnerTransactionChecksum matches orig_info.hash_inputs_check
foreach orig O (idx2):
Request output O, orig_hash, idx2 STAGE_REQUEST_3_ORIG_OUTPUT
Add O to InnerTransactionChecksum
Add O to LegacyTransactionDigest
Ensure InnerTransactionChecksum matches orig_hash_outputs
Verify signature of LegacyTransactionDigest
Ensure OuterTransactionChecksum matches orig_info.hash_inputs_check
Phase2: sign inputs, check that nothing changed
===============================================
if (Decred)
Skip to STAGE_REQUEST_DECRED_WITNESS
foreach I (idx1): // input to sign
if (idx1 is not legacy)
Request I STAGE_REQUEST_NONLEGACY_INPUT
Return serialized input chunk
else
foreach I (idx2):
Request I STAGE_REQUEST_4_INPUT
If idx1 == idx2
Fill scriptsig
Remember key for signing
Add I to StreamTransactionSign
Add I to TransactionChecksum
foreach O (idx2):
Request O STAGE_REQUEST_4_OUTPUT
Add O to StreamTransactionSign
Add O to TransactionChecksum
Compare TransactionChecksum with checksum computed in Phase 1
If different:
Failure
Sign StreamTransactionSign
Return signed chunk
foreach O (idx1):
Request O STAGE_REQUEST_5_OUTPUT
Rewrite change address
Return O
Phase3: sign segwit inputs, check that nothing changed
===============================================
foreach I (idx1): // input to sign
Request I STAGE_REQUEST_SEGWIT_WITNESS
Check amount
Sign segwit prevhash, sequence, amount, outputs
Return witness
Phase3: sign Decred inputs
==========================
foreach I (idx1): // input to sign STAGE_REQUEST_DECRED_WITNESS
Request I
Fill scriptSig
Compute hash_witness
Sign (hash_type || decred_hash_prefix || hash_witness)
Return witness
clang-format on
*/
static bool add_amount(uint64_t *dest, uint64_t amount) {
if (*dest + amount < *dest) {
fsm_sendFailure(FailureType_Failure_DataError, _("Value overflow"));
signing_abort();
return false;
}
*dest += amount;
return true;
}
static bool is_rbf_enabled(TxInfo *tx_info) {
return tx_info->min_sequence <= MAX_BIP125_RBF_SEQUENCE;
}
static void set_external_input(uint32_t i) {
external_inputs[i / 32] |= (1 << (i % 32));
}
static bool is_external_input(uint32_t i) {
return external_inputs[i / 32] & (1 << (i % 32));
}
static void report_progress(bool force) {
static uint32_t update_ctr = 0;
if (!force && update_ctr < progress_update) {
update_ctr++;
return;
}
uint32_t progress = 0;
if (progress_midpoint != 0) {
if (progress_step < progress_midpoint) {
// Checking previous transactions.
progress =
(500 * progress_step + 500 * progress_substep / progress_substeps) /
progress_midpoint;
} else {
// Signing transaction after checking. No substeps.
progress = 500 + 500 * (progress_step - progress_midpoint) /
(progress_steps - progress_midpoint);
}
} else {
// Loading transaction or signing transaction without checking. No substeps.
progress = 1000 * progress_step / progress_steps;
}
layoutProgress(progress_label, progress);
update_ctr = 0;
}
#if DEBUG_LINK
static bool assert_progress_finished(void) {
char line[54] = {0};
if (progress_step != progress_steps) {
snprintf(line, sizeof(line), "%s finished at %" PRIu32 "/%" PRIu32,
progress_label, progress_step, progress_steps);
} else if (progress_substep != 0) {
snprintf(line, sizeof(line), "%s finished at substep %" PRIu32,
progress_label, progress_substep);
} else {
return true;
}
fsm_sendFailure(FailureType_Failure_FirmwareError, line);
signing_abort();
return false;
}
#endif
static void init_loading_progress(void) {
progress_label = _("Loading transaction");
progress_step = 0;
progress_substep = 0;
progress_substeps = 1; // no substeps in tx loading
progress_midpoint = 0; // no midpoint in tx loading
progress_update = 10; // update screen every 10 steps
// Stage 1 and 2 - load inputs and outputs
progress_steps = info.inputs_count + info.outputs_count;
report_progress(true);
}
static void init_signing_progress(void) {
progress_label = _("Signing transaction");
progress_step = 0;
progress_steps = 0;
progress_update = 20; // update screen every 20 steps
// Verify previous transactions (STAGE_REQUEST_3_PREV_*).
// We don't know how long it will take to fetch the previous transactions. If
// they need to be checked, then we will reserve 50 % of the progress for
// this. Once we fetch a prev_tx's metadata, we subdivide the reserved space
// into substeps which represent the progress of fetching one prev_tx input or
// output.
if (!taproot_only && !(coin->overwintered && info.version == 5)) {
progress_steps += info.inputs_count;
progress_midpoint = progress_steps;
}
uint32_t external_count = 0;
for (size_t i = 0; i < info.inputs_count; ++i) {
external_count += is_external_input(i);
}
// Process inputs.
if (!(coin->force_bip143 || coin->overwintered || coin->decred)) {
// Sign and optionally serialize legacy inputs (STAGE_REQUEST_4_*).
progress_steps += (info.inputs_count - info.segwit_count - external_count) *
(info.inputs_count + info.outputs_count);
if (serialize) {
// Serialize non-legacy inputs (STAGE_REQUEST_NONLEGACY_INPUT).
progress_steps += info.segwit_count + external_count;
}
if (is_replacement) {
// Verify original input signatures (STAGE_REQUEST_3_ORIG_*).
progress_steps +=
(orig_info.inputs_count - orig_info.segwit_count - external_count) *
(orig_info.inputs_count + orig_info.outputs_count);
progress_steps += orig_info.segwit_count;
}
} else {
// Sign and optionally serialize each input (STAGE_REQUEST_NONLEGACY_INPUT,
// or in case of Decred STAGE_REQUEST_DECRED_WITNESS).
progress_steps += info.inputs_count;
if (is_replacement) {
// Verify each original input (STAGE_REQUEST_3_ORIG_NONLEGACY_INPUT).
progress_steps += orig_info.inputs_count;
}
}
if (to.is_segwit) {
if (serialize) {
// Serialize witnesses for all inputs (STAGE_REQUEST_SEGWIT_WITNESS).
progress_steps += info.inputs_count;
} else {
// Process witnesses for all internal inputs
// (STAGE_REQUEST_SEGWIT_WITNESS).
progress_steps += info.inputs_count - external_count;
}
}
// Serialize outputs (STAGE_REQUEST_5_OUTPUT).
if (serialize && !coin->decred) {
progress_steps += info.outputs_count;
}
report_progress(true);
}
void send_req_1_input(void) {
signing_stage = STAGE_REQUEST_1_INPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx1;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_1_orig_meta(void) {
signing_stage = STAGE_REQUEST_1_ORIG_META;
resp.has_request_type = true;
resp.request_type = RequestType_TXMETA;
resp.has_details = true;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = sizeof(orig_hash);
memcpy(resp.details.tx_hash.bytes, orig_hash, resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_1_orig_input(void) {
signing_stage = STAGE_REQUEST_1_ORIG_INPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXORIGINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx2;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = sizeof(orig_hash);
memcpy(resp.details.tx_hash.bytes, orig_hash, resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_2_output(void) {
signing_stage = STAGE_REQUEST_2_OUTPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXOUTPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx1;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_2_orig_output(void) {
signing_stage = STAGE_REQUEST_2_ORIG_OUTPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXORIGOUTPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx2;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = sizeof(orig_hash);
memcpy(resp.details.tx_hash.bytes, orig_hash, resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
#if !BITCOIN_ONLY
void send_req_2_orig_extradata(uint32_t chunk_offset, uint32_t chunk_len) {
signing_stage = STAGE_REQUEST_2_ORIG_EXTRADATA;
resp.has_request_type = true;
resp.request_type = RequestType_TXEXTRADATA;
resp.has_details = true;
resp.details.has_extra_data_offset = true;
resp.details.extra_data_offset = chunk_offset;
resp.details.has_extra_data_len = true;
resp.details.extra_data_len = chunk_len;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = sizeof(orig_hash);
memcpy(resp.details.tx_hash.bytes, orig_hash, resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
#endif
void send_req_3_input(void) {
signing_stage = STAGE_REQUEST_3_INPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx1;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_3_prev_meta(void) {
signing_stage = STAGE_REQUEST_3_PREV_META;
resp.has_request_type = true;
resp.request_type = RequestType_TXMETA;
resp.has_details = true;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = input.prev_hash.size;
memcpy(resp.details.tx_hash.bytes, input.prev_hash.bytes,
input.prev_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_3_prev_input(void) {
signing_stage = STAGE_REQUEST_3_PREV_INPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx2;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = input.prev_hash.size;
memcpy(resp.details.tx_hash.bytes, input.prev_hash.bytes,
resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_3_prev_output(void) {
signing_stage = STAGE_REQUEST_3_PREV_OUTPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXOUTPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx2;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = input.prev_hash.size;
memcpy(resp.details.tx_hash.bytes, input.prev_hash.bytes,
resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
#if !BITCOIN_ONLY
void send_req_3_prev_extradata(uint32_t chunk_offset, uint32_t chunk_len) {
signing_stage = STAGE_REQUEST_3_PREV_EXTRADATA;
resp.has_request_type = true;
resp.request_type = RequestType_TXEXTRADATA;
resp.has_details = true;
resp.details.has_extra_data_offset = true;
resp.details.extra_data_offset = chunk_offset;
resp.details.has_extra_data_len = true;
resp.details.extra_data_len = chunk_len;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = input.prev_hash.size;
memcpy(resp.details.tx_hash.bytes, input.prev_hash.bytes,
resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
#endif
void send_req_3_orig_nonlegacy_input(void) {
signing_stage = STAGE_REQUEST_3_ORIG_NONLEGACY_INPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXORIGINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx1;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = sizeof(orig_hash);
memcpy(resp.details.tx_hash.bytes, orig_hash, resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_3_orig_input(void) {
signing_stage = STAGE_REQUEST_3_ORIG_INPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXORIGINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx2;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = sizeof(orig_hash);
memcpy(resp.details.tx_hash.bytes, orig_hash, resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_3_orig_output(void) {
signing_stage = STAGE_REQUEST_3_ORIG_OUTPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXORIGOUTPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx2;
resp.details.has_tx_hash = true;
resp.details.tx_hash.size = sizeof(orig_hash);
memcpy(resp.details.tx_hash.bytes, orig_hash, resp.details.tx_hash.size);
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_4_input(void) {
signing_stage = STAGE_REQUEST_4_INPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx2;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_4_output(void) {
signing_stage = STAGE_REQUEST_4_OUTPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXOUTPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx2;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_nonlegacy_input(void) {
signing_stage = STAGE_REQUEST_NONLEGACY_INPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx1;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_segwit_witness(void) {
signing_stage = STAGE_REQUEST_SEGWIT_WITNESS;
resp.has_request_type = true;
resp.request_type = RequestType_TXINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx1;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
#if !BITCOIN_ONLY
void send_req_decred_witness(void) {
signing_stage = STAGE_REQUEST_DECRED_WITNESS;
resp.has_request_type = true;
resp.request_type = RequestType_TXINPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx1;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
#endif
void send_req_5_output(void) {
signing_stage = STAGE_REQUEST_5_OUTPUT;
resp.has_request_type = true;
resp.request_type = RequestType_TXOUTPUT;
resp.has_details = true;
resp.details.has_request_index = true;
resp.details.request_index = idx1;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void send_req_finished(void) {
#if DEBUG_LINK
if (!assert_progress_finished()) {
return;
}
#endif
resp.has_request_type = true;
resp.request_type = RequestType_TXFINISHED;
msg_write(MessageType_MessageType_TxRequest, &resp);
}
void phase1_request_next_input(void) {
if (idx1 < info.inputs_count - 1) {
idx1++;
send_req_1_input();
} else {
idx1 = 0;
if (is_replacement) {
if (idx2 != orig_info.inputs_count) {
fsm_sendFailure(FailureType_Failure_DataError,
_("Removal of original inputs is not supported."));
signing_abort();
return;
}
char *description = NULL;
if (!is_rbf_enabled(&info) && is_rbf_enabled(&orig_info)) {
description = _("Finalize TXID:");
} else {
description = _("Update TXID:");
}
// Confirm original TXID.
layoutConfirmReplacement(description, orig_hash);
if (!protectButton(ButtonRequestType_ButtonRequest_SignTx, false)) {
fsm_sendFailure(FailureType_Failure_ActionCancelled, NULL);
signing_abort();
return;
}
idx2 = 0;
}
if (to.is_segwit) {
tx_base_weight += TXSIZE_SEGWIT_OVERHEAD;
tx_weight += TXSIZE_SEGWIT_OVERHEAD + to.inputs_len;
our_weight += TXSIZE_SEGWIT_OVERHEAD + our_inputs_len;
}
send_req_2_output();
}
}
void phase1_request_orig_input(void) {
if (!is_replacement) {
// Get original tx metadata before getting first original input.
memcpy(orig_hash, input.orig_hash.bytes, sizeof(orig_hash));
is_replacement = true;
idx2 = 0;
send_req_1_orig_meta();
} else {
if (memcmp(input.orig_hash.bytes, orig_hash, sizeof(orig_hash)) != 0) {
fsm_sendFailure(FailureType_Failure_ProcessError,
_("Only one original transaction is allowed."));
signing_abort();
return;
}
if (input.orig_index >= orig_info.inputs_count) {
fsm_sendFailure(FailureType_Failure_DataError,
_("Not enough inputs in original transaction."));
signing_abort();
return;
}
if (idx2 != input.orig_index) {
fsm_sendFailure(
FailureType_Failure_DataError,
_("Rearranging or removal of original inputs is not supported."));
signing_abort();
return;
}
send_req_1_orig_input();
}
}
void phase2_request_next_witness(bool first) {
if (first) {
idx1 = 0;
if (!to.is_segwit) {
send_req_finished();
signing_abort();
return;
}
} else if (idx1 < info.inputs_count - 1) {
idx1++;
} else {
send_req_finished();
signing_abort();
return;
}
if (!serialize) {
// Skip external inputs when serialization is disabled.
while (is_external_input(idx1)) {
if (idx1 >= info.inputs_count - 1) {
send_req_finished();
signing_abort();
return;
}
idx1++;
}
}
send_req_segwit_witness();
return;
}
void phase2_request_next_output(bool first) {
if (first) {
if (serialize) {
idx1 = 0;
send_req_5_output();
return;
}
} else if (idx1 < info.outputs_count - 1) {
idx1++;
send_req_5_output();
return;
}
// Output serialization is finished. Generate witnesses.
phase2_request_next_witness(true);
}
void phase2_request_next_input(bool first) {
if (first) {
idx1 = 0;
} else if (idx1 < info.inputs_count - 1) {
idx1++;
} else {
// Input processing is finished. Serialize outputs.
phase2_request_next_output(true);
return;
}
if (serialize || coin->force_bip143 || coin->overwintered) {
// We are processing all inputs.
if (idx1 == info.next_legacy_input) {
idx2 = 0;
send_req_4_input();
} else {
send_req_nonlegacy_input();
}
} else {
// We are only signing legacy inputs.
if (info.next_legacy_input == 0xffffffff || idx1 > info.next_legacy_input) {
// There are no legacy inputs or no more legacy inputs, so serialize
// outputs.
phase2_request_next_output(true);
} else {
// Sign next legacy input.
idx1 = info.next_legacy_input;
idx2 = 0;
send_req_4_input();
}
}
}
void phase2_request_orig_input(void) {
if (idx1 < orig_info.inputs_count) {
if (idx1 == 0) {
// Reset outer transaction check.
hasher_Reset(&hasher_check);
}
if (idx1 == orig_info.next_legacy_input) {
idx2 = 0;
send_req_3_orig_input();
} else {
send_req_3_orig_nonlegacy_input();
}
} else {
// Ensure that the original transaction inputs haven't changed for the outer
// transaction check.
uint8_t hash[32];
hasher_Final(&hasher_check, hash);
if (memcmp(hash, orig_info.hash_inputs_check, 32) != 0) {
fsm_sendFailure(FailureType_Failure_DataError,
_("Transaction has changed during signing"));
signing_abort();
return;
}
phase2_request_next_input(true);
}
}
static bool extract_input_multisig_fp(TxInfo *tx_info,
const TxInputType *txinput) {
if (txinput->has_multisig && !tx_info->multisig_fp_mismatch) {
uint8_t h[32] = {0};
if (cryptoMultisigFingerprint(&txinput->multisig, h) == 0) {
fsm_sendFailure(FailureType_Failure_ProcessError,
_("Error computing multisig fingerprint"));
signing_abort();
return false;
}
if (tx_info->multisig_fp_set) {
if (memcmp(tx_info->multisig_fp, h, 32) != 0) {
tx_info->multisig_fp_mismatch = true;
}
} else {
memcpy(tx_info->multisig_fp, h, 32);
tx_info->multisig_fp_set = true;
}
} else { // single signature
tx_info->multisig_fp_mismatch = true;
}
return true;
}
bool check_change_multisig_fp(const TxInfo *tx_info,
const TxOutputType *txoutput) {
uint8_t h[32] = {0};
return tx_info->multisig_fp_set && !tx_info->multisig_fp_mismatch &&
cryptoMultisigFingerprint(&(txoutput->multisig), h) &&
memcmp(tx_info->multisig_fp, h, 32) == 0;
}
static InputScriptType simple_script_type(InputScriptType script_type) {
// SPENDMULTISIG is used only for non-SegWit and is effectively the same as
// SPENDADDRESS. For SegWit inputs and outputs multisig is indicated by the
// presence of the multisig structure. for both SegWit and non-SegWit we can
// rely on multisig_fp to check the multisig structure.
if (script_type == InputScriptType_SPENDMULTISIG) {
script_type = InputScriptType_SPENDADDRESS;
}
return script_type;
}