Skip to main content

keep_bitcoin/
descriptor.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3use std::str::FromStr;
4
5use bitcoin::bip32::{ChainCode, ChildNumber, Fingerprint, Xpub};
6use bitcoin::hashes::{hash160, Hash};
7use bitcoin::secp256k1::PublicKey;
8use bitcoin::{Network, NetworkKind, XOnlyPublicKey};
9use keep_core::frost_bip32::deterministic_chaincode;
10use miniscript::{Descriptor, DescriptorPublicKey};
11
12use crate::address::AddressDerivation;
13use crate::error::{BitcoinError, Result};
14use crate::recovery::RecoveryConfig;
15
16pub fn xpub_to_x_only(xpub: &str, network: Network) -> Result<[u8; 32]> {
17    let parsed =
18        Xpub::from_str(xpub).map_err(|e| BitcoinError::Descriptor(format!("invalid xpub: {e}")))?;
19
20    let is_mainnet = network == Network::Bitcoin;
21    let is_mainnet_xpub = xpub.starts_with("xpub");
22    if is_mainnet != is_mainnet_xpub {
23        let (expected, got) = if is_mainnet {
24            ("mainnet xpub", "testnet tpub")
25        } else {
26            ("testnet tpub", "mainnet xpub")
27        };
28        return Err(BitcoinError::Descriptor(format!(
29            "expected {expected} but got {got}"
30        )));
31    }
32
33    Ok(parsed.to_x_only_pub().serialize())
34}
35
36pub struct DescriptorExport {
37    pub descriptor: String,
38    pub checksum: String,
39    pub fingerprint: String,
40    pub network: Network,
41}
42
43impl DescriptorExport {
44    pub fn from_derivation(derivation: &AddressDerivation, account: u32) -> Result<Self> {
45        let network = derivation.network();
46        let fingerprint = derivation.master_fingerprint()?;
47        let xpub = derivation.account_xpub(account)?;
48
49        let coin_type = if network == Network::Bitcoin { 0 } else { 1 };
50
51        let descriptor = format!("tr([{fingerprint}/86'/{coin_type}'/{account}']{xpub}/0/*)");
52
53        let (descriptor, checksum) = canonicalize_descriptor(&descriptor)?;
54
55        Ok(Self {
56            descriptor,
57            checksum,
58            fingerprint: fingerprint.to_string(),
59            network,
60        })
61    }
62
63    pub fn from_frost_wallet(
64        group_pubkey: &[u8; 32],
65        recovery: Option<&RecoveryConfig>,
66        network: Network,
67    ) -> Result<Self> {
68        let xonly = XOnlyPublicKey::from_slice(group_pubkey)
69            .map_err(|e| BitcoinError::Descriptor(format!("invalid group pubkey: {e}")))?;
70        let fingerprint = Self::pubkey_fingerprint(group_pubkey);
71
72        let (descriptor, checksum) = match recovery {
73            None => {
74                // #487 PR 4/4: emit a BIP-86-style HD taproot descriptor over
75                // the FROST group's own xpub (built from the deterministic
76                // chaincode in PR 1) so `/0/*` and `/1/*` derive distinct
77                // receive- and change-address chains. Downstream wallets
78                // walk the xpub with the standard BIP-32 rules, and the
79                // FROST signing loop applies the matching composite tweak
80                // (PR 2 + PR 3) at spend time.
81                let xpub = group_xpub_string(group_pubkey, network)?;
82                let coin_type = if network == Network::Bitcoin { 0 } else { 1 };
83                canonicalize_descriptor(&format!(
84                    "tr([{fingerprint}/86'/{coin_type}'/0']{xpub}/0/*)"
85                ))?
86            }
87            Some(config) => {
88                let output = config.build_with_internal_key(&xonly)?;
89                canonicalize_descriptor(&output.descriptor)?
90            }
91        };
92
93        Ok(Self {
94            descriptor,
95            checksum,
96            fingerprint,
97            network,
98        })
99    }
100
101    pub fn pubkey_fingerprint(pubkey: &[u8; 32]) -> String {
102        let mut compressed = [0u8; 33];
103        compressed[0] = 0x02;
104        compressed[1..].copy_from_slice(pubkey);
105        let h = hash160::Hash::hash(&compressed);
106        hex::encode(&h[..4])
107    }
108
109    /// Return the raw Base58Check-encoded xpub string that
110    /// [`Self::from_frost_wallet`] wraps into its BIP-86 descriptor. Exposed
111    /// so callers exporting to other wallets (Sparrow, Electrum, BDK) can
112    /// hand off just the xpub without also parsing back the wrapping
113    /// descriptor.
114    pub fn frost_group_xpub(group_pubkey: &[u8; 32], network: Network) -> Result<String> {
115        group_xpub_string(group_pubkey, network)
116    }
117
118    pub fn external_descriptor(&self) -> &str {
119        &self.descriptor
120    }
121
122    pub fn internal_descriptor(&self) -> Result<String> {
123        let body = keep_core::descriptor::rewrite_trailing_zero_to_one(self.descriptor_body());
124        let (canonical, _) = canonicalize_descriptor(&body)?;
125        Ok(canonical)
126    }
127
128    pub fn is_single_chain(&self) -> bool {
129        let body = self.descriptor_body();
130        !keep_core::descriptor::has_single_path_tail(body)
131            && !keep_core::descriptor::has_multipath_marker(body)
132    }
133
134    fn descriptor_body(&self) -> &str {
135        self.descriptor
136            .split('#')
137            .next()
138            .unwrap_or(&self.descriptor)
139    }
140
141    pub fn multipath_descriptor(&self) -> Result<String> {
142        multipath_from_external(&self.descriptor)
143    }
144
145    pub fn to_sparrow_json(&self, name: &str) -> Result<String> {
146        if self.is_single_chain() {
147            return Err(BitcoinError::Descriptor(
148                "single-chain descriptor cannot be exported to Sparrow: external and change paths would collide causing address reuse".into(),
149            ));
150        }
151        let internal = self.internal_descriptor()?;
152
153        let json = serde_json::json!({
154            "name": name,
155            "network": match self.network {
156                Network::Bitcoin => "mainnet",
157                Network::Testnet => "testnet",
158                Network::Signet => "signet",
159                Network::Regtest => "regtest",
160                _ => "unknown",
161            },
162            "keystore": {
163                "type": "bip39",
164                "derivation": format!("m/86'/{}'/0'", if self.network == Network::Bitcoin { 0 } else { 1 }),
165            },
166            "outputDescriptor": self.descriptor,
167            "changeDescriptor": internal,
168        });
169
170        serde_json::to_string_pretty(&json).map_err(|e| BitcoinError::Descriptor(e.to_string()))
171    }
172}
173
174/// Build a BIP-389 multipath descriptor from a single-path external descriptor.
175///
176/// Rewrites every trailing `/0/*` key derivation to `/<0;1>/*`. Matching is
177/// anchored so only a `/0/*` that terminates a key expression (immediately
178/// followed by `,` or `)`, and preceded by a non-`/` character) is rewritten;
179/// occurrences inside longer paths or origin info are left alone. Descriptors
180/// containing a terminating `/1/*` (internal) path, or already holding
181/// `<1;0>` (reverse-order multipath), are rejected rather than silently
182/// coerced: swapping external and change order would produce divergent
183/// receive/change mappings across co-signers.
184pub fn multipath_from_external(external: &str) -> Result<String> {
185    let body = external.split('#').next().unwrap_or(external);
186
187    if keep_core::descriptor::contains_tail(body, '1') {
188        return Err(BitcoinError::Descriptor(
189            "descriptor contains /1/* internal path; expected external /0/* or multipath".into(),
190        ));
191    }
192    if body.contains("<1;0>") {
193        return Err(BitcoinError::Descriptor(
194            "descriptor uses <1;0> multipath order; reorder to <0;1> before building".into(),
195        ));
196    }
197
198    let normalized = keep_core::descriptor::rewrite_trailing_zero_star(body);
199
200    let (canonical, _) = canonicalize_descriptor(&normalized)?;
201    Ok(canonical)
202}
203
204/// Derive the `script_pubkey` for a definite (non-ranged) descriptor string.
205/// Used to bind a supplied [`crate::RecoveryOutput`] to the descriptor
206/// identified by a canonical hash before sweeping its coins. A recovery output
207/// is by definition a single, non-ranged output, so a ranged descriptor is
208/// rejected rather than silently resolved at an arbitrary index.
209pub fn descriptor_script_pubkey(descriptor: &str) -> Result<bitcoin::ScriptBuf> {
210    let parsed = parse_definite_descriptor(descriptor)?;
211    Ok(parsed.script_pubkey())
212}
213
214/// Derive the address for a definite (non-ranged) descriptor string on
215/// `network`. Used to pick the sweep destination from a finalized FROST wallet
216/// descriptor, which is definite (`tr(<xonly>,<tree>)`, no wildcard).
217pub fn descriptor_address(descriptor: &str, network: Network) -> Result<bitcoin::Address> {
218    let parsed = parse_definite_descriptor(descriptor)?;
219    parsed
220        .address(network)
221        .map_err(|e| BitcoinError::Descriptor(format!("address derivation failed: {e}")))
222}
223
224/// Resolve a ranged OR definite descriptor at a concrete derivation `index` and
225/// return its address on `network`. Unlike [`descriptor_address`], this accepts
226/// a ranged descriptor (`.../0/*`) by resolving it at `index` rather than
227/// rejecting it. Used to pick the single deterministic migration-sweep
228/// destination for a successor FROST wallet descriptor: `index` 0 is the first
229/// external `/0/0` receive address, which both proposer and responder derive
230/// identically from the same persisted descriptor.
231pub fn descriptor_address_at_index(
232    descriptor: &str,
233    network: Network,
234    index: u32,
235) -> Result<bitcoin::Address> {
236    let parsed = parse_descriptor_body(descriptor)?;
237    parsed
238        .at_derivation_index(index)
239        .map_err(|e| BitcoinError::Descriptor(format!("definite descriptor: {e}")))?
240        .address(network)
241        .map_err(|e| BitcoinError::Descriptor(format!("address derivation failed: {e}")))
242}
243
244/// Derive the change (internal, `/1/*`) `script_pubkey` at `index` from a
245/// BIP-86 external descriptor (`.../0/*`), applying the same `/0/* -> /1/*`
246/// rewrite as [`DescriptorExport::internal_descriptor`].
247///
248/// This is the single source of truth for "does this output pay to the
249/// wallet's own change branch". Callers compare the returned script against a
250/// PSBT output's `script_pubkey` (which is consensus-committed) rather than
251/// trusting the attacker-suppliable key-origin metadata in a PSBT output, which
252/// otherwise lets a payment to an attacker's address masquerade as change.
253pub fn change_script_at_index(
254    external_descriptor: &str,
255    network: Network,
256    index: u32,
257) -> Result<bitcoin::ScriptBuf> {
258    let parsed = parse_descriptor_body(external_descriptor)?;
259    if parsed.is_multipath() {
260        // BIP-389 multipath (`<0;1>`): the change branch is the second
261        // single-path descriptor. keep only builds/accepts external-first
262        // (`<0;1>`) order (see `multipath_from_external`).
263        let singles = parsed
264            .into_single_descriptors()
265            .map_err(|e| BitcoinError::Descriptor(format!("multipath descriptor: {e}")))?;
266        let change = singles.get(1).ok_or_else(|| {
267            BitcoinError::Descriptor("multipath descriptor missing change branch".into())
268        })?;
269        return Ok(change
270            .at_derivation_index(index)
271            .map_err(|e| BitcoinError::Descriptor(format!("definite descriptor: {e}")))?
272            .script_pubkey());
273    }
274    let body = external_descriptor
275        .split('#')
276        .next()
277        .unwrap_or(external_descriptor);
278    let internal_body = keep_core::descriptor::rewrite_trailing_zero_to_one(body);
279    let (internal, _) = canonicalize_descriptor(&internal_body)?;
280    Ok(descriptor_address_at_index(&internal, network, index)?.script_pubkey())
281}
282
283/// Build the raw Base58Check-encoded xpub for a FROST group by combining its
284/// x-only pubkey (lifted to its +even secp256k1 point) with the deterministic
285/// chaincode from #487 PR1. Depth 0, no parent, child number 0: this is the
286/// group's own xpub, not a derivation of anything above it.
287///
288/// Downstream wallets consume the xpub through the normal BIP-32 rules, and
289/// keep-frost-net's sign path applies the matching composite tweak (PR 2 +
290/// PR 3) so a `/0/N` receive-address spend produces a signature that BIP-340
291/// verifies against the address's key.
292fn group_xpub_string(group_pubkey: &[u8; 32], network: Network) -> Result<String> {
293    let network_kind = if network == Network::Bitcoin {
294        NetworkKind::Main
295    } else {
296        NetworkKind::Test
297    };
298    let mut compressed = [0u8; 33];
299    compressed[0] = 0x02;
300    compressed[1..].copy_from_slice(group_pubkey);
301    let public_key = PublicKey::from_slice(&compressed)
302        .map_err(|e| BitcoinError::Descriptor(format!("group pubkey not on curve: {e}")))?;
303    let chain_code = ChainCode::from(deterministic_chaincode(group_pubkey));
304    let xpub = Xpub {
305        network: network_kind,
306        depth: 0,
307        parent_fingerprint: Fingerprint::from([0u8; 4]),
308        child_number: ChildNumber::from_normal_idx(0)
309            .map_err(|e| BitcoinError::Descriptor(format!("child number 0: {e}")))?,
310        public_key,
311        chain_code,
312    };
313    Ok(xpub.to_string())
314}
315
316fn parse_definite_descriptor(
317    descriptor: &str,
318) -> Result<Descriptor<miniscript::DefiniteDescriptorKey>> {
319    let parsed = parse_descriptor_body(descriptor)?;
320    if parsed.has_wildcard() {
321        return Err(BitcoinError::Descriptor(
322            "descriptor is ranged; expected a definite output".into(),
323        ));
324    }
325    parsed
326        .at_derivation_index(0)
327        .map_err(|e| BitcoinError::Descriptor(format!("definite descriptor: {e}")))
328}
329
330fn parse_descriptor_body(descriptor: &str) -> Result<Descriptor<DescriptorPublicKey>> {
331    let body = descriptor.split('#').next().unwrap_or(descriptor);
332    body.parse()
333        .map_err(|e| BitcoinError::Descriptor(format!("invalid descriptor: {e}")))
334}
335
336fn canonicalize_descriptor(body: &str) -> Result<(String, String)> {
337    let parsed = parse_descriptor_body(body)?;
338    let canonical = parsed.to_string();
339    let (_, checksum) = canonical.rsplit_once('#').ok_or_else(|| {
340        BitcoinError::Descriptor("rust-miniscript returned descriptor without checksum".into())
341    })?;
342    let checksum = checksum.to_string();
343    Ok((canonical, checksum))
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    #[test]
351    fn test_descriptor_export() {
352        let secret = [1u8; 32];
353        let derivation = AddressDerivation::new(&secret, Network::Testnet).unwrap();
354
355        let export = DescriptorExport::from_derivation(&derivation, 0).unwrap();
356
357        assert!(export.descriptor.contains("tr("));
358        assert!(export.descriptor.contains("86'/1'/0'"));
359        assert!(export.descriptor.contains("#"));
360    }
361
362    #[test]
363    fn test_descriptor_address_for_definite_frost_wallet() {
364        use crate::recovery::{RecoveryTier, SpendingTier};
365
366        let group = test_group_pubkey();
367        let config = RecoveryConfig {
368            primary: SpendingTier {
369                keys: vec![test_keypair(1)],
370                threshold: 1,
371            },
372            recovery_tiers: vec![RecoveryTier {
373                keys: vec![test_keypair(2)],
374                threshold: 1,
375                timelock_months: 6,
376            }],
377            network: Network::Testnet,
378        };
379        // Real wallet descriptors are definite: tr(<xonly>,<tree>), no wildcard.
380        let export =
381            DescriptorExport::from_frost_wallet(&group, Some(&config), Network::Testnet).unwrap();
382
383        let addr = descriptor_address(&export.descriptor, Network::Testnet).unwrap();
384        assert!(addr.to_string().starts_with("tb1p"));
385
386        let spk = descriptor_script_pubkey(&export.descriptor).unwrap();
387        assert_eq!(addr.script_pubkey(), spk);
388    }
389
390    #[test]
391    fn test_descriptor_address_rejects_ranged_descriptor() {
392        let secret = [7u8; 32];
393        let derivation = AddressDerivation::new(&secret, Network::Testnet).unwrap();
394        let export = DescriptorExport::from_derivation(&derivation, 0).unwrap();
395        let err = descriptor_address(&export.descriptor, Network::Testnet).unwrap_err();
396        assert!(err.to_string().contains("ranged"));
397    }
398
399    #[test]
400    fn test_internal_descriptor() {
401        let secret = [2u8; 32];
402        let derivation = AddressDerivation::new(&secret, Network::Testnet).unwrap();
403
404        let export = DescriptorExport::from_derivation(&derivation, 0).unwrap();
405        let internal = export.internal_descriptor().unwrap();
406
407        assert!(internal.contains("/1/*)"));
408    }
409
410    #[test]
411    fn test_sparrow_export() {
412        let secret = [3u8; 32];
413        let derivation = AddressDerivation::new(&secret, Network::Testnet).unwrap();
414
415        let export = DescriptorExport::from_derivation(&derivation, 0).unwrap();
416        let json = export.to_sparrow_json("test-wallet").unwrap();
417
418        assert!(json.contains("test-wallet"));
419        assert!(json.contains("testnet"));
420    }
421
422    /// #487 PR 4: the address a downstream wallet derives from the emitted
423    /// descriptor at `/0/N` MUST have the x-only pubkey that
424    /// `keep_core::frost::bip32_signing::derive_child(group, &[0, N])`
425    /// produces. If these ever drift, wallets receive to addresses that
426    /// keep cannot sign for. Cross-check by pinning the descriptor and
427    /// deriving both sides for a few leaves.
428    #[test]
429    fn descriptor_addresses_match_bip32_signing_derivation() {
430        use bitcoin::bip32::{ChildNumber, DerivationPath, Xpub};
431        use bitcoin::secp256k1::Secp256k1;
432        use keep_core::frost::bip32_signing::derive_child;
433
434        let group = test_group_pubkey();
435        let export = DescriptorExport::from_frost_wallet(&group, None, Network::Testnet).unwrap();
436
437        // Extract the xpub embedded in the descriptor.
438        let xpub_str = DescriptorExport::frost_group_xpub(&group, Network::Testnet).unwrap();
439        let xpub: Xpub = xpub_str.parse().unwrap();
440        assert!(
441            export.descriptor.contains(xpub_str.as_str()),
442            "descriptor must embed the exact frost_group_xpub value"
443        );
444
445        let secp = Secp256k1::verification_only();
446        for leaf in [0u32, 1, 5, 100] {
447            let child_pubkey_bip32_signing = derive_child(&group, &[0, leaf]).unwrap().child_pubkey;
448
449            let path = DerivationPath::from(vec![
450                ChildNumber::from_normal_idx(0).unwrap(),
451                ChildNumber::from_normal_idx(leaf).unwrap(),
452            ]);
453            let derived_xpub = xpub.derive_pub(&secp, &path).unwrap();
454            let child_pubkey_descriptor = derived_xpub.public_key.x_only_public_key().0.serialize();
455
456            assert_eq!(
457                child_pubkey_descriptor, child_pubkey_bip32_signing,
458                "leaf {leaf}: descriptor-derived key MUST equal FROST-signing child"
459            );
460
461            let change_pubkey_bip32_signing =
462                derive_child(&group, &[1, leaf]).unwrap().child_pubkey;
463
464            let change_path = DerivationPath::from(vec![
465                ChildNumber::from_normal_idx(1).unwrap(),
466                ChildNumber::from_normal_idx(leaf).unwrap(),
467            ]);
468            let derived_change_xpub = xpub.derive_pub(&secp, &change_path).unwrap();
469            let change_pubkey_descriptor = derived_change_xpub
470                .public_key
471                .x_only_public_key()
472                .0
473                .serialize();
474
475            assert_eq!(
476                change_pubkey_descriptor, change_pubkey_bip32_signing,
477                "leaf {leaf}: CHANGE-chain descriptor-derived key MUST equal FROST-signing child"
478            );
479        }
480    }
481
482    #[test]
483    fn change_script_at_index_uses_internal_branch() {
484        let group = test_group_pubkey();
485        let export = DescriptorExport::from_frost_wallet(&group, None, Network::Testnet).unwrap();
486        let external = export.external_descriptor();
487        let net = Network::Testnet;
488
489        let change0 = change_script_at_index(external, net, 0).unwrap();
490        // Change (`/1/0`) must differ from the external receive script (`/0/0`).
491        let recv0 = descriptor_address_at_index(external, net, 0)
492            .unwrap()
493            .script_pubkey();
494        assert_ne!(change0, recv0, "change /1/0 must differ from receive /0/0");
495        // And must equal the internal descriptor derived at the same index.
496        let internal = export.internal_descriptor().unwrap();
497        let internal0 = descriptor_address_at_index(&internal, net, 0)
498            .unwrap()
499            .script_pubkey();
500        assert_eq!(change0, internal0);
501        // Distinct indices produce distinct change scripts.
502        assert_ne!(change0, change_script_at_index(external, net, 1).unwrap());
503
504        // A BIP-389 multipath (`<0;1>`) descriptor resolves the same change
505        // branch as the single-path external form.
506        let multipath = export.multipath_descriptor().unwrap();
507        assert_eq!(change0, change_script_at_index(&multipath, net, 0).unwrap());
508        assert_eq!(
509            change_script_at_index(external, net, 3).unwrap(),
510            change_script_at_index(&multipath, net, 3).unwrap()
511        );
512    }
513
514    #[test]
515    fn change_script_at_index_accepts_definite_descriptor() {
516        // A definite (non-ranged) taproot descriptor has no /0/* tail: it reuses
517        // one script, so change is index-independent. It must be accepted, not
518        // rejected, and never index-dependent.
519        let group = test_group_pubkey();
520        let xonly_hex: String = group.iter().map(|b| format!("{b:02x}")).collect();
521        let definite = format!("tr({xonly_hex})");
522        let net = Network::Testnet;
523        let s0 = change_script_at_index(&definite, net, 0).unwrap();
524        let s7 = change_script_at_index(&definite, net, 7).unwrap();
525        assert_eq!(s0, s7, "definite descriptor is index-independent");
526    }
527
528    /// #487 PR 4: the mainnet output users actually ship uses BIP-86
529    /// `coin_type` 0 and an `xpub` (not tpub) prefix. Testnet/Signet tests
530    /// exercise `coin_type` 1 only, so pin the mainnet branch explicitly.
531    #[test]
532    fn frost_wallet_mainnet_descriptor_uses_coin_type_0() {
533        let group = test_group_pubkey();
534        let export = DescriptorExport::from_frost_wallet(&group, None, Network::Bitcoin).unwrap();
535
536        let fingerprint = export.fingerprint;
537        assert!(
538            export
539                .descriptor
540                .starts_with(&format!("tr([{fingerprint}/86'/0'/0']")),
541            "mainnet descriptor must use coin_type 0: {}",
542            export.descriptor
543        );
544        assert!(
545            export.descriptor.contains("xpub"),
546            "mainnet descriptor must embed an xpub, not a tpub: {}",
547            export.descriptor
548        );
549        assert!(
550            export.descriptor.contains("/0/*)"),
551            "mainnet descriptor must be a ranged external chain: {}",
552            export.descriptor
553        );
554    }
555
556    /// #487 PR 4: the external chain (`/0/*`) and internal chain (`/1/*`)
557    /// produce distinct addresses at every leaf. This is the property that
558    /// justified the whole issue (address diversity for receive vs change).
559    #[test]
560    fn external_and_internal_leaves_produce_distinct_addresses() {
561        use bitcoin::bip32::{ChildNumber, DerivationPath, Xpub};
562        use bitcoin::secp256k1::Secp256k1;
563
564        let group = test_group_pubkey();
565        let xpub_str = DescriptorExport::frost_group_xpub(&group, Network::Testnet).unwrap();
566        let xpub: Xpub = xpub_str.parse().unwrap();
567        let secp = Secp256k1::verification_only();
568
569        for leaf in 0u32..8 {
570            let ext = xpub
571                .derive_pub(
572                    &secp,
573                    &DerivationPath::from(vec![
574                        ChildNumber::from_normal_idx(0).unwrap(),
575                        ChildNumber::from_normal_idx(leaf).unwrap(),
576                    ]),
577                )
578                .unwrap()
579                .public_key
580                .x_only_public_key()
581                .0
582                .serialize();
583            let int = xpub
584                .derive_pub(
585                    &secp,
586                    &DerivationPath::from(vec![
587                        ChildNumber::from_normal_idx(1).unwrap(),
588                        ChildNumber::from_normal_idx(leaf).unwrap(),
589                    ]),
590                )
591                .unwrap()
592                .public_key
593                .x_only_public_key()
594                .0
595                .serialize();
596            assert_ne!(ext, int, "leaf {leaf}: external and internal must differ");
597        }
598    }
599
600    fn test_group_pubkey() -> [u8; 32] {
601        use bitcoin::secp256k1::{Keypair, Secp256k1};
602        let secp = Secp256k1::new();
603        let secret = [42u8; 32];
604        let kp = Keypair::from_seckey_slice(&secp, &secret).unwrap();
605        kp.x_only_public_key().0.serialize()
606    }
607
608    fn test_keypair(seed: u8) -> [u8; 32] {
609        use bitcoin::secp256k1::{Keypair, Secp256k1};
610        let secp = Secp256k1::new();
611        let mut secret = [seed; 32];
612        secret[0] = seed.wrapping_add(1);
613        let kp = Keypair::from_seckey_slice(&secp, &secret).unwrap();
614        kp.x_only_public_key().0.serialize()
615    }
616
617    #[test]
618    fn test_frost_wallet_simple_descriptor() {
619        // #487 PR 4: non-recovery FROST descriptor is now an xpub-shaped
620        // BIP-86 descriptor (`tr([fp/86'/coin_type'/0']xpub/0/*)`) rather
621        // than a static `tr(xonly)`, so `/0/*` and `/1/*` derive distinct
622        // receive- and change-address chains.
623        let group_pk = test_group_pubkey();
624        let export =
625            DescriptorExport::from_frost_wallet(&group_pk, None, Network::Testnet).unwrap();
626
627        // Fingerprint is the same lift-then-hash rule as always.
628        let fingerprint = DescriptorExport::pubkey_fingerprint(&group_pk);
629        assert!(
630            export
631                .descriptor
632                .starts_with(&format!("tr([{fingerprint}/86'/1'/0']")),
633            "descriptor must open with the expected BIP-86 origin: got {}",
634            export.descriptor
635        );
636        // Wraps an xpub (tpub for testnet) followed by the receive path.
637        assert!(export.descriptor.contains("tpub"));
638        assert!(export.descriptor.contains("/0/*)"));
639        // A canonicalized checksum is appended after the descriptor body.
640        assert!(export.descriptor.contains('#'));
641        // #487 whole point: internal and external are no longer equal.
642        assert_ne!(
643            export.internal_descriptor().unwrap(),
644            export.descriptor,
645            "external `/0/*` and internal `/1/*` chains MUST differ (#487)"
646        );
647    }
648
649    #[test]
650    fn test_frost_wallet_with_recovery() {
651        use crate::recovery::{RecoveryTier, SpendingTier};
652
653        let group_pk = test_group_pubkey();
654        let pk1 = test_keypair(1);
655        let pk2 = test_keypair(2);
656
657        let config = RecoveryConfig {
658            primary: SpendingTier {
659                keys: vec![pk1],
660                threshold: 1,
661            },
662            recovery_tiers: vec![RecoveryTier {
663                keys: vec![pk2],
664                threshold: 1,
665                timelock_months: 6,
666            }],
667            network: Network::Testnet,
668        };
669
670        let export =
671            DescriptorExport::from_frost_wallet(&group_pk, Some(&config), Network::Testnet)
672                .unwrap();
673
674        let xonly = XOnlyPublicKey::from_slice(&group_pk).unwrap();
675        assert!(export.descriptor.starts_with(&format!("tr({xonly},")));
676        assert!(export.descriptor.contains("older("));
677        assert!(export.descriptor.contains('#'));
678    }
679
680    #[test]
681    fn test_xpub_to_x_only_testnet() {
682        use bitcoin::bip32::{Xpriv, Xpub};
683        use bitcoin::secp256k1::Secp256k1;
684        let secp = Secp256k1::new();
685        let secret = [42u8; 32];
686
687        let xpriv = Xpriv::new_master(Network::Testnet, &secret).unwrap();
688        let xpub = Xpub::from_priv(&secp, &xpriv);
689        let xpub_str = xpub.to_string();
690
691        let result = xpub_to_x_only(&xpub_str, Network::Testnet).unwrap();
692        let result_xonly = XOnlyPublicKey::from_slice(&result).unwrap();
693
694        assert_eq!(result_xonly, xpub.to_x_only_pub());
695    }
696
697    #[test]
698    fn test_xpub_to_x_only_invalid() {
699        assert!(xpub_to_x_only("not-an-xpub", Network::Testnet).is_err());
700    }
701
702    #[test]
703    fn test_xpub_to_x_only_network_mismatch() {
704        use bitcoin::bip32::{Xpriv, Xpub};
705        use bitcoin::secp256k1::Secp256k1;
706        let secp = Secp256k1::new();
707        let xpriv = Xpriv::new_master(Network::Testnet, &[42u8; 32]).unwrap();
708        let xpub = Xpub::from_priv(&secp, &xpriv);
709        let xpub_str = xpub.to_string();
710
711        assert!(xpub_to_x_only(&xpub_str, Network::Bitcoin).is_err());
712    }
713
714    #[test]
715    fn test_multipath_rewrites_single_key() {
716        let out = multipath_from_external("tr(xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz/0/*)").unwrap();
717        let body = out.split('#').next().unwrap();
718        assert!(body.ends_with("/<0;1>/*)"));
719        assert!(!body.contains("/0/*)"));
720    }
721
722    #[test]
723    fn test_multipath_preserves_already_multipath() {
724        let out = multipath_from_external(
725            "tr(xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz/<0;1>/*)",
726        )
727        .unwrap();
728        let body = out.split('#').next().unwrap();
729        assert!(body.ends_with("/<0;1>/*)"));
730        assert_eq!(body.matches("<0;1>").count(), 1);
731    }
732
733    #[test]
734    fn test_multipath_normalizes_mixed_multisig() {
735        let xpub = "xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz";
736        let input = format!("wsh(sortedmulti(2,{xpub}/<0;1>/*,{xpub}/0/*))");
737        let out = multipath_from_external(&input).unwrap();
738        let body = out.split('#').next().unwrap();
739        assert_eq!(body.matches("<0;1>").count(), 2);
740        assert!(!body.contains("/0/*,"));
741        assert!(!body.contains("/0/*)"));
742    }
743
744    #[test]
745    fn test_multipath_leaves_origin_info_alone() {
746        let out = multipath_from_external(
747            "tr([deadbeef/86'/0'/0']xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz/0/*)",
748        )
749        .unwrap();
750        let body = out.split('#').next().unwrap();
751        assert!(body.contains("[deadbeef/86'/0'/0']"));
752        assert!(body.ends_with("/<0;1>/*)"));
753    }
754
755    #[test]
756    fn test_multipath_does_not_mangle_nested_paths() {
757        // xpub/0/0/*) must become xpub/0/<0;1>/*), not xpub/<0;1>/*.
758        let input = "tr(xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz/0/0/*)";
759        let out = multipath_from_external(input).unwrap();
760        let body = out.split('#').next().unwrap();
761        assert!(body.ends_with("/0/<0;1>/*)"));
762    }
763
764    #[test]
765    fn test_multipath_no_derivation_tail_unchanged() {
766        // Bare descriptor with no /0/* tail: body should be unchanged aside
767        // from the appended checksum.
768        let xpub = "xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz";
769        let input = format!("tr({xpub})");
770        let out = multipath_from_external(&input).unwrap();
771        let body = out.split('#').next().unwrap();
772        assert_eq!(body, input);
773    }
774
775    #[test]
776    fn test_multipath_rejects_internal_only_descriptor() {
777        let err = multipath_from_external("tr(xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz/1/*)");
778        assert!(err.is_err());
779    }
780
781    #[test]
782    fn test_multipath_rejects_reverse_order_marker() {
783        let xpub = "xpub6CUGRUonZSQ4TWtTMmzXdrXDtypWKiKrhko4egpiMZbpiaQL2jkwSB1icqYh2cfDfVxdx4df189oLKnC5fSwqPfgyP3hooxujYzAu3fDVmz";
784        let input = format!("wsh(sortedmulti(2,{xpub}/<1;0>/*,{xpub}/<0;1>/*))");
785        let err = multipath_from_external(&input).unwrap_err();
786        let msg = err.to_string();
787        assert!(msg.contains("<1;0>"), "unexpected error: {msg}");
788    }
789
790    #[test]
791    fn test_descriptor_round_trips_through_miniscript() {
792        use crate::recovery::{RecoveryTier, SpendingTier};
793        use bitcoin::secp256k1::{Keypair, Secp256k1};
794        use miniscript::{Descriptor, DescriptorPublicKey};
795
796        let secp = Secp256k1::new();
797        let seeded = |seed: u8| -> [u8; 32] {
798            let kp = Keypair::from_seckey_slice(&secp, &[seed; 32]).unwrap();
799            kp.x_only_public_key().0.serialize()
800        };
801
802        let group_pk = seeded(0x42);
803        let primary_pk = seeded(0x10);
804        let recovery1_pk = seeded(0x20);
805        let recovery2_pk = seeded(0x30);
806
807        let config = RecoveryConfig {
808            primary: SpendingTier {
809                keys: vec![primary_pk, group_pk],
810                threshold: 2,
811            },
812            recovery_tiers: vec![
813                RecoveryTier {
814                    keys: vec![recovery1_pk],
815                    threshold: 1,
816                    timelock_months: 6,
817                },
818                RecoveryTier {
819                    keys: vec![recovery2_pk],
820                    threshold: 1,
821                    timelock_months: 12,
822                },
823            ],
824            network: Network::Signet,
825        };
826
827        let export =
828            DescriptorExport::from_frost_wallet(&group_pk, Some(&config), Network::Signet).unwrap();
829
830        let external = export.external_descriptor().to_string();
831
832        let external_roundtrip = Descriptor::<DescriptorPublicKey>::from_str(&external)
833            .unwrap()
834            .to_string();
835        assert_eq!(external, external_roundtrip);
836
837        let (_, emitted_checksum) = external.rsplit_once('#').unwrap();
838        assert_eq!(emitted_checksum.len(), 8);
839        assert!(
840            emitted_checksum
841                .chars()
842                .all(|c| "qpzry9x8gf2tvdw0s3jn54khce6mua7l".contains(c)),
843            "checksum {emitted_checksum} contains non-BIP-380 charset chars"
844        );
845    }
846
847    #[test]
848    fn test_reference_descriptor_canonical_form() {
849        // Guards against accidental miniscript version bumps that shift
850        // canonical descriptor formatting. The emitted descriptor string is a
851        // consensus value across FROST peers; if this literal changes, mixed
852        // miniscript versions will break descriptor coordination.
853        // secp256k1 generator point G x-coordinate; stable, known-valid x-only key.
854        let xonly = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798";
855        let expected =
856            "tr(79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798)#gxjkeue2";
857        let (canonical, _) = canonicalize_descriptor(&format!("tr({xonly})")).unwrap();
858        assert_eq!(canonical, expected);
859    }
860
861    #[test]
862    fn test_frost_wallet_descriptor_has_checksum() {
863        let group_pk = test_group_pubkey();
864        let export =
865            DescriptorExport::from_frost_wallet(&group_pk, None, Network::Testnet).unwrap();
866
867        assert!(export.descriptor.contains('#'));
868        assert_eq!(export.checksum.len(), 8);
869
870        let parts: Vec<&str> = export.descriptor.split('#').collect();
871        assert_eq!(parts.len(), 2);
872        assert_eq!(parts[1], export.checksum);
873    }
874}