Skip to content
Closed
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
26 changes: 13 additions & 13 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,16 +183,16 @@ harness = false
#vss-client-ng = { path = "../vss-client" }
#vss-client-ng = { git = "https://github.com/lightningdevkit/vss-client", branch = "main" }
#
#[patch."https://github.com/lightningdevkit/rust-lightning"]
#lightning = { path = "../rust-lightning/lightning" }
#lightning-types = { path = "../rust-lightning/lightning-types" }
#lightning-invoice = { path = "../rust-lightning/lightning-invoice" }
#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" }
#lightning-persister = { path = "../rust-lightning/lightning-persister" }
#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" }
#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" }
#lightning-block-sync = { path = "../rust-lightning/lightning-block-sync" }
#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync" }
#lightning-liquidity = { path = "../rust-lightning/lightning-liquidity" }
#lightning-macros = { path = "../rust-lightning/lightning-macros" }
#lightning-dns-resolver = { path = "../rust-lightning/lightning-dns-resolver" }
[patch."https://github.com/lightningdevkit/rust-lightning"]
lightning = { path = "../rust-lightning-3/lightning" }
lightning-types = { path = "../rust-lightning-3/lightning-types" }
lightning-invoice = { path = "../rust-lightning-3/lightning-invoice" }
lightning-net-tokio = { path = "../rust-lightning-3/lightning-net-tokio" }
lightning-persister = { path = "../rust-lightning-3/lightning-persister" }
lightning-background-processor = { path = "../rust-lightning-3/lightning-background-processor" }
lightning-rapid-gossip-sync = { path = "../rust-lightning-3/lightning-rapid-gossip-sync" }
lightning-block-sync = { path = "../rust-lightning-3/lightning-block-sync" }
lightning-transaction-sync = { path = "../rust-lightning-3/lightning-transaction-sync" }
lightning-liquidity = { path = "../rust-lightning-3/lightning-liquidity" }
lightning-macros = { path = "../rust-lightning-3/lightning-macros" }
lightning-dns-resolver = { path = "../rust-lightning-3/lightning-dns-resolver" }
56 changes: 53 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,6 +43,7 @@ use lightning::util::persist::{
use lightning::util::ser::ReadableArgs;
use lightning::util::sweep::OutputSweeper;
use lightning_dns_resolver::OMDomainResolver;
use lightning_liquidity::lsps2::router::LSPS2Router;
use vss_client::headers::VssHeaderProvider;

use crate::chain::ChainSource;
Expand DownExpand Up@@ -70,7 +71,7 @@ use crate::io::{
};
use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig};
use crate::lnurl_auth::LnurlAuth;
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
Expand DownExpand Up@@ -1762,13 +1763,17 @@ fn build_with_store_internal(
}

let scoring_fee_params = ProbabilisticScoringFeeParameters::default();
let router = Arc::new(DefaultRouter::new(
let inner_router = DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
scoring_fee_params,
));
);
// Wrap the default router to inject LSPS2 JIT-channel blinded payment paths into BOLT12
// invoices based on the latest invoice parameters negotiated with our configured LSPs. The
// LSPS2 client handler is wired up below, once the liquidity source is built.
let router = Arc::new(LSPS2Router::new(inner_router));

let mut user_config = default_user_config(&config);

Expand DownExpand Up@@ -1916,6 +1921,7 @@ fn build_with_store_internal(
Arc::clone(&channel_manager),
Arc::clone(&om_resolver),
IgnoringMessageHandler {},
false,
))
} else {
Arc::new(OnionMessenger::new(
Expand DownExpand Up@@ -1992,6 +1998,50 @@ fn build_with_store_internal(
let custom_message_handler =
Arc::new(NodeCustomMessageHandler::new(Arc::clone(&liquidity_source)));

// Wire up the LSPS2 client handler, having the router inject JIT-channel blinded payment
// paths based on the latest invoice parameters negotiated with our configured LSPs.
//
// Beforehand, wipe any parameters previously negotiated with LSPs that are no longer
// configured, making sure the router won't have payments routed through them anymore.
if let Some(lsps2_client_handler) =
liquidity_source.liquidity_manager().lsps2_client_handler_arc()
{
let stale_lsp_node_ids = lsps2_client_handler
.latest_invoice_params()
.into_iter()
.map(|invoice_params| invoice_params.counterparty_node_id)
.filter(|counterparty_node_id| {
!liquidity_source_config.map_or(false, |lsc| {
lsc.lsp_nodes.iter().any(|n| n.node_id == *counterparty_node_id)
})
})
.collect::<Vec<_>>();

for counterparty_node_id in stale_lsp_node_ids {
let wipe_handler = Arc::clone(&lsps2_client_handler);
let wipe_logger = Arc::clone(&logger);
runtime.spawn_background_task(async move {
log_info!(
wipe_logger,
"Wiping LSPS2 invoice parameters previously negotiated with now-unconfigured LSP {}",
counterparty_node_id,
);
if let Err(e) =
wipe_handler.clear_latest_invoice_params(&counterparty_node_id).await
{
log_error!(
wipe_logger,
"Failed to wipe LSPS2 invoice parameters for LSP {}: {:?}",
counterparty_node_id,
e
);
}
});
}

router.set_lsps2_client_handler(lsps2_client_handler);
}

(liquidity_source, custom_message_handler)
};

Expand Down
6 changes: 3 additions & 3 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -218,7 +218,7 @@ where

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::impl_ser_tlv_based;
use lightning::util::test_utils::TestLogger;

use super::*;
Expand All@@ -236,7 +236,7 @@ mod tests {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });
impl_ser_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
Expand DownExpand Up@@ -276,7 +276,7 @@ mod tests {
}
}

impl_writeable_tlv_based!(TestObject, {
impl_ser_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});
Expand Down
132 changes: 118 additions & 14 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@

use core::future::Future;
use core::task::{Poll, Waker};
use std::collections::VecDeque;
use std::collections::{BTreeMap, VecDeque};
use std::ops::Deref;
use std::sync::{Arc, Mutex};

Expand All@@ -29,7 +29,9 @@ use lightning::util::config::{ChannelConfigOverrides, ChannelConfigUpdate};
use lightning::util::errors::APIError;
use lightning::util::persist::KVStore;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum};
use lightning::{impl_ser_tlv_based, impl_ser_tlv_based_enum};
use lightning_liquidity::lsps2::client::LSPS2InvoiceParameters;
use lightning_liquidity::lsps2::router::LSPS2_PAYMENT_METADATA_KEY;
use lightning_liquidity::lsps2::utils::compute_opening_fee;
use lightning_types::payment::{PaymentHash, PaymentPreimage};

Expand DownExpand Up@@ -78,7 +80,7 @@ pub struct HTLCLocator {
pub node_id: Option<PublicKey>,
}

impl_writeable_tlv_based!(HTLCLocator, {
impl_ser_tlv_based!(HTLCLocator, {
(1, channel_id, required),
(3, user_channel_id, option),
(5, node_id, option),
Expand DownExpand Up@@ -294,7 +296,7 @@ pub enum Event {
},
}

impl_writeable_tlv_based_enum!(Event,
impl_ser_tlv_based_enum!(Event,
(0, PaymentSuccessful) => {
(0, payment_hash, required),
(1, fee_paid_msat, option),
Expand DownExpand Up@@ -611,6 +613,21 @@ where
})
}

fn lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_metadata: Option<&BTreeMap<u64, Vec<u8>>>, payment_size_msat: u64,
) -> Option<u64> {
// For BOLT12 payments, the router encoded the negotiated LSPS2 invoice parameters in the
// payment metadata of any JIT-channel blinded payment paths it constructed. Recompute the
// maximum acceptable opening fee from the negotiated opening fee parameters.
let encoded_params = payment_metadata?.get(&LSPS2_PAYMENT_METADATA_KEY)?;
let invoice_params = LSPS2InvoiceParameters::read(&mut &encoded_params[..]).ok()?;
compute_opening_fee(
payment_size_msat,
invoice_params.opening_fee_params.min_fee_msat,
invoice_params.opening_fee_params.proportional as u64,
)
}

pub async fn handle_event(&self, event: LdkEvent) -> Result<(), ReplayEvent> {
match event {
LdkEvent::FundingGenerationReady {
Expand DownExpand Up@@ -798,13 +815,19 @@ where
.and_then(|metadata| {
Self::lsps2_max_total_opening_fee_msat(metadata, amount_msat)
}),
PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
Self::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_context.payment_metadata.as_ref(),
amount_msat + counterparty_skimmed_fee_msat,
)
},
_ => None,
};

let Some(max_total_opening_fee_msat) = max_total_opening_fee_msat else {
log_info!(
self.logger,
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid BOLT11 LSPS2 payment metadata",
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid LSPS2 payment metadata",
hex_utils::to_string(&payment_hash.0),
counterparty_skimmed_fee_msat,
);
Expand All@@ -828,18 +851,24 @@ where
match &info.kind {
PaymentKind::Bolt11 { .. } => {
let update = PaymentDetailsUpdate {
counterparty_skimmed_fee_msat: Some(Some(counterparty_skimmed_fee_msat)),
counterparty_skimmed_fee_msat: Some(Some(
counterparty_skimmed_fee_msat,
)),
..PaymentDetailsUpdate::new(payment_id)
};
match self.payment_store.update(update).await {
Ok(_) => (),
Err(e) => {
log_error!(self.logger, "Failed to access payment store: {}", e);
log_error!(
self.logger,
"Failed to access payment store: {}",
e
);
return Err(ReplayEvent());
},
};
},
_ => debug_assert!(false, "We only expect the counterparty to get away with withholding fees for BOLT11 payments."),
_ => {},
}
}
}
Expand DownExpand Up@@ -1725,15 +1754,24 @@ where

self.bump_tx_event_handler.handle_event(&bte).await;
},
LdkEvent::OnionMessageIntercepted { peer_node_id, message } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
LdkEvent::OnionMessageIntercepted { next_hop, message, .. } => match next_hop {
lightning::blinded_path::message::NextMessageHop::NodeId(peer_node_id) => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
);
}
},
lightning::blinded_path::message::NextMessageHop::ShortChannelId(scid) => {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
"Onion message intercepted for unknown SCID {}, ignoring",
scid
);
}
},
},
LdkEvent::OnionMessagePeerConnected { peer_node_id } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
Expand DownExpand Up@@ -1939,6 +1977,72 @@ mod tests {
);
}

#[test]
fn lsps2_bolt12_payment_metadata_decodes_fee_limit() {
use lightning_liquidity::lsps0::ser::LSPSDateTime;
use lightning_liquidity::lsps2::msgs::LSPS2OpeningFeeParams;

use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};

use std::str::FromStr;

let counterparty_node_id = PublicKey::from_secret_key(
&Secp256k1::new(),
&SecretKey::from_slice(&[42; 32]).unwrap(),
);
let invoice_params = LSPS2InvoiceParameters {
counterparty_node_id,
intercept_scid: 42,
cltv_expiry_delta: 144,
opening_fee_params: LSPS2OpeningFeeParams {
min_fee_msat: 21_000,
proportional: 10_000,
valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(),
min_lifetime: 144,
max_client_to_self_delay: 128,
min_payment_size_msat: 1,
max_payment_size_msat: 100_000_000,
promise: "promise".to_string(),
},
};

let mut payment_metadata = BTreeMap::new();
payment_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, invoice_params.encode());

// max(min_fee_msat, proportional * payment_size / 1_000_000) = max(21_000, 10_000_000)
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&payment_metadata),
1_000_000_000,
),
Some(10_000_000)
);

// Missing metadata, missing key, or malformed parameters are rejected.
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
None, 1_000_000,
),
None
);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&BTreeMap::new()),
1_000_000,
),
None
);
let mut malformed_metadata = BTreeMap::new();
malformed_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, vec![0xff]);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&malformed_metadata),
1_000_000,
),
None
);
}

