keep-bitcoin 0.7.5

Bitcoin PSBT and Taproot support for Keep
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
// SPDX-FileCopyrightText: © 2026 PrivKey LLC
// SPDX-License-Identifier: MIT
use crate::error::{BitcoinError, Result};
use crate::recovery::{RecoveryOutput, TierInfo};
use bitcoin::hashes::Hash as _;
use bitcoin::key::Secp256k1;
use bitcoin::psbt::Psbt;
use bitcoin::secp256k1::{All, Keypair, Message};
use bitcoin::sighash::{Prevouts, SighashCache, TapSighashType};
use bitcoin::taproot::{ControlBlock, LeafVersion, Signature as TaprootSignature, TapLeafHash};
use bitcoin::{
    Amount, OutPoint, ScriptBuf, Sequence, Transaction, TxIn, TxOut, Witness, XOnlyPublicKey,
};
use zeroize::Zeroizing;

const MAX_FEE_SATS: u64 = 100_000_000; // 1 BTC
/// Bitcoin Core's default dust threshold for taproot (P2TR) outputs in sats.
/// Outputs smaller than this are non-standard and unlikely to relay.
pub const TAPROOT_DUST_LIMIT_SATS: u64 = 330;
/// Maximum number of inputs in a single consolidating sweep. Taproot
/// script-path inputs carry a sizable witness (signature, leaf script, control
/// block), so a large input count both risks the ~100 kvB standardness weight
/// limit and is costly to sign (one sighash per input per signer). Bound it
/// conservatively; callers needing to consolidate more must batch into
/// multiple sweeps.
pub const MAX_SWEEP_INPUTS: usize = 100;

/// A single UTXO under the recovery output being consolidated by
/// [`RecoveryTxBuilder::build_sweep_psbt`].
#[derive(Clone, Debug)]
pub struct SweepUtxo {
    pub outpoint: OutPoint,
    pub value_sats: u64,
}

pub struct RecoveryTxBuilder {
    recovery_output: RecoveryOutput,
    secp: Secp256k1<All>,
}

impl RecoveryTxBuilder {
    pub fn new(recovery_output: RecoveryOutput) -> Self {
        Self {
            recovery_output,
            secp: Secp256k1::new(),
        }
    }

    pub fn build_recovery_psbt(
        &self,
        tier_index: usize,
        utxo: OutPoint,
        utxo_value: u64,
        destination: &ScriptBuf,
        fee_sats: u64,
    ) -> Result<Psbt> {
        let tier = self.get_tier(tier_index)?;

        if fee_sats > MAX_FEE_SATS {
            return Err(BitcoinError::Recovery(format!(
                "fee {fee_sats} sats exceeds maximum {MAX_FEE_SATS} sats"
            )));
        }
        if utxo_value <= fee_sats {
            return Err(BitcoinError::Recovery("insufficient funds".into()));
        }
        let output_value = utxo_value - fee_sats;
        if output_value < TAPROOT_DUST_LIMIT_SATS {
            return Err(BitcoinError::Recovery(format!(
                "output below dust threshold ({TAPROOT_DUST_LIMIT_SATS} sats)"
            )));
        }

        let sequence = match tier.timelock_blocks {
            Some(timelock_blocks) => crate::recovery::recovery_sequence(timelock_blocks)?,
            None => Sequence::ENABLE_RBF_NO_LOCKTIME,
        };

        let tx = Transaction {
            version: bitcoin::transaction::Version(2),
            lock_time: bitcoin::absolute::LockTime::ZERO,
            input: vec![TxIn {
                previous_output: utxo,
                script_sig: ScriptBuf::new(),
                sequence,
                witness: Witness::default(),
            }],
            output: vec![TxOut {
                value: Amount::from_sat(output_value),
                script_pubkey: destination.clone(),
            }],
        };

        let mut psbt =
            Psbt::from_unsigned_tx(tx).map_err(|e| BitcoinError::Recovery(e.to_string()))?;

        psbt.inputs[0].witness_utxo = Some(TxOut {
            value: Amount::from_sat(utxo_value),
            script_pubkey: self.recovery_output.address.script_pubkey(),
        });

        let control_block = self.control_block(tier)?;
        psbt.inputs[0]
            .tap_scripts
            .insert(control_block, (tier.script.clone(), LeafVersion::TapScript));

        Ok(psbt)
    }

