Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/daemon/api/balance.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::Arc;

use axum::Json;
use ldk_node::Node;
use mdk::client::MdkClient;

use crate::daemon::api::error::AppError;
use crate::daemon::types::GetBalanceResponse;
Expand All @@ -20,16 +20,26 @@ use crate::daemon::types::GetBalanceResponse;
/// can be zero even when the channel has a real outbound balance.
///
/// `onchain_balance_sat` is what the user can actually sweep/send on-chain right now.
pub async fn handle_get_balance(node: Arc<Node>) -> Result<Json<GetBalanceResponse>, AppError> {
///
/// `max_withdrawable_sat` is what `balance_sat` can pay out after subtracting
/// a routing-fee buffer (see [`mdk::max_sendable`]). `None` when no usable
/// LSP channel exists.
pub async fn handle_get_balance(
client: Arc<MdkClient>,
) -> Result<Json<GetBalanceResponse>, AppError> {
let node = client.node();
let balances = node.list_balances();
let lightning_sat: u64 = node
.list_channels()
.iter()
.map(|ch| ch.outbound_capacity_msat / 1000)
.sum();

let max_withdrawable_sat = client.max_sendable().ok().map(|e| e.amount_msat / 1000);

Ok(Json(GetBalanceResponse {
balance_sat: lightning_sat,
onchain_balance_sat: balances.spendable_onchain_balance_sats,
max_withdrawable_sat,
}))
}
2 changes: 1 addition & 1 deletion src/daemon/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ async fn get_info(State(state): State<AppState>) -> Result<Json<GetInfoResponse>
security(("basic_auth" = []))
)]
async fn get_balance(State(state): State<AppState>) -> Result<Json<GetBalanceResponse>, AppError> {
balance::handle_get_balance(state.node).await
balance::handle_get_balance(state.mdk_client).await
}

#[utoipa::path(
Expand Down
23 changes: 23 additions & 0 deletions src/daemon/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use ldk_node::bitcoin::Network;
use ldk_node::lightning::ln::msgs::SocketAddress;
use ldk_node::lightning::routing::gossip::NodeAlias;
use log::LevelFilter;
use mdk::max_sendable::MaxSendableConfig;
use mdk::node::ScoringOverrides;
use serde::Deserialize;

