diff --git a/silentpayments/README.md b/silentpayments/README.md index 1cc97cae..71e3331b 100644 --- a/silentpayments/README.md +++ b/silentpayments/README.md @@ -19,7 +19,7 @@ The library is split up in two parts: sending and receiving. This library offers granular feature flags to minimize dependencies for different use cases: - **default**: Enables all features (`encode`, `sending`, `receiving`) -- **encode**: Enables string encoding/decoding for `SilentPaymentAddress` (adds `bech32` dependency) +- **encode**: Enables string encoding/decoding for `SilentPaymentAddressDisplay` (adds `bech32` dependency) - **serde**: Enables serde serialization/deserialization for types (adds `serde` dependency) - **sending**: Enables sending functionality (adds `bitcoin_hashes`, `hex` dependencies) - **receiving**: Enables receiving functionality (adds `bitcoin_hashes`, `hex`, `bimap`, `serde` dependencies) @@ -35,7 +35,7 @@ silentpayments = { version = "0.4", default-features = false } This configuration only pulls in `secp256k1` as a dependency, significantly reducing the dependency tree for applications that only need to work with silent payment addresses without implementing the full protocol. -**Bring Your Own Parser**: Even without the `encode` feature, you can construct a `SilentPaymentAddress` using `SilentPaymentAddress::new()` if you parse the bech32 yourself. This is useful if your application already has a bech32 parser and you want to avoid duplicate dependencies. The constructor documentation includes the complete bech32 format specification. +**Bring Your Own Parser**: Even without the `encode` feature, you can construct a `SilentPaymentAddress` using `SilentPaymentAddress::new()` from pubkeys you parsed yourself. With `encode`, use `SilentPaymentAddressDisplay` for bech32m strings; see `SilentPaymentAddressDisplay::new` for the on-wire format if you parse bech32 yourself. ### Custom Feature Combinations diff --git a/silentpayments/examples/create_wallet.rs b/silentpayments/examples/create_wallet.rs index f1e66e6a..a090c349 100644 --- a/silentpayments/examples/create_wallet.rs +++ b/silentpayments/examples/create_wallet.rs @@ -45,7 +45,12 @@ fn main() -> Result<(), Box> { )?; // Print the receiving address to the console - println!("Receiving address: {}", receiver.get_receiving_address()); + println!( + "Receiving address: {}", + receiver + .get_receiving_address() + .to_display_for_network(receiver.network) + ); Ok(()) } diff --git a/silentpayments/examples/custom_parser.rs b/silentpayments/examples/custom_parser.rs deleted file mode 100644 index 08d5f5b1..00000000 --- a/silentpayments/examples/custom_parser.rs +++ /dev/null @@ -1,47 +0,0 @@ -/// Example showing how to construct a SilentPaymentAddress without the `encode` feature. -/// -/// This is useful if your application already has a bech32 parser and you want to -/// avoid duplicate dependencies. You can parse the address yourself and then -/// construct the type using the public constructor. -/// -/// To run this example: -/// ```bash -/// cargo run --example custom_parser --no-default-features -/// ``` -fn main() { - use secp256k1::{PublicKey, Secp256k1, SecretKey}; - use silentpayments::{Network, SilentPaymentAddress}; - - // Example: Simulating what you'd get after parsing bech32 yourself - // In a real application, you would: - // 1. Parse the bech32m string (e.g., "sp1...") - // 2. Extract the HRP to determine the network - // 3. Decode the data part to get version + 33-byte scan key + 33-byte spend key - // 4. Deserialize the pubkeys from those bytes - // 5. Construct the SilentPaymentAddress using the constructor - - // For this example, we'll generate valid pubkeys - let secp = Secp256k1::new(); - let scan_secret = SecretKey::from_slice(&[0x01; 32]).expect("valid key"); - let spend_secret = SecretKey::from_slice(&[0x02; 32]).expect("valid key"); - - let scan_pubkey = PublicKey::from_secret_key(&secp, &scan_secret); - let spend_pubkey = PublicKey::from_secret_key(&secp, &spend_secret); - - // Construct the SilentPaymentAddress without needing the `encode` feature - let address = SilentPaymentAddress::new( - scan_pubkey, - spend_pubkey, - Network::Mainnet, - silentpayments::SpVersion::ZERO, - ); - - println!("Successfully created SilentPaymentAddress without encode feature!"); - println!("Network: {:?}", address.get_network()); - println!("Version: {}", address.get_version()); - println!("Scan key: {:?}", address.get_scan_key()); - println!("Spend key: {:?}", address.get_spend_key()); - - println!("\n✅ This example compiled and ran with ZERO features enabled!"); - println!(" Only dependencies: secp256k1, rand, rand_core, secp256k1-sys"); -} diff --git a/silentpayments/src/lib.rs b/silentpayments/src/lib.rs index 97eeddd4..d12dff75 100644 --- a/silentpayments/src/lib.rs +++ b/silentpayments/src/lib.rs @@ -6,7 +6,7 @@ //! This library offers granular feature flags to minimize dependencies: //! //! - **default**: Enables `encode`, `sending`, and `receiving` features -//! - **encode**: Enables string encoding/decoding for `SilentPaymentAddress` (requires `bech32`) +//! - **encode**: Enables string encoding/decoding for `SilentPaymentAddressDisplay` (requires `bech32`) //! - **serde**: Enables serde serialization/deserialization for types //! - **sending**: Enables sending functionality (requires `bitcoin_hashes`, `hex`, and `encode`) //! - **receiving**: Enables receiving functionality (requires `bitcoin_hashes`, `hex`, `bimap`, `serde`, and `encode`) @@ -24,10 +24,10 @@ //! This will only pull in `secp256k1` as a dependency, giving you access to the core types //! without any encoding, serialization, or protocol functionality. //! -//! **Note**: Even without the `encode` feature, you can still construct a `SilentPaymentAddress` -//! from its components using `SilentPaymentAddress::new()`. This allows you to use your own -//! bech32 parser (if your application already has one) and avoid duplicate dependencies. -//! See the `SilentPaymentAddress::new()` documentation for the bech32 format specification. +//! **Note**: Without the `encode` feature, construct a [`SilentPaymentAddress`] from +//! parsed pubkeys using [`SilentPaymentAddress::new`]. With `encode`, use +//! [`SilentPaymentAddressDisplay`] for bech32m strings (see [`SilentPaymentAddressDisplay::new`] +//! for the on-wire format if you parse bech32 yourself). //! //! ## Examples //! @@ -55,6 +55,8 @@ pub use utils::common::Network; #[cfg(any(feature = "sending", feature = "receiving"))] pub use utils::common::SharedSecret; pub use utils::common::SilentPaymentAddress; +#[cfg(feature = "encode")] +pub use utils::common::SilentPaymentAddressDisplay; pub use utils::common::SpVersion; pub type Result = std::result::Result; diff --git a/silentpayments/src/receiving.rs b/silentpayments/src/receiving.rs index 2e5cc208..89984810 100644 --- a/silentpayments/src/receiving.rs +++ b/silentpayments/src/receiving.rs @@ -467,7 +467,7 @@ impl Receiver { } fn get_silent_payment_address(&self, m_pubkey: PublicKey) -> SilentPaymentAddress { - SilentPaymentAddress::new(self.scan_pubkey, m_pubkey, self.network, self.version) + SilentPaymentAddress::new(self.version, self.scan_pubkey, m_pubkey) } } diff --git a/silentpayments/src/sending.rs b/silentpayments/src/sending.rs index 0d3f7338..f9e07e6b 100644 --- a/silentpayments/src/sending.rs +++ b/silentpayments/src/sending.rs @@ -13,10 +13,10 @@ use std::collections::HashMap; use crate::utils::common::calculate_t_n; use crate::utils::common::SharedSecret; +use crate::utils::common::SilentPaymentAddress; use crate::utils::sending::calculate_ecdh_shared_secret; use crate::utils::sending::PartialSecret; use crate::Result; -use crate::SilentPaymentAddress; /// Create outputs for a given set of silent payment recipients and their corresponding shared secrets. /// @@ -26,7 +26,7 @@ use crate::SilentPaymentAddress; /// /// # Arguments /// -/// * `recipients` - A [Vec] of silent payment addresses strings to be paid. +/// * `recipients` - A [Vec] of silent payment addresses to be paid. /// * `partial_secret` - [PartialSecret] that represents the sum of the private keys of eligible inputs of the transaction multiplied by the input hash. /// /// # Returns @@ -38,7 +38,6 @@ use crate::SilentPaymentAddress; /// /// This function will return an error if: /// -/// * The recipients [Vec] contains a silent payment address with an incorrect format. /// * Edge cases are hit during elliptic curve computation (extremely unlikely). pub fn generate_recipient_pubkeys( recipients: Vec, @@ -49,14 +48,15 @@ pub fn generate_recipient_pubkeys( let mut silent_payment_groups: HashMap)> = HashMap::new(); for address in recipients { - let B_scan = address.get_scan_key(); + let recipient_scan_key = address.scan_key(); - if let Some((_, payments)) = silent_payment_groups.get_mut(&B_scan) { + if let Some((_, payments)) = silent_payment_groups.get_mut(&recipient_scan_key) { payments.push(address); } else { - let ecdh_shared_secret = calculate_ecdh_shared_secret(&B_scan, &partial_secret); + let ecdh_shared_secret = + calculate_ecdh_shared_secret(&recipient_scan_key, &partial_secret); - silent_payment_groups.insert(B_scan, (ecdh_shared_secret, vec![address])); + silent_payment_groups.insert(recipient_scan_key, (ecdh_shared_secret, vec![address])); } } @@ -68,7 +68,7 @@ pub fn generate_recipient_pubkeys( let t_n = calculate_t_n(&ecdh_shared_secret, n as u32)?; let res = t_n.public_key(&secp); - let reskey = res.combine(&addr.get_spend_key())?; + let reskey = res.combine(&addr.m_pubkey())?; let (reskey_xonly, _) = reskey.x_only_public_key(); let entry = result.entry(addr).or_default(); diff --git a/silentpayments/src/utils/common.rs b/silentpayments/src/utils/common.rs index 74d01173..af33cdfe 100644 --- a/silentpayments/src/utils/common.rs +++ b/silentpayments/src/utils/common.rs @@ -4,12 +4,12 @@ use core::fmt; #[cfg(any(feature = "sending", feature = "receiving"))] use crate::utils::hash::SharedSecretHash; use crate::Error; -#[cfg(any(feature = "sending", feature = "receiving", feature = "encode"))] use crate::Result; #[cfg(feature = "encode")] use bech32::{FromBase32, ToBase32}; #[cfg(any(feature = "sending", feature = "receiving"))] use bitcoin_hashes::Hash; +use secp256k1::constants::PUBLIC_KEY_SIZE; use secp256k1::PublicKey; #[cfg(any(feature = "sending", feature = "receiving"))] use secp256k1::{Scalar, Secp256k1, SecretKey}; @@ -146,23 +146,99 @@ impl TryFrom for SpVersion { match value { 0 => Ok(Self::ZERO), _ => Err(Error::GenericError( - "Unknwon silent payment version".to_string(), + "Unknown silent payment version".to_string(), )), } } } -/// A silent payment address struct that can be used to deserialize a silent payment address string. +/// Silent payment address (version + scan pubkey + `m` pubkey), without network. +/// +/// [`m_pubkey`](Self::m_pubkey) is the address spend pubkey (`B_m` in BIP352): +/// the receiver's spend public key, which may be unlabeled (`B_spend`) or labeled +/// (`B_spend + m·G`). +#[cfg_attr( + feature = "encode", + doc = "\n\nNetwork is only needed for bech32m strings; use [`SilentPaymentAddressDisplay`] or [`SilentPaymentAddress::to_display_for_network`] when encoding or showing an address." +)] #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] pub struct SilentPaymentAddress { version: SpVersion, - scan_pubkey: PublicKey, + scan_key: PublicKey, m_pubkey: PublicKey, +} + +impl SilentPaymentAddress { + /// Create a silent payment address from version, scan pubkey, and `m` pubkey. + /// + /// `m_pubkey` is the address spend pubkey (`B_m`), which may be labeled or not. + pub fn new(version: SpVersion, scan_key: PublicKey, m_pubkey: PublicKey) -> Self { + Self { + version, + scan_key, + m_pubkey, + } + } + + /// Create a version-0 silent payment address. + /// + /// `m_pubkey` is the address spend pubkey (`B_m`), which may be labeled or not. + pub fn new_v0(scan_key: PublicKey, m_pubkey: PublicKey) -> Self { + Self::new(SpVersion::ZERO, scan_key, m_pubkey) + } + + #[cfg(feature = "encode")] + /// Attach a [`Network`] for string encoding via [`SilentPaymentAddressDisplay`]. + pub fn to_display_for_network(&self, network: Network) -> SilentPaymentAddressDisplay { + SilentPaymentAddressDisplay::from_sp_address(*self, network) + } + + pub fn try_from_byte_array_v0(bytes: &[u8; PUBLIC_KEY_SIZE * 2]) -> Result { + let scan_key = PublicKey::from_slice(&bytes[..PUBLIC_KEY_SIZE])?; + let m_pubkey = PublicKey::from_slice(&bytes[PUBLIC_KEY_SIZE..])?; + Ok(Self::new(SpVersion::ZERO, scan_key, m_pubkey)) + } + + pub fn version(&self) -> SpVersion { + self.version + } + + pub fn scan_key(&self) -> PublicKey { + self.scan_key + } + + /// The address spend pubkey (`B_m` in BIP352). + /// + /// This may be the unlabeled spend pubkey, or a labeled one (`B_spend + m·G`). + pub fn m_pubkey(&self) -> PublicKey { + self.m_pubkey + } +} + +#[cfg(feature = "encode")] +impl From for SilentPaymentAddress { + fn from(value: SilentPaymentAddressDisplay) -> Self { + value.sp_address + } +} + +#[cfg(feature = "encode")] +impl From<&SilentPaymentAddressDisplay> for SilentPaymentAddress { + fn from(value: &SilentPaymentAddressDisplay) -> Self { + value.sp_address + } +} + +/// A silent payment address with network, serializable as a bech32m string. +#[cfg(feature = "encode")] +#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] +pub struct SilentPaymentAddressDisplay { + sp_address: SilentPaymentAddress, network: Network, } -#[cfg(all(feature = "serde", feature = "encode"))] -impl Serialize for SilentPaymentAddress { +#[cfg(feature = "serde")] +impl Serialize for SilentPaymentAddressDisplay { fn serialize(&self, serializer: S) -> std::result::Result where S: Serializer, @@ -172,95 +248,122 @@ impl Serialize for SilentPaymentAddress { } } -#[cfg(all(feature = "serde", feature = "encode"))] -impl<'de> Deserialize<'de> for SilentPaymentAddress { +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for SilentPaymentAddressDisplay { fn deserialize(deserializer: D) -> std::result::Result where D: Deserializer<'de>, { let addr_str: String = Deserialize::deserialize(deserializer)?; - SilentPaymentAddress::try_from(addr_str.as_str()).map_err(serde::de::Error::custom) + Self::try_from(addr_str.as_str()).map_err(serde::de::Error::custom) } } -impl SilentPaymentAddress { - /// Construct a `SilentPaymentAddress` from its component parts. +#[cfg(feature = "encode")] +impl SilentPaymentAddressDisplay { + /// Build a display address from an existing [`SilentPaymentAddress`] and [`Network`]. + pub fn from_sp_address(sp_address: SilentPaymentAddress, network: Network) -> Self { + Self { + sp_address, + network, + } + } + + /// Construct a [`SilentPaymentAddressDisplay`] from its component parts. /// - /// This constructor is always available, even without the `encode` feature. - /// If you have your own bech32 parser, you can use it to extract the components - /// and then construct the address using this method. + /// Combines a [`SilentPaymentAddress`] with a [`Network`] for bech32m string + /// encoding. If you already have a [`SilentPaymentAddress`], prefer + /// [`Self::from_sp_address`]. /// - /// # Bech32 Format (for external parsers) + /// If you use your own bech32 parser, extract the HRP and payload, then build + /// a [`SilentPaymentAddress`] (or call this method) and attach the network. + /// + /// # Bech32 format (for external parsers) /// /// Silent payment addresses use bech32m encoding with the following structure: /// - **HRP (Human Readable Part)**: /// - Mainnet: `"sp"` /// - Testnet/Signet: `"tsp"` /// - Regtest: `"sprt"` - /// - **Data**: version (1 byte) + scan_pubkey (33 bytes) + spend_pubkey (33 bytes) + /// - **Data**: a single 5-bit version digit, then the 66-byte payload + /// `serP(B_scan) ‖ serP(B_m)` converted to 5-bit characters. + /// `B_m` is the address spend pubkey (labeled or not). /// /// # Example /// /// ```ignore /// use secp256k1::PublicKey; - /// use silentpayments::{SilentPaymentAddress, Network}; + /// use silentpayments::{Network, SilentPaymentAddressDisplay, SpVersion}; /// /// // After parsing bech32 yourself and extracting the pubkeys: - /// let scan_pubkey = PublicKey::from_slice(&scan_bytes)?; - /// let spend_pubkey = PublicKey::from_slice(&spend_bytes)?; + /// let scan_key = PublicKey::from_slice(&scan_bytes)?; + /// let m_pubkey = PublicKey::from_slice(&m_pubkey_bytes)?; /// - /// let address = SilentPaymentAddress::new( - /// scan_pubkey, - /// spend_pubkey, + /// let display = SilentPaymentAddressDisplay::new( + /// scan_key, + /// m_pubkey, /// Network::Mainnet, - /// 0 // version - /// )?; + /// SpVersion::ZERO, + /// ); + /// + /// // Sending/receiving APIs take the network-agnostic address: + /// let sp_address: silentpayments::SilentPaymentAddress = display.into(); /// ``` + /// + /// `m_pubkey` is the address spend pubkey (`B_m`), which may be labeled or not. pub fn new( - scan_pubkey: PublicKey, + scan_key: PublicKey, m_pubkey: PublicKey, network: Network, version: SpVersion, ) -> Self { - SilentPaymentAddress { - scan_pubkey, - m_pubkey, + Self::from_sp_address( + SilentPaymentAddress::new(version, scan_key, m_pubkey), network, - version, - } + ) } - /// Get the scan public key. - pub fn get_scan_key(&self) -> PublicKey { - self.scan_pubkey + /// Calls new() with version set at SpVersion::ZERO. + /// + /// `m_pubkey` is the address spend pubkey (`B_m`), which may be labeled or not. + pub fn new_v0(scan_key: PublicKey, m_pubkey: PublicKey, network: Network) -> Self { + Self::new(scan_key, m_pubkey, network, SpVersion::ZERO) } - /// Get the spend public key. - pub fn get_spend_key(&self) -> PublicKey { - self.m_pubkey + pub fn scan_key(&self) -> PublicKey { + self.sp_address.scan_key() } - /// Get the network. - pub fn get_network(&self) -> Network { + /// The address spend pubkey (`B_m` in BIP352). + /// + /// This may be the unlabeled spend pubkey, or a labeled one (`B_spend + m·G`). + pub fn m_pubkey(&self) -> PublicKey { + self.sp_address.m_pubkey() + } + + pub fn network(&self) -> Network { self.network } - /// Get the version byte. - pub fn get_version(&self) -> u8 { - self.version.into() + pub fn version(&self) -> SpVersion { + self.sp_address.version() + } + + pub fn as_inner(&self) -> SilentPaymentAddress { + self.sp_address } } #[cfg(feature = "encode")] -impl fmt::Display for SilentPaymentAddress { +impl fmt::Display for SilentPaymentAddressDisplay { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", >::into(*self)) + write!(f, "{}", >::into(*self)) } } #[cfg(feature = "encode")] -impl TryFrom<&str> for SilentPaymentAddress { +impl TryFrom<&str> for SilentPaymentAddressDisplay { type Error = Error; fn try_from(addr: &str) -> Result { @@ -286,20 +389,18 @@ impl TryFrom<&str> for SilentPaymentAddress { let data = Vec::::from_base32(&data[1..])?; - let scan_pubkey = PublicKey::from_slice(&data[..33])?; + let scan_key = PublicKey::from_slice(&data[..33])?; let m_pubkey = PublicKey::from_slice(&data[33..])?; - Ok(SilentPaymentAddress::new( - scan_pubkey, - m_pubkey, + Ok(Self::from_sp_address( + SilentPaymentAddress::new(version, scan_key, m_pubkey), network, - version, )) } } #[cfg(feature = "encode")] -impl TryFrom for SilentPaymentAddress { +impl TryFrom for SilentPaymentAddressDisplay { type Error = Error; fn try_from(addr: String) -> Result { @@ -308,24 +409,25 @@ impl TryFrom for SilentPaymentAddress { } #[cfg(feature = "encode")] -impl From for String { - fn from(val: SilentPaymentAddress) -> Self { +impl From for String { + fn from(val: SilentPaymentAddressDisplay) -> Self { let hrp = match val.network { Network::Testnet => "tsp", Network::Regtest => "sprt", Network::Mainnet => "sp", }; - let version = bech32::u5::try_from_u8(val.version.into()).unwrap(); + let version = bech32::u5::try_from_u8(val.version().into()) + .expect("SpVersion guarantees this conversion"); - let B_scan_bytes = val.scan_pubkey.serialize(); - let B_m_bytes = val.m_pubkey.serialize(); + let B_scan_bytes = val.scan_key().serialize(); + let B_m_bytes = val.m_pubkey().serialize(); let mut data = [B_scan_bytes, B_m_bytes].concat().to_base32(); data.insert(0, version); - bech32::encode(hrp, data, bech32::Variant::Bech32m).unwrap() + bech32::encode(hrp, data, bech32::Variant::Bech32m).expect("We know our hrps") } } @@ -333,9 +435,10 @@ pub(crate) struct NonEmptyArray<'a, T>(&'a [T]); impl<'a, T> NonEmptyArray<'a, T> { pub fn new(arr: &'a [T]) -> crate::Result { - match !arr.is_empty() { - true => Ok(Self(arr)), - false => Err(crate::Error::EmptyArray), + if !arr.is_empty() { + Ok(Self(arr)) + } else { + Err(crate::Error::EmptyArray) } } diff --git a/silentpayments/tests/common/structs.rs b/silentpayments/tests/common/structs.rs index 46688544..e8f4f6b1 100644 --- a/silentpayments/tests/common/structs.rs +++ b/silentpayments/tests/common/structs.rs @@ -1,6 +1,6 @@ #![allow(non_snake_case)] use serde::Deserialize; -use silentpayments::SilentPaymentAddress; +use silentpayments::SilentPaymentAddressDisplay; #[derive(Debug, Deserialize)] pub struct TestData { @@ -50,7 +50,7 @@ pub struct ReceivingDataGiven { #[derive(Debug, Deserialize)] pub struct ReceivingDataExpected { - pub addresses: Vec, + pub addresses: Vec, pub outputs: Vec, } diff --git a/silentpayments/tests/common/utils.rs b/silentpayments/tests/common/utils.rs index f3000112..a4e9182d 100644 --- a/silentpayments/tests/common/utils.rs +++ b/silentpayments/tests/common/utils.rs @@ -3,7 +3,7 @@ use std::{fs::File, io::Read, str::FromStr}; use bitcoin_hashes::Hash; use secp256k1::{Message, Scalar, SecretKey, XOnlyPublicKey}; use serde_json::from_str; -use silentpayments::SilentPaymentAddress; +use silentpayments::{SilentPaymentAddress, SilentPaymentAddressDisplay}; use super::structs::{OutputWithSignature, TestData}; @@ -66,7 +66,10 @@ pub fn decode_outputs_to_check(outputs: &[String]) -> Vec { pub fn decode_recipients(recipients: &[String]) -> Vec { recipients .iter() - .map(|sp_addr_str| sp_addr_str.as_str().try_into().unwrap()) + .map(|sp_addr_str| { + let display: SilentPaymentAddressDisplay = sp_addr_str.as_str().try_into().unwrap(); + SilentPaymentAddress::from(display) + }) .collect() } diff --git a/silentpayments/tests/vector_tests.rs b/silentpayments/tests/vector_tests.rs index f657bbbe..f820d9a3 100644 --- a/silentpayments/tests/vector_tests.rs +++ b/silentpayments/tests/vector_tests.rs @@ -161,12 +161,15 @@ mod tests { receiving_addresses.remove(&sp_receiver.get_change_address()); } - let set1: HashSet<_> = receiving_addresses.iter().collect(); - let set2: HashSet<_> = expected.addresses.iter().collect(); + let expected_addresses: HashSet = expected + .addresses + .iter() + .map(SilentPaymentAddress::from) + .collect(); // check that the receiving addresses generated are equal // to the expected addresses - assert_eq!(set1, set2); + assert_eq!(receiving_addresses, expected_addresses); let tweak_data = calculate_tweak_data(&input_pub_keys, &outpoints).unwrap(); let ecdh_shared_secret = calculate_ecdh_shared_secret(&tweak_data, &b_scan); diff --git a/spdk-wallet/examples/simple_scanner.rs b/spdk-wallet/examples/simple_scanner.rs index a06ca456..9a2ae873 100644 --- a/spdk-wallet/examples/simple_scanner.rs +++ b/spdk-wallet/examples/simple_scanner.rs @@ -90,8 +90,20 @@ async fn main() -> Result<(), Box> { let client = SpClient::new(scan_sk, SpendKey::Secret(spend_sk), NETWORK)?; + let sp_network = match NETWORK { + Network::Bitcoin => silentpayments::Network::Mainnet, + Network::Testnet | Network::Signet => silentpayments::Network::Testnet, + Network::Regtest => silentpayments::Network::Regtest, + _ => unreachable!(), + }; + println!("Receiving address for this key pair + network:"); - println!("{}", client.get_receiving_address()); + println!( + "{}", + client + .get_receiving_address() + .to_display_for_network(sp_network) + ); let mut scanner = SpScanner::new( client, diff --git a/spdk-wallet/src/client/bip321_parsing.rs b/spdk-wallet/src/client/bip321_parsing.rs index c323da31..4e4fabab 100644 --- a/spdk-wallet/src/client/bip321_parsing.rs +++ b/spdk-wallet/src/client/bip321_parsing.rs @@ -1,7 +1,7 @@ use std::fmt; use bip321::{Bip321Error, ExtensionHandler, FieldWithAttributes}; -use silentpayments::{Network, SilentPaymentAddress}; +use silentpayments::{Network, SilentPaymentAddressDisplay}; /// Error returned when validating silent payment fields of a BIP 321 URI. #[derive(Debug)] @@ -102,13 +102,13 @@ impl ExtensionHandler for SpUriExtension { fn parse_slot( fields: &[FieldWithAttributes], expected: Network, -) -> Result, SpUriParseError> { +) -> Result, SpUriParseError> { fields .iter() .map(|field| { - let addr = SilentPaymentAddress::try_from(field.inner().as_str()) + let addr = SilentPaymentAddressDisplay::try_from(field.inner().as_str()) .map_err(SpUriParseError::Address)?; - let got = addr.get_network(); + let got = addr.network(); let ok = match expected { Network::Mainnet => got == Network::Mainnet, _ => got != Network::Mainnet, @@ -127,7 +127,7 @@ fn parse_slot( /// every entry is parsed. Each address must be mainnet. pub fn parse_sp( fields: &[FieldWithAttributes], -) -> Result, SpUriParseError> { +) -> Result, SpUriParseError> { parse_slot(fields, Network::Mainnet) } @@ -138,7 +138,7 @@ pub fn parse_sp( /// regtest), matching bip321's `tb` rule. pub fn parse_tsp( fields: &[FieldWithAttributes], -) -> Result, SpUriParseError> { +) -> Result, SpUriParseError> { parse_slot(fields, Network::Testnet) } @@ -151,10 +151,10 @@ mod tests { use silentpayments::SpVersion; use super::{ - Network, SilentPaymentAddress, SpUriExtension, SpUriParseError, parse_sp, parse_tsp, + Network, SilentPaymentAddressDisplay, SpUriExtension, SpUriParseError, parse_sp, parse_tsp, }; - fn make_sp_address(network: Network) -> SilentPaymentAddress { + fn make_sp_address(network: Network) -> SilentPaymentAddressDisplay { let secp = Secp256k1::new(); let (scan_bytes, spend_bytes) = match network { Network::Mainnet => ([0x03; 32], [0x04; 32]), @@ -167,7 +167,7 @@ mod tests { let spend = SecretKey::from_slice(&spend_bytes) .unwrap() .public_key(&secp); - SilentPaymentAddress::new(scan, spend, network, SpVersion::ZERO) + SilentPaymentAddressDisplay::new(scan, spend, network, SpVersion::ZERO) } fn parse(s: &str) -> Bip321Uri { @@ -180,7 +180,7 @@ mod tests { let uri = parse(&format!("bitcoin:?sp={sp}")); let addrs = parse_sp(uri.sp()).unwrap(); assert_eq!(addrs.len(), 1); - assert_eq!(addrs[0].get_network(), Network::Mainnet); + assert_eq!(addrs[0].network(), Network::Mainnet); assert!(uri.extensions().tsp().is_empty()); } @@ -190,7 +190,7 @@ mod tests { let uri = parse(&format!("bitcoin:?tsp={tsp}")); let addrs = parse_tsp(uri.extensions().tsp()).unwrap(); assert_eq!(addrs.len(), 1); - assert_eq!(addrs[0].get_network(), Network::Testnet); + assert_eq!(addrs[0].network(), Network::Testnet); assert!(uri.sp().is_empty()); } @@ -200,7 +200,7 @@ mod tests { let uri = parse(&format!("bitcoin:?tsp={regtest}")); let addrs = parse_tsp(uri.extensions().tsp()).unwrap(); assert_eq!(addrs.len(), 1); - assert_eq!(addrs[0].get_network(), Network::Regtest); + assert_eq!(addrs[0].network(), Network::Regtest); assert!(uri.sp().is_empty()); } @@ -261,8 +261,8 @@ mod tests { let uri = parse(&format!("bitcoin:?tsp={tsp}&tsp={regtest}")); let addrs = parse_tsp(uri.extensions().tsp()).unwrap(); assert_eq!(addrs.len(), 2); - assert_eq!(addrs[0].get_network(), Network::Testnet); - assert_eq!(addrs[1].get_network(), Network::Regtest); + assert_eq!(addrs[0].network(), Network::Testnet); + assert_eq!(addrs[1].network(), Network::Regtest); } #[test] diff --git a/spdk-wallet/src/client/client.rs b/spdk-wallet/src/client/client.rs index 346e32b1..4bece843 100644 --- a/spdk-wallet/src/client/client.rs +++ b/spdk-wallet/src/client/client.rs @@ -115,8 +115,8 @@ impl SpClient { pub fn get_client_fingerprint(&self) -> Result<[u8; 8]> { let sp_address: SilentPaymentAddress = self.get_receiving_address(); - let scan_pk = sp_address.get_scan_key(); - let spend_pk = sp_address.get_spend_key(); + let scan_pk = sp_address.scan_key(); + let spend_pk = sp_address.m_pubkey(); // take a fingerprint of the wallet by hashing its keys let mut engine = sha256::HashEngine::default(); diff --git a/spdk-wallet/src/client/spend.rs b/spdk-wallet/src/client/spend.rs index 13d3d506..13292081 100644 --- a/spdk-wallet/src/client/spend.rs +++ b/spdk-wallet/src/client/spend.rs @@ -18,7 +18,7 @@ use bitcoin::{ }; use silentpayments::utils as sp_utils; use silentpayments::utils::sending::PartialSecret; -use silentpayments::{Network as SpNetwork, SilentPaymentAddress}; +use silentpayments::{Network as SpNetwork, SilentPaymentAddress, SilentPaymentAddressDisplay}; use spdk_core::constants::{DATA_CARRIER_SIZE, NUMS}; use spdk_core::updater::DiscoveredOutput; @@ -64,7 +64,7 @@ impl SpClient { }) } RecipientAddress::SpAddress(sp_address) => { - if sp_address.get_network() != address_sp_network { + if sp_address.network() != address_sp_network { return Err(Error::msg(format!( "Wrong network for address {}", sp_address @@ -135,7 +135,10 @@ impl SpClient { let change = coin_selector.drain(target, change_policy); let change_value = if change.is_some() { change.value } else { 0 }; if change_value > 0 { - let change_address = self.sp_receiver.get_change_address(); + let change_address = SilentPaymentAddressDisplay::from_sp_address( + self.sp_receiver.get_change_address(), + address_sp_network, + ); recipients.push(Recipient { address: RecipientAddress::SpAddress(change_address), amount: Amount::from_sat(change_value), @@ -181,7 +184,7 @@ impl SpClient { script_pubkey: address.clone().require_network(network)?.script_pubkey(), }), RecipientAddress::SpAddress(sp_address) => { - if sp_address.get_network() != address_sp_network { + if sp_address.network() != address_sp_network { return Err(Error::msg(format!( "Wrong network for address {}", sp_address @@ -270,7 +273,9 @@ impl SpClient { .recipients .iter() .filter_map(|r| match &r.address { - RecipientAddress::SpAddress(sp_address) => Some(sp_address.to_owned()), + RecipientAddress::SpAddress(sp_address) => { + Some(SilentPaymentAddress::from(*sp_address)) + } _ => None, }) .collect(); @@ -287,7 +292,7 @@ impl SpClient { RecipientAddress::SpAddress(s) => { // We now need to fill the sp outputs with actual spk let pubkeys = sp_address2xonlypubkeys - .get(s) + .get(&SilentPaymentAddress::from(*s)) .ok_or(Error::msg("Unknown sp address"))?; // we currently only allow having 1 output per silent payment address diff --git a/spdk-wallet/src/client/structs.rs b/spdk-wallet/src/client/structs.rs index ef958fb8..258762dc 100644 --- a/spdk-wallet/src/client/structs.rs +++ b/spdk-wallet/src/client/structs.rs @@ -7,7 +7,7 @@ use bitcoin::key::Secp256k1; use bitcoin::secp256k1::{PublicKey, SecretKey}; use bitcoin::{Address, Amount, Network, OutPoint, Transaction}; use serde::{Deserialize, Serialize}; -use silentpayments::SilentPaymentAddress; +use silentpayments::SilentPaymentAddressDisplay; use silentpayments::utils::sending::PartialSecret; use spdk_core::updater::DiscoveredOutput; @@ -19,14 +19,14 @@ pub use bdk_coin_select::FeeRate; #[serde(untagged)] pub enum RecipientAddress { LegacyAddress(Address), - SpAddress(SilentPaymentAddress), + SpAddress(SilentPaymentAddressDisplay), Data(Vec), // OpReturn output } impl TryFrom for RecipientAddress { type Error = anyhow::Error; fn try_from(value: String) -> Result { - if let Ok(sp_address) = SilentPaymentAddress::try_from(value.as_str()) { + if let Ok(sp_address) = SilentPaymentAddressDisplay::try_from(value.as_str()) { Ok(Self::SpAddress(sp_address)) } else if let Ok(legacy_address) = Address::from_str(&value) { Ok(Self::LegacyAddress(legacy_address))