    /// Build a consolidating sweep PSBT that spends every UTXO in `utxos`
    /// (all under this recovery output, via the same `tier_index` scriptpath)
    /// into a single output paying `destination`. The output value is the sum
    /// of all UTXO values minus `fee_sats`.
    ///
    /// Every input is tagged with the tier's `tap_scripts` entry and
    /// `witness_utxo`, so each can be signed via [`script_spend_sighashes`] and
    /// aggregated by the PSBT coordination layer. `utxos` must be non-empty and
    /// contain no duplicate outpoints.
    pub fn build_sweep_psbt(
        &self,
        tier_index: usize,
        utxos: &[SweepUtxo],
        destination: &ScriptBuf,
        fee_sats: u64,
    ) -> Result<Psbt> {
        let tier = self.get_tier(tier_index)?;

        if utxos.is_empty() {
            return Err(BitcoinError::Recovery(
                "sweep requires at least one UTXO".into(),
            ));
        }
        if utxos.len() > MAX_SWEEP_INPUTS {
            return Err(BitcoinError::Recovery(format!(
                "sweep input count {} exceeds maximum {MAX_SWEEP_INPUTS}",
                utxos.len()
            )));
        }
        if fee_sats > MAX_FEE_SATS {
            return Err(BitcoinError::Recovery(format!(
                "fee {fee_sats} sats exceeds maximum {MAX_FEE_SATS} sats"
            )));
        }

        let mut seen = std::collections::HashSet::new();
        let mut total_in: u64 = 0;
        for utxo in utxos {
            if !seen.insert(utxo.outpoint) {
                return Err(BitcoinError::Recovery(format!(
                    "duplicate UTXO {} in sweep",
                    utxo.outpoint
                )));
            }
            total_in = total_in
                .checked_add(utxo.value_sats)
                .ok_or_else(|| BitcoinError::Recovery("sweep input value overflow".into()))?;
        }

        if total_in <= fee_sats {
            return Err(BitcoinError::Recovery("insufficient funds".into()));
        }
        let output_value = total_in - fee_sats;
        if output_value < TAPROOT_DUST_LIMIT_SATS {
            return Err(BitcoinError::Recovery(format!(
                "sweep output below dust threshold ({TAPROOT_DUST_LIMIT_SATS} sats)"
            )));
        }

        let sequence = match tier.timelock_blocks {
            Some(timelock_blocks) => crate::recovery::recovery_sequence(timelock_blocks)?,
            None => Sequence::ENABLE_RBF_NO_LOCKTIME,
        };

        let input: Vec<TxIn> = utxos
            .iter()
            .map(|u| TxIn {
                previous_output: u.outpoint,
                script_sig: ScriptBuf::new(),
                sequence,
                witness: Witness::default(),
            })
            .collect();

        let tx = Transaction {
            version: bitcoin::transaction::Version(2),
            lock_time: bitcoin::absolute::LockTime::ZERO,
            input,
            output: vec![TxOut {
                value: Amount::from_sat(output_value),
                script_pubkey: destination.clone(),
            }],
        };

        let mut psbt =
            Psbt::from_unsigned_tx(tx).map_err(|e| BitcoinError::Recovery(e.to_string()))?;

        let control_block = self.control_block(tier)?;
        let spk = self.recovery_output.address.script_pubkey();
        for (i, utxo) in utxos.iter().enumerate() {
            psbt.inputs[i].witness_utxo = Some(TxOut {
                value: Amount::from_sat(utxo.value_sats),
                script_pubkey: spk.clone(),
            });
            psbt.inputs[i].tap_scripts.insert(
                control_block.clone(),
                (tier.script.clone(), LeafVersion::TapScript),
            );
        }

        Ok(psbt)
    }

    /// Sign the single input of `psbt` for the given recovery tier.
    ///
    /// `psbt` MUST contain exactly one input. This is the recovery-tier
    /// invariant: every PSBT produced by [`Self::build_recovery_psbt`] is
    /// single-input, and finalize_recovery / aggregate_partial_psbts assume
    /// the same shape. Multi-input PSBTs are rejected.
    pub fn sign_recovery(
        &self,
        psbt: &mut Psbt,
        tier_index: usize,
        secret_key: &[u8; 32],
    ) -> Result<()> {
        let tier = self.get_tier(tier_index)?;
        if psbt.inputs.len() != 1 {
            return Err(BitcoinError::Recovery(format!(
                "sign_recovery requires exactly one PSBT input, got {}",
                psbt.inputs.len()
            )));
        }
        let sk_bytes = Zeroizing::new(*secret_key);
        let keypair = Keypair::from_seckey_slice(&self.secp, &*sk_bytes)
            .map_err(|e| BitcoinError::InvalidSecretKey(e.to_string()))?;
        let (x_only, _) = keypair.x_only_public_key();

        let prevouts: Vec<TxOut> = psbt
            .inputs
            .iter()
            .enumerate()
            .map(|(i, input)| {
                input
                    .witness_utxo
                    .clone()
                    .ok_or(BitcoinError::MissingWitnessUtxo(i))
            })
            .collect::<Result<Vec<_>>>()?;

        let mut sighash_cache = SighashCache::new(&psbt.unsigned_tx);
        let leaf_hash = tier.leaf_hash;

        let sighash = sighash_cache
            .taproot_script_spend_signature_hash(
                0,
                &Prevouts::All(&prevouts),
                leaf_hash,
                TapSighashType::Default,
            )
            .map_err(|e| BitcoinError::Sighash(e.to_string()))?;

        let msg = Message::from_digest_slice(sighash.as_ref())
            .map_err(|e| BitcoinError::Signing(e.to_string()))?;

        let aux_rand = crate::aux_rand()?;
        let sig = self
            .secp
            .sign_schnorr_with_aux_rand(&msg, &keypair, &aux_rand);

        psbt.inputs[0].tap_script_sigs.insert(
            (x_only, leaf_hash),
            TaprootSignature {
                signature: sig,
                sighash_type: TapSighashType::Default,
            },
        );

        Ok(())
    }