#[test]
fn lsps2_payment_metadata_missing_or_malformed_limit_is_rejected() {
let empty_metadata = PaymentMetadata { lsps2_parameters: None }.encode();
Expand Down
2 changes: 1 addition & 1 deletion src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1270,7 +1270,7 @@ impl Bolt11Invoice {
}

/// Recover the payee's public key (only to be used if none was included in the invoice)
pub fn recover_payee_pub_key(&self) -> PublicKey {
pub fn recover_payee_pub_key(&self) -> Option<PublicKey> {
self.inner.recover_payee_pub_key()
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/io/vss_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ use bitcoin::bip32::{ChildNumber, Xpriv};
use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
use bitcoin::key::Secp256k1;
use bitcoin::Network;
use lightning::impl_writeable_tlv_based_enum;
use lightning::impl_ser_tlv_based_enum;
use lightning::io::{self, Error, ErrorKind};
use lightning::sign::{EntropySource as LdkEntropySource, RandomBytes};
use lightning::util::persist::KVStore;
Expand DownExpand Up@@ -65,7 +65,7 @@ enum VssSchemaVersion {
V1,
}

impl_writeable_tlv_based_enum!(VssSchemaVersion,
impl_ser_tlv_based_enum!(VssSchemaVersion,
(0, V0) => {},
(1, V1) => {},
);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
BOLT12 LSPS2 Support via persisted BOLT12 state by TheBlueMatt · Pull Request #964 · lightningdevkit/ldk-node · GitHub
Skip to content
Closed
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
26 changes: 13 additions & 13 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,16 +183,16 @@ harness = false
#vss-client-ng = { path = "../vss-client" }
#vss-client-ng = { git = "https://github.com/lightningdevkit/vss-client", branch = "main" }
#
#[patch."https://github.com/lightningdevkit/rust-lightning"]
#lightning = { path = "../rust-lightning/lightning" }
#lightning-types = { path = "../rust-lightning/lightning-types" }
#lightning-invoice = { path = "../rust-lightning/lightning-invoice" }
#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" }
#lightning-persister = { path = "../rust-lightning/lightning-persister" }
#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" }
#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" }
#lightning-block-sync = { path = "../rust-lightning/lightning-block-sync" }
#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync" }
#lightning-liquidity = { path = "../rust-lightning/lightning-liquidity" }
#lightning-macros = { path = "../rust-lightning/lightning-macros" }
#lightning-dns-resolver = { path = "../rust-lightning/lightning-dns-resolver" }
[patch."https://github.com/lightningdevkit/rust-lightning"]
lightning = { path = "../rust-lightning-3/lightning" }
lightning-types = { path = "../rust-lightning-3/lightning-types" }
lightning-invoice = { path = "../rust-lightning-3/lightning-invoice" }
lightning-net-tokio = { path = "../rust-lightning-3/lightning-net-tokio" }
lightning-persister = { path = "../rust-lightning-3/lightning-persister" }
lightning-background-processor = { path = "../rust-lightning-3/lightning-background-processor" }
lightning-rapid-gossip-sync = { path = "../rust-lightning-3/lightning-rapid-gossip-sync" }
lightning-block-sync = { path = "../rust-lightning-3/lightning-block-sync" }
lightning-transaction-sync = { path = "../rust-lightning-3/lightning-transaction-sync" }
lightning-liquidity = { path = "../rust-lightning-3/lightning-liquidity" }
lightning-macros = { path = "../rust-lightning-3/lightning-macros" }
lightning-dns-resolver = { path = "../rust-lightning-3/lightning-dns-resolver" }
56 changes: 53 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,6 +43,7 @@ use lightning::util::persist::{
use lightning::util::ser::ReadableArgs;
use lightning::util::sweep::OutputSweeper;
use lightning_dns_resolver::OMDomainResolver;
use lightning_liquidity::lsps2::router::LSPS2Router;
use vss_client::headers::VssHeaderProvider;

use crate::chain::ChainSource;
Expand DownExpand Up@@ -70,7 +71,7 @@ use crate::io::{
};
use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig};
use crate::lnurl_auth::LnurlAuth;
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
Expand DownExpand Up@@ -1762,13 +1763,17 @@ fn build_with_store_internal(
}

let scoring_fee_params = ProbabilisticScoringFeeParameters::default();
let router = Arc::new(DefaultRouter::new(
let inner_router = DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
scoring_fee_params,
));
);
// Wrap the default router to inject LSPS2 JIT-channel blinded payment paths into BOLT12
// invoices based on the latest invoice parameters negotiated with our configured LSPs. The
// LSPS2 client handler is wired up below, once the liquidity source is built.
let router = Arc::new(LSPS2Router::new(inner_router));

let mut user_config = default_user_config(&config);

Expand DownExpand Up@@ -1916,6 +1921,7 @@ fn build_with_store_internal(
Arc::clone(&channel_manager),
Arc::clone(&om_resolver),
IgnoringMessageHandler {},
false,
))
} else {
Arc::new(OnionMessenger::new(
Expand DownExpand Up@@ -1992,6 +1998,50 @@ fn build_with_store_internal(
let custom_message_handler =
Arc::new(NodeCustomMessageHandler::new(Arc::clone(&liquidity_source)));

// Wire up the LSPS2 client handler, having the router inject JIT-channel blinded payment
// paths based on the latest invoice parameters negotiated with our configured LSPs.
//
// Beforehand, wipe any parameters previously negotiated with LSPs that are no longer
// configured, making sure the router won't have payments routed through them anymore.
if let Some(lsps2_client_handler) =
liquidity_source.liquidity_manager().lsps2_client_handler_arc()
{
let stale_lsp_node_ids = lsps2_client_handler
.latest_invoice_params()
.into_iter()
.map(|invoice_params| invoice_params.counterparty_node_id)
.filter(|counterparty_node_id| {
!liquidity_source_config.map_or(false, |lsc| {
lsc.lsp_nodes.iter().any(|n| n.node_id == *counterparty_node_id)
})
})
.collect::<Vec<_>>();

for counterparty_node_id in stale_lsp_node_ids {
let wipe_handler = Arc::clone(&lsps2_client_handler);
let wipe_logger = Arc::clone(&logger);
runtime.spawn_background_task(async move {
log_info!(
wipe_logger,
"Wiping LSPS2 invoice parameters previously negotiated with now-unconfigured LSP {}",
counterparty_node_id,
);
if let Err(e) =
wipe_handler.clear_latest_invoice_params(&counterparty_node_id).await
{
log_error!(
wipe_logger,
"Failed to wipe LSPS2 invoice parameters for LSP {}: {:?}",
counterparty_node_id,
e
);
}
});
}

router.set_lsps2_client_handler(lsps2_client_handler);
}

(liquidity_source, custom_message_handler)
};

Expand Down
6 changes: 3 additions & 3 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -218,7 +218,7 @@ where

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::impl_ser_tlv_based;
use lightning::util::test_utils::TestLogger;

use super::*;
Expand All@@ -236,7 +236,7 @@ mod tests {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });
impl_ser_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
Expand DownExpand Up@@ -276,7 +276,7 @@ mod tests {
}
}

impl_writeable_tlv_based!(TestObject, {
impl_ser_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});
Expand Down
132 changes: 118 additions & 14 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@

use core::future::Future;
use core::task::{Poll, Waker};
use std::collections::VecDeque;
use std::collections::{BTreeMap, VecDeque};
use std::ops::Deref;
use std::sync::{Arc, Mutex};

Expand All@@ -29,7 +29,9 @@ use lightning::util::config::{ChannelConfigOverrides, ChannelConfigUpdate};
use lightning::util::errors::APIError;
use lightning::util::persist::KVStore;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum};
use lightning::{impl_ser_tlv_based, impl_ser_tlv_based_enum};
use lightning_liquidity::lsps2::client::LSPS2InvoiceParameters;
use lightning_liquidity::lsps2::router::LSPS2_PAYMENT_METADATA_KEY;
use lightning_liquidity::lsps2::utils::compute_opening_fee;
use lightning_types::payment::{PaymentHash, PaymentPreimage};

Expand DownExpand Up@@ -78,7 +80,7 @@ pub struct HTLCLocator {
pub node_id: Option<PublicKey>,
}

impl_writeable_tlv_based!(HTLCLocator, {
impl_ser_tlv_based!(HTLCLocator, {
(1, channel_id, required),
(3, user_channel_id, option),
(5, node_id, option),
Expand DownExpand Up@@ -294,7 +296,7 @@ pub enum Event {
},
}

impl_writeable_tlv_based_enum!(Event,
impl_ser_tlv_based_enum!(Event,
(0, PaymentSuccessful) => {
(0, payment_hash, required),
(1, fee_paid_msat, option),
Expand DownExpand Up@@ -611,6 +613,21 @@ where
})
}

fn lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_metadata: Option<&BTreeMap<u64, Vec<u8>>>, payment_size_msat: u64,
) -> Option<u64> {
// For BOLT12 payments, the router encoded the negotiated LSPS2 invoice parameters in the
// payment metadata of any JIT-channel blinded payment paths it constructed. Recompute the
// maximum acceptable opening fee from the negotiated opening fee parameters.
let encoded_params = payment_metadata?.get(&LSPS2_PAYMENT_METADATA_KEY)?;
let invoice_params = LSPS2InvoiceParameters::read(&mut &encoded_params[..]).ok()?;
compute_opening_fee(
payment_size_msat,
invoice_params.opening_fee_params.min_fee_msat,
invoice_params.opening_fee_params.proportional as u64,
)
}

pub async fn handle_event(&self, event: LdkEvent) -> Result<(), ReplayEvent> {
match event {
LdkEvent::FundingGenerationReady {
Expand DownExpand Up@@ -798,13 +815,19 @@ where
.and_then(|metadata| {
Self::lsps2_max_total_opening_fee_msat(metadata, amount_msat)
}),
PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
Self::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_context.payment_metadata.as_ref(),
amount_msat + counterparty_skimmed_fee_msat,
)
},
_ => None,
};

let Some(max_total_opening_fee_msat) = max_total_opening_fee_msat else {
log_info!(
self.logger,
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid BOLT11 LSPS2 payment metadata",
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid LSPS2 payment metadata",
hex_utils::to_string(&payment_hash.0),
counterparty_skimmed_fee_msat,
);
Expand All@@ -828,18 +851,24 @@ where
match &info.kind {
PaymentKind::Bolt11 { .. } => {
let update = PaymentDetailsUpdate {
counterparty_skimmed_fee_msat: Some(Some(counterparty_skimmed_fee_msat)),
counterparty_skimmed_fee_msat: Some(Some(
counterparty_skimmed_fee_msat,
)),
..PaymentDetailsUpdate::new(payment_id)
};
match self.payment_store.update(update).await {
Ok(_) => (),
Err(e) => {
log_error!(self.logger, "Failed to access payment store: {}", e);
log_error!(
self.logger,
"Failed to access payment store: {}",
e
);
return Err(ReplayEvent());
},
};
},
_ => debug_assert!(false, "We only expect the counterparty to get away with withholding fees for BOLT11 payments."),
_ => {},
}
}
}
Expand DownExpand Up@@ -1725,15 +1754,24 @@ where

self.bump_tx_event_handler.handle_event(&bte).await;
},
LdkEvent::OnionMessageIntercepted { peer_node_id, message } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
LdkEvent::OnionMessageIntercepted { next_hop, message, .. } => match next_hop {
lightning::blinded_path::message::NextMessageHop::NodeId(peer_node_id) => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
);
}
},
lightning::blinded_path::message::NextMessageHop::ShortChannelId(scid) => {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
"Onion message intercepted for unknown SCID {}, ignoring",
scid
);
}
},
},
LdkEvent::OnionMessagePeerConnected { peer_node_id } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
Expand DownExpand Up@@ -1939,6 +1977,72 @@ mod tests {
);
}

#[test]
fn lsps2_bolt12_payment_metadata_decodes_fee_limit() {
use lightning_liquidity::lsps0::ser::LSPSDateTime;
use lightning_liquidity::lsps2::msgs::LSPS2OpeningFeeParams;

use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};

use std::str::FromStr;

let counterparty_node_id = PublicKey::from_secret_key(
&Secp256k1::new(),
&SecretKey::from_slice(&[42; 32]).unwrap(),
);
let invoice_params = LSPS2InvoiceParameters {
counterparty_node_id,
intercept_scid: 42,
cltv_expiry_delta: 144,
opening_fee_params: LSPS2OpeningFeeParams {
min_fee_msat: 21_000,
proportional: 10_000,
valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(),
min_lifetime: 144,
max_client_to_self_delay: 128,
min_payment_size_msat: 1,
max_payment_size_msat: 100_000_000,
promise: "promise".to_string(),
},
};

let mut payment_metadata = BTreeMap::new();
payment_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, invoice_params.encode());

// max(min_fee_msat, proportional * payment_size / 1_000_000) = max(21_000, 10_000_000)
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&payment_metadata),
1_000_000_000,
),
Some(10_000_000)
);

// Missing metadata, missing key, or malformed parameters are rejected.
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
None, 1_000_000,
),
None
);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&BTreeMap::new()),
1_000_000,
),
None
);
let mut malformed_metadata = BTreeMap::new();
malformed_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, vec![0xff]);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&malformed_metadata),
1_000_000,
),
None
);
}

