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
// SPDX-FileCopyrightText: © 2026 PrivKey LLC
// SPDX-License-Identifier: MIT
use crate::error::{BitcoinError, Result};
use bitcoin::key::Secp256k1;
use bitcoin::secp256k1::All;
use bitcoin::taproot::{LeafVersion, TaprootBuilder, TaprootSpendInfo};
use bitcoin::{Address, Network, ScriptBuf, Sequence, TapLeafHash, XOnlyPublicKey};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

const BLOCKS_PER_DAY: u32 = 144;
const BLOCKS_PER_MONTH: u32 = BLOCKS_PER_DAY * 30;
const MAX_KEYS_PER_TIER: usize = 20;
const MAX_RECOVERY_TIERS: usize = 10;
const MAX_CSV_BLOCKS: u32 = 0xFFFF;

// BIP-341 unspendable internal key (no known discrete log).
const NUMS_POINT: [u8; 32] = [
    0x50, 0x92, 0x9b, 0x74, 0xc1, 0xa0, 0x49, 0x54, 0xb7, 0x8b, 0x4b, 0x60, 0x35, 0xe9, 0x7a, 0x5e,
    0x07, 0x8a, 0x5a, 0x0f, 0x28, 0xec, 0x96, 0xd5, 0x47, 0xbf, 0xee, 0x9a, 0xce, 0x80, 0x3a, 0xc0,
];

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RecoveryConfig {
    pub primary: SpendingTier,
    pub recovery_tiers: Vec<RecoveryTier>,
    pub network: Network,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SpendingTier {
    pub keys: Vec<[u8; 32]>,
    pub threshold: u32,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RecoveryTier {
    pub keys: Vec<[u8; 32]>,
    pub threshold: u32,
    pub timelock_months: u32,
}

#[derive(Clone, Debug)]
pub struct RecoveryOutput {
    pub address: Address,
    pub spend_info: TaprootSpendInfo,
    pub descriptor: String,
    pub tiers: Vec<TierInfo>,
}

#[derive(Clone, Debug)]
pub struct TierInfo {
    pub name: String,
    pub script: ScriptBuf,
    pub leaf_hash: TapLeafHash,
    pub timelock_blocks: Option<u32>,
    pub threshold: u32,
    pub keys: Vec<XOnlyPublicKey>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PolicyInput {
    pub primary: PolicyTierInput,
    pub recovery_tiers: Vec<PolicyTierInput>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PolicyTierInput {
    pub threshold: u32,
    pub timelock_months: u32,
    pub keys: Vec<[u8; 32]>,
}

impl RecoveryConfig {
    pub fn from_policy_input(input: &PolicyInput, network: Network) -> Result<Self> {
        let primary = SpendingTier {
            keys: input.primary.keys.clone(),
            threshold: input.primary.threshold,
        };

        let recovery_tiers = input
            .recovery_tiers
            .iter()
            .map(|tier| RecoveryTier {
                keys: tier.keys.clone(),
                threshold: tier.threshold,
                timelock_months: tier.timelock_months,
            })
            .collect();

        let config = Self {
            primary,
            recovery_tiers,
            network,
        };
        config.validate()?;
        Ok(config)
    }

    pub fn validate(&self) -> Result<()> {
        if self.primary.keys.is_empty() {
            return Err(BitcoinError::Recovery("primary tier has no keys".into()));
        }
        if self.primary.keys.len() > MAX_KEYS_PER_TIER {
            return Err(BitcoinError::Recovery(format!(
                "primary tier exceeds {MAX_KEYS_PER_TIER} keys"
            )));
        }
        if self.primary.threshold == 0 || self.primary.threshold > self.primary.keys.len() as u32 {
            return Err(BitcoinError::Recovery("invalid primary threshold".into()));
        }
        check_duplicate_keys("primary", &self.primary.keys)?;

        if self.recovery_tiers.is_empty() {
            return Err(BitcoinError::Recovery(
                "at least one recovery tier is required".into(),
            ));
        }
        if self.recovery_tiers.len() > MAX_RECOVERY_TIERS {
            return Err(BitcoinError::Recovery(format!(
                "recovery tier count {} exceeds maximum {}",
                self.recovery_tiers.len(),
                MAX_RECOVERY_TIERS
            )));
        }

        // Key reuse across tiers is intentionally allowed (#425). Taproot's
        // design encodes recovery semantics in the script tree, not in key
        // independence: the same xpub appearing in `2-of-3 @ 1mo` and
        // `1-of-3 @ 6mo` serves distinct roles via distinct leaves with
        // distinct CSV locks. Within-tier duplicates are still rejected
        // because those would silently collapse a k-of-n threshold to
        // k-of-(n-1), which is a real correctness bug, not a key-reuse policy.
        for (i, tier) in self.recovery_tiers.iter().enumerate() {
            if tier.keys.is_empty() {
                return Err(BitcoinError::Recovery(format!(
                    "recovery tier {i} has no keys"
                )));
            }
            if tier.keys.len() > MAX_KEYS_PER_TIER {
                return Err(BitcoinError::Recovery(format!(
                    "recovery tier {i} exceeds {MAX_KEYS_PER_TIER} keys"
                )));
            }
            if tier.threshold == 0 || tier.threshold > tier.keys.len() as u32 {
                return Err(BitcoinError::Recovery(format!(
                    "invalid threshold for recovery tier {i}"
                )));
            }
            if tier.timelock_months == 0 {
                return Err(BitcoinError::Recovery(format!(
                    "recovery tier {i} must have nonzero timelock"
                )));
            }
            let timelock_blocks = months_to_blocks(tier.timelock_months)?;
            if timelock_blocks > MAX_CSV_BLOCKS {
                return Err(BitcoinError::Recovery(format!(
                    "recovery tier {} timelock {} months ({} blocks) exceeds CSV maximum {}",
                    i, tier.timelock_months, timelock_blocks, MAX_CSV_BLOCKS
                )));
            }
            check_duplicate_keys(&format!("recovery tier {i}"), &tier.keys)?;
        }
        for w in self.recovery_tiers.windows(2) {
            if w[1].timelock_months <= w[0].timelock_months {
                return Err(BitcoinError::Recovery(
                    "recovery tiers must have increasing timelocks".into(),
                ));
            }
        }
        Ok(())
    }

    pub fn build(&self) -> Result<RecoveryOutput> {
        self.validate()?;
        let secp = Secp256k1::new();
        let tiers = self.build_tier_infos()?;
        let internal_key = self.internal_key()?;
        let depths = optimal_depth(tiers.len());
        let spend_info = self.build_taproot(&secp, internal_key, &tiers, &depths)?;
        let address = Address::p2tr_tweaked(spend_info.output_key(), self.network);
        let descriptor = self.format_descriptor(internal_key, &tiers, &depths);

        Ok(RecoveryOutput {
            address,
            spend_info,
            descriptor,
            tiers,
        })
    }

    pub fn build_with_internal_key(&self, internal_key: &XOnlyPublicKey) -> Result<RecoveryOutput> {
        self.validate()?;
        let secp = Secp256k1::new();
        let tiers = self.build_tier_infos()?;
        let depths = optimal_depth(tiers.len());
        let spend_info = self.build_taproot(&secp, *internal_key, &tiers, &depths)?;
        let address = Address::p2tr_tweaked(spend_info.output_key(), self.network);
        let descriptor = self.format_descriptor(*internal_key, &tiers, &depths);

        Ok(RecoveryOutput {
            address,
            spend_info,
            descriptor,
            tiers,
        })
    }

    fn internal_key(&self) -> Result<XOnlyPublicKey> {
        if self.primary.keys.len() == 1 && self.primary.threshold == 1 {
            return parse_xonly(&self.primary.keys[0]);
        }
        XOnlyPublicKey::from_slice(&NUMS_POINT)
            .map_err(|e| BitcoinError::Recovery(format!("NUMS point: {e}")))
    }

    fn build_tier_infos(&self) -> Result<Vec<TierInfo>> {
        let mut tiers = Vec::new();

        if self.primary.keys.len() > 1 || self.primary.threshold > 1 {
            let pubkeys = parse_xonly_keys(&self.primary.keys)?;
            let script = build_multisig_script(&self.primary.keys, self.primary.threshold)?;
            tiers.push(TierInfo {
                name: "primary".to_string(),
                leaf_hash: TapLeafHash::from_script(&script, LeafVersion::TapScript),
                script,
                timelock_blocks: None,
                threshold: self.primary.threshold,
                keys: pubkeys,
            });
        }

        for (i, tier) in self.recovery_tiers.iter().enumerate() {
            let timelock_blocks = months_to_blocks(tier.timelock_months)?;
            let pubkeys = parse_xonly_keys(&tier.keys)?;
            let script = build_timelocked_multisig(&tier.keys, tier.threshold, timelock_blocks)?;
            tiers.push(TierInfo {
                name: format!("recovery_{}", i + 1),
                leaf_hash: TapLeafHash::from_script(&script, LeafVersion::TapScript),
                script,
                timelock_blocks: Some(timelock_blocks),
                threshold: tier.threshold,
                keys: pubkeys,
            });
        }

        Ok(tiers)
    }

    fn build_taproot(
        &self,
        secp: &Secp256k1<All>,
        internal_key: XOnlyPublicKey,
        tiers: &[TierInfo],
        depths: &[u8],
    ) -> Result<TaprootSpendInfo> {
        if tiers.is_empty() {
            return TaprootBuilder::new()
                .finalize(secp, internal_key)
                .map_err(|e| BitcoinError::Recovery(format!("taproot finalize: {e:?}")));
        }

        debug_assert_eq!(tiers.len(), depths.len());
        let mut builder = TaprootBuilder::new();

        for (i, tier) in tiers.iter().enumerate() {
            builder = builder
                .add_leaf(depths[i], tier.script.clone())
                .map_err(|e| BitcoinError::Recovery(format!("add leaf: {e:?}")))?;
        }

        builder
            .finalize(secp, internal_key)
            .map_err(|e| BitcoinError::Recovery(format!("taproot finalize: {e:?}")))
    }

    fn format_descriptor(
        &self,
        internal_key: XOnlyPublicKey,
        tiers: &[TierInfo],
        depths: &[u8],
    ) -> String {
        if tiers.is_empty() {
            return format!("tr({internal_key})");
        }
        debug_assert_eq!(tiers.len(), depths.len());
        let leaves: Vec<String> = tiers.iter().map(tier_miniscript).collect();
        let tree = build_tree_string(&leaves, depths);
        format!("tr({internal_key},{tree})")
    }
}

fn tier_miniscript(tier: &TierInfo) -> String {
    let inner = if tier.keys.len() == 1 && tier.threshold == 1 {
        format!("pk({})", tier.keys[0])
    } else {
        let keys = tier
            .keys
            .iter()
            .map(XOnlyPublicKey::to_string)
            .collect::<Vec<_>>()
            .join(",");
        format!("multi_a({},{keys})", tier.threshold)
    };
    match tier.timelock_blocks {
        Some(blocks) => format!("and_v(v:older({blocks}),{inner})"),
        None => inner,
    }
}

fn build_tree_string(leaves: &[String], depths: &[u8]) -> String {
    debug_assert_eq!(leaves.len(), depths.len());
    let mut stack: Vec<(u8, String)> = Vec::with_capacity(leaves.len());
    for (leaf, &d) in leaves.iter().zip(depths) {
        stack.push((d, leaf.clone()));
        while stack.len() >= 2 && stack[stack.len() - 1].0 == stack[stack.len() - 2].0 {
            let (d_top, s_top) = stack.pop().expect("len >= 2");
            let (_, s_second) = stack.pop().expect("len >= 2");
            stack.push((d_top.saturating_sub(1), format!("{{{s_second},{s_top}}}")));
        }
    }
    stack.pop().map(|(_, s)| s).unwrap_or_default()
}

fn build_multisig_script(keys: &[[u8; 32]], threshold: u32) -> Result<ScriptBuf> {
    let pubkeys: Vec<XOnlyPublicKey> = keys.iter().map(parse_xonly).collect::<Result<Vec<_>>>()?;

    let mut builder = ScriptBuf::builder();
    builder = push_checksig_chain(builder, &pubkeys);

    if needs_threshold_check(threshold, pubkeys.len()) {
        builder = builder
            .push_int(threshold as i64)
            .push_opcode(bitcoin::opcodes::all::OP_NUMEQUAL);
    }

    Ok(builder.into_script())
}

fn build_timelocked_multisig(
    keys: &[[u8; 32]],
    threshold: u32,
    timelock_blocks: u32,
) -> Result<ScriptBuf> {
    let seq_u16 = u16::try_from(timelock_blocks).map_err(|_| {
        BitcoinError::Recovery(format!(
            "timelock {timelock_blocks} exceeds CSV maximum {MAX_CSV_BLOCKS}"
        ))
    })?;

    let pubkeys: Vec<XOnlyPublicKey> = keys.iter().map(parse_xonly).collect::<Result<Vec<_>>>()?;

    // v0.4+: OP_VERIFY form per miniscript canonical older(n);
    // v0.3.x recovery addresses (OP_DROP form) are incompatible and must be
    // swept externally before upgrading.
    let mut builder = ScriptBuf::builder()
        .push_sequence(Sequence::from_height(seq_u16))
        .push_opcode(bitcoin::opcodes::all::OP_CSV)
        .push_opcode(bitcoin::opcodes::all::OP_VERIFY);

    builder = push_checksig_chain(builder, &pubkeys);

    if needs_threshold_check(threshold, pubkeys.len()) {
        builder = builder
            .push_int(threshold as i64)
            .push_opcode(bitcoin::opcodes::all::OP_NUMEQUAL);
    }

    Ok(builder.into_script())
}

fn push_checksig_chain(
    mut builder: bitcoin::script::Builder,
    pubkeys: &[XOnlyPublicKey],
) -> bitcoin::script::Builder {
    for (i, pk) in pubkeys.iter().enumerate() {
        builder = builder.push_x_only_key(pk);
        if i == 0 {
            builder = builder.push_opcode(bitcoin::opcodes::all::OP_CHECKSIG);
        } else {
            builder = builder.push_opcode(bitcoin::opcodes::all::OP_CHECKSIGADD);
        }
    }
    builder
}

fn parse_xonly(bytes: &[u8; 32]) -> Result<XOnlyPublicKey> {
    XOnlyPublicKey::from_slice(bytes).map_err(|e| BitcoinError::InvalidPublicKey(e.to_string()))
}

fn parse_xonly_keys(keys: &[[u8; 32]]) -> Result<Vec<XOnlyPublicKey>> {
    keys.iter().map(parse_xonly).collect()
}

fn needs_threshold_check(threshold: u32, key_count: usize) -> bool {
    threshold > 1 || key_count > 1
}

fn check_duplicate_keys(tier_name: &str, keys: &[[u8; 32]]) -> Result<()> {
    let mut seen = HashSet::with_capacity(keys.len());
    for key in keys {
        if !seen.insert(key) {
            return Err(BitcoinError::Recovery(format!(
                "duplicate key in {}: {}",
                tier_name,
                hex::encode(key)
            )));
        }
    }
    Ok(())
}

fn optimal_depth(count: usize) -> Vec<u8> {
    match count {
        0 => vec![],
        1 => vec![0],
        _ => {
            let depth = (usize::BITS - (count - 1).leading_zeros()) as u8;
            let full_capacity = 1usize << depth;
            let shallow_count = full_capacity - count;
            (0..count)
                .map(|i| if i < shallow_count { depth - 1 } else { depth })
                .collect()
        }
    }
}

pub fn recovery_sequence(timelock_blocks: u32) -> Result<Sequence> {
    let blocks_u16 = u16::try_from(timelock_blocks).map_err(|_| {
        BitcoinError::Recovery(format!(
            "timelock {timelock_blocks} exceeds maximum relative lock height 65535"
        ))
    })?;
    Ok(Sequence::from_height(blocks_u16))
}

pub fn months_to_blocks(months: u32) -> Result<u32> {
    months.checked_mul(BLOCKS_PER_MONTH).ok_or_else(|| {
        BitcoinError::Recovery(format!("timelock {months} months overflows block count"))
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use bitcoin::secp256k1::{Keypair, Secp256k1};

    fn test_keypair(seed: u8) -> [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();
        kp.x_only_public_key().0.serialize()
    }

    #[test]
    fn test_single_key_primary_with_recovery() {
        let pk1 = test_keypair(1);
        let pk2 = test_keypair(2);
        let pk3 = test_keypair(3);

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

        let output = config.build().unwrap();
        assert!(output.address.to_string().starts_with("tb1p"));
        assert_eq!(output.tiers.len(), 1);
        assert_eq!(output.tiers[0].timelock_blocks, Some(6 * BLOCKS_PER_MONTH));
    }

    #[test]
    fn test_multisig_primary_with_two_recovery_tiers() {
        let keys: Vec<[u8; 32]> = (1..=9).map(test_keypair).collect();

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![keys[0], keys[1], keys[2]],
                threshold: 2,
            },
            recovery_tiers: vec![
                RecoveryTier {
                    keys: vec![keys[3], keys[4], keys[5], keys[6], keys[7]],
                    threshold: 3,
                    timelock_months: 6,
                },
                RecoveryTier {
                    keys: vec![keys[8]],
                    threshold: 1,
                    timelock_months: 12,
                },
            ],
            network: Network::Testnet,
        };

        let output = config.build().unwrap();
        assert!(output.address.to_string().starts_with("tb1p"));
        assert_eq!(output.tiers.len(), 3);
        assert!(output.tiers[0].timelock_blocks.is_none());
        assert_eq!(output.tiers[1].timelock_blocks, Some(6 * BLOCKS_PER_MONTH));
        assert_eq!(output.tiers[2].timelock_blocks, Some(12 * BLOCKS_PER_MONTH));
    }

    #[test]
    fn test_validation_errors() {
        let pk = test_keypair(1);
        let pk2 = test_keypair(2);
        let pk3 = test_keypair(3);
        let pk4 = test_keypair(4);

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![],
                threshold: 1,
            },
            recovery_tiers: vec![],
            network: Network::Testnet,
        };
        assert!(config.validate().is_err());

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk],
                threshold: 1,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2],
                threshold: 1,
                timelock_months: 0,
            }],
            network: Network::Testnet,
        };
        assert!(config.validate().is_err());

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk],
                threshold: 1,
            },
            recovery_tiers: vec![
                RecoveryTier {
                    keys: vec![pk3],
                    threshold: 1,
                    timelock_months: 12,
                },
                RecoveryTier {
                    keys: vec![pk4],
                    threshold: 1,
                    timelock_months: 6,
                },
            ],
            network: Network::Testnet,
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_descriptor_format() {
        let pk1 = test_keypair(1);
        let pk2 = test_keypair(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();
        assert!(output.descriptor.starts_with("tr("));
        assert!(output.descriptor.contains("older("));
    }

    #[test]
    fn test_descriptor_parses_as_miniscript() {
        use bitcoin::secp256k1::Secp256k1;
        use miniscript::Descriptor;

        let keys: Vec<[u8; 32]> = (1..=12).map(test_keypair).collect();
        let cases = vec![
            RecoveryConfig {
                primary: SpendingTier {
                    keys: vec![keys[0]],
                    threshold: 1,
                },
                recovery_tiers: vec![RecoveryTier {
                    keys: vec![keys[1]],
                    threshold: 1,
                    timelock_months: 6,
                }],
                network: Network::Testnet,
            },
            RecoveryConfig {
                primary: SpendingTier {
                    keys: vec![keys[0], keys[1], keys[2]],
                    threshold: 2,
                },
                recovery_tiers: vec![
                    RecoveryTier {
                        keys: vec![keys[3], keys[4]],
                        threshold: 2,
                        timelock_months: 6,
                    },
                    RecoveryTier {
                        keys: vec![keys[5]],
                        threshold: 1,
                        timelock_months: 12,
                    },
                ],
                network: Network::Testnet,
            },
            RecoveryConfig {
                primary: SpendingTier {
                    keys: vec![keys[0], keys[1]],
                    threshold: 2,
                },
                recovery_tiers: vec![
                    RecoveryTier {
                        keys: vec![keys[2]],
                        threshold: 1,
                        timelock_months: 6,
                    },
                    RecoveryTier {
                        keys: vec![keys[3]],
                        threshold: 1,
                        timelock_months: 12,
                    },
                ],
                network: Network::Testnet,
            },
            RecoveryConfig {
                primary: SpendingTier {
                    keys: vec![keys[0], keys[1]],
                    threshold: 2,
                },
                recovery_tiers: vec![
                    RecoveryTier {
                        keys: vec![keys[2]],
                        threshold: 1,
                        timelock_months: 3,
                    },
                    RecoveryTier {
                        keys: vec![keys[3]],
                        threshold: 1,
                        timelock_months: 6,
                    },
                    RecoveryTier {
                        keys: vec![keys[4]],
                        threshold: 1,
                        timelock_months: 9,
                    },
                    RecoveryTier {
                        keys: vec![keys[5]],
                        threshold: 1,
                        timelock_months: 12,
                    },
                ],
                network: Network::Testnet,
            },
        ];

        let _ = Secp256k1::new();
        for config in cases {
            let output = config.build().unwrap();
            let desc: Descriptor<miniscript::DescriptorPublicKey> = output
                .descriptor
                .parse()
                .unwrap_or_else(|e| panic!("parse failed for {}: {e}", output.descriptor));
            let parsed_spk = desc.at_derivation_index(0).unwrap().script_pubkey();
            let expected_spk = bitcoin::ScriptBuf::new_p2tr_tweaked(output.spend_info.output_key());
            assert_eq!(
                parsed_spk, expected_spk,
                "miniscript-derived scriptPubKey mismatches TaprootBuilder output for {}",
                output.descriptor
            );
        }
    }

    #[test]
    fn test_timelock_script_structure() {
        let pk = test_keypair(1);
        let blocks = months_to_blocks(6).unwrap();

        let script = build_timelocked_multisig(&[pk], 1, blocks).unwrap();

        let asm = script.to_asm_string();
        assert!(asm.contains("OP_CSV"));
        assert!(asm.contains("OP_VERIFY"));
        assert!(asm.contains("OP_CHECKSIG"));
    }

    #[test]
    fn test_months_to_blocks() {
        assert_eq!(months_to_blocks(6).unwrap(), 6 * 144 * 30);
        assert_eq!(months_to_blocks(12).unwrap(), 12 * 144 * 30);
    }

    #[test]
    fn test_months_to_blocks_overflow() {
        assert!(months_to_blocks(u32::MAX).is_err());
    }

    #[test]
    fn test_recovery_sequence() {
        let seq = recovery_sequence(25920).unwrap();
        assert!(seq.is_relative_lock_time());
    }

    #[test]
    fn test_recovery_sequence_overflow() {
        assert!(recovery_sequence(70000).is_err());
    }

    #[test]
    fn test_optimal_depth_valid_trees() {
        for count in 1..=10 {
            let depths = optimal_depth(count);
            assert_eq!(depths.len(), count);

            let mut builder = TaprootBuilder::new();
            let secp = Secp256k1::new();
            let pk = test_keypair(1);
            let xonly = XOnlyPublicKey::from_slice(&pk).unwrap();
            let script = ScriptBuf::builder()
                .push_x_only_key(&xonly)
                .push_opcode(bitcoin::opcodes::all::OP_CHECKSIG)
                .into_script();

            for &d in &depths {
                builder = builder.add_leaf(d, script.clone()).unwrap();
            }
            let internal = XOnlyPublicKey::from_slice(&NUMS_POINT).unwrap();
            assert!(builder.finalize(&secp, internal).is_ok());
        }
    }

    #[test]
    fn test_nums_internal_key_for_multisig() {
        let pk1 = test_keypair(1);
        let pk2 = test_keypair(2);
        let pk3 = test_keypair(3);

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

        let output = config.build().unwrap();
        assert!(output.address.to_string().starts_with("tb1p"));
        assert_eq!(output.tiers.len(), 2);
        assert_eq!(output.tiers[0].name, "primary");
    }

    #[test]
    fn test_multisig_script_uses_numequal() {
        let pk1 = test_keypair(1);
        let pk2 = test_keypair(2);
        let pk3 = test_keypair(3);

        let script = build_multisig_script(&[pk1, pk2, pk3], 2).unwrap();
        let asm = script.to_asm_string();
        assert!(asm.contains("OP_NUMEQUAL"));
        assert!(!asm.contains("OP_NUMEQUALVERIFY"));
    }

    #[test]
    fn test_key_count_limit() {
        let keys: Vec<[u8; 32]> = (1..=21).map(|i| test_keypair(i as u8)).collect();
        let recovery_pk = test_keypair(100);

        let config = RecoveryConfig {
            primary: SpendingTier { keys, threshold: 1 },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![recovery_pk],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_tier_info_has_threshold_and_keys() {
        let pk1 = test_keypair(1);
        let pk2 = test_keypair(2);
        let pk3 = test_keypair(3);

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

        let output = config.build().unwrap();
        assert_eq!(output.tiers[0].threshold, 2);
        assert_eq!(output.tiers[0].keys.len(), 2);
    }

    #[test]
    fn test_duplicate_keys_within_tier() {
        let pk = test_keypair(1);
        let pk2 = test_keypair(2);

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk, pk],
                threshold: 2,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn key_reuse_across_tiers_now_allowed() {
        // #425: taproot encodes recovery semantics in the script tree, not in
        // key independence. WDC participants auto-contribute one xpub each, so
        // multi-tier proposals legitimately reuse the same xpubs across the
        // primary and recovery tiers. Previously the validator rejected this
        // with "duplicate key across tiers", blocking any multi-tier WDC flow.
        let pk = test_keypair(1);
        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk],
                threshold: 1,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };
        config
            .validate()
            .expect("identical key across primary + recovery tier must validate");
    }

    #[test]
    fn key_reuse_across_multi_tier_recovery_now_allowed() {
        // The real WDC shape: each share-holder contributes one xpub, and the
        // same N xpubs appear in both `2-of-3 @ 1mo` and `1-of-3 @ 6mo`.
        let a = test_keypair(1);
        let b = test_keypair(2);
        let c = test_keypair(3);

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![a, b, c],
                threshold: 3,
            },
            recovery_tiers: vec![
                RecoveryTier {
                    keys: vec![a, b, c],
                    threshold: 2,
                    timelock_months: 1,
                },
                RecoveryTier {
                    keys: vec![a, b, c],
                    threshold: 1,
                    timelock_months: 6,
                },
            ],
            network: Network::Testnet,
        };
        config
            .validate()
            .expect("multi-tier WDC shape with reused xpubs must validate");
        config
            .build()
            .expect("the descriptor must still build under reused xpubs");
    }

    #[test]
    fn within_tier_duplicate_still_rejected_in_recovery() {
        // The within-tier check is the real correctness invariant: duplicate
        // keys inside one tier silently collapse a k-of-n threshold to
        // k-of-(n-1). Pinning this so the #425 relaxation doesn't accidentally
        // weaken it.
        let pk = test_keypair(1);
        let pk2 = test_keypair(2);
        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk, pk2],
                threshold: 2,
            },
            recovery_tiers: vec![RecoveryTier {
                keys: vec![pk2, pk2],
                threshold: 1,
                timelock_months: 6,
            }],
            network: Network::Testnet,
        };
        let err = config.validate().expect_err("within-tier dup must fail");
        assert!(
            err.to_string().to_lowercase().contains("duplicate"),
            "got {err}"
        );
    }

    #[test]
    fn test_empty_recovery_tiers_rejected() {
        let pk = test_keypair(1);

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk],
                threshold: 1,
            },
            recovery_tiers: vec![],
            network: Network::Testnet,
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_from_policy_input_single_tier() {
        let pk1 = test_keypair(1);
        let pk2 = test_keypair(2);
        let pk3 = test_keypair(3);

        let input = PolicyInput {
            primary: PolicyTierInput {
                threshold: 1,
                timelock_months: 0,
                keys: vec![pk1],
            },
            recovery_tiers: vec![PolicyTierInput {
                threshold: 1,
                timelock_months: 6,
                keys: vec![pk2, pk3],
            }],
        };

        let config = RecoveryConfig::from_policy_input(&input, Network::Testnet).unwrap();
        assert_eq!(config.primary.keys.len(), 1);
        assert_eq!(config.primary.threshold, 1);
        assert_eq!(config.recovery_tiers.len(), 1);
        assert_eq!(config.recovery_tiers[0].keys.len(), 2);
        assert_eq!(config.recovery_tiers[0].threshold, 1);
        assert_eq!(config.recovery_tiers[0].timelock_months, 6);

        let output = config.build().unwrap();
        assert!(output.address.to_string().starts_with("tb1p"));
    }

    #[test]
    fn test_from_policy_input_multi_tier() {
        let keys: Vec<[u8; 32]> = (1..=7).map(test_keypair).collect();

        let input = PolicyInput {
            primary: PolicyTierInput {
                threshold: 2,
                timelock_months: 0,
                keys: vec![keys[0], keys[1], keys[2]],
            },
            recovery_tiers: vec![
                PolicyTierInput {
                    threshold: 2,
                    timelock_months: 6,
                    keys: vec![keys[3], keys[4]],
                },
                PolicyTierInput {
                    threshold: 1,
                    timelock_months: 12,
                    keys: vec![keys[5], keys[6]],
                },
            ],
        };

        let config = RecoveryConfig::from_policy_input(&input, Network::Testnet).unwrap();
        assert_eq!(config.recovery_tiers.len(), 2);
        assert_eq!(config.recovery_tiers[0].timelock_months, 6);
        assert_eq!(config.recovery_tiers[1].timelock_months, 12);

        let output = config.build().unwrap();
        assert_eq!(output.tiers.len(), 3);
    }

    #[test]
    fn test_from_policy_input_validates() {
        let pk1 = test_keypair(1);
        let pk2 = test_keypair(2);

        let input = PolicyInput {
            primary: PolicyTierInput {
                threshold: 5,
                timelock_months: 0,
                keys: vec![pk1],
            },
            recovery_tiers: vec![PolicyTierInput {
                threshold: 1,
                timelock_months: 6,
                keys: vec![pk2],
            }],
        };

        assert!(RecoveryConfig::from_policy_input(&input, Network::Testnet).is_err());
    }

    #[test]
    fn test_max_recovery_tiers_exceeded() {
        let pk = test_keypair(1);
        let tiers: Vec<RecoveryTier> = (0..11)
            .map(|i| RecoveryTier {
                keys: vec![test_keypair((i + 2) as u8)],
                threshold: 1,
                timelock_months: (i + 1) as u32,
            })
            .collect();

        let config = RecoveryConfig {
            primary: SpendingTier {
                keys: vec![pk],
                threshold: 1,
            },
            recovery_tiers: tiers,
            network: Network::Testnet,
        };
        assert!(config.validate().is_err());
    }
}