Skip to content
Draft
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
37 changes: 29 additions & 8 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ use crate::io::{
PENDING_PAYMENT_INFO_PERSISTENCE_PRIMARY_NAMESPACE,
PENDING_PAYMENT_INFO_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::service::lsps1::LSPS1Service;
use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig};
use crate::lnurl_auth::LnurlAuth;
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
Expand Down Expand Up @@ -131,6 +132,8 @@ struct PathfindingScoresSyncConfig {
struct LiquiditySourceConfig {
// Acts for both LSPS1 and LSPS2 clients connecting to the given service.
lsp_nodes: Vec<LspConfig>,
// Act as an LSPS1 service.
lsps1_service: Option<LSPS1Service>,
// Act as an LSPS2 service.
lsps2_service: Option<LSPS2ServiceConfig>,
}
Expand Down Expand Up @@ -509,18 +512,22 @@ impl NodeBuilder {
self
}

/// Configures the [`Node`] instance to provide an [LSPS2] service, issuing just-in-time
/// channels to clients.
/// Configures the [`Node`] instance to provide an [LSPS1] and/or [LSPS2] service to clients.
///
/// Allowing normal channel purchases and/or just-in-time channels respectively.
///
/// **Caution**: LSP service support is in **alpha** and is considered an experimental feature.
///
/// [LSPS1]: https://github.com/lightning/blips/blob/master/blip-0051.md
/// [LSPS2]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/blob/main/LSPS2/README.md
pub fn enable_liquidity_provider(
&mut self, lsps2_service_config: LSPS2ServiceConfig,
&mut self, lsps1_service_config: Option<LSPS1Service>,
lsps2_service_config: Option<LSPS2ServiceConfig>,
) -> &mut Self {
let liquidity_source_config =
self.liquidity_source_config.get_or_insert(LiquiditySourceConfig::default());
liquidity_source_config.lsps2_service = Some(lsps2_service_config);
liquidity_source_config.lsps1_service = lsps1_service_config;
liquidity_source_config.lsps2_service = lsps2_service_config;
self
}

Expand Down Expand Up @@ -1114,14 +1121,22 @@ impl ArcedNodeBuilder {
);
}

