1use crate::error::{BitcoinError, Result};
4use bitcoin::key::Secp256k1;
5use bitcoin::secp256k1::All;
6use bitcoin::taproot::{LeafVersion, TaprootBuilder, TaprootSpendInfo};
7use bitcoin::{Address, Network, ScriptBuf, Sequence, TapLeafHash, XOnlyPublicKey};
8use serde::{Deserialize, Serialize};
9use std::collections::HashSet;
10
11const BLOCKS_PER_DAY: u32 = 144;
12const BLOCKS_PER_MONTH: u32 = BLOCKS_PER_DAY * 30;
13const MAX_KEYS_PER_TIER: usize = 20;
14const MAX_RECOVERY_TIERS: usize = 10;
15const MAX_CSV_BLOCKS: u32 = 0xFFFF;
16
17const NUMS_POINT: [u8; 32] = [
19 0x50, 0x92, 0x9b, 0x74, 0xc1, 0xa0, 0x49, 0x54, 0xb7, 0x8b, 0x4b, 0x60, 0x35, 0xe9, 0x7a, 0x5e,
20 0x07, 0x8a, 0x5a, 0x0f, 0x28, 0xec, 0x96, 0xd5, 0x47, 0xbf, 0xee, 0x9a, 0xce, 0x80, 0x3a, 0xc0,
21];
22
23#[derive(Clone, Debug, Serialize, Deserialize)]
24pub struct RecoveryConfig {
25 pub primary: SpendingTier,
26 pub recovery_tiers: Vec<RecoveryTier>,
27 pub network: Network,
28}
29
30#[derive(Clone, Debug, Serialize, Deserialize)]
31pub struct SpendingTier {
32 pub keys: Vec<[u8; 32]>,
33 pub threshold: u32,
34}
35
36#[derive(Clone, Debug, Serialize, Deserialize)]
37pub struct RecoveryTier {
38 pub keys: Vec<[u8; 32]>,
39 pub threshold: u32,
40 pub timelock_months: u32,
41}
42
43#[derive(Clone, Debug)]
44pub struct RecoveryOutput {
45 pub address: Address,
46 pub spend_info: TaprootSpendInfo,
47 pub descriptor: String,
48 pub tiers: Vec<TierInfo>,
49}
50
51#[derive(Clone, Debug)]
52pub struct TierInfo {
53 pub name: String,
54 pub script: ScriptBuf,
55 pub leaf_hash: TapLeafHash,
56 pub timelock_blocks: Option<u32>,
57 pub threshold: u32,
58 pub keys: Vec<XOnlyPublicKey>,
59}
60
61#[derive(Clone, Debug, Serialize, Deserialize)]
62pub struct PolicyInput {
63 pub primary: PolicyTierInput,
64 pub recovery_tiers: Vec<PolicyTierInput>,
65}
66
67#[derive(Clone, Debug, Serialize, Deserialize)]
68pub struct PolicyTierInput {
69 pub threshold: u32,
70 pub timelock_months: u32,
71 pub keys: Vec<[u8; 32]>,
72}
73
74impl RecoveryConfig {
75 pub fn from_policy_input(input: &PolicyInput, network: Network) -> Result<Self> {
76 let primary = SpendingTier {
77 keys: input.primary.keys.clone(),
78 threshold: input.primary.threshold,
79 };
80
81 let recovery_tiers = input
82 .recovery_tiers
83 .iter()
84 .map(|tier| RecoveryTier {
85 keys: tier.keys.clone(),
86 threshold: tier.threshold,
87 timelock_months: tier.timelock_months,
88 })
89 .collect();
90
91 let config = Self {
92 primary,
93 recovery_tiers,
94 network,
95 };
96 config.validate()?;
97 Ok(config)
98 }
99
100 pub fn validate(&self) -> Result<()> {
101 if self.primary.keys.is_empty() {
102 return Err(BitcoinError::Recovery("primary tier has no keys".into()));
103 }
104 if self.primary.keys.len() > MAX_KEYS_PER_TIER {
105 return Err(BitcoinError::Recovery(format!(
106 "primary tier exceeds {MAX_KEYS_PER_TIER} keys"
107 )));
108 }
109 if self.primary.threshold == 0 || self.primary.threshold > self.primary.keys.len() as u32 {
110 return Err(BitcoinError::Recovery("invalid primary threshold".into()));
111 }
112 check_duplicate_keys("primary", &self.primary.keys)?;
113
114 if self.recovery_tiers.is_empty() {
115 return Err(BitcoinError::Recovery(
116 "at least one recovery tier is required".into(),
117 ));
118 }
119 if self.recovery_tiers.len() > MAX_RECOVERY_TIERS {
120 return Err(BitcoinError::Recovery(format!(
121 "recovery tier count {} exceeds maximum {}",
122 self.recovery_tiers.len(),
123 MAX_RECOVERY_TIERS
124 )));
125 }
126
127 for (i, tier) in self.recovery_tiers.iter().enumerate() {
135 if tier.keys.is_empty() {
136 return Err(BitcoinError::Recovery(format!(
137 "recovery tier {i} has no keys"
138 )));
139 }
140 if tier.keys.len() > MAX_KEYS_PER_TIER {
141 return Err(BitcoinError::Recovery(format!(
142 "recovery tier {i} exceeds {MAX_KEYS_PER_TIER} keys"
143 )));
144 }
145 if tier.threshold == 0 || tier.threshold > tier.keys.len() as u32 {
146 return Err(BitcoinError::Recovery(format!(
147 "invalid threshold for recovery tier {i}"
148 )));
149 }
150 if tier.timelock_months == 0 {
151 return Err(BitcoinError::Recovery(format!(
152 "recovery tier {i} must have nonzero timelock"
153 )));
154 }
155 let timelock_blocks = months_to_blocks(tier.timelock_months)?;
156 if timelock_blocks > MAX_CSV_BLOCKS {
157 return Err(BitcoinError::Recovery(format!(
158 "recovery tier {} timelock {} months ({} blocks) exceeds CSV maximum {}",
159 i, tier.timelock_months, timelock_blocks, MAX_CSV_BLOCKS
160 )));
161 }
162 check_duplicate_keys(&format!("recovery tier {i}"), &tier.keys)?;
163 }
164 for w in self.recovery_tiers.windows(2) {
165 if w[1].timelock_months <= w[0].timelock_months {
166 return Err(BitcoinError::Recovery(
167 "recovery tiers must have increasing timelocks".into(),
168 ));
169 }
170 }
171 Ok(())
172 }
173
174 pub fn build(&self) -> Result<RecoveryOutput> {
175 self.validate()?;
176 let secp = Secp256k1::new();
177 let tiers = self.build_tier_infos()?;
178 let internal_key = self.internal_key()?;
179 let depths = optimal_depth(tiers.len());
180 let spend_info = self.build_taproot(&secp, internal_key, &tiers, &depths)?;
181 let address = Address::p2tr_tweaked(spend_info.output_key(), self.network);
182 let descriptor = self.format_descriptor(internal_key, &tiers, &depths);
183
184 Ok(RecoveryOutput {
185 address,
186 spend_info,
187 descriptor,
188 tiers,
189 })
190 }
191
192 pub fn build_with_internal_key(&self, internal_key: &XOnlyPublicKey) -> Result<RecoveryOutput> {
193 self.validate()?;
194 let secp = Secp256k1::new();
195 let tiers = self.build_tier_infos()?;
196 let depths = optimal_depth(tiers.len());
197 let spend_info = self.build_taproot(&secp, *internal_key, &tiers, &depths)?;
198 let address = Address::p2tr_tweaked(spend_info.output_key(), self.network);
199 let descriptor = self.format_descriptor(*internal_key, &tiers, &depths);
200
201 Ok(RecoveryOutput {
202 address,
203 spend_info,
204 descriptor,
205 tiers,
206 })
207 }
208
209 fn internal_key(&self) -> Result<XOnlyPublicKey> {
210 if self.primary.keys.len() == 1 && self.primary.threshold == 1 {
211 return parse_xonly(&self.primary.keys[0]);
212 }
213 XOnlyPublicKey::from_slice(&NUMS_POINT)
214 .map_err(|e| BitcoinError::Recovery(format!("NUMS point: {e}")))
215 }
216
217 fn build_tier_infos(&self) -> Result<Vec<TierInfo>> {
218 let mut tiers = Vec::new();
219
220 if self.primary.keys.len() > 1 || self.primary.threshold > 1 {
221 let pubkeys = parse_xonly_keys(&self.primary.keys)?;
222 let script = build_multisig_script(&self.primary.keys, self.primary.threshold)?;
223 tiers.push(TierInfo {
224 name: "primary".to_string(),
225 leaf_hash: TapLeafHash::from_script(&script, LeafVersion::TapScript),
226 script,
227 timelock_blocks: None,
228 threshold: self.primary.threshold,
229 keys: pubkeys,
230 });
231 }
232
233 for (i, tier) in self.recovery_tiers.iter().enumerate() {
234 let timelock_blocks = months_to_blocks(tier.timelock_months)?;
235 let pubkeys = parse_xonly_keys(&tier.keys)?;
236 let script = build_timelocked_multisig(&tier.keys, tier.threshold, timelock_blocks)?;
237 tiers.push(TierInfo {
238 name: format!("recovery_{}", i + 1),
239 leaf_hash: TapLeafHash::from_script(&script, LeafVersion::TapScript),
240 script,
241 timelock_blocks: Some(timelock_blocks),
242 threshold: tier.threshold,
243 keys: pubkeys,
244 });
245 }
246
247 Ok(tiers)
248 }
249
250 fn build_taproot(
251 &self,
252 secp: &Secp256k1<All>,
253 internal_key: XOnlyPublicKey,
254 tiers: &[TierInfo],
255 depths: &[u8],
256 ) -> Result<TaprootSpendInfo> {
257 if tiers.is_empty() {
258 return TaprootBuilder::new()
259 .finalize(secp, internal_key)
260 .map_err(|e| BitcoinError::Recovery(format!("taproot finalize: {e:?}")));
261 }
262
263 debug_assert_eq!(tiers.len(), depths.len());
264 let mut builder = TaprootBuilder::new();
265
266 for (i, tier) in tiers.iter().enumerate() {
267 builder = builder
268 .add_leaf(depths[i], tier.script.clone())
269 .map_err(|e| BitcoinError::Recovery(format!("add leaf: {e:?}")))?;
270 }
271
272 builder
273 .finalize(secp, internal_key)
274 .map_err(|e| BitcoinError::Recovery(format!("taproot finalize: {e:?}")))
275 }
276
277 fn format_descriptor(
278 &self,
279 internal_key: XOnlyPublicKey,
280 tiers: &[TierInfo],
281 depths: &[u8],
282 ) -> String {
283 if tiers.is_empty() {
284 return format!("tr({internal_key})");
285 }
286 debug_assert_eq!(tiers.len(), depths.len());
287 let leaves: Vec<String> = tiers.iter().map(tier_miniscript).collect();
288 let tree = build_tree_string(&leaves, depths);
289 format!("tr({internal_key},{tree})")
290 }
291}
292
293fn tier_miniscript(tier: &TierInfo) -> String {
294 let inner = if tier.keys.len() == 1 && tier.threshold == 1 {
295 format!("pk({})", tier.keys[0])
296 } else {
297 let keys = tier
298 .keys
299 .iter()
300 .map(XOnlyPublicKey::to_string)
301 .collect::<Vec<_>>()
302 .join(",");
303 format!("multi_a({},{keys})", tier.threshold)
304 };
305 match tier.timelock_blocks {
306 Some(blocks) => format!("and_v(v:older({blocks}),{inner})"),
307 None => inner,
308 }
309}
310
311fn build_tree_string(leaves: &[String], depths: &[u8]) -> String {
312 debug_assert_eq!(leaves.len(), depths.len());
313 let mut stack: Vec<(u8, String)> = Vec::with_capacity(leaves.len());
314 for (leaf, &d) in leaves.iter().zip(depths) {
315 stack.push((d, leaf.clone()));
316 while stack.len() >= 2 && stack[stack.len() - 1].0 == stack[stack.len() - 2].0 {
317 let (d_top, s_top) = stack.pop().expect("len >= 2");
318 let (_, s_second) = stack.pop().expect("len >= 2");
319 stack.push((d_top.saturating_sub(1), format!("{{{s_second},{s_top}}}")));
320 }
321 }
322 stack.pop().map(|(_, s)| s).unwrap_or_default()
323}
324
325fn build_multisig_script(keys: &[[u8; 32]], threshold: u32) -> Result<ScriptBuf> {
326 let pubkeys: Vec<XOnlyPublicKey> = keys.iter().map(parse_xonly).collect::<Result<Vec<_>>>()?;
327
328 let mut builder = ScriptBuf::builder();
329 builder = push_checksig_chain(builder, &pubkeys);
330
331 if needs_threshold_check(threshold, pubkeys.len()) {
332 builder = builder
333 .push_int(threshold as i64)
334 .push_opcode(bitcoin::opcodes::all::OP_NUMEQUAL);
335 }
336
337 Ok(builder.into_script())
338}
339
340fn build_timelocked_multisig(
341 keys: &[[u8; 32]],
342 threshold: u32,
343 timelock_blocks: u32,
344) -> Result<ScriptBuf> {
345 let seq_u16 = u16::try_from(timelock_blocks).map_err(|_| {
346 BitcoinError::Recovery(format!(
347 "timelock {timelock_blocks} exceeds CSV maximum {MAX_CSV_BLOCKS}"
348 ))
349 })?;
350
351 let pubkeys: Vec<XOnlyPublicKey> = keys.iter().map(parse_xonly).collect::<Result<Vec<_>>>()?;
352
353 let mut builder = ScriptBuf::builder()
357 .push_sequence(Sequence::from_height(seq_u16))
358 .push_opcode(bitcoin::opcodes::all::OP_CSV)
359 .push_opcode(bitcoin::opcodes::all::OP_VERIFY);
360
361 builder = push_checksig_chain(builder, &pubkeys);
362
363 if needs_threshold_check(threshold, pubkeys.len()) {
364 builder = builder
365 .push_int(threshold as i64)
366 .push_opcode(bitcoin::opcodes::all::OP_NUMEQUAL);
367 }
368
369 Ok(builder.into_script())
370}
371
372fn push_checksig_chain(
373 mut builder: bitcoin::script::Builder,
374 pubkeys: &[XOnlyPublicKey],
375) -> bitcoin::script::Builder {
376 for (i, pk) in pubkeys.iter().enumerate() {
377 builder = builder.push_x_only_key(pk);
378 if i == 0 {
379 builder = builder.push_opcode(bitcoin::opcodes::all::OP_CHECKSIG);
380 } else {
381 builder = builder.push_opcode(bitcoin::opcodes::all::OP_CHECKSIGADD);
382 }
383 }
384 builder
385}
386
387fn parse_xonly(bytes: &[u8; 32]) -> Result<XOnlyPublicKey> {
388 XOnlyPublicKey::from_slice(bytes).map_err(|e| BitcoinError::InvalidPublicKey(e.to_string()))
389}
390
391fn parse_xonly_keys(keys: &[[u8; 32]]) -> Result<Vec<XOnlyPublicKey>> {
392 keys.iter().map(parse_xonly).collect()
393}
394
395fn needs_threshold_check(threshold: u32, key_count: usize) -> bool {
396 threshold > 1 || key_count > 1
397}
398
399fn check_duplicate_keys(tier_name: &str, keys: &[[u8; 32]]) -> Result<()> {
400 let mut seen = HashSet::with_capacity(keys.len());
401 for key in keys {
402 if !seen.insert(key) {
403 return Err(BitcoinError::Recovery(format!(
404 "duplicate key in {}: {}",
405 tier_name,
406 hex::encode(key)
407 )));
408 }
409 }
410 Ok(())
411}
412
413fn optimal_depth(count: usize) -> Vec<u8> {
414 match count {
415 0 => vec![],
416 1 => vec![0],
417 _ => {
418 let depth = (usize::BITS - (count - 1).leading_zeros()) as u8;
419 let full_capacity = 1usize << depth;
420 let shallow_count = full_capacity - count;
421 (0..count)
422 .map(|i| if i < shallow_count { depth - 1 } else { depth })
423 .collect()
424 }
425 }
426}
427
428pub fn recovery_sequence(timelock_blocks: u32) -> Result<Sequence> {
429 let blocks_u16 = u16::try_from(timelock_blocks).map_err(|_| {
430 BitcoinError::Recovery(format!(
431 "timelock {timelock_blocks} exceeds maximum relative lock height 65535"
432 ))
433 })?;
434 Ok(Sequence::from_height(blocks_u16))
435}
436
437pub fn months_to_blocks(months: u32) -> Result<u32> {
438 months.checked_mul(BLOCKS_PER_MONTH).ok_or_else(|| {
439 BitcoinError::Recovery(format!("timelock {months} months overflows block count"))
440 })
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446 use bitcoin::secp256k1::{Keypair, Secp256k1};
447
448 fn test_keypair(seed: u8) -> [u8; 32] {
449 let secp = Secp256k1::new();
450 let mut secret = [seed; 32];
451 secret[0] = seed.wrapping_add(1);
452 let kp = Keypair::from_seckey_slice(&secp, &secret).unwrap();
453 kp.x_only_public_key().0.serialize()
454 }
455
456 #[test]
457 fn test_single_key_primary_with_recovery() {
458 let pk1 = test_keypair(1);
459 let pk2 = test_keypair(2);
460 let pk3 = test_keypair(3);
461
462 let config = RecoveryConfig {
463 primary: SpendingTier {
464 keys: vec![pk1],
465 threshold: 1,
466 },
467 recovery_tiers: vec![RecoveryTier {
468 keys: vec![pk2, pk3],
469 threshold: 1,
470 timelock_months: 6,
471 }],
472 network: Network::Testnet,
473 };
474
475 let output = config.build().unwrap();
476 assert!(output.address.to_string().starts_with("tb1p"));
477 assert_eq!(output.tiers.len(), 1);
478 assert_eq!(output.tiers[0].timelock_blocks, Some(6 * BLOCKS_PER_MONTH));
479 }
480
481 #[test]
482 fn test_multisig_primary_with_two_recovery_tiers() {
483 let keys: Vec<[u8; 32]> = (1..=9).map(test_keypair).collect();
484
485 let config = RecoveryConfig {
486 primary: SpendingTier {
487 keys: vec![keys[0], keys[1], keys[2]],
488 threshold: 2,
489 },
490 recovery_tiers: vec![
491 RecoveryTier {
492 keys: vec![keys[3], keys[4], keys[5], keys[6], keys[7]],
493 threshold: 3,
494 timelock_months: 6,
495 },
496 RecoveryTier {
497 keys: vec![keys[8]],
498 threshold: 1,
499 timelock_months: 12,
500 },
501 ],
502 network: Network::Testnet,
503 };
504
505 let output = config.build().unwrap();
506 assert!(output.address.to_string().starts_with("tb1p"));
507 assert_eq!(output.tiers.len(), 3);
508 assert!(output.tiers[0].timelock_blocks.is_none());
509 assert_eq!(output.tiers[1].timelock_blocks, Some(6 * BLOCKS_PER_MONTH));
510 assert_eq!(output.tiers[2].timelock_blocks, Some(12 * BLOCKS_PER_MONTH));
511 }
512
513 #[test]
514 fn test_validation_errors() {
515 let pk = test_keypair(1);
516 let pk2 = test_keypair(2);
517 let pk3 = test_keypair(3);
518 let pk4 = test_keypair(4);
519
520 let config = RecoveryConfig {
521 primary: SpendingTier {
522 keys: vec![],
523 threshold: 1,
524 },
525 recovery_tiers: vec![],
526 network: Network::Testnet,
527 };
528 assert!(config.validate().is_err());
529
530 let config = RecoveryConfig {
531 primary: SpendingTier {
532 keys: vec![pk],
533 threshold: 1,
534 },
535 recovery_tiers: vec![RecoveryTier {
536 keys: vec![pk2],
537 threshold: 1,
538 timelock_months: 0,
539 }],
540 network: Network::Testnet,
541 };
542 assert!(config.validate().is_err());
543
544 let config = RecoveryConfig {
545 primary: SpendingTier {
546 keys: vec![pk],
547 threshold: 1,
548 },
549 recovery_tiers: vec![
550 RecoveryTier {
551 keys: vec![pk3],
552 threshold: 1,
553 timelock_months: 12,
554 },
555 RecoveryTier {
556 keys: vec![pk4],
557 threshold: 1,
558 timelock_months: 6,
559 },
560 ],
561 network: Network::Testnet,
562 };
563 assert!(config.validate().is_err());
564 }
565
566 #[test]
567 fn test_descriptor_format() {
568 let pk1 = test_keypair(1);
569 let pk2 = test_keypair(2);
570
571 let config = RecoveryConfig {
572 primary: SpendingTier {
573 keys: vec![pk1],
574 threshold: 1,
575 },
576 recovery_tiers: vec![RecoveryTier {
577 keys: vec![pk2],
578 threshold: 1,
579 timelock_months: 6,
580 }],
581 network: Network::Testnet,
582 };
583
584 let output = config.build().unwrap();
585 assert!(output.descriptor.starts_with("tr("));
586 assert!(output.descriptor.contains("older("));
587 }
588
589 #[test]
590 fn test_descriptor_parses_as_miniscript() {
591 use bitcoin::secp256k1::Secp256k1;
592 use miniscript::Descriptor;
593
594 let keys: Vec<[u8; 32]> = (1..=12).map(test_keypair).collect();
595 let cases = vec![
596 RecoveryConfig {
597 primary: SpendingTier {
598 keys: vec![keys[0]],
599 threshold: 1,
600 },
601 recovery_tiers: vec![RecoveryTier {
602 keys: vec![keys[1]],
603 threshold: 1,
604 timelock_months: 6,
605 }],
606 network: Network::Testnet,
607 },
608 RecoveryConfig {
609 primary: SpendingTier {
610 keys: vec![keys[0], keys[1], keys[2]],
611 threshold: 2,
612 },
613 recovery_tiers: vec![
614 RecoveryTier {
615 keys: vec![keys[3], keys[4]],
616 threshold: 2,
617 timelock_months: 6,
618 },
619 RecoveryTier {
620 keys: vec![keys[5]],
621 threshold: 1,
622 timelock_months: 12,
623 },
624 ],
625 network: Network::Testnet,
626 },
627 RecoveryConfig {
628 primary: SpendingTier {
629 keys: vec![keys[0], keys[1]],
630 threshold: 2,
631 },
632 recovery_tiers: vec![
633 RecoveryTier {
634 keys: vec![keys[2]],
635 threshold: 1,
636 timelock_months: 6,
637 },
638 RecoveryTier {
639 keys: vec![keys[3]],
640 threshold: 1,
641 timelock_months: 12,
642 },
643 ],
644 network: Network::Testnet,
645 },
646 RecoveryConfig {
647 primary: SpendingTier {
648 keys: vec![keys[0], keys[1]],
649 threshold: 2,
650 },
651 recovery_tiers: vec![
652 RecoveryTier {
653 keys: vec![keys[2]],
654 threshold: 1,
655 timelock_months: 3,
656 },
657 RecoveryTier {
658 keys: vec![keys[3]],
659 threshold: 1,
660 timelock_months: 6,
661 },
662 RecoveryTier {
663 keys: vec![keys[4]],
664 threshold: 1,
665 timelock_months: 9,
666 },
667 RecoveryTier {
668 keys: vec![keys[5]],
669 threshold: 1,
670 timelock_months: 12,
671 },
672 ],
673 network: Network::Testnet,
674 },
675 ];
676
677 let _ = Secp256k1::new();
678 for config in cases {
679 let output = config.build().unwrap();
680 let desc: Descriptor<miniscript::DescriptorPublicKey> = output
681 .descriptor
682 .parse()
683 .unwrap_or_else(|e| panic!("parse failed for {}: {e}", output.descriptor));
684 let parsed_spk = desc.at_derivation_index(0).unwrap().script_pubkey();
685 let expected_spk = bitcoin::ScriptBuf::new_p2tr_tweaked(output.spend_info.output_key());
686 assert_eq!(
687 parsed_spk, expected_spk,
688 "miniscript-derived scriptPubKey mismatches TaprootBuilder output for {}",
689 output.descriptor
690 );
691 }
692 }
693
694 #[test]
695 fn test_timelock_script_structure() {
696 let pk = test_keypair(1);
697 let blocks = months_to_blocks(6).unwrap();
698
699 let script = build_timelocked_multisig(&[pk], 1, blocks).unwrap();
700
701 let asm = script.to_asm_string();
702 assert!(asm.contains("OP_CSV"));
703 assert!(asm.contains("OP_VERIFY"));
704 assert!(asm.contains("OP_CHECKSIG"));
705 }
706
707 #[test]
708 fn test_months_to_blocks() {
709 assert_eq!(months_to_blocks(6).unwrap(), 6 * 144 * 30);
710 assert_eq!(months_to_blocks(12).unwrap(), 12 * 144 * 30);
711 }
712
713 #[test]
714 fn test_months_to_blocks_overflow() {
715 assert!(months_to_blocks(u32::MAX).is_err());
716 }
717
718 #[test]
719 fn test_recovery_sequence() {
720 let seq = recovery_sequence(25920).unwrap();
721 assert!(seq.is_relative_lock_time());
722 }
723
724 #[test]
725 fn test_recovery_sequence_overflow() {
726 assert!(recovery_sequence(70000).is_err());
727 }
728
729 #[test]
730 fn test_optimal_depth_valid_trees() {
731 for count in 1..=10 {
732 let depths = optimal_depth(count);
733 assert_eq!(depths.len(), count);
734
735 let mut builder = TaprootBuilder::new();
736 let secp = Secp256k1::new();
737 let pk = test_keypair(1);
738 let xonly = XOnlyPublicKey::from_slice(&pk).unwrap();
739 let script = ScriptBuf::builder()
740 .push_x_only_key(&xonly)
741 .push_opcode(bitcoin::opcodes::all::OP_CHECKSIG)
742 .into_script();
743
744 for &d in &depths {
745 builder = builder.add_leaf(d, script.clone()).unwrap();
746 }
747 let internal = XOnlyPublicKey::from_slice(&NUMS_POINT).unwrap();
748 assert!(builder.finalize(&secp, internal).is_ok());
749 }
750 }
751
752 #[test]
753 fn test_nums_internal_key_for_multisig() {
754 let pk1 = test_keypair(1);
755 let pk2 = test_keypair(2);
756 let pk3 = test_keypair(3);
757
758 let config = RecoveryConfig {
759 primary: SpendingTier {
760 keys: vec![pk1, pk2],
761 threshold: 2,
762 },
763 recovery_tiers: vec![RecoveryTier {
764 keys: vec![pk3],
765 threshold: 1,
766 timelock_months: 6,
767 }],
768 network: Network::Testnet,
769 };
770
771 let output = config.build().unwrap();
772 assert!(output.address.to_string().starts_with("tb1p"));
773 assert_eq!(output.tiers.len(), 2);
774 assert_eq!(output.tiers[0].name, "primary");
775 }
776
777 #[test]
778 fn test_multisig_script_uses_numequal() {
779 let pk1 = test_keypair(1);
780 let pk2 = test_keypair(2);
781 let pk3 = test_keypair(3);
782
783 let script = build_multisig_script(&[pk1, pk2, pk3], 2).unwrap();
784 let asm = script.to_asm_string();
785 assert!(asm.contains("OP_NUMEQUAL"));
786 assert!(!asm.contains("OP_NUMEQUALVERIFY"));
787 }
788
789 #[test]
790 fn test_key_count_limit() {
791 let keys: Vec<[u8; 32]> = (1..=21).map(|i| test_keypair(i as u8)).collect();
792 let recovery_pk = test_keypair(100);
793
794 let config = RecoveryConfig {
795 primary: SpendingTier { keys, threshold: 1 },
796 recovery_tiers: vec![RecoveryTier {
797 keys: vec![recovery_pk],
798 threshold: 1,
799 timelock_months: 6,
800 }],
801 network: Network::Testnet,
802 };
803 assert!(config.validate().is_err());
804 }
805
806 #[test]
807 fn test_tier_info_has_threshold_and_keys() {
808 let pk1 = test_keypair(1);
809 let pk2 = test_keypair(2);
810 let pk3 = test_keypair(3);
811
812 let config = RecoveryConfig {
813 primary: SpendingTier {
814 keys: vec![pk1],
815 threshold: 1,
816 },
817 recovery_tiers: vec![RecoveryTier {
818 keys: vec![pk2, pk3],
819 threshold: 2,
820 timelock_months: 6,
821 }],
822 network: Network::Testnet,
823 };
824
825 let output = config.build().unwrap();
826 assert_eq!(output.tiers[0].threshold, 2);
827 assert_eq!(output.tiers[0].keys.len(), 2);
828 }
829
830 #[test]
831 fn test_duplicate_keys_within_tier() {
832 let pk = test_keypair(1);
833 let pk2 = test_keypair(2);
834
835 let config = RecoveryConfig {
836 primary: SpendingTier {
837 keys: vec![pk, pk],
838 threshold: 2,
839 },
840 recovery_tiers: vec![RecoveryTier {
841 keys: vec![pk2],
842 threshold: 1,
843 timelock_months: 6,
844 }],
845 network: Network::Testnet,
846 };
847 assert!(config.validate().is_err());
848 }
849
850 #[test]
851 fn key_reuse_across_tiers_now_allowed() {
852 let pk = test_keypair(1);
858 let config = RecoveryConfig {
859 primary: SpendingTier {
860 keys: vec![pk],
861 threshold: 1,
862 },
863 recovery_tiers: vec![RecoveryTier {
864 keys: vec![pk],
865 threshold: 1,
866 timelock_months: 6,
867 }],
868 network: Network::Testnet,
869 };
870 config
871 .validate()
872 .expect("identical key across primary + recovery tier must validate");
873 }
874
875 #[test]
876 fn key_reuse_across_multi_tier_recovery_now_allowed() {
877 let a = test_keypair(1);
880 let b = test_keypair(2);
881 let c = test_keypair(3);
882
883 let config = RecoveryConfig {
884 primary: SpendingTier {
885 keys: vec![a, b, c],
886 threshold: 3,
887 },
888 recovery_tiers: vec![
889 RecoveryTier {
890 keys: vec![a, b, c],
891 threshold: 2,
892 timelock_months: 1,
893 },
894 RecoveryTier {
895 keys: vec![a, b, c],
896 threshold: 1,
897 timelock_months: 6,
898 },
899 ],
900 network: Network::Testnet,
901 };
902 config
903 .validate()
904 .expect("multi-tier WDC shape with reused xpubs must validate");
905 config
906 .build()
907 .expect("the descriptor must still build under reused xpubs");
908 }
909
910 #[test]
911 fn within_tier_duplicate_still_rejected_in_recovery() {
912 let pk = test_keypair(1);
917 let pk2 = test_keypair(2);
918 let config = RecoveryConfig {
919 primary: SpendingTier {
920 keys: vec![pk, pk2],
921 threshold: 2,
922 },
923 recovery_tiers: vec![RecoveryTier {
924 keys: vec![pk2, pk2],
925 threshold: 1,
926 timelock_months: 6,
927 }],
928 network: Network::Testnet,
929 };
930 let err = config.validate().expect_err("within-tier dup must fail");
931 assert!(
932 err.to_string().to_lowercase().contains("duplicate"),
933 "got {err}"
934 );
935 }
936
937 #[test]
938 fn test_empty_recovery_tiers_rejected() {
939 let pk = test_keypair(1);
940
941 let config = RecoveryConfig {
942 primary: SpendingTier {
943 keys: vec![pk],
944 threshold: 1,
945 },
946 recovery_tiers: vec![],
947 network: Network::Testnet,
948 };
949 assert!(config.validate().is_err());
950 }
951
952 #[test]
953 fn test_from_policy_input_single_tier() {
954 let pk1 = test_keypair(1);
955 let pk2 = test_keypair(2);
956 let pk3 = test_keypair(3);
957
958 let input = PolicyInput {
959 primary: PolicyTierInput {
960 threshold: 1,
961 timelock_months: 0,
962 keys: vec![pk1],
963 },
964 recovery_tiers: vec![PolicyTierInput {
965 threshold: 1,
966 timelock_months: 6,
967 keys: vec![pk2, pk3],
968 }],
969 };
970
971 let config = RecoveryConfig::from_policy_input(&input, Network::Testnet).unwrap();
972 assert_eq!(config.primary.keys.len(), 1);
973 assert_eq!(config.primary.threshold, 1);
974 assert_eq!(config.recovery_tiers.len(), 1);
975 assert_eq!(config.recovery_tiers[0].keys.len(), 2);
976 assert_eq!(config.recovery_tiers[0].threshold, 1);
977 assert_eq!(config.recovery_tiers[0].timelock_months, 6);
978
979 let output = config.build().unwrap();
980 assert!(output.address.to_string().starts_with("tb1p"));
981 }
982
983 #[test]
984 fn test_from_policy_input_multi_tier() {
985 let keys: Vec<[u8; 32]> = (1..=7).map(test_keypair).collect();
986
987 let input = PolicyInput {
988 primary: PolicyTierInput {
989 threshold: 2,
990 timelock_months: 0,
991 keys: vec![keys[0], keys[1], keys[2]],
992 },
993 recovery_tiers: vec![
994 PolicyTierInput {
995 threshold: 2,
996 timelock_months: 6,
997 keys: vec![keys[3], keys[4]],
998 },
999 PolicyTierInput {
1000 threshold: 1,
1001 timelock_months: 12,
1002 keys: vec![keys[5], keys[6]],
1003 },
1004 ],
1005 };
1006
1007 let config = RecoveryConfig::from_policy_input(&input, Network::Testnet).unwrap();
1008 assert_eq!(config.recovery_tiers.len(), 2);
1009 assert_eq!(config.recovery_tiers[0].timelock_months, 6);
1010 assert_eq!(config.recovery_tiers[1].timelock_months, 12);
1011
1012 let output = config.build().unwrap();
1013 assert_eq!(output.tiers.len(), 3);
1014 }
1015
1016 #[test]
1017 fn test_from_policy_input_validates() {
1018 let pk1 = test_keypair(1);
1019 let pk2 = test_keypair(2);
1020
1021 let input = PolicyInput {
1022 primary: PolicyTierInput {
1023 threshold: 5,
1024 timelock_months: 0,
1025 keys: vec![pk1],
1026 },
1027 recovery_tiers: vec![PolicyTierInput {
1028 threshold: 1,
1029 timelock_months: 6,
1030 keys: vec![pk2],
1031 }],
1032 };
1033
1034 assert!(RecoveryConfig::from_policy_input(&input, Network::Testnet).is_err());
1035 }
1036
1037 #[test]
1038 fn test_max_recovery_tiers_exceeded() {
1039 let pk = test_keypair(1);
1040 let tiers: Vec<RecoveryTier> = (0..11)
1041 .map(|i| RecoveryTier {
1042 keys: vec![test_keypair((i + 2) as u8)],
1043 threshold: 1,
1044 timelock_months: (i + 1) as u32,
1045 })
1046 .collect();
1047
1048 let config = RecoveryConfig {
1049 primary: SpendingTier {
1050 keys: vec![pk],
1051 threshold: 1,
1052 },
1053 recovery_tiers: tiers,
1054 network: Network::Testnet,
1055 };
1056 assert!(config.validate().is_err());
1057 }
1058}