spark_rust/wallet/client.rs
1//! # Spark Wallet SDK
2//!
3//! The central entry point for interacting with the Spark protocol, a non-custodial Bitcoin wallet
4//! and payment solution. This module provides the main SDK structure that coordinates all Spark
5//! functionality including:
6//!
7//! - Wallet initialization and authentication
8//! - Creating and managing deposit addresses
9//! - Transferring funds between wallets
10//! - Lightning network payments
11//! - On-chain transaction management
12//! - Leaf (UTXO) management
13//! - Fee estimation and handling
14//!
15//! The SDK is designed around a modular signer architecture that allows for both the provided
16//! default implementation and custom signing solutions.
17
18use super::leaf_manager::LeafManager;
19use crate::signer::default_signer::DefaultSigner;
20use crate::signer::traits::SparkSigner;
21use crate::wallet::config::WalletConfig;
22use std::sync::Arc;
23use tokio::sync::MutexGuard;
24
25/// Macro to wrap handler functions with a global lock
26///
27/// This macro takes a handler function call and wraps it with the handler lock acquisition.
28/// It's useful for ensuring exclusive access to all leaves during handler operations.
29///
30/// # Usage
31/// ```
32/// // Inside an SDK method
33/// with_handler_lock!(self, async {
34/// // Your handler implementation here
35/// self.some_internal_method().await?;
36/// Ok(result)
37/// }).await
38/// ```
39#[macro_export]
40macro_rules! with_handler_lock {
41 ($self:expr, $handler_impl:expr) => {{
42 let _guard = $self.acquire_handler_lock().await;
43 $handler_impl
44 }};
45}
46
47/// The main interface for the Spark wallet SDK
48///
49/// `SparkSdk` is the primary point of interaction with the Spark protocol, providing
50/// a complete set of wallet functionality for Bitcoin and Lightning operations.
51/// It coordinates between the cryptographic signer, wallet configuration, and
52/// leaf (UTXO) management components.
53///
54/// The SDK supports a pluggable signer architecture through its generic parameter,
55/// allowing applications to use either the provided `DefaultSigner` or implement
56/// their own custom signing solution (e.g., for hardware wallet integration).
57///
58/// Key functionality provided by the SDK includes:
59///
60/// - **Initialization:** Create and set up a new wallet instance
61/// - **Deposits:** Generate deposit addresses and deposit trees
62/// - **Transfers:** Send funds to other Spark users or Bitcoin addresses
63/// - **Lightning:** Make and receive Lightning Network payments
64/// - **Leaves:** Manage individual UTXOs within the wallet
65/// - **Swaps:** Swap funds between different payment channels
66/// - **Timelocks:** Manage timelock conditions for funds
67/// - **Fees:** Estimate and manage transaction fees
68///
69/// # Examples
70///
71/// ```
72/// use spark_rust::{
73/// error::SparkSdkError,
74/// signer::default_signer::DefaultSigner,
75/// signer::traits::SparkSigner,
76/// SparkNetwork, SparkSdk,
77/// };
78/// use std::sync::Arc;
79///
80/// async fn example() -> Result<(), SparkSdkError> {
81/// // Initialize with a mnemonic phrase and network
82/// let mnemonic = "abandon ability able about above absent absorb abstract absurd abuse access accident";
83/// let network = SparkNetwork::Regtest;
84///
85/// // Create the signer
86/// let signer = Arc::new(DefaultSigner::from_mnemonic(mnemonic, network.clone()).await?);
87///
88/// // Initialize the SDK
89/// let sdk = SparkSdk::new(network, signer).await?;
90///
91/// // Get wallet information
92/// let address = sdk.get_spark_address()?;
93/// println!("Spark address: {}", hex::encode(address.serialize()));
94///
95/// // Use other SDK functionality...
96///
97/// Ok(())
98/// }
99/// ```
100///
101/// # Security Considerations
102///
103/// The Spark SDK architecture implements security through several layers:
104///
105/// ## SDK Architecture Security
106/// - Separation of concerns: The SDK delegates all key operations to the signer component
107/// - Secure API communication with Spark operators using authenticated sessions
108/// - Protocol-level validation of all operator responses
109/// - Thread-safe access to shared resources
110///
111/// ## Signer Security (using DefaultSigner)
112/// - BIP39 mnemonic-based key generation with proper entropy
113/// - BIP32/BIP44 compliant hierarchical deterministic key derivation
114/// - Secure storage of private keys with optional encryption
115/// - Explicit methods for sensitive operations with clear security warnings
116///
117/// ## Spark Protocol Security
118/// - Threshold signature schemes (FROST) requiring multiple parties to sign transactions
119/// - Defense in depth through multiple security mechanisms
120/// - Timelocked refund transactions as safety guarantees
121/// - Verifiable cryptographic proofs for key operations
122///
123/// Note: This is an early version of the SDK, and future updates will further enhance
124/// isolation and security properties.
125#[derive(Clone)]
126pub struct SparkSdk<S: SparkSigner + Send + Sync = DefaultSigner> {
127 /// Wallet configuration including network settings and session information
128 pub(crate) config: WalletConfig,
129
130 /// Cryptographic signer that manages private keys and signing operations
131 pub(crate) signer: Arc<S>,
132
133 /// Manager for wallet leaves (UTXOs)
134 pub(crate) leaf_manager: Arc<LeafManager>,
135
136 /// Global lock for handler operations
137 pub(crate) handler_lock: Arc<tokio::sync::Mutex<()>>,
138}
139
140impl<S: SparkSigner + Send + Sync + Clone + 'static> SparkSdk<S> {
141 /// Acquires the global handler lock to ensure exclusive access to all leaves during a handler operation.
142 ///
143 /// This method returns a guard that will automatically release the lock when it's dropped.
144 /// If the handler code panics or returns early, the lock will still be released.
145 ///
146 /// # Returns
147 /// A MutexGuard that will release the lock when dropped
148 ///
149 /// # Usage
150 /// ```
151 /// async fn some_handler_method(&self) -> Result<(), SparkSdkError> {
152 /// // Acquire the lock at the beginning of the handler
153 /// let _guard = self.acquire_handler_lock().await;
154 ///
155 /// // Rest of handler implementation...
156 ///
157 /// // Lock is automatically released when _guard goes out of scope
158 /// Ok(())
159 /// }
160 /// ```
161 pub(crate) async fn acquire_handler_lock(&self) -> MutexGuard<'_, ()> {
162 self.handler_lock.lock().await
163 }
164}