#[test]
fn lsps2_payment_metadata_missing_or_malformed_limit_is_rejected() {
let empty_metadata = PaymentMetadata { lsps2_parameters: None }.encode();
Expand Down
2 changes: 1 addition & 1 deletion src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1270,7 +1270,7 @@ impl Bolt11Invoice {
}

/// Recover the payee's public key (only to be used if none was included in the invoice)
pub fn recover_payee_pub_key(&self) -> PublicKey {
pub fn recover_payee_pub_key(&self) -> Option<PublicKey> {
self.inner.recover_payee_pub_key()
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/io/vss_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ use bitcoin::bip32::{ChildNumber, Xpriv};
use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
use bitcoin::key::Secp256k1;
use bitcoin::Network;
use lightning::impl_writeable_tlv_based_enum;
use lightning::impl_ser_tlv_based_enum;
use lightning::io::{self, Error, ErrorKind};
use lightning::sign::{EntropySource as LdkEntropySource, RandomBytes};
use lightning::util::persist::KVStore;
Expand DownExpand Up@@ -65,7 +65,7 @@ enum VssSchemaVersion {
V1,
}

impl_writeable_tlv_based_enum!(VssSchemaVersion,
impl_ser_tlv_based_enum!(VssSchemaVersion,
(0, V0) => {},
(1, V1) => {},
);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT12 LSPS2 Support via persisted BOLT12 state by TheBlueMatt · Pull Request #964 · lightningdevkit/ldk-node · GitHub
Skip to content
Closed
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
26 changes: 13 additions & 13 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,16 +183,16 @@ harness = false
#vss-client-ng = { path = "../vss-client" }
#vss-client-ng = { git = "https://github.com/lightningdevkit/vss-client", branch = "main" }
#
#[patch."https://github.com/lightningdevkit/rust-lightning"]
#lightning = { path = "../rust-lightning/lightning" }
#lightning-types = { path = "../rust-lightning/lightning-types" }
#lightning-invoice = { path = "../rust-lightning/lightning-invoice" }
#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" }
#lightning-persister = { path = "../rust-lightning/lightning-persister" }
#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" }
#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" }
#lightning-block-sync = { path = "../rust-lightning/lightning-block-sync" }
#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync" }
#lightning-liquidity = { path = "../rust-lightning/lightning-liquidity" }
#lightning-macros = { path = "../rust-lightning/lightning-macros" }
#lightning-dns-resolver = { path = "../rust-lightning/lightning-dns-resolver" }
[patch."https://github.com/lightningdevkit/rust-lightning"]
lightning = { path = "../rust-lightning-3/lightning" }
lightning-types = { path = "../rust-lightning-3/lightning-types" }
lightning-invoice = { path = "../rust-lightning-3/lightning-invoice" }
lightning-net-tokio = { path = "../rust-lightning-3/lightning-net-tokio" }
lightning-persister = { path = "../rust-lightning-3/lightning-persister" }
lightning-background-processor = { path = "../rust-lightning-3/lightning-background-processor" }
lightning-rapid-gossip-sync = { path = "../rust-lightning-3/lightning-rapid-gossip-sync" }
lightning-block-sync = { path = "../rust-lightning-3/lightning-block-sync" }
lightning-transaction-sync = { path = "../rust-lightning-3/lightning-transaction-sync" }
lightning-liquidity = { path = "../rust-lightning-3/lightning-liquidity" }
lightning-macros = { path = "../rust-lightning-3/lightning-macros" }
lightning-dns-resolver = { path = "../rust-lightning-3/lightning-dns-resolver" }
56 changes: 53 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,6 +43,7 @@ use lightning::util::persist::{
use lightning::util::ser::ReadableArgs;
use lightning::util::sweep::OutputSweeper;
use lightning_dns_resolver::OMDomainResolver;
use lightning_liquidity::lsps2::router::LSPS2Router;
use vss_client::headers::VssHeaderProvider;

use crate::chain::ChainSource;
Expand DownExpand Up@@ -70,7 +71,7 @@ use crate::io::{
};
use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig};
use crate::lnurl_auth::LnurlAuth;
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
Expand DownExpand Up@@ -1762,13 +1763,17 @@ fn build_with_store_internal(
}

let scoring_fee_params = ProbabilisticScoringFeeParameters::default();
let router = Arc::new(DefaultRouter::new(
let inner_router = DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
scoring_fee_params,
));
);
// Wrap the default router to inject LSPS2 JIT-channel blinded payment paths into BOLT12
// invoices based on the latest invoice parameters negotiated with our configured LSPs. The
// LSPS2 client handler is wired up below, once the liquidity source is built.
let router = Arc::new(LSPS2Router::new(inner_router));

let mut user_config = default_user_config(&config);

Expand DownExpand Up@@ -1916,6 +1921,7 @@ fn build_with_store_internal(
Arc::clone(&channel_manager),
Arc::clone(&om_resolver),
IgnoringMessageHandler {},
false,
))
} else {
Arc::new(OnionMessenger::new(
Expand DownExpand Up@@ -1992,6 +1998,50 @@ fn build_with_store_internal(
let custom_message_handler =
Arc::new(NodeCustomMessageHandler::new(Arc::clone(&liquidity_source)));

// Wire up the LSPS2 client handler, having the router inject JIT-channel blinded payment
// paths based on the latest invoice parameters negotiated with our configured LSPs.
//
// Beforehand, wipe any parameters previously negotiated with LSPs that are no longer
// configured, making sure the router won't have payments routed through them anymore.
if let Some(lsps2_client_handler) =
liquidity_source.liquidity_manager().lsps2_client_handler_arc()
{
let stale_lsp_node_ids = lsps2_client_handler
.latest_invoice_params()
.into_iter()
.map(|invoice_params| invoice_params.counterparty_node_id)
.filter(|counterparty_node_id| {
!liquidity_source_config.map_or(false, |lsc| {
lsc.lsp_nodes.iter().any(|n| n.node_id == *counterparty_node_id)
})
})
.collect::<Vec<_>>();

for counterparty_node_id in stale_lsp_node_ids {
let wipe_handler = Arc::clone(&lsps2_client_handler);
let wipe_logger = Arc::clone(&logger);
runtime.spawn_background_task(async move {
log_info!(
wipe_logger,
"Wiping LSPS2 invoice parameters previously negotiated with now-unconfigured LSP {}",
counterparty_node_id,
);
if let Err(e) =
wipe_handler.clear_latest_invoice_params(&counterparty_node_id).await
{
log_error!(
wipe_logger,
"Failed to wipe LSPS2 invoice parameters for LSP {}: {:?}",
counterparty_node_id,
e
);
}
});
}

router.set_lsps2_client_handler(lsps2_client_handler);
}

(liquidity_source, custom_message_handler)
};

Expand Down
6 changes: 3 additions & 3 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -218,7 +218,7 @@ where

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::impl_ser_tlv_based;
use lightning::util::test_utils::TestLogger;

use super::*;
Expand All@@ -236,7 +236,7 @@ mod tests {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });
impl_ser_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
Expand DownExpand Up@@ -276,7 +276,7 @@ mod tests {
}
}

impl_writeable_tlv_based!(TestObject, {
impl_ser_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});
Expand Down
132 changes: 118 additions & 14 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@

use core::future::Future;
use core::task::{Poll, Waker};
use std::collections::VecDeque;
use std::collections::{BTreeMap, VecDeque};
use std::ops::Deref;
use std::sync::{Arc, Mutex};

Expand All@@ -29,7 +29,9 @@ use lightning::util::config::{ChannelConfigOverrides, ChannelConfigUpdate};
use lightning::util::errors::APIError;
use lightning::util::persist::KVStore;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum};
use lightning::{impl_ser_tlv_based, impl_ser_tlv_based_enum};
use lightning_liquidity::lsps2::client::LSPS2InvoiceParameters;
use lightning_liquidity::lsps2::router::LSPS2_PAYMENT_METADATA_KEY;
use lightning_liquidity::lsps2::utils::compute_opening_fee;
use lightning_types::payment::{PaymentHash, PaymentPreimage};

Expand DownExpand Up@@ -78,7 +80,7 @@ pub struct HTLCLocator {
pub node_id: Option<PublicKey>,
}

impl_writeable_tlv_based!(HTLCLocator, {
impl_ser_tlv_based!(HTLCLocator, {
(1, channel_id, required),
(3, user_channel_id, option),
(5, node_id, option),
Expand DownExpand Up@@ -294,7 +296,7 @@ pub enum Event {
},
}

impl_writeable_tlv_based_enum!(Event,
impl_ser_tlv_based_enum!(Event,
(0, PaymentSuccessful) => {
(0, payment_hash, required),
(1, fee_paid_msat, option),
Expand DownExpand Up@@ -611,6 +613,21 @@ where
})
}

fn lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_metadata: Option<&BTreeMap<u64, Vec<u8>>>, payment_size_msat: u64,
) -> Option<u64> {
// For BOLT12 payments, the router encoded the negotiated LSPS2 invoice parameters in the
// payment metadata of any JIT-channel blinded payment paths it constructed. Recompute the
// maximum acceptable opening fee from the negotiated opening fee parameters.
let encoded_params = payment_metadata?.get(&LSPS2_PAYMENT_METADATA_KEY)?;
let invoice_params = LSPS2InvoiceParameters::read(&mut &encoded_params[..]).ok()?;
compute_opening_fee(
payment_size_msat,
invoice_params.opening_fee_params.min_fee_msat,
invoice_params.opening_fee_params.proportional as u64,
)
}

pub async fn handle_event(&self, event: LdkEvent) -> Result<(), ReplayEvent> {
match event {
LdkEvent::FundingGenerationReady {
Expand DownExpand Up@@ -798,13 +815,19 @@ where
.and_then(|metadata| {
Self::lsps2_max_total_opening_fee_msat(metadata, amount_msat)
}),
PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
Self::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_context.payment_metadata.as_ref(),
amount_msat + counterparty_skimmed_fee_msat,
)
},
_ => None,
};

let Some(max_total_opening_fee_msat) = max_total_opening_fee_msat else {
log_info!(
self.logger,
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid BOLT11 LSPS2 payment metadata",
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid LSPS2 payment metadata",
hex_utils::to_string(&payment_hash.0),
counterparty_skimmed_fee_msat,
);
Expand All@@ -828,18 +851,24 @@ where
match &info.kind {
PaymentKind::Bolt11 { .. } => {
let update = PaymentDetailsUpdate {
counterparty_skimmed_fee_msat: Some(Some(counterparty_skimmed_fee_msat)),
counterparty_skimmed_fee_msat: Some(Some(
counterparty_skimmed_fee_msat,
)),
..PaymentDetailsUpdate::new(payment_id)
};
match self.payment_store.update(update).await {
Ok(_) => (),
Err(e) => {
log_error!(self.logger, "Failed to access payment store: {}", e);
log_error!(
self.logger,
"Failed to access payment store: {}",
e
);
return Err(ReplayEvent());
},
};
},
_ => debug_assert!(false, "We only expect the counterparty to get away with withholding fees for BOLT11 payments."),
_ => {},
}
}
}
Expand DownExpand Up@@ -1725,15 +1754,24 @@ where

self.bump_tx_event_handler.handle_event(&bte).await;
},
LdkEvent::OnionMessageIntercepted { peer_node_id, message } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
LdkEvent::OnionMessageIntercepted { next_hop, message, .. } => match next_hop {
lightning::blinded_path::message::NextMessageHop::NodeId(peer_node_id) => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
);
}
},
lightning::blinded_path::message::NextMessageHop::ShortChannelId(scid) => {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
"Onion message intercepted for unknown SCID {}, ignoring",
scid
);
}
},
},
LdkEvent::OnionMessagePeerConnected { peer_node_id } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
Expand DownExpand Up@@ -1939,6 +1977,72 @@ mod tests {
);
}

#[test]
fn lsps2_bolt12_payment_metadata_decodes_fee_limit() {
use lightning_liquidity::lsps0::ser::LSPSDateTime;
use lightning_liquidity::lsps2::msgs::LSPS2OpeningFeeParams;

use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};

use std::str::FromStr;

let counterparty_node_id = PublicKey::from_secret_key(
&Secp256k1::new(),
&SecretKey::from_slice(&[42; 32]).unwrap(),
);
let invoice_params = LSPS2InvoiceParameters {
counterparty_node_id,
intercept_scid: 42,
cltv_expiry_delta: 144,
opening_fee_params: LSPS2OpeningFeeParams {
min_fee_msat: 21_000,
proportional: 10_000,
valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(),
min_lifetime: 144,
max_client_to_self_delay: 128,
min_payment_size_msat: 1,
max_payment_size_msat: 100_000_000,
promise: "promise".to_string(),
},
};

let mut payment_metadata = BTreeMap::new();
payment_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, invoice_params.encode());

// max(min_fee_msat, proportional * payment_size / 1_000_000) = max(21_000, 10_000_000)
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&payment_metadata),
1_000_000_000,
),
Some(10_000_000)
);

// Missing metadata, missing key, or malformed parameters are rejected.
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
None, 1_000_000,
),
None
);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&BTreeMap::new()),
1_000_000,
),
None
);
let mut malformed_metadata = BTreeMap::new();
malformed_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, vec![0xff]);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&malformed_metadata),
1_000_000,
),
None
);
}

