Skip to main content

breez_sdk_spark/sdk/
mod.rs

1mod api;
2mod bridging;
3mod buy;
4mod chain_queries;
5mod contacts;
6mod deposits;
7pub(crate) mod exit_chain_downloader;
8mod helpers;
9mod init;
10mod lightning_address;
11mod lightning_sender;
12mod lnurl;
13mod payments;
14mod recover_funds;
15mod runtime;
16mod sync;
17mod sync_coordinator;
18mod token_allowances;
19mod unilateral_exit;
20mod unilateral_exit_backup;
21mod watchtower_exit;
22
23pub use bridging::{
24    BridgeAmountSide, BridgeRoutePair, BridgeRoutePairSide, BridgeStatus, BridgingClient,
25    BridgingConfig, CreateBridgeRequest, CreateBridgeResponse, GetBridgeRoutesRequest,
26    GetBridgeRoutesResponse, GetBridgeStatusRequest, GetBridgeStatusResponse,
27    default_bridging_config, new_bridging_client,
28};
29pub(crate) use helpers::partner_id;
30pub(crate) use lightning_sender::{LightningSender, PendingLightningSend};
31pub(crate) use runtime::{RuntimeEvent, SdkRuntime, runtime_from_config};
32pub(crate) use sync_coordinator::SyncCoordinator;
33
34use bitflags::bitflags;
35use breez_sdk_common::{buy::moonpay::MoonpayProvider, fiat::FiatService};
36use platform_utils::HttpClient;
37use platform_utils::tokio;
38use spark_wallet::SparkWallet;
39use std::sync::Arc;
40use tokio::sync::{Mutex, OnceCell, oneshot, watch};
41
42use crate::{
43    BitcoinChainService, LeafOptimizationConfig, Logger, Network, SyncError,
44    TokenOptimizationConfig, error::SdkError, events::EventEmitter, lnurl::LnurlServerClient,
45    logger, models::Config, models::SparkConfig, persist::Storage, rewards::RewardsDelegator,
46    signer::lnurl_auth::LnurlAuthSignerAdapter, stable_balance::StableBalance,
47    token_conversion::TokenConverter,
48};
49
50#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
51const BREEZ_SYNC_SERVICE_URL: &str = "https://datasync.breez.technology";
52
53#[cfg(all(target_family = "wasm", target_os = "unknown"))]
54const BREEZ_SYNC_SERVICE_URL: &str = "https://datasync.breez.technology:442";
55
56pub(crate) const CLAIM_TX_SIZE_VBYTES: u64 = 99;
57pub(crate) const SYNC_PAGING_LIMIT: u32 = 100;
58
59bitflags! {
60    #[derive(Clone, Debug, PartialEq, Eq)]
61    pub(crate) struct SyncType: u32 {
62        const Wallet = 1 << 0;
63        const WalletState = 1 << 1;
64        const Deposits = 1 << 2;
65        const LnurlMetadata = 1 << 3;
66        const ExitChainState = 1 << 4;
67        const Full = Self::Wallet.0.0
68            | Self::WalletState.0.0
69            | Self::Deposits.0.0
70            | Self::LnurlMetadata.0.0
71            | Self::ExitChainState.0.0;
72    }
73}
74
75#[derive(Clone, Debug)]
76pub(crate) struct SyncRequest {
77    pub(crate) sync_type: SyncType,
78    #[allow(clippy::type_complexity)]
79    pub(crate) reply: Arc<Mutex<Option<oneshot::Sender<Result<(), SdkError>>>>>,
80    /// If true, bypass the "recently synced" check and sync immediately.
81    /// Use for event-driven syncs (after payments, transfers, etc.) that should happen immediately.
82    pub(crate) force: bool,
83}
84
85impl SyncRequest {
86    pub(crate) async fn reply(&self, error: Option<SdkError>) {
87        if let Some(reply) = self.reply.lock().await.take() {
88            let _ = match error {
89                Some(e) => reply.send(Err(e)),
90                None => reply.send(Ok(())),
91            };
92        }
93    }
94}
95
96/// `BreezSDK` is a wrapper around `SparkSDK` that provides a more structured API
97/// with request/response objects and comprehensive error handling.
98#[derive(Clone)]
99#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
100pub struct BreezSdk {
101    /// The wallet's identity public key, which tags the instance's log lines.
102    pub(crate) instance_id: String,
103    pub(crate) config: Config,
104    pub(crate) spark_wallet: Arc<SparkWallet>,
105    pub(crate) storage: Arc<dyn Storage>,
106    pub(crate) chain_service: Arc<dyn BitcoinChainService>,
107    pub(crate) fiat_service: Arc<dyn FiatService>,
108    pub(crate) lnurl_client: Arc<dyn HttpClient>,
109    pub(crate) lnurl_server_client: Option<Arc<dyn LnurlServerClient>>,
110    pub(crate) lnurl_auth_signer: Option<Arc<LnurlAuthSignerAdapter>>,
111    pub(crate) event_emitter: Arc<EventEmitter>,
112    pub(crate) shutdown_sender: watch::Sender<()>,
113    /// Wakes the exit chain downloader once an operation has changed the leaf
114    /// set. Held even when collection is off, so nothing has to branch on it.
115    pub(crate) exit_chain_trigger: exit_chain_downloader::ExitChainTrigger,
116    pub(crate) runtime: SdkRuntime,
117    /// Coordinator for coalescing duplicate sync requests
118    pub(crate) sync_coordinator: SyncCoordinator,
119    /// Serialises claim attempts on the same deposit across the sync cascade
120    /// and explicit `claim_deposit` calls.
121    pub(crate) claim_guards: deposits::ClaimGuards,
122    pub(crate) initial_synced_watcher: watch::Receiver<bool>,
123    /// The latest wallet sync's failure, cleared when one succeeds.
124    pub(crate) last_sync_error: Arc<Mutex<Option<SyncError>>>,
125    /// Parses payment inputs over the SDK's own transports, so lightning-address
126    /// and LNURL lookups honour the proxy and ride the redirect-validating
127    /// LNURL client (their hosts are chosen by remote parties).
128    pub(crate) input_parser: Arc<SdkInputParser>,
129    pub(crate) spark_private_mode_initialized: Arc<OnceCell<()>>,
130    pub(crate) token_converter: Arc<dyn TokenConverter>,
131    /// Set on mainnet only.
132    pub(crate) rewards_delegator: Option<Arc<RewardsDelegator>>,
133    pub(crate) stable_balance: Option<Arc<StableBalance>>,
134    pub(crate) buy_bitcoin_provider: Arc<MoonpayProvider>,
135    pub(crate) cross_chain_context: crate::cross_chain::CrossChainContext,
136    /// The wallet-backed Orchestra service, built whether or not cross-chain
137    /// payments are enabled. Set on mainnet with background tasks on.
138    pub(crate) orchestra: Option<Arc<crate::cross_chain::OrchestraService>>,
139    /// Shared helper for paying LN invoices and persisting the resulting
140    /// payment rows. Reused by cross-chain providers (e.g. Boltz) that
141    /// need to pay an LN invoice as part of a larger flow.
142    #[allow(dead_code)]
143    pub(crate) lightning_sender: Arc<LightningSender>,
144}
145
146/// The parser bound to the SDK's shared HTTP client and its DNS resolver.
147pub(crate) type SdkInputParser =
148    breez_sdk_common::input::InputParser<Arc<dyn HttpClient>, breez_sdk_common::dns::Resolver>;
149
150pub(crate) struct BreezSdkParams {
151    pub instance_id: String,
152    pub config: Config,
153    pub input_parser: Arc<SdkInputParser>,
154    pub storage: Arc<dyn Storage>,
155    pub chain_service: Arc<dyn BitcoinChainService>,
156    pub fiat_service: Arc<dyn FiatService>,
157    pub lnurl_client: Arc<dyn HttpClient>,
158    pub lnurl_server_client: Option<Arc<dyn LnurlServerClient>>,
159    pub lnurl_auth_signer: Option<Arc<LnurlAuthSignerAdapter>>,
160    pub shutdown_sender: watch::Sender<()>,
161    pub runtime: SdkRuntime,
162    pub spark_wallet: Arc<SparkWallet>,
163    pub event_emitter: Arc<EventEmitter>,
164    pub buy_bitcoin_provider: Arc<MoonpayProvider>,
165    pub token_converter: Arc<dyn TokenConverter>,
166    pub rewards_delegator: Option<Arc<RewardsDelegator>>,
167    pub stable_balance: Option<Arc<StableBalance>>,
168    pub sync_coordinator: SyncCoordinator,
169    pub cross_chain_context: crate::cross_chain::CrossChainContext,
170    pub orchestra: Option<Arc<crate::cross_chain::OrchestraService>>,
171    pub lightning_sender: Arc<LightningSender>,
172}
173
174#[allow(clippy::needless_pass_by_value)]
175#[cfg_attr(feature = "uniffi", uniffi::export)]
176pub fn init_logging(
177    log_dir: Option<String>,
178    app_logger: Option<Box<dyn Logger>>,
179    log_filter: Option<String>,
180) -> Result<(), SdkError> {
181    logger::init_logging(log_dir.as_deref(), app_logger, log_filter.as_deref())
182}
183
184/// Connects to the Spark network using the provided configuration and mnemonic.
185///
186/// # Arguments
187///
188/// * `request` - The connection request object
189///
190/// # Returns
191///
192/// Result containing either the initialized `BreezSdk` or an `SdkError`
193#[cfg(feature = "sqlite")]
194#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
195pub async fn connect(request: crate::ConnectRequest) -> Result<BreezSdk, SdkError> {
196    let builder = super::sdk_builder::SdkBuilder::new(request.config, request.seed)
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 an external signer.
203///
204/// This method allows using a custom signer implementation instead of providing
205/// a seed directly.
206///
207/// # Arguments
208///
209/// * `request` - The connection request object with external signer
210///
211/// # Returns
212///
213/// Result containing either the initialized `BreezSdk` or an `SdkError`
214#[cfg(feature = "sqlite")]
215#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
216pub async fn connect_with_signer(
217    request: crate::ConnectWithSignerRequest,
218) -> Result<BreezSdk, SdkError> {
219    let builder = super::sdk_builder::SdkBuilder::new_with_signer(
220        request.config,
221        request.breez_signer,
222        request.spark_signer,
223    )
224    .with_default_storage(request.storage_dir);
225    let sdk = builder.build().await?;
226    Ok(sdk)
227}
228
229/// Connects to the Spark network using a signing-only external signer.
230///
231/// Use this instead of [`connect_with_signer`] for a signer that can't perform
232/// the SDK's local ECIES/HMAC operations (for example a policy-restricted
233/// enclave). The SDK keeps session tokens in plaintext and disables the features
234/// that rely on ECIES/HMAC.
235///
236/// # Arguments
237///
238/// * `request` - The connection request object with a signing-only external signer
239///
240/// # Returns
241///
242/// Result containing either the initialized `BreezSdk` or an `SdkError`
243#[cfg(feature = "sqlite")]
244#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
245pub async fn connect_with_signing_only_signer(
246    request: crate::ConnectWithSigningOnlySignerRequest,
247) -> Result<BreezSdk, SdkError> {
248    let builder = super::sdk_builder::SdkBuilder::new_with_signing_only_signer(
249        request.config,
250        request.breez_signer,
251        request.spark_signer,
252    )
253    .with_default_storage(request.storage_dir);
254    let sdk = builder.build().await?;
255    Ok(sdk)
256}
257
258/// Reads a [`SparkConfig`] from JSON, for a deployment that publishes its
259/// operators, service provider and certificates as a file. Set it on
260/// [`Config::spark_config`] to connect a wallet to that deployment.
261#[cfg_attr(feature = "uniffi", uniffi::export)]
262// The bindings pass an owned string.
263#[allow(clippy::needless_pass_by_value)]
264pub fn parse_spark_config(json: String) -> Result<SparkConfig, SdkError> {
265    serde_json::from_str(&json).map_err(|e| SdkError::InvalidInput(e.to_string()))
266}
267
268#[cfg_attr(feature = "uniffi", uniffi::export)]
269pub fn default_config(network: Network) -> Config {
270    let lnurl_domain = match network {
271        Network::Mainnet => Some("breez.tips".to_string()),
272        Network::Signet | Network::Regtest => None,
273    };
274    Config {
275        api_key: None,
276        network,
277        sync_interval_secs: 60, // every 1 minute
278        max_deposit_claim_fee: Some(crate::MaxFee {
279            onchain: crate::MaxOnchainFee::Rate { sat_per_vbyte: 1 },
280            proportional_ppm: Some(1_000),
281        }),
282        lnurl_domain,
283        prefer_spark_over_lightning: false,
284        exit_chain_auto_fetch_enabled: true,
285        watchtower_fee_ladder_enabled: None,
286        external_input_parsers: None,
287        use_default_external_input_parsers: true,
288        real_time_sync_server_url: Some(BREEZ_SYNC_SERVICE_URL.to_string()),
289        private_enabled_default: true,
290        leaf_optimization_config: LeafOptimizationConfig {
291            auto_enabled: true,
292            multiplicity: 1,
293        },
294        token_optimization_config: TokenOptimizationConfig {
295            auto_enabled: true,
296            target_output_count: 5,
297            min_outputs_threshold: 50,
298        },
299        stable_balance_config: None,
300        max_concurrent_claims: 4,
301        spark_config: match network {
302            Network::Mainnet | Network::Regtest => Some(default_spark_config(network)),
303            Network::Signet => None,
304        },
305        background_tasks_enabled: true,
306        proxy: None,
307        cross_chain_config: None,
308    }
309}
310
311/// Builds a [`Config`] suitable for multi-tenant server-mode deployments.
312///
313/// This preset returns the same configuration as [`default_config`] with
314/// [`background_tasks_enabled`](Config::background_tasks_enabled) set to
315/// `false`. In server mode, the SDK is treated as a library: the host
316/// orchestrates sync, claiming, and event delivery (typically via webhooks)
317/// explicitly, so an ephemeral SDK instance stays cheap and predictable.
318///
319/// Config fields whose background services are gated off are reset to their
320/// inactive shape: `real_time_sync_server_url` and `cross_chain_config` are
321/// set to `None`, and both `leaf_optimization_config.auto_enabled` and
322/// `token_optimization_config.auto_enabled` are set to `false`. The SDK
323/// rejects builds where `background_tasks_enabled` is `false` and any of
324/// those fields is left in its active shape, so flip the flag via this
325/// helper rather than by hand.
326///
327/// Explicit operations (`sync_wallet`, `claim_deposit`,
328/// `list_unclaimed_deposits`, `refund_deposit`,
329/// `refund_pending_conversions`, etc.) continue to work and are the intended
330/// entry points in this mode.
331///
332/// Stable Balance is not supported in this mode because its conversion worker
333/// is a background service.
334///
335/// One-time setup that the SDK normally applies automatically — notably
336/// `private_enabled_default` — is NOT applied in this mode. Drive setup
337/// explicitly via `update_user_settings` (and any other relevant APIs) so
338/// ephemeral per-request SDK instances incur no implicit setup overhead.
339///
340/// `get_info` reads balance directly from the spark wallet in this mode
341/// rather than from the background-maintained storage cache, so balance
342/// reflects the latest local sync and `ensure_synced=true` is rejected with
343/// an invalid-input error
344#[cfg_attr(feature = "uniffi", uniffi::export)]
345pub fn default_server_config(network: Network) -> Config {
346    let mut config = default_config(network);
347    config.background_tasks_enabled = false;
348    config.real_time_sync_server_url = None;
349    config.leaf_optimization_config.auto_enabled = false;
350    config.token_optimization_config.auto_enabled = false;
351    config.cross_chain_config = None;
352    config
353}
354
355/// Builds the default [`SparkConfig`](crate::models::SparkConfig) for the given network.
356///
357/// Surfaced through [`default_config`] as `Config::spark_config` so callers can read the
358/// baked-in operator and SSP endpoints and selectively override individual fields (e.g. to
359/// point at a staging environment) before passing the [`Config`] to [`connect`].
360fn default_spark_config(network: Network) -> crate::models::SparkConfig {
361    use crate::models::{SparkSigningOperator, SparkSspConfig};
362
363    let wallet_config = spark_wallet::SparkWalletConfig::default_config(network.into());
364
365    let coordinator_identifier = hex::encode(
366        wallet_config
367            .operator_pool
368            .get_coordinator()
369            .identifier
370            .serialize(),
371    );
372
373    let signing_operators = wallet_config
374        .operator_pool
375        .get_all_operators()
376        .map(|op| SparkSigningOperator {
377            id: u32::try_from(op.id).expect("operator id fits in u32"),
378            identifier: hex::encode(op.identifier.serialize()),
379            address: op.address.clone(),
380            identity_public_key: hex::encode(op.identity_public_key.serialize()),
381            ca_cert_pem: op
382                .ca_cert
383                .as_ref()
384                .and_then(|b| String::from_utf8(b.clone()).ok()),
385        })
386        .collect();
387
388    let ssp = &wallet_config.service_provider_config;
389
390    crate::models::SparkConfig {
391        coordinator_identifier,
392        threshold: wallet_config.split_secret_threshold,
393        signing_operators,
394        ssp_config: SparkSspConfig {
395            base_url: ssp.base_url.clone(),
396            identity_public_key: hex::encode(ssp.identity_public_key.serialize()),
397            schema_endpoint: ssp.schema_endpoint.clone(),
398        },
399        expected_withdraw_bond_sats: wallet_config.tokens_config.expected_withdraw_bond_sats,
400        expected_withdraw_relative_block_locktime: wallet_config
401            .tokens_config
402            .expected_withdraw_relative_block_locktime,
403        max_token_transaction_inputs: None,
404    }
405}
406
407/// The two default external signers created from one mnemonic by
408/// [`default_external_signers`].
409#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
410pub struct ExternalSigners {
411    /// External signer for non-Spark SDK signing (LNURL-auth, sync, message
412    /// signing, ECIES).
413    pub breez_signer: Arc<dyn crate::signer::ExternalBreezSigner>,
414    /// External high-level Spark signer for the Spark wallet flows.
415    pub spark_signer: Arc<dyn crate::signer::ExternalSparkSigner>,
416}
417
418/// A signing-only external signer paired with the Spark signer, for wallets that
419/// connect via [`connect_with_signing_only_signer`]. The Breez half performs
420/// signing only, without the SDK's local ECIES/HMAC operations.
421#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
422pub struct SigningOnlyExternalSigners {
423    /// Signing-only external signer for non-Spark SDK signing.
424    pub breez_signer: Arc<dyn crate::signer::ExternalSigningSigner>,
425    /// External high-level Spark signer for the Spark wallet flows.
426    pub spark_signer: Arc<dyn crate::signer::ExternalSparkSigner>,
427}
428
429/// Creates the default external signers from a mnemonic.
430///
431/// This is a convenience factory method for creating the two signer halves
432/// that can be passed to `connect_with_signer` or `SdkBuilder::new_with_signer`.
433/// Key derivation matches the seed-based connect path: an SDK built either way
434/// from the same mnemonic is the same wallet.
435///
436/// # Arguments
437///
438/// * `mnemonic` - BIP39 mnemonic phrase (12 or 24 words)
439/// * `passphrase` - Optional passphrase for the mnemonic
440/// * `network` - Network to use (Mainnet, Signet, or Regtest)
441/// * `account_number` - Account number in the derivation path. Unset uses the
442///   network default: 0 on Regtest and Signet, 1 on Mainnet.
443#[cfg_attr(feature = "uniffi", uniffi::export)]
444pub fn default_external_signers(
445    mnemonic: String,
446    passphrase: Option<String>,
447    network: Network,
448    account_number: Option<u32>,
449) -> Result<ExternalSigners, SdkError> {
450    use crate::signer::{DefaultExternalSigner, DefaultExternalSparkSigner};
451
452    let breez_signer = DefaultExternalSigner::new(
453        mnemonic.clone(),
454        passphrase.clone(),
455        network,
456        account_number,
457    )?;
458    let spark_signer =
459        DefaultExternalSparkSigner::new(mnemonic, passphrase, network, account_number)?;
460
461    Ok(ExternalSigners {
462        breez_signer: Arc::new(breez_signer),
463        spark_signer: Arc::new(spark_signer),
464    })
465}
466
467/// Options for [`get_spark_status`].
468#[derive(Debug, Clone, Default)]
469#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
470pub struct GetSparkStatusRequest {
471    /// Routes the status request through a SOCKS5 proxy. Pass the same value as
472    /// [`Config::proxy`]: this call runs without an SDK instance, so it cannot
473    /// pick the setting up on its own.
474    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
475    pub proxy: Option<crate::ProxyConfig>,
476}
477
478/// Fetches the current status of Spark network services relevant to the SDK.
479///
480/// This function queries the Spark status API and returns the worst status
481/// across the Spark Operators and SSP services.
482#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
483pub async fn get_spark_status(
484    request: GetSparkStatusRequest,
485) -> Result<crate::SparkStatus, SdkError> {
486    use chrono::DateTime;
487
488    #[derive(serde::Deserialize)]
489    struct StatusApiResponse {
490        services: Vec<StatusApiService>,
491        #[serde(rename = "lastUpdated")]
492        last_updated: String,
493    }
494
495    #[derive(serde::Deserialize)]
496    struct StatusApiService {
497        name: String,
498        status: String,
499    }
500
501    fn parse_service_status(s: &str) -> crate::ServiceStatus {
502        match s {
503            "operational" => crate::ServiceStatus::Operational,
504            "degraded" => crate::ServiceStatus::Degraded,
505            "partial" => crate::ServiceStatus::Partial,
506            "major" => crate::ServiceStatus::Major,
507            _ => {
508                tracing::warn!("Unknown service status: {s}");
509                crate::ServiceStatus::Unknown
510            }
511        }
512    }
513
514    let http_client = crate::ProxyConfig::http_client(request.proxy.as_ref(), None)?;
515
516    let response = http_client
517        .get("https://spark.money/api/v1/status".to_string(), None)
518        .await
519        .map_err(|e| SdkError::NetworkError(e.to_string()))?;
520
521    let api_response: StatusApiResponse = response
522        .json()
523        .map_err(|e| SdkError::Generic(format!("Failed to parse status response: {e}")))?;
524
525    let status = api_response
526        .services
527        .iter()
528        .filter(|s| s.name == "Spark Operators" || s.name == "SSP")
529        .map(|s| parse_service_status(&s.status))
530        .max()
531        .unwrap_or(crate::ServiceStatus::Unknown);
532
533    let last_updated = DateTime::parse_from_rfc3339(&api_response.last_updated)
534        .map(|dt| dt.timestamp().cast_unsigned())
535        .map_err(|e| SdkError::Generic(format!("Failed to parse lastUpdated timestamp: {e}")))?;
536
537    Ok(crate::SparkStatus {
538        status,
539        last_updated,
540    })
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546
547    #[test]
548    fn default_server_config_disables_background_tasks() {
549        for network in [Network::Mainnet, Network::Regtest, Network::Signet] {
550            let cfg = default_server_config(network);
551            assert!(!cfg.background_tasks_enabled);
552            assert!(cfg.real_time_sync_server_url.is_none());
553            assert!(!cfg.leaf_optimization_config.auto_enabled);
554            assert!(!cfg.token_optimization_config.auto_enabled);
555        }
556    }
557
558    #[test]
559    fn default_config_enables_background_tasks() {
560        assert!(default_config(Network::Mainnet).background_tasks_enabled);
561        assert!(default_config(Network::Regtest).background_tasks_enabled);
562        assert!(default_config(Network::Signet).background_tasks_enabled);
563    }
564
565    /// The shape a local environment writes, which a wallet loads as it is.
566    #[test]
567    fn parse_spark_config_reads_an_environments_file() {
568        let json = r#"{
569          "coordinator_identifier": "01",
570          "threshold": 2,
571          "signing_operators": [
572            {
573              "id": 0,
574              "identifier": "01",
575              "address": "http://127.0.0.1:8535",
576              "identity_public_key": "02aa"
577            }
578          ],
579          "ssp_config": {
580            "base_url": "http://127.0.0.1:59049",
581            "identity_public_key": "03bb",
582            "schema_endpoint": "graphql/spark/rc"
583          },
584          "expected_withdraw_bond_sats": 10000,
585          "expected_withdraw_relative_block_locktime": 1000
586        }"#;
587
588        let config = parse_spark_config(json.to_string()).unwrap();
589
590        assert_eq!(config.threshold, 2);
591        assert_eq!(config.signing_operators.len(), 1);
592        assert_eq!(config.signing_operators[0].address, "http://127.0.0.1:8535");
593        assert_eq!(config.ssp_config.base_url, "http://127.0.0.1:59049");
594        // Absent from the file, and not required of it.
595        assert!(config.signing_operators[0].ca_cert_pem.is_none());
596        assert!(config.max_token_transaction_inputs.is_none());
597    }
598
599    #[test]
600    fn parse_spark_config_rejects_what_is_not_one() {
601        assert!(parse_spark_config("{}".to_string()).is_err());
602    }
603
604    /// Whether an impl block's body declares a public method taking `self`.
605    fn has_public_method(body: &[&str]) -> bool {
606        let next_lines = body.iter().skip(1).map(Some).chain(std::iter::once(None));
607        body.iter().zip(next_lines).any(|(line, next)| {
608            let Some(signature) = line.strip_prefix("    pub ") else {
609                return false;
610            };
611            if !signature.starts_with("fn ") && !signature.starts_with("async fn ") {
612                return false;
613            }
614            // The receiver is on the signature's first line or right after it.
615            line.contains("self") || next.is_some_and(|next| next.contains("self"))
616        })
617    }
618
619    fn rust_files(dir: &std::path::Path, files: &mut Vec<std::path::PathBuf>) {
620        for entry in std::fs::read_dir(dir).unwrap() {
621            let path = entry.unwrap().path();
622            if path.is_dir() {
623                rust_files(&path, files);
624            } else if path.extension().is_some_and(|ext| ext == "rs") {
625                files.push(path);
626            }
627        }
628    }
629
630    /// Public `BreezSdk` methods log in their instance's span only through
631    /// `#[macros::instance_span]` on their impl block, which is easy to forget
632    /// on a new one.
633    #[test]
634    fn impl_blocks_with_public_methods_have_an_instance_span() {
635        let mut files = Vec::new();
636        rust_files(
637            &std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"),
638            &mut files,
639        );
640        let mut missing = Vec::new();
641        for path in files {
642            let source = std::fs::read_to_string(&path).unwrap();
643            let lines: Vec<&str> = source.lines().collect();
644            for (i, line) in lines.iter().enumerate() {
645                if !line.starts_with("impl BreezSdk") {
646                    continue;
647                }
648                let body: Vec<&str> = lines[i..]
649                    .iter()
650                    .skip(1)
651                    .copied()
652                    .take_while(|l| *l != "}")
653                    .collect();
654                if !has_public_method(&body) {
655                    continue;
656                }
657                let has_attribute = lines[..i]
658                    .iter()
659                    .rev()
660                    .take_while(|l| l.starts_with("#[") || l.starts_with("///"))
661                    .any(|l| *l == "#[macros::instance_span]");
662                if !has_attribute {
663                    missing.push(format!("{}:{}", path.display(), i.saturating_add(1)));
664                }
665            }
666        }
667        assert!(
668            missing.is_empty(),
669            "impl blocks missing #[macros::instance_span]: {missing:?}"
670        );
671    }
672}