/// Configures the [`Node`] instance to provide an [LSPS2] service, issuing just-in-time
/// channels to clients.
/// Configures the [`Node`] instance to provide an [LSPS1] and/or [LSPS2] service to clients.
///
/// Allowing normal channel purchases and/or just-in-time channels respectively.
///
/// **Caution**: LSP service support is in **alpha** and is considered an experimental feature.
///
/// [LSPS1]: https://github.com/lightning/blips/blob/master/blip-0051.md
/// [LSPS2]: https://github.com/BitcoinAndLightningLayerSpecs/lsp/blob/main/LSPS2/README.md
pub fn enable_liquidity_provider(&self, lsps2_service_config: LSPS2ServiceConfig) {
self.inner.write().expect("lock").enable_liquidity_provider(lsps2_service_config);
pub fn enable_liquidity_provider(
&self, lsps1_service_config: Option<LSPS1Service>,
lsps2_service_config: Option<LSPS2ServiceConfig>,
) {
self.inner
.write()
.expect("lock")
.enable_liquidity_provider(lsps1_service_config, lsps2_service_config);
}

/// Sets the used storage directory path.
Expand Down Expand Up @@ -2177,6 +2192,10 @@ fn build_with_store_internal(
lsc.lsps2_service.as_ref().map(|config| {
liquidity_source_builder.lsps2_service(promise_secret, config.clone())
});

lsc.lsps1_service
.as_ref()
.map(|config| liquidity_source_builder.lsps1_service(*config));
}

let liquidity_source = runtime
Expand Down Expand Up @@ -2236,6 +2255,8 @@ fn build_with_store_internal(

liquidity_source.lsps2_service().set_peer_manager(Arc::downgrade(&peer_manager));

liquidity_source.lsps1_service().set_peer_manager(Arc::downgrade(&peer_manager));

let connection_manager = Arc::new(ConnectionManager::new(
Arc::clone(&peer_manager),
config.tor_config.clone(),
Expand Down
171 changes: 171 additions & 0 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ use crate::io::{
EVENT_QUEUE_PERSISTENCE_KEY, EVENT_QUEUE_PERSISTENCE_PRIMARY_NAMESPACE,
EVENT_QUEUE_PERSISTENCE_SECONDARY_NAMESPACE,
};
use crate::liquidity::service::lsps1::{PendingLSPS1Channel, PendingLSPS1Order};
use crate::liquidity::LiquiditySource;
use crate::logger::{log_debug, log_error, log_info, log_trace, LdkLogger, Logger};
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
Expand Down Expand Up @@ -834,6 +835,124 @@ where
counterparty_skimmed_fee_msat,
..
} => {
// We intercept early and check if the payment was an LSPS1
// order payment and handle properly.
if let Ok(bytes) = self.event_queue.kv_store.read(
"lsps1_pending_orders",
"",
&payment_hash.0.to_string(),
) {
if let Ok(pending_order) = PendingLSPS1Order::read(&mut &bytes[..]) {
let (payment_preimage, payment_method) = match purpose {
PaymentPurpose::Bolt11InvoicePayment { payment_preimage, .. } => (
payment_preimage,
lightning_liquidity::lsps1::service::PaymentMethod::Bolt11,
),
PaymentPurpose::Bolt12OfferPayment { payment_preimage, .. } => (
payment_preimage,
lightning_liquidity::lsps1::service::PaymentMethod::Bolt12,
),
_ => (None, lightning_liquidity::lsps1::service::PaymentMethod::Bolt11),
};

if let Some(preimage) = payment_preimage {
let expected_msat =
pending_order.order_total_amount_sat.saturating_mul(1000);

if amount_msat < expected_msat {
log_error!(
self.logger,
"Refused LSPS1 payment: underpaid. Expected {} msat, received {} msat.",
expected_msat,
amount_msat
);
self.channel_manager.fail_htlc_backwards(&payment_hash);
return Ok(());
}

self.runtime.block_on(async {
self.liquidity_source
.lsps1_service()
.handle_order_payment_received(
pending_order.counterparty_node_id,
pending_order.request_id.into(),
payment_method,
)
.await
});

self.channel_manager.claim_funds(preimage);

let mut config = self.channel_manager.get_current_config();

// We set the forwarding fee to 0 for now as we're getting paid by the channel fee.
config.channel_config.forwarding_fee_base_msat = 0;

let channel_size_sat = pending_order.order_params.lsp_balance_sat
+ pending_order.order_params.client_balance_sat;

let push_msat =
pending_order.order_params.client_balance_sat.saturating_mul(1000);

let user_channel_id: u128 = u128::from_ne_bytes(
self.keys_manager.get_secure_random_bytes()[..16]
.try_into()
.expect("slice is exactly 16 bytes"),
);

let pending_channel = PendingLSPS1Channel {
order_id: pending_order.request_id.into().clone(),
channel_expiry_blocks: pending_order
.order_params
.channel_expiry_blocks,
};

let _ = self.event_queue.kv_store.write(
"lsps1_pending_channels",
"",
&user_channel_id.to_string(),
pending_channel.encode(),
);

if let Err(e) = self.channel_manager.create_channel(
pending_order.counterparty_node_id,
channel_size_sat,
push_msat,
user_channel_id,
None,
Some(config),
) {
log_error!(
self.logger,
"Failed to open LSPS1 channel after claiming funds: {:?}",
e
);
self.liquidity_source
.lsps1_service()
.handle_order_failed_and_refunded(
pending_order.counterparty_node_id,
pending_order.request_id.into(),
)
.await
}

let _ = self.event_queue.kv_store.remove(
"lsps1_pending_orders",
"",
&payment_hash.0.to_string(),
false,
);
} else {
log_error!(
self.logger,
"Failed to claim LSPS1 payment: preimage unknown or unsupported payment purpose."
);
self.channel_manager.fail_htlc_backwards(&payment_hash);
}
return Ok(());
}
}

let (payment_id, mut payment_info) =
self.resolve_inbound_payment_id(payment_id, &payment_hash).await?;
if let Some(info) = payment_info.as_ref() {
Expand Down Expand Up @@ -1779,6 +1898,58 @@ where
counterparty_node_id,
);

// We check if this event was triggered by an LSPS1 order and handle it properly
if let Ok(bytes) = self.event_queue.kv_store.read(
"lsps1_pending_channels",
"",
&user_channel_id.to_string(),
) {
if let Ok(pending_channel) = PendingLSPS1Channel::read(&mut &bytes[..]) {
let now_secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();

let funded_at =
lightning_liquidity::lsps0::ser::LSPSDateTime::from_unix_timestamp(
now_secs,
)
.expect("Valid timestamp");

let expiry_secs =
now_secs + (pending_channel.channel_expiry_blocks as u64 * 600);
let expires_at =
lightning_liquidity::lsps0::ser::LSPSDateTime::from_unix_timestamp(
expiry_secs,
)
.expect("Valid timestamp");

let channel_info = LSPS1ChannelInfo {
funded_at,
funding_outpoint: funding_txo.into_bitcoin_outpoint(),
expires_at,
};

self.runtime.block_on(async {
self.liquidity_source
.lsps1_service()
.handle_order_channel_opened(
counterparty_node_id,
pending_channel.order_id,
channel_info,
)
.await
});

let _ = self.event_queue.kv_store.remove(
"lsps1_pending_channels",
"",
&user_channel_id.to_string(),
false,
);
}
}

let former_temporary_channel_id = former_temporary_channel_id.expect(
"LDK Node has only ever persisted ChannelPending events from rust-lightning 0.0.115 or later",
);
Expand Down
Loading
Loading