#[test]
fn lsps2_payment_metadata_missing_or_malformed_limit_is_rejected() {
let empty_metadata = PaymentMetadata { lsps2_parameters: None }.encode();
Expand Down
2 changes: 1 addition & 1 deletion src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1270,7 +1270,7 @@ impl Bolt11Invoice {
}

/// Recover the payee's public key (only to be used if none was included in the invoice)
pub fn recover_payee_pub_key(&self) -> PublicKey {
pub fn recover_payee_pub_key(&self) -> Option<PublicKey> {
self.inner.recover_payee_pub_key()
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/io/vss_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ use bitcoin::bip32::{ChildNumber, Xpriv};
use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
use bitcoin::key::Secp256k1;
use bitcoin::Network;
use lightning::impl_writeable_tlv_based_enum;
use lightning::impl_ser_tlv_based_enum;
use lightning::io::{self, Error, ErrorKind};
use lightning::sign::{EntropySource as LdkEntropySource, RandomBytes};
use lightning::util::persist::KVStore;
Expand DownExpand Up@@ -65,7 +65,7 @@ enum VssSchemaVersion {
V1,
}

impl_writeable_tlv_based_enum!(VssSchemaVersion,
impl_ser_tlv_based_enum!(VssSchemaVersion,
(0, V0) => {},
(1, V1) => {},
);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT12 LSPS2 Support via persisted BOLT12 state by TheBlueMatt · Pull Request #964 · lightningdevkit/ldk-node · GitHub
Skip to content
Closed
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
26 changes: 13 additions & 13 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,16 +183,16 @@ harness = false
#vss-client-ng = { path = "../vss-client" }
#vss-client-ng = { git = "https://github.com/lightningdevkit/vss-client", branch = "main" }
#
#[patch."https://github.com/lightningdevkit/rust-lightning"]
#lightning = { path = "../rust-lightning/lightning" }
#lightning-types = { path = "../rust-lightning/lightning-types" }
#lightning-invoice = { path = "../rust-lightning/lightning-invoice" }
#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" }
#lightning-persister = { path = "../rust-lightning/lightning-persister" }
#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" }
#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" }
#lightning-block-sync = { path = "../rust-lightning/lightning-block-sync" }
#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync" }
#lightning-liquidity = { path = "../rust-lightning/lightning-liquidity" }
#lightning-macros = { path = "../rust-lightning/lightning-macros" }
#lightning-dns-resolver = { path = "../rust-lightning/lightning-dns-resolver" }
[patch."https://github.com/lightningdevkit/rust-lightning"]
lightning = { path = "../rust-lightning-3/lightning" }
lightning-types = { path = "../rust-lightning-3/lightning-types" }
lightning-invoice = { path = "../rust-lightning-3/lightning-invoice" }
lightning-net-tokio = { path = "../rust-lightning-3/lightning-net-tokio" }
lightning-persister = { path = "../rust-lightning-3/lightning-persister" }
lightning-background-processor = { path = "../rust-lightning-3/lightning-background-processor" }
lightning-rapid-gossip-sync = { path = "../rust-lightning-3/lightning-rapid-gossip-sync" }
lightning-block-sync = { path = "../rust-lightning-3/lightning-block-sync" }
lightning-transaction-sync = { path = "../rust-lightning-3/lightning-transaction-sync" }
lightning-liquidity = { path = "../rust-lightning-3/lightning-liquidity" }
lightning-macros = { path = "../rust-lightning-3/lightning-macros" }
lightning-dns-resolver = { path = "../rust-lightning-3/lightning-dns-resolver" }
56 changes: 53 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,6 +43,7 @@ use lightning::util::persist::{
use lightning::util::ser::ReadableArgs;
use lightning::util::sweep::OutputSweeper;
use lightning_dns_resolver::OMDomainResolver;
use lightning_liquidity::lsps2::router::LSPS2Router;
use vss_client::headers::VssHeaderProvider;

use crate::chain::ChainSource;
Expand DownExpand Up@@ -70,7 +71,7 @@ use crate::io::{
};
use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig};
use crate::lnurl_auth::LnurlAuth;
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
Expand DownExpand Up@@ -1762,13 +1763,17 @@ fn build_with_store_internal(
}

let scoring_fee_params = ProbabilisticScoringFeeParameters::default();
let router = Arc::new(DefaultRouter::new(
let inner_router = DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
scoring_fee_params,
));
);
// Wrap the default router to inject LSPS2 JIT-channel blinded payment paths into BOLT12
// invoices based on the latest invoice parameters negotiated with our configured LSPs. The
// LSPS2 client handler is wired up below, once the liquidity source is built.
let router = Arc::new(LSPS2Router::new(inner_router));

let mut user_config = default_user_config(&config);

Expand DownExpand Up@@ -1916,6 +1921,7 @@ fn build_with_store_internal(
Arc::clone(&channel_manager),
Arc::clone(&om_resolver),
IgnoringMessageHandler {},
false,
))
} else {
Arc::new(OnionMessenger::new(
Expand DownExpand Up@@ -1992,6 +1998,50 @@ fn build_with_store_internal(
let custom_message_handler =
Arc::new(NodeCustomMessageHandler::new(Arc::clone(&liquidity_source)));

// Wire up the LSPS2 client handler, having the router inject JIT-channel blinded payment
// paths based on the latest invoice parameters negotiated with our configured LSPs.
//
// Beforehand, wipe any parameters previously negotiated with LSPs that are no longer
// configured, making sure the router won't have payments routed through them anymore.
if let Some(lsps2_client_handler) =
liquidity_source.liquidity_manager().lsps2_client_handler_arc()
{
let stale_lsp_node_ids = lsps2_client_handler
.latest_invoice_params()
.into_iter()
.map(|invoice_params| invoice_params.counterparty_node_id)
.filter(|counterparty_node_id| {
!liquidity_source_config.map_or(false, |lsc| {
lsc.lsp_nodes.iter().any(|n| n.node_id == *counterparty_node_id)
})
})
.collect::<Vec<_>>();

for counterparty_node_id in stale_lsp_node_ids {
let wipe_handler = Arc::clone(&lsps2_client_handler);
let wipe_logger = Arc::clone(&logger);
runtime.spawn_background_task(async move {
log_info!(
wipe_logger,
"Wiping LSPS2 invoice parameters previously negotiated with now-unconfigured LSP {}",
counterparty_node_id,
);
if let Err(e) =
wipe_handler.clear_latest_invoice_params(&counterparty_node_id).await
{
log_error!(
wipe_logger,
"Failed to wipe LSPS2 invoice parameters for LSP {}: {:?}",
counterparty_node_id,
e
);
}
});
}

router.set_lsps2_client_handler(lsps2_client_handler);
}

(liquidity_source, custom_message_handler)
};

Expand Down
6 changes: 3 additions & 3 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -218,7 +218,7 @@ where

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::impl_ser_tlv_based;
use lightning::util::test_utils::TestLogger;

use super::*;
Expand All@@ -236,7 +236,7 @@ mod tests {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });
impl_ser_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
Expand DownExpand Up@@ -276,7 +276,7 @@ mod tests {
}
}

impl_writeable_tlv_based!(TestObject, {
impl_ser_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});
Expand Down
132 changes: 118 additions & 14 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@

use core::future::Future;
use core::task::{Poll, Waker};
use std::collections::VecDeque;
use std::collections::{BTreeMap, VecDeque};
use std::ops::Deref;
use std::sync::{Arc, Mutex};

Expand All@@ -29,7 +29,9 @@ use lightning::util::config::{ChannelConfigOverrides, ChannelConfigUpdate};
use lightning::util::errors::APIError;
use lightning::util::persist::KVStore;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum};
use lightning::{impl_ser_tlv_based, impl_ser_tlv_based_enum};
use lightning_liquidity::lsps2::client::LSPS2InvoiceParameters;
use lightning_liquidity::lsps2::router::LSPS2_PAYMENT_METADATA_KEY;
use lightning_liquidity::lsps2::utils::compute_opening_fee;
use lightning_types::payment::{PaymentHash, PaymentPreimage};

Expand DownExpand Up@@ -78,7 +80,7 @@ pub struct HTLCLocator {
pub node_id: Option<PublicKey>,
}

impl_writeable_tlv_based!(HTLCLocator, {
impl_ser_tlv_based!(HTLCLocator, {
(1, channel_id, required),
(3, user_channel_id, option),
(5, node_id, option),
Expand DownExpand Up@@ -294,7 +296,7 @@ pub enum Event {
},
}

impl_writeable_tlv_based_enum!(Event,
impl_ser_tlv_based_enum!(Event,
(0, PaymentSuccessful) => {
(0, payment_hash, required),
(1, fee_paid_msat, option),
Expand DownExpand Up@@ -611,6 +613,21 @@ where
})
}

fn lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_metadata: Option<&BTreeMap<u64, Vec<u8>>>, payment_size_msat: u64,
) -> Option<u64> {
// For BOLT12 payments, the router encoded the negotiated LSPS2 invoice parameters in the
// payment metadata of any JIT-channel blinded payment paths it constructed. Recompute the
// maximum acceptable opening fee from the negotiated opening fee parameters.
let encoded_params = payment_metadata?.get(&LSPS2_PAYMENT_METADATA_KEY)?;
let invoice_params = LSPS2InvoiceParameters::read(&mut &encoded_params[..]).ok()?;
compute_opening_fee(
payment_size_msat,
invoice_params.opening_fee_params.min_fee_msat,
invoice_params.opening_fee_params.proportional as u64,
)
}

pub async fn handle_event(&self, event: LdkEvent) -> Result<(), ReplayEvent> {
match event {
LdkEvent::FundingGenerationReady {
Expand DownExpand Up@@ -798,13 +815,19 @@ where
.and_then(|metadata| {
Self::lsps2_max_total_opening_fee_msat(metadata, amount_msat)
}),
PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
Self::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_context.payment_metadata.as_ref(),
amount_msat + counterparty_skimmed_fee_msat,
)
},
_ => None,
};

let Some(max_total_opening_fee_msat) = max_total_opening_fee_msat else {
log_info!(
self.logger,
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid BOLT11 LSPS2 payment metadata",
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid LSPS2 payment metadata",
hex_utils::to_string(&payment_hash.0),
counterparty_skimmed_fee_msat,
);
Expand All@@ -828,18 +851,24 @@ where
match &info.kind {
PaymentKind::Bolt11 { .. } => {
let update = PaymentDetailsUpdate {
counterparty_skimmed_fee_msat: Some(Some(counterparty_skimmed_fee_msat)),
counterparty_skimmed_fee_msat: Some(Some(
counterparty_skimmed_fee_msat,
)),
..PaymentDetailsUpdate::new(payment_id)
};
match self.payment_store.update(update).await {
Ok(_) => (),
Err(e) => {
log_error!(self.logger, "Failed to access payment store: {}", e);
log_error!(
self.logger,
"Failed to access payment store: {}",
e
);
return Err(ReplayEvent());
},
};
},
_ => debug_assert!(false, "We only expect the counterparty to get away with withholding fees for BOLT11 payments."),
_ => {},
}
}
}
Expand DownExpand Up@@ -1725,15 +1754,24 @@ where

self.bump_tx_event_handler.handle_event(&bte).await;
},
LdkEvent::OnionMessageIntercepted { peer_node_id, message } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
LdkEvent::OnionMessageIntercepted { next_hop, message, .. } => match next_hop {
lightning::blinded_path::message::NextMessageHop::NodeId(peer_node_id) => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
);
}
},
lightning::blinded_path::message::NextMessageHop::ShortChannelId(scid) => {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
"Onion message intercepted for unknown SCID {}, ignoring",
scid
);
}
},
},
LdkEvent::OnionMessagePeerConnected { peer_node_id } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
Expand DownExpand Up@@ -1939,6 +1977,72 @@ mod tests {
);
}

#[test]
fn lsps2_bolt12_payment_metadata_decodes_fee_limit() {
use lightning_liquidity::lsps0::ser::LSPSDateTime;
use lightning_liquidity::lsps2::msgs::LSPS2OpeningFeeParams;

use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};

use std::str::FromStr;

let counterparty_node_id = PublicKey::from_secret_key(
&Secp256k1::new(),
&SecretKey::from_slice(&[42; 32]).unwrap(),
);
let invoice_params = LSPS2InvoiceParameters {
counterparty_node_id,
intercept_scid: 42,
cltv_expiry_delta: 144,
opening_fee_params: LSPS2OpeningFeeParams {
min_fee_msat: 21_000,
proportional: 10_000,
valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(),
min_lifetime: 144,
max_client_to_self_delay: 128,
min_payment_size_msat: 1,
max_payment_size_msat: 100_000_000,
promise: "promise".to_string(),
},
};

let mut payment_metadata = BTreeMap::new();
payment_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, invoice_params.encode());

// max(min_fee_msat, proportional * payment_size / 1_000_000) = max(21_000, 10_000_000)
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&payment_metadata),
1_000_000_000,
),
Some(10_000_000)
);

// Missing metadata, missing key, or malformed parameters are rejected.
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
None, 1_000_000,
),
None
);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&BTreeMap::new()),
1_000_000,
),
None
);
let mut malformed_metadata = BTreeMap::new();
malformed_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, vec![0xff]);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&malformed_metadata),
1_000_000,
),
None
);
}

