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#[macro_export]
30macro_rules! with_handler_lock {
31 ($self:expr, $handler_impl:expr) => {{
32 let _guard = $self.acquire_handler_lock().await;
33 $handler_impl
34 }};
35}
36
37/// The main interface for the Spark wallet SDK
38///
39/// `SparkSdk` is the primary point of interaction with the Spark protocol, providing
40/// a complete set of wallet functionality for Bitcoin and Lightning operations.
41/// It coordinates between the cryptographic signer, wallet configuration, and
42/// leaf (UTXO) management components.
43///
44/// The SDK supports a pluggable signer architecture through its generic parameter,
45/// allowing applications to use either the provided `DefaultSigner` or implement
46/// their own custom signing solution (e.g., for hardware wallet integration).
47///
48/// Key functionality provided by the SDK includes:
49///
50/// - **Initialization:** Create and set up a new wallet instance
51/// - **Deposits:** Generate deposit addresses and deposit trees
52/// - **Transfers:** Send funds to other Spark users or Bitcoin addresses
53/// - **Lightning:** Make and receive Lightning Network payments
54/// - **Leaves:** Manage individual UTXOs within the wallet
55/// - **Swaps:** Swap funds between different payment channels
56/// - **Timelocks:** Manage timelock conditions for funds
57/// - **Fees:** Estimate and manage transaction fees
58///
59/// # Examples
60///
61/// ```
62/// use spark_rust::{
63/// error::SparkSdkError,
64/// signer::default_signer::DefaultSigner,
65/// signer::traits::SparkSigner,
66/// SparkNetwork, SparkSdk,
67/// };
68/// use std::sync::Arc;
69///
70/// async fn example() -> Result<(), SparkSdkError> {
71/// // Initialize with a mnemonic phrase and network
72/// let mnemonic = "abandon ability able about above absent absorb abstract absurd abuse access accident";
73/// let network = SparkNetwork::Regtest;
74///
75/// // Create the signer
76/// let signer = DefaultSigner::from_mnemonic(mnemonic, network.clone()).await?;
77///
78/// // Initialize the SDK
79/// let sdk = SparkSdk::new(network, signer).await?;
80///
81/// // Get wallet information
82/// let address = sdk.get_spark_address()?;
83/// println!("Spark address: {}", hex::encode(address.serialize()));
84///
85/// // Use other SDK functionality...
86///
87/// Ok(())
88/// }
89/// ```
90///
91/// # Security Considerations
92///
93/// The Spark SDK architecture implements security through several layers:
94///
95/// ## SDK Architecture Security
96/// - Separation of concerns: The SDK delegates all key operations to the signer component
97/// - Secure API communication with Spark operators using authenticated sessions
98/// - Protocol-level validation of all operator responses
99/// - Thread-safe access to shared resources
100///
101/// ## Signer Security (using DefaultSigner)
102/// - BIP39 mnemonic-based key generation with proper entropy
103/// - BIP32/BIP44 compliant hierarchical deterministic key derivation
104/// - Secure storage of private keys with optional encryption
105/// - Explicit methods for sensitive operations with clear security warnings
106///
107/// ## Spark Protocol Security
108/// - Threshold signature schemes (FROST) requiring multiple parties to sign transactions
109/// - Defense in depth through multiple security mechanisms
110/// - Timelocked refund transactions as safety guarantees
111/// - Verifiable cryptographic proofs for key operations
112///
113/// Note: This is an early version of the SDK, and future updates will further enhance
114/// isolation and security properties.
115#[derive(Clone)]
116pub struct SparkSdk<S: SparkSigner + Send + Sync = DefaultSigner> {
117 /// Wallet configuration including network settings and session information
118 pub(crate) config: WalletConfig,
119
120 /// Cryptographic signer that manages private keys and signing operations
121 pub(crate) signer: Arc<S>,
122
123 /// Manager for wallet leaves (UTXOs)
124 pub(crate) leaf_manager: Arc<LeafManager>,
125
126 /// Global lock for handler operations
127 pub(crate) handler_lock: Arc<tokio::sync::Mutex<()>>,
128}
129
130impl<S: SparkSigner + Send + Sync + Clone + 'static> SparkSdk<S> {
131 /// Acquires the global handler lock to ensure exclusive access to all leaves during a handler operation.
132 ///
133 /// This method returns a guard that will automatically release the lock when it's dropped.
134 /// If the handler code panics or returns early, the lock will still be released.
135 ///
136 /// # Returns
137 /// A MutexGuard that will release the lock when dropped
138 pub(crate) async fn acquire_handler_lock(&self) -> MutexGuard<'_, ()> {
139 self.handler_lock.lock().await
140 }
141}