-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_generator.py
More file actions
1976 lines (1720 loc) · 77.6 KB
/
Copy pathtest_generator.py
File metadata and controls
1976 lines (1720 loc) · 77.6 KB
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
#!/usr/bin/env python3
"""
BIP-375 Test Vector Generator
Configuration-driven system for generating test vectors with support for large PSBTs.
Organized by validation type → input/output type → complexity.
"""
import base64
from dataclasses import dataclass, field
from enum import Enum
import json
import hashlib
import os
from pathlib import Path
import struct
import sys
from typing import Dict, List, Optional, Any, Tuple
import yaml
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from test_framework.crypto.secp256k1 import GE, G
from test_framework.messages import COutPoint, CTransaction, CTxIn, CTxOut, hash256, uint256_from_str
from test_framework.script import hash160
from test_framework.script_util import (
key_to_p2pkh_script,
keys_to_multisig_script,
output_key_to_p2tr_script,
program_to_witness_script,
script_to_p2sh_script,
script_to_p2wsh_script,
)
import spdk_psbt
from spdk_psbt import (
add_raw_global_field,
add_raw_input_field,
add_raw_output_field,
remove_raw_input_fields_by_type,
SilentPaymentPsbt,
PsbtOutput
)
from generator_utils import (
PSBTKeyType,
PrivateKey,
PublicKey,
Wallet,
UTXO,
compute_bip352_output_script,
apply_label_to_spend_key,
sign_p2wpkh_input,
sign_p2pkh_input,
sign_p2tr_input,
verify_receiver_detects_outputs,
verify_no_empty_output_script_headers,
)
def _deterministic_hash(s: str) -> int:
"""Deterministic hash that is stable across Python sessions (unlike hash())."""
return int.from_bytes(hashlib.sha256(s.encode()).digest()[:4], "big") % 1000
NUMS_H = bytes.fromhex("50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0")
# ============================================================================
# Pure PSBT helper functions
# ============================================================================
def _create_psbt(num_inputs: int, num_outputs: int, *, tx_modifiable: bool = False) -> SilentPaymentPsbt:
"""Create a PSBT v2 with the given number of inputs/outputs.
Uses the Rust SilentPaymentPsbt.create() which sets standard global fields
(VERSION, TX_VERSION, INPUT_COUNT, OUTPUT_COUNT, TX_MODIFIABLE), then
overrides TX_MODIFIABLE to match the test scenario.
"""
psbt = SilentPaymentPsbt.create(num_inputs, num_outputs)
psbt.set_tx_modifiable(0x01 if tx_modifiable else 0x00)
return psbt
def _sorted_outpoints_and_input_map(
all_inputs: List[Dict],
eligible_inputs: List[Dict],
) -> tuple:
"""Sort outpoints lexicographically and build eligible input index map.
Outpoints are from ALL inputs (BIP-352: outpoint_L is the smallest
outpoint in the transaction). The index map only contains eligible
inputs for pubkey/ECDH summation.
"""
outpoints = [(inp["previous_txid"], inp["prevout_index"]) for inp in all_inputs]
outpoints.sort(key=lambda x: (x[0], x[1]))
outpoint_to_input = {
(inp["previous_txid"], inp["prevout_index"]): inp for inp in eligible_inputs
}
return outpoints, outpoint_to_input
def _sum_pubkeys_in_outpoint_order(
outpoints: List[tuple],
outpoint_to_input: Dict,
):
"""Sum input public keys in sorted outpoint order (BIP-352 requirement)."""
summed = None
for outpoint in outpoints:
if outpoint not in outpoint_to_input:
continue
pk = outpoint_to_input[outpoint]["public_key"]
summed = pk if summed is None else summed + pk
return summed
def _sum_ecdh_shares_for_scan_key(
outpoints: List[tuple],
outpoint_to_input: Dict,
ecdh_data: Dict,
scan_key_id: str,
) -> tuple:
"""Sum ECDH shares for one scan key in sorted outpoint order.
Returns (summed_ecdh_point_or_None, coverage_complete) where
coverage_complete is True only when every outpoint contributed a share.
"""
inputs_with_ecdh: set = set()
summed = None
eligible_outpoints = [op for op in outpoints if op in outpoint_to_input]
for outpoint in eligible_outpoints:
inp = outpoint_to_input[outpoint]
ecdh_key = (inp["input_index"], scan_key_id)
if ecdh_key in ecdh_data:
ecdh_result, _ = ecdh_data[ecdh_key]
inputs_with_ecdh.add(inp["input_index"])
summed = ecdh_result if summed is None else summed + ecdh_result
return summed, len(inputs_with_ecdh) == len(eligible_outpoints)
# ============================================================================
# Core Data Structures
# ============================================================================
class InputType(Enum):
P2WPKH = "p2wpkh"
P2PKH = "p2pkh"
P2SH_P2WPKH = "p2sh_p2wpkh"
P2SH_MULTISIG = "p2sh_multisig"
P2WSH_MULTISIG = "p2wsh_multisig"
P2TR = "p2tr"
class OutputType(Enum):
SILENT_PAYMENT = "silent_payment"
REGULAR_P2TR = "regular_p2tr"
REGULAR_P2WPKH = "regular_p2wpkh"
class ValidationResult(Enum):
VALID = "valid"
INVALID = "invalid"
@dataclass
class InputSpec:
"""Specification for creating a PSBT input"""
input_type: InputType
amount: int
sequence: int = 0xFFFFFFFE
# Type-specific parameters
use_segwit_v2: bool = False
multisig_threshold: Optional[int] = None
multisig_pubkey_count: Optional[int] = None
key_derivation_suffix: str = "" # For deterministic key generation
use_nums_tap_internal_key: bool = False # For testing taproot internal key
eligible_override: Optional[bool] = None # Force is_eligible regardless of input type
skip_signing: bool = False # Force input to remain unsigned even if eligible
@dataclass
class OutputSpec:
"""Specification for creating a PSBT output"""
output_type: OutputType
amount: int
# Silent payment specific
scan_key_id: Optional[str] = None # References scan key from scenario
spend_key_id: Optional[str] = None
label: Optional[int] = None
force_wrong_script: bool = False # For testing wrong addresses
force_k_index: Optional[int] = None
spend_derivation_suffix: Optional[str] = None # Override spend key per output
# Regular output specific
add_bip32_derivation: bool = (
False # Add PSBT_OUT_BIP32_DERIVATION for change identification
)
@dataclass
class ScanKeySpec:
"""Specification for a scan/spend key pair"""
key_id: str
derivation_suffix: str = "" # For deterministic generation
@dataclass
class TestScenario:
"""Complete specification for a test case"""
description: str
validation_result: ValidationResult
inputs: List[InputSpec]
outputs: List[OutputSpec]
scan_keys: List[ScanKeySpec]
# List of explicit validation checks to perform - all checks will be performed if empty
# (e.g. ["psbt_structure", "ecdh_coverage", "input_eligibility", "output_scripts"])
checks: List[str]
exclude_material: List[str] = field(default_factory=list) # List of material fields to exclude from test vector (e.g. ["inputs", "sp_proofs", "outputs"])
# control override for invalid tests
missing_dleq_for_input: Optional[int] = None
invalid_dleq_for_input: Optional[int] = None
no_sighash_for_input: Optional[int] = None
wrong_sighash_for_input: Optional[int] = None
missing_ecdh_for_input: Optional[int] = None
wrong_sp_info_size: bool = False
missing_global_dleq: bool = False
use_global_ecdh: Optional[List[str]] = (
None # list of scan key IDs to use global ECDH
)
use_segwit_v2_input: bool = False
set_tx_modifiable: bool = False
missing_sp_info_field: bool = False
wrong_ecdh_share_size: bool = False
wrong_dleq_proof_size: bool = False
missing_ecdh_for_scan_key: Optional[str] = None
missing_dleq_for_scan_key: Optional[str] = None
invalid_dleq_for_scan_key: Optional[str] = None
inject_ineligible_ecdh: bool = False
force_output_script: bool = False
strip_input_pubkeys_for_input: Optional[int] = None
invalid_global_dleq: bool = False
missing_ecdh_for_input_scan_key: Optional[tuple] = None # (input_index, scan_key_id)
force_ecdh_for_input_scan_key: Optional[tuple] = None # (input_index, scan_key_id)
force_partial_ecdh_output_script: bool = False
skip_regular_output_script: bool = False
empty_regular_output_script: bool = False
# ============================================================================
# Specialized Input Factories
# ============================================================================
class InputFactory:
"""Creates PSBT inputs based on specifications"""
def __init__(self, wallet: Wallet, base_seed: str = "deterministic_test"):
self.wallet = wallet
self.base_seed = base_seed
def create_input(
self,
spec: InputSpec,
input_index: int,
scenario: Optional["TestScenario"] = None,
) -> Dict[str, Any]:
"""Create input based on specification"""
if scenario and scenario.use_segwit_v2_input:
spec.use_segwit_v2 = True
if spec.input_type == InputType.P2WPKH:
result = self._create_p2wpkh_input(spec, input_index)
elif spec.input_type == InputType.P2PKH:
result = self._create_p2pkh_input(spec, input_index)
elif spec.input_type == InputType.P2SH_P2WPKH:
result = self._create_p2sh_p2wpkh_input(spec, input_index)
elif spec.input_type == InputType.P2SH_MULTISIG:
result = self._create_p2sh_multisig_input(spec, input_index)
elif spec.input_type == InputType.P2WSH_MULTISIG:
result = self._create_p2wsh_multisig_input(spec, input_index)
elif spec.input_type == InputType.P2TR:
result = self._create_p2tr_input(spec, input_index)
else:
raise ValueError(f"Unknown input type: {spec.input_type}")
if spec.eligible_override is not None:
result["is_eligible"] = spec.eligible_override
if spec.skip_signing:
result["skip_signing"] = True
return result
def _create_p2wpkh_input(self, spec: InputSpec, input_index: int) -> Dict[str, Any]:
"""Create P2WPKH input"""
# Deterministic key generation
key_suffix = f"{spec.key_derivation_suffix}_{input_index}"
input_priv, input_pub = self.wallet.create_key_pair(
"input", _deterministic_hash(key_suffix)
)
# Create prevout
prev_input_txid = hashlib.sha256(
f"{self.base_seed}_prevout_{input_index}".encode()
).digest()
# P2WPKH witness program. Error injection: use segwit v2 instead of v0.
segwit_version = 2 if spec.use_segwit_v2 else 0
script_pubkey = bytes(
program_to_witness_script(segwit_version, hash160(input_pub.bytes))
)
prev_tx = self._create_prev_tx(prev_input_txid, spec.amount, script_pubkey)
previous_txid = hash256(prev_tx)
witness_utxo = CTxOut(spec.amount, script_pubkey).serialize()
return {
"input_index": input_index,
"input_type": InputType.P2WPKH,
"private_key": input_priv,
"public_key": input_pub,
"previous_txid": previous_txid,
"prevout_index": 0,
"script_pubkey": script_pubkey,
"witness_utxo": witness_utxo,
"non_witness_utxo": prev_tx,
"amount": spec.amount,
"sequence": spec.sequence,
"is_eligible": True,
}
def _create_p2pkh_input(self, spec: InputSpec, input_index: int) -> Dict[str, Any]:
"""Create P2PKH input (BIP-352 eligible; public key exposed via BIP32_DERIVATION)"""
key_suffix = f"{spec.key_derivation_suffix}_{input_index}"
input_priv, input_pub = self.wallet.create_key_pair(
"input", _deterministic_hash(key_suffix)
)
script_pubkey = bytes(key_to_p2pkh_script(input_pub.bytes))
prev_input_txid = hashlib.sha256(
f"{self.base_seed}_p2pkh_prevout_{input_index}".encode()
).digest()
prev_tx = self._create_prev_tx(prev_input_txid, spec.amount, script_pubkey)
previous_txid = hash256(prev_tx)
return {
"input_index": input_index,
"input_type": InputType.P2PKH,
"private_key": input_priv,
"public_key": input_pub,
"previous_txid": previous_txid,
"prevout_index": 0,
"script_pubkey": script_pubkey,
"non_witness_utxo": prev_tx,
"amount": spec.amount,
"sequence": spec.sequence,
"is_eligible": True,
}
def _create_p2sh_p2wpkh_input(self, spec: InputSpec, input_index: int) -> Dict[str, Any]:
"""Create P2SH-P2WPKH input (BIP-352 eligible wrapped segwit)"""
key_suffix = f"{spec.key_derivation_suffix}_{input_index}"
input_priv, input_pub = self.wallet.create_key_pair(
"input", _deterministic_hash(key_suffix)
)
# Redeem script is the inner P2WPKH witness program: OP_0 <20-byte hash>
redeem_script = bytes(program_to_witness_script(0, hash160(input_pub.bytes)))
# P2SH scriptPubKey wrapping the redeem script
script_pubkey = bytes(script_to_p2sh_script(redeem_script))
prev_input_txid = hashlib.sha256(
f"{self.base_seed}_p2sh_p2wpkh_prevout_{input_index}".encode()
).digest()
prev_tx = self._create_prev_tx(prev_input_txid, spec.amount, script_pubkey)
previous_txid = hash256(prev_tx)
# PSBT_IN_WITNESS_UTXO for P2SH-P2WPKH uses the P2SH scriptPubKey
witness_utxo = CTxOut(spec.amount, script_pubkey).serialize()
return {
"input_index": input_index,
"input_type": InputType.P2SH_P2WPKH,
"private_key": input_priv,
"public_key": input_pub,
"previous_txid": previous_txid,
"prevout_index": 0,
"script_pubkey": script_pubkey,
"redeem_script": redeem_script,
"witness_utxo": witness_utxo,
"non_witness_utxo": prev_tx,
"amount": spec.amount,
"sequence": spec.sequence,
"is_eligible": True,
}
def _generate_multisig_keys_and_script(
self, spec: InputSpec, input_index: int, purpose: str
) -> Tuple[list, bytes]:
"""Generate multisig keys and build OP_CHECKMULTISIG script.
Returns (keys, multisig_script) where keys is [(priv, pub), ...] and
multisig_script is OP_M <pubs> OP_N OP_CHECKMULTISIG.
"""
threshold = spec.multisig_threshold or 2
pubkey_count = spec.multisig_pubkey_count or 2
keys = []
for i in range(pubkey_count):
key_suffix = f"{spec.key_derivation_suffix}_{input_index}_{i}"
priv_key, pub_key = self.wallet.create_key_pair(
purpose, _deterministic_hash(key_suffix)
)
keys.append((priv_key, pub_key))
script = bytes(keys_to_multisig_script(
[pub_key.to_bytes_compressed() for _, pub_key in keys], k=threshold
))
return keys, script
def _multisig_common_fields(
self, keys: list, spec: InputSpec, input_index: int
) -> Dict[str, Any]:
"""Build the return-dict fields shared by P2SH and P2WSH multisig inputs."""
return {
"input_index": input_index,
"private_keys": [priv for priv, _ in keys],
"public_keys": [pub for _, pub in keys],
"public_key": keys[0][1] if keys else None,
"prevout_index": 0,
"amount": spec.amount,
"sequence": spec.sequence,
"is_eligible": False,
}
def _create_p2sh_multisig_input(
self, spec: InputSpec, input_index: int
) -> Dict[str, Any]:
"""Create P2SH multisig input"""
keys, redeem_script = self._generate_multisig_keys_and_script(
spec, input_index, "multisig"
)
# P2SH scriptPubKey wrapping the multisig redeem script
script_pubkey = bytes(script_to_p2sh_script(redeem_script))
# Create non-witness UTXO for P2SH
prev_input_txid = hashlib.sha256(
f"{self.base_seed}_p2sh_prevout_{input_index}".encode()
).digest()
prev_tx = self._create_prev_tx(prev_input_txid, spec.amount, script_pubkey)
result = self._multisig_common_fields(keys, spec, input_index)
result.update({
"input_type": InputType.P2SH_MULTISIG,
"previous_txid": hash256(prev_tx),
"script_pubkey": script_pubkey,
"redeem_script": redeem_script,
"non_witness_utxo": prev_tx,
})
return result
def _create_p2wsh_multisig_input(
self, spec: InputSpec, input_index: int
) -> Dict[str, Any]:
"""Create P2WSH multisig input"""
keys, witness_script = self._generate_multisig_keys_and_script(
spec, input_index, "wsh_multisig"
)
# P2WSH scriptPubKey wrapping the multisig witness script
script_pubkey = bytes(script_to_p2wsh_script(witness_script))
# Create witness UTXO
prev_input_txid = hashlib.sha256(
f"{self.base_seed}_p2wsh_prevout_{input_index}".encode()
).digest()
prev_tx = self._create_prev_tx(prev_input_txid, spec.amount, script_pubkey)
previous_txid = hash256(prev_tx)
witness_utxo = CTxOut(spec.amount, script_pubkey).serialize()
result = self._multisig_common_fields(keys, spec, input_index)
result.update({
"input_type": InputType.P2WSH_MULTISIG,
"previous_txid": previous_txid,
"script_pubkey": script_pubkey,
"witness_script": witness_script,
"witness_utxo": witness_utxo,
"non_witness_utxo": prev_tx,
})
return result
def _create_p2tr_input(self, spec: InputSpec, input_index: int) -> Dict[str, Any]:
"""Create P2TR key-path input (unsigned/WIP — no taptweak applied)."""
key_suffix = f"{spec.key_derivation_suffix}_{input_index}"
input_priv, input_pub = self.wallet.create_key_pair(
"input", _deterministic_hash(key_suffix)
)
prev_input_txid = hashlib.sha256(
f"{self.base_seed}_p2tr_prevout_{input_index}".encode()
).digest()
# Negate private key if pubkey has odd y (BIP340 even-y requirement for lift_x)
if int(input_pub.y) % 2 != 0:
input_priv = PrivateKey(GE.ORDER - int(input_priv))
input_pub = PublicKey(int(input_priv) * G)
if spec.use_nums_tap_internal_key:
# NUMS point as taproot internal key: no private key exists, input is ineligible
# for Silent Payments (cannot contribute an ECDH share).
script_pubkey = bytes(output_key_to_p2tr_script(NUMS_H))
prev_tx = self._create_prev_tx(prev_input_txid, spec.amount, script_pubkey)
previous_txid = hash256(prev_tx)
witness_utxo = CTxOut(spec.amount, script_pubkey).serialize()
return {
"input_index": input_index,
"input_type": InputType.P2TR,
"private_key": input_priv,
"public_key": input_pub,
"tap_internal_key": NUMS_H,
"previous_txid": previous_txid,
"prevout_index": 0,
"script_pubkey": script_pubkey,
"witness_utxo": witness_utxo,
"non_witness_utxo": prev_tx,
"amount": spec.amount,
"sequence": spec.sequence,
"is_eligible": False,
}
# P2TR scriptPubKey: OP_1 + 32-byte x-only key
script_pubkey = bytes(output_key_to_p2tr_script(input_pub.bytes_xonly))
prev_tx = self._create_prev_tx(prev_input_txid, spec.amount, script_pubkey)
previous_txid = hash256(prev_tx)
witness_utxo = CTxOut(spec.amount, script_pubkey).serialize()
return {
"input_index": input_index,
"input_type": InputType.P2TR,
"private_key": input_priv,
"public_key": input_pub,
"previous_txid": previous_txid,
"prevout_index": 0,
"script_pubkey": script_pubkey,
"witness_utxo": witness_utxo,
"non_witness_utxo": prev_tx,
"amount": spec.amount,
"sequence": spec.sequence,
"is_eligible": True,
}
def _create_prev_tx(
self, prev_input_txid: bytes, amount: int, script_pubkey: bytes
) -> bytes:
"""Create a previous transaction for non-witness UTXOs"""
tx = CTransaction()
tx.version = 2
tx.nLockTime = 0
tx.vin.append(
CTxIn(COutPoint(uint256_from_str(prev_input_txid), 0), b"", 0xFFFFFFFF)
)
tx.vout.append(CTxOut(amount, bytes(script_pubkey)))
return tx.serialize_without_witness()
# ============================================================================
# Output Factory
# ============================================================================
class OutputFactory:
"""Creates PSBT outputs based on specifications"""
def __init__(self, wallet: Wallet):
self.wallet = wallet
def create_output(
self, spec: OutputSpec, output_index: int, scan_keys: Dict[str, tuple]
) -> Dict[str, Any]:
"""Create output based on specification"""
if spec.output_type == OutputType.SILENT_PAYMENT:
return self._create_silent_payment_output(spec, output_index, scan_keys)
elif spec.output_type == OutputType.REGULAR_P2TR:
return self._create_regular_p2tr_output(spec, output_index)
elif spec.output_type == OutputType.REGULAR_P2WPKH:
return self._create_regular_p2wpkh_output(spec, output_index)
else:
raise ValueError(f"Unknown output type: {spec.output_type}")
def _create_silent_payment_output(
self, spec: OutputSpec, output_index: int, scan_keys: Dict[str, tuple]
) -> Dict[str, Any]:
"""Create silent payment output"""
if not spec.scan_key_id or spec.scan_key_id not in scan_keys:
raise ValueError("Silent payment output requires valid scan_key_id")
scan_pub, spend_pub = scan_keys[spec.scan_key_id]
if spec.spend_derivation_suffix is not None:
spend_seed = _deterministic_hash(f"spend_{spec.spend_derivation_suffix}")
_, spend_pub = self.wallet.create_key_pair("spend", spend_seed)
return {
"output_index": output_index,
"output_type": OutputType.SILENT_PAYMENT,
"amount": spec.amount,
"scan_pubkey": scan_pub,
"base_spend_pubkey": spend_pub,
"label": spec.label,
"force_wrong_script": spec.force_wrong_script,
"force_k_index": spec.force_k_index,
}
def _create_regular_p2tr_output(
self, spec: OutputSpec, output_index: int
) -> Dict[str, Any]:
"""Create regular P2TR output"""
# Simple P2TR output for testing
output_script = bytes(output_key_to_p2tr_script(
hashlib.sha256(f"regular_p2tr_{output_index}".encode()).digest()
))
return {
"output_index": output_index,
"output_type": OutputType.REGULAR_P2TR,
"amount": spec.amount,
"script": output_script,
"add_bip32_derivation": spec.add_bip32_derivation, # FIXME: this should error for p2tr outputs
}
def _create_regular_p2wpkh_output(
self, spec: OutputSpec, output_index: int
) -> Dict[str, Any]:
"""Create regular P2WPKH output"""
# Simple P2WPKH output for testing
pubkey_hash = hashlib.sha256(
f"regular_p2wpkh_{output_index}".encode()
).digest()[:20]
output_script = bytes(program_to_witness_script(0, pubkey_hash))
return {
"output_index": output_index,
"output_type": OutputType.REGULAR_P2WPKH,
"amount": spec.amount,
"script": output_script,
"add_bip32_derivation": spec.add_bip32_derivation,
}
# ============================================================================
# PSBT Builder
# ============================================================================
class PSBTBuilder:
"""Builds PSBTs from test scenarios"""
def __init__(self, wallet: Wallet, base_seed: str = "deterministic_test"):
self.wallet = wallet
self.base_seed = base_seed
self.input_factory = InputFactory(wallet, base_seed)
self.output_factory = OutputFactory(wallet)
def build_psbt(self, scenario: TestScenario) -> Dict[str, Any]:
"""Build a complete PSBT from a test scenario"""
# Create base PSBT structure
psbt = self._create_psbt_base(
len(scenario.inputs), len(scenario.outputs), scenario
)
# Generate scan keys deterministically
scan_keys = self._generate_scan_keys(scenario.scan_keys)
# Create inputs
input_data = []
for i, input_spec in enumerate(scenario.inputs):
input_info = self.input_factory.create_input(input_spec, i, scenario)
input_data.append(input_info)
self._add_input_to_psbt(psbt, input_info)
# Create outputs
output_data = []
for i, output_spec in enumerate(scenario.outputs):
output_info = self.output_factory.create_output(output_spec, i, scan_keys)
output_data.append(output_info)
# Compute ECDH shares for silent payment outputs
ecdh_data = self._compute_ecdh_shares(input_data, scan_keys, scenario)
# Add ECDH shares to PSBT (with error injection); track which inputs get signed
signed_input_indices: set = set()
self._add_ecdh_shares_to_psbt(psbt, ecdh_data, scenario, input_data, scan_keys, signed_input_indices)
# Error injection: strip BIP32_DERIVATION from specified input
if scenario.strip_input_pubkeys_for_input is not None:
idx = scenario.strip_input_pubkeys_for_input
remove_raw_input_fields_by_type(
psbt, idx, PSBTKeyType.PSBT_IN_BIP32_DERIVATION
)
# Compute and add outputs to PSBT; collect finalized scripts for signing
finalized_outputs = self._add_outputs_to_psbt(psbt, output_data, input_data, ecdh_data, scenario, scan_keys)
# Auto-sign all eligible inputs when output scripts are complete
if self._should_auto_sign(scenario):
for input_info in input_data:
if input_info.get("is_eligible", False) and not input_info.get("skip_signing", False):
self._sign_single_input(
psbt, input_info, input_data, finalized_outputs, input_info["input_index"]
)
signed_input_indices.add(input_info["input_index"])
if not scenario.set_tx_modifiable:
psbt.set_tx_modifiable(0x00)
# Self-check valid scenarios from the receiver side (independent oracle).
if scenario.validation_result == ValidationResult.VALID:
verify_receiver_detects_outputs(input_data, output_data, self.scan_privs)
# Build result structure
return {
"psbt": psbt,
"input_data": input_data,
"output_data": output_data,
"scan_keys": scan_keys,
"ecdh_data": ecdh_data,
"scenario": scenario,
"signed_input_indices": signed_input_indices,
}
def _create_psbt_base(
self, num_inputs: int, num_outputs: int, scenario: TestScenario
) -> SilentPaymentPsbt:
"""Create PSBT v2 base structure"""
return _create_psbt(
num_inputs,
num_outputs,
tx_modifiable=scenario.set_tx_modifiable,
)
def _generate_scan_keys(
self, scan_key_specs: List[ScanKeySpec]
) -> Dict[str, tuple]:
"""Generate scan/spend key pairs deterministically.
Also records the scan private key for each scan public key in
self.scan_privs (keyed by compressed scan pubkey bytes) so labeled
spend keys can be computed with the correct scan key. The map is reset
on every call since the builder is reused across scenarios.
"""
scan_keys = {}
self.scan_privs: Dict[bytes, PrivateKey] = {}
for spec in scan_key_specs:
if spec.key_id == "default":
# Use wallet's default keys
scan_priv, scan_pub = self.wallet.scan_priv, self.wallet.scan_pub
scan_keys[spec.key_id] = (scan_pub, self.wallet.spend_pub)
else:
# Generate deterministic keys
seed_suffix = _deterministic_hash(
f"{spec.key_id}_{spec.derivation_suffix}"
)
scan_priv, scan_pub = self.wallet.create_key_pair("scan", seed_suffix)
_, spend_pub = self.wallet.create_key_pair("spend", seed_suffix)
scan_keys[spec.key_id] = (scan_pub, spend_pub)
self.scan_privs[scan_pub.to_bytes_compressed()] = scan_priv
return scan_keys
def _add_input_to_psbt(self, psbt: SilentPaymentPsbt, input_info: Dict[str, Any]):
"""Add input fields to PSBT based on input type"""
idx = input_info["input_index"]
input_type = input_info["input_type"]
# Add common fields
add_raw_input_field(
psbt, idx, PSBTKeyType.PSBT_IN_PREVIOUS_TXID, b"", input_info["previous_txid"]
)
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_OUTPUT_INDEX,
b"",
struct.pack("<I", input_info["prevout_index"]),
)
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_SEQUENCE,
b"",
struct.pack("<I", input_info["sequence"]),
)
if input_type == InputType.P2WPKH:
# Add witness UTXO and BIP32 derivation
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_WITNESS_UTXO,
b"",
input_info["witness_utxo"],
)
# Add BIP32 derivation for pubkey exposure
fake_derivation = struct.pack("<I", 0x80000000) + struct.pack(
"<I", idx
) # m/0'/idx'
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_BIP32_DERIVATION,
input_info["public_key"].bytes,
fake_derivation,
)
elif input_type == InputType.P2PKH:
# Non-witness UTXO (full prev tx) + BIP32 derivation to expose public key
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_NON_WITNESS_UTXO,
b"",
input_info["non_witness_utxo"],
)
fake_derivation = struct.pack("<I", 0x80000000) + struct.pack("<I", idx)
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_BIP32_DERIVATION,
input_info["public_key"].bytes,
fake_derivation,
)
elif input_type == InputType.P2SH_P2WPKH:
# Both non-witness UTXO (full prev tx) and witness UTXO (P2SH scriptPubKey),
# plus the redeem script and BIP32 derivation to expose the public key
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_NON_WITNESS_UTXO,
b"",
input_info["non_witness_utxo"],
)
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_WITNESS_UTXO,
b"",
input_info["witness_utxo"],
)
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_REDEEM_SCRIPT,
b"",
input_info["redeem_script"],
)
fake_derivation = struct.pack("<I", 0x80000000) + struct.pack("<I", idx)
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_BIP32_DERIVATION,
input_info["public_key"].bytes,
fake_derivation,
)
elif input_type == InputType.P2SH_MULTISIG:
# Add non-witness UTXO and redeem script
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_NON_WITNESS_UTXO,
b"",
input_info["non_witness_utxo"],
)
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_REDEEM_SCRIPT,
b"",
input_info["redeem_script"],
)
elif input_type == InputType.P2WSH_MULTISIG:
# Add witness UTXO and witness script
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_WITNESS_UTXO,
b"",
input_info["witness_utxo"],
)
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_WITNESS_SCRIPT,
b"",
input_info["witness_script"],
)
elif input_type == InputType.P2TR:
# Add witness UTXO and taproot internal key
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_WITNESS_UTXO,
b"",
input_info["witness_utxo"],
)
tap_key = input_info.get("tap_internal_key", input_info["public_key"].bytes_xonly)
add_raw_input_field(
psbt,
idx,
PSBTKeyType.PSBT_IN_TAP_INTERNAL_KEY,
b"",
tap_key,
)
def _compute_ecdh_shares(
self,
input_data: List[Dict],
scan_keys: Dict[str, tuple],
scenario: TestScenario,
) -> Dict:
"""Compute ECDH shares for eligible inputs"""
ecdh_shares = {} # (input_idx, scan_key_id) -> (ecdh_result, dleq_proof)
eligible_inputs = [inp for inp in input_data if inp["is_eligible"]]
for input_info in eligible_inputs:
input_idx = input_info["input_index"]
# Error injection says to skip this input
if scenario.missing_ecdh_for_input == input_idx:
continue
private_key = input_info["private_key"]
for scan_key_id, (scan_pub, _) in scan_keys.items():
# Skip ECDH for specific scan key (affects all inputs)
if scenario.missing_ecdh_for_scan_key == scan_key_id:
continue
# Skip ECDH for a specific (input, scan_key) pair only
if (
scenario.missing_ecdh_for_input_scan_key is not None
and scenario.missing_ecdh_for_input_scan_key == (input_idx, scan_key_id)
):
continue
# Compute ECDH share
ecdh_result = private_key * scan_pub
# Generate DLEQ proof (with potential Error injection)
if (
scenario.invalid_dleq_for_input == input_idx
or scenario.invalid_dleq_for_scan_key == scan_key_id
):
# Use wrong private key for invalid proof
wrong_priv, _ = self.wallet.create_key_pair("wrong", 999)
dleq_proof = spdk_psbt.dleq_generate_proof(
wrong_priv.bytes, scan_pub.bytes, self.wallet.random_bytes(32)
)
elif (
scenario.missing_dleq_for_input == input_idx
or scenario.missing_dleq_for_scan_key == scan_key_id
):
dleq_proof = None
else:
# Normal valid proof
random_bytes = hashlib.sha256(
f"{self.base_seed}_dleq_{input_idx}_{scan_key_id}".encode()
).digest()
dleq_proof = spdk_psbt.dleq_generate_proof(
private_key.bytes, scan_pub.bytes, random_bytes
)
# Error injection: Wrong DLEQ proof size
if scenario.wrong_dleq_proof_size:
dleq_proof = dleq_proof[:63] # Truncate to wrong size
ecdh_shares[(input_idx, scan_key_id)] = (ecdh_result, dleq_proof)
return ecdh_shares
def _add_ecdh_shares_to_psbt(
self,
psbt: SilentPaymentPsbt,
ecdh_data: Dict,
scenario: TestScenario,
input_data: List[Dict],