#[test]
fn lsps2_payment_metadata_missing_or_malformed_limit_is_rejected() {
let empty_metadata = PaymentMetadata { lsps2_parameters: None }.encode();
Expand Down
2 changes: 1 addition & 1 deletion src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1270,7 +1270,7 @@ impl Bolt11Invoice {
}

/// Recover the payee's public key (only to be used if none was included in the invoice)
pub fn recover_payee_pub_key(&self) -> PublicKey {
pub fn recover_payee_pub_key(&self) -> Option<PublicKey> {
self.inner.recover_payee_pub_key()
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/io/vss_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ use bitcoin::bip32::{ChildNumber, Xpriv};
use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
use bitcoin::key::Secp256k1;
use bitcoin::Network;
use lightning::impl_writeable_tlv_based_enum;
use lightning::impl_ser_tlv_based_enum;
use lightning::io::{self, Error, ErrorKind};
use lightning::sign::{EntropySource as LdkEntropySource, RandomBytes};
use lightning::util::persist::KVStore;
Expand DownExpand Up@@ -65,7 +65,7 @@ enum VssSchemaVersion {
V1,
}

impl_writeable_tlv_based_enum!(VssSchemaVersion,
impl_ser_tlv_based_enum!(VssSchemaVersion,
(0, V0) => {},
(1, V1) => {},
);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' BOLT12 LSPS2 Support via persisted BOLT12 state by TheBlueMatt · Pull Request #964 · lightningdevkit/ldk-node · GitHub
Skip to content
Closed
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
26 changes: 13 additions & 13 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,16 +183,16 @@ harness = false
#vss-client-ng = { path = "../vss-client" }
#vss-client-ng = { git = "https://github.com/lightningdevkit/vss-client", branch = "main" }
#
#[patch."https://github.com/lightningdevkit/rust-lightning"]
#lightning = { path = "../rust-lightning/lightning" }
#lightning-types = { path = "../rust-lightning/lightning-types" }
#lightning-invoice = { path = "../rust-lightning/lightning-invoice" }
#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" }
#lightning-persister = { path = "../rust-lightning/lightning-persister" }
#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" }
#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" }
#lightning-block-sync = { path = "../rust-lightning/lightning-block-sync" }
#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync" }
#lightning-liquidity = { path = "../rust-lightning/lightning-liquidity" }
#lightning-macros = { path = "../rust-lightning/lightning-macros" }
#lightning-dns-resolver = { path = "../rust-lightning/lightning-dns-resolver" }
[patch."https://github.com/lightningdevkit/rust-lightning"]
lightning = { path = "../rust-lightning-3/lightning" }
lightning-types = { path = "../rust-lightning-3/lightning-types" }
lightning-invoice = { path = "../rust-lightning-3/lightning-invoice" }
lightning-net-tokio = { path = "../rust-lightning-3/lightning-net-tokio" }
lightning-persister = { path = "../rust-lightning-3/lightning-persister" }
lightning-background-processor = { path = "../rust-lightning-3/lightning-background-processor" }
lightning-rapid-gossip-sync = { path = "../rust-lightning-3/lightning-rapid-gossip-sync" }
lightning-block-sync = { path = "../rust-lightning-3/lightning-block-sync" }
lightning-transaction-sync = { path = "../rust-lightning-3/lightning-transaction-sync" }
lightning-liquidity = { path = "../rust-lightning-3/lightning-liquidity" }
lightning-macros = { path = "../rust-lightning-3/lightning-macros" }
lightning-dns-resolver = { path = "../rust-lightning-3/lightning-dns-resolver" }
56 changes: 53 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,6 +43,7 @@ use lightning::util::persist::{
use lightning::util::ser::ReadableArgs;
use lightning::util::sweep::OutputSweeper;
use lightning_dns_resolver::OMDomainResolver;
use lightning_liquidity::lsps2::router::LSPS2Router;
use vss_client::headers::VssHeaderProvider;

use crate::chain::ChainSource;
Expand DownExpand Up@@ -70,7 +71,7 @@ use crate::io::{
};
use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig};
use crate::lnurl_auth::LnurlAuth;
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
Expand DownExpand Up@@ -1762,13 +1763,17 @@ fn build_with_store_internal(
}

let scoring_fee_params = ProbabilisticScoringFeeParameters::default();
let router = Arc::new(DefaultRouter::new(
let inner_router = DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
scoring_fee_params,
));
);
// Wrap the default router to inject LSPS2 JIT-channel blinded payment paths into BOLT12
// invoices based on the latest invoice parameters negotiated with our configured LSPs. The
// LSPS2 client handler is wired up below, once the liquidity source is built.
let router = Arc::new(LSPS2Router::new(inner_router));

let mut user_config = default_user_config(&config);

Expand DownExpand Up@@ -1916,6 +1921,7 @@ fn build_with_store_internal(
Arc::clone(&channel_manager),
Arc::clone(&om_resolver),
IgnoringMessageHandler {},
false,
))
} else {
Arc::new(OnionMessenger::new(
Expand DownExpand Up@@ -1992,6 +1998,50 @@ fn build_with_store_internal(
let custom_message_handler =
Arc::new(NodeCustomMessageHandler::new(Arc::clone(&liquidity_source)));

// Wire up the LSPS2 client handler, having the router inject JIT-channel blinded payment
// paths based on the latest invoice parameters negotiated with our configured LSPs.
//
// Beforehand, wipe any parameters previously negotiated with LSPs that are no longer
// configured, making sure the router won't have payments routed through them anymore.
if let Some(lsps2_client_handler) =
liquidity_source.liquidity_manager().lsps2_client_handler_arc()
{
let stale_lsp_node_ids = lsps2_client_handler
.latest_invoice_params()
.into_iter()
.map(|invoice_params| invoice_params.counterparty_node_id)
.filter(|counterparty_node_id| {
!liquidity_source_config.map_or(false, |lsc| {
lsc.lsp_nodes.iter().any(|n| n.node_id == *counterparty_node_id)
})
})
.collect::<Vec<_>>();

for counterparty_node_id in stale_lsp_node_ids {
let wipe_handler = Arc::clone(&lsps2_client_handler);
let wipe_logger = Arc::clone(&logger);
runtime.spawn_background_task(async move {
log_info!(
wipe_logger,
"Wiping LSPS2 invoice parameters previously negotiated with now-unconfigured LSP {}",
counterparty_node_id,
);
if let Err(e) =
wipe_handler.clear_latest_invoice_params(&counterparty_node_id).await
{
log_error!(
wipe_logger,
"Failed to wipe LSPS2 invoice parameters for LSP {}: {:?}",
counterparty_node_id,
e
);
}
});
}

router.set_lsps2_client_handler(lsps2_client_handler);
}

(liquidity_source, custom_message_handler)
};

Expand Down
6 changes: 3 additions & 3 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -218,7 +218,7 @@ where

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::impl_ser_tlv_based;
use lightning::util::test_utils::TestLogger;

use super::*;
Expand All@@ -236,7 +236,7 @@ mod tests {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });
impl_ser_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
Expand DownExpand Up@@ -276,7 +276,7 @@ mod tests {
}
}

impl_writeable_tlv_based!(TestObject, {
impl_ser_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});
Expand Down
132 changes: 118 additions & 14 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@

use core::future::Future;
use core::task::{Poll, Waker};
use std::collections::VecDeque;
use std::collections::{BTreeMap, VecDeque};
use std::ops::Deref;
use std::sync::{Arc, Mutex};

Expand All@@ -29,7 +29,9 @@ use lightning::util::config::{ChannelConfigOverrides, ChannelConfigUpdate};
use lightning::util::errors::APIError;
use lightning::util::persist::KVStore;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum};
use lightning::{impl_ser_tlv_based, impl_ser_tlv_based_enum};
use lightning_liquidity::lsps2::client::LSPS2InvoiceParameters;
use lightning_liquidity::lsps2::router::LSPS2_PAYMENT_METADATA_KEY;
use lightning_liquidity::lsps2::utils::compute_opening_fee;
use lightning_types::payment::{PaymentHash, PaymentPreimage};

Expand DownExpand Up@@ -78,7 +80,7 @@ pub struct HTLCLocator {
pub node_id: Option<PublicKey>,
}

impl_writeable_tlv_based!(HTLCLocator, {
impl_ser_tlv_based!(HTLCLocator, {
(1, channel_id, required),
(3, user_channel_id, option),
(5, node_id, option),
Expand DownExpand Up@@ -294,7 +296,7 @@ pub enum Event {
},
}

impl_writeable_tlv_based_enum!(Event,
impl_ser_tlv_based_enum!(Event,
(0, PaymentSuccessful) => {
(0, payment_hash, required),
(1, fee_paid_msat, option),
Expand DownExpand Up@@ -611,6 +613,21 @@ where
})
}

fn lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_metadata: Option<&BTreeMap<u64, Vec<u8>>>, payment_size_msat: u64,
) -> Option<u64> {
// For BOLT12 payments, the router encoded the negotiated LSPS2 invoice parameters in the
// payment metadata of any JIT-channel blinded payment paths it constructed. Recompute the
// maximum acceptable opening fee from the negotiated opening fee parameters.
let encoded_params = payment_metadata?.get(&LSPS2_PAYMENT_METADATA_KEY)?;
let invoice_params = LSPS2InvoiceParameters::read(&mut &encoded_params[..]).ok()?;
compute_opening_fee(
payment_size_msat,
invoice_params.opening_fee_params.min_fee_msat,
invoice_params.opening_fee_params.proportional as u64,
)
}

pub async fn handle_event(&self, event: LdkEvent) -> Result<(), ReplayEvent> {
match event {
LdkEvent::FundingGenerationReady {
Expand DownExpand Up@@ -798,13 +815,19 @@ where
.and_then(|metadata| {
Self::lsps2_max_total_opening_fee_msat(metadata, amount_msat)
}),
PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
Self::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_context.payment_metadata.as_ref(),
amount_msat + counterparty_skimmed_fee_msat,
)
},
_ => None,
};

let Some(max_total_opening_fee_msat) = max_total_opening_fee_msat else {
log_info!(
self.logger,
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid BOLT11 LSPS2 payment metadata",
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid LSPS2 payment metadata",
hex_utils::to_string(&payment_hash.0),
counterparty_skimmed_fee_msat,
);
Expand All@@ -828,18 +851,24 @@ where
match &info.kind {
PaymentKind::Bolt11 { .. } => {
let update = PaymentDetailsUpdate {
counterparty_skimmed_fee_msat: Some(Some(counterparty_skimmed_fee_msat)),
counterparty_skimmed_fee_msat: Some(Some(
counterparty_skimmed_fee_msat,
)),
..PaymentDetailsUpdate::new(payment_id)
};
match self.payment_store.update(update).await {
Ok(_) => (),
Err(e) => {
log_error!(self.logger, "Failed to access payment store: {}", e);
log_error!(
self.logger,
"Failed to access payment store: {}",
e
);
return Err(ReplayEvent());
},
};
},
_ => debug_assert!(false, "We only expect the counterparty to get away with withholding fees for BOLT11 payments."),
_ => {},
}
}
}
Expand DownExpand Up@@ -1725,15 +1754,24 @@ where

self.bump_tx_event_handler.handle_event(&bte).await;
},
LdkEvent::OnionMessageIntercepted { peer_node_id, message } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
LdkEvent::OnionMessageIntercepted { next_hop, message, .. } => match next_hop {
lightning::blinded_path::message::NextMessageHop::NodeId(peer_node_id) => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
);
}
},
lightning::blinded_path::message::NextMessageHop::ShortChannelId(scid) => {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
"Onion message intercepted for unknown SCID {}, ignoring",
scid
);
}
},
},
LdkEvent::OnionMessagePeerConnected { peer_node_id } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
Expand DownExpand Up@@ -1939,6 +1977,72 @@ mod tests {
);
}

#[test]
fn lsps2_bolt12_payment_metadata_decodes_fee_limit() {
use lightning_liquidity::lsps0::ser::LSPSDateTime;
use lightning_liquidity::lsps2::msgs::LSPS2OpeningFeeParams;

use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};

use std::str::FromStr;

let counterparty_node_id = PublicKey::from_secret_key(
&Secp256k1::new(),
&SecretKey::from_slice(&[42; 32]).unwrap(),
);
let invoice_params = LSPS2InvoiceParameters {
counterparty_node_id,
intercept_scid: 42,
cltv_expiry_delta: 144,
opening_fee_params: LSPS2OpeningFeeParams {
min_fee_msat: 21_000,
proportional: 10_000,
valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(),
min_lifetime: 144,
max_client_to_self_delay: 128,
min_payment_size_msat: 1,
max_payment_size_msat: 100_000_000,
promise: "promise".to_string(),
},
};

let mut payment_metadata = BTreeMap::new();
payment_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, invoice_params.encode());

// max(min_fee_msat, proportional * payment_size / 1_000_000) = max(21_000, 10_000_000)
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&payment_metadata),
1_000_000_000,
),
Some(10_000_000)
);

// Missing metadata, missing key, or malformed parameters are rejected.
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
None, 1_000_000,
),
None
);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&BTreeMap::new()),
1_000_000,
),
None
);
let mut malformed_metadata = BTreeMap::new();
malformed_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, vec![0xff]);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&malformed_metadata),
1_000_000,
),
None
);
}

