Skip to main content

keep_core/
frost_bip32.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! BIP-32 child-key primitives for FROST group keys (#487, PR 1 of 4).
5//!
6//! A FROST group holds a single aggregated schnorr key. That key alone is not
7//! a BIP-32 HD tree; it has no chaincode and no derivation path, so `wallet
8//! descriptor` collapses `/0/*` and `/1/*` into the same address and every
9//! receive plus every change output reuses the same script.
10//!
11//! This module ships the crypto foundation for a proper HD wallet on top of a
12//! FROST group without touching signing, wire format, or the descriptor
13//! emitter. Subsequent PRs (see #487) wire (a) FROST signing under the
14//! composed BIP-32 + BIP-341 tweak, (b) the sign wire protocol carrying the
15//! derivation path, and (c) descriptor emission using the resulting xpub. All
16//! three depend on the primitives here matching a reference impl exactly.
17//!
18//! Design choices captured for the review of #487:
19//!
20//! - **Chaincode is deterministic from the group pubkey**, `sha256(DOMAIN ||
21//!   group_pubkey_x_only)`. No storage bump, no protocol change, and the same
22//!   chaincode falls out on every share by construction (it depends only on
23//!   the public group key, which every share already carries). BIP-32
24//!   chaincodes are not secret; they are part of the xpub. Using a
25//!   deterministic derivation makes them shareable without a separate wire.
26//! - **BIP-32 unhardened public derivation only**: hardened derivation needs
27//!   the private key. FROST groups do not have one to hand around, so
28//!   hardened derivation is architecturally out of scope for HD receive/
29//!   change chains. This matches BIP-86 taproot single-sig practice (`/0/*`
30//!   and `/1/*` are both unhardened).
31//! - **X-only pubkeys** as the public interface: the group key surfaces
32//!   everywhere in this codebase as a BIP-340 x-only 32-byte value, so the
33//!   primitive returns x-only child pubkeys. Internally we work with the
34//!   compressed 33-byte form because that is what `HMAC-SHA512` hashes in the
35//!   BIP-32 spec. A bare x-only input (the group key, or a single-step
36//!   `derive_child` parent) is lifted to its +even point (0x02 prefix), matching
37//!   how BIP-340 recovers a key from an x-only value. Crucially, a multi-level
38//!   `derive_path` walk carries each intermediate node's *true* compressed parity
39//!   into the next HMAC, exactly as BIP-32 `ckd_pub` does; it does not re-lift
40//!   intermediates to even, so derivation stays byte-for-byte conformant at every
41//!   depth (a receive/change leaf under an odd-y `/0` or `/1` node still matches).
42//!
43//! Reference vectors are cross-checked against `bitcoin::bip32::Xpub::derive_pub`
44//! in tests, so any drift from BIP-32 fails a unit test.
45
46use bitcoin::hashes::{sha256, sha512, Hash as _, HashEngine as _, Hmac, HmacEngine};
47use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
48
49use crate::error::{KeepError, Result};
50
51/// Local shim so downstream call sites (moved from keep-bitcoin in #487 PR2)
52/// keep using the same variant name for BIP-32 pathing errors. Every
53/// derivation failure is reported as `KeepError::Frost(...)` under the hood.
54#[inline]
55fn derivation_path_error(msg: impl Into<String>) -> KeepError {
56    KeepError::Frost(msg.into())
57}
58
59/// Domain separator for the deterministic chaincode. Bumping the version tag
60/// invalidates every previously derived child; keep it stable across releases.
61const CHAINCODE_DOMAIN: &[u8] = b"keep-frost-bip32-chaincode-v1";
62
63/// BIP-32 says child index >= 2^31 selects hardened derivation, which needs
64/// the private key. FROST groups only ever do unhardened public derivation
65/// (see the module doc), so every index must live below the hardened bit.
66pub const HARDENED_INDEX_START: u32 = 0x8000_0000;
67
68/// Maximum derivation-path length accepted by the path walkers. BIP-32's own
69/// serialized `depth` field is a single byte, so 255 is the natural ceiling;
70/// a real receive/change path is length 2. Bounding it keeps a wire-supplied
71/// path (see #487) from forcing unbounded HMAC-SHA512 + EC work on a signer.
72pub const MAX_DERIVATION_DEPTH: usize = 255;
73
74/// Derive the deterministic 32-byte chaincode for a FROST group key.
75///
76/// `group_pubkey` is the BIP-340 x-only 32-byte aggregated FROST group key.
77/// The result is a domain-separated sha256 hash so a chaincode collision
78/// implies a sha256 collision.
79pub fn deterministic_chaincode(group_pubkey: &[u8; 32]) -> [u8; 32] {
80    let mut engine = sha256::Hash::engine();
81    engine.input(CHAINCODE_DOMAIN);
82    engine.input(group_pubkey);
83    sha256::Hash::from_engine(engine).to_byte_array()
84}
85
86/// Result of one BIP-32 unhardened public derivation step.
87///
88/// `tweak` is the scalar that must be added to the parent point (and, in the
89/// FROST signing path, to every co-signer's share) to produce the child key.
90/// `child_chaincode` feeds into the next derivation step along the path.
91/// `child_pubkey` is the x-only 32-byte child public key.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub struct ChildDerivation {
94    /// Scalar tweak `IL` from BIP-32 (the left 32 bytes of the HMAC output).
95    pub tweak: [u8; 32],
96    /// Next-level chaincode `IR` from BIP-32 (the right 32 bytes).
97    pub child_chaincode: [u8; 32],
98    /// Child public key as a BIP-340 x-only 32-byte value.
99    pub child_pubkey: [u8; 32],
100}
101
102/// Lift a BIP-340 x-only value to its +even (0x02 prefix) secp256k1 point,
103/// which is how BIP-340 recovers a public key from a bare x-only value.
104fn even_lift(xonly: &[u8; 32]) -> Result<PublicKey> {
105    let mut compressed = [0u8; 33];
106    compressed[0] = 0x02;
107    compressed[1..].copy_from_slice(xonly);
108    PublicKey::from_slice(&compressed)
109        .map_err(|e| derivation_path_error(format!("x-only pubkey not on curve: {e}")))
110}
111
112/// One BIP-32 unhardened `ckd_pub` step on a full parent point.
113///
114/// Serializes the parent with its *true* compressed parity (0x02 or 0x03) into
115/// the HMAC, exactly as the spec requires, and returns the real child point so
116/// callers can chain further steps without discarding parity. Returns the
117/// scalar tweak `IL`, the child chaincode `IR`, and the child point.
118fn ckd_pub_point(
119    parent_point: &PublicKey,
120    chaincode: &[u8; 32],
121    index: u32,
122) -> Result<([u8; 32], [u8; 32], PublicKey)> {
123    if index >= HARDENED_INDEX_START {
124        return Err(derivation_path_error(format!(
125            "hardened index {index} not supported for FROST groups; \
126             only unhardened public derivation is meaningful without a group secret"
127        )));
128    }
129    // BIP-32 unhardened: HMAC-SHA512(chaincode, ser_P(parent_point) || ser32(index)),
130    // where ser_P is the 33-byte compressed pubkey carrying the parent's real parity.
131    let compressed = parent_point.serialize();
132    let mut engine = HmacEngine::<sha512::Hash>::new(chaincode);
133    engine.input(&compressed);
134    engine.input(&index.to_be_bytes());
135    let i = Hmac::<sha512::Hash>::from_engine(engine).to_byte_array();
136
137    let mut tweak = [0u8; 32];
138    tweak.copy_from_slice(&i[..32]);
139    let mut child_chaincode = [0u8; 32];
140    child_chaincode.copy_from_slice(&i[32..]);
141
142    let scalar = Scalar::from_be_bytes(tweak).map_err(|_| {
143        // BIP-32 says: "In case parse256(IL) >= n or Ki is the point at infinity,
144        // the resulting key is invalid, and one should proceed with the next
145        // value for i." We surface this so callers can retry at their layer;
146        // for the deterministic chaincode + reasonable indexes this has
147        // never been observed in practice.
148        derivation_path_error(format!(
149            "BIP-32 child tweak >= curve order at index {index}; caller must skip to next index"
150        ))
151    })?;
152    let secp = Secp256k1::verification_only();
153    let child_point = parent_point.add_exp_tweak(&secp, &scalar).map_err(|e| {
154        derivation_path_error(format!("BIP-32 child tweak produced invalid point: {e}"))
155    })?;
156    Ok((tweak, child_chaincode, child_point))
157}
158
159/// Derive one BIP-32 unhardened child of the given (parent_pubkey, chaincode)
160/// pair. Refuses hardened indexes (>= 2^31) and refuses the vanishingly rare
161/// case where the HMAC left-half scalar is >= n (spec-mandated retry with a
162/// different path segment; we surface it as an error so callers can react).
163///
164/// `parent_pubkey` is a bare x-only value and is lifted to its +even point, so
165/// this is only conformant as a single step off the group key. For a multi-level
166/// walk use [`derive_path`], which threads each intermediate node's true parity;
167/// re-feeding this function's x-only output as the next parent would force even
168/// parity and diverge from BIP-32 whenever an intermediate node has odd y.
169pub fn derive_child(
170    parent_pubkey: &[u8; 32],
171    chaincode: &[u8; 32],
172    index: u32,
173) -> Result<ChildDerivation> {
174    let parent_point = even_lift(parent_pubkey)?;
175    let (tweak, child_chaincode, child_point) = ckd_pub_point(&parent_point, chaincode, index)?;
176    Ok(ChildDerivation {
177        tweak,
178        child_chaincode,
179        child_pubkey: child_point.x_only_public_key().0.serialize(),
180    })
181}
182
183/// Result of walking a full BIP-32 path, with the aggregate scalar tweak
184/// needed to reproduce the terminal child key from the +even lift of the
185/// group key. Used by FROST signing so every co-signer applies one
186/// composite tweak to its share instead of walking the tree per signer.
187///
188/// BIP-32 unhardened tweaks compose additively over the group:
189/// `child_final = group_lifted + t_agg·G (mod n)` where `t_agg = sum(t_i)`
190/// with each `t_i` computed against the actual on-curve parent point at
191/// its own depth. The stepwise tweaks are NOT interchangeable with the
192/// aggregate at intermediate depths (the HMAC input at level `i+1` depends
193/// on level `i`'s real parity, not on any x-only summary), so callers that
194/// want the aggregate must use this walker.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub struct CompositeDerivation {
197    /// Aggregate BIP-32 scalar tweak: applying it once to every FROST
198    /// signing share (mod n) and the group verifying key produces a
199    /// tweaked signing set whose aggregate signature verifies under
200    /// [`Self::child_pubkey`]. This is the single scalar the composed
201    /// BIP-32 + BIP-341 sign path passes to `KeyPackage`.
202    pub aggregate_tweak: [u8; 32],
203    /// Terminal chaincode. Callers walking children below the terminal
204    /// node (e.g. a wallet exposing further sub-paths) use it as the
205    /// parent chaincode for the next step.
206    pub terminal_chaincode: [u8; 32],
207    /// Terminal x-only child public key: the address-forming key at the
208    /// end of the path, and the key an aggregated signature must verify
209    /// against.
210    pub child_pubkey: [u8; 32],
211}
212
213/// Walk a BIP-32 path and return the aggregate scalar tweak plus the
214/// terminal chaincode and x-only child pubkey. Refuses hardened indexes
215/// and refuses paths whose stepwise tweaks aggregate to zero mod n (an
216/// invalid signing key; also a BIP-32-spec-mandated retry condition).
217pub fn derive_path_composite(
218    group_pubkey: &[u8; 32],
219    chaincode: &[u8; 32],
220    path: &[u32],
221) -> Result<CompositeDerivation> {
222    if path.is_empty() {
223        return Err(derivation_path_error(
224            "derive_path_composite requires at least one index",
225        ));
226    }
227    if path.len() > MAX_DERIVATION_DEPTH {
228        return Err(derivation_path_error(format!(
229            "derivation path length {} exceeds maximum {MAX_DERIVATION_DEPTH}",
230            path.len()
231        )));
232    }
233    let mut parent_point = even_lift(group_pubkey)?;
234    let mut parent_chaincode = *chaincode;
235
236    // Accumulate the scalar tweak in a SecretKey for modular add_tweak
237    // arithmetic. The value is not a secret (chaincodes and unhardened
238    // tweaks are public by construction), we just reuse the API surface
239    // for its mod-n scalar addition. Seed with the first step's tweak.
240    let first_index = path[0];
241    let (first_tweak, first_cc, first_point) =
242        ckd_pub_point(&parent_point, &parent_chaincode, first_index)?;
243    let mut acc = SecretKey::from_slice(&first_tweak).map_err(|e| {
244        derivation_path_error(format!("BIP-32 first tweak is not a valid scalar: {e}"))
245    })?;
246    parent_point = first_point;
247    parent_chaincode = first_cc;
248
249    for &index in &path[1..] {
250        let (step_tweak, step_cc, step_point) =
251            ckd_pub_point(&parent_point, &parent_chaincode, index)?;
252        let step_scalar = Scalar::from_be_bytes(step_tweak).map_err(|_| {
253            derivation_path_error(format!("BIP-32 step tweak >= curve order at index {index}"))
254        })?;
255        acc = acc.add_tweak(&step_scalar).map_err(|e| {
256            derivation_path_error(format!(
257                "BIP-32 aggregate tweak became invalid at index {index}: {e}"
258            ))
259        })?;
260        parent_point = step_point;
261        parent_chaincode = step_cc;
262    }
263
264    let aggregate_tweak = acc.secret_bytes();
265    // Sanity-check invariant: applying the aggregate tweak to the +even
266    // lift of the group key must reproduce the terminal child point.
267    // Any drift here means the composite tweak cannot be used for FROST
268    // signing under the derived child key, which is the whole point of
269    // this helper. Refuse rather than return an unsigned-worthy tweak.
270    let secp = Secp256k1::verification_only();
271    let reproduced = even_lift(group_pubkey)?
272        .add_exp_tweak(
273            &secp,
274            &Scalar::from_be_bytes(aggregate_tweak).map_err(|_| {
275                derivation_path_error("aggregate tweak >= curve order after accumulation")
276            })?,
277        )
278        .map_err(|e| {
279            derivation_path_error(format!("aggregate tweak produced invalid point: {e}"))
280        })?;
281    if reproduced != parent_point {
282        return Err(derivation_path_error(
283            "composed BIP-32 tweak does not reproduce terminal child point; \
284             signing under the aggregate would diverge from stepwise derivation",
285        ));
286    }
287
288    Ok(CompositeDerivation {
289        aggregate_tweak,
290        terminal_chaincode: parent_chaincode,
291        child_pubkey: parent_point.x_only_public_key().0.serialize(),
292    })
293}
294
295/// Walk a full BIP-32 path (all unhardened) starting from the group key and
296/// its deterministic chaincode, returning the terminal derivation. Convenience
297/// wrapper: the descriptor path `m/0/*` at index N is `derive_path(&[0, N])`.
298///
299/// The group key is lifted to its +even point once; every intermediate node's
300/// true compressed parity is then carried into the next HMAC, so the walk stays
301/// byte-for-byte BIP-32 conformant even under odd-y intermediate nodes.
302pub fn derive_path(
303    group_pubkey: &[u8; 32],
304    chaincode: &[u8; 32],
305    path: &[u32],
306) -> Result<ChildDerivation> {
307    if path.is_empty() {
308        return Err(derivation_path_error(
309            "derive_path requires at least one index",
310        ));
311    }
312    if path.len() > MAX_DERIVATION_DEPTH {
313        return Err(derivation_path_error(format!(
314            "derivation path length {} exceeds maximum {MAX_DERIVATION_DEPTH}",
315            path.len()
316        )));
317    }
318    let mut parent_point = even_lift(group_pubkey)?;
319    let mut parent_chaincode = *chaincode;
320    let mut last: Option<ChildDerivation> = None;
321    for &index in path {
322        let (tweak, child_chaincode, child_point) =
323            ckd_pub_point(&parent_point, &parent_chaincode, index)?;
324        parent_point = child_point;
325        parent_chaincode = child_chaincode;
326        last = Some(ChildDerivation {
327            tweak,
328            child_chaincode,
329            child_pubkey: child_point.x_only_public_key().0.serialize(),
330        });
331    }
332    Ok(last.expect("non-empty path always sets last"))
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use bitcoin::bip32::{ChainCode, ChildNumber, Xpub};
339    use bitcoin::secp256k1::SecretKey;
340    use bitcoin::NetworkKind;
341
342    /// A stable, well-formed FROST-group-shaped x-only pubkey. Generated from
343    /// a fixed secret so the reference vectors below are reproducible.
344    fn stable_group_pubkey() -> [u8; 32] {
345        let secp = Secp256k1::signing_only();
346        let sk = SecretKey::from_slice(&[0x42; 32]).unwrap();
347        let (xonly, _) = sk.x_only_public_key(&secp);
348        xonly.serialize()
349    }
350
351    /// #487 PR1: the same group pubkey always yields the same chaincode, so
352    /// every share can reproduce it locally without a wire exchange.
353    #[test]
354    fn chaincode_is_deterministic() {
355        let group = stable_group_pubkey();
356        let cc1 = deterministic_chaincode(&group);
357        let cc2 = deterministic_chaincode(&group);
358        assert_eq!(cc1, cc2);
359    }
360
361    /// Two different group pubkeys must yield different chaincodes so a
362    /// child derived from group A cannot accidentally match a child from B.
363    #[test]
364    fn chaincode_differs_per_group_pubkey() {
365        let a = stable_group_pubkey();
366        let mut b = a;
367        b[0] ^= 0x01;
368        assert_ne!(deterministic_chaincode(&a), deterministic_chaincode(&b));
369    }
370
371    /// Hardened indexes are refused, not silently accepted. This is
372    /// architectural: without the group secret there is no meaningful
373    /// hardened derivation.
374    #[test]
375    fn hardened_index_refused() {
376        let group = stable_group_pubkey();
377        let cc = deterministic_chaincode(&group);
378        let err = derive_child(&group, &cc, HARDENED_INDEX_START)
379            .expect_err("hardened index must be refused");
380        assert!(matches!(err, KeepError::Frost(_)));
381        // The last unhardened index still works.
382        derive_child(&group, &cc, HARDENED_INDEX_START - 1).unwrap();
383    }
384
385    /// Different indexes off the same parent produce different child pubkeys
386    /// (address diversity along the `/0/*` chain).
387    #[test]
388    fn distinct_indexes_yield_distinct_child_pubkeys() {
389        let group = stable_group_pubkey();
390        let cc = deterministic_chaincode(&group);
391        let a = derive_child(&group, &cc, 0).unwrap().child_pubkey;
392        let b = derive_child(&group, &cc, 1).unwrap().child_pubkey;
393        let c = derive_child(&group, &cc, 2).unwrap().child_pubkey;
394        assert_ne!(a, b);
395        assert_ne!(b, c);
396        assert_ne!(a, c);
397    }
398
399    /// The external chain (`/0/N`) and internal chain (`/1/N`) at the same
400    /// leaf index produce distinct child pubkeys, so `wallet descriptor`
401    /// stops reusing addresses between receive and change once this
402    /// derivation is wired in.
403    #[test]
404    fn external_and_internal_chains_diverge_at_matching_leaf() {
405        let group = stable_group_pubkey();
406        let cc = deterministic_chaincode(&group);
407        for leaf in 0u32..8 {
408            let external = derive_path(&group, &cc, &[0, leaf]).unwrap().child_pubkey;
409            let internal = derive_path(&group, &cc, &[1, leaf]).unwrap().child_pubkey;
410            assert_ne!(
411                external, internal,
412                "external and internal chain must diverge at leaf {leaf}"
413            );
414        }
415    }
416
417    /// Build the reference `bitcoin::bip32::Xpub` carrying our (group_pubkey,
418    /// chaincode), rooted at the +even lift of the x-only group key, so we can
419    /// hand it to bitcoin::bip32's normal `ckd_pub` path.
420    fn ref_xpub_for(group: &[u8; 32], cc: &[u8; 32]) -> Xpub {
421        let mut compressed = [0u8; 33];
422        compressed[0] = 0x02;
423        compressed[1..].copy_from_slice(group);
424        let parent_point = bitcoin::secp256k1::PublicKey::from_slice(&compressed).unwrap();
425        Xpub {
426            network: NetworkKind::Main,
427            depth: 0,
428            parent_fingerprint: Default::default(),
429            child_number: ChildNumber::from_normal_idx(0).unwrap(),
430            public_key: parent_point,
431            chain_code: ChainCode::from(*cc),
432        }
433    }
434
435    /// Assert our derivation matches `bitcoin::bip32::Xpub::derive_pub` byte for
436    /// byte across a spread of single- and multi-level unhardened paths.
437    fn assert_matches_bip32_reference(group: [u8; 32]) {
438        let cc = deterministic_chaincode(&group);
439        let xpub = ref_xpub_for(&group, &cc);
440        let secp = Secp256k1::verification_only();
441
442        for &path in &[
443            &[0u32][..],
444            &[1u32][..],
445            &[0, 0][..],
446            &[0, 1][..],
447            &[1, 0][..],
448            &[1, 42][..],
449            &[0, 100_000][..],
450        ] {
451            let ours = derive_path(&group, &cc, path).unwrap();
452
453            let bip32_path: bitcoin::bip32::DerivationPath = path
454                .iter()
455                .map(|i| ChildNumber::from_normal_idx(*i).unwrap())
456                .collect::<Vec<_>>()
457                .into();
458            let ref_xpub = xpub.derive_pub(&secp, &bip32_path).unwrap();
459            let (ref_xonly, _) = ref_xpub.public_key.x_only_public_key();
460
461            assert_eq!(
462                ours.child_pubkey,
463                ref_xonly.serialize(),
464                "path {path:?}: our child pubkey diverges from bitcoin::bip32"
465            );
466            assert_eq!(
467                ours.child_chaincode,
468                ref_xpub.chain_code.to_bytes(),
469                "path {path:?}: our child chaincode diverges from bitcoin::bip32"
470            );
471        }
472    }
473
474    /// Reference vectors: our tweak-based child derivation MUST match
475    /// `bitcoin::bip32::Xpub::derive_pub`, which is a widely deployed BIP-32
476    /// implementation. If this test drifts, we've broken conformance and
477    /// every downstream wallet importing our xpub would derive different
478    /// addresses.
479    #[test]
480    fn matches_bitcoin_bip32_reference() {
481        assert_matches_bip32_reference(stable_group_pubkey());
482    }
483
484    /// Regression for the parity-threading bug: a multi-level walk under an
485    /// intermediate node with *odd* y must still match BIP-32. A fixed even-y
486    /// key never exercises this, so search for a group key whose `/0` node is
487    /// odd-y and assert conformance under it. If `derive_path` ever re-lifts
488    /// intermediates to even, `/0/*` and `/1/*` here diverge from the reference.
489    #[test]
490    fn matches_bip32_reference_under_oddy_intermediate() {
491        let secp = Secp256k1::new();
492        let group = (1u8..=255)
493            .find_map(|seed| {
494                let sk = SecretKey::from_slice(&[seed; 32]).ok()?;
495                let (xonly, _) = sk.x_only_public_key(&secp);
496                let g = xonly.serialize();
497                let cc = deterministic_chaincode(&g);
498                let child0 = ref_xpub_for(&g, &cc)
499                    .derive_pub(&secp, &[ChildNumber::from_normal_idx(0).unwrap()])
500                    .unwrap();
501                // Compressed prefix 0x03 == odd y on the `/0` node.
502                (child0.public_key.serialize()[0] == 0x03).then_some(g)
503            })
504            .expect("some group key in range must have an odd-y /0 node");
505
506        assert_matches_bip32_reference(group);
507    }
508
509    /// The tweak returned by `derive_child` MUST be exactly the scalar
510    /// `parent_point + tweak * G = child_point` uses. Verify by applying it
511    /// with libsecp256k1 directly and matching against the child pubkey.
512    #[test]
513    fn tweak_reproduces_child_when_applied_to_parent() {
514        let group = stable_group_pubkey();
515        let cc = deterministic_chaincode(&group);
516        let step = derive_child(&group, &cc, 7).unwrap();
517
518        let mut compressed = [0u8; 33];
519        compressed[0] = 0x02;
520        compressed[1..].copy_from_slice(&group);
521        let parent_point = bitcoin::secp256k1::PublicKey::from_slice(&compressed).unwrap();
522        let secp = Secp256k1::verification_only();
523        let scalar = Scalar::from_be_bytes(step.tweak).unwrap();
524        let child_point = parent_point.add_exp_tweak(&secp, &scalar).unwrap();
525        let (child_xonly, _) = child_point.x_only_public_key();
526        assert_eq!(child_xonly.serialize(), step.child_pubkey);
527    }
528
529    /// Empty path is a caller error; we surface it clearly rather than
530    /// silently returning the parent state as if a zero-step walk succeeded.
531    #[test]
532    fn empty_path_refused() {
533        let group = stable_group_pubkey();
534        let cc = deterministic_chaincode(&group);
535        assert!(derive_path(&group, &cc, &[]).is_err());
536        assert!(derive_path_composite(&group, &cc, &[]).is_err());
537    }
538
539    /// A path longer than `MAX_DERIVATION_DEPTH` is refused before doing the
540    /// per-index HMAC + EC work, bounding CPU on a wire-supplied path.
541    #[test]
542    fn overlong_path_refused() {
543        let group = stable_group_pubkey();
544        let cc = deterministic_chaincode(&group);
545        let too_long = vec![0u32; MAX_DERIVATION_DEPTH + 1];
546        assert!(derive_path(&group, &cc, &too_long).is_err());
547        assert!(derive_path_composite(&group, &cc, &too_long).is_err());
548    }
549
550    /// #487 PR2 core: the aggregate scalar tweak returned by
551    /// `derive_path_composite` reproduces the same terminal child point as
552    /// the stepwise walk. This is the invariant every co-signer relies on
553    /// when applying ONE composite tweak to its share instead of walking
554    /// the tree per signer.
555    #[test]
556    fn composite_tweak_reproduces_terminal_child_point() {
557        let group = stable_group_pubkey();
558        let cc = deterministic_chaincode(&group);
559        for path in &[
560            &[0u32][..],
561            &[1u32][..],
562            &[0, 0][..],
563            &[0, 1][..],
564            &[1, 0][..],
565            &[1, 42][..],
566            &[0, 100_000][..],
567        ] {
568            let stepwise = derive_path(&group, &cc, path).unwrap();
569            let composite = derive_path_composite(&group, &cc, path).unwrap();
570
571            // Composite and stepwise walks converge on the same terminal
572            // (chaincode, x-only child pubkey), so callers of either
573            // helper see a consistent tree.
574            assert_eq!(
575                composite.child_pubkey, stepwise.child_pubkey,
576                "path {path:?}: composite child pubkey diverges from stepwise walk"
577            );
578            assert_eq!(
579                composite.terminal_chaincode, stepwise.child_chaincode,
580                "path {path:?}: composite chaincode diverges from stepwise walk"
581            );
582
583            // The aggregate tweak, applied once to the +even lift of the
584            // group pubkey, reproduces the terminal child point. This is
585            // the property the FROST signing path (PR 3 of #487) will
586            // depend on for its one-tweak-per-share optimisation.
587            let secp = Secp256k1::verification_only();
588            let parent = even_lift(&group).unwrap();
589            let scalar = Scalar::from_be_bytes(composite.aggregate_tweak).unwrap();
590            let reproduced = parent.add_exp_tweak(&secp, &scalar).unwrap();
591            assert_eq!(
592                reproduced.x_only_public_key().0.serialize(),
593                composite.child_pubkey,
594                "path {path:?}: applying aggregate tweak to +even group does not reproduce child"
595            );
596        }
597    }
598
599    /// The aggregate tweak for a single-step path equals the stepwise
600    /// tweak byte-for-byte: the composite walker MUST NOT drift away
601    /// from the primitive for the trivial case.
602    #[test]
603    fn composite_matches_stepwise_tweak_at_depth_one() {
604        let group = stable_group_pubkey();
605        let cc = deterministic_chaincode(&group);
606        for &index in &[0u32, 1, 2, 7, 42, 100_000] {
607            let step = derive_child(&group, &cc, index).unwrap();
608            let composite = derive_path_composite(&group, &cc, &[index]).unwrap();
609            assert_eq!(step.tweak, composite.aggregate_tweak, "index {index}");
610        }
611    }
612
613    /// Different composite paths must yield different aggregate tweaks:
614    /// the whole point of derivation is address (and signing-key) diversity.
615    #[test]
616    fn composite_tweaks_differ_across_paths() {
617        let group = stable_group_pubkey();
618        let cc = deterministic_chaincode(&group);
619        let a = derive_path_composite(&group, &cc, &[0, 0])
620            .unwrap()
621            .aggregate_tweak;
622        let b = derive_path_composite(&group, &cc, &[0, 1])
623            .unwrap()
624            .aggregate_tweak;
625        let c = derive_path_composite(&group, &cc, &[1, 0])
626            .unwrap()
627            .aggregate_tweak;
628        assert_ne!(a, b);
629        assert_ne!(a, c);
630        assert_ne!(b, c);
631    }
632}