diff --git a/Cargo.toml b/Cargo.toml index 93519d9a..55eaa3f9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "spdk-wallet", "silentpayments", "scanners/local", + "bip392", ] resolver = "3" @@ -15,6 +16,7 @@ spdk-wallet = { path = "spdk-wallet" } silentpayments = { path = "silentpayments" } backend-blindbit-v1 = { path = "backends/blindbit-v1" } local-scanner = { path = "scanners/local" } +bip392 = { path = "bip392" } # Core dependencies - shared across crates anyhow = "1.0" @@ -23,7 +25,8 @@ serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.107" bip321 = { git = "https://gitlab.com/Sosthene00/bark.git", rev = "83ab79264159869503b16fa475e0ed61ffa33174", default-features = false } bitcoin = { version = "0.32.8", features = ["serde", "rand", "base64"] } -bitcoin_hashes = "0.13.0" +miniscript = "13.0.0" +bitcoin_hashes = "0.14.101" rayon = "1.10.0" tokio = { version = "1", features = ["macros", "rt-multi-thread"] } futures = "0.3" diff --git a/bip392/Cargo.toml b/bip392/Cargo.toml new file mode 100644 index 00000000..2cf8a182 --- /dev/null +++ b/bip392/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "bip392" +version = "0.1.0" +edition = "2024" +repository.workspace = true + +[lib] +crate-type = ["lib"] + +[dependencies] +secp256k1.workspace = true +silentpayments.workspace = true + +miniscript.workspace = true diff --git a/bip392/src/error.rs b/bip392/src/error.rs new file mode 100644 index 00000000..04e3556f --- /dev/null +++ b/bip392/src/error.rs @@ -0,0 +1,91 @@ +//! Errors for parsing and materializing `sp()` descriptors. + +use core::fmt; + +use miniscript::bitcoin::bip32; + +use crate::keys::SpKeyError; + +/// A descriptor key expression cannot be used as silent-payment key material. +/// +/// These are the failures of turning a [`DescriptorSecretKey`] into a scalar, +/// and the same failures on a public spend key. +/// +/// [`DescriptorSecretKey`]: miniscript::DescriptorSecretKey +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum KeyError { + /// The key is a BIP-389 multipath expression. + Multipath, + /// The derivation path contains a wildcard (`/*` or `/*h`). + Wildcard, + /// A single key is uncompressed. + Uncompressed, + /// BIP-32 child derivation failed. + Derivation(bip32::Error), +} + +impl fmt::Display for KeyError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Multipath => f.write_str("must not be multipath"), + Self::Wildcard => f.write_str("must not contain a wildcard"), + Self::Uncompressed => f.write_str("must be compressed"), + Self::Derivation(err) => fmt::Display::fmt(err, f), + } + } +} + +impl std::error::Error for KeyError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Derivation(err) => Some(err), + Self::Multipath | Self::Wildcard | Self::Uncompressed => None, + } + } +} + +/// An error parsing or constructing an [`Sp`] descriptor. +/// +/// [`Sp`]: crate::Sp +#[derive(Debug)] +pub enum Error { + /// The scan key cannot be materialized. + Scan(KeyError), + /// The spend key cannot be materialized. + Spend(KeyError), + /// The descriptor string is not a valid expression. + Parse(miniscript::Error), + /// An `spscan` or `spspend` encoding is invalid. + SpKey(SpKeyError), + /// A constraint that is not one of the key-material failures above. + Unexpected(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Scan(err) => write!(f, "sp() scan key: {err}"), + Self::Spend(err) => write!(f, "sp() spend key: {err}"), + Self::Parse(err) => fmt::Display::fmt(err, f), + Self::SpKey(err) => fmt::Display::fmt(err, f), + Self::Unexpected(message) => f.write_str(message), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Scan(err) | Self::Spend(err) => Some(err), + Self::Parse(err) => Some(err), + Self::SpKey(err) => Some(err), + Self::Unexpected(_) => None, + } + } +} + +impl From for Error { + fn from(err: miniscript::Error) -> Self { + Self::Parse(err) + } +} diff --git a/bip392/src/keys.rs b/bip392/src/keys.rs new file mode 100644 index 00000000..bc7df958 --- /dev/null +++ b/bip392/src/keys.rs @@ -0,0 +1,361 @@ +//! Silent payment key expressions (BIP-392). +//! +//! Defines `spscan` and `spspend` key types which are Bech32m encodings of +//! silent payment key material as specified in BIP-392: +//! +//! - `spscan`: scan private key (32 bytes) + spend public key (33 bytes) +//! - `spspend`: scan private key (32 bytes) + spend private key (32 bytes) + +use core::fmt; +use core::str::FromStr; + +use miniscript::bitcoin::bech32::{self, Bech32m, Hrp}; +use secp256k1::{PublicKey, SecretKey}; +use silentpayments::{Network as SpNetwork, SpVersion}; + +/// The HRP for spscan keys on mainnet. +const SPSCAN_MAINNET_HRP: &str = "spscan"; +/// The HRP for spscan keys on testnets. +const SPSCAN_TESTNET_HRP: &str = "tspscan"; +/// The HRP for spspend keys on mainnet. +const SPSPEND_MAINNET_HRP: &str = "spspend"; +/// The HRP for spspend keys on testnets. +const SPSPEND_TESTNET_HRP: &str = "tspspend"; + +/// Total payload size for spscan: 32 (scan privkey) + 33 (spend pubkey) = 65 bytes. +const SPSCAN_PAYLOAD_LEN: usize = 65; +/// Total payload size for spspend: 32 (scan privkey) + 32 (spend privkey) = 64 bytes. +const SPSPEND_PAYLOAD_LEN: usize = 64; + +/// An error when parsing an `spscan` or `spspend` key. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SpKeyError { + /// Bech32 decoding error. + Bech32(String), + /// Invalid or unrecognized HRP. + InvalidHrp(String), + /// Invalid silent payment version (expected 0). + InvalidVersion(u8), + /// Invalid payload length. + InvalidPayloadLength { + /// Expected payload length. + expected: usize, + /// Actual payload length. + actual: usize, + }, + // Failed to parse keys + InvalidKeys(String), +} + +impl fmt::Display for SpKeyError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + SpKeyError::Bech32(e) => write!(f, "bech32 error: {}", e), + SpKeyError::InvalidHrp(hrp) => write!(f, "invalid HRP: {}", hrp), + SpKeyError::InvalidVersion(v) => { + write!(f, "invalid silent payment version: {} (expected 0)", v) + } + SpKeyError::InvalidPayloadLength { expected, actual } => { + write!( + f, + "invalid payload length: {} (expected {})", + actual, expected + ) + } + SpKeyError::InvalidKeys(e) => write!(f, "Failed to parse key: {}", e), + } + } +} + +impl std::error::Error for SpKeyError {} + +/// A unified silent payment key type. +/// +/// This is either an `spscan` key (watch-only) or an `spspend` key (full wallet). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SpKey { + /// A scan-only key (watch-only): holds scan private key + spend public key. + Scan(SpScanKey), + /// A full spend key: holds scan private key + spend private key. + Spend(SpSpendKey), +} + +impl SpKey { + /// Returns the scan private key. + pub fn scan_privkey(&self) -> SecretKey { + match self { + SpKey::Scan(k) => k.scan_key, + SpKey::Spend(k) => k.scan_key, + } + } + + /// Returns the network this key is for. + pub fn network(&self) -> SpNetwork { + match self { + SpKey::Scan(k) => k.network, + SpKey::Spend(k) => k.network, + } + } +} + +impl fmt::Display for SpKey { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + SpKey::Scan(k) => fmt::Display::fmt(k, f), + SpKey::Spend(k) => fmt::Display::fmt(k, f), + } + } +} + +impl FromStr for SpKey { + type Err = SpKeyError; + + fn from_str(s: &str) -> Result { + // Decode the bech32m string + let (hrp, data) = bech32::decode(s).map_err(|e| SpKeyError::Bech32(e.to_string()))?; + + let hrp_str = hrp.to_string(); + let hrp_lower = hrp_str.to_ascii_lowercase(); + + if let Some(&version) = data.first() { + if version != SpVersion::ZERO.into() { + return Err(SpKeyError::InvalidVersion(version)); + } + } else { + return Err(SpKeyError::InvalidPayloadLength { + expected: 1, + actual: 0, + }); + } + + let payload = &data[1..]; + + match hrp_lower.as_str() { + SPSCAN_MAINNET_HRP | SPSCAN_TESTNET_HRP => { + let network = if hrp_lower == SPSCAN_MAINNET_HRP { + SpNetwork::Mainnet + } else { + SpNetwork::Testnet + }; + if payload.len() != SPSCAN_PAYLOAD_LEN { + return Err(SpKeyError::InvalidPayloadLength { + expected: SPSCAN_PAYLOAD_LEN, + actual: payload.len(), + }); + } + let scan_key = SecretKey::from_slice(&payload[..32]) + .map_err(|e| SpKeyError::InvalidKeys(e.to_string()))?; + let spend_key = PublicKey::from_slice(&payload[32..]) + .map_err(|e| SpKeyError::InvalidKeys(e.to_string()))?; + Ok(SpKey::Scan(SpScanKey { + scan_key, + spend_key, + network, + })) + } + SPSPEND_MAINNET_HRP | SPSPEND_TESTNET_HRP => { + let network = if hrp_lower == SPSPEND_MAINNET_HRP { + SpNetwork::Mainnet + } else { + SpNetwork::Testnet + }; + if payload.len() != SPSPEND_PAYLOAD_LEN { + return Err(SpKeyError::InvalidPayloadLength { + expected: SPSPEND_PAYLOAD_LEN, + actual: payload.len(), + }); + } + let scan_key = SecretKey::from_slice(&payload[..32]) + .map_err(|e| SpKeyError::InvalidKeys(e.to_string()))?; + let spend_key = SecretKey::from_slice(&payload[32..]) + .map_err(|e| SpKeyError::InvalidKeys(e.to_string()))?; + Ok(SpKey::Spend(SpSpendKey { + scan_key, + spend_key, + network, + })) + } + _ => Err(SpKeyError::InvalidHrp(hrp_lower)), + } + } +} + +/// A watch-only silent payment key (`spscan`). +/// +/// Contains the scan private key and spend public key. +/// This allows scanning for silent payment outputs but not spending them. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SpScanKey { + /// The scan private key (32 bytes, `ser_256(b_scan)`). + pub scan_key: SecretKey, + /// The spend public key (33 bytes, compressed, `ser_P(B_spend)`). + pub spend_key: PublicKey, + /// The network this key is for. + pub network: SpNetwork, +} + +impl SpScanKey { + fn hrp(&self) -> &str { + match self.network { + SpNetwork::Mainnet => SPSCAN_MAINNET_HRP, + SpNetwork::Testnet | SpNetwork::Regtest => SPSCAN_TESTNET_HRP, + } + } + + fn to_payload(&self) -> Vec { + let mut payload = Vec::with_capacity(1 + SPSCAN_PAYLOAD_LEN); + payload.push(SpVersion::ZERO.into()); + payload.extend_from_slice(&self.scan_key.secret_bytes()); + payload.extend_from_slice(&self.spend_key.serialize()); + payload + } +} + +impl fmt::Display for SpScanKey { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let hrp = Hrp::parse(self.hrp()).expect("valid HRP constant"); + let payload = self.to_payload(); + let encoded = + bech32::encode::(hrp, &payload).expect("valid payload for bech32m encoding"); + f.write_str(&encoded) + } +} + +/// A full silent payment key (`spspend`). +/// +/// Contains both the scan private key and spend private key. +/// This allows both scanning for and spending silent payment outputs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SpSpendKey { + /// The scan private key (32 bytes, `ser_256(b_scan)`). + pub scan_key: SecretKey, + /// The spend private key (32 bytes, `ser_256(b_spend)`). + pub spend_key: SecretKey, + /// The network this key is for. + pub network: SpNetwork, +} + +impl SpSpendKey { + fn hrp(&self) -> &str { + match self.network { + SpNetwork::Mainnet => SPSPEND_MAINNET_HRP, + SpNetwork::Testnet | SpNetwork::Regtest => SPSPEND_TESTNET_HRP, + } + } + + fn to_payload(&self) -> Vec { + let mut payload = Vec::with_capacity(1 + SPSPEND_PAYLOAD_LEN); + payload.push(SpVersion::ZERO.into()); + payload.extend_from_slice(&self.scan_key.secret_bytes()); + payload.extend_from_slice(&self.spend_key.secret_bytes()); + payload + } +} + +impl fmt::Display for SpSpendKey { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let hrp = Hrp::parse(self.hrp()).expect("valid HRP constant"); + let payload = self.to_payload(); + let encoded = + bech32::encode::(hrp, &payload).expect("valid payload for bech32m encoding"); + f.write_str(&encoded) + } +} + +#[cfg(test)] +mod tests { + use secp256k1::Secp256k1; + + use super::*; + + fn secret(bytes: [u8; 32]) -> SecretKey { + SecretKey::from_slice(&bytes).expect("valid scalar") + } + + fn compressed(sk: &SecretKey) -> PublicKey { + let secp = Secp256k1::signing_only(); + sk.public_key(&secp) + } + + #[test] + fn spscan_roundtrip() { + let key = SpScanKey { + scan_key: secret([0xab; 32]), + spend_key: compressed(&secret([0xcd; 32])), + network: SpNetwork::Mainnet, + }; + let encoded = key.to_string(); + assert!(encoded.starts_with("spscan1")); + + let decoded = SpKey::from_str(&encoded).unwrap(); + match &decoded { + SpKey::Scan(k) => { + assert_eq!(k.scan_key, key.scan_key); + assert_eq!(k.spend_key, key.spend_key); + assert_eq!(k.network, SpNetwork::Mainnet); + } + _ => panic!("Expected SpKey::Scan"), + } + // Display roundtrip + assert_eq!(decoded.to_string(), encoded); + } + + #[test] + fn spspend_roundtrip() { + let key = SpSpendKey { + scan_key: secret([0xab; 32]), + spend_key: secret([0xcd; 32]), + network: SpNetwork::Mainnet, + }; + let encoded = key.to_string(); + assert!(encoded.starts_with("spspend1")); + + let decoded = SpKey::from_str(&encoded).unwrap(); + match &decoded { + SpKey::Spend(k) => { + assert_eq!(k.scan_key, key.scan_key); + assert_eq!(k.spend_key, key.spend_key); + assert_eq!(k.network, SpNetwork::Mainnet); + } + _ => panic!("Expected SpKey::Spend"), + } + assert_eq!(decoded.to_string(), encoded); + } + + #[test] + fn testnet_spscan_roundtrip() { + let key = SpScanKey { + scan_key: secret([0x01; 32]), + spend_key: compressed(&secret([0x02; 32])), + network: SpNetwork::Testnet, + }; + let encoded = key.to_string(); + assert!(encoded.starts_with("tspscan1")); + + let decoded = SpKey::from_str(&encoded).unwrap(); + assert_eq!(decoded.network(), SpNetwork::Testnet); + } + + #[test] + fn testnet_spspend_roundtrip() { + let key = SpSpendKey { + scan_key: secret([0x01; 32]), + spend_key: secret([0x02; 32]), + network: SpNetwork::Testnet, + }; + let encoded = key.to_string(); + assert!(encoded.starts_with("tspspend1")); + + let decoded = SpKey::from_str(&encoded).unwrap(); + assert_eq!(decoded.network(), SpNetwork::Testnet); + } + + #[test] + fn invalid_hrp() { + let err = SpKey::from_str("badhrp1qqqqqqqqqqqqqqqqqqqq").unwrap_err(); + match err { + SpKeyError::InvalidHrp(_) | SpKeyError::Bech32(_) => {} + e => panic!("Expected InvalidHrp or Bech32 error, got {:?}", e), + } + } +} diff --git a/bip392/src/lib.rs b/bip392/src/lib.rs new file mode 100644 index 00000000..2060ea47 --- /dev/null +++ b/bip392/src/lib.rs @@ -0,0 +1,648 @@ +//! # Silent Payment Output Script Descriptors (BIP-392) +//! +//! This module implements `sp()` output script descriptors for silent payments +//! as defined in BIP-392. Unlike other descriptors, `sp()` is a standalone type +//! that does not participate in the [`super::Descriptor`] enum, because silent +//! payment descriptors cannot produce a `script_pubkey` or `address` without +//! external context (the sender's input public keys, as defined in BIP-352). +//! +//! # Forms +//! +//! The `sp()` descriptor has two forms: +//! +//! - **Single-argument**: `sp(KEY)` where KEY is an `spscan` or `spspend` encoded key +//! - **Two-argument**: `sp(KEY, KEY)` where the first key is a private scan key and the second is a +//! spend key (public or private) +//! +//! # Examples +//! +//! ```text +//! sp(spscan1q...) // Watch-only using spscan encoding +//! sp(spspend1q...) // Full wallet using spspend encoding +//! sp(L4rK...,0260b2...) // WIF scan key with compressed public spend key +//! sp([deadbeef/352h/0h/0h]xprv.../0h,xpub.../0) // Extended keys with origin +//! ``` + +use core::fmt; +use core::str::FromStr; + +use miniscript::bitcoin::bip32::{self, ChildNumber, DerivationPath, Fingerprint}; +use miniscript::descriptor::Wildcard; +pub use miniscript::descriptor::{ + DescriptorPublicKey, DescriptorSecretKey, SinglePubKey, checksum, +}; +pub use miniscript::expression; +use secp256k1::{PublicKey, SecretKey}; +use silentpayments::Network as SpNetwork; + +mod error; +mod keys; + +pub use self::error::{Error, KeyError}; +pub use self::keys::{SpKey, SpKeyError, SpScanKey, SpSpendKey}; + +/// A silent payment descriptor. +/// +/// This is a standalone descriptor type (not part of [`super::Descriptor`]) +/// because silent payment outputs cannot be computed without sender context. +/// +/// It holds the key material needed by a wallet to scan for and/or spend +/// silent payment outputs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sp { + /// The key material for this silent payment descriptor. + inner: SpInner, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct TwoKey { + scan: DescriptorSecretKey, + spend: DescriptorSpendKey, + scan_secret: SecretKey, + spend_secret: Option, + spend_pubkey: PublicKey, +} + +/// The inner representation of an `sp()` descriptor's key material. +#[derive(Debug, Clone, PartialEq, Eq)] +enum SpInner { + /// Single-argument form: an `spscan` or `spspend` encoded key. + /// + /// `origin`, when present, is the master fingerprint and the path to the + /// parent from which BIP-352 derives the scan key (`1h/0`) and the spend + /// key (`0h/0`). + Encoded { + /// Optional key origin (`[fingerprint/path]`). + origin: Option, + /// The encoded silent payment key. + key: SpKey, + }, + /// Two-argument form: a private scan key and a spend key expression. + TwoKey(Box), +} + +/// The spend key in the two-argument form. +/// +/// Can be either a public or private key expression. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DescriptorSpendKey { + /// A public key expression (compressed pubkey, xpub, etc.) + Public(DescriptorPublicKey), + /// A private key expression (WIF, xprv, etc.) + Private(DescriptorSecretKey), +} + +impl Sp { + fn from_encoded(origin: Option, key: SpKey) -> Self { + Sp { + inner: SpInner::Encoded { origin, key }, + } + } + + /// Creates a new `Sp` descriptor from an encoded `spscan` or `spspend` key. + pub fn from_sp_key(key: SpKey) -> Self { + Self::from_encoded(None, key) + } + + /// Creates a new `Sp` descriptor from a private scan key and a spend key. + pub fn from_keys(scan: DescriptorSecretKey, spend: DescriptorSpendKey) -> Result { + Ok(Sp { + inner: SpInner::TwoKey(Box::new(TwoKey::new(scan, spend)?)), + }) + } + + /// Returns `true` if this descriptor contains spend private key material + /// (i.e., the wallet can both scan and spend). + pub fn has_spend_key(&self) -> bool { + match &self.inner { + SpInner::Encoded { key, .. } => matches!(key, SpKey::Spend(_)), + SpInner::TwoKey(keys) => keys.spend_secret().is_some(), + } + } + + /// Returns `true` if this is a watch-only descriptor (can scan but not spend). + pub fn is_watch_only(&self) -> bool { + !self.has_spend_key() + } + + /// Returns `true` if this descriptor is for mainnet. + /// + /// For the encoded form, this uses the `spscan`/`spspend` HRP. + /// For the two-key form, this uses the scan key's network (WIF or xprv). + pub fn is_mainnet(&self) -> bool { + match &self.inner { + SpInner::Encoded { key, .. } => key.network() == SpNetwork::Mainnet, + SpInner::TwoKey(keys) => match keys.scan() { + DescriptorSecretKey::Single(sk) => sk.key.network.is_mainnet(), + DescriptorSecretKey::XPrv(xprv) => xprv.xkey.network.is_mainnet(), + DescriptorSecretKey::MultiXPrv(_) => { + unreachable!("sp() does not support multipath keys") + } + }, + } + } + + /// Returns the scan private key bytes, if available. + /// + /// For the encoded form, this extracts from the spscan/spspend payload. + /// For the two-key form, this extracts from the secret key. + pub fn scan_key(&self) -> SecretKey { + match &self.inner { + SpInner::Encoded { key, .. } => key.scan_privkey(), + SpInner::TwoKey(keys) => keys.scan_secret(), + } + } + + /// Spend private key, when this descriptor can spend. + pub fn spend_secret(&self) -> Option { + match &self.inner { + SpInner::Encoded { key, .. } => match key { + SpKey::Scan(_) => None, + SpKey::Spend(spend_key) => Some(spend_key.spend_key), + }, + SpInner::TwoKey(keys) => keys.spend_secret(), + } + } + + /// Spend public key. Derived from [`Self::spend_secret`] when the descriptor can spend. + pub fn spend_pubkey(&self) -> PublicKey { + match &self.inner { + SpInner::Encoded { key, .. } => match key { + SpKey::Scan(scan_key) => scan_key.spend_key, + SpKey::Spend(spend_key) => spend_key + .spend_key + .public_key(&secp256k1::Secp256k1::signing_only()), + }, + SpInner::TwoKey(keys) => keys.spend_pubkey(), + } + } +} + +impl TwoKey { + /// Rejects keys that cannot be materialized and stores the derived keys. + fn new(scan: DescriptorSecretKey, spend: DescriptorSpendKey) -> Result { + let secp = secp256k1::Secp256k1::new(); + let scan_secret = derive_secret_key(&secp, &scan).map_err(Error::Scan)?; + let spend_secret: Option; + let spend_pubkey: PublicKey; + match spend { + DescriptorSpendKey::Private(ref desc) => { + let secret = derive_secret_key(&secp, desc).map_err(Error::Spend)?; + spend_pubkey = secret.public_key(&secp); + spend_secret = Some(secret); + } + DescriptorSpendKey::Public(ref desc) => { + spend_pubkey = derive_pubkey(&secp, desc)?; + spend_secret = None; + } + }; + // let (spend_secret, spend_pubkey) = materialize_spend(&secp, &spend)?; + Ok(Self { + scan, + spend, + scan_secret, + spend_secret, + spend_pubkey, + }) + } + + fn scan(&self) -> &DescriptorSecretKey { + &self.scan + } + + fn spend(&self) -> &DescriptorSpendKey { + &self.spend + } + + fn scan_secret(&self) -> SecretKey { + self.scan_secret + } + + fn spend_secret(&self) -> Option { + self.spend_secret + } + + fn spend_pubkey(&self) -> PublicKey { + self.spend_pubkey + } +} + +fn derive_secret_key( + secp: &secp256k1::Secp256k1, + descriptor_secret_key: &DescriptorSecretKey, +) -> Result { + let secret = match descriptor_secret_key { + DescriptorSecretKey::MultiXPrv(_) => return Err(KeyError::Multipath), + DescriptorSecretKey::XPrv(xprv) => { + if xprv.wildcard != Wildcard::None { + return Err(KeyError::Wildcard); + } + xprv.xkey + .derive_priv(secp, &xprv.derivation_path) + .map(|derived| derived.private_key) + .map_err(KeyError::Derivation)? + } + DescriptorSecretKey::Single(s) if !s.key.compressed => { + return Err(KeyError::Uncompressed); + } + DescriptorSecretKey::Single(s) => s.key.inner, + }; + Ok(secret) +} + +fn derive_pubkey( + secp: &secp256k1::Secp256k1, + descriptor_pubkey: &DescriptorPublicKey, +) -> Result { + match descriptor_pubkey { + DescriptorPublicKey::MultiXPub(_) => Err(Error::Spend(KeyError::Multipath)), + DescriptorPublicKey::XPub(xpub) => { + if xpub.wildcard != Wildcard::None { + return Err(Error::Spend(KeyError::Wildcard)); + } + if descriptor_pubkey.has_hardened_step() { + return Err(Error::Unexpected( + "sp() public spend key cannot use a hardened derivation step".to_string(), + )); + } + xpub.xkey + .derive_pub(secp, &xpub.derivation_path) + .map(|derived| derived.public_key) + .map_err(|err| Error::Spend(KeyError::Derivation(err))) + } + DescriptorPublicKey::Single(s) => match s.key { + SinglePubKey::FullKey(full) if !full.compressed => { + Err(Error::Spend(KeyError::Uncompressed)) + } + SinglePubKey::FullKey(full) => Ok(full.inner), + SinglePubKey::XOnly(_) => Err(Error::Unexpected( + "sp() spend key must be compressed".to_string(), + )), + }, + } +} + +/// Splits a leading `[fingerprint/path]` off a key expression. +fn split_key_origin(s: &str) -> Result<(&str, Option), Error> { + if !s.starts_with('[') { + return Ok((s, None)); + } + let (origin, key) = s[1..] + .split_once(']') + .ok_or_else(|| Error::Unexpected("sp() key origin is missing closing ']'".to_string()))?; + if key.is_empty() { + return Err(Error::Unexpected( + "sp() key origin is not followed by a key".to_string(), + )); + } + if key.contains(']') { + return Err(Error::Unexpected( + "sp() key expression contains multiple origins".to_string(), + )); + } + + let mut parts = origin.split('/'); + let fingerprint_hex = parts.next().unwrap_or(""); + if fingerprint_hex.len() != 8 { + return Err(Error::Unexpected(format!( + "sp() key origin fingerprint must be 8 hex chars, got '{fingerprint_hex}'" + ))); + } + let fingerprint = Fingerprint::from_hex(fingerprint_hex) + .map_err(|e| Error::Unexpected(format!("sp() key origin fingerprint: {e}")))?; + let children = parts + .map(ChildNumber::from_str) + .collect::, _>>() + .map_err(|e| Error::Unexpected(format!("sp() key origin path: {e}")))?; + Ok((key, Some((fingerprint, DerivationPath::from(children))))) +} + +fn write_key_origin(f: &mut impl fmt::Write, origin: &bip32::KeySource) -> fmt::Result { + f.write_str("[")?; + for byte in origin.0.as_bytes() { + write!(f, "{byte:02x}")?; + } + for child in &origin.1 { + write!(f, "/{child:#}")?; + } + f.write_str("]") +} + +impl fmt::Display for DescriptorSpendKey { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + DescriptorSpendKey::Public(pk) => fmt::Display::fmt(pk, f), + DescriptorSpendKey::Private(sk) => fmt::Display::fmt(sk, f), + } + } +} + +impl fmt::Display for Sp { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use fmt::Write; + let mut wrapped_f = checksum::Formatter::new(f); + match &self.inner { + SpInner::Encoded { origin, key } => { + write!(wrapped_f, "sp(")?; + if let Some(origin) = origin { + write_key_origin(&mut wrapped_f, origin)?; + } + write!(wrapped_f, "{key})")?; + } + SpInner::TwoKey(keys) => { + write!(wrapped_f, "sp({},{})", keys.scan(), keys.spend())?; + } + } + wrapped_f.write_checksum_if_not_alt() + } +} + +impl FromStr for Sp { + type Err = Error; + + fn from_str(s: &str) -> Result { + let expr_tree = expression::Tree::from_str(s)?; + Self::from_tree(expr_tree.root()) + } +} + +impl Sp { + fn from_tree(root: expression::TreeIterItem) -> Result { + root.verify_toplevel("sp", 1..=2) + .map_err(miniscript::ParseError::from) + .map_err(miniscript::Error::Parse)?; + + let mut children = root.children(); + let first = children.next().unwrap(); + + match root.n_children() { + 1 => { + // Single-argument form: spscan or spspend, optionally with a key origin. + if first.n_children() > 0 { + return Err(Error::Unexpected( + "sp() single-argument form expects an spscan or spspend key".to_string(), + )); + } + let (key_str, origin) = split_key_origin(first.name())?; + let key = SpKey::from_str(key_str).map_err(Error::SpKey)?; + Ok(Sp::from_encoded(origin, key)) + } + 2 => { + // Two-argument form: private scan key, then spend key. + let second = children.next().unwrap(); + if first.n_children() > 0 { + return Err(Error::Unexpected( + "sp() scan key must be a single private key".to_string(), + )); + } + let scan = DescriptorSecretKey::from_str(first.name()) + .map_err(|e| Error::Unexpected(format!("sp() scan key: {e}")))?; + let spend = parse_spend_key(second)?; + Sp::from_keys(scan, spend) + } + _ => unreachable!("verify_toplevel checked 1..=2"), + } + } +} + +fn parse_spend_key(node: expression::TreeIterItem) -> Result { + if node.n_children() > 0 { + return Err(Error::Unexpected( + "sp() spend key must be a single key expression".to_string(), + )); + } + + match DescriptorSecretKey::from_str(node.name()) { + Ok(sk) => Ok(DescriptorSpendKey::Private(sk)), + Err(_) => { + let pk = DescriptorPublicKey::from_str(node.name()) + .map_err(|e| Error::Unexpected(format!("sp() spend key: {e}")))?; + Ok(DescriptorSpendKey::Public(pk)) + } + } +} + +#[cfg(test)] +mod tests { + use miniscript::bitcoin::Network; + use miniscript::bitcoin::bip32::{DerivationPath, Xpriv, Xpub}; + use secp256k1::{Secp256k1, SecretKey}; + + use super::*; + + const WIF_SCAN: &str = "L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1"; + const SPEND_PUB: &str = "0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600"; + const UNCOMPRESSED_WIF: &str = "5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss"; + + fn secret(byte: u8) -> SecretKey { + SecretKey::from_slice(&[byte; 32]).expect("valid scalar") + } + + fn spscan() -> String { + SpScanKey { + scan_key: secret(0xab), + spend_key: { + let secp = Secp256k1::signing_only(); + secret(0xcd).public_key(&secp) + }, + network: SpNetwork::Mainnet, + } + .to_string() + } + + fn spscan_testnet() -> String { + SpScanKey { + scan_key: secret(0xab), + spend_key: { + let secp = Secp256k1::signing_only(); + secret(0xcd).public_key(&secp) + }, + network: SpNetwork::Testnet, + } + .to_string() + } + + fn spspend() -> String { + SpSpendKey { + scan_key: secret(0xab), + spend_key: secret(0xcd), + network: SpNetwork::Mainnet, + } + .to_string() + } + + /// Account-level extended keys used to fill in the BIP's `xprv...` / `xpub...` placeholders. + fn account_xkeys() -> (Xpriv, Xpub) { + let master = Xpriv::new_master(Network::Bitcoin, &[0x11; 64]).expect("valid seed"); + let secp = Secp256k1::new(); + let path: DerivationPath = "m/352h/0h/0h".parse().unwrap(); + let xprv = master.derive_priv(&secp, &path).unwrap(); + let xpub = Xpub::from_priv(&secp, &xprv); + (xprv, xpub) + } + + fn assert_roundtrip(desc: &str) { + let sp = Sp::from_str(desc).unwrap_or_else(|e| panic!("parse {desc}: {e}")); + let displayed = sp.to_string(); + let again = Sp::from_str(&displayed).unwrap_or_else(|e| panic!("reparse {displayed}: {e}")); + assert_eq!(sp, again); + } + + #[test] + fn valid_spscan() { + let desc = format!("sp({})", spscan()); + let sp = Sp::from_str(&desc).unwrap(); + assert!(sp.is_watch_only()); + assert!(sp.is_mainnet()); + assert_roundtrip(&desc); + } + + #[test] + fn valid_spscan_testnet() { + let desc = format!("sp({})", spscan_testnet()); + let sp = Sp::from_str(&desc).unwrap(); + assert!(!sp.is_mainnet()); + assert_roundtrip(&desc); + } + + #[test] + fn valid_spscan_with_origin() { + let desc = format!("sp([deadbeef/352h/0h/0h]{})", spscan()); + let sp = Sp::from_str(&desc).unwrap(); + assert!(sp.is_watch_only()); + assert!( + sp.to_string() + .starts_with("sp([deadbeef/352h/0h/0h]spscan1") + ); + assert_roundtrip(&desc); + } + + #[test] + fn valid_spspend() { + let desc = format!("sp({})", spspend()); + let sp = Sp::from_str(&desc).unwrap(); + assert!(sp.has_spend_key()); + assert!(sp.is_mainnet()); + assert_roundtrip(&desc); + } + + #[test] + fn valid_wif_and_compressed_pubkey() { + let desc = format!("sp({WIF_SCAN},{SPEND_PUB})"); + let sp = Sp::from_str(&desc).unwrap(); + assert!(sp.is_watch_only()); + assert!(sp.is_mainnet()); + assert_roundtrip(&desc); + } + + #[test] + fn valid_xprv_and_xpub() { + let (xprv, xpub) = account_xkeys(); + let secp = Secp256k1::new(); + let scan_path: DerivationPath = "m/0h".parse().unwrap(); + let spend_path: DerivationPath = "m/0".parse().unwrap(); + let expected_scan = xprv.derive_priv(&secp, &scan_path).unwrap().private_key; + // Hardened children cannot be derived from an xpub. + let expected_spend = xpub.derive_pub(&secp, &spend_path).unwrap().public_key; + + let desc = format!("sp([deadbeef/352h/0h/0h]{xprv}/0h,{xpub}/0)"); + let sp = Sp::from_str(&desc).unwrap(); + assert!(sp.is_watch_only()); + assert_eq!(sp.scan_key(), expected_scan); + assert_ne!(sp.scan_key(), xprv.private_key); + assert_eq!(sp.spend_secret(), None); + assert_eq!(sp.spend_pubkey(), expected_spend); + assert_ne!(sp.spend_pubkey(), xpub.public_key); + assert_roundtrip(&desc); + } + + #[test] + fn valid_xprv_and_xprv() { + let (xprv, _) = account_xkeys(); + let secp = Secp256k1::new(); + let child_path: DerivationPath = "m/0h".parse().unwrap(); + let expected = xprv.derive_priv(&secp, &child_path).unwrap().private_key; + + let desc = format!("sp([deadbeef/352h/0h/0h]{xprv}/0h,{xprv}/0h)"); + let sp = Sp::from_str(&desc).unwrap(); + assert!(sp.has_spend_key()); + assert_eq!(sp.scan_key(), expected); + assert_ne!(sp.scan_key(), xprv.private_key); + assert_eq!(sp.spend_secret(), Some(expected)); + assert_ne!(sp.spend_secret(), Some(xprv.private_key)); + assert_roundtrip(&desc); + } + + #[test] + fn invalid_empty() { + assert!(Sp::from_str("sp()").is_err()); + } + + #[test] + fn invalid_single_xpub() { + let (_, xpub) = account_xkeys(); + assert!(Sp::from_str(&format!("sp({xpub})")).is_err()); + } + + #[test] + fn invalid_two_xpubs() { + let (_, xpub) = account_xkeys(); + assert!(Sp::from_str(&format!("sp({xpub},{xpub})")).is_err()); + } + + #[test] + fn invalid_hardened_xpub() { + let (xprv, xpub) = account_xkeys(); + for desc in [ + format!("sp({xprv},{xpub}/0h)"), + format!("sp({xprv},{xpub}/1h/0)"), + ] { + match Sp::from_str(&desc) { + Err(Error::Unexpected(msg)) => { + assert!(msg.contains("hardened"), "{desc}: {msg}"); + } + other => panic!("expected hardened xpub rejection for {desc}, got {other:?}"), + } + } + } + + #[test] + fn invalid_wildcard() { + let (xprv, xpub) = account_xkeys(); + for (desc, scan) in [ + (format!("sp({xprv}/*,{xpub})"), true), + (format!("sp({xprv},{xpub}/*h)"), false), + (format!("sp({xprv},{xprv}/*)"), false), + ] { + match Sp::from_str(&desc) { + Err(Error::Scan(KeyError::Wildcard)) if scan => {} + Err(Error::Spend(KeyError::Wildcard)) if !scan => {} + other => panic!("expected wildcard rejection for {desc}, got {other:?}"), + } + } + } + + #[test] + fn invalid_two_spscan_keys() { + let scan = spscan(); + assert!(Sp::from_str(&format!("sp({scan},{scan})")).is_err()); + } + + #[test] + fn invalid_uncompressed_scan_key() { + match Sp::from_str(&format!("sp({UNCOMPRESSED_WIF},{SPEND_PUB})")) { + Err(Error::Scan(KeyError::Uncompressed)) => {} + other => panic!("expected uncompressed scan key rejection, got {other:?}"), + } + } + + #[test] + fn invalid_nested_in_sh() { + assert!(Sp::from_str(&format!("sh(sp({}))", spscan())).is_err()); + } + + #[test] + fn invalid_nested_in_wsh() { + assert!(Sp::from_str(&format!("wsh(sp({}))", spscan())).is_err()); + } +} diff --git a/spdk-wallet/Cargo.toml b/spdk-wallet/Cargo.toml index c578f3eb..cd22d214 100644 --- a/spdk-wallet/Cargo.toml +++ b/spdk-wallet/Cargo.toml @@ -12,6 +12,7 @@ crate-type = ["lib", "staticlib", "cdylib"] spdk-core.workspace = true backend-blindbit-v1 = { workspace = true, optional = true } local-scanner = { workspace = true, optional = true, features = ["rayon"] } +bip392 = { workspace = true, optional = true } anyhow.workspace = true bitcoin.workspace = true @@ -30,6 +31,7 @@ serde_json.workspace = true [features] default = ["backend-blindbit-v1", "local-scanner"] +bip392 = ["dep:bip392"] [lints] workspace = true diff --git a/spdk-wallet/src/client/client.rs b/spdk-wallet/src/client/client.rs index b7ddf858..8cdff39a 100644 --- a/spdk-wallet/src/client/client.rs +++ b/spdk-wallet/src/client/client.rs @@ -45,6 +45,20 @@ impl SpClient { }) } + /// Builds a client from an `sp()` descriptor. + /// + /// `network` must be mainnet when the descriptor is mainnet, and a non-mainnet + /// network otherwise. The descriptor cannot tell regtest, signet, and testnet apart. + #[cfg(feature = "bip392")] + pub fn from_descriptor(descriptor: &bip392::Sp, network: Network) -> Result { + if descriptor.is_mainnet() != matches!(network, Network::Bitcoin) { + return Err(Error::msg( + "descriptor network does not match the wallet network", + )); + } + Self::new(descriptor.scan_key(), SpendKey::from(descriptor), network) + } + pub fn receiver(&self) -> Receiver { self.sp_receiver.clone() } @@ -102,3 +116,41 @@ impl Drop for SpClient { self.scan_sk.non_secure_erase(); } } + +#[cfg(all(test, feature = "bip392"))] +mod tests { + use std::str::FromStr as _; + + use bip392::Sp; + + use super::{Network, SpClient, SpendKey}; + + const WIF: &str = "L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1"; + const SPEND_PUB: &str = "0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600"; + + #[test] + fn descriptor_spend_pubkey_wraps_into_client() { + let descriptor = Sp::from_str(&format!("sp({WIF},{SPEND_PUB})")).unwrap(); + let SpendKey::Public(pk) = SpendKey::from(&descriptor) else { + panic!("watch-only descriptor"); + }; + assert_eq!(pk, descriptor.spend_pubkey()); + assert!(descriptor.spend_secret().is_none()); + + let client = SpClient::from_descriptor(&descriptor, Network::Bitcoin).unwrap(); + assert!(client.try_secret_spend_key().is_err()); + assert!(SpClient::from_descriptor(&descriptor, Network::Signet).is_err()); + } + + #[test] + fn descriptor_spend_secret_wraps_into_client() { + let descriptor = Sp::from_str(&format!("sp({WIF},{WIF})")).unwrap(); + let SpendKey::Secret(sk) = SpendKey::from(&descriptor) else { + panic!("descriptor with spend secret"); + }; + assert_eq!(Some(sk), descriptor.spend_secret()); + + let client = SpClient::from_descriptor(&descriptor, Network::Bitcoin).unwrap(); + assert_eq!(client.try_secret_spend_key().unwrap(), sk); + } +} diff --git a/spdk-wallet/src/client/mod.rs b/spdk-wallet/src/client/mod.rs index e8614080..dac2bf55 100644 --- a/spdk-wallet/src/client/mod.rs +++ b/spdk-wallet/src/client/mod.rs @@ -2,9 +2,11 @@ mod client; mod coin_select; mod spend; +mod spend_key; mod structs; pub use client::SpClient; pub use coin_select::{CoinSelectProposal, DrainSelection, Strategy}; pub use spend::{propose_coin_selections, propose_drain_selection}; +pub use spend_key::SpendKey; pub use structs::*; diff --git a/spdk-wallet/src/client/spend_key.rs b/spdk-wallet/src/client/spend_key.rs new file mode 100644 index 00000000..c97d1d5a --- /dev/null +++ b/spdk-wallet/src/client/spend_key.rs @@ -0,0 +1,48 @@ +use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; + +/// A spend key that can be either a secret key (full wallet) or a public key (watch-only). +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum SpendKey { + Secret(SecretKey), + Public(PublicKey), +} + +impl Drop for SpendKey { + fn drop(&mut self) { + if let Self::Secret(sk) = self { + // Erase the key material before dropping. + // secp256k1::SecretKey does not implement Zeroize (its inner + // array is private); non_secure_erase() is the zeroize-documented + // erase path (volatile C-level memset, cannot be optimized away). + sk.non_secure_erase(); + } + } +} + +impl From<&SpendKey> for PublicKey { + fn from(value: &SpendKey) -> Self { + match value { + SpendKey::Secret(k) => { + let secp = Secp256k1::signing_only(); + k.public_key(&secp) + } + SpendKey::Public(p) => *p, + } + } +} + +impl From for PublicKey { + fn from(value: SpendKey) -> Self { + (&value).into() + } +} + +#[cfg(feature = "bip392")] +impl From<&bip392::Sp> for SpendKey { + fn from(descriptor: &bip392::Sp) -> Self { + match descriptor.spend_secret() { + Some(secret) => Self::Secret(secret), + None => Self::Public(descriptor.spend_pubkey()), + } + } +} diff --git a/spdk-wallet/src/client/structs.rs b/spdk-wallet/src/client/structs.rs index 3bbd20b4..d8913e25 100644 --- a/spdk-wallet/src/client/structs.rs +++ b/spdk-wallet/src/client/structs.rs @@ -1,15 +1,11 @@ use std::str::FromStr as _; -use anyhow::Error; // re-export from bdk_coin_select, as we use this in the api pub use bdk_coin_select::FeeRate; use bitcoin::address::NetworkUnchecked; use bitcoin::hex::{DisplayHex as _, FromHex as _}; -use bitcoin::key::Secp256k1; use bitcoin::script::PushBytesBuf; -use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::{Address, Amount, Network, OutPoint, Transaction}; -use serde::{Deserialize, Serialize}; use silentpayments::SilentPaymentCode; use silentpayments::utils::sending::PartialSecret; use spdk_core::scanner::DiscoveredOutput; @@ -74,49 +70,3 @@ pub struct SilentPaymentUnsignedTransaction { /// Coin-selection strategy used for a payment; `None` for drain transactions. pub strategy: Option, } - -#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] -pub enum SpendKey { - Secret(SecretKey), - Public(PublicKey), -} - -impl Drop for SpendKey { - fn drop(&mut self) { - if let Self::Secret(sk) = self { - // Erase the key material before dropping. - // secp256k1::SecretKey does not implement Zeroize (its inner - // array is private); non_secure_erase() is the zeroize-documented - // erase path (volatile C-level memset, cannot be optimized away). - sk.non_secure_erase(); - } - } -} - -impl TryInto for SpendKey { - type Error = anyhow::Error; - fn try_into(self) -> std::prelude::v1::Result { - match self { - Self::Secret(k) => Ok(k), - Self::Public(_) => Err(Error::msg("Can't take SecretKey from Public")), - } - } -} - -impl From<&SpendKey> for PublicKey { - fn from(value: &SpendKey) -> Self { - match value { - SpendKey::Secret(k) => { - let secp = Secp256k1::signing_only(); - k.public_key(&secp) - } - SpendKey::Public(p) => *p, - } - } -} - -impl From for PublicKey { - fn from(value: SpendKey) -> Self { - (&value).into() - } -} diff --git a/spdk-wallet/src/lib.rs b/spdk-wallet/src/lib.rs index 0a938b21..50b94786 100644 --- a/spdk-wallet/src/lib.rs +++ b/spdk-wallet/src/lib.rs @@ -8,8 +8,10 @@ pub use backend_blindbit_v1; // re-export libraries for consumers pub use bip321; pub use bip321_parsing::{SpUriExtension, SpUriParseError, parse_sp, parse_tsp}; -pub use bitcoin; // re-export local scanner if enabled +#[cfg(feature = "bip392")] +pub use bip392; +pub use bitcoin; #[cfg(feature = "local-scanner")] pub use local_scanner::SpScanner; pub use silentpayments;