#[test]
fn lsps2_payment_metadata_missing_or_malformed_limit_is_rejected() {
let empty_metadata = PaymentMetadata { lsps2_parameters: None }.encode();
Expand Down
2 changes: 1 addition & 1 deletion src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1270,7 +1270,7 @@ impl Bolt11Invoice {
}

/// Recover the payee's public key (only to be used if none was included in the invoice)
pub fn recover_payee_pub_key(&self) -> PublicKey {
pub fn recover_payee_pub_key(&self) -> Option<PublicKey> {
self.inner.recover_payee_pub_key()
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/io/vss_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ use bitcoin::bip32::{ChildNumber, Xpriv};
use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
use bitcoin::key::Secp256k1;
use bitcoin::Network;
use lightning::impl_writeable_tlv_based_enum;
use lightning::impl_ser_tlv_based_enum;
use lightning::io::{self, Error, ErrorKind};
use lightning::sign::{EntropySource as LdkEntropySource, RandomBytes};
use lightning::util::persist::KVStore;
Expand DownExpand Up@@ -65,7 +65,7 @@ enum VssSchemaVersion {
V1,
}

impl_writeable_tlv_based_enum!(VssSchemaVersion,
impl_ser_tlv_based_enum!(VssSchemaVersion,
(0, V0) => {},
(1, V1) => {},
);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT12 LSPS2 Support via persisted BOLT12 state by TheBlueMatt · Pull Request #964 · lightningdevkit/ldk-node · GitHub
Skip to content
Closed
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
26 changes: 13 additions & 13 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,16 +183,16 @@ harness = false
#vss-client-ng = { path = "../vss-client" }
#vss-client-ng = { git = "https://github.com/lightningdevkit/vss-client", branch = "main" }
#
#[patch."https://github.com/lightningdevkit/rust-lightning"]
#lightning = { path = "../rust-lightning/lightning" }
#lightning-types = { path = "../rust-lightning/lightning-types" }
#lightning-invoice = { path = "../rust-lightning/lightning-invoice" }
#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" }
#lightning-persister = { path = "../rust-lightning/lightning-persister" }
#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" }
#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" }
#lightning-block-sync = { path = "../rust-lightning/lightning-block-sync" }
#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync" }
#lightning-liquidity = { path = "../rust-lightning/lightning-liquidity" }
#lightning-macros = { path = "../rust-lightning/lightning-macros" }
#lightning-dns-resolver = { path = "../rust-lightning/lightning-dns-resolver" }
[patch."https://github.com/lightningdevkit/rust-lightning"]
lightning = { path = "../rust-lightning-3/lightning" }
lightning-types = { path = "../rust-lightning-3/lightning-types" }
lightning-invoice = { path = "../rust-lightning-3/lightning-invoice" }
lightning-net-tokio = { path = "../rust-lightning-3/lightning-net-tokio" }
lightning-persister = { path = "../rust-lightning-3/lightning-persister" }
lightning-background-processor = { path = "../rust-lightning-3/lightning-background-processor" }
lightning-rapid-gossip-sync = { path = "../rust-lightning-3/lightning-rapid-gossip-sync" }
lightning-block-sync = { path = "../rust-lightning-3/lightning-block-sync" }
lightning-transaction-sync = { path = "../rust-lightning-3/lightning-transaction-sync" }
lightning-liquidity = { path = "../rust-lightning-3/lightning-liquidity" }
lightning-macros = { path = "../rust-lightning-3/lightning-macros" }
lightning-dns-resolver = { path = "../rust-lightning-3/lightning-dns-resolver" }
56 changes: 53 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,6 +43,7 @@ use lightning::util::persist::{
use lightning::util::ser::ReadableArgs;
use lightning::util::sweep::OutputSweeper;
use lightning_dns_resolver::OMDomainResolver;
use lightning_liquidity::lsps2::router::LSPS2Router;
use vss_client::headers::VssHeaderProvider;

use crate::chain::ChainSource;
Expand DownExpand Up@@ -70,7 +71,7 @@ use crate::io::{
};
use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig};
use crate::lnurl_auth::LnurlAuth;
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
Expand DownExpand Up@@ -1762,13 +1763,17 @@ fn build_with_store_internal(
}

let scoring_fee_params = ProbabilisticScoringFeeParameters::default();
let router = Arc::new(DefaultRouter::new(
let inner_router = DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
scoring_fee_params,
));
);
// Wrap the default router to inject LSPS2 JIT-channel blinded payment paths into BOLT12
// invoices based on the latest invoice parameters negotiated with our configured LSPs. The
// LSPS2 client handler is wired up below, once the liquidity source is built.
let router = Arc::new(LSPS2Router::new(inner_router));

let mut user_config = default_user_config(&config);

Expand DownExpand Up@@ -1916,6 +1921,7 @@ fn build_with_store_internal(
Arc::clone(&channel_manager),
Arc::clone(&om_resolver),
IgnoringMessageHandler {},
false,
))
} else {
Arc::new(OnionMessenger::new(
Expand DownExpand Up@@ -1992,6 +1998,50 @@ fn build_with_store_internal(
let custom_message_handler =
Arc::new(NodeCustomMessageHandler::new(Arc::clone(&liquidity_source)));

// Wire up the LSPS2 client handler, having the router inject JIT-channel blinded payment
// paths based on the latest invoice parameters negotiated with our configured LSPs.
//
// Beforehand, wipe any parameters previously negotiated with LSPs that are no longer
// configured, making sure the router won't have payments routed through them anymore.
if let Some(lsps2_client_handler) =
liquidity_source.liquidity_manager().lsps2_client_handler_arc()
{
let stale_lsp_node_ids = lsps2_client_handler
.latest_invoice_params()
.into_iter()
.map(|invoice_params| invoice_params.counterparty_node_id)
.filter(|counterparty_node_id| {
!liquidity_source_config.map_or(false, |lsc| {
lsc.lsp_nodes.iter().any(|n| n.node_id == *counterparty_node_id)
})
})
.collect::<Vec<_>>();

for counterparty_node_id in stale_lsp_node_ids {
let wipe_handler = Arc::clone(&lsps2_client_handler);
let wipe_logger = Arc::clone(&logger);
runtime.spawn_background_task(async move {
log_info!(
wipe_logger,
"Wiping LSPS2 invoice parameters previously negotiated with now-unconfigured LSP {}",
counterparty_node_id,
);
if let Err(e) =
wipe_handler.clear_latest_invoice_params(&counterparty_node_id).await
{
log_error!(
wipe_logger,
"Failed to wipe LSPS2 invoice parameters for LSP {}: {:?}",
counterparty_node_id,
e
);
}
});
}

router.set_lsps2_client_handler(lsps2_client_handler);
}

(liquidity_source, custom_message_handler)
};

Expand Down
6 changes: 3 additions & 3 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -218,7 +218,7 @@ where

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::impl_ser_tlv_based;
use lightning::util::test_utils::TestLogger;

use super::*;
Expand All@@ -236,7 +236,7 @@ mod tests {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });
impl_ser_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
Expand DownExpand Up@@ -276,7 +276,7 @@ mod tests {
}
}

impl_writeable_tlv_based!(TestObject, {
impl_ser_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});
Expand Down
132 changes: 118 additions & 14 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@

use core::future::Future;
use core::task::{Poll, Waker};
use std::collections::VecDeque;
use std::collections::{BTreeMap, VecDeque};
use std::ops::Deref;
use std::sync::{Arc, Mutex};

Expand All@@ -29,7 +29,9 @@ use lightning::util::config::{ChannelConfigOverrides, ChannelConfigUpdate};
use lightning::util::errors::APIError;
use lightning::util::persist::KVStore;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum};
use lightning::{impl_ser_tlv_based, impl_ser_tlv_based_enum};
use lightning_liquidity::lsps2::client::LSPS2InvoiceParameters;
use lightning_liquidity::lsps2::router::LSPS2_PAYMENT_METADATA_KEY;
use lightning_liquidity::lsps2::utils::compute_opening_fee;
use lightning_types::payment::{PaymentHash, PaymentPreimage};

Expand DownExpand Up@@ -78,7 +80,7 @@ pub struct HTLCLocator {
pub node_id: Option<PublicKey>,
}

impl_writeable_tlv_based!(HTLCLocator, {
impl_ser_tlv_based!(HTLCLocator, {
(1, channel_id, required),
(3, user_channel_id, option),
(5, node_id, option),
Expand DownExpand Up@@ -294,7 +296,7 @@ pub enum Event {
},
}

impl_writeable_tlv_based_enum!(Event,
impl_ser_tlv_based_enum!(Event,
(0, PaymentSuccessful) => {
(0, payment_hash, required),
(1, fee_paid_msat, option),
Expand DownExpand Up@@ -611,6 +613,21 @@ where
})
}

fn lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_metadata: Option<&BTreeMap<u64, Vec<u8>>>, payment_size_msat: u64,
) -> Option<u64> {
// For BOLT12 payments, the router encoded the negotiated LSPS2 invoice parameters in the
// payment metadata of any JIT-channel blinded payment paths it constructed. Recompute the
// maximum acceptable opening fee from the negotiated opening fee parameters.
let encoded_params = payment_metadata?.get(&LSPS2_PAYMENT_METADATA_KEY)?;
let invoice_params = LSPS2InvoiceParameters::read(&mut &encoded_params[..]).ok()?;
compute_opening_fee(
payment_size_msat,
invoice_params.opening_fee_params.min_fee_msat,
invoice_params.opening_fee_params.proportional as u64,
)
}

pub async fn handle_event(&self, event: LdkEvent) -> Result<(), ReplayEvent> {
match event {
LdkEvent::FundingGenerationReady {
Expand DownExpand Up@@ -798,13 +815,19 @@ where
.and_then(|metadata| {
Self::lsps2_max_total_opening_fee_msat(metadata, amount_msat)
}),
PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
Self::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_context.payment_metadata.as_ref(),
amount_msat + counterparty_skimmed_fee_msat,
)
},
_ => None,
};

let Some(max_total_opening_fee_msat) = max_total_opening_fee_msat else {
log_info!(
self.logger,
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid BOLT11 LSPS2 payment metadata",
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid LSPS2 payment metadata",
hex_utils::to_string(&payment_hash.0),
counterparty_skimmed_fee_msat,
);
Expand All@@ -828,18 +851,24 @@ where
match &info.kind {
PaymentKind::Bolt11 { .. } => {
let update = PaymentDetailsUpdate {
counterparty_skimmed_fee_msat: Some(Some(counterparty_skimmed_fee_msat)),
counterparty_skimmed_fee_msat: Some(Some(
counterparty_skimmed_fee_msat,
)),
..PaymentDetailsUpdate::new(payment_id)
};
match self.payment_store.update(update).await {
Ok(_) => (),
Err(e) => {
log_error!(self.logger, "Failed to access payment store: {}", e);
log_error!(
self.logger,
"Failed to access payment store: {}",
e
);
return Err(ReplayEvent());
},
};
},
_ => debug_assert!(false, "We only expect the counterparty to get away with withholding fees for BOLT11 payments."),
_ => {},
}
}
}
Expand DownExpand Up@@ -1725,15 +1754,24 @@ where

self.bump_tx_event_handler.handle_event(&bte).await;
},
LdkEvent::OnionMessageIntercepted { peer_node_id, message } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
LdkEvent::OnionMessageIntercepted { next_hop, message, .. } => match next_hop {
lightning::blinded_path::message::NextMessageHop::NodeId(peer_node_id) => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
);
}
},
lightning::blinded_path::message::NextMessageHop::ShortChannelId(scid) => {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
"Onion message intercepted for unknown SCID {}, ignoring",
scid
);
}
},
},
LdkEvent::OnionMessagePeerConnected { peer_node_id } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
Expand DownExpand Up@@ -1939,6 +1977,72 @@ mod tests {
);
}

#[test]
fn lsps2_bolt12_payment_metadata_decodes_fee_limit() {
use lightning_liquidity::lsps0::ser::LSPSDateTime;
use lightning_liquidity::lsps2::msgs::LSPS2OpeningFeeParams;

use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};

use std::str::FromStr;

let counterparty_node_id = PublicKey::from_secret_key(
&Secp256k1::new(),
&SecretKey::from_slice(&[42; 32]).unwrap(),
);
let invoice_params = LSPS2InvoiceParameters {
counterparty_node_id,
intercept_scid: 42,
cltv_expiry_delta: 144,
opening_fee_params: LSPS2OpeningFeeParams {
min_fee_msat: 21_000,
proportional: 10_000,
valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(),
min_lifetime: 144,
max_client_to_self_delay: 128,
min_payment_size_msat: 1,
max_payment_size_msat: 100_000_000,
promise: "promise".to_string(),
},
};

let mut payment_metadata = BTreeMap::new();
payment_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, invoice_params.encode());

// max(min_fee_msat, proportional * payment_size / 1_000_000) = max(21_000, 10_000_000)
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&payment_metadata),
1_000_000_000,
),
Some(10_000_000)
);

// Missing metadata, missing key, or malformed parameters are rejected.
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
None, 1_000_000,
),
None
);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&BTreeMap::new()),
1_000_000,
),
None
);
let mut malformed_metadata = BTreeMap::new();
malformed_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, vec![0xff]);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&malformed_metadata),
1_000_000,
),
None
);
}

