Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jobs:
strategy:
matrix:
toolchain:
- 1.82
- 1.85
- nightly
os:
- ubuntu-latest
Expand All @@ -49,7 +49,7 @@ jobs:
strategy:
matrix:
toolchain:
- 1.82
- 1.85
os:
- ubuntu-latest
runs-on: ${{ matrix.os }}
Expand All @@ -69,7 +69,7 @@ jobs:
strategy:
matrix:
toolchain:
- 1.82
- 1.85
os:
- ubuntu-latest
runs-on: ${{ matrix.os }}
Expand Down
11 changes: 8 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ chacha20poly1305 = {version = "0.10.1", default-features = false, features = ["a
rand = {version = "0.9.2", optional = true}
base64 = {version = "0.22", default-features = false, features = ["alloc"], optional = true}

# Old format (BEB magic, AES-256-GCM): used solely on the decrypt path
# as a transparent fallback for backups produced by 0.0.2.
bitcoin-encrypted-backup-v0 = { version = "0.0.2", package = "bitcoin-encrypted-backup", default-features = false, optional = true }

#miniscript
mscript_12_3_5 = { version = "12.3.5", default-features = false, features = ["serde", "no-std"], package = "miniscript" , optional = true}
mscript_12_0 = { version = "12.0", default-features = false, features = ["serde", "no-std"], package = "miniscript" , optional = true}
Expand All @@ -36,12 +40,13 @@ path = "src/bin/main.rs"
required-features = ["cli"]

[features]
default = ["miniscript_latest", "rand", "base64"]
default = ["miniscript_latest", "rand", "base64", "v0"]
rand = ["dep:rand"]
base64 = ["dep:base64"]
v0 = ["dep:bitcoin-encrypted-backup-v0"]
miniscript_latest = ["miniscript_12_3_5"]
miniscript_12_3_5 = ["mscript_12_3_5"]
miniscript_12_0 = ["mscript_12_0"]
miniscript_12_3_5 = ["mscript_12_3_5", "bitcoin-encrypted-backup-v0?/miniscript_12_3_5"]
miniscript_12_0 = ["mscript_12_0", "bitcoin-encrypted-backup-v0?/miniscript_12_0"]
tokio = ["dep:tokio"]
devices = ["dep:async-hwi", "tokio"]
cli = ["dep:clap", "tokio", "miniscript_latest", "rand"]
19 changes: 17 additions & 2 deletions src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,15 +134,30 @@ async fn main() -> Result<(), CliError> {
.map_err(CliError::CantConvertToDescriptor)?;

// encrypt the descriptor
let bytes = EncryptedBackup::new()
let encrypted = EncryptedBackup::new()
.set_payload(&descriptor)
.map_err(CliError::FailedToEncrypt)?
.encrypt()
.map_err(CliError::FailedToEncrypt)?;

for w in &encrypted.warnings {
match w {
bitcoin_encrypted_backup::Warning::DisallowedKeyExpression(k) => {
eprintln!(
"warning: disallowed key expression excluded from encryption-key set: {k}; the cosigner holding this key cannot decrypt the backup with their key"
);
}
bitcoin_encrypted_backup::Warning::NumsKey(k) => {
eprintln!("warning: BIP341 NUMS key excluded from encryption-key set: {k}");
}
}
}

// pass the byte vector to a file
let mut output = File::create(&output_path).map_err(CliError::CreateError)?;
output.write(&bytes).map_err(CliError::WriteError)?;
output
.write(&encrypted.bytes)
.map_err(CliError::WriteError)?;
println!("descriptor written to {output_path:?}");
}
Commands::Decrypt { file, key, output } => {
Expand Down
190 changes: 144 additions & 46 deletions src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,53 @@ use alloc::{collections::BTreeSet, str::FromStr, vec::Vec};

use miniscript::{
bitcoin::{self, bip32::DerivationPath, secp256k1},
descriptor::{DerivPaths, SinglePubKey, Wildcard},
Descriptor, DescriptorPublicKey, ForEachKey,
};

use crate::Error;

pub fn dpk_to_pk(key: &DescriptorPublicKey) -> bitcoin::secp256k1::PublicKey {
/// Internal-only x-only normalization used by NUMS detection. Bypasses the
/// allow/disallow check intentionally so a NUMS literal in tr() is reported
/// as Warning::NumsKey rather than DisallowedKeyExpression.
fn xonly_of(key: &DescriptorPublicKey) -> [u8; 32] {
match key {
DescriptorPublicKey::Single(key) => match key.key {
miniscript::descriptor::SinglePubKey::FullKey(pk) => pk.inner,
miniscript::descriptor::SinglePubKey::XOnly(pk) => {
pk.public_key(bitcoin::key::Parity::Even)
}
DescriptorPublicKey::Single(k) => match k.key {
SinglePubKey::FullKey(pk) => pk.inner.x_only_public_key().0.serialize(),
SinglePubKey::XOnly(xo) => xo.serialize(),
},
DescriptorPublicKey::XPub(key) => key.xkey.public_key,
DescriptorPublicKey::MultiXPub(key) => key.xkey.public_key,
DescriptorPublicKey::XPub(k) => k.xkey.public_key.x_only_public_key().0.serialize(),
DescriptorPublicKey::MultiXPub(k) => k.xkey.public_key.x_only_public_key().0.serialize(),
}
}

use crate::{Error, Warning};

pub fn dpk_to_pk(key: &DescriptorPublicKey) -> Result<bitcoin::secp256k1::PublicKey, Error> {
let (key, path, wildcard) = match key {
DescriptorPublicKey::Single(_) => return Err(Error::InvalidKeyExpression),
DescriptorPublicKey::XPub(key) => (
key.xkey.public_key,
DerivPaths::new(vec![key.derivation_path.clone()]).expect("path not empty"),
key.wildcard,
),
DescriptorPublicKey::MultiXPub(key) => (
key.xkey.public_key,
key.derivation_paths.clone(),
key.wildcard,
),
};
let path = path.into_paths();
let mut deriv = true;
if path.is_empty() {
deriv = false;
}
for p in path {
if p.is_empty() {
deriv = false;
}
}
(deriv || wildcard != Wildcard::None)
.then_some(key)
.ok_or(Error::InvalidKeyExpression)
}

fn dpk_to_deriv_path(key: &DescriptorPublicKey) -> Option<DerivationPath> {
Expand Down Expand Up @@ -54,9 +85,11 @@ pub fn descr_to_dpks(
let nums_xonly = bip341_nums().x_only_public_key().0;
let mut keys = BTreeSet::new();
descriptor.for_each_key(|k| {
let pk = dpk_to_pk(k);
if pk.x_only_public_key().0 != nums_xonly {
keys.insert(k.clone());
// invalid key expressions are sorted out
if let Ok(pk) = dpk_to_pk(k) {
if pk.x_only_public_key().0 != nums_xonly {
keys.insert(k.clone());
}
}
true
});
Expand All @@ -69,15 +102,37 @@ pub fn descr_to_dpks(
}
}

/// Walk the descriptor and emit a warning for every key expression that
/// `descr_to_dpks` sorts out of the encryption-key set: disallowed
/// expressions (literal pubkey, bare xpub) and the BIP341 NUMS key.
/// NUMS detection wins over the disallow rule so a NUMS literal in tr()
/// is reported with the more specific reason.
pub fn descr_warnings(descriptor: &Descriptor<DescriptorPublicKey>) -> Result<Vec<Warning>, Error> {
let nums_xonly = bip341_nums().x_only_public_key().0.serialize();
let mut warnings = Vec::new();
descriptor.for_each_key(|k| {
if xonly_of(k) == nums_xonly {
warnings.push(Warning::NumsKey(k.clone()));
} else if dpk_to_pk(k).is_err() {
warnings.push(Warning::DisallowedKeyExpression(k.clone()));
}
true
});
Ok(warnings)
}

pub fn dpks_to_derivation_keys_paths(
dpks: &Vec<DescriptorPublicKey>,
) -> (Vec<secp256k1::PublicKey>, Vec<DerivationPath>) {
let mut derivation_paths = BTreeSet::new();
let mut keys = BTreeSet::new();
for k in dpks {
keys.insert(dpk_to_pk(k));
if let Some(path) = dpk_to_deriv_path(k) {
derivation_paths.insert(path);
// invalid key expressions are sorted out
if let Ok(key) = dpk_to_pk(k) {
keys.insert(key);
if let Some(path) = dpk_to_deriv_path(k) {
derivation_paths.insert(path);
}
}
}
let deriv = derivation_paths.into_iter().collect();
Expand Down Expand Up @@ -129,31 +184,30 @@ pub mod tests {

#[test]
fn test_dpk_to_pk() {
// Valid key expressions (xpub with /<0;1>/*) extract the xpub root
// pubkey and are accepted by dpk_to_pk.
let expected = pk();
let pk = dpk_to_pk(&dpk_1());
assert_eq!(pk, expected);
let pk = dpk_to_pk(&dpk_2());
assert_eq!(pk, expected);
let p = dpk_to_pk(&dpk_1()).unwrap();
assert_eq!(p, expected);
let p = dpk_to_pk(&dpk_2()).unwrap();
assert_eq!(p, expected);

// Single
// Single FullKey; disallowed by the spec's key-expression rule.
let single_str = "0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0";
let dpk = DescriptorPublicKey::from_str(single_str).unwrap();
let pk = dpk_to_pk(&dpk);
let expected = bitcoin::secp256k1::PublicKey::from_str(single_str).unwrap();
assert_eq!(expected, pk);
assert_eq!(dpk_to_pk(&dpk), Err(Error::InvalidKeyExpression));

// Single Xonly
// Single XOnly; disallowed.
let xonly = bitcoin::PublicKey::from_str(single_str)
.unwrap()
.to_x_only_pubkey();
let dpk = DescriptorPublicKey::Single(SinglePub {
origin: None,
key: descriptor::SinglePubKey::XOnly(xonly),
});
let pk = dpk_to_pk(&dpk);
assert_eq!(expected, pk);
assert_eq!(dpk_to_pk(&dpk), Err(Error::InvalidKeyExpression));

// Xpub
// Xpub with no derivation and no wildcard; disallowed.
let xpub = bip32::Xpub {
network: bitcoin::NetworkKind::Test,
depth: 1,
Expand All @@ -162,25 +216,42 @@ pub mod tests {
public_key: bitcoin::secp256k1::PublicKey::from_str(single_str).unwrap(),
chain_code: ChainCode::from(&[1u8; 32]),
};
let dpk = DescriptorPublicKey::XPub(DescriptorXKey {
let bare_xpub = DescriptorPublicKey::XPub(DescriptorXKey {
origin: None,
xkey: xpub,
derivation_path: DerivationPath::default(),
wildcard: Wildcard::None,
});
let pk = dpk_to_pk(&dpk);
assert_eq!(expected, pk);
assert_eq!(dpk_to_pk(&bare_xpub), Err(Error::InvalidKeyExpression));

// MultiXpub
let dpk = DescriptorPublicKey::MultiXPub(DescriptorMultiXKey {
// Xpub with non-empty derivation, no wildcard; allowed.
let xpub_fixed = DescriptorPublicKey::XPub(DescriptorXKey {
origin: None,
xkey: xpub,
derivation_path: DerivationPath::from_str("0/5").unwrap(),
wildcard: Wildcard::None,
});
let expected_xpub_pk = bitcoin::secp256k1::PublicKey::from_str(single_str).unwrap();
assert_eq!(dpk_to_pk(&xpub_fixed).unwrap(), expected_xpub_pk);

// Xpub with empty derivation and wildcard; allowed.
let xpub_wild = DescriptorPublicKey::XPub(DescriptorXKey {
origin: None,
xkey: xpub,
derivation_path: DerivationPath::default(),
wildcard: Wildcard::Unhardened,
});
assert_eq!(dpk_to_pk(&xpub_wild).unwrap(), expected_xpub_pk);

// MultiXpub with non-empty path, no wildcard; allowed (deriv only).
let multi_fixed = DescriptorPublicKey::MultiXPub(DescriptorMultiXKey {
origin: None,
xkey: xpub,
derivation_paths: DerivPaths::new(vec![DerivationPath::from_str("0").unwrap()])
.unwrap(),
wildcard: Wildcard::None,
});
let pk = dpk_to_pk(&dpk);
assert_eq!(expected, pk);
assert_eq!(dpk_to_pk(&multi_fixed).unwrap(), expected_xpub_pk);
}

#[test]
Expand All @@ -200,7 +271,7 @@ pub mod tests {
let dpk = DescriptorPublicKey::from_str(single_str).unwrap();
let none = dpk_to_deriv_path(&dpk);
assert!(none.is_none());
let single_pk = SinglePubKey::FullKey(dpk_to_pk(&dpk).into());
let single_pk = SinglePubKey::FullKey(bitcoin::PublicKey::from_str(single_str).unwrap());
let dpk = DescriptorPublicKey::Single(SinglePub {
origin: origin.clone(),
key: single_pk,
Expand Down Expand Up @@ -270,13 +341,19 @@ pub mod tests {
let keys = descr_to_dpks(&descriptor).unwrap();
let nums_xonly = bip341_nums().x_only_public_key().0;
for key in keys {
let pk = dpk_to_pk(&key);
let pk = dpk_to_pk(&key).unwrap();
assert_ne!(pk.x_only_public_key().0, nums_xonly);
}
// but the descriptor contains unspendable
// but the descriptor contains unspendable. The descriptor here uses
// only xpub key expressions, so reading `xkey.public_key` directly
// is sufficient and avoids exposing an unvalidated extractor.
let contains_unspendable = descriptor.for_any_key(|k| {
let pk = dpk_to_pk(k);
pk.x_only_public_key().0 == nums_xonly
let xpub_key = match k {
DescriptorPublicKey::XPub(x) => x.xkey.public_key,
DescriptorPublicKey::MultiXPub(x) => x.xkey.public_key,
DescriptorPublicKey::Single(_) => return false,
};
xpub_key.x_only_public_key().0 == nums_xonly
});
assert!(contains_unspendable);
}
Expand All @@ -303,7 +380,9 @@ mod keys_types {
struct TestVector {
description: String,
key: String,
expected: String,
// Some(hex) → expression is allowed; expected x-only normalization.
// None → expression is disallowed; dpk_to_pk must return Err.
expected: Option<String>,
}

#[test]
Expand All @@ -312,9 +391,27 @@ mod keys_types {

for v in vectors {
let dpk = DescriptorPublicKey::from_str(&v.key).expect(&v.description);
let pk = dpk_to_pk(&dpk);
let res = hex::encode(pk.x_only_public_key().0.serialize());
assert_eq!(v.expected, res, "{}", v.description);
match (&v.expected, dpk_to_pk(&dpk)) {
(Some(hex_expected), Ok(pk)) => {
let res = hex::encode(pk.x_only_public_key().0.serialize());
assert_eq!(*hex_expected, res, "{}", v.description);
}
(None, Err(_)) => {
// Disallowed expression correctly rejected by dpk_to_pk.
}
(Some(_), Err(e)) => {
panic!(
"{}: expected allowed but dpk_to_pk failed with {e:?}",
v.description
);
}
(None, Ok(_)) => {
panic!(
"{}: expected disallowed but dpk_to_pk succeeded",
v.description
);
}
}
}
}

Expand All @@ -324,8 +421,9 @@ mod keys_types {
let mut vectors: Vec<TestVector> = serde_json::from_str(TEST_VECTORS_JSON).unwrap();
for v in vectors.iter_mut() {
let dpk = DescriptorPublicKey::from_str(&v.key).expect(&v.description);
let pk = dpk_to_pk(&dpk);
v.expected = hex::encode(pk.x_only_public_key().0.serialize());
v.expected = dpk_to_pk(&dpk)
.ok()
.map(|pk| hex::encode(pk.x_only_public_key().0.serialize()));
}
let out = serde_json::to_string_pretty(&vectors).unwrap();
std::fs::write("test_vectors/keys_types.json", out).unwrap();
Expand Down
Loading
Loading