Skip to main content

breez_sdk_spark/sdk/
mod.rs

1mod api;
2mod contacts;
3mod deposits;
4pub(crate) mod exit_chain_downloader;
5mod helpers;
6mod init;
7mod lightning_address;
8mod lightning_sender;
9mod lnurl;
10mod payments;
11mod runtime;
12mod sync;
13mod sync_coordinator;
14mod unilateral_exit;
15mod unilateral_exit_backup;
16
17pub(crate) use lightning_sender::LightningSender;
18pub(crate) use runtime::{RuntimeEvent, SdkRuntime, runtime_from_config};
19pub(crate) use sync_coordinator::SyncCoordinator;
20
21use bitflags::bitflags;
22use breez_sdk_common::{buy::moonpay::MoonpayProvider, fiat::FiatService};
23use platform_utils::HttpClient;
24use platform_utils::tokio;
25use spark_wallet::SparkWallet;
26use std::sync::Arc;
27use tokio::sync::{Mutex, OnceCell, oneshot, watch};
28
29use crate::{
30    BitcoinChainService, ExternalInputParser, InputType, LeafOptimizationConfig, Logger, Network,
31    TokenOptimizationConfig, error::SdkError, events::EventEmitter, lnurl::LnurlServerClient,
32    logger, models::Config, persist::Storage, signer::lnurl_auth::LnurlAuthSignerAdapter,
33    stable_balance::StableBalance, token_conversion::TokenConverter,
34};
35
36#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
37const BREEZ_SYNC_SERVICE_URL: &str = "https://datasync.breez.technology";
38
39#[cfg(all(target_family = "wasm", target_os = "unknown"))]
40const BREEZ_SYNC_SERVICE_URL: &str = "https://datasync.breez.technology:442";
41
42pub(crate) const CLAIM_TX_SIZE_VBYTES: u64 = 99;
43pub(crate) const SYNC_PAGING_LIMIT: u32 = 100;
44
45bitflags! {
46    #[derive(Clone, Debug, PartialEq, Eq)]
47    pub(crate) struct SyncType: u32 {
48        const Wallet = 1 << 0;
49        const WalletState = 1 << 1;
50        const Deposits = 1 << 2;
51        const LnurlMetadata = 1 << 3;
52        const Full = Self::Wallet.0.0
53            | Self::WalletState.0.0
54            | Self::Deposits.0.0
55            | Self::LnurlMetadata.0.0;
56    }
57}
58
59#[derive(Clone, Debug)]
60pub(crate) struct SyncRequest {
61    pub(crate) sync_type: SyncType,
62    #[allow(clippy::type_complexity)]
63    pub(crate) reply: Arc<Mutex<Option<oneshot::Sender<Result<(), SdkError>>>>>,
64    /// If true, bypass the "recently synced" check and sync immediately.
65    /// Use for event-driven syncs (after payments, transfers, etc.) that should happen immediately.
66    pub(crate) force: bool,
67}
68
69impl SyncRequest {
70    pub(crate) async fn reply(&self, error: Option<SdkError>) {
71        if let Some(reply) = self.reply.lock().await.take() {
72            let _ = match error {
73                Some(e) => reply.send(Err(e)),
74                None => reply.send(Ok(())),
75            };
76        }
77    }
78}
79
80/// `BreezSDK` is a wrapper around `SparkSDK` that provides a more structured API
81/// with request/response objects and comprehensive error handling.
82#[derive(Clone)]
83#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
84pub struct BreezSdk {
85    pub(crate) config: Config,
86    pub(crate) spark_wallet: Arc<SparkWallet>,
87    pub(crate) storage: Arc<dyn Storage>,
88    pub(crate) chain_service: Arc<dyn BitcoinChainService>,
89    pub(crate) fiat_service: Arc<dyn FiatService>,
90    pub(crate) lnurl_client: Arc<dyn HttpClient>,
91    pub(crate) lnurl_server_client: Option<Arc<dyn LnurlServerClient>>,
92    pub(crate) lnurl_auth_signer: Option<Arc<LnurlAuthSignerAdapter>>,
93    pub(crate) event_emitter: Arc<EventEmitter>,
94    pub(crate) shutdown_sender: watch::Sender<()>,
95    /// Wakes the exit chain downloader once an operation has changed the leaf
96    /// set. Held even when collection is off, so nothing has to branch on it.
97    pub(crate) exit_chain_trigger: exit_chain_downloader::ExitChainTrigger,
98    pub(crate) runtime: SdkRuntime,
99    /// Coordinator for coalescing duplicate sync requests
100    pub(crate) sync_coordinator: SyncCoordinator,
101    pub(crate) initial_synced_watcher: watch::Receiver<bool>,
102    pub(crate) external_input_parsers: Vec<ExternalInputParser>,
103    pub(crate) spark_private_mode_initialized: Arc<OnceCell<()>>,
104    pub(crate) token_converter: Arc<dyn TokenConverter>,
105    pub(crate) stable_balance: Option<Arc<StableBalance>>,
106    pub(crate) buy_bitcoin_provider: Arc<MoonpayProvider>,
107    pub(crate) cross_chain_context: crate::cross_chain::CrossChainContext,
108    /// Shared helper for paying LN invoices and persisting the resulting
109    /// payment rows. Reused by cross-chain providers (e.g. Boltz) that
110    /// need to pay an LN invoice as part of a larger flow.
111    #[allow(dead_code)]
112    pub(crate) lightning_sender: Arc<LightningSender>,
113}
114
115pub(crate) struct BreezSdkParams {
116    pub config: Config,
117    pub storage: Arc<dyn Storage>,
118    pub chain_service: Arc<dyn BitcoinChainService>,
119    pub fiat_service: Arc<dyn FiatService>,
120    pub lnurl_client: Arc<dyn HttpClient>,
121    pub lnurl_server_client: Option<Arc<dyn LnurlServerClient>>,
122    pub lnurl_auth_signer: Option<Arc<LnurlAuthSignerAdapter>>,
123    pub shutdown_sender: watch::Sender<()>,
124    pub runtime: SdkRuntime,
125    pub spark_wallet: Arc<SparkWallet>,
126    pub event_emitter: Arc<EventEmitter>,
127    pub buy_bitcoin_provider: Arc<MoonpayProvider>,
128    pub token_converter: Arc<dyn TokenConverter>,
129    pub stable_balance: Option<Arc<StableBalance>>,
130    pub sync_coordinator: SyncCoordinator,
131    pub cross_chain_context: crate::cross_chain::CrossChainContext,
132    pub lightning_sender: Arc<LightningSender>,
133}
134
135pub async fn parse_input(
136    input: &str,
137    external_input_parsers: Option<Vec<ExternalInputParser>>,
138) -> Result<InputType, SdkError> {
139    Ok(breez_sdk_common::input::parse(
140        input,
141        external_input_parsers.map(|parsers| parsers.into_iter().map(From::from).collect()),
142    )
143    .await?
144    .into())
145}
146
147#[allow(clippy::needless_pass_by_value)]
148#[cfg_attr(feature = "uniffi", uniffi::export)]
149pub fn init_logging(
150    log_dir: Option<String>,
151    app_logger: Option<Box<dyn Logger>>,
152    log_filter: Option<String>,
153) -> Result<(), SdkError> {
154    logger::init_logging(log_dir.as_deref(), app_logger, log_filter.as_deref())
155}
156
157/// Connects to the Spark network using the provided configuration and mnemonic.
158///
159/// # Arguments
160///
161/// * `request` - The connection request object
162///
163/// # Returns
164///
165/// Result containing either the initialized `BreezSdk` or an `SdkError`
166#[cfg(feature = "sqlite")]
167#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
168pub async fn connect(request: crate::ConnectRequest) -> Result<BreezSdk, SdkError> {
169    let builder = super::sdk_builder::SdkBuilder::new(request.config, request.seed)
170        .with_default_storage(request.storage_dir);
171    let sdk = builder.build().await?;
172    Ok(sdk)
173}
174
175/// Connects to the Spark network using an external signer.
176///
177/// This method allows using a custom signer implementation instead of providing
178/// a seed directly.
179///
180/// # Arguments
181///
182/// * `request` - The connection request object with external signer
183///
184/// # Returns
185///
186/// Result containing either the initialized `BreezSdk` or an `SdkError`
187#[cfg(feature = "sqlite")]
188#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
189pub async fn connect_with_signer(
190    request: crate::ConnectWithSignerRequest,
191) -> Result<BreezSdk, SdkError> {
192    let builder = super::sdk_builder::SdkBuilder::new_with_signer(
193        request.config,
194        request.breez_signer,
195        request.spark_signer,
196    )
197    .with_default_storage(request.storage_dir);
198    let sdk = builder.build().await?;
199    Ok(sdk)
200}
201
202/// Connects to the Spark network using a signing-only external signer.
203///
204/// Use this instead of [`connect_with_signer`] for a signer that can't perform
205/// the SDK's local ECIES/HMAC operations (for example a policy-restricted
206/// enclave). The SDK keeps session tokens in plaintext and disables the features
207/// that rely on ECIES/HMAC.
208///
209/// # Arguments
210///
211/// * `request` - The connection request object with a signing-only external signer
212///
213/// # Returns
214///
215/// Result containing either the initialized `BreezSdk` or an `SdkError`
216#[cfg(feature = "sqlite")]
217#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
218pub async fn connect_with_signing_only_signer(
219    request: crate::ConnectWithSigningOnlySignerRequest,
220) -> Result<BreezSdk, SdkError> {
221    let builder = super::sdk_builder::SdkBuilder::new_with_signing_only_signer(
222        request.config,
223        request.breez_signer,
224        request.spark_signer,
225    )
226    .with_default_storage(request.storage_dir);
227    let sdk = builder.build().await?;
228    Ok(sdk)
229}
230
231#[cfg_attr(feature = "uniffi", uniffi::export)]
232pub fn default_config(network: Network) -> Config {
233    let lnurl_domain = match network {
234        Network::Mainnet => Some("breez.tips".to_string()),
235        Network::Regtest => None,
236    };
237    Config {
238        api_key: None,
239        network,
240        sync_interval_secs: 60, // every 1 minute
241        max_deposit_claim_fee: Some(crate::MaxFee::Rate { sat_per_vbyte: 1 }),
242        max_instant_deposit_claim_fee_bps: None,
243        lnurl_domain,
244        prefer_spark_over_lightning: false,
245        exit_chain_auto_fetch_enabled: true,
246        external_input_parsers: None,
247        use_default_external_input_parsers: true,
248        real_time_sync_server_url: Some(BREEZ_SYNC_SERVICE_URL.to_string()),
249        private_enabled_default: true,
250        leaf_optimization_config: LeafOptimizationConfig {
251            auto_enabled: true,
252            multiplicity: 1,
253        },
254        token_optimization_config: TokenOptimizationConfig {
255            auto_enabled: true,
256            target_output_count: 5,
257            min_outputs_threshold: 50,
258        },
259        stable_balance_config: None,
260        max_concurrent_claims: 4,
261        spark_config: Some(default_spark_config(network)),
262        background_tasks_enabled: true,
263        cross_chain_config: None,
264    }
265}
266
267/// Builds a [`Config`] suitable for multi-tenant server-mode deployments.
268///
269/// This preset returns the same configuration as [`default_config`] with
270/// [`background_tasks_enabled`](Config::background_tasks_enabled) set to
271/// `false`. In server mode, the SDK is treated as a library: the host
272/// orchestrates sync, claiming, and event delivery (typically via webhooks)
273/// explicitly, so an ephemeral SDK instance stays cheap and predictable.
274///
275/// Config fields whose background services are gated off are reset to their
276/// inactive shape: `real_time_sync_server_url` and `cross_chain_config` are
277/// set to `None`, and both `leaf_optimization_config.auto_enabled` and
278/// `token_optimization_config.auto_enabled` are set to `false`. The SDK
279/// rejects builds where `background_tasks_enabled` is `false` and any of
280/// those fields is left in its active shape, so flip the flag via this
281/// helper rather than by hand.
282///
283/// Explicit operations (`sync_wallet`, `claim_deposit`,
284/// `list_unclaimed_deposits`, `refund_deposit`,
285/// `refund_pending_conversions`, etc.) continue to work and are the intended
286/// entry points in this mode.
287///
288/// Stable Balance is not supported in this mode because its conversion worker
289/// is a background service.
290///
291/// One-time setup that the SDK normally applies automatically — notably
292/// `private_enabled_default` — is NOT applied in this mode. Drive setup
293/// explicitly via `update_user_settings` (and any other relevant APIs) so
294/// ephemeral per-request SDK instances incur no implicit setup overhead.
295///
296/// `get_info` reads balance directly from the spark wallet in this mode
297/// rather than from the background-maintained storage cache, so balance
298/// reflects the latest local sync and `ensure_synced=true` is rejected with
299/// an invalid-input error
300#[cfg_attr(feature = "uniffi", uniffi::export)]
301pub fn default_server_config(network: Network) -> Config {
302    let mut config = default_config(network);
303    config.background_tasks_enabled = false;
304    config.real_time_sync_server_url = None;
305    config.leaf_optimization_config.auto_enabled = false;
306    config.token_optimization_config.auto_enabled = false;
307    config.cross_chain_config = None;
308    config
309}
310
311/// Builds the default [`SparkConfig`](crate::models::SparkConfig) for the given network.
312///
313/// Surfaced through [`default_config`] as `Config::spark_config` so callers can read the
314/// baked-in operator and SSP endpoints and selectively override individual fields (e.g. to
315/// point at a staging environment) before passing the [`Config`] to [`connect`].
316fn default_spark_config(network: Network) -> crate::models::SparkConfig {
317    use crate::models::{SparkSigningOperator, SparkSspConfig};
318
319    let wallet_config = spark_wallet::SparkWalletConfig::default_config(network.into());
320
321    let coordinator_identifier = hex::encode(
322        wallet_config
323            .operator_pool
324            .get_coordinator()
325            .identifier
326            .serialize(),
327    );
328
329    let signing_operators = wallet_config
330        .operator_pool
331        .get_all_operators()
332        .map(|op| SparkSigningOperator {
333            id: u32::try_from(op.id).expect("operator id fits in u32"),
334            identifier: hex::encode(op.identifier.serialize()),
335            address: op.address.clone(),
336            identity_public_key: hex::encode(op.identity_public_key.serialize()),
337            ca_cert_pem: op
338                .ca_cert
339                .as_ref()
340                .and_then(|b| String::from_utf8(b.clone()).ok()),
341        })
342        .collect();
343
344    let ssp = &wallet_config.service_provider_config;
345
346    crate::models::SparkConfig {
347        coordinator_identifier,
348        threshold: wallet_config.split_secret_threshold,
349        signing_operators,
350        ssp_config: SparkSspConfig {
351            base_url: ssp.base_url.clone(),
352            identity_public_key: hex::encode(ssp.identity_public_key.serialize()),
353            schema_endpoint: ssp.schema_endpoint.clone(),
354        },
355        expected_withdraw_bond_sats: wallet_config.tokens_config.expected_withdraw_bond_sats,
356        expected_withdraw_relative_block_locktime: wallet_config
357            .tokens_config
358            .expected_withdraw_relative_block_locktime,
359        max_token_transaction_inputs: None,
360    }
361}
362
363/// The two default external signers created from one mnemonic by
364/// [`default_external_signers`].
365#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
366pub struct ExternalSigners {
367    /// External signer for non-Spark SDK signing (LNURL-auth, sync, message
368    /// signing, ECIES).
369    pub breez_signer: Arc<dyn crate::signer::ExternalBreezSigner>,
370    /// External high-level Spark signer for the Spark wallet flows.
371    pub spark_signer: Arc<dyn crate::signer::ExternalSparkSigner>,
372}
373
374/// A signing-only external signer paired with the Spark signer, for wallets that
375/// connect via [`connect_with_signing_only_signer`]. The Breez half performs
376/// signing only, without the SDK's local ECIES/HMAC operations.
377#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
378pub struct SigningOnlyExternalSigners {
379    /// Signing-only external signer for non-Spark SDK signing.
380    pub breez_signer: Arc<dyn crate::signer::ExternalSigningSigner>,
381    /// External high-level Spark signer for the Spark wallet flows.
382    pub spark_signer: Arc<dyn crate::signer::ExternalSparkSigner>,
383}
384
385/// Creates the default external signers from a mnemonic.
386///
387/// This is a convenience factory method for creating the two signer halves
388/// that can be passed to `connect_with_signer` or `SdkBuilder::new_with_signer`.
389/// Key derivation matches the seed-based connect path: an SDK built either way
390/// from the same mnemonic is the same wallet.
391///
392/// # Arguments
393///
394/// * `mnemonic` - BIP39 mnemonic phrase (12 or 24 words)
395/// * `passphrase` - Optional passphrase for the mnemonic
396/// * `network` - Network to use (Mainnet or Regtest)
397/// * `account_number` - Account number in the derivation path. Unset uses the
398///   network default: 0 on Regtest, 1 on all other networks.
399#[cfg_attr(feature = "uniffi", uniffi::export)]
400pub fn default_external_signers(
401    mnemonic: String,
402    passphrase: Option<String>,
403    network: Network,
404    account_number: Option<u32>,
405) -> Result<ExternalSigners, SdkError> {
406    use crate::signer::{DefaultExternalSigner, DefaultExternalSparkSigner};
407
408    let breez_signer = DefaultExternalSigner::new(
409        mnemonic.clone(),
410        passphrase.clone(),
411        network,
412        account_number,
413    )?;
414    let spark_signer =
415        DefaultExternalSparkSigner::new(mnemonic, passphrase, network, account_number)?;
416
417    Ok(ExternalSigners {
418        breez_signer: Arc::new(breez_signer),
419        spark_signer: Arc::new(spark_signer),
420    })
421}
422
423/// Fetches the current status of Spark network services relevant to the SDK.
424///
425/// This function queries the Spark status API and returns the worst status
426/// across the Spark Operators and SSP services.
427#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
428pub async fn get_spark_status() -> Result<crate::SparkStatus, SdkError> {
429    use chrono::DateTime;
430    use platform_utils::DefaultHttpClient;
431
432    #[derive(serde::Deserialize)]
433    struct StatusApiResponse {
434        services: Vec<StatusApiService>,
435        #[serde(rename = "lastUpdated")]
436        last_updated: String,
437    }
438
439    #[derive(serde::Deserialize)]
440    struct StatusApiService {
441        name: String,
442        status: String,
443    }
444
445    fn parse_service_status(s: &str) -> crate::ServiceStatus {
446        match s {
447            "operational" => crate::ServiceStatus::Operational,
448            "degraded" => crate::ServiceStatus::Degraded,
449            "partial" => crate::ServiceStatus::Partial,
450            "major" => crate::ServiceStatus::Major,
451            _ => {
452                tracing::warn!("Unknown service status: {s}");
453                crate::ServiceStatus::Unknown
454            }
455        }
456    }
457
458    let http_client = DefaultHttpClient::default();
459
460    let response = http_client
461        .get("https://spark.money/api/v1/status".to_string(), None)
462        .await
463        .map_err(|e| SdkError::NetworkError(e.to_string()))?;
464
465    let api_response: StatusApiResponse = response
466        .json()
467        .map_err(|e| SdkError::Generic(format!("Failed to parse status response: {e}")))?;
468
469    let status = api_response
470        .services
471        .iter()
472        .filter(|s| s.name == "Spark Operators" || s.name == "SSP")
473        .map(|s| parse_service_status(&s.status))
474        .max()
475        .unwrap_or(crate::ServiceStatus::Unknown);
476
477    let last_updated = DateTime::parse_from_rfc3339(&api_response.last_updated)
478        .map(|dt| dt.timestamp().cast_unsigned())
479        .map_err(|e| SdkError::Generic(format!("Failed to parse lastUpdated timestamp: {e}")))?;
480
481    Ok(crate::SparkStatus {
482        status,
483        last_updated,
484    })
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490
491    #[test]
492    fn default_server_config_disables_background_tasks() {
493        for network in [Network::Mainnet, Network::Regtest] {
494            let cfg = default_server_config(network);
495            assert!(!cfg.background_tasks_enabled);
496            assert!(cfg.real_time_sync_server_url.is_none());
497            assert!(!cfg.leaf_optimization_config.auto_enabled);
498            assert!(!cfg.token_optimization_config.auto_enabled);
499        }
500    }
501
502    #[test]
503    fn default_config_enables_background_tasks() {
504        assert!(default_config(Network::Mainnet).background_tasks_enabled);
505        assert!(default_config(Network::Regtest).background_tasks_enabled);
506    }
507}