#[test]
fn lsps2_payment_metadata_missing_or_malformed_limit_is_rejected() {
let empty_metadata = PaymentMetadata { lsps2_parameters: None }.encode();
Expand Down
2 changes: 1 addition & 1 deletion src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1270,7 +1270,7 @@ impl Bolt11Invoice {
}

/// Recover the payee's public key (only to be used if none was included in the invoice)
pub fn recover_payee_pub_key(&self) -> PublicKey {
pub fn recover_payee_pub_key(&self) -> Option<PublicKey> {
self.inner.recover_payee_pub_key()
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/io/vss_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ use bitcoin::bip32::{ChildNumber, Xpriv};
use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
use bitcoin::key::Secp256k1;
use bitcoin::Network;
use lightning::impl_writeable_tlv_based_enum;
use lightning::impl_ser_tlv_based_enum;
use lightning::io::{self, Error, ErrorKind};
use lightning::sign::{EntropySource as LdkEntropySource, RandomBytes};
use lightning::util::persist::KVStore;
Expand DownExpand Up@@ -65,7 +65,7 @@ enum VssSchemaVersion {
V1,
}

impl_writeable_tlv_based_enum!(VssSchemaVersion,
impl_ser_tlv_based_enum!(VssSchemaVersion,
(0, V0) => {},
(1, V1) => {},
);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT12 LSPS2 Support via persisted BOLT12 state by TheBlueMatt · Pull Request #964 · lightningdevkit/ldk-node · GitHub
Skip to content
Closed
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
26 changes: 13 additions & 13 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,16 +183,16 @@ harness = false
#vss-client-ng = { path = "../vss-client" }
#vss-client-ng = { git = "https://github.com/lightningdevkit/vss-client", branch = "main" }
#
#[patch."https://github.com/lightningdevkit/rust-lightning"]
#lightning = { path = "../rust-lightning/lightning" }
#lightning-types = { path = "../rust-lightning/lightning-types" }
#lightning-invoice = { path = "../rust-lightning/lightning-invoice" }
#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" }
#lightning-persister = { path = "../rust-lightning/lightning-persister" }
#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" }
#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" }
#lightning-block-sync = { path = "../rust-lightning/lightning-block-sync" }
#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync" }
#lightning-liquidity = { path = "../rust-lightning/lightning-liquidity" }
#lightning-macros = { path = "../rust-lightning/lightning-macros" }
#lightning-dns-resolver = { path = "../rust-lightning/lightning-dns-resolver" }
[patch."https://github.com/lightningdevkit/rust-lightning"]
lightning = { path = "../rust-lightning-3/lightning" }
lightning-types = { path = "../rust-lightning-3/lightning-types" }
lightning-invoice = { path = "../rust-lightning-3/lightning-invoice" }
lightning-net-tokio = { path = "../rust-lightning-3/lightning-net-tokio" }
lightning-persister = { path = "../rust-lightning-3/lightning-persister" }
lightning-background-processor = { path = "../rust-lightning-3/lightning-background-processor" }
lightning-rapid-gossip-sync = { path = "../rust-lightning-3/lightning-rapid-gossip-sync" }
lightning-block-sync = { path = "../rust-lightning-3/lightning-block-sync" }
lightning-transaction-sync = { path = "../rust-lightning-3/lightning-transaction-sync" }
lightning-liquidity = { path = "../rust-lightning-3/lightning-liquidity" }
lightning-macros = { path = "../rust-lightning-3/lightning-macros" }
lightning-dns-resolver = { path = "../rust-lightning-3/lightning-dns-resolver" }
56 changes: 53 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,6 +43,7 @@ use lightning::util::persist::{
use lightning::util::ser::ReadableArgs;
use lightning::util::sweep::OutputSweeper;
use lightning_dns_resolver::OMDomainResolver;
use lightning_liquidity::lsps2::router::LSPS2Router;
use vss_client::headers::VssHeaderProvider;

use crate::chain::ChainSource;
Expand DownExpand Up@@ -70,7 +71,7 @@ use crate::io::{
};
use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig};
use crate::lnurl_auth::LnurlAuth;
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
Expand DownExpand Up@@ -1762,13 +1763,17 @@ fn build_with_store_internal(
}

let scoring_fee_params = ProbabilisticScoringFeeParameters::default();
let router = Arc::new(DefaultRouter::new(
let inner_router = DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
scoring_fee_params,
));
);
// Wrap the default router to inject LSPS2 JIT-channel blinded payment paths into BOLT12
// invoices based on the latest invoice parameters negotiated with our configured LSPs. The
// LSPS2 client handler is wired up below, once the liquidity source is built.
let router = Arc::new(LSPS2Router::new(inner_router));

let mut user_config = default_user_config(&config);

Expand DownExpand Up@@ -1916,6 +1921,7 @@ fn build_with_store_internal(
Arc::clone(&channel_manager),
Arc::clone(&om_resolver),
IgnoringMessageHandler {},
false,
))
} else {
Arc::new(OnionMessenger::new(
Expand DownExpand Up@@ -1992,6 +1998,50 @@ fn build_with_store_internal(
let custom_message_handler =
Arc::new(NodeCustomMessageHandler::new(Arc::clone(&liquidity_source)));

// Wire up the LSPS2 client handler, having the router inject JIT-channel blinded payment
// paths based on the latest invoice parameters negotiated with our configured LSPs.
//
// Beforehand, wipe any parameters previously negotiated with LSPs that are no longer
// configured, making sure the router won't have payments routed through them anymore.
if let Some(lsps2_client_handler) =
liquidity_source.liquidity_manager().lsps2_client_handler_arc()
{
let stale_lsp_node_ids = lsps2_client_handler
.latest_invoice_params()
.into_iter()
.map(|invoice_params| invoice_params.counterparty_node_id)
.filter(|counterparty_node_id| {
!liquidity_source_config.map_or(false, |lsc| {
lsc.lsp_nodes.iter().any(|n| n.node_id == *counterparty_node_id)
})
})
.collect::<Vec<_>>();

for counterparty_node_id in stale_lsp_node_ids {
let wipe_handler = Arc::clone(&lsps2_client_handler);
let wipe_logger = Arc::clone(&logger);
runtime.spawn_background_task(async move {
log_info!(
wipe_logger,
"Wiping LSPS2 invoice parameters previously negotiated with now-unconfigured LSP {}",
counterparty_node_id,
);
if let Err(e) =
wipe_handler.clear_latest_invoice_params(&counterparty_node_id).await
{
log_error!(
wipe_logger,
"Failed to wipe LSPS2 invoice parameters for LSP {}: {:?}",
counterparty_node_id,
e
);
}
});
}

router.set_lsps2_client_handler(lsps2_client_handler);
}

(liquidity_source, custom_message_handler)
};

Expand Down
6 changes: 3 additions & 3 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -218,7 +218,7 @@ where

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::impl_ser_tlv_based;
use lightning::util::test_utils::TestLogger;

use super::*;
Expand All@@ -236,7 +236,7 @@ mod tests {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });
impl_ser_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
Expand DownExpand Up@@ -276,7 +276,7 @@ mod tests {
}
}

impl_writeable_tlv_based!(TestObject, {
impl_ser_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});
Expand Down
132 changes: 118 additions & 14 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@

use core::future::Future;
use core::task::{Poll, Waker};
use std::collections::VecDeque;
use std::collections::{BTreeMap, VecDeque};
use std::ops::Deref;
use std::sync::{Arc, Mutex};

Expand All@@ -29,7 +29,9 @@ use lightning::util::config::{ChannelConfigOverrides, ChannelConfigUpdate};
use lightning::util::errors::APIError;
use lightning::util::persist::KVStore;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum};
use lightning::{impl_ser_tlv_based, impl_ser_tlv_based_enum};
use lightning_liquidity::lsps2::client::LSPS2InvoiceParameters;
use lightning_liquidity::lsps2::router::LSPS2_PAYMENT_METADATA_KEY;
use lightning_liquidity::lsps2::utils::compute_opening_fee;
use lightning_types::payment::{PaymentHash, PaymentPreimage};

Expand DownExpand Up@@ -78,7 +80,7 @@ pub struct HTLCLocator {
pub node_id: Option<PublicKey>,
}

impl_writeable_tlv_based!(HTLCLocator, {
impl_ser_tlv_based!(HTLCLocator, {
(1, channel_id, required),
(3, user_channel_id, option),
(5, node_id, option),
Expand DownExpand Up@@ -294,7 +296,7 @@ pub enum Event {
},
}

impl_writeable_tlv_based_enum!(Event,
impl_ser_tlv_based_enum!(Event,
(0, PaymentSuccessful) => {
(0, payment_hash, required),
(1, fee_paid_msat, option),
Expand DownExpand Up@@ -611,6 +613,21 @@ where
})
}

fn lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_metadata: Option<&BTreeMap<u64, Vec<u8>>>, payment_size_msat: u64,
) -> Option<u64> {
// For BOLT12 payments, the router encoded the negotiated LSPS2 invoice parameters in the
// payment metadata of any JIT-channel blinded payment paths it constructed. Recompute the
// maximum acceptable opening fee from the negotiated opening fee parameters.
let encoded_params = payment_metadata?.get(&LSPS2_PAYMENT_METADATA_KEY)?;
let invoice_params = LSPS2InvoiceParameters::read(&mut &encoded_params[..]).ok()?;
compute_opening_fee(
payment_size_msat,
invoice_params.opening_fee_params.min_fee_msat,
invoice_params.opening_fee_params.proportional as u64,
)
}

pub async fn handle_event(&self, event: LdkEvent) -> Result<(), ReplayEvent> {
match event {
LdkEvent::FundingGenerationReady {
Expand DownExpand Up@@ -798,13 +815,19 @@ where
.and_then(|metadata| {
Self::lsps2_max_total_opening_fee_msat(metadata, amount_msat)
}),
PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
Self::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_context.payment_metadata.as_ref(),
amount_msat + counterparty_skimmed_fee_msat,
)
},
_ => None,
};

let Some(max_total_opening_fee_msat) = max_total_opening_fee_msat else {
log_info!(
self.logger,
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid BOLT11 LSPS2 payment metadata",
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid LSPS2 payment metadata",
hex_utils::to_string(&payment_hash.0),
counterparty_skimmed_fee_msat,
);
Expand All@@ -828,18 +851,24 @@ where
match &info.kind {
PaymentKind::Bolt11 { .. } => {
let update = PaymentDetailsUpdate {
counterparty_skimmed_fee_msat: Some(Some(counterparty_skimmed_fee_msat)),
counterparty_skimmed_fee_msat: Some(Some(
counterparty_skimmed_fee_msat,
)),
..PaymentDetailsUpdate::new(payment_id)
};
match self.payment_store.update(update).await {
Ok(_) => (),
Err(e) => {
log_error!(self.logger, "Failed to access payment store: {}", e);
log_error!(
self.logger,
"Failed to access payment store: {}",
e
);
return Err(ReplayEvent());
},
};
},
_ => debug_assert!(false, "We only expect the counterparty to get away with withholding fees for BOLT11 payments."),
_ => {},
}
}
}
Expand DownExpand Up@@ -1725,15 +1754,24 @@ where

self.bump_tx_event_handler.handle_event(&bte).await;
},
LdkEvent::OnionMessageIntercepted { peer_node_id, message } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
LdkEvent::OnionMessageIntercepted { next_hop, message, .. } => match next_hop {
lightning::blinded_path::message::NextMessageHop::NodeId(peer_node_id) => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
);
}
},
lightning::blinded_path::message::NextMessageHop::ShortChannelId(scid) => {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
"Onion message intercepted for unknown SCID {}, ignoring",
scid
);
}
},
},
LdkEvent::OnionMessagePeerConnected { peer_node_id } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
Expand DownExpand Up@@ -1939,6 +1977,72 @@ mod tests {
);
}

#[test]
fn lsps2_bolt12_payment_metadata_decodes_fee_limit() {
use lightning_liquidity::lsps0::ser::LSPSDateTime;
use lightning_liquidity::lsps2::msgs::LSPS2OpeningFeeParams;

use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};

use std::str::FromStr;

let counterparty_node_id = PublicKey::from_secret_key(
&Secp256k1::new(),
&SecretKey::from_slice(&[42; 32]).unwrap(),
);
let invoice_params = LSPS2InvoiceParameters {
counterparty_node_id,
intercept_scid: 42,
cltv_expiry_delta: 144,
opening_fee_params: LSPS2OpeningFeeParams {
min_fee_msat: 21_000,
proportional: 10_000,
valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(),
min_lifetime: 144,
max_client_to_self_delay: 128,
min_payment_size_msat: 1,
max_payment_size_msat: 100_000_000,
promise: "promise".to_string(),
},
};

let mut payment_metadata = BTreeMap::new();
payment_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, invoice_params.encode());

// max(min_fee_msat, proportional * payment_size / 1_000_000) = max(21_000, 10_000_000)
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&payment_metadata),
1_000_000_000,
),
Some(10_000_000)
);

// Missing metadata, missing key, or malformed parameters are rejected.
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
None, 1_000_000,
),
None
);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&BTreeMap::new()),
1_000_000,
),
None
);
let mut malformed_metadata = BTreeMap::new();
malformed_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, vec![0xff]);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&malformed_metadata),
1_000_000,
),
None
);
}