Expand All @@ -19,6 +20,7 @@ struct TomlConfig {
storage: Option<StorageSection>,
log: Option<LogSection>,
splice: Option<SpliceSection>,
max_sendable: Option<MaxSendableSection>,
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -90,6 +92,12 @@ struct SpliceSection {
poll_interval_secs: Option<u64>,
}

#[derive(Deserialize)]
struct MaxSendableSection {
fee_buffer_bps: Option<u16>,
fee_buffer_floor_sats: Option<u64>,
}

pub struct MdkConfig {
pub network: Network,
pub listening_addrs: Option<Vec<SocketAddress>>,
Expand All @@ -101,6 +109,7 @@ pub struct MdkConfig {
pub pathfinding_scores_source_url: Option<String>,
pub scoring_overrides: ScoringOverrides,
pub splice: SpliceConfig,
pub max_sendable: MaxSendableConfig,
}

pub fn load_config(path: &str) -> io::Result<MdkConfig> {
Expand Down Expand Up @@ -173,6 +182,19 @@ pub fn load_config(path: &str) -> io::Result<MdkConfig> {
None => SpliceConfig::default(),
};

let max_sendable = match toml.max_sendable {
Some(s) => {
let defaults = MaxSendableConfig::default();
MaxSendableConfig {
fee_buffer_bps: s.fee_buffer_bps.unwrap_or(defaults.fee_buffer_bps),
fee_buffer_floor_sats: s
.fee_buffer_floor_sats
.unwrap_or(defaults.fee_buffer_floor_sats),
}
}
None => MaxSendableConfig::default(),
};

Ok(MdkConfig {
network,
listening_addrs,
Expand All @@ -184,6 +206,7 @@ pub fn load_config(path: &str) -> io::Result<MdkConfig> {
pathfinding_scores_source_url: node.pathfinding_scores_source_url,
scoring_overrides,
splice,
max_sendable,
})
}

Expand Down
6 changes: 6 additions & 0 deletions src/daemon/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,12 @@ pub struct GetBalanceResponse {
pub balance_sat: u64,
/// Spendable on-chain balance in sats.
pub onchain_balance_sat: u64,
/// Best-effort max sendable over Lightning right now (sats), with
/// routing-fee headroom subtracted. `null` when no usable LSP
/// channel exists. `Some(0)` is distinct from `null`: it means a
/// channel exists but the balance is fully consumed by the fee
/// buffer (dust).
pub max_withdrawable_sat: Option<u64>,
}

#[derive(Serialize, ToSchema)]
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod mdk;
pub use mdk::client;
pub use mdk::config;
pub use mdk::error;
pub use mdk::max_sendable;
pub use mdk::mdk_api;
pub use mdk::node;
pub use mdk::types;
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ fn main() {
infra,
scoring_overrides: config_file.scoring_overrides,
splice: config_file.splice,
max_sendable: config_file.max_sendable,
};

// Separate HTTP client for daemon concerns (webhooks, expiry monitor).
Expand Down
20 changes: 20 additions & 0 deletions src/mdk/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ use tokio::sync::broadcast;
use tokio_util::sync::CancellationToken;

use crate::mdk::error::{MdkError, SpliceError};
use crate::mdk::max_sendable::{
compute_estimate, ChannelSnapshot, MaxSendableConfig, MaxSendableError, MaxSendableEstimate,
};
use crate::mdk::mdk_api::client::MdkApiClient;
use crate::mdk::mdk_api::types::{
CheckoutCustomer, CreateCheckoutRequest, PaymentEntry, PaymentReceivedRequest,
Expand All @@ -37,6 +40,7 @@ pub struct MdkClient {
api: Arc<MdkApiClient>,
lsp_pubkey: PublicKey,
splice_cfg: SpliceConfig,
max_sendable_cfg: MaxSendableConfig,
event_tx: broadcast::Sender<MdkEvent>,
event_handler: Option<EventHandler>,
shutdown: CancellationToken,
Expand Down Expand Up @@ -77,6 +81,7 @@ impl MdkClient {
let lsp_pubkey = PublicKey::from_str(&config.infra.lsp_node_id)
.map_err(|e| MdkError::InvalidInput(format!("bad lsp_node_id: {e}")))?;
let splice_cfg = config.splice.clone();
let max_sendable_cfg = config.max_sendable.clone();

let node = build_node(config, handle.clone())?;
let http_client = build_http_client(socks_proxy.as_deref())?;
Expand All @@ -92,6 +97,7 @@ impl MdkClient {
api,
lsp_pubkey,
splice_cfg,
max_sendable_cfg,
event_tx,
event_handler,
shutdown: CancellationToken::new(),
Expand Down Expand Up @@ -137,6 +143,20 @@ impl MdkClient {
self.lsp_pubkey
}

/// Best-effort estimate of the largest amount that can flow out
/// over Lightning right now, with routing-fee headroom subtracted.
/// Computed inline from `node.list_channels()` on every call so
/// the result reflects in-flight HTLCs and reserve as of *now*.
pub fn max_sendable(&self) -> Result<MaxSendableEstimate, MaxSendableError> {
let snaps: Vec<ChannelSnapshot> = self
.node
.list_channels()
.iter()
.map(ChannelSnapshot::from)
.collect();
compute_estimate(&snaps, &self.lsp_pubkey, &self.max_sendable_cfg)
}

/// Splice `amount_sats` of confirmed on-chain funds into the
/// existing channel identified by `user_channel_id`, with the
/// LSP as counterparty.
Expand Down
Loading
Loading