forked from LedgerHQ/app-nervos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apdu_sign.c
1302 lines (1145 loc) · 57.4 KB
/
apdu_sign.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
#include "apdu_sign.h"
#include "apdu.h"
#include "globals.h"
#include "key_macros.h"
#include "keys.h"
#include "memory.h"
#include "to_string.h"
#include "protocol.h"
#include "ui.h"
#define MOL_PIC(x) ((typeof(x)) PIC(x))
#define MOL_PIC_STRUCT(t,x) (x?((t*) PIC(x)):NULL)
#define mol_printf(...) PRINTF(__VA_ARGS__)
#define mol_emerg_reject THROW(EXC_MEMORY_ERROR)
#include "cx.h"
#include "annotated.h"
#include <string.h>
#define G global.apdu.u.sign
#define PARSE_ERROR() THROW(EXC_PARSE_ERROR)
static inline void conditional_init_hash_state(blake2b_hash_state_t *const state) {
check_null(state);
if (!state->initialized) {
CX_THROW(cx_blake2b_init2_no_throw(&state->state, SIGN_HASH_SIZE * 8, NULL, 0, (uint8_t *)blake2b_personalization,
sizeof(blake2b_personalization) - 1));
state->initialized = true;
}
}
static void blake2b_incremental_hash(
/*in*/ const uint8_t *const out, size_t const out_size,
/*in/out*/ blake2b_hash_state_t *const state) {
check_null(out);
check_null(state);
conditional_init_hash_state(state);
CX_THROW(cx_hash_no_throw((cx_hash_t *)&state->state, 0, out, out_size, NULL, 0));
}
static void blake2b_finish_hash(
/*out*/ uint8_t *const out, size_t const out_size,
/*in/out*/ blake2b_hash_state_t *const state) {
check_null(out);
check_null(state);
conditional_init_hash_state(state);
CX_THROW(cx_hash_no_throw((cx_hash_t *)&state->state, CX_LAST, NULL, 0, out, out_size));
}
static int perform_signature(bool const on_hash, bool const send_hash);
static inline void clear_data(void) {
memset(&G, 0, sizeof(G));
}
static bool sign_without_hash_ok(void) {
delayed_send(perform_signature(true, false));
return true;
}
static bool sign_with_hash_ok(void) {
delayed_send(perform_signature(true, true));
return true;
}
static bool sign_reject(void) {
clear_data();
delay_reject();
return true; // Return to idle
}
static void multi_output_prompts_cb(size_t which) {
switch(which) {
case 0:
{
static const char prompt[]="Confirm";
static const char value[]="Transaction";
memcpy(global.ui.prompt.active_prompt, (const void*)PIC(prompt), sizeof(prompt));
memcpy(global.ui.prompt.active_value, (const void*)PIC(value), sizeof(value));
}
break;
case 1:
{
static const char prompt[]="Amount";
memcpy(global.ui.prompt.active_prompt, (const void*)PIC(prompt), sizeof(prompt));
frac_ckb_to_string_indirect(global.ui.prompt.active_value, sizeof(global.ui.prompt.active_value), &G.maybe_transaction.v.amount.snd);
}
break;
case 2:
{
static const char prompt[]="Fee";
memcpy(global.ui.prompt.active_prompt, (const void*)PIC(prompt), sizeof(prompt));
frac_ckb_to_string_indirect(global.ui.prompt.active_value, sizeof(global.ui.prompt.active_value), &G.maybe_transaction.v.total_fee);
}
break;
default:
{
if(sizeof(global.ui.prompt.active_prompt)<13) THROW(EXC_WRONG_LENGTH);
if(sizeof(global.ui.prompt.active_value)<29) THROW(EXC_WRONG_LENGTH);
static const char prompt[]="Output ";
memcpy(global.ui.prompt.active_prompt, (const void*)PIC(prompt), sizeof(prompt));
size_t prompt_fill=sizeof(prompt)-1;
if(which<100) prompt_fill+=number_to_string(global.ui.prompt.active_prompt+prompt_fill, which-2);
if(G.u.tx.output_count<100) {
global.ui.prompt.active_prompt[prompt_fill++]='/';
number_to_string(global.ui.prompt.active_prompt+prompt_fill, G.u.tx.output_count);
}
frac_ckb_to_string_indirect(global.ui.prompt.active_value, sizeof(global.ui.prompt.active_value), &G.u.tx.outputs[which-3].capacity);
// Maximum of 20
size_t value_fill=strnlen(global.ui.prompt.active_value, sizeof(global.ui.prompt.active_value));
static const char separator[]=" CKB -> ";
memcpy(global.ui.prompt.active_value+value_fill, separator, sizeof(separator));
// Maximum of 28
value_fill+=sizeof(separator)-1;
void (*lock_arg_to_destination_address)(char *const, size_t const, lock_arg_t const *const) = G.u.tx.outputs[which-3].is_multisig ? lock_arg_to_multisig_address : lock_arg_to_sighash_address;
lock_arg_to_destination_address(global.ui.prompt.active_value+value_fill, sizeof(global.ui.prompt.active_value), &G.u.tx.outputs[which-3].destination);
}
}
}
#define MAX_NUMBER_CHARS (MAX_INT_DIGITS + 2) // include decimal point and terminating null
static void sign_complete(uint8_t instruction) {
ui_callback_t const ok_c = instruction == INS_SIGN_WITH_HASH ? sign_with_hash_ok : sign_without_hash_ok;
void *lock_arg_to_destination_address_cb = G.u.tx.outputs[0].is_multisig ? lock_arg_to_multisig_address : lock_arg_to_sighash_address;
switch (G.maybe_transaction.v.tag) {
case OPERATION_TAG_PLAIN_TRANSFER: {
static const uint32_t TYPE_INDEX = 0;
static const uint32_t AMOUNT_INDEX = 1;
static const uint32_t FEE_INDEX = 2;
static const uint32_t DESTINATION_INDEX = 3;
static const uint32_t CONTRACT_INDEX = 4;
if (N_data.contract_data_type == ALLOW_CONTRACT_DATA) {
static const char *const transaction_prompts[] = {PROMPT("Confirm"), PROMPT("Amount"), PROMPT("Fee"),
PROMPT("Destination"), PROMPT("Contract"), NULL};
REGISTER_STATIC_UI_VALUE(TYPE_INDEX, "Transaction");
//register_ui_callback(SOURCE_INDEX, lock_arg_to_address, &G.maybe_transaction.v.source);
register_ui_callback(AMOUNT_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.amount.snd);
register_ui_callback(FEE_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.total_fee);
register_ui_callback(DESTINATION_INDEX, lock_arg_to_destination_address_cb, &G.u.tx.outputs[0].destination);
register_ui_callback(CONTRACT_INDEX, contract_type_to_string_indirect, &G.maybe_transaction.v.contract_type);
ui_prompt(transaction_prompts, ok_c, sign_reject);
} else {
static const char *const transaction_prompts[] = {PROMPT("Confirm"), PROMPT("Amount"), PROMPT("Fee"),
PROMPT("Destination"), NULL};
REGISTER_STATIC_UI_VALUE(TYPE_INDEX, "Transaction");
//register_ui_callback(SOURCE_INDEX, lock_arg_to_address, &G.maybe_transaction.v.source);
register_ui_callback(AMOUNT_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.amount.snd);
register_ui_callback(FEE_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.total_fee);
register_ui_callback(DESTINATION_INDEX, lock_arg_to_destination_address_cb, &G.u.tx.outputs[0].destination);
ui_prompt(transaction_prompts, ok_c, sign_reject);
}
} break;
case OPERATION_TAG_MULTI_OUTPUT_TRANSFER: {
ui_prompt_with_cb(&multi_output_prompts_cb, 3 + G.u.tx.output_count, ok_c, sign_reject);
} break;
case OPERATION_TAG_SELF_TRANSFER: {
static const uint32_t TYPE_INDEX = 0;
static const uint32_t AMOUNT_INDEX = 1;
static const uint32_t FEE_INDEX = 2;
static const uint32_t DESTINATION_INDEX = 3;
static const char *const transaction_prompts[] = {PROMPT("Confirm"), PROMPT("Amount"), PROMPT("Fee"),
PROMPT("Destination"), NULL};
REGISTER_STATIC_UI_VALUE(TYPE_INDEX, "Self-Transfer");
register_ui_callback(AMOUNT_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.amount.snd);
register_ui_callback(FEE_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.total_fee);
register_ui_callback(DESTINATION_INDEX, lock_arg_to_destination_address_cb, &G.u.tx.outputs[0].destination);
ui_prompt(transaction_prompts, ok_c, sign_reject);
} break;
case OPERATION_TAG_MULTI_INPUT_TRANSFER: {
static const uint32_t TYPE_INDEX = 0;
static const uint32_t INPUT_COUNT_INDEX = 1;
static const uint32_t SOURCE_INDEX = 2;
static const uint32_t AMOUNT_INDEX = 3;
static const uint32_t FEE_INDEX = 4;
static const uint32_t DESTINATION_INDEX = 5;
static const char *const transaction_prompts[] = {PROMPT("Confirm"), PROMPT("Input"), PROMPT("Source"),
PROMPT("Amount"), PROMPT("Fee"),
PROMPT("Destination"), NULL};
REGISTER_STATIC_UI_VALUE(TYPE_INDEX, "Multi-Input Transaction");
register_ui_callback(INPUT_COUNT_INDEX, uint64_tuple_to_string, &G.maybe_transaction.v.input_count);
register_ui_callback(SOURCE_INDEX, lock_arg_to_sighash_address, &G.current_lock_arg);
register_ui_callback(AMOUNT_INDEX, frac_ckb_tuple_to_string_indirect, &G.maybe_transaction.v.amount);
register_ui_callback(FEE_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.total_fee);
register_ui_callback(DESTINATION_INDEX, lock_arg_to_destination_address_cb, &G.u.tx.outputs[0].destination);
ui_prompt(transaction_prompts, ok_c, sign_reject);
} break;
case OPERATION_TAG_DAO_DEPOSIT: {
static const uint32_t TYPE_INDEX = 0;
static const uint32_t AMOUNT_INDEX = 1;
static const uint32_t FEE_INDEX = 2;
static const uint32_t OWNER_INDEX = 3;
static const char *const transaction_prompts[] = {PROMPT("Confirm DAO"), PROMPT("Deposit Amount"), PROMPT("Fee"), PROMPT("Cell Owner"),
NULL};
REGISTER_STATIC_UI_VALUE(TYPE_INDEX, "Deposit");
// register_ui_callback(SOURCE_INDEX, lock_arg_to_address, &G.maybe_transaction.v.source);
register_ui_callback(AMOUNT_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.dao_amount);
register_ui_callback(FEE_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.total_fee);
register_ui_callback(OWNER_INDEX, lock_arg_to_sighash_address, &G.dao_cell_owner);
ui_prompt(transaction_prompts, ok_c, sign_reject);
} break;
case OPERATION_TAG_DAO_PREPARE: {
static const uint32_t TYPE_INDEX = 0;
static const uint32_t AMOUNT_INDEX = 1;
static const uint32_t FEE_INDEX = 2;
static const uint32_t OWNER_INDEX = 3;
static const char *const prepare_prompts_full[] = {
PROMPT("Confirm DAO"),
PROMPT("Deposit Amount"),
PROMPT("Fee"),
PROMPT("Cell Owner"),
NULL };
REGISTER_STATIC_UI_VALUE(TYPE_INDEX, "Prepare");
register_ui_callback(AMOUNT_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.dao_amount);
register_ui_callback(FEE_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.total_fee);
register_ui_callback(OWNER_INDEX, lock_arg_to_sighash_address, &G.dao_cell_owner);
ui_prompt(prepare_prompts_full,
ok_c, sign_reject);
break;
}
case OPERATION_TAG_DAO_WITHDRAW: {
static const uint32_t TYPE_INDEX = 0;
static const uint32_t AMOUNT_INDEX = 1;
static const uint32_t COMPENSATION_INDEX = 2;
static const uint32_t OWNER_INDEX = 3;
static const char *const transaction_prompts[] = {PROMPT("Confirm DAO"),
PROMPT("Deposit Amount"),
PROMPT("Compensation"),
PROMPT("Cell Owner"),
NULL};
REGISTER_STATIC_UI_VALUE(TYPE_INDEX, "Withdrawal");
register_ui_callback(AMOUNT_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.dao_amount);
register_ui_callback(COMPENSATION_INDEX, frac_ckb_to_string_indirect, &G.maybe_transaction.v.total_fee);
register_ui_callback(OWNER_INDEX, lock_arg_to_sighash_address, &G.dao_cell_owner);
ui_prompt(transaction_prompts, ok_c, sign_reject);
} break;
default:
THROW(EXC_REJECT);
}
}
/***********************************************************/
#define REJECT_RETURN(ret_val, msg, ...) \
do { \
PRINTF("Rejecting: " msg "\n", ##__VA_ARGS__); \
G.maybe_transaction.unsafe = true; \
return ret_val; \
} while(false)
#define REJECT(msg, ...) REJECT_RETURN((void)0, msg, ##__VA_ARGS__)
#define REJECT_HARD_RETURN(ret_val, msg, ...) \
do { \
PRINTF("Can't sign: " msg "\n", ##__VA_ARGS__); \
G.maybe_transaction.hard_reject = true; \
return ret_val; \
} while(false)
#define REJECT_HARD(msg, ...) REJECT_HARD_RETURN((void)0, msg, ##__VA_ARGS__)
void prep_lock_arg(bip32_path_t *key, standard_lock_arg_t *destination) {
cx_ecfp_public_key_t public_key;
generate_public_key(&public_key, key);
generate_lock_arg_for_pubkey(&public_key, destination);
}
/* Start of parser callbacks */
void blake2b_chunk(uint8_t* buf, mol_num_t len) {
blake2b_incremental_hash(buf, len, &G.hash_state);
}
void inputs_start() {
explicit_bzero((void*)&G.u.inp.last_input_lock_arg, sizeof(G.u.inp.last_input_lock_arg));
}
void input_start() {
explicit_bzero(&G.cell_state, sizeof(G.cell_state));
explicit_bzero((void*) &G.lock_arg_tmp, sizeof(G.lock_arg_tmp));
explicit_bzero((void*)&G.u.inp.input_state, sizeof(G.u.inp.input_state));
}
void input_save_index(uint8_t *index, mol_num_t index_length) {
(void) index_length; // guaranteed by parser
memcpy(&G.u.inp.input_state.index, index, sizeof(G.u.inp.input_state.index));
}
void context_blake2b_chunk(uint8_t *chunk, mol_num_t length) {
blake2b_incremental_hash(chunk, length, &G.u.inp.input_state.hash_state);
}
void finish_context_txn(void) {
uint8_t tx_hash[32];
blake2b_finish_hash(tx_hash, 32, &G.u.inp.input_state.hash_state);
blake2b_chunk(tx_hash, 32);
blake2b_chunk((uint8_t *) &G.u.inp.input_state.index, sizeof(G.u.inp.input_state.index));
explicit_bzero(&G.u.inp.input_state, sizeof(G.u.inp.input_state));
}
void finish_inputs(void) {
explicit_bzero(&G.u, sizeof(G.u));
}
void input_context_start_idx(mol_num_t idx) {
// Enable/disable the remaining input callbacks based on whether we're on that output.
G.cell_state.active = idx == G.u.inp.input_state.index;
}
void cell_capacity(uint8_t* capacity, mol_num_t len) {
(void)len; // constant from the parser
if(!G.cell_state.active) return;
G.cell_state.capacity = *(uint64_t*) capacity;
}
const uint8_t defaultLockScript[] = {0x9b, 0xd7, 0xe0, 0x6f, 0x3e, 0xcf, 0x4b, 0xe0, 0xf2, 0xfc, 0xd2,
0x18, 0x8b, 0x23, 0xf1, 0xb9, 0xfc, 0xc8, 0x8e, 0x5d, 0x4b, 0x65,
0xa8, 0x63, 0x7b, 0x17, 0x72, 0x3b, 0xbd, 0xa3, 0xcc, 0xe8};
const uint8_t multisigLockScript[] = { 0x5c, 0x50, 0x69, 0xeb, 0x08, 0x57, 0xef, 0xc6, 0x5e, 0x1b, 0xca,
0x0c, 0x07, 0xdf, 0x34, 0xc3, 0x16, 0x63, 0xb3, 0x62, 0x2f, 0xd3,
0x87, 0x6c, 0x87, 0x63, 0x20, 0xfc, 0x96, 0x34, 0xe2, 0xa8 };
const uint8_t dao_type_script_hash[] = {0x82, 0xd7, 0x6d, 0x1b, 0x75, 0xfe, 0x2f, 0xd9, 0xa2, 0x7d, 0xfb,
0xaa, 0x65, 0xa0, 0x39, 0x22, 0x1a, 0x38, 0x0d, 0x76, 0xc9, 0x26,
0xf3, 0x78, 0xd3, 0xf8, 0x1c, 0xf3, 0xe7, 0xe1, 0x3f, 0x2e};
void cell_lock_code_hash(uint8_t* buf, mol_num_t len) {
(void)len;
if(!G.cell_state.active) return;
if(!memcmp(buf, defaultLockScript, 32)) {
G.cell_state.is_multisig = false;
} else if (!memcmp(buf, multisigLockScript, 32)) {
G.cell_state.is_multisig = true;
} else if (N_data.contract_data_type == DISALLOW_CONTRACT_DATA) {
REJECT("The lock script is unsupported");
}
}
void cell_script_hash_type(uint8_t hash_type) {
if(!G.cell_state.active) return;
if (hash_type != 1 && N_data.contract_data_type == DISALLOW_CONTRACT_DATA)
REJECT("Incorrect hash type for standard lock or dao script");
}
void script_arg_start_input() {
if(!G.cell_state.active) return;
G.cell_state.lock_arg_index = 0;
G.cell_state.lock_arg_nonequal = 0;
// current_lock_arg is the one we are signing with
G.lock_arg_cmp = G.current_lock_arg;
}
void script_arg_chunk(uint8_t* buf, mol_num_t buflen) {
if(!G.cell_state.active) return;
uint32_t current_offset = G.cell_state.lock_arg_index;
if(G.cell_state.lock_arg_index+buflen > 28) { // Unknown arg
G.cell_state.lock_arg_nonequal |= true;
return;
}
memcpy(((uint8_t*) &G.lock_arg_tmp) + current_offset, buf, buflen);
G.cell_state.lock_arg_index+=buflen;
if(!G.lock_arg_cmp) {
G.cell_state.lock_arg_nonequal=true;
return;
}
for(mol_num_t i=0;i<buflen;i++) {
G.cell_state.lock_arg_nonequal |= (G.lock_arg_cmp[current_offset+i] != buf[i]);
if(G.cell_state.lock_arg_nonequal) return;
}
}
void input_lock_arg_end() {
if(!G.cell_state.active) return;
if (memcmp(&G.u.inp.last_input_lock_arg, &G.lock_arg_tmp.hash, sizeof(G.u.inp.last_input_lock_arg))) {
G.distinct_input_sources += 1;
if (G.cell_state.lock_arg_nonequal == 0) {
// We are signing this input
// Store the 'index' of this input wrt all other inputs
// The 'index' starts from 1
if (G.maybe_transaction.v.input_count.fst != 0)
REJECT("Input cells in AnnotatedTransaction are not in expected order");
G.maybe_transaction.v.input_count.fst = G.distinct_input_sources;
}
}
memcpy(&G.u.inp.last_input_lock_arg, &G.lock_arg_tmp.hash, sizeof(G.u.inp.last_input_lock_arg));
}
void cell_type_code_hash(uint8_t* buf, mol_num_t len) {
if(!G.cell_state.active) return;
(void) len; // Guaranteed to be 32
// If this exists, we require it to be the DAO for now. Verify.
if(!memcmp(buf, dao_type_script_hash, sizeof(dao_type_script_hash)))
G.cell_state.is_dao = true;
else if(N_data.contract_data_type == DISALLOW_CONTRACT_DATA)
REJECT("Only the DAO type script is supported with contract data by default; allow contract data in settings to sign this");
}
bool cell_type_arg_length(mol_num_t length) {
if(!G.cell_state.active) return true;
// DAO is empty.
if(length != 4 && G.cell_state.is_dao)
REJECT_RETURN(true, "DAO cell has nonempty args");
if(length != 4 && N_data.contract_data_type == DISALLOW_CONTRACT_DATA)
REJECT_RETURN(true, "Cannot handle cell arguments");
return true;
}
bool set_cell_data_size(mol_num_t size) {
if (!G.cell_state.active) true;
if (size < 4)
REJECT_HARD_RETURN(false, "Can't sign: Size too small for expected length prefix.\n");
G.cell_state.data_size = MIN(15, size - 4); // size includes the 4-byte size header in Bytes
return true;
}
void check_cell_data_data_chunk(uint8_t *buf, mol_num_t length) {
if(!G.cell_state.active) return;
for(mol_num_t i=0;i<length;i++)
G.cell_state.dao_data_is_nonzero |= buf[i];
}
void finish_input_cell_data() {
if(!G.cell_state.active) return;
if(G.cell_state.is_dao) {
memcpy(&G.dao_cell_owner, &G.lock_arg_tmp.hash, sizeof(G.lock_arg_tmp.hash));
if(G.cell_state.data_size != 8) REJECT("DAO data must be 8 bytes");
G.dao_input_amount += G.cell_state.capacity;
if(G.cell_state.dao_data_is_nonzero) {
if(G.maybe_transaction.v.tag != OPERATION_TAG_DAO_WITHDRAW && G.maybe_transaction.v.tag != 0) REJECT("Can't mix deposit, prepare, and withdraw in one transaction");
G.maybe_transaction.v.tag = OPERATION_TAG_DAO_WITHDRAW;
} else {
if(G.maybe_transaction.v.tag != OPERATION_TAG_DAO_PREPARE && G.maybe_transaction.v.tag != 0) REJECT("Can't mix deposit, prepare, and withdraw in one transaction");
G.maybe_transaction.v.tag = OPERATION_TAG_DAO_PREPARE;
}
} else {
if(G.cell_state.data_size != 0 && N_data.contract_data_type == DISALLOW_CONTRACT_DATA) {
REJECT("Data found in non-dao cell; allow contract data in settings to sign this");
}
if (G.cell_state.data_size > 0) // TODO: parse contract data here
G.maybe_transaction.v.contract_type = CONTRACT_UNKNOWN;
// total input amount
G.input_amount.snd += G.cell_state.capacity;
if(!G.cell_state.lock_arg_nonequal) {
// amount we are signing
G.input_amount.fst += G.cell_state.capacity;
}
G.signing_multisig_input |= G.cell_state.is_multisig;
}
}
const struct byte_callbacks hash_type_cb = { cell_script_hash_type };
// Process one input, provided as an AnnotatedCellInput.
const AnnotatedCellInput_cb annotatedCellInput_callbacks = {
.start = input_start,
.input = &(CellInput_cb) {
.since = &(Uint64_cb) { { blake2b_chunk } },
.previous_output = &(OutPoint_cb) {
.index = &(Uint32_cb) { { input_save_index } }
}
},
.source = &(RawTransaction_cb) {
.chunk = context_blake2b_chunk,
.outputs = &(CellOutputVec_cb) {
.index = input_context_start_idx,
.item = &(CellOutput_cb) {
.capacity = &(Uint64_cb) { { cell_capacity } },
.lock = &(Script_cb) {
.code_hash = &(Byte32_cb) { { cell_lock_code_hash } },
.hash_type = &hash_type_cb,
.args = &(Bytes_cb) { .start = script_arg_start_input, .body_chunk = script_arg_chunk },
.end = input_lock_arg_end
},
.type_ = &(ScriptOpt_cb) { .item = &(Script_cb) {
.code_hash = &(Byte32_cb) { { cell_type_code_hash } },
.hash_type = &hash_type_cb,
.args = &(Bytes_cb) { .size = cell_type_arg_length }
} }
}
},
.outputs_data = &(BytesVec_cb) {
.index = input_context_start_idx,
.item = &(Bytes_cb) { .size = set_cell_data_size, .body_chunk = check_cell_data_data_chunk, .end = finish_input_cell_data }
},
.end = finish_context_txn,
}
};
// Add the number of inputs to the raw transaction hash; used at the start of the inputs. This is the header for the implicit FixVec<CellInput> we are writing into the hash.
void blake2b_input_count(mol_num_t length) {
if(length != G.input_count) REJECT_HARD("Number of input cells reported in AnnotatedTransaction does not match the actual number of input cells");
blake2b_incremental_hash((uint8_t*) &G.input_count, 4, &G.hash_state);
}
void computeNewOffsetsToHash(struct AnnotatedRawTransaction_state *s) {
mol_num_t to_subtract = s->outputs_offset - s->inputs_offset - ( 44 * G.input_count + 4);
mol_num_t scratch;
scratch=s->total_size - to_subtract;
blake2b_incremental_hash((uint8_t*) &scratch, 4, &G.hash_state);
blake2b_incremental_hash((uint8_t*) &s->version_offset, 4, &G.hash_state);
blake2b_incremental_hash((uint8_t*) &s->cell_deps_offset, 4, &G.hash_state);
blake2b_incremental_hash((uint8_t*) &s->header_deps_offset, 4, &G.hash_state);
blake2b_incremental_hash((uint8_t*) &s->inputs_offset, 4, &G.hash_state);
scratch=s->outputs_offset - to_subtract;
blake2b_incremental_hash((uint8_t*) &scratch, 4, &G.hash_state);
scratch=s->outputs_data_offset - to_subtract;
blake2b_incremental_hash((uint8_t*) &scratch, 4, &G.hash_state);
}
void output_start(mol_num_t index) {
G.u.tx.current_output_index=index;
explicit_bzero((void*) &G.cell_state, sizeof(G.cell_state));
explicit_bzero((void*) &G.lock_arg_tmp, sizeof(G.lock_arg_tmp));
G.cell_state.active = true;
G.lock_arg_cmp=G.change_lock_arg;
}
// Called per item (tx output in this case)
void output_end(void) {
if(G.cell_state.is_dao) {
memcpy(&G.dao_cell_owner, &G.lock_arg_tmp.hash, sizeof(G.lock_arg_tmp.hash));
G.u.tx.dao_output_amount += G.cell_state.capacity;
G.u.tx.dao_bitmask |= 1<<G.u.tx.current_output_index;
if(G.cell_state.lock_arg_nonequal || G.cell_state.is_multisig)
REJECT("Not allowing DAO outputs to be sent to a non-self address");
G.maybe_transaction.v.flags |= HAS_CHANGE_ADDRESS;
} else {
// if the output lock arg doesn't match the change bip-32 path
if(G.cell_state.lock_arg_nonequal || G.cell_state.is_multisig) {
if (!(G.maybe_transaction.v.flags & HAS_DESTINATION_ADDRESS) ) {
if (G.u.tx.output_count != 0) {
// Should be 0 if we haven't seent address yet
THROW(EXC_MEMORY_ERROR);
}
G.u.tx.outputs[0].is_multisig = G.cell_state.is_multisig;
memcpy(&G.u.tx.outputs[0].destination, &G.lock_arg_tmp, sizeof(lock_arg_t));
G.u.tx.output_count++; // we found the first output
} else if(memcmp(G.u.tx.outputs[G.u.tx.output_count-1].destination.hash, G.lock_arg_tmp.hash, 20)
|| G.u.tx.outputs[G.u.tx.output_count-1].is_multisig != G.cell_state.is_multisig) {
// Not the same as last output, so cannot coalesce and need to
// make new prompt / cell in our output array.
if(G.maybe_transaction.v.tag != OPERATION_TAG_NOT_SET
&& G.maybe_transaction.v.tag != OPERATION_TAG_MULTI_OUTPUT_TRANSFER)
REJECT("Can't handle mixed transaction types with multiple non-change destination addresses. Tag: %d", G.maybe_transaction.v.tag);
G.maybe_transaction.v.tag = OPERATION_TAG_MULTI_OUTPUT_TRANSFER;
if(G.u.tx.output_count>=MAX_OUTPUTS) REJECT("Can't handle more than five outputs");
G.u.tx.outputs[G.u.tx.output_count].is_multisig = G.cell_state.is_multisig;
memcpy(&G.u.tx.outputs[G.u.tx.output_count].destination, &G.lock_arg_tmp, sizeof(lock_arg_t));
G.u.tx.output_count++;
} else {
// Same address as last output, can reuse promopt and so do
// nothing here.
}
// We have either the old output array cell, because we can and did
// coalesce and the address is the same, or a new cell, because it
// wasn't.
G.u.tx.plain_output_amount += G.cell_state.capacity;
G.u.tx.outputs[G.u.tx.output_count - 1].capacity+=G.cell_state.capacity;
G.maybe_transaction.v.flags |= HAS_DESTINATION_ADDRESS;
} else {
G.u.tx.change_amount += G.cell_state.capacity;
G.maybe_transaction.v.flags |= HAS_CHANGE_ADDRESS;
}
}
}
// Called after all transaction outputs
void outputs_end(void) {
// Don't do any self transfer stuff if dao
if (G.u.tx.dao_bitmask
|| G.maybe_transaction.v.tag == OPERATION_TAG_DAO_PREPARE
|| G.maybe_transaction.v.tag == OPERATION_TAG_DAO_WITHDRAW)
return;
G.u.tx.is_self_transfer =
!(G.maybe_transaction.v.flags & HAS_DESTINATION_ADDRESS)
&& (G.maybe_transaction.v.flags & HAS_CHANGE_ADDRESS);
if(G.u.tx.is_self_transfer) {
if (G.u.tx.plain_output_amount != 0) {
// If all outputs are change, then the output amount should be 0
THROW(EXC_WRONG_PARAM);
}
if (G.u.tx.output_count != 0) {
// Should be 0 if we haven't seent address yet
THROW(EXC_MEMORY_ERROR);
}
// Swap output and change, so output is change and change is 0
G.u.tx.plain_output_amount = G.u.tx.change_amount;
G.u.tx.change_amount = 0;
// Swap flags likewise
G.maybe_transaction.v.flags |= HAS_DESTINATION_ADDRESS;
G.maybe_transaction.v.flags &= !HAS_CHANGE_ADDRESS;
// Set single output prompt for the then-change-now-output
G.u.tx.output_count = 1;
memcpy(G.u.tx.outputs[G.u.tx.output_count - 1].destination.hash, G.change_lock_arg, 20);
}
}
void validate_output_data_start(mol_num_t idx) {
typeof(G.u.tx.dao_bitmask) bit =
((typeof(G.u.tx.dao_bitmask))1) << idx;
G.cell_state.is_dao = (G.u.tx.dao_bitmask & bit) != 0;
}
void finish_output_cell_data(void) {
if(G.cell_state.is_dao) {
if(G.cell_state.data_size != 8) REJECT("DAO data must be 8 bytes");
if(G.cell_state.dao_data_is_nonzero) {
if(G.maybe_transaction.v.tag != OPERATION_TAG_DAO_PREPARE && G.maybe_transaction.v.tag != 0) REJECT("Can't mix deposit, prepare, and withdraw in one transaction");
G.maybe_transaction.v.tag = OPERATION_TAG_DAO_PREPARE;
} else {
PRINTF("%d\n", G.maybe_transaction.v.tag);
if(G.maybe_transaction.v.tag != OPERATION_TAG_DAO_DEPOSIT && G.maybe_transaction.v.tag != 0) REJECT("Can't mix deposit, prepare, and withdraw in one transaction");
G.maybe_transaction.v.tag = OPERATION_TAG_DAO_DEPOSIT;
}
} else {
if (G.cell_state.data_size != 0 && N_data.contract_data_type == DISALLOW_CONTRACT_DATA)
REJECT("Data found in non-dao cell; allow contract data in settings to sign this");
if (G.cell_state.data_size > 0) // TODO: parse contract data here
G.maybe_transaction.v.contract_type = CONTRACT_UNKNOWN;
}
}
void finalize_raw_transaction(void) {
switch(G.maybe_transaction.v.tag) {
case OPERATION_TAG_NONE:
break;
case OPERATION_TAG_MULTI_INPUT_TRANSFER:
REJECT("This is a tag just for rendering, and should just be set below");
case OPERATION_TAG_NOT_SET:
case OPERATION_TAG_PLAIN_TRANSFER:
if (G.distinct_input_sources > 1) {
if (G.signing_multisig_input)
REJECT("Signing multi-input transaction with multisig input is not supported");
G.maybe_transaction.v.tag = OPERATION_TAG_MULTI_INPUT_TRANSFER;
// The input 'index' we are signing should have been set to non-zero value
if (G.maybe_transaction.v.input_count.fst == 0)
REJECT("Internal error in handling multi-input transaction");
G.maybe_transaction.v.input_count.snd = G.distinct_input_sources;
// Display the complete input amount we are signing, without deducting change
G.maybe_transaction.v.amount.fst = G.input_amount.fst;
} else {
G.maybe_transaction.v.tag = G.u.tx.is_self_transfer ?
OPERATION_TAG_SELF_TRANSFER : OPERATION_TAG_PLAIN_TRANSFER;
}
// N.B. In plain_output_amount, the change was never summed (unless
// self-transfer, where there is no change in the end).
G.maybe_transaction.v.amount.snd = G.u.tx.plain_output_amount;
break;
// Shouldn't actually hit this case because of the handling of TAG_NOT_SET above
case OPERATION_TAG_SELF_TRANSFER:
G.maybe_transaction.v.amount.snd = G.u.tx.plain_output_amount;
break;
case OPERATION_TAG_MULTI_OUTPUT_TRANSFER:
if(G.distinct_input_sources > 1) REJECT("Multi-input multi-output transactions are not supported");
G.maybe_transaction.v.amount.snd = G.u.tx.plain_output_amount;
break;
case OPERATION_TAG_DAO_DEPOSIT:
G.maybe_transaction.v.dao_amount = G.u.tx.dao_output_amount;
break;
case OPERATION_TAG_DAO_PREPARE:
G.maybe_transaction.v.dao_amount = G.u.tx.dao_output_amount;
if(G.u.tx.dao_output_amount != G.dao_input_amount) REJECT("DAO input and output amounts do not match for prepare operation"); // Not a complete check; full DAO requirement is that _each cell_ match exactly. Just providing some fail-fast here.
break;
case OPERATION_TAG_DAO_WITHDRAW:
G.maybe_transaction.v.dao_amount = G.dao_input_amount;
if(G.u.tx.dao_output_amount != 0) REJECT("Can't mix DAO withdraw and other DAO operations");
if(G.u.tx.plain_output_amount != 0) REJECT("DAO withdrawals cannot be sent directly to another account");
break;
}
G.maybe_transaction.v.total_fee = (G.input_amount.snd + G.dao_input_amount) - (G.u.tx.plain_output_amount + G.u.tx.dao_output_amount + G.u.tx.change_amount);
if(G.maybe_transaction.v.tag == OPERATION_TAG_DAO_WITHDRAW) {
// Can't compute fee without a bunch more info, calculating return instead and putting that in this slot so the user can get equivalent info.
G.maybe_transaction.v.total_fee = -G.maybe_transaction.v.total_fee;
}
blake2b_finish_hash(G.u.tx.transaction_hash, sizeof(G.u.tx.transaction_hash), &G.hash_state);
}
// Process a whole transaction to sign.
const struct AnnotatedRawTransaction_callbacks AnnotatedRawTransaction_callbacks = {
.offsets = computeNewOffsetsToHash,
.version = &(Uint32_cb) { { blake2b_chunk } },
.cell_deps = &(CellDepVec_cb) { .chunk = blake2b_chunk },
.header_deps = &(Byte32Vec_cb) { .chunk = blake2b_chunk },
.inputs = &(AnnotatedCellInputVec_cb) {
.start = inputs_start,
.length = blake2b_input_count,
.item = &annotatedCellInput_callbacks,
.end = finish_inputs
},
.outputs = &(CellOutputVec_cb) {
.chunk = blake2b_chunk,
.index = output_start,
.item = &(CellOutput_cb) {
.capacity = &(Uint64_cb) { { cell_capacity } },
.lock = &(Script_cb) {
.code_hash = &(Byte32_cb) { { cell_lock_code_hash } },
.hash_type = &hash_type_cb,
.args = &(Bytes_cb) {
// don't need a `script_arg_start_output` callback here
// because output_start above handles it.
.body_chunk = script_arg_chunk
}
},
.type_ = &(ScriptOpt_cb) {
.item = &(Script_cb) {
.code_hash = &(Byte32_cb) { { cell_type_code_hash } },
.hash_type = &hash_type_cb,
.args = &(Bytes_cb) { .size = cell_type_arg_length }
}
},
.end = output_end
},
.end = outputs_end
},
.outputs_data = &(BytesVec_cb) {
.chunk = blake2b_chunk,
.index = validate_output_data_start,
.item = &(Bytes_cb) { .size = set_cell_data_size, .body_chunk = check_cell_data_data_chunk, .end = finish_output_cell_data }
},
.end = finalize_raw_transaction
};
bool init_bip32(mol_num_t size) {
if (size < 4)
REJECT_HARD_RETURN(false, "Can't sign: Size too small for expected length prefix.\n");
if (size - 4 > sizeof(G.u.temp_key.components))
REJECT_HARD_RETURN(false, "Can't sign: Too many components in bip32 path");
G.u.temp_key.length=0;
return true;
}
void bip32_component(uint8_t* buf, mol_num_t len) {
(void) len;
G.u.temp_key.components[G.u.temp_key.length++]=*(uint32_t*)buf;
}
void set_sign_path(void) {
bip32_path_t key;
memcpy(&key, &G.u.temp_key, sizeof(key));
prep_lock_arg(&key, &G.current_lock_arg);
memcpy(G.key_path_components, key.components + 2, sizeof(G.key_path_components));
G.key_length = key.length;
// Default the change lock arg to the one we're currently going to sign for
memcpy(&G.change_lock_arg, G.current_lock_arg, 20);
}
void set_change_path(void) {
prep_lock_arg(&G.u.temp_key, &G.change_lock_arg);
}
void witness_offsets(struct WitnessArgs_state *state) {
if (G.signing_multisig_input) {
// Assume the WitnessArgs are correct
mol_num_t header[4];
header[0] = state->total_size;
header[1] = state->lock_offset;
header[2] = state->input_type_offset;
header[3] = state->output_type_offset;
uint64_t len64 = header[0];
blake2b_incremental_hash((uint8_t*) &len64, sizeof(uint64_t), &G.hash_state);
blake2b_incremental_hash((uint8_t*) header, sizeof(header), &G.hash_state);
/* PRINTF("witness_multisig header %.*h\n", 16, header ); */
} else {
int lock_wit_len = state->input_type_offset-state->lock_offset;
int shift = 69-lock_wit_len;
mol_num_t new_header[4];
new_header[0] = state->total_size + shift;
new_header[1] = state->lock_offset;
new_header[2] = state->input_type_offset + shift;
new_header[3] = state->output_type_offset + shift;
uint64_t len64 = new_header[0];
blake2b_incremental_hash((uint8_t*) &len64, sizeof(uint64_t), &G.hash_state);
blake2b_incremental_hash((uint8_t*) new_header, sizeof(new_header), &G.hash_state);
static const uint8_t zero_witness[] = {
0x41, 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, 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};
blake2b_incremental_hash(zero_witness, sizeof(zero_witness), &G.hash_state);
}
}
bool witness_lock_arg_size(mol_num_t size) {
if (!G.signing_multisig_input) return true;
if (size < 4) {
REJECT_HARD_RETURN(false, "Can't sign: Size too small for expected length prefix.\n");
}
uint32_t size_adjusted = size - 4;
blake2b_incremental_hash((void*) &size_adjusted, sizeof(uint32_t), &G.hash_state);
return true;
}
// multisig_script | Signature1 | Signature2 | ...
//
// Where the components are of the following format:
//
// multisig_script: S | R | M | N | PubKeyHash1 | PubKeyHash2 | ...
//
// +-------------+------------------------------------+-------+
// | | Description | Bytes |
// +-------------+------------------------------------+-------+
// | S | reserved field, must be zero | 1 |
// | R | first nth public keys must match | 1 |
// | M | threshold | 1 |
// | N | total public keys | 1 |
// | PubkeyHashN | blake160 hash of compressed pubkey | 20 |
// | SignatureN | recoverable signature | 65 |
// +-------------+------------------------------------+-------+
void witness_lock_arg_body_chunk(uint8_t *buf, mol_num_t buflen) {
if (!G.signing_multisig_input) return;
mol_num_t consumed = G.u.tx.witness_multisig_lock_arg_consumed;
if (consumed == 0 && (buf[0] != 0))
REJECT("Reserved field of multisig_script is non-zero");
if (consumed < 3) {
mol_num_t threshold_index = 2 - consumed;
G.u.tx.witness_multisig_threshold = buf[threshold_index];
}
if (consumed < 4) {
mol_num_t pubkeys_cnt_index = 3 - consumed;
G.u.tx.witness_multisig_pubkeys_cnt = buf[pubkeys_cnt_index];
}
if (G.u.tx.witness_multisig_pubkeys_cnt > 0) {
size_t multisig_script_len = 4 /* FLAGS_SIZE */ + 20 /* BLAKE160_SIZE */ * G.u.tx.witness_multisig_pubkeys_cnt;
size_t signatures_start = multisig_script_len - consumed;
if (signatures_start > 0 && buflen > signatures_start) {
// Zero signatures
for(mol_num_t i = signatures_start; i < buflen; i++) {
buf[i] = 0;
}
}
}
/* PRINTF("witness threshold %d\n", G.u.tx.witness_multisig_threshold); */
/* PRINTF("witness pubkeys_cnt %d\n", G.u.tx.witness_multisig_pubkeys_cnt); */
/* PRINTF("witness_lock_arg_body_chunk %.*h\n", buflen, buf); */
blake2b_chunk(buf, buflen);
G.u.tx.witness_multisig_lock_arg_consumed += buflen;
}
const WitnessArgs_cb WitnessArgs_rewrite_callbacks = {
.offsets = witness_offsets,
.lock = &(BytesOpt_cb) { .item = &(Bytes_cb) {
.size = witness_lock_arg_size,
.body_chunk = witness_lock_arg_body_chunk
}},
.input_type = &(BytesOpt_cb) { .chunk = blake2b_chunk },
.output_type = &(BytesOpt_cb) { .chunk = blake2b_chunk }
};
void begin_witness(mol_num_t index) {
G.u.tx.is_first_witness = index == 0;
if(G.u.tx.is_first_witness) {
G.u.tx.witness_multisig_threshold = 0;
G.u.tx.witness_multisig_pubkeys_cnt = 0;
G.u.tx.witness_multisig_lock_arg_consumed = 0;
explicit_bzero(&G.hash_state, sizeof(G.hash_state));
blake2b_incremental_hash(G.u.tx.transaction_hash, SIGN_HASH_SIZE, &G.hash_state);
MolReader_WitnessArgs_init_state((struct WitnessArgs_state*)G.u.tx.witness_stack, &WitnessArgs_rewrite_callbacks);
}
}
bool hash_witness_length(mol_num_t size) {
if (size < 4) {
PRINTF("Can't sign: Size too small for expected length prefix.\n");
return false;
}
if (!(G.u.tx.is_first_witness)) {
uint64_t size_as_64 = size - 4;
blake2b_incremental_hash((void*) &size_as_64, sizeof(uint64_t), &G.hash_state);
}
return true;
}
void process_witness(uint8_t *buff, mol_num_t buff_size) {
if(G.u.tx.is_first_witness) { // First witness handling
struct mol_chunk chunk = { buff, buff_size, 0 };
mol_rv rv = MolReader_WitnessArgs_parse((struct WitnessArgs_state*)G.u.tx.witness_stack, &chunk, &WitnessArgs_rewrite_callbacks, MOL_NUM_MAX);
if(rv == COMPLETE) {
G.u.tx.first_witness_done=1;
}
} else {
blake2b_incremental_hash(buff, buff_size, &G.hash_state);
}
}
void process_witness_end() {
// If something went wrong parsing the first arg, just assume that it's the usual empty one.
if(G.u.tx.is_first_witness && G.u.tx.first_witness_done!=1) {
G.u.tx.first_witness_done=1;
explicit_bzero(&G.hash_state, sizeof(G.hash_state));
blake2b_incremental_hash(G.u.tx.transaction_hash, SIGN_HASH_SIZE, &G.hash_state);
static const uint8_t self_witness[] = {
0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Length of WitnessArg,
0x55, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x55, 0x00, // WitnessArg
0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x41, 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, 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};
blake2b_incremental_hash(self_witness, sizeof(self_witness), &G.hash_state);
}
}
void finalize_witnesses() {
blake2b_finish_hash(G.u.tx.final_hash, sizeof(G.u.tx.final_hash), &G.hash_state);
}
void set_input_count(uint8_t *buf, mol_num_t len) {
(void) len;
G.input_count=*(uint32_t*) buf;
}
const struct AnnotatedTransaction_callbacks annotatedTransaction_callbacks = {
.signPath = &(Bip32_cb) { .size = init_bip32, .item = &(Uint32_cb) { { bip32_component } }, .end = set_sign_path },
.changePath = &(Bip32_cb) { .size = init_bip32, .item = &(Uint32_cb) { { bip32_component } }, .end = set_change_path },
.inputCount = &(Uint32_cb) { { set_input_count } },
.raw = &AnnotatedRawTransaction_callbacks,
.witnesses = &(BytesVec_cb) {
.index = begin_witness,
.item = &(Bytes_cb) { .size = hash_witness_length, .body_chunk = process_witness, .end = process_witness_end },
.end = finalize_witnesses
}
};
#define P1_FIRST 0x00
#define P1_NEXT 0x01
#define P1_NO_FALLBACK 0x40
#define P1_LAST_MARKER 0x80
#define P1_MASK (~(P1_LAST_MARKER | P1_NO_FALLBACK))
static size_t handle_apdu(uint8_t const instruction) {
uint8_t *const buff = &G_io_apdu_buffer[OFFSET_CDATA];
uint8_t const p1 = READ_UNALIGNED_BIG_ENDIAN(uint8_t, &G_io_apdu_buffer[OFFSET_P1]);
uint8_t const buff_size = READ_UNALIGNED_BIG_ENDIAN(uint8_t, &G_io_apdu_buffer[OFFSET_LC]);
if (buff_size > MAX_APDU_SIZE)
THROW(EXC_WRONG_LENGTH_FOR_INS);
bool last = (p1 & P1_LAST_MARKER) != 0;
bool secure_only = (p1 & P1_NO_FALLBACK) != 0;
struct mol_chunk chunk = { buff, buff_size, 0 };
mol_rv rv;
switch (p1 & P1_MASK) {
case P1_FIRST:
clear_data();
PRINTF("Initializing parser\n");
MolReader_AnnotatedTransaction_init_state((struct AnnotatedTransaction_state*) &G.transaction_stack, &annotatedTransaction_callbacks);
PRINTF("Initialized parser\n");
__attribute__((fallthrough));
case P1_NEXT:
if(G.maybe_transaction.hard_reject) THROW(EXC_PARSE_ERROR);
PRINTF("Calling parser\n");
rv = MolReader_AnnotatedTransaction_parse((struct AnnotatedTransaction_state*) &G.transaction_stack, &chunk, &annotatedTransaction_callbacks, MOL_NUM_MAX);
if(last) {