#[test]
fn lsps2_payment_metadata_missing_or_malformed_limit_is_rejected() {
let empty_metadata = PaymentMetadata { lsps2_parameters: None }.encode();
Expand Down
2 changes: 1 addition & 1 deletion src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1270,7 +1270,7 @@ impl Bolt11Invoice {
}

/// Recover the payee's public key (only to be used if none was included in the invoice)
pub fn recover_payee_pub_key(&self) -> PublicKey {
pub fn recover_payee_pub_key(&self) -> Option<PublicKey> {
self.inner.recover_payee_pub_key()
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/io/vss_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ use bitcoin::bip32::{ChildNumber, Xpriv};
use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
use bitcoin::key::Secp256k1;
use bitcoin::Network;
use lightning::impl_writeable_tlv_based_enum;
use lightning::impl_ser_tlv_based_enum;
use lightning::io::{self, Error, ErrorKind};
use lightning::sign::{EntropySource as LdkEntropySource, RandomBytes};
use lightning::util::persist::KVStore;
Expand DownExpand Up@@ -65,7 +65,7 @@ enum VssSchemaVersion {
V1,
}

impl_writeable_tlv_based_enum!(VssSchemaVersion,
impl_ser_tlv_based_enum!(VssSchemaVersion,
(0, V0) => {},
(1, V1) => {},
);
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); BOLT12 LSPS2 Support via persisted BOLT12 state by TheBlueMatt · Pull Request #964 · lightningdevkit/ldk-node · GitHub
Skip to content
Closed
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
26 changes: 13 additions & 13 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -183,16 +183,16 @@ harness = false
#vss-client-ng = { path = "../vss-client" }
#vss-client-ng = { git = "https://github.com/lightningdevkit/vss-client", branch = "main" }
#
#[patch."https://github.com/lightningdevkit/rust-lightning"]
#lightning = { path = "../rust-lightning/lightning" }
#lightning-types = { path = "../rust-lightning/lightning-types" }
#lightning-invoice = { path = "../rust-lightning/lightning-invoice" }
#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" }
#lightning-persister = { path = "../rust-lightning/lightning-persister" }
#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" }
#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" }
#lightning-block-sync = { path = "../rust-lightning/lightning-block-sync" }
#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync" }
#lightning-liquidity = { path = "../rust-lightning/lightning-liquidity" }
#lightning-macros = { path = "../rust-lightning/lightning-macros" }
#lightning-dns-resolver = { path = "../rust-lightning/lightning-dns-resolver" }
[patch."https://github.com/lightningdevkit/rust-lightning"]
lightning = { path = "../rust-lightning-3/lightning" }
lightning-types = { path = "../rust-lightning-3/lightning-types" }
lightning-invoice = { path = "../rust-lightning-3/lightning-invoice" }
lightning-net-tokio = { path = "../rust-lightning-3/lightning-net-tokio" }
lightning-persister = { path = "../rust-lightning-3/lightning-persister" }
lightning-background-processor = { path = "../rust-lightning-3/lightning-background-processor" }
lightning-rapid-gossip-sync = { path = "../rust-lightning-3/lightning-rapid-gossip-sync" }
lightning-block-sync = { path = "../rust-lightning-3/lightning-block-sync" }
lightning-transaction-sync = { path = "../rust-lightning-3/lightning-transaction-sync" }
lightning-liquidity = { path = "../rust-lightning-3/lightning-liquidity" }
lightning-macros = { path = "../rust-lightning-3/lightning-macros" }
lightning-dns-resolver = { path = "../rust-lightning-3/lightning-dns-resolver" }
56 changes: 53 additions & 3 deletions src/builder.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -43,6 +43,7 @@ use lightning::util::persist::{
use lightning::util::ser::ReadableArgs;
use lightning::util::sweep::OutputSweeper;
use lightning_dns_resolver::OMDomainResolver;
use lightning_liquidity::lsps2::router::LSPS2Router;
use vss_client::headers::VssHeaderProvider;

use crate::chain::ChainSource;
Expand DownExpand Up@@ -70,7 +71,7 @@ use crate::io::{
};
use crate::liquidity::{LSPS2ServiceConfig, LiquiditySourceBuilder, LspConfig};
use crate::lnurl_auth::LnurlAuth;
use crate::logger::{log_error, LdkLogger, LogLevel, LogWriter, Logger};
use crate::logger::{log_error, log_info, LdkLogger, LogLevel, LogWriter, Logger};
use crate::message_handler::NodeCustomMessageHandler;
use crate::payment::asynchronous::om_mailbox::OnionMessageMailbox;
use crate::peer_store::PeerStore;
Expand DownExpand Up@@ -1762,13 +1763,17 @@ fn build_with_store_internal(
}

let scoring_fee_params = ProbabilisticScoringFeeParameters::default();
let router = Arc::new(DefaultRouter::new(
let inner_router = DefaultRouter::new(
Arc::clone(&network_graph),
Arc::clone(&logger),
Arc::clone(&keys_manager),
Arc::clone(&scorer),
scoring_fee_params,
));
);
// Wrap the default router to inject LSPS2 JIT-channel blinded payment paths into BOLT12
// invoices based on the latest invoice parameters negotiated with our configured LSPs. The
// LSPS2 client handler is wired up below, once the liquidity source is built.
let router = Arc::new(LSPS2Router::new(inner_router));

let mut user_config = default_user_config(&config);

Expand DownExpand Up@@ -1916,6 +1921,7 @@ fn build_with_store_internal(
Arc::clone(&channel_manager),
Arc::clone(&om_resolver),
IgnoringMessageHandler {},
false,
))
} else {
Arc::new(OnionMessenger::new(
Expand DownExpand Up@@ -1992,6 +1998,50 @@ fn build_with_store_internal(
let custom_message_handler =
Arc::new(NodeCustomMessageHandler::new(Arc::clone(&liquidity_source)));

// Wire up the LSPS2 client handler, having the router inject JIT-channel blinded payment
// paths based on the latest invoice parameters negotiated with our configured LSPs.
//
// Beforehand, wipe any parameters previously negotiated with LSPs that are no longer
// configured, making sure the router won't have payments routed through them anymore.
if let Some(lsps2_client_handler) =
liquidity_source.liquidity_manager().lsps2_client_handler_arc()
{
let stale_lsp_node_ids = lsps2_client_handler
.latest_invoice_params()
.into_iter()
.map(|invoice_params| invoice_params.counterparty_node_id)
.filter(|counterparty_node_id| {
!liquidity_source_config.map_or(false, |lsc| {
lsc.lsp_nodes.iter().any(|n| n.node_id == *counterparty_node_id)
})
})
.collect::<Vec<_>>();

for counterparty_node_id in stale_lsp_node_ids {
let wipe_handler = Arc::clone(&lsps2_client_handler);
let wipe_logger = Arc::clone(&logger);
runtime.spawn_background_task(async move {
log_info!(
wipe_logger,
"Wiping LSPS2 invoice parameters previously negotiated with now-unconfigured LSP {}",
counterparty_node_id,
);
if let Err(e) =
wipe_handler.clear_latest_invoice_params(&counterparty_node_id).await
{
log_error!(
wipe_logger,
"Failed to wipe LSPS2 invoice parameters for LSP {}: {:?}",
counterparty_node_id,
e
);
}
});
}

router.set_lsps2_client_handler(lsps2_client_handler);
}

(liquidity_source, custom_message_handler)
};

Expand Down
6 changes: 3 additions & 3 deletions src/data_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -218,7 +218,7 @@ where

#[cfg(test)]
mod tests {
use lightning::impl_writeable_tlv_based;
use lightning::impl_ser_tlv_based;
use lightning::util::test_utils::TestLogger;

use super::*;
Expand All@@ -236,7 +236,7 @@ mod tests {
hex_utils::to_string(&self.id)
}
}
impl_writeable_tlv_based!(TestObjectId, { (0, id, required) });
impl_ser_tlv_based!(TestObjectId, { (0, id, required) });

struct TestObjectUpdate {
id: TestObjectId,
Expand DownExpand Up@@ -276,7 +276,7 @@ mod tests {
}
}

impl_writeable_tlv_based!(TestObject, {
impl_ser_tlv_based!(TestObject, {
(0, id, required),
(2, data, required),
});
Expand Down
132 changes: 118 additions & 14 deletions src/event.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@

use core::future::Future;
use core::task::{Poll, Waker};
use std::collections::VecDeque;
use std::collections::{BTreeMap, VecDeque};
use std::ops::Deref;
use std::sync::{Arc, Mutex};

Expand All@@ -29,7 +29,9 @@ use lightning::util::config::{ChannelConfigOverrides, ChannelConfigUpdate};
use lightning::util::errors::APIError;
use lightning::util::persist::KVStore;
use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use lightning::{impl_writeable_tlv_based, impl_writeable_tlv_based_enum};
use lightning::{impl_ser_tlv_based, impl_ser_tlv_based_enum};
use lightning_liquidity::lsps2::client::LSPS2InvoiceParameters;
use lightning_liquidity::lsps2::router::LSPS2_PAYMENT_METADATA_KEY;
use lightning_liquidity::lsps2::utils::compute_opening_fee;
use lightning_types::payment::{PaymentHash, PaymentPreimage};

Expand DownExpand Up@@ -78,7 +80,7 @@ pub struct HTLCLocator {
pub node_id: Option<PublicKey>,
}

impl_writeable_tlv_based!(HTLCLocator, {
impl_ser_tlv_based!(HTLCLocator, {
(1, channel_id, required),
(3, user_channel_id, option),
(5, node_id, option),
Expand DownExpand Up@@ -294,7 +296,7 @@ pub enum Event {
},
}

impl_writeable_tlv_based_enum!(Event,
impl_ser_tlv_based_enum!(Event,
(0, PaymentSuccessful) => {
(0, payment_hash, required),
(1, fee_paid_msat, option),
Expand DownExpand Up@@ -611,6 +613,21 @@ where
})
}

fn lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_metadata: Option<&BTreeMap<u64, Vec<u8>>>, payment_size_msat: u64,
) -> Option<u64> {
// For BOLT12 payments, the router encoded the negotiated LSPS2 invoice parameters in the
// payment metadata of any JIT-channel blinded payment paths it constructed. Recompute the
// maximum acceptable opening fee from the negotiated opening fee parameters.
let encoded_params = payment_metadata?.get(&LSPS2_PAYMENT_METADATA_KEY)?;
let invoice_params = LSPS2InvoiceParameters::read(&mut &encoded_params[..]).ok()?;
compute_opening_fee(
payment_size_msat,
invoice_params.opening_fee_params.min_fee_msat,
invoice_params.opening_fee_params.proportional as u64,
)
}

pub async fn handle_event(&self, event: LdkEvent) -> Result<(), ReplayEvent> {
match event {
LdkEvent::FundingGenerationReady {
Expand DownExpand Up@@ -798,13 +815,19 @@ where
.and_then(|metadata| {
Self::lsps2_max_total_opening_fee_msat(metadata, amount_msat)
}),
PaymentPurpose::Bolt12OfferPayment { payment_context, .. } => {
Self::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
payment_context.payment_metadata.as_ref(),
amount_msat + counterparty_skimmed_fee_msat,
)
},
_ => None,
};

let Some(max_total_opening_fee_msat) = max_total_opening_fee_msat else {
log_info!(
self.logger,
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid BOLT11 LSPS2 payment metadata",
"Refusing inbound payment with hash {} as the counterparty withheld {}msat without valid LSPS2 payment metadata",
hex_utils::to_string(&payment_hash.0),
counterparty_skimmed_fee_msat,
);
Expand All@@ -828,18 +851,24 @@ where
match &info.kind {
PaymentKind::Bolt11 { .. } => {
let update = PaymentDetailsUpdate {
counterparty_skimmed_fee_msat: Some(Some(counterparty_skimmed_fee_msat)),
counterparty_skimmed_fee_msat: Some(Some(
counterparty_skimmed_fee_msat,
)),
..PaymentDetailsUpdate::new(payment_id)
};
match self.payment_store.update(update).await {
Ok(_) => (),
Err(e) => {
log_error!(self.logger, "Failed to access payment store: {}", e);
log_error!(
self.logger,
"Failed to access payment store: {}",
e
);
return Err(ReplayEvent());
},
};
},
_ => debug_assert!(false, "We only expect the counterparty to get away with withholding fees for BOLT11 payments."),
_ => {},
}
}
}
Expand DownExpand Up@@ -1725,15 +1754,24 @@ where

self.bump_tx_event_handler.handle_event(&bte).await;
},
LdkEvent::OnionMessageIntercepted { peer_node_id, message } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
LdkEvent::OnionMessageIntercepted { next_hop, message, .. } => match next_hop {
lightning::blinded_path::message::NextMessageHop::NodeId(peer_node_id) => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
om_mailbox.onion_message_intercepted(peer_node_id, message);
} else {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
);
}
},
lightning::blinded_path::message::NextMessageHop::ShortChannelId(scid) => {
log_trace!(
self.logger,
"Onion message intercepted, but no onion message mailbox available"
"Onion message intercepted for unknown SCID {}, ignoring",
scid
);
}
},
},
LdkEvent::OnionMessagePeerConnected { peer_node_id } => {
if let Some(om_mailbox) = self.om_mailbox.as_ref() {
Expand DownExpand Up@@ -1939,6 +1977,72 @@ mod tests {
);
}

#[test]
fn lsps2_bolt12_payment_metadata_decodes_fee_limit() {
use lightning_liquidity::lsps0::ser::LSPSDateTime;
use lightning_liquidity::lsps2::msgs::LSPS2OpeningFeeParams;

use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};

use std::str::FromStr;

let counterparty_node_id = PublicKey::from_secret_key(
&Secp256k1::new(),
&SecretKey::from_slice(&[42; 32]).unwrap(),
);
let invoice_params = LSPS2InvoiceParameters {
counterparty_node_id,
intercept_scid: 42,
cltv_expiry_delta: 144,
opening_fee_params: LSPS2OpeningFeeParams {
min_fee_msat: 21_000,
proportional: 10_000,
valid_until: LSPSDateTime::from_str("2035-05-20T08:30:45Z").unwrap(),
min_lifetime: 144,
max_client_to_self_delay: 128,
min_payment_size_msat: 1,
max_payment_size_msat: 100_000_000,
promise: "promise".to_string(),
},
};

let mut payment_metadata = BTreeMap::new();
payment_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, invoice_params.encode());

// max(min_fee_msat, proportional * payment_size / 1_000_000) = max(21_000, 10_000_000)
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&payment_metadata),
1_000_000_000,
),
Some(10_000_000)
);

// Missing metadata, missing key, or malformed parameters are rejected.
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
None, 1_000_000,
),
None
);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&BTreeMap::new()),
1_000_000,
),
None
);
let mut malformed_metadata = BTreeMap::new();
malformed_metadata.insert(LSPS2_PAYMENT_METADATA_KEY, vec![0xff]);
assert_eq!(
EventHandler::<Arc<TestLogger>>::lsps2_max_total_opening_fee_msat_from_bolt12_metadata(
Some(&malformed_metadata),
1_000_000,
),
None
);
}

#[test]
fn lsps2_payment_metadata_missing_or_malformed_limit_is_rejected() {
let empty_metadata = PaymentMetadata { lsps2_parameters: None }.encode();
Expand Down
2 changes: 1 addition & 1 deletion src/ffi/types.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1270,7 +1270,7 @@ impl Bolt11Invoice {
}

/// Recover the payee's public key (only to be used if none was included in the invoice)
pub fn recover_payee_pub_key(&self) -> PublicKey {
pub fn recover_payee_pub_key(&self) -> Option<PublicKey> {
self.inner.recover_payee_pub_key()
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/io/vss_store.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -21,7 +21,7 @@ use bitcoin::bip32::{ChildNumber, Xpriv};
use bitcoin::hashes::{sha256, Hash, HashEngine, Hmac, HmacEngine};
use bitcoin::key::Secp256k1;
use bitcoin::Network;
use lightning::impl_writeable_tlv_based_enum;
use lightning::impl_ser_tlv_based_enum;
use lightning::io::{self, Error, ErrorKind};
use lightning::sign::{EntropySource as LdkEntropySource, RandomBytes};
use lightning::util::persist::KVStore;
Expand DownExpand Up@@ -65,7 +65,7 @@ enum VssSchemaVersion {
V1,
}

impl_writeable_tlv_based_enum!(VssSchemaVersion,
impl_ser_tlv_based_enum!(VssSchemaVersion,
(0, V0) => {},
(1, V1) => {},
);
Expand Down
Loading