    /// Finalize a recovery PSBT by attaching the witness stack for the given
    /// tier. Assumes `tier.script` is the CHECKSIGADD-style multisig script
    /// produced by `RecoveryConfig::build` (one stack push per key, in
    /// reverse-key order, followed by the leaf script and control block).
    /// `RecoveryConfig::build` is the only sanctioned producer of tier
    /// scripts, so this layout is guaranteed by construction.
    pub fn finalize_recovery(&self, psbt: &mut Psbt, tier_index: usize) -> Result<Transaction> {
        let tier = self.get_tier(tier_index)?;
        if psbt.inputs.len() != 1 || psbt.unsigned_tx.input.len() != 1 {
            return Err(BitcoinError::Recovery(format!(
                "finalize_recovery requires exactly one PSBT input, got {}",
                psbt.inputs.len()
            )));
        }
        let control_block = self.control_block(tier)?;
        // Defensive check: a CHECKSIGADD witness needs one push per key, so a
        // tier with zero keys cannot be finalized. Fail closed rather than
        // panic, a malformed RecoveryConfig must not crash the node.
        if tier.keys.is_empty() {
            return Err(BitcoinError::Recovery(format!(
                "tier {tier_index} has no keys; cannot build CHECKSIGADD witness"
            )));
        }

        let sig_count = psbt.inputs[0]
            .tap_script_sigs
            .iter()
            .filter(|((_, lh), _)| *lh == tier.leaf_hash)
            .count();

        if (sig_count as u32) < tier.threshold {
            return Err(BitcoinError::Recovery(format!(
                "insufficient signatures: have {}, need {}",
                sig_count, tier.threshold
            )));
        }

        let mut witness = Witness::new();
        let mut sigs_included: u32 = 0;
        for key in tier.keys.iter().rev() {
            if sigs_included < tier.threshold {
                if let Some(sig) = psbt.inputs[0].tap_script_sigs.get(&(*key, tier.leaf_hash)) {
                    witness.push(sig.to_vec());
                    sigs_included += 1;
                } else {
                    witness.push([]);
                }
            } else {
                witness.push([]);
            }
        }
        witness.push(tier.script.as_bytes());
        witness.push(control_block.serialize());

        let mut tx = psbt.unsigned_tx.clone();
        tx.input[0].witness = witness;

        Ok(tx)
    }

    fn get_tier(&self, index: usize) -> Result<&TierInfo> {
        let tier = self
            .recovery_output
            .tiers
            .get(index)
            .ok_or_else(|| BitcoinError::Recovery(format!("tier {index} not found")))?;
        if tier.keys.is_empty() {
            return Err(BitcoinError::Recovery(format!("tier {index} has no keys")));
        }
        if tier.threshold < 1 {
            return Err(BitcoinError::Recovery(format!(
                "tier {index} threshold must be at least 1"
            )));
        }
        if tier.threshold as usize > tier.keys.len() {
            return Err(BitcoinError::Recovery(format!(
                "tier {index} threshold {} exceeds key count {}",
                tier.threshold,
                tier.keys.len()
            )));
        }
        Ok(tier)
    }

    fn control_block(&self, tier: &TierInfo) -> Result<ControlBlock> {
        self.recovery_output
            .spend_info
            .control_block(&(tier.script.clone(), LeafVersion::TapScript))
            .ok_or_else(|| BitcoinError::Recovery("no control block for tier script".into()))
    }
}

/// Per-input recovery-tier script-spend sighash bundle.
///
/// Returned by [`script_spend_sighashes`]. Each entry contains the BIP-341
/// sighash bytes the remote signer must sign, plus the leaf hash, leaf script,
/// and control block needed to merge the resulting Schnorr signature back into
/// the PSBT via [`merge_tap_script_sig`].
#[derive(Clone, Debug)]
pub struct ScriptSpendSighash {
    pub input_index: usize,
    pub sighash: [u8; 32],
    pub leaf_hash: TapLeafHash,
    pub script: ScriptBuf,
    pub control_block: ControlBlock,
}

/// Compute the BIP-341 script-spend sighash for every input of `psbt` using
/// the tap_scripts entries already attached to the PSBT. Each input must carry
/// exactly one `tap_scripts` entry (as inserted by [`RecoveryTxBuilder::build_recovery_psbt`])
/// and a `witness_utxo`. Returns one [`ScriptSpendSighash`] per input.
pub fn script_spend_sighashes(psbt: &Psbt) -> Result<Vec<ScriptSpendSighash>> {
    let prevouts: Vec<TxOut> = psbt
        .inputs
        .iter()
        .enumerate()
        .map(|(i, input)| {
            input
                .witness_utxo
                .clone()
                .ok_or(BitcoinError::MissingWitnessUtxo(i))
        })
        .collect::<Result<Vec<_>>>()?;

    let mut sighash_cache = SighashCache::new(&psbt.unsigned_tx);
    let mut out = Vec::with_capacity(psbt.inputs.len());
    for (i, input) in psbt.inputs.iter().enumerate() {
        let mut iter = input.tap_scripts.iter();
        let (control_block, (script, leaf_version)) = iter
            .next()
            .ok_or_else(|| BitcoinError::Recovery(format!("input {i} has no tap_scripts entry")))?;
        if iter.next().is_some() {
            return Err(BitcoinError::Recovery(format!(
                "input {i} has more than one tap_scripts entry; ambiguous tier"
            )));
        }
        let leaf_hash = TapLeafHash::from_script(script, *leaf_version);
        let sighash = sighash_cache
            .taproot_script_spend_signature_hash(
                i,
                &Prevouts::All(&prevouts),
                leaf_hash,
                TapSighashType::Default,
            )
            .map_err(|e| BitcoinError::Sighash(e.to_string()))?;
        out.push(ScriptSpendSighash {
            input_index: i,
            sighash: sighash.to_byte_array(),
            leaf_hash,
            script: script.clone(),
            control_block: control_block.clone(),
        });
    }
    Ok(out)
}

/// Insert a remote Schnorr signature into `psbt.inputs[input_index].tap_script_sigs`
/// keyed by `(xonly_pubkey, leaf_hash)` with `SIGHASH_DEFAULT`.
///
/// `sighash` MUST be the BIP-341 script-spend sighash bytes for this input
/// (typically the value taken from the corresponding [`ScriptSpendSighash`]).
/// The signature is verified against `(sighash, xonly_pubkey)` before being
/// inserted; an invalid signature is rejected so callers cannot silently
/// merge garbage from a malicious or buggy remote signer.
pub fn merge_tap_script_sig(
    psbt: &mut Psbt,
    input_index: usize,
    xonly_pubkey: bitcoin::XOnlyPublicKey,
    leaf_hash: TapLeafHash,
    sighash: &[u8; 32],
    schnorr_sig: [u8; 64],
) -> Result<()> {
    let input = psbt
        .inputs
        .get_mut(input_index)
        .ok_or_else(|| BitcoinError::Recovery(format!("input {input_index} out of range")))?;
    let signature = bitcoin::secp256k1::schnorr::Signature::from_slice(&schnorr_sig)
        .map_err(|e| BitcoinError::Signing(format!("invalid schnorr sig: {e}")))?;
    let msg = Message::from_digest_slice(sighash)
        .map_err(|e| BitcoinError::Signing(format!("invalid sighash: {e}")))?;
    let secp = Secp256k1::verification_only();
    secp.verify_schnorr(&signature, &msg, &xonly_pubkey)
        .map_err(|e| BitcoinError::Signing(format!("schnorr verify failed: {e}")))?;
    input.tap_script_sigs.insert(
        (xonly_pubkey, leaf_hash),
        TaprootSignature {
            signature,
            sighash_type: TapSighashType::Default,
        },
    );
    Ok(())
}

/// Verify that the script-spend bundle for `input_index` of `psbt` is bound
/// to the input's `witness_utxo` and that the leaf script commits to
/// `local_xonly`.
///
/// This is the security-critical gate that turns a "blind sighash signer"
/// into one that can only sign for outputs it actually controls. It enforces:
///
/// 1. `witness_utxo` is set and is a 34-byte P2TR script (so the output
///    key can be extracted).
/// 2. The PSBT input carries exactly one `tap_scripts` entry. Multiple
///    candidate scripts make the leaf-hash ambiguous and are rejected.
/// 3. The `(control_block, script, leaf_version)` triple committed to the
///    `witness_utxo`'s taproot output key, i.e. the leaf is provably part
///    of the taproot tree being spent.
/// 4. The leaf script contains `local_xonly` as a 32-byte push. This binds
///    the responder's signing key to a key actually present in the leaf;
///    without it a malicious proposer could ask the responder to sign for
///    an unrelated taproot leaf that happens to commit to the same output.
///
/// Returns the verified [`ScriptSpendSighash`] for this input on success.
pub fn verify_script_spend_input_binding(
    psbt: &Psbt,
    input_index: usize,
    local_xonly: &[u8; 32],
) -> Result<ScriptSpendSighash> {
    let input = psbt
        .inputs
        .get(input_index)
        .ok_or_else(|| BitcoinError::Recovery(format!("input {input_index} out of range")))?;

    let wu = input
        .witness_utxo
        .as_ref()
        .ok_or(BitcoinError::MissingWitnessUtxo(input_index))?;
    let spk = wu.script_pubkey.as_bytes();
    if !wu.script_pubkey.is_p2tr() || spk.len() != 34 {
        return Err(BitcoinError::Recovery(format!(
            "input {input_index} witness_utxo is not a P2TR output",
        )));
    }
    let mut output_key_bytes = [0u8; 32];
    output_key_bytes.copy_from_slice(&spk[2..34]);
    let output_key = XOnlyPublicKey::from_slice(&output_key_bytes).map_err(|e| {
        BitcoinError::Recovery(format!(
            "input {input_index} witness_utxo output key invalid: {e}"
        ))
    })?;

    let mut iter = input.tap_scripts.iter();
    let (control_block, (script, leaf_version)) = iter.next().ok_or_else(|| {
        BitcoinError::Recovery(format!("input {input_index} has no tap_scripts entry"))
    })?;
    if iter.next().is_some() {
        return Err(BitcoinError::Recovery(format!(
            "input {input_index} has more than one tap_scripts entry; ambiguous tier"
        )));
    }

    let secp = Secp256k1::verification_only();
    if !control_block.verify_taproot_commitment(&secp, output_key, script) {
        return Err(BitcoinError::Recovery(format!(
            "input {input_index} tap_scripts entry does not commit to the witness_utxo output key",
        )));
    }

    if !script_contains_xonly(script, local_xonly) {
        return Err(BitcoinError::Recovery(format!(
            "input {input_index} leaf script does not reference the local responder x-only key",
        )));
    }

    let leaf_hash = TapLeafHash::from_script(script, *leaf_version);

    let prevouts: Vec<TxOut> = psbt
        .inputs
        .iter()
        .enumerate()
        .map(|(i, inp)| {
            inp.witness_utxo
                .clone()
                .ok_or(BitcoinError::MissingWitnessUtxo(i))
        })
        .collect::<Result<Vec<_>>>()?;
    let mut sighash_cache = SighashCache::new(&psbt.unsigned_tx);
    let sighash = sighash_cache
        .taproot_script_spend_signature_hash(
            input_index,
            &Prevouts::All(&prevouts),
            leaf_hash,
            TapSighashType::Default,
        )
        .map_err(|e| BitcoinError::Sighash(e.to_string()))?;

    Ok(ScriptSpendSighash {
        input_index,
        sighash: sighash.to_byte_array(),
        leaf_hash,
        script: script.clone(),
        control_block: control_block.clone(),
    })
}

/// Verify every PSBT input's script-spend binding upfront and return the
/// per-input [`ScriptSpendSighash`] bundles. Errors with the offending
/// input index if any input fails the security-critical binding check in
/// [`verify_script_spend_input_binding`].
pub fn verify_all_script_spend_input_bindings(
    psbt: &Psbt,
    local_xonly: &[u8; 32],
) -> Result<Vec<ScriptSpendSighash>> {
    let mut out = Vec::with_capacity(psbt.inputs.len());
    for i in 0..psbt.inputs.len() {
        out.push(verify_script_spend_input_binding(psbt, i, local_xonly)?);
    }
    Ok(out)
}

/// Scan `script` opcodes for any 32-byte push equal to `xonly`. Recovery
/// tier leaves built by `RecoveryConfig::build` push each x-only key with
/// `OP_PUSHBYTES_32`, so any participating key shows up as such a push.
fn script_contains_xonly(script: &bitcoin::Script, xonly: &[u8; 32]) -> bool {
    use bitcoin::script::Instruction;
    for instr in script.instructions() {
        if let Ok(Instruction::PushBytes(b)) = instr {
            if b.as_bytes() == xonly.as_slice() {
                return true;
            }
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::recovery::{RecoveryConfig, RecoveryTier, SpendingTier};
    use bitcoin::hashes::Hash;
    use bitcoin::secp256k1::Keypair;
    use bitcoin::{Network, XOnlyPublicKey};

    fn test_keypair_full(seed: u8) -> ([u8; 32], [u8; 32]) {
        let secp = Secp256k1::new();
        let mut secret = [seed; 32];
        secret[0] = seed.wrapping_add(1);
        let kp = Keypair::from_seckey_slice(&secp, &secret).unwrap();
        let xonly = kp.x_only_public_key().0.serialize();
        (secret, xonly)
    }

    #[test]
    fn test_build_recovery_psbt() {
        let (_, pk1) = test_keypair_full(1);
        let (_, pk2) = test_keypair_full(2);

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk1],
                threshold: 1,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };

        let output = config.build().unwrap();
        let builder = RecoveryTxBuilder::new(output);

        let utxo = OutPoint {
            txid: bitcoin::Txid::all_zeros(),
            vout: 0,
        };
        let xonly_pk1 = XOnlyPublicKey::from_slice(&pk1).unwrap();
        let dest = ScriptBuf::new_p2tr(&Secp256k1::new(), xonly_pk1, None);

        let psbt = builder
            .build_recovery_psbt(0, utxo, 100_000, &dest, 1_000)
            .unwrap();

        assert_eq!(psbt.unsigned_tx.input.len(), 1);
        assert_eq!(psbt.unsigned_tx.output.len(), 1);
        assert_eq!(psbt.unsigned_tx.output[0].value.to_sat(), 99_000);
        assert!(psbt.unsigned_tx.input[0].sequence.is_relative_lock_time());
    }

    #[test]
    fn test_sign_and_finalize_recovery() {
        let (_, pk1) = test_keypair_full(1);
        let (sk2, pk2) = test_keypair_full(2);
        let secp = Secp256k1::new();

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk1],
                threshold: 1,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };

        let output = config.build().unwrap();
        let builder = RecoveryTxBuilder::new(output);

        let utxo = OutPoint {
            txid: bitcoin::Txid::all_zeros(),
            vout: 0,
        };
        let xonly_pk1 = XOnlyPublicKey::from_slice(&pk1).unwrap();
        let dest = ScriptBuf::new_p2tr(&secp, xonly_pk1, None);

        let mut psbt = builder
            .build_recovery_psbt(0, utxo, 100_000, &dest, 1_000)
            .unwrap();

        builder.sign_recovery(&mut psbt, 0, &sk2).unwrap();

        let tx = builder.finalize_recovery(&mut psbt, 0).unwrap();
        assert!(!tx.input[0].witness.is_empty());
    }

    #[test]
    fn test_build_sweep_psbt_consolidates_utxos() {
        let (_, pk1) = test_keypair_full(1);
        let (_, pk2) = test_keypair_full(2);
        let secp = Secp256k1::new();

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk1],
                threshold: 1,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };

        let output = config.build().unwrap();
        let builder = RecoveryTxBuilder::new(output);

        let utxos = vec![
            SweepUtxo {
                outpoint: OutPoint {
                    txid: bitcoin::Txid::all_zeros(),
                    vout: 0,
                },
                value_sats: 100_000,
            },
            SweepUtxo {
                outpoint: OutPoint {
                    txid: bitcoin::Txid::all_zeros(),
                    vout: 1,
                },
                value_sats: 50_000,
            },
        ];

        let xonly_pk1 = XOnlyPublicKey::from_slice(&pk1).unwrap();
        let dest = ScriptBuf::new_p2tr(&secp, xonly_pk1, None);

        let psbt = builder.build_sweep_psbt(0, &utxos, &dest, 2_000).unwrap();

        assert_eq!(psbt.unsigned_tx.input.len(), 2);
        assert_eq!(psbt.unsigned_tx.output.len(), 1);
        assert_eq!(psbt.unsigned_tx.output[0].value.to_sat(), 148_000);
        for input in &psbt.inputs {
            assert!(input.witness_utxo.is_some());
            assert_eq!(input.tap_scripts.len(), 1);
        }
        assert!(psbt.unsigned_tx.input[0].sequence.is_relative_lock_time());
    }

    #[test]
    fn test_build_sweep_psbt_rejects_empty_and_duplicate() {
        let (_, pk1) = test_keypair_full(1);
        let (_, pk2) = test_keypair_full(2);
        let secp = Secp256k1::new();
        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk1],
                threshold: 1,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };
        let builder = RecoveryTxBuilder::new(config.build().unwrap());
        let xonly_pk1 = XOnlyPublicKey::from_slice(&pk1).unwrap();
        let dest = ScriptBuf::new_p2tr(&secp, xonly_pk1, None);

        assert!(builder.build_sweep_psbt(0, &[], &dest, 1_000).is_err());

        let op = OutPoint {
            txid: bitcoin::Txid::all_zeros(),
            vout: 0,
        };
        let dup = vec![
            SweepUtxo {
                outpoint: op,
                value_sats: 100_000,
            },
            SweepUtxo {
                outpoint: op,
                value_sats: 100_000,
            },
        ];
        let err = builder.build_sweep_psbt(0, &dup, &dest, 1_000).unwrap_err();
        assert!(err.to_string().contains("duplicate"));
    }

    #[test]
    fn test_build_sweep_psbt_insufficient_funds() {
        let (_, pk1) = test_keypair_full(1);
        let (_, pk2) = test_keypair_full(2);
        let secp = Secp256k1::new();
        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk1],
                threshold: 1,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };
        let builder = RecoveryTxBuilder::new(config.build().unwrap());
        let xonly_pk1 = XOnlyPublicKey::from_slice(&pk1).unwrap();
        let dest = ScriptBuf::new_p2tr(&secp, xonly_pk1, None);
        let utxos = vec![SweepUtxo {
            outpoint: OutPoint {
                txid: bitcoin::Txid::all_zeros(),
                vout: 0,
            },
            value_sats: 500,
        }];
        assert!(builder.build_sweep_psbt(0, &utxos, &dest, 1_000).is_err());
    }

    #[test]
    fn test_finalize_with_excess_signatures() {
        let (_, pk1) = test_keypair_full(1);
        let (sk2, pk2) = test_keypair_full(2);
        let (sk3, pk3) = test_keypair_full(3);
        let (sk4, pk4) = test_keypair_full(4);
        let secp = Secp256k1::new();

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk1],
                threshold: 1,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2, pk3, pk4],
                threshold: 2,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };

        let output = config.build().unwrap();
        let builder = RecoveryTxBuilder::new(output);

        let utxo = OutPoint {
            txid: bitcoin::Txid::all_zeros(),
            vout: 0,
        };
        let xonly_pk1 = XOnlyPublicKey::from_slice(&pk1).unwrap();
        let dest = ScriptBuf::new_p2tr(&secp, xonly_pk1, None);

        let mut psbt = builder
            .build_recovery_psbt(0, utxo, 100_000, &dest, 1_000)
            .unwrap();

        builder.sign_recovery(&mut psbt, 0, &sk2).unwrap();
        builder.sign_recovery(&mut psbt, 0, &sk3).unwrap();
        builder.sign_recovery(&mut psbt, 0, &sk4).unwrap();

        assert_eq!(
            psbt.inputs[0]
                .tap_script_sigs
                .iter()
                .filter(|((_, lh), _)| *lh == builder.recovery_output.tiers[0].leaf_hash)
                .count(),
            3
        );

        let tx = builder.finalize_recovery(&mut psbt, 0).unwrap();
        assert!(!tx.input[0].witness.is_empty());

        let sig_count = tx.input[0]
            .witness
            .iter()
            .take(3)
            .filter(|w| !w.is_empty())
            .count();
        assert_eq!(sig_count, 2);
    }

    // === #417 round 4a: targeted unit tests killing the surviving mutations ===
    //
    // The boundary checks below are #414/#502's exact security boundary:
    // - `fee_sats > MAX_FEE_SATS` (defends against runaway fees)
    // - `utxo_value <= fee_sats` (insufficient funds)
    // - `output_value < TAPROOT_DUST_LIMIT_SATS` (dust)
    //
    // `>` ↔ `==` / `>=` and `<` ↔ `==` / `<=` mutations on these checks
    // would let through "exactly at the cap" inputs or skip the gate
    // entirely on a malicious proposer-supplied amount, exactly the
    // attack surface #414 describes.

    fn fixture_builder() -> RecoveryTxBuilder {
        let (_, pk1) = test_keypair_full(1);
        let (_, pk2) = test_keypair_full(2);
        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk1],
                threshold: 1,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };
        let output = config.build().unwrap();
        RecoveryTxBuilder::new(output)
    }

    fn fixture_outpoint() -> OutPoint {
        OutPoint {
            txid: bitcoin::Txid::all_zeros(),
            vout: 0,
        }
    }

    fn fixture_dest() -> ScriptBuf {
        let (_, pk) = test_keypair_full(7);
        let xonly = XOnlyPublicKey::from_slice(&pk).unwrap();
        ScriptBuf::new_p2tr(&Secp256k1::new(), xonly, None)
    }

    /// Fee strictly equal to MAX_FEE_SATS is REJECTED only if `>` is
    /// strict; a `>=` mutation would refuse exactly-at-cap fees,
    /// while a `==` mutation would let above-cap fees slip past for
    /// any non-equality. Both are corrupt; pin the exact boundary.
    #[test]
    fn build_recovery_psbt_rejects_fee_above_max_only() {
        let builder = fixture_builder();
        let utxo = fixture_outpoint();
        let dest = fixture_dest();

        // Exactly MAX_FEE_SATS is allowed (the `>` check is strict).
        // Use a large enough utxo to leave output above dust.
        assert!(
            builder
                .build_recovery_psbt(0, utxo, MAX_FEE_SATS + 1_000, &dest, MAX_FEE_SATS)
                .is_ok(),
            "fee exactly at the MAX_FEE_SATS cap must be allowed"
        );

        // One sat above the cap is refused.
        let err = builder
            .build_recovery_psbt(0, utxo, MAX_FEE_SATS + 2_000, &dest, MAX_FEE_SATS + 1)
            .unwrap_err();
        assert!(err.to_string().contains("exceeds maximum"));
    }

    /// `utxo_value <= fee_sats` means we have no output value left after
    /// paying the fee. The `<` ↔ `==` or `<=` mutation would either
    /// silently accept a zero-output transaction (which is non-standard)
    /// or refuse the legitimate one-sat-above-fee case.
    #[test]
    fn build_recovery_psbt_rejects_when_fee_equals_or_exceeds_utxo_value() {
        let builder = fixture_builder();
        let utxo = fixture_outpoint();
        let dest = fixture_dest();

        // fee == utxo_value: output value is zero, refused.
        let err = builder
            .build_recovery_psbt(0, utxo, 1_000, &dest, 1_000)
            .unwrap_err();
        assert!(err.to_string().contains("insufficient funds"));

        // fee > utxo_value: also refused.
        let err = builder
            .build_recovery_psbt(0, utxo, 1_000, &dest, 1_001)
            .unwrap_err();
        assert!(err.to_string().contains("insufficient funds"));
    }

    /// The dust threshold check is strict: an output of EXACTLY
    /// TAPROOT_DUST_LIMIT_SATS is allowed; one below is refused. A `<` ↔
    /// `==` or `<=` mutation would either refuse the legal exactly-dust
    /// boundary (defeating recovery on tight budgets) or accept a
    /// 1-sat-below-dust output (producing a non-standard tx that
    /// mempool would reject anyway, but the call still succeeds).
    #[test]
    fn build_recovery_psbt_dust_boundary_is_strict() {
        let builder = fixture_builder();
        let utxo = fixture_outpoint();
        let dest = fixture_dest();

        // output == dust limit: allowed.
        let utxo_value = TAPROOT_DUST_LIMIT_SATS + 100;
        let fee = 100;
        assert!(
            builder
                .build_recovery_psbt(0, utxo, utxo_value, &dest, fee)
                .is_ok(),
            "output exactly at dust limit must be allowed"
        );

        // output == dust limit - 1: refused.
        let utxo_value = TAPROOT_DUST_LIMIT_SATS + 100;
        let fee = 101;
        let err = builder
            .build_recovery_psbt(0, utxo, utxo_value, &dest, fee)
            .unwrap_err();
        assert!(err.to_string().contains("dust threshold"));
    }

    /// Same three boundary invariants for `build_sweep_psbt`: fee cap,
    /// insufficient funds, dust. The sweep path has its own surviving
    /// mutations on each, and an authorized proposer attacks the sweep
    /// path the same way as the single-input recovery path.
    #[test]
    fn build_sweep_psbt_rejects_fee_above_max_only() {
        let builder = fixture_builder();
        let dest = fixture_dest();
        let utxos = vec![SweepUtxo {
            outpoint: fixture_outpoint(),
            value_sats: MAX_FEE_SATS + 1_000,
        }];

        // Exactly at the cap: allowed.
        assert!(builder
            .build_sweep_psbt(0, &utxos, &dest, MAX_FEE_SATS)
            .is_ok());

        // One above: refused.
        let err = builder
            .build_sweep_psbt(0, &utxos, &dest, MAX_FEE_SATS + 1)
            .unwrap_err();
        assert!(err.to_string().contains("exceeds maximum"));
    }

    /// `build_sweep_psbt` insufficient-funds boundary: pin `<= fee` is
    /// rejected and `> fee` accepted (when above dust).
    #[test]
    fn build_sweep_psbt_rejects_when_total_inputs_equal_or_below_fee() {
        let builder = fixture_builder();
        let dest = fixture_dest();

        // total == fee: refused.
        let utxos = vec![SweepUtxo {
            outpoint: fixture_outpoint(),
            value_sats: 1_000,
        }];
        let err = builder
            .build_sweep_psbt(0, &utxos, &dest, 1_000)
            .unwrap_err();
        assert!(err.to_string().contains("insufficient funds"));

        // total > fee but output below dust: surfaces the dust error
        // (not the insufficient-funds error). Pin both for clarity.
        let utxos = vec![SweepUtxo {
            outpoint: fixture_outpoint(),
            value_sats: 1_000,
        }];
        let err = builder
            .build_sweep_psbt(0, &utxos, &dest, 1_000 - (TAPROOT_DUST_LIMIT_SATS - 1))
            .unwrap_err();
        assert!(err.to_string().contains("dust threshold"));
    }

    /// Pins only the `MissingWitnessUtxo` early return: a PSBT with the
    /// witness_utxo stripped is rejected before any of the three binding
    /// checks run. The checks themselves are pinned by the dedicated
    /// success and negative tests below.
    #[test]
    fn verify_script_spend_input_binding_refuses_psbt_with_no_witness_utxo() {
        let builder = fixture_builder();
        let utxo = fixture_outpoint();
        let dest = fixture_dest();
        let (_, local_pk) = test_keypair_full(2);

        // Build a valid recovery PSBT, then strip the witness_utxo.
        let mut psbt = builder
            .build_recovery_psbt(0, utxo, 100_000, &dest, 1_000)
            .unwrap();
        psbt.inputs[0].witness_utxo = None;

        let result = verify_script_spend_input_binding(&psbt, 0, &local_pk);
        assert!(
            result.is_err(),
            "missing witness_utxo must surface a binding error"
        );
    }

    /// Success path: a PSBT built by the real builder passes all three
    /// security checks (P2TR witness_utxo, control block commits to the
    /// output key, leaf script references the local x-only key) and
    /// returns the verified sighash bundle. This drives every `!`-negated
    /// guard through its accept branch, so a `delete !` mutation on any of
    /// them flips this success into a failure.
    #[test]
    fn verify_script_spend_input_binding_accepts_valid_psbt() {
        let builder = fixture_builder();
        let utxo = fixture_outpoint();
        let dest = fixture_dest();
        let (_, local_pk) = test_keypair_full(2);

        let psbt = builder
            .build_recovery_psbt(0, utxo, 100_000, &dest, 1_000)
            .unwrap();

        let bundle = verify_script_spend_input_binding(&psbt, 0, &local_pk).unwrap();
        assert_eq!(bundle.input_index, 0);
    }

    /// Trips the P2TR check: a witness_utxo whose script_pubkey is not a
    /// 34-byte P2TR output is rejected. A `delete !` on the `!is_p2tr()`
    /// guard would accept a non-P2TR output.
    #[test]
    fn verify_script_spend_input_binding_rejects_non_p2tr_witness_utxo() {
        let builder = fixture_builder();
        let utxo = fixture_outpoint();
        let dest = fixture_dest();
        let (_, local_pk) = test_keypair_full(2);

        let mut psbt = builder
            .build_recovery_psbt(0, utxo, 100_000, &dest, 1_000)
            .unwrap();
        psbt.inputs[0].witness_utxo = Some(TxOut {
            value: Amount::from_sat(100_000),
            script_pubkey: ScriptBuf::new(),
        });

        let err = verify_script_spend_input_binding(&psbt, 0, &local_pk).unwrap_err();
        assert!(err.to_string().contains("not a P2TR output"));
    }

    /// Trips the taproot-commitment check: a valid P2TR witness_utxo whose
    /// output key differs from the one the tap_scripts control block
    /// commits to is rejected. A `delete !` on
    /// `!verify_taproot_commitment(...)` would accept a leaf that isn't
    /// part of the spent output's taproot tree.
    #[test]
    fn verify_script_spend_input_binding_rejects_uncommitted_control_block() {
        let builder = fixture_builder();
        let utxo = fixture_outpoint();
        let dest = fixture_dest();
        let (_, local_pk) = test_keypair_full(2);

        let mut psbt = builder
            .build_recovery_psbt(0, utxo, 100_000, &dest, 1_000)
            .unwrap();
        // Swap in a valid but unrelated P2TR output key; the control
        // block no longer commits to it.
        let (_, other_pk) = test_keypair_full(9);
        let other_xonly = XOnlyPublicKey::from_slice(&other_pk).unwrap();
        psbt.inputs[0].witness_utxo = Some(TxOut {
            value: Amount::from_sat(100_000),
            script_pubkey: ScriptBuf::new_p2tr(&Secp256k1::new(), other_xonly, None),
        });

        let err = verify_script_spend_input_binding(&psbt, 0, &local_pk).unwrap_err();
        assert!(err.to_string().contains("does not commit"));
    }

    /// Trips the leaf-key check: even with a valid P2TR witness_utxo and a
    /// committing control block, a local x-only key absent from the leaf
    /// script is rejected. A `delete !` on `!script_contains_xonly(...)`
    /// would let a malicious proposer bind the responder to an unrelated
    /// leaf.
    #[test]
    fn verify_script_spend_input_binding_rejects_local_key_absent_from_leaf() {
        let builder = fixture_builder();
        let utxo = fixture_outpoint();
        let dest = fixture_dest();
        // Key 9 participates in no tier built by fixture_builder.
        let (_, absent_pk) = test_keypair_full(9);

        let psbt = builder
            .build_recovery_psbt(0, utxo, 100_000, &dest, 1_000)
            .unwrap();

        let err = verify_script_spend_input_binding(&psbt, 0, &absent_pk).unwrap_err();
        assert!(err
            .to_string()
            .contains("does not reference the local responder"));
    }

    /// `script_contains_xonly` is a small but security-critical helper:
    /// it scans a tap-script's pushdata for a 32-byte x-only key. A
    /// `true`/`false`-return regression silently accepts any key as
    /// present (or none); an `==` ↔ `!=` regression would match every
    /// non-matching key.
    #[test]
    fn script_contains_xonly_only_matches_exact_32_byte_pushdata() {
        let key_a = [0xAAu8; 32];
        let key_b = [0xBBu8; 32];

        // Script containing key_a as a pushdata.
        let script_a = bitcoin::ScriptBuf::builder()
            .push_slice(key_a)
            .into_script();
        assert!(script_contains_xonly(&script_a, &key_a));
        assert!(!script_contains_xonly(&script_a, &key_b));

        // Empty script never matches.
        let empty = bitcoin::ScriptBuf::new();
        assert!(!script_contains_xonly(&empty, &key_a));
    }
}