use bitcoin::hashes::{sha256, sha512, Hash as _, HashEngine as _, Hmac, HmacEngine};
use bitcoin::secp256k1::{PublicKey, Scalar, Secp256k1, SecretKey};
use crate::error::{KeepError, Result};
#[inline]
fn derivation_path_error(msg: impl Into<String>) -> KeepError {
KeepError::Frost(msg.into())
}
const CHAINCODE_DOMAIN: &[u8] = b"keep-frost-bip32-chaincode-v1";
pub const HARDENED_INDEX_START: u32 = 0x8000_0000;
pub const MAX_DERIVATION_DEPTH: usize = 255;
pub fn deterministic_chaincode(group_pubkey: &[u8; 32]) -> [u8; 32] {
let mut engine = sha256::Hash::engine();
engine.input(CHAINCODE_DOMAIN);
engine.input(group_pubkey);
sha256::Hash::from_engine(engine).to_byte_array()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChildDerivation {
pub tweak: [u8; 32],
pub child_chaincode: [u8; 32],
pub child_pubkey: [u8; 32],
}
fn even_lift(xonly: &[u8; 32]) -> Result<PublicKey> {
let mut compressed = [0u8; 33];
compressed[0] = 0x02;
compressed[1..].copy_from_slice(xonly);
PublicKey::from_slice(&compressed)
.map_err(|e| derivation_path_error(format!("x-only pubkey not on curve: {e}")))
}
fn ckd_pub_point(
parent_point: &PublicKey,
chaincode: &[u8; 32],
index: u32,
) -> Result<([u8; 32], [u8; 32], PublicKey)> {
if index >= HARDENED_INDEX_START {
return Err(derivation_path_error(format!(
"hardened index {index} not supported for FROST groups; \
only unhardened public derivation is meaningful without a group secret"
)));
}
let compressed = parent_point.serialize();
let mut engine = HmacEngine::<sha512::Hash>::new(chaincode);
engine.input(&compressed);
engine.input(&index.to_be_bytes());
let i = Hmac::<sha512::Hash>::from_engine(engine).to_byte_array();
let mut tweak = [0u8; 32];
tweak.copy_from_slice(&i[..32]);
let mut child_chaincode = [0u8; 32];
child_chaincode.copy_from_slice(&i[32..]);
let scalar = Scalar::from_be_bytes(tweak).map_err(|_| {
derivation_path_error(format!(
"BIP-32 child tweak >= curve order at index {index}; caller must skip to next index"
))
})?;
let secp = Secp256k1::verification_only();
let child_point = parent_point.add_exp_tweak(&secp, &scalar).map_err(|e| {
derivation_path_error(format!("BIP-32 child tweak produced invalid point: {e}"))
})?;
Ok((tweak, child_chaincode, child_point))
}
pub fn derive_child(
parent_pubkey: &[u8; 32],
chaincode: &[u8; 32],
index: u32,
) -> Result<ChildDerivation> {
let parent_point = even_lift(parent_pubkey)?;
let (tweak, child_chaincode, child_point) = ckd_pub_point(&parent_point, chaincode, index)?;
Ok(ChildDerivation {
tweak,
child_chaincode,
child_pubkey: child_point.x_only_public_key().0.serialize(),
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CompositeDerivation {
pub aggregate_tweak: [u8; 32],
pub terminal_chaincode: [u8; 32],
pub child_pubkey: [u8; 32],
}
pub fn derive_path_composite(
group_pubkey: &[u8; 32],
chaincode: &[u8; 32],
path: &[u32],
) -> Result<CompositeDerivation> {
if path.is_empty() {
return Err(derivation_path_error(
"derive_path_composite requires at least one index",
));
}
if path.len() > MAX_DERIVATION_DEPTH {
return Err(derivation_path_error(format!(
"derivation path length {} exceeds maximum {MAX_DERIVATION_DEPTH}",
path.len()
)));
}
let mut parent_point = even_lift(group_pubkey)?;
let mut parent_chaincode = *chaincode;
let first_index = path[0];
let (first_tweak, first_cc, first_point) =
ckd_pub_point(&parent_point, &parent_chaincode, first_index)?;
let mut acc = SecretKey::from_slice(&first_tweak).map_err(|e| {
derivation_path_error(format!("BIP-32 first tweak is not a valid scalar: {e}"))
})?;
parent_point = first_point;
parent_chaincode = first_cc;
for &index in &path[1..] {
let (step_tweak, step_cc, step_point) =
ckd_pub_point(&parent_point, &parent_chaincode, index)?;
let step_scalar = Scalar::from_be_bytes(step_tweak).map_err(|_| {
derivation_path_error(format!("BIP-32 step tweak >= curve order at index {index}"))
})?;
acc = acc.add_tweak(&step_scalar).map_err(|e| {
derivation_path_error(format!(
"BIP-32 aggregate tweak became invalid at index {index}: {e}"
))
})?;
parent_point = step_point;
parent_chaincode = step_cc;
}
let aggregate_tweak = acc.secret_bytes();
let secp = Secp256k1::verification_only();
let reproduced = even_lift(group_pubkey)?
.add_exp_tweak(
&secp,
&Scalar::from_be_bytes(aggregate_tweak).map_err(|_| {
derivation_path_error("aggregate tweak >= curve order after accumulation")
})?,
)
.map_err(|e| {
derivation_path_error(format!("aggregate tweak produced invalid point: {e}"))
})?;
if reproduced != parent_point {
return Err(derivation_path_error(
"composed BIP-32 tweak does not reproduce terminal child point; \
signing under the aggregate would diverge from stepwise derivation",
));
}
Ok(CompositeDerivation {
aggregate_tweak,
terminal_chaincode: parent_chaincode,
child_pubkey: parent_point.x_only_public_key().0.serialize(),
})
}
pub fn derive_path(
group_pubkey: &[u8; 32],
chaincode: &[u8; 32],
path: &[u32],
) -> Result<ChildDerivation> {
if path.is_empty() {
return Err(derivation_path_error(
"derive_path requires at least one index",
));
}
if path.len() > MAX_DERIVATION_DEPTH {
return Err(derivation_path_error(format!(
"derivation path length {} exceeds maximum {MAX_DERIVATION_DEPTH}",
path.len()
)));
}
let mut parent_point = even_lift(group_pubkey)?;
let mut parent_chaincode = *chaincode;
let mut last: Option<ChildDerivation> = None;
for &index in path {
let (tweak, child_chaincode, child_point) =
ckd_pub_point(&parent_point, &parent_chaincode, index)?;
parent_point = child_point;
parent_chaincode = child_chaincode;
last = Some(ChildDerivation {
tweak,
child_chaincode,
child_pubkey: child_point.x_only_public_key().0.serialize(),
});
}
Ok(last.expect("non-empty path always sets last"))
}
#[cfg(test)]
mod tests {
use super::*;
use bitcoin::bip32::{ChainCode, ChildNumber, Xpub};
use bitcoin::secp256k1::SecretKey;
use bitcoin::NetworkKind;
fn stable_group_pubkey() -> [u8; 32] {
let secp = Secp256k1::signing_only();
let sk = SecretKey::from_slice(&[0x42; 32]).unwrap();
let (xonly, _) = sk.x_only_public_key(&secp);
xonly.serialize()
}
#[test]
fn chaincode_is_deterministic() {
let group = stable_group_pubkey();
let cc1 = deterministic_chaincode(&group);
let cc2 = deterministic_chaincode(&group);
assert_eq!(cc1, cc2);
}
#[test]
fn chaincode_differs_per_group_pubkey() {
let a = stable_group_pubkey();
let mut b = a;
b[0] ^= 0x01;
assert_ne!(deterministic_chaincode(&a), deterministic_chaincode(&b));
}
#[test]
fn hardened_index_refused() {
let group = stable_group_pubkey();
let cc = deterministic_chaincode(&group);
let err = derive_child(&group, &cc, HARDENED_INDEX_START)
.expect_err("hardened index must be refused");
assert!(matches!(err, KeepError::Frost(_)));
derive_child(&group, &cc, HARDENED_INDEX_START - 1).unwrap();
}
#[test]
fn distinct_indexes_yield_distinct_child_pubkeys() {
let group = stable_group_pubkey();
let cc = deterministic_chaincode(&group);
let a = derive_child(&group, &cc, 0).unwrap().child_pubkey;
let b = derive_child(&group, &cc, 1).unwrap().child_pubkey;
let c = derive_child(&group, &cc, 2).unwrap().child_pubkey;
assert_ne!(a, b);
assert_ne!(b, c);
assert_ne!(a, c);
}
#[test]
fn external_and_internal_chains_diverge_at_matching_leaf() {
let group = stable_group_pubkey();
let cc = deterministic_chaincode(&group);
for leaf in 0u32..8 {
let external = derive_path(&group, &cc, &[0, leaf]).unwrap().child_pubkey;
let internal = derive_path(&group, &cc, &[1, leaf]).unwrap().child_pubkey;
assert_ne!(
external, internal,
"external and internal chain must diverge at leaf {leaf}"
);
}
}
fn ref_xpub_for(group: &[u8; 32], cc: &[u8; 32]) -> Xpub {
let mut compressed = [0u8; 33];
compressed[0] = 0x02;
compressed[1..].copy_from_slice(group);
let parent_point = bitcoin::secp256k1::PublicKey::from_slice(&compressed).unwrap();
Xpub {
network: NetworkKind::Main,
depth: 0,
parent_fingerprint: Default::default(),
child_number: ChildNumber::from_normal_idx(0).unwrap(),
public_key: parent_point,
chain_code: ChainCode::from(*cc),
}
}
fn assert_matches_bip32_reference(group: [u8; 32]) {
let cc = deterministic_chaincode(&group);
let xpub = ref_xpub_for(&group, &cc);
let secp = Secp256k1::verification_only();
for &path in &[
&[0u32][..],
&[1u32][..],
&[0, 0][..],
&[0, 1][..],
&[1, 0][..],
&[1, 42][..],
&[0, 100_000][..],
] {
let ours = derive_path(&group, &cc, path).unwrap();
let bip32_path: bitcoin::bip32::DerivationPath = path
.iter()
.map(|i| ChildNumber::from_normal_idx(*i).unwrap())
.collect::<Vec<_>>()
.into();
let ref_xpub = xpub.derive_pub(&secp, &bip32_path).unwrap();
let (ref_xonly, _) = ref_xpub.public_key.x_only_public_key();
assert_eq!(
ours.child_pubkey,
ref_xonly.serialize(),
"path {path:?}: our child pubkey diverges from bitcoin::bip32"
);
assert_eq!(
ours.child_chaincode,
ref_xpub.chain_code.to_bytes(),
"path {path:?}: our child chaincode diverges from bitcoin::bip32"
);
}
}
#[test]
fn matches_bitcoin_bip32_reference() {
assert_matches_bip32_reference(stable_group_pubkey());
}
#[test]
fn matches_bip32_reference_under_oddy_intermediate() {
let secp = Secp256k1::new();
let group = (1u8..=255)
.find_map(|seed| {
let sk = SecretKey::from_slice(&[seed; 32]).ok()?;
let (xonly, _) = sk.x_only_public_key(&secp);
let g = xonly.serialize();
let cc = deterministic_chaincode(&g);
let child0 = ref_xpub_for(&g, &cc)
.derive_pub(&secp, &[ChildNumber::from_normal_idx(0).unwrap()])
.unwrap();
(child0.public_key.serialize()[0] == 0x03).then_some(g)
})
.expect("some group key in range must have an odd-y /0 node");
assert_matches_bip32_reference(group);
}
#[test]
fn tweak_reproduces_child_when_applied_to_parent() {
let group = stable_group_pubkey();
let cc = deterministic_chaincode(&group);
let step = derive_child(&group, &cc, 7).unwrap();
let mut compressed = [0u8; 33];
compressed[0] = 0x02;
compressed[1..].copy_from_slice(&group);
let parent_point = bitcoin::secp256k1::PublicKey::from_slice(&compressed).unwrap();
let secp = Secp256k1::verification_only();
let scalar = Scalar::from_be_bytes(step.tweak).unwrap();
let child_point = parent_point.add_exp_tweak(&secp, &scalar).unwrap();
let (child_xonly, _) = child_point.x_only_public_key();
assert_eq!(child_xonly.serialize(), step.child_pubkey);
}
#[test]
fn empty_path_refused() {
let group = stable_group_pubkey();
let cc = deterministic_chaincode(&group);
assert!(derive_path(&group, &cc, &[]).is_err());
assert!(derive_path_composite(&group, &cc, &[]).is_err());
}
#[test]
fn overlong_path_refused() {
let group = stable_group_pubkey();
let cc = deterministic_chaincode(&group);
let too_long = vec![0u32; MAX_DERIVATION_DEPTH + 1];
assert!(derive_path(&group, &cc, &too_long).is_err());
assert!(derive_path_composite(&group, &cc, &too_long).is_err());
}
#[test]
fn composite_tweak_reproduces_terminal_child_point() {
let group = stable_group_pubkey();
let cc = deterministic_chaincode(&group);
for path in &[
&[0u32][..],
&[1u32][..],
&[0, 0][..],
&[0, 1][..],
&[1, 0][..],
&[1, 42][..],
&[0, 100_000][..],
] {
let stepwise = derive_path(&group, &cc, path).unwrap();
let composite = derive_path_composite(&group, &cc, path).unwrap();
assert_eq!(
composite.child_pubkey, stepwise.child_pubkey,
"path {path:?}: composite child pubkey diverges from stepwise walk"
);
assert_eq!(
composite.terminal_chaincode, stepwise.child_chaincode,
"path {path:?}: composite chaincode diverges from stepwise walk"
);
let secp = Secp256k1::verification_only();
let parent = even_lift(&group).unwrap();
let scalar = Scalar::from_be_bytes(composite.aggregate_tweak).unwrap();
let reproduced = parent.add_exp_tweak(&secp, &scalar).unwrap();
assert_eq!(
reproduced.x_only_public_key().0.serialize(),
composite.child_pubkey,
"path {path:?}: applying aggregate tweak to +even group does not reproduce child"
);
}
}
#[test]
fn composite_matches_stepwise_tweak_at_depth_one() {
let group = stable_group_pubkey();
let cc = deterministic_chaincode(&group);
for &index in &[0u32, 1, 2, 7, 42, 100_000] {
let step = derive_child(&group, &cc, index).unwrap();
let composite = derive_path_composite(&group, &cc, &[index]).unwrap();
assert_eq!(step.tweak, composite.aggregate_tweak, "index {index}");
}
}
#[test]
fn composite_tweaks_differ_across_paths() {
let group = stable_group_pubkey();
let cc = deterministic_chaincode(&group);
let a = derive_path_composite(&group, &cc, &[0, 0])
.unwrap()
.aggregate_tweak;
let b = derive_path_composite(&group, &cc, &[0, 1])
.unwrap()
.aggregate_tweak;
let c = derive_path_composite(&group, &cc, &[1, 0])
.unwrap()
.aggregate_tweak;
assert_ne!(a, b);
assert_ne!(a, c);
assert_ne!(b, c);
}
}