Merged
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
8 changes: 4 additions & 4 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,17 +201,17 @@ interface Bolt11Payment {

interface Bolt12Payment {
[Throws=NodeError]
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note);
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note);
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive(u64 amount_msat, [ByRef]string description, u32? expiry_secs, u64? quantity);
[Throws=NodeError]
Offer receive_variable_amount([ByRef]string description, u32? expiry_secs);
[Throws=NodeError]
Bolt12Invoice request_refund_payment([ByRef]Refund refund);
[Throws=NodeError]
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note);
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive_async();
[Throws=NodeError]
Expand DownExpand Up@@ -256,7 +256,7 @@ interface UnifiedQrPayment {
[Throws=NodeError]
string receive(u64 amount_sats, [ByRef]string message, u32 expiry_sec);
[Throws=NodeError]
QrPaymentResult send([ByRef]string uri_str);
QrPaymentResult send([ByRef]string uri_str, RouteParametersConfig? route_parameters);
};

interface LSPS1Liquidity {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -854,6 +854,7 @@ impl Node {
Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand All@@ -868,6 +869,7 @@ impl Node {
Arc::new(Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand Down
35 changes: 25 additions & 10 deletions src/payment/bolt12.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ use lightning::util::ser::{Readable, Writeable};
use lightning_types::string::UntrustedString;
use rand::RngCore;

use crate::config::{AsyncPaymentsRole, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::config::{AsyncPaymentsRole, Config, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::error::Error;
use crate::ffi::{maybe_deref, maybe_wrap};
use crate::logger::{log_error, log_info, LdkLogger, Logger};
Expand DownExpand Up@@ -54,6 +54,7 @@ type Refund = Arc<crate::ffi::Refund>;
pub struct Bolt12Payment {
channel_manager: Arc<ChannelManager>,
payment_store: Arc<PaymentStore>,
config: Arc<Config>,
is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand All@@ -62,10 +63,10 @@ pub struct Bolt12Payment {
impl Bolt12Payment {
pub(crate) fn new(
channel_manager: Arc<ChannelManager>, payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
config: Arc<Config>, is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
) -> Self {
Self { channel_manager, payment_store, is_running, logger, async_payments_role }
Self { channel_manager, payment_store, config, is_running, logger, async_payments_role }
}

/// Send a payment given an offer.
Expand All@@ -74,8 +75,12 @@ impl Bolt12Payment {
/// response.
///
/// If `quantity` is `Some` it represents the number of items requested.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send(
&self, offer: &Offer, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure your feeling on this, but could avoid an additional Option parameter by chaining a call when creating Bolt12Payment:

node.bolt12_payment().with_route_params(route_params).send()

Though maybe an argument against is that it is specific to sending so not relevant to other calls. At very least, these aren't specific to a given Offer.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I guess that would make sense if we did the builder-style refactor eventually. Not necessarily opposed to it, but IMO if we would go in that direction we should probably consider refactor the payment APIs to be fully in builder -pattern style.

) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -87,7 +92,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -104,7 +110,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager
Expand DownExpand Up@@ -181,8 +187,12 @@ impl Bolt12Payment {
///
/// If `payer_note` is `Some` it will be seen by the recipient and reflected back in the invoice
/// response.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send_using_amount(
&self, offer: &Offer, amount_msat: u64, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -194,7 +204,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -215,7 +226,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager.pay_for_offer_with_quantity(
Expand DownExpand Up@@ -402,10 +413,13 @@ impl Bolt12Payment {

/// Returns a [`Refund`] object that can be used to offer a refund payment of the amount given.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [`Refund`]: lightning::offers::refund::Refund
pub fn initiate_refund(
&self, amount_msat: u64, expiry_secs: u32, quantity: Option<u64>,
payer_note: Option<String>,
payer_note: Option<String>, route_parameters: Option<RouteParametersConfig>,
) -> Result<Refund, Error> {
let mut random_bytes = [0u8; 32];
rand::rng().fill_bytes(&mut random_bytes);
Expand All@@ -415,7 +429,8 @@ impl Bolt12Payment {
.duration_since(UNIX_EPOCH)
.unwrap();
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let mut refund_builder = self
.channel_manager
Expand All@@ -424,7 +439,7 @@ impl Bolt12Payment {
absolute_expiry,
payment_id,
retry_strategy,
route_params_config,
route_parameters,
)
.map_err(|e| {
log_error!(self.logger, "Failed to create refund builder: {:?}", e);
Expand Down
12 changes: 9 additions & 3 deletions src/payment/unified_qr.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ use bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bitcoin::{Amount, Txid};
use lightning::ln::channelmanager::PaymentId;
use lightning::offers::offer::Offer;
use lightning::routing::router::RouteParametersConfig;
use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, Description};

use crate::error::Error;
Expand DownExpand Up@@ -137,8 +138,13 @@ impl UnifiedQrPayment {
/// Returns a `QrPaymentResult` indicating the outcome of the payment. If an error
/// occurs, an `Error` is returned detailing the issue encountered.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
pub fn send(&self, uri_str: &str) -> Result<QrPaymentResult, Error> {
pub fn send(
&self, uri_str: &str, route_parameters: Option<RouteParametersConfig>,
) -> Result<QrPaymentResult, Error> {
let uri: bip21::Uri<NetworkUnchecked, Extras> =
uri_str.parse().map_err(|_| Error::InvalidUri)?;

Expand All@@ -147,15 +153,15 @@ impl UnifiedQrPayment {

if let Some(offer) = uri_network_checked.extras.bolt12_offer {
let offer = maybe_wrap(offer);
match self.bolt12_payment.send(&offer, None, None) {
match self.bolt12_payment.send(&offer, None, None, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt12 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT12 offer: {:?}. This is part of a unified QR code payment. Falling back to the BOLT11 invoice.", e),
}
}

if let Some(invoice) = uri_network_checked.extras.bolt11_invoice {
let invoice = maybe_wrap(invoice);
match self.bolt11_invoice.send(&invoice, None) {
match self.bolt11_invoice.send(&invoice, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt11 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT11 invoice: {:?}. This is part of a unified QR code payment. Falling back to the on-chain transaction.", e),
}
Expand Down
21 changes: 14 additions & 7 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -967,7 +967,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let payment_id = node_a
.bolt12_payment()
.send(&offer, expected_quantity, expected_payer_note.clone())
.send(&offer, expected_quantity, expected_payer_note.clone(), None)
.unwrap();

expect_payment_successful_event!(node_a, Some(payment_id), None);
Expand DownExpand Up@@ -1023,7 +1023,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
assert!(node_a
.bolt12_payment()
.send_using_amount(&offer, less_than_offer_amount, None, None)
.send_using_amount(&offer, less_than_offer_amount, None, None, None)
.is_err());
let payment_id = node_a
.bolt12_payment()
Expand All@@ -1032,6 +1032,7 @@ async fn simple_bolt12_send_receive() {
expected_amount_msat,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();

Expand DownExpand Up@@ -1089,7 +1090,13 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let refund = node_b
.bolt12_payment()
.initiate_refund(overpaid_amount, 3600, expected_quantity, expected_payer_note.clone())
.initiate_refund(
overpaid_amount,
3600,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();
let invoice = node_a.bolt12_payment().request_refund_payment(&refund).unwrap();
expect_payment_received_event!(node_a, overpaid_amount);
Expand DownExpand Up@@ -1275,7 +1282,7 @@ async fn async_payment() {
node_receiver.stop().unwrap();

let payment_id =
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None).unwrap();
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None, None).unwrap();

// Sleep to allow the payment reach a state where the htlc is held and waiting for the receiver to come online.
tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
Expand DownExpand Up@@ -1473,7 +1480,7 @@ async fn unified_qr_send_receive() {

let uqr_payment = node_b.unified_qr_payment().receive(expected_amount_sats, "asdf", expiry_sec);
let uri_str = uqr_payment.clone().unwrap();
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str) {
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str, None) {
Ok(QrPaymentResult::Bolt12 { payment_id }) => {
println!("\nBolt12 payment sent successfully with PaymentID: {:?}", payment_id);
payment_id
Expand All@@ -1494,7 +1501,7 @@ async fn unified_qr_send_receive() {
// Cut off the BOLT12 part to fallback to BOLT11.
let uri_str_without_offer = uri_str.split("&lno=").next().unwrap();
let invoice_payment_id: PaymentId =
match node_a.unified_qr_payment().send(uri_str_without_offer) {
match node_a.unified_qr_payment().send(uri_str_without_offer, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected Bolt11 payment but got Bolt12");
},
Expand All@@ -1517,7 +1524,7 @@ async fn unified_qr_send_receive() {

// Cut off any lightning part to fallback to on-chain only.
let uri_str_without_lightning = onchain_uqr_payment.split("&lightning=").next().unwrap();
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning) {
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected on-chain payment but got Bolt12")
},
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n 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;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
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
8 changes: 4 additions & 4 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,17 +201,17 @@ interface Bolt11Payment {

interface Bolt12Payment {
[Throws=NodeError]
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note);
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note);
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive(u64 amount_msat, [ByRef]string description, u32? expiry_secs, u64? quantity);
[Throws=NodeError]
Offer receive_variable_amount([ByRef]string description, u32? expiry_secs);
[Throws=NodeError]
Bolt12Invoice request_refund_payment([ByRef]Refund refund);
[Throws=NodeError]
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note);
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive_async();
[Throws=NodeError]
Expand DownExpand Up@@ -256,7 +256,7 @@ interface UnifiedQrPayment {
[Throws=NodeError]
string receive(u64 amount_sats, [ByRef]string message, u32 expiry_sec);
[Throws=NodeError]
QrPaymentResult send([ByRef]string uri_str);
QrPaymentResult send([ByRef]string uri_str, RouteParametersConfig? route_parameters);
};

interface LSPS1Liquidity {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -854,6 +854,7 @@ impl Node {
Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand All@@ -868,6 +869,7 @@ impl Node {
Arc::new(Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand Down
35 changes: 25 additions & 10 deletions src/payment/bolt12.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ use lightning::util::ser::{Readable, Writeable};
use lightning_types::string::UntrustedString;
use rand::RngCore;

use crate::config::{AsyncPaymentsRole, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::config::{AsyncPaymentsRole, Config, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::error::Error;
use crate::ffi::{maybe_deref, maybe_wrap};
use crate::logger::{log_error, log_info, LdkLogger, Logger};
Expand DownExpand Up@@ -54,6 +54,7 @@ type Refund = Arc<crate::ffi::Refund>;
pub struct Bolt12Payment {
channel_manager: Arc<ChannelManager>,
payment_store: Arc<PaymentStore>,
config: Arc<Config>,
is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand All@@ -62,10 +63,10 @@ pub struct Bolt12Payment {
impl Bolt12Payment {
pub(crate) fn new(
channel_manager: Arc<ChannelManager>, payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
config: Arc<Config>, is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
) -> Self {
Self { channel_manager, payment_store, is_running, logger, async_payments_role }
Self { channel_manager, payment_store, config, is_running, logger, async_payments_role }
}

/// Send a payment given an offer.
Expand All@@ -74,8 +75,12 @@ impl Bolt12Payment {
/// response.
///
/// If `quantity` is `Some` it represents the number of items requested.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send(
&self, offer: &Offer, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure your feeling on this, but could avoid an additional Option parameter by chaining a call when creating Bolt12Payment:

node.bolt12_payment().with_route_params(route_params).send()

Though maybe an argument against is that it is specific to sending so not relevant to other calls. At very least, these aren't specific to a given Offer.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I guess that would make sense if we did the builder-style refactor eventually. Not necessarily opposed to it, but IMO if we would go in that direction we should probably consider refactor the payment APIs to be fully in builder -pattern style.

) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -87,7 +92,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -104,7 +110,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager
Expand DownExpand Up@@ -181,8 +187,12 @@ impl Bolt12Payment {
///
/// If `payer_note` is `Some` it will be seen by the recipient and reflected back in the invoice
/// response.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send_using_amount(
&self, offer: &Offer, amount_msat: u64, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -194,7 +204,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -215,7 +226,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager.pay_for_offer_with_quantity(
Expand DownExpand Up@@ -402,10 +413,13 @@ impl Bolt12Payment {

/// Returns a [`Refund`] object that can be used to offer a refund payment of the amount given.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [`Refund`]: lightning::offers::refund::Refund
pub fn initiate_refund(
&self, amount_msat: u64, expiry_secs: u32, quantity: Option<u64>,
payer_note: Option<String>,
payer_note: Option<String>, route_parameters: Option<RouteParametersConfig>,
) -> Result<Refund, Error> {
let mut random_bytes = [0u8; 32];
rand::rng().fill_bytes(&mut random_bytes);
Expand All@@ -415,7 +429,8 @@ impl Bolt12Payment {
.duration_since(UNIX_EPOCH)
.unwrap();
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let mut refund_builder = self
.channel_manager
Expand All@@ -424,7 +439,7 @@ impl Bolt12Payment {
absolute_expiry,
payment_id,
retry_strategy,
route_params_config,
route_parameters,
)
.map_err(|e| {
log_error!(self.logger, "Failed to create refund builder: {:?}", e);
Expand Down
12 changes: 9 additions & 3 deletions src/payment/unified_qr.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ use bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bitcoin::{Amount, Txid};
use lightning::ln::channelmanager::PaymentId;
use lightning::offers::offer::Offer;
use lightning::routing::router::RouteParametersConfig;
use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, Description};

use crate::error::Error;
Expand DownExpand Up@@ -137,8 +138,13 @@ impl UnifiedQrPayment {
/// Returns a `QrPaymentResult` indicating the outcome of the payment. If an error
/// occurs, an `Error` is returned detailing the issue encountered.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
pub fn send(&self, uri_str: &str) -> Result<QrPaymentResult, Error> {
pub fn send(
&self, uri_str: &str, route_parameters: Option<RouteParametersConfig>,
) -> Result<QrPaymentResult, Error> {
let uri: bip21::Uri<NetworkUnchecked, Extras> =
uri_str.parse().map_err(|_| Error::InvalidUri)?;

Expand All@@ -147,15 +153,15 @@ impl UnifiedQrPayment {

if let Some(offer) = uri_network_checked.extras.bolt12_offer {
let offer = maybe_wrap(offer);
match self.bolt12_payment.send(&offer, None, None) {
match self.bolt12_payment.send(&offer, None, None, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt12 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT12 offer: {:?}. This is part of a unified QR code payment. Falling back to the BOLT11 invoice.", e),
}
}

if let Some(invoice) = uri_network_checked.extras.bolt11_invoice {
let invoice = maybe_wrap(invoice);
match self.bolt11_invoice.send(&invoice, None) {
match self.bolt11_invoice.send(&invoice, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt11 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT11 invoice: {:?}. This is part of a unified QR code payment. Falling back to the on-chain transaction.", e),
}
Expand Down
21 changes: 14 additions & 7 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -967,7 +967,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let payment_id = node_a
.bolt12_payment()
.send(&offer, expected_quantity, expected_payer_note.clone())
.send(&offer, expected_quantity, expected_payer_note.clone(), None)
.unwrap();

expect_payment_successful_event!(node_a, Some(payment_id), None);
Expand DownExpand Up@@ -1023,7 +1023,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
assert!(node_a
.bolt12_payment()
.send_using_amount(&offer, less_than_offer_amount, None, None)
.send_using_amount(&offer, less_than_offer_amount, None, None, None)
.is_err());
let payment_id = node_a
.bolt12_payment()
Expand All@@ -1032,6 +1032,7 @@ async fn simple_bolt12_send_receive() {
expected_amount_msat,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();

Expand DownExpand Up@@ -1089,7 +1090,13 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let refund = node_b
.bolt12_payment()
.initiate_refund(overpaid_amount, 3600, expected_quantity, expected_payer_note.clone())
.initiate_refund(
overpaid_amount,
3600,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();
let invoice = node_a.bolt12_payment().request_refund_payment(&refund).unwrap();
expect_payment_received_event!(node_a, overpaid_amount);
Expand DownExpand Up@@ -1275,7 +1282,7 @@ async fn async_payment() {
node_receiver.stop().unwrap();

let payment_id =
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None).unwrap();
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None, None).unwrap();

// Sleep to allow the payment reach a state where the htlc is held and waiting for the receiver to come online.
tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
Expand DownExpand Up@@ -1473,7 +1480,7 @@ async fn unified_qr_send_receive() {

let uqr_payment = node_b.unified_qr_payment().receive(expected_amount_sats, "asdf", expiry_sec);
let uri_str = uqr_payment.clone().unwrap();
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str) {
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str, None) {
Ok(QrPaymentResult::Bolt12 { payment_id }) => {
println!("\nBolt12 payment sent successfully with PaymentID: {:?}", payment_id);
payment_id
Expand All@@ -1494,7 +1501,7 @@ async fn unified_qr_send_receive() {
// Cut off the BOLT12 part to fallback to BOLT11.
let uri_str_without_offer = uri_str.split("&lno=").next().unwrap();
let invoice_payment_id: PaymentId =
match node_a.unified_qr_payment().send(uri_str_without_offer) {
match node_a.unified_qr_payment().send(uri_str_without_offer, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected Bolt11 payment but got Bolt12");
},
Expand All@@ -1517,7 +1524,7 @@ async fn unified_qr_send_receive() {

// Cut off any lightning part to fallback to on-chain only.
let uri_str_without_lightning = onchain_uqr_payment.split("&lightning=").next().unwrap();
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning) {
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected on-chain payment but got Bolt12")
},
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
8 changes: 4 additions & 4 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,17 +201,17 @@ interface Bolt11Payment {

interface Bolt12Payment {
[Throws=NodeError]
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note);
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note);
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive(u64 amount_msat, [ByRef]string description, u32? expiry_secs, u64? quantity);
[Throws=NodeError]
Offer receive_variable_amount([ByRef]string description, u32? expiry_secs);
[Throws=NodeError]
Bolt12Invoice request_refund_payment([ByRef]Refund refund);
[Throws=NodeError]
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note);
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive_async();
[Throws=NodeError]
Expand DownExpand Up@@ -256,7 +256,7 @@ interface UnifiedQrPayment {
[Throws=NodeError]
string receive(u64 amount_sats, [ByRef]string message, u32 expiry_sec);
[Throws=NodeError]
QrPaymentResult send([ByRef]string uri_str);
QrPaymentResult send([ByRef]string uri_str, RouteParametersConfig? route_parameters);
};

interface LSPS1Liquidity {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -854,6 +854,7 @@ impl Node {
Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand All@@ -868,6 +869,7 @@ impl Node {
Arc::new(Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand Down
35 changes: 25 additions & 10 deletions src/payment/bolt12.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ use lightning::util::ser::{Readable, Writeable};
use lightning_types::string::UntrustedString;
use rand::RngCore;

use crate::config::{AsyncPaymentsRole, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::config::{AsyncPaymentsRole, Config, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::error::Error;
use crate::ffi::{maybe_deref, maybe_wrap};
use crate::logger::{log_error, log_info, LdkLogger, Logger};
Expand DownExpand Up@@ -54,6 +54,7 @@ type Refund = Arc<crate::ffi::Refund>;
pub struct Bolt12Payment {
channel_manager: Arc<ChannelManager>,
payment_store: Arc<PaymentStore>,
config: Arc<Config>,
is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand All@@ -62,10 +63,10 @@ pub struct Bolt12Payment {
impl Bolt12Payment {
pub(crate) fn new(
channel_manager: Arc<ChannelManager>, payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
config: Arc<Config>, is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
) -> Self {
Self { channel_manager, payment_store, is_running, logger, async_payments_role }
Self { channel_manager, payment_store, config, is_running, logger, async_payments_role }
}

/// Send a payment given an offer.
Expand All@@ -74,8 +75,12 @@ impl Bolt12Payment {
/// response.
///
/// If `quantity` is `Some` it represents the number of items requested.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send(
&self, offer: &Offer, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure your feeling on this, but could avoid an additional Option parameter by chaining a call when creating Bolt12Payment:

node.bolt12_payment().with_route_params(route_params).send()

Though maybe an argument against is that it is specific to sending so not relevant to other calls. At very least, these aren't specific to a given Offer.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I guess that would make sense if we did the builder-style refactor eventually. Not necessarily opposed to it, but IMO if we would go in that direction we should probably consider refactor the payment APIs to be fully in builder -pattern style.

) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -87,7 +92,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -104,7 +110,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager
Expand DownExpand Up@@ -181,8 +187,12 @@ impl Bolt12Payment {
///
/// If `payer_note` is `Some` it will be seen by the recipient and reflected back in the invoice
/// response.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send_using_amount(
&self, offer: &Offer, amount_msat: u64, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -194,7 +204,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -215,7 +226,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager.pay_for_offer_with_quantity(
Expand DownExpand Up@@ -402,10 +413,13 @@ impl Bolt12Payment {

/// Returns a [`Refund`] object that can be used to offer a refund payment of the amount given.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [`Refund`]: lightning::offers::refund::Refund
pub fn initiate_refund(
&self, amount_msat: u64, expiry_secs: u32, quantity: Option<u64>,
payer_note: Option<String>,
payer_note: Option<String>, route_parameters: Option<RouteParametersConfig>,
) -> Result<Refund, Error> {
let mut random_bytes = [0u8; 32];
rand::rng().fill_bytes(&mut random_bytes);
Expand All@@ -415,7 +429,8 @@ impl Bolt12Payment {
.duration_since(UNIX_EPOCH)
.unwrap();
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let mut refund_builder = self
.channel_manager
Expand All@@ -424,7 +439,7 @@ impl Bolt12Payment {
absolute_expiry,
payment_id,
retry_strategy,
route_params_config,
route_parameters,
)
.map_err(|e| {
log_error!(self.logger, "Failed to create refund builder: {:?}", e);
Expand Down
12 changes: 9 additions & 3 deletions src/payment/unified_qr.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ use bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bitcoin::{Amount, Txid};
use lightning::ln::channelmanager::PaymentId;
use lightning::offers::offer::Offer;
use lightning::routing::router::RouteParametersConfig;
use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, Description};

use crate::error::Error;
Expand DownExpand Up@@ -137,8 +138,13 @@ impl UnifiedQrPayment {
/// Returns a `QrPaymentResult` indicating the outcome of the payment. If an error
/// occurs, an `Error` is returned detailing the issue encountered.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
pub fn send(&self, uri_str: &str) -> Result<QrPaymentResult, Error> {
pub fn send(
&self, uri_str: &str, route_parameters: Option<RouteParametersConfig>,
) -> Result<QrPaymentResult, Error> {
let uri: bip21::Uri<NetworkUnchecked, Extras> =
uri_str.parse().map_err(|_| Error::InvalidUri)?;

Expand All@@ -147,15 +153,15 @@ impl UnifiedQrPayment {

if let Some(offer) = uri_network_checked.extras.bolt12_offer {
let offer = maybe_wrap(offer);
match self.bolt12_payment.send(&offer, None, None) {
match self.bolt12_payment.send(&offer, None, None, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt12 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT12 offer: {:?}. This is part of a unified QR code payment. Falling back to the BOLT11 invoice.", e),
}
}

if let Some(invoice) = uri_network_checked.extras.bolt11_invoice {
let invoice = maybe_wrap(invoice);
match self.bolt11_invoice.send(&invoice, None) {
match self.bolt11_invoice.send(&invoice, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt11 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT11 invoice: {:?}. This is part of a unified QR code payment. Falling back to the on-chain transaction.", e),
}
Expand Down
21 changes: 14 additions & 7 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -967,7 +967,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let payment_id = node_a
.bolt12_payment()
.send(&offer, expected_quantity, expected_payer_note.clone())
.send(&offer, expected_quantity, expected_payer_note.clone(), None)
.unwrap();

expect_payment_successful_event!(node_a, Some(payment_id), None);
Expand DownExpand Up@@ -1023,7 +1023,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
assert!(node_a
.bolt12_payment()
.send_using_amount(&offer, less_than_offer_amount, None, None)
.send_using_amount(&offer, less_than_offer_amount, None, None, None)
.is_err());
let payment_id = node_a
.bolt12_payment()
Expand All@@ -1032,6 +1032,7 @@ async fn simple_bolt12_send_receive() {
expected_amount_msat,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();

Expand DownExpand Up@@ -1089,7 +1090,13 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let refund = node_b
.bolt12_payment()
.initiate_refund(overpaid_amount, 3600, expected_quantity, expected_payer_note.clone())
.initiate_refund(
overpaid_amount,
3600,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();
let invoice = node_a.bolt12_payment().request_refund_payment(&refund).unwrap();
expect_payment_received_event!(node_a, overpaid_amount);
Expand DownExpand Up@@ -1275,7 +1282,7 @@ async fn async_payment() {
node_receiver.stop().unwrap();

let payment_id =
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None).unwrap();
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None, None).unwrap();

// Sleep to allow the payment reach a state where the htlc is held and waiting for the receiver to come online.
tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
Expand DownExpand Up@@ -1473,7 +1480,7 @@ async fn unified_qr_send_receive() {

let uqr_payment = node_b.unified_qr_payment().receive(expected_amount_sats, "asdf", expiry_sec);
let uri_str = uqr_payment.clone().unwrap();
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str) {
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str, None) {
Ok(QrPaymentResult::Bolt12 { payment_id }) => {
println!("\nBolt12 payment sent successfully with PaymentID: {:?}", payment_id);
payment_id
Expand All@@ -1494,7 +1501,7 @@ async fn unified_qr_send_receive() {
// Cut off the BOLT12 part to fallback to BOLT11.
let uri_str_without_offer = uri_str.split("&lno=").next().unwrap();
let invoice_payment_id: PaymentId =
match node_a.unified_qr_payment().send(uri_str_without_offer) {
match node_a.unified_qr_payment().send(uri_str_without_offer, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected Bolt11 payment but got Bolt12");
},
Expand All@@ -1517,7 +1524,7 @@ async fn unified_qr_send_receive() {

// Cut off any lightning part to fallback to on-chain only.
let uri_str_without_lightning = onchain_uqr_payment.split("&lightning=").next().unwrap();
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning) {
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected on-chain payment but got Bolt12")
},
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
8 changes: 4 additions & 4 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,17 +201,17 @@ interface Bolt11Payment {

interface Bolt12Payment {
[Throws=NodeError]
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note);
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note);
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive(u64 amount_msat, [ByRef]string description, u32? expiry_secs, u64? quantity);
[Throws=NodeError]
Offer receive_variable_amount([ByRef]string description, u32? expiry_secs);
[Throws=NodeError]
Bolt12Invoice request_refund_payment([ByRef]Refund refund);
[Throws=NodeError]
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note);
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive_async();
[Throws=NodeError]
Expand DownExpand Up@@ -256,7 +256,7 @@ interface UnifiedQrPayment {
[Throws=NodeError]
string receive(u64 amount_sats, [ByRef]string message, u32 expiry_sec);
[Throws=NodeError]
QrPaymentResult send([ByRef]string uri_str);
QrPaymentResult send([ByRef]string uri_str, RouteParametersConfig? route_parameters);
};

interface LSPS1Liquidity {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -854,6 +854,7 @@ impl Node {
Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand All@@ -868,6 +869,7 @@ impl Node {
Arc::new(Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand Down
35 changes: 25 additions & 10 deletions src/payment/bolt12.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ use lightning::util::ser::{Readable, Writeable};
use lightning_types::string::UntrustedString;
use rand::RngCore;

use crate::config::{AsyncPaymentsRole, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::config::{AsyncPaymentsRole, Config, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::error::Error;
use crate::ffi::{maybe_deref, maybe_wrap};
use crate::logger::{log_error, log_info, LdkLogger, Logger};
Expand DownExpand Up@@ -54,6 +54,7 @@ type Refund = Arc<crate::ffi::Refund>;
pub struct Bolt12Payment {
channel_manager: Arc<ChannelManager>,
payment_store: Arc<PaymentStore>,
config: Arc<Config>,
is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand All@@ -62,10 +63,10 @@ pub struct Bolt12Payment {
impl Bolt12Payment {
pub(crate) fn new(
channel_manager: Arc<ChannelManager>, payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
config: Arc<Config>, is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
) -> Self {
Self { channel_manager, payment_store, is_running, logger, async_payments_role }
Self { channel_manager, payment_store, config, is_running, logger, async_payments_role }
}

/// Send a payment given an offer.
Expand All@@ -74,8 +75,12 @@ impl Bolt12Payment {
/// response.
///
/// If `quantity` is `Some` it represents the number of items requested.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send(
&self, offer: &Offer, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure your feeling on this, but could avoid an additional Option parameter by chaining a call when creating Bolt12Payment:

node.bolt12_payment().with_route_params(route_params).send()

Though maybe an argument against is that it is specific to sending so not relevant to other calls. At very least, these aren't specific to a given Offer.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I guess that would make sense if we did the builder-style refactor eventually. Not necessarily opposed to it, but IMO if we would go in that direction we should probably consider refactor the payment APIs to be fully in builder -pattern style.

) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -87,7 +92,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -104,7 +110,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager
Expand DownExpand Up@@ -181,8 +187,12 @@ impl Bolt12Payment {
///
/// If `payer_note` is `Some` it will be seen by the recipient and reflected back in the invoice
/// response.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send_using_amount(
&self, offer: &Offer, amount_msat: u64, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -194,7 +204,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -215,7 +226,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager.pay_for_offer_with_quantity(
Expand DownExpand Up@@ -402,10 +413,13 @@ impl Bolt12Payment {

/// Returns a [`Refund`] object that can be used to offer a refund payment of the amount given.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [`Refund`]: lightning::offers::refund::Refund
pub fn initiate_refund(
&self, amount_msat: u64, expiry_secs: u32, quantity: Option<u64>,
payer_note: Option<String>,
payer_note: Option<String>, route_parameters: Option<RouteParametersConfig>,
) -> Result<Refund, Error> {
let mut random_bytes = [0u8; 32];
rand::rng().fill_bytes(&mut random_bytes);
Expand All@@ -415,7 +429,8 @@ impl Bolt12Payment {
.duration_since(UNIX_EPOCH)
.unwrap();
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let mut refund_builder = self
.channel_manager
Expand All@@ -424,7 +439,7 @@ impl Bolt12Payment {
absolute_expiry,
payment_id,
retry_strategy,
route_params_config,
route_parameters,
)
.map_err(|e| {
log_error!(self.logger, "Failed to create refund builder: {:?}", e);
Expand Down
12 changes: 9 additions & 3 deletions src/payment/unified_qr.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ use bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bitcoin::{Amount, Txid};
use lightning::ln::channelmanager::PaymentId;
use lightning::offers::offer::Offer;
use lightning::routing::router::RouteParametersConfig;
use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, Description};

use crate::error::Error;
Expand DownExpand Up@@ -137,8 +138,13 @@ impl UnifiedQrPayment {
/// Returns a `QrPaymentResult` indicating the outcome of the payment. If an error
/// occurs, an `Error` is returned detailing the issue encountered.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
pub fn send(&self, uri_str: &str) -> Result<QrPaymentResult, Error> {
pub fn send(
&self, uri_str: &str, route_parameters: Option<RouteParametersConfig>,
) -> Result<QrPaymentResult, Error> {
let uri: bip21::Uri<NetworkUnchecked, Extras> =
uri_str.parse().map_err(|_| Error::InvalidUri)?;

Expand All@@ -147,15 +153,15 @@ impl UnifiedQrPayment {

if let Some(offer) = uri_network_checked.extras.bolt12_offer {
let offer = maybe_wrap(offer);
match self.bolt12_payment.send(&offer, None, None) {
match self.bolt12_payment.send(&offer, None, None, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt12 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT12 offer: {:?}. This is part of a unified QR code payment. Falling back to the BOLT11 invoice.", e),
}
}

if let Some(invoice) = uri_network_checked.extras.bolt11_invoice {
let invoice = maybe_wrap(invoice);
match self.bolt11_invoice.send(&invoice, None) {
match self.bolt11_invoice.send(&invoice, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt11 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT11 invoice: {:?}. This is part of a unified QR code payment. Falling back to the on-chain transaction.", e),
}
Expand Down
21 changes: 14 additions & 7 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -967,7 +967,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let payment_id = node_a
.bolt12_payment()
.send(&offer, expected_quantity, expected_payer_note.clone())
.send(&offer, expected_quantity, expected_payer_note.clone(), None)
.unwrap();

expect_payment_successful_event!(node_a, Some(payment_id), None);
Expand DownExpand Up@@ -1023,7 +1023,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
assert!(node_a
.bolt12_payment()
.send_using_amount(&offer, less_than_offer_amount, None, None)
.send_using_amount(&offer, less_than_offer_amount, None, None, None)
.is_err());
let payment_id = node_a
.bolt12_payment()
Expand All@@ -1032,6 +1032,7 @@ async fn simple_bolt12_send_receive() {
expected_amount_msat,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();

Expand DownExpand Up@@ -1089,7 +1090,13 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let refund = node_b
.bolt12_payment()
.initiate_refund(overpaid_amount, 3600, expected_quantity, expected_payer_note.clone())
.initiate_refund(
overpaid_amount,
3600,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();
let invoice = node_a.bolt12_payment().request_refund_payment(&refund).unwrap();
expect_payment_received_event!(node_a, overpaid_amount);
Expand DownExpand Up@@ -1275,7 +1282,7 @@ async fn async_payment() {
node_receiver.stop().unwrap();

let payment_id =
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None).unwrap();
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None, None).unwrap();

// Sleep to allow the payment reach a state where the htlc is held and waiting for the receiver to come online.
tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
Expand DownExpand Up@@ -1473,7 +1480,7 @@ async fn unified_qr_send_receive() {

let uqr_payment = node_b.unified_qr_payment().receive(expected_amount_sats, "asdf", expiry_sec);
let uri_str = uqr_payment.clone().unwrap();
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str) {
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str, None) {
Ok(QrPaymentResult::Bolt12 { payment_id }) => {
println!("\nBolt12 payment sent successfully with PaymentID: {:?}", payment_id);
payment_id
Expand All@@ -1494,7 +1501,7 @@ async fn unified_qr_send_receive() {
// Cut off the BOLT12 part to fallback to BOLT11.
let uri_str_without_offer = uri_str.split("&lno=").next().unwrap();
let invoice_payment_id: PaymentId =
match node_a.unified_qr_payment().send(uri_str_without_offer) {
match node_a.unified_qr_payment().send(uri_str_without_offer, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected Bolt11 payment but got Bolt12");
},
Expand All@@ -1517,7 +1524,7 @@ async fn unified_qr_send_receive() {

// Cut off any lightning part to fallback to on-chain only.
let uri_str_without_lightning = onchain_uqr_payment.split("&lightning=").next().unwrap();
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning) {
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected on-chain payment but got Bolt12")
},
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
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
8 changes: 4 additions & 4 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,17 +201,17 @@ interface Bolt11Payment {

interface Bolt12Payment {
[Throws=NodeError]
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note);
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note);
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive(u64 amount_msat, [ByRef]string description, u32? expiry_secs, u64? quantity);
[Throws=NodeError]
Offer receive_variable_amount([ByRef]string description, u32? expiry_secs);
[Throws=NodeError]
Bolt12Invoice request_refund_payment([ByRef]Refund refund);
[Throws=NodeError]
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note);
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive_async();
[Throws=NodeError]
Expand DownExpand Up@@ -256,7 +256,7 @@ interface UnifiedQrPayment {
[Throws=NodeError]
string receive(u64 amount_sats, [ByRef]string message, u32 expiry_sec);
[Throws=NodeError]
QrPaymentResult send([ByRef]string uri_str);
QrPaymentResult send([ByRef]string uri_str, RouteParametersConfig? route_parameters);
};

interface LSPS1Liquidity {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -854,6 +854,7 @@ impl Node {
Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand All@@ -868,6 +869,7 @@ impl Node {
Arc::new(Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand Down
35 changes: 25 additions & 10 deletions src/payment/bolt12.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ use lightning::util::ser::{Readable, Writeable};
use lightning_types::string::UntrustedString;
use rand::RngCore;

use crate::config::{AsyncPaymentsRole, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::config::{AsyncPaymentsRole, Config, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::error::Error;
use crate::ffi::{maybe_deref, maybe_wrap};
use crate::logger::{log_error, log_info, LdkLogger, Logger};
Expand DownExpand Up@@ -54,6 +54,7 @@ type Refund = Arc<crate::ffi::Refund>;
pub struct Bolt12Payment {
channel_manager: Arc<ChannelManager>,
payment_store: Arc<PaymentStore>,
config: Arc<Config>,
is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand All@@ -62,10 +63,10 @@ pub struct Bolt12Payment {
impl Bolt12Payment {
pub(crate) fn new(
channel_manager: Arc<ChannelManager>, payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
config: Arc<Config>, is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
) -> Self {
Self { channel_manager, payment_store, is_running, logger, async_payments_role }
Self { channel_manager, payment_store, config, is_running, logger, async_payments_role }
}

/// Send a payment given an offer.
Expand All@@ -74,8 +75,12 @@ impl Bolt12Payment {
/// response.
///
/// If `quantity` is `Some` it represents the number of items requested.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send(
&self, offer: &Offer, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure your feeling on this, but could avoid an additional Option parameter by chaining a call when creating Bolt12Payment:

node.bolt12_payment().with_route_params(route_params).send()

Though maybe an argument against is that it is specific to sending so not relevant to other calls. At very least, these aren't specific to a given Offer.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I guess that would make sense if we did the builder-style refactor eventually. Not necessarily opposed to it, but IMO if we would go in that direction we should probably consider refactor the payment APIs to be fully in builder -pattern style.

) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -87,7 +92,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -104,7 +110,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager
Expand DownExpand Up@@ -181,8 +187,12 @@ impl Bolt12Payment {
///
/// If `payer_note` is `Some` it will be seen by the recipient and reflected back in the invoice
/// response.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send_using_amount(
&self, offer: &Offer, amount_msat: u64, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -194,7 +204,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -215,7 +226,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager.pay_for_offer_with_quantity(
Expand DownExpand Up@@ -402,10 +413,13 @@ impl Bolt12Payment {

/// Returns a [`Refund`] object that can be used to offer a refund payment of the amount given.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [`Refund`]: lightning::offers::refund::Refund
pub fn initiate_refund(
&self, amount_msat: u64, expiry_secs: u32, quantity: Option<u64>,
payer_note: Option<String>,
payer_note: Option<String>, route_parameters: Option<RouteParametersConfig>,
) -> Result<Refund, Error> {
let mut random_bytes = [0u8; 32];
rand::rng().fill_bytes(&mut random_bytes);
Expand All@@ -415,7 +429,8 @@ impl Bolt12Payment {
.duration_since(UNIX_EPOCH)
.unwrap();
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let mut refund_builder = self
.channel_manager
Expand All@@ -424,7 +439,7 @@ impl Bolt12Payment {
absolute_expiry,
payment_id,
retry_strategy,
route_params_config,
route_parameters,
)
.map_err(|e| {
log_error!(self.logger, "Failed to create refund builder: {:?}", e);
Expand Down
12 changes: 9 additions & 3 deletions src/payment/unified_qr.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ use bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bitcoin::{Amount, Txid};
use lightning::ln::channelmanager::PaymentId;
use lightning::offers::offer::Offer;
use lightning::routing::router::RouteParametersConfig;
use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, Description};

use crate::error::Error;
Expand DownExpand Up@@ -137,8 +138,13 @@ impl UnifiedQrPayment {
/// Returns a `QrPaymentResult` indicating the outcome of the payment. If an error
/// occurs, an `Error` is returned detailing the issue encountered.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
pub fn send(&self, uri_str: &str) -> Result<QrPaymentResult, Error> {
pub fn send(
&self, uri_str: &str, route_parameters: Option<RouteParametersConfig>,
) -> Result<QrPaymentResult, Error> {
let uri: bip21::Uri<NetworkUnchecked, Extras> =
uri_str.parse().map_err(|_| Error::InvalidUri)?;

Expand All@@ -147,15 +153,15 @@ impl UnifiedQrPayment {

if let Some(offer) = uri_network_checked.extras.bolt12_offer {
let offer = maybe_wrap(offer);
match self.bolt12_payment.send(&offer, None, None) {
match self.bolt12_payment.send(&offer, None, None, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt12 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT12 offer: {:?}. This is part of a unified QR code payment. Falling back to the BOLT11 invoice.", e),
}
}

if let Some(invoice) = uri_network_checked.extras.bolt11_invoice {
let invoice = maybe_wrap(invoice);
match self.bolt11_invoice.send(&invoice, None) {
match self.bolt11_invoice.send(&invoice, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt11 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT11 invoice: {:?}. This is part of a unified QR code payment. Falling back to the on-chain transaction.", e),
}
Expand Down
21 changes: 14 additions & 7 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -967,7 +967,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let payment_id = node_a
.bolt12_payment()
.send(&offer, expected_quantity, expected_payer_note.clone())
.send(&offer, expected_quantity, expected_payer_note.clone(), None)
.unwrap();

expect_payment_successful_event!(node_a, Some(payment_id), None);
Expand DownExpand Up@@ -1023,7 +1023,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
assert!(node_a
.bolt12_payment()
.send_using_amount(&offer, less_than_offer_amount, None, None)
.send_using_amount(&offer, less_than_offer_amount, None, None, None)
.is_err());
let payment_id = node_a
.bolt12_payment()
Expand All@@ -1032,6 +1032,7 @@ async fn simple_bolt12_send_receive() {
expected_amount_msat,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();

Expand DownExpand Up@@ -1089,7 +1090,13 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let refund = node_b
.bolt12_payment()
.initiate_refund(overpaid_amount, 3600, expected_quantity, expected_payer_note.clone())
.initiate_refund(
overpaid_amount,
3600,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();
let invoice = node_a.bolt12_payment().request_refund_payment(&refund).unwrap();
expect_payment_received_event!(node_a, overpaid_amount);
Expand DownExpand Up@@ -1275,7 +1282,7 @@ async fn async_payment() {
node_receiver.stop().unwrap();

let payment_id =
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None).unwrap();
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None, None).unwrap();

// Sleep to allow the payment reach a state where the htlc is held and waiting for the receiver to come online.
tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
Expand DownExpand Up@@ -1473,7 +1480,7 @@ async fn unified_qr_send_receive() {

let uqr_payment = node_b.unified_qr_payment().receive(expected_amount_sats, "asdf", expiry_sec);
let uri_str = uqr_payment.clone().unwrap();
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str) {
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str, None) {
Ok(QrPaymentResult::Bolt12 { payment_id }) => {
println!("\nBolt12 payment sent successfully with PaymentID: {:?}", payment_id);
payment_id
Expand All@@ -1494,7 +1501,7 @@ async fn unified_qr_send_receive() {
// Cut off the BOLT12 part to fallback to BOLT11.
let uri_str_without_offer = uri_str.split("&lno=").next().unwrap();
let invoice_payment_id: PaymentId =
match node_a.unified_qr_payment().send(uri_str_without_offer) {
match node_a.unified_qr_payment().send(uri_str_without_offer, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected Bolt11 payment but got Bolt12");
},
Expand All@@ -1517,7 +1524,7 @@ async fn unified_qr_send_receive() {

// Cut off any lightning part to fallback to on-chain only.
let uri_str_without_lightning = onchain_uqr_payment.split("&lightning=").next().unwrap();
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning) {
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected on-chain payment but got Bolt12")
},
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
8 changes: 4 additions & 4 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,17 +201,17 @@ interface Bolt11Payment {

interface Bolt12Payment {
[Throws=NodeError]
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note);
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note);
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive(u64 amount_msat, [ByRef]string description, u32? expiry_secs, u64? quantity);
[Throws=NodeError]
Offer receive_variable_amount([ByRef]string description, u32? expiry_secs);
[Throws=NodeError]
Bolt12Invoice request_refund_payment([ByRef]Refund refund);
[Throws=NodeError]
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note);
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive_async();
[Throws=NodeError]
Expand DownExpand Up@@ -256,7 +256,7 @@ interface UnifiedQrPayment {
[Throws=NodeError]
string receive(u64 amount_sats, [ByRef]string message, u32 expiry_sec);
[Throws=NodeError]
QrPaymentResult send([ByRef]string uri_str);
QrPaymentResult send([ByRef]string uri_str, RouteParametersConfig? route_parameters);
};

interface LSPS1Liquidity {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -854,6 +854,7 @@ impl Node {
Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand All@@ -868,6 +869,7 @@ impl Node {
Arc::new(Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand Down
35 changes: 25 additions & 10 deletions src/payment/bolt12.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ use lightning::util::ser::{Readable, Writeable};
use lightning_types::string::UntrustedString;
use rand::RngCore;

use crate::config::{AsyncPaymentsRole, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::config::{AsyncPaymentsRole, Config, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::error::Error;
use crate::ffi::{maybe_deref, maybe_wrap};
use crate::logger::{log_error, log_info, LdkLogger, Logger};
Expand DownExpand Up@@ -54,6 +54,7 @@ type Refund = Arc<crate::ffi::Refund>;
pub struct Bolt12Payment {
channel_manager: Arc<ChannelManager>,
payment_store: Arc<PaymentStore>,
config: Arc<Config>,
is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand All@@ -62,10 +63,10 @@ pub struct Bolt12Payment {
impl Bolt12Payment {
pub(crate) fn new(
channel_manager: Arc<ChannelManager>, payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
config: Arc<Config>, is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
) -> Self {
Self { channel_manager, payment_store, is_running, logger, async_payments_role }
Self { channel_manager, payment_store, config, is_running, logger, async_payments_role }
}

/// Send a payment given an offer.
Expand All@@ -74,8 +75,12 @@ impl Bolt12Payment {
/// response.
///
/// If `quantity` is `Some` it represents the number of items requested.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send(
&self, offer: &Offer, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure your feeling on this, but could avoid an additional Option parameter by chaining a call when creating Bolt12Payment:

node.bolt12_payment().with_route_params(route_params).send()

Though maybe an argument against is that it is specific to sending so not relevant to other calls. At very least, these aren't specific to a given Offer.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I guess that would make sense if we did the builder-style refactor eventually. Not necessarily opposed to it, but IMO if we would go in that direction we should probably consider refactor the payment APIs to be fully in builder -pattern style.

) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -87,7 +92,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -104,7 +110,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager
Expand DownExpand Up@@ -181,8 +187,12 @@ impl Bolt12Payment {
///
/// If `payer_note` is `Some` it will be seen by the recipient and reflected back in the invoice
/// response.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send_using_amount(
&self, offer: &Offer, amount_msat: u64, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -194,7 +204,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -215,7 +226,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager.pay_for_offer_with_quantity(
Expand DownExpand Up@@ -402,10 +413,13 @@ impl Bolt12Payment {

/// Returns a [`Refund`] object that can be used to offer a refund payment of the amount given.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [`Refund`]: lightning::offers::refund::Refund
pub fn initiate_refund(
&self, amount_msat: u64, expiry_secs: u32, quantity: Option<u64>,
payer_note: Option<String>,
payer_note: Option<String>, route_parameters: Option<RouteParametersConfig>,
) -> Result<Refund, Error> {
let mut random_bytes = [0u8; 32];
rand::rng().fill_bytes(&mut random_bytes);
Expand All@@ -415,7 +429,8 @@ impl Bolt12Payment {
.duration_since(UNIX_EPOCH)
.unwrap();
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let mut refund_builder = self
.channel_manager
Expand All@@ -424,7 +439,7 @@ impl Bolt12Payment {
absolute_expiry,
payment_id,
retry_strategy,
route_params_config,
route_parameters,
)
.map_err(|e| {
log_error!(self.logger, "Failed to create refund builder: {:?}", e);
Expand Down
12 changes: 9 additions & 3 deletions src/payment/unified_qr.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ use bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bitcoin::{Amount, Txid};
use lightning::ln::channelmanager::PaymentId;
use lightning::offers::offer::Offer;
use lightning::routing::router::RouteParametersConfig;
use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, Description};

use crate::error::Error;
Expand DownExpand Up@@ -137,8 +138,13 @@ impl UnifiedQrPayment {
/// Returns a `QrPaymentResult` indicating the outcome of the payment. If an error
/// occurs, an `Error` is returned detailing the issue encountered.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
pub fn send(&self, uri_str: &str) -> Result<QrPaymentResult, Error> {
pub fn send(
&self, uri_str: &str, route_parameters: Option<RouteParametersConfig>,
) -> Result<QrPaymentResult, Error> {
let uri: bip21::Uri<NetworkUnchecked, Extras> =
uri_str.parse().map_err(|_| Error::InvalidUri)?;

Expand All@@ -147,15 +153,15 @@ impl UnifiedQrPayment {

if let Some(offer) = uri_network_checked.extras.bolt12_offer {
let offer = maybe_wrap(offer);
match self.bolt12_payment.send(&offer, None, None) {
match self.bolt12_payment.send(&offer, None, None, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt12 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT12 offer: {:?}. This is part of a unified QR code payment. Falling back to the BOLT11 invoice.", e),
}
}

if let Some(invoice) = uri_network_checked.extras.bolt11_invoice {
let invoice = maybe_wrap(invoice);
match self.bolt11_invoice.send(&invoice, None) {
match self.bolt11_invoice.send(&invoice, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt11 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT11 invoice: {:?}. This is part of a unified QR code payment. Falling back to the on-chain transaction.", e),
}
Expand Down
21 changes: 14 additions & 7 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -967,7 +967,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let payment_id = node_a
.bolt12_payment()
.send(&offer, expected_quantity, expected_payer_note.clone())
.send(&offer, expected_quantity, expected_payer_note.clone(), None)
.unwrap();

expect_payment_successful_event!(node_a, Some(payment_id), None);
Expand DownExpand Up@@ -1023,7 +1023,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
assert!(node_a
.bolt12_payment()
.send_using_amount(&offer, less_than_offer_amount, None, None)
.send_using_amount(&offer, less_than_offer_amount, None, None, None)
.is_err());
let payment_id = node_a
.bolt12_payment()
Expand All@@ -1032,6 +1032,7 @@ async fn simple_bolt12_send_receive() {
expected_amount_msat,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();

Expand DownExpand Up@@ -1089,7 +1090,13 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let refund = node_b
.bolt12_payment()
.initiate_refund(overpaid_amount, 3600, expected_quantity, expected_payer_note.clone())
.initiate_refund(
overpaid_amount,
3600,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();
let invoice = node_a.bolt12_payment().request_refund_payment(&refund).unwrap();
expect_payment_received_event!(node_a, overpaid_amount);
Expand DownExpand Up@@ -1275,7 +1282,7 @@ async fn async_payment() {
node_receiver.stop().unwrap();

let payment_id =
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None).unwrap();
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None, None).unwrap();

// Sleep to allow the payment reach a state where the htlc is held and waiting for the receiver to come online.
tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
Expand DownExpand Up@@ -1473,7 +1480,7 @@ async fn unified_qr_send_receive() {

let uqr_payment = node_b.unified_qr_payment().receive(expected_amount_sats, "asdf", expiry_sec);
let uri_str = uqr_payment.clone().unwrap();
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str) {
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str, None) {
Ok(QrPaymentResult::Bolt12 { payment_id }) => {
println!("\nBolt12 payment sent successfully with PaymentID: {:?}", payment_id);
payment_id
Expand All@@ -1494,7 +1501,7 @@ async fn unified_qr_send_receive() {
// Cut off the BOLT12 part to fallback to BOLT11.
let uri_str_without_offer = uri_str.split("&lno=").next().unwrap();
let invoice_payment_id: PaymentId =
match node_a.unified_qr_payment().send(uri_str_without_offer) {
match node_a.unified_qr_payment().send(uri_str_without_offer, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected Bolt11 payment but got Bolt12");
},
Expand All@@ -1517,7 +1524,7 @@ async fn unified_qr_send_receive() {

// Cut off any lightning part to fallback to on-chain only.
let uri_str_without_lightning = onchain_uqr_payment.split("&lightning=").next().unwrap();
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning) {
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected on-chain payment but got Bolt12")
},
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
8 changes: 4 additions & 4 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,17 +201,17 @@ interface Bolt11Payment {

interface Bolt12Payment {
[Throws=NodeError]
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note);
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note);
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive(u64 amount_msat, [ByRef]string description, u32? expiry_secs, u64? quantity);
[Throws=NodeError]
Offer receive_variable_amount([ByRef]string description, u32? expiry_secs);
[Throws=NodeError]
Bolt12Invoice request_refund_payment([ByRef]Refund refund);
[Throws=NodeError]
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note);
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive_async();
[Throws=NodeError]
Expand DownExpand Up@@ -256,7 +256,7 @@ interface UnifiedQrPayment {
[Throws=NodeError]
string receive(u64 amount_sats, [ByRef]string message, u32 expiry_sec);
[Throws=NodeError]
QrPaymentResult send([ByRef]string uri_str);
QrPaymentResult send([ByRef]string uri_str, RouteParametersConfig? route_parameters);
};

interface LSPS1Liquidity {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -854,6 +854,7 @@ impl Node {
Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand All@@ -868,6 +869,7 @@ impl Node {
Arc::new(Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand Down
35 changes: 25 additions & 10 deletions src/payment/bolt12.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ use lightning::util::ser::{Readable, Writeable};
use lightning_types::string::UntrustedString;
use rand::RngCore;

use crate::config::{AsyncPaymentsRole, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::config::{AsyncPaymentsRole, Config, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::error::Error;
use crate::ffi::{maybe_deref, maybe_wrap};
use crate::logger::{log_error, log_info, LdkLogger, Logger};
Expand DownExpand Up@@ -54,6 +54,7 @@ type Refund = Arc<crate::ffi::Refund>;
pub struct Bolt12Payment {
channel_manager: Arc<ChannelManager>,
payment_store: Arc<PaymentStore>,
config: Arc<Config>,
is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand All@@ -62,10 +63,10 @@ pub struct Bolt12Payment {
impl Bolt12Payment {
pub(crate) fn new(
channel_manager: Arc<ChannelManager>, payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
config: Arc<Config>, is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
) -> Self {
Self { channel_manager, payment_store, is_running, logger, async_payments_role }
Self { channel_manager, payment_store, config, is_running, logger, async_payments_role }
}

/// Send a payment given an offer.
Expand All@@ -74,8 +75,12 @@ impl Bolt12Payment {
/// response.
///
/// If `quantity` is `Some` it represents the number of items requested.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send(
&self, offer: &Offer, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure your feeling on this, but could avoid an additional Option parameter by chaining a call when creating Bolt12Payment:

node.bolt12_payment().with_route_params(route_params).send()

Though maybe an argument against is that it is specific to sending so not relevant to other calls. At very least, these aren't specific to a given Offer.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I guess that would make sense if we did the builder-style refactor eventually. Not necessarily opposed to it, but IMO if we would go in that direction we should probably consider refactor the payment APIs to be fully in builder -pattern style.

) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -87,7 +92,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -104,7 +110,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager
Expand DownExpand Up@@ -181,8 +187,12 @@ impl Bolt12Payment {
///
/// If `payer_note` is `Some` it will be seen by the recipient and reflected back in the invoice
/// response.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send_using_amount(
&self, offer: &Offer, amount_msat: u64, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -194,7 +204,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -215,7 +226,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager.pay_for_offer_with_quantity(
Expand DownExpand Up@@ -402,10 +413,13 @@ impl Bolt12Payment {

/// Returns a [`Refund`] object that can be used to offer a refund payment of the amount given.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [`Refund`]: lightning::offers::refund::Refund
pub fn initiate_refund(
&self, amount_msat: u64, expiry_secs: u32, quantity: Option<u64>,
payer_note: Option<String>,
payer_note: Option<String>, route_parameters: Option<RouteParametersConfig>,
) -> Result<Refund, Error> {
let mut random_bytes = [0u8; 32];
rand::rng().fill_bytes(&mut random_bytes);
Expand All@@ -415,7 +429,8 @@ impl Bolt12Payment {
.duration_since(UNIX_EPOCH)
.unwrap();
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let mut refund_builder = self
.channel_manager
Expand All@@ -424,7 +439,7 @@ impl Bolt12Payment {
absolute_expiry,
payment_id,
retry_strategy,
route_params_config,
route_parameters,
)
.map_err(|e| {
log_error!(self.logger, "Failed to create refund builder: {:?}", e);
Expand Down
12 changes: 9 additions & 3 deletions src/payment/unified_qr.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ use bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bitcoin::{Amount, Txid};
use lightning::ln::channelmanager::PaymentId;
use lightning::offers::offer::Offer;
use lightning::routing::router::RouteParametersConfig;
use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, Description};

use crate::error::Error;
Expand DownExpand Up@@ -137,8 +138,13 @@ impl UnifiedQrPayment {
/// Returns a `QrPaymentResult` indicating the outcome of the payment. If an error
/// occurs, an `Error` is returned detailing the issue encountered.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
pub fn send(&self, uri_str: &str) -> Result<QrPaymentResult, Error> {
pub fn send(
&self, uri_str: &str, route_parameters: Option<RouteParametersConfig>,
) -> Result<QrPaymentResult, Error> {
let uri: bip21::Uri<NetworkUnchecked, Extras> =
uri_str.parse().map_err(|_| Error::InvalidUri)?;

Expand All@@ -147,15 +153,15 @@ impl UnifiedQrPayment {

if let Some(offer) = uri_network_checked.extras.bolt12_offer {
let offer = maybe_wrap(offer);
match self.bolt12_payment.send(&offer, None, None) {
match self.bolt12_payment.send(&offer, None, None, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt12 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT12 offer: {:?}. This is part of a unified QR code payment. Falling back to the BOLT11 invoice.", e),
}
}

if let Some(invoice) = uri_network_checked.extras.bolt11_invoice {
let invoice = maybe_wrap(invoice);
match self.bolt11_invoice.send(&invoice, None) {
match self.bolt11_invoice.send(&invoice, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt11 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT11 invoice: {:?}. This is part of a unified QR code payment. Falling back to the on-chain transaction.", e),
}
Expand Down
21 changes: 14 additions & 7 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -967,7 +967,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let payment_id = node_a
.bolt12_payment()
.send(&offer, expected_quantity, expected_payer_note.clone())
.send(&offer, expected_quantity, expected_payer_note.clone(), None)
.unwrap();

expect_payment_successful_event!(node_a, Some(payment_id), None);
Expand DownExpand Up@@ -1023,7 +1023,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
assert!(node_a
.bolt12_payment()
.send_using_amount(&offer, less_than_offer_amount, None, None)
.send_using_amount(&offer, less_than_offer_amount, None, None, None)
.is_err());
let payment_id = node_a
.bolt12_payment()
Expand All@@ -1032,6 +1032,7 @@ async fn simple_bolt12_send_receive() {
expected_amount_msat,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();

Expand DownExpand Up@@ -1089,7 +1090,13 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let refund = node_b
.bolt12_payment()
.initiate_refund(overpaid_amount, 3600, expected_quantity, expected_payer_note.clone())
.initiate_refund(
overpaid_amount,
3600,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();
let invoice = node_a.bolt12_payment().request_refund_payment(&refund).unwrap();
expect_payment_received_event!(node_a, overpaid_amount);
Expand DownExpand Up@@ -1275,7 +1282,7 @@ async fn async_payment() {
node_receiver.stop().unwrap();

let payment_id =
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None).unwrap();
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None, None).unwrap();

// Sleep to allow the payment reach a state where the htlc is held and waiting for the receiver to come online.
tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
Expand DownExpand Up@@ -1473,7 +1480,7 @@ async fn unified_qr_send_receive() {

let uqr_payment = node_b.unified_qr_payment().receive(expected_amount_sats, "asdf", expiry_sec);
let uri_str = uqr_payment.clone().unwrap();
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str) {
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str, None) {
Ok(QrPaymentResult::Bolt12 { payment_id }) => {
println!("\nBolt12 payment sent successfully with PaymentID: {:?}", payment_id);
payment_id
Expand All@@ -1494,7 +1501,7 @@ async fn unified_qr_send_receive() {
// Cut off the BOLT12 part to fallback to BOLT11.
let uri_str_without_offer = uri_str.split("&lno=").next().unwrap();
let invoice_payment_id: PaymentId =
match node_a.unified_qr_payment().send(uri_str_without_offer) {
match node_a.unified_qr_payment().send(uri_str_without_offer, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected Bolt11 payment but got Bolt12");
},
Expand All@@ -1517,7 +1524,7 @@ async fn unified_qr_send_receive() {

// Cut off any lightning part to fallback to on-chain only.
let uri_str_without_lightning = onchain_uqr_payment.split("&lightning=").next().unwrap();
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning) {
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected on-chain payment but got Bolt12")
},
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
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
8 changes: 4 additions & 4 deletions bindings/ldk_node.udl
Original file line numberDiff line numberDiff line change
Expand Up@@ -201,17 +201,17 @@ interface Bolt11Payment {

interface Bolt12Payment {
[Throws=NodeError]
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note);
PaymentId send([ByRef]Offer offer, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note);
PaymentId send_using_amount([ByRef]Offer offer, u64 amount_msat, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive(u64 amount_msat, [ByRef]string description, u32? expiry_secs, u64? quantity);
[Throws=NodeError]
Offer receive_variable_amount([ByRef]string description, u32? expiry_secs);
[Throws=NodeError]
Bolt12Invoice request_refund_payment([ByRef]Refund refund);
[Throws=NodeError]
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note);
Refund initiate_refund(u64 amount_msat, u32 expiry_secs, u64? quantity, string? payer_note, RouteParametersConfig? route_parameters);
[Throws=NodeError]
Offer receive_async();
[Throws=NodeError]
Expand DownExpand Up@@ -256,7 +256,7 @@ interface UnifiedQrPayment {
[Throws=NodeError]
string receive(u64 amount_sats, [ByRef]string message, u32 expiry_sec);
[Throws=NodeError]
QrPaymentResult send([ByRef]string uri_str);
QrPaymentResult send([ByRef]string uri_str, RouteParametersConfig? route_parameters);
};

interface LSPS1Liquidity {
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -854,6 +854,7 @@ impl Node {
Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand All@@ -868,6 +869,7 @@ impl Node {
Arc::new(Bolt12Payment::new(
Arc::clone(&self.channel_manager),
Arc::clone(&self.payment_store),
Arc::clone(&self.config),
Arc::clone(&self.is_running),
Arc::clone(&self.logger),
self.async_payments_role,
Expand Down
35 changes: 25 additions & 10 deletions src/payment/bolt12.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -23,7 +23,7 @@ use lightning::util::ser::{Readable, Writeable};
use lightning_types::string::UntrustedString;
use rand::RngCore;

use crate::config::{AsyncPaymentsRole, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::config::{AsyncPaymentsRole, Config, LDK_PAYMENT_RETRY_TIMEOUT};
use crate::error::Error;
use crate::ffi::{maybe_deref, maybe_wrap};
use crate::logger::{log_error, log_info, LdkLogger, Logger};
Expand DownExpand Up@@ -54,6 +54,7 @@ type Refund = Arc<crate::ffi::Refund>;
pub struct Bolt12Payment {
channel_manager: Arc<ChannelManager>,
payment_store: Arc<PaymentStore>,
config: Arc<Config>,
is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
Expand All@@ -62,10 +63,10 @@ pub struct Bolt12Payment {
impl Bolt12Payment {
pub(crate) fn new(
channel_manager: Arc<ChannelManager>, payment_store: Arc<PaymentStore>,
is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
config: Arc<Config>, is_running: Arc<RwLock<bool>>, logger: Arc<Logger>,
async_payments_role: Option<AsyncPaymentsRole>,
) -> Self {
Self { channel_manager, payment_store, is_running, logger, async_payments_role }
Self { channel_manager, payment_store, config, is_running, logger, async_payments_role }
}

/// Send a payment given an offer.
Expand All@@ -74,8 +75,12 @@ impl Bolt12Payment {
/// response.
///
/// If `quantity` is `Some` it represents the number of items requested.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send(
&self, offer: &Offer, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure your feeling on this, but could avoid an additional Option parameter by chaining a call when creating Bolt12Payment:

node.bolt12_payment().with_route_params(route_params).send()

Though maybe an argument against is that it is specific to sending so not relevant to other calls. At very least, these aren't specific to a given Offer.

Copy link
Copy Markdown
CollaboratorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I guess that would make sense if we did the builder-style refactor eventually. Not necessarily opposed to it, but IMO if we would go in that direction we should probably consider refactor the payment APIs to be fully in builder -pattern style.

) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -87,7 +92,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -104,7 +110,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager
Expand DownExpand Up@@ -181,8 +187,12 @@ impl Bolt12Payment {
///
/// If `payer_note` is `Some` it will be seen by the recipient and reflected back in the invoice
/// response.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send_using_amount(
&self, offer: &Offer, amount_msat: u64, quantity: Option<u64>, payer_note: Option<String>,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
Expand All@@ -194,7 +204,8 @@ impl Bolt12Payment {
rand::rng().fill_bytes(&mut random_bytes);
let payment_id = PaymentId(random_bytes);
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let offer_amount_msat = match offer.amount() {
Some(Amount::Bitcoin { amount_msats }) => amount_msats,
Expand All@@ -215,7 +226,7 @@ impl Bolt12Payment {
let params = OptionalOfferPaymentParams {
payer_note: payer_note.clone(),
retry_strategy,
route_params_config,
route_params_config: route_parameters,
};
let res = if let Some(quantity) = quantity {
self.channel_manager.pay_for_offer_with_quantity(
Expand DownExpand Up@@ -402,10 +413,13 @@ impl Bolt12Payment {

/// Returns a [`Refund`] object that can be used to offer a refund payment of the amount given.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [`Refund`]: lightning::offers::refund::Refund
pub fn initiate_refund(
&self, amount_msat: u64, expiry_secs: u32, quantity: Option<u64>,
payer_note: Option<String>,
payer_note: Option<String>, route_parameters: Option<RouteParametersConfig>,
) -> Result<Refund, Error> {
let mut random_bytes = [0u8; 32];
rand::rng().fill_bytes(&mut random_bytes);
Expand All@@ -415,7 +429,8 @@ impl Bolt12Payment {
.duration_since(UNIX_EPOCH)
.unwrap();
let retry_strategy = Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT);
let route_params_config = RouteParametersConfig::default();
let route_parameters =
route_parameters.or(self.config.route_parameters).unwrap_or_default();

let mut refund_builder = self
.channel_manager
Expand All@@ -424,7 +439,7 @@ impl Bolt12Payment {
absolute_expiry,
payment_id,
retry_strategy,
route_params_config,
route_parameters,
)
.map_err(|e| {
log_error!(self.logger, "Failed to create refund builder: {:?}", e);
Expand Down
12 changes: 9 additions & 3 deletions src/payment/unified_qr.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ use bitcoin::address::{NetworkChecked, NetworkUnchecked};
use bitcoin::{Amount, Txid};
use lightning::ln::channelmanager::PaymentId;
use lightning::offers::offer::Offer;
use lightning::routing::router::RouteParametersConfig;
use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, Description};

use crate::error::Error;
Expand DownExpand Up@@ -137,8 +138,13 @@ impl UnifiedQrPayment {
/// Returns a `QrPaymentResult` indicating the outcome of the payment. If an error
/// occurs, an `Error` is returned detailing the issue encountered.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
///
/// [BIP 21]: https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki
pub fn send(&self, uri_str: &str) -> Result<QrPaymentResult, Error> {
pub fn send(
&self, uri_str: &str, route_parameters: Option<RouteParametersConfig>,
) -> Result<QrPaymentResult, Error> {
let uri: bip21::Uri<NetworkUnchecked, Extras> =
uri_str.parse().map_err(|_| Error::InvalidUri)?;

Expand All@@ -147,15 +153,15 @@ impl UnifiedQrPayment {

if let Some(offer) = uri_network_checked.extras.bolt12_offer {
let offer = maybe_wrap(offer);
match self.bolt12_payment.send(&offer, None, None) {
match self.bolt12_payment.send(&offer, None, None, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt12 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT12 offer: {:?}. This is part of a unified QR code payment. Falling back to the BOLT11 invoice.", e),
}
}

if let Some(invoice) = uri_network_checked.extras.bolt11_invoice {
let invoice = maybe_wrap(invoice);
match self.bolt11_invoice.send(&invoice, None) {
match self.bolt11_invoice.send(&invoice, route_parameters) {
Ok(payment_id) => return Ok(QrPaymentResult::Bolt11 { payment_id }),
Err(e) => log_error!(self.logger, "Failed to send BOLT11 invoice: {:?}. This is part of a unified QR code payment. Falling back to the on-chain transaction.", e),
}
Expand Down
21 changes: 14 additions & 7 deletions tests/integration_tests_rust.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -967,7 +967,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let payment_id = node_a
.bolt12_payment()
.send(&offer, expected_quantity, expected_payer_note.clone())
.send(&offer, expected_quantity, expected_payer_note.clone(), None)
.unwrap();

expect_payment_successful_event!(node_a, Some(payment_id), None);
Expand DownExpand Up@@ -1023,7 +1023,7 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
assert!(node_a
.bolt12_payment()
.send_using_amount(&offer, less_than_offer_amount, None, None)
.send_using_amount(&offer, less_than_offer_amount, None, None, None)
.is_err());
let payment_id = node_a
.bolt12_payment()
Expand All@@ -1032,6 +1032,7 @@ async fn simple_bolt12_send_receive() {
expected_amount_msat,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();

Expand DownExpand Up@@ -1089,7 +1090,13 @@ async fn simple_bolt12_send_receive() {
let expected_payer_note = Some("Test".to_string());
let refund = node_b
.bolt12_payment()
.initiate_refund(overpaid_amount, 3600, expected_quantity, expected_payer_note.clone())
.initiate_refund(
overpaid_amount,
3600,
expected_quantity,
expected_payer_note.clone(),
None,
)
.unwrap();
let invoice = node_a.bolt12_payment().request_refund_payment(&refund).unwrap();
expect_payment_received_event!(node_a, overpaid_amount);
Expand DownExpand Up@@ -1275,7 +1282,7 @@ async fn async_payment() {
node_receiver.stop().unwrap();

let payment_id =
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None).unwrap();
node_sender.bolt12_payment().send_using_amount(&offer, 5_000, None, None, None).unwrap();

// Sleep to allow the payment reach a state where the htlc is held and waiting for the receiver to come online.
tokio::time::sleep(std::time::Duration::from_millis(3000)).await;
Expand DownExpand Up@@ -1473,7 +1480,7 @@ async fn unified_qr_send_receive() {

let uqr_payment = node_b.unified_qr_payment().receive(expected_amount_sats, "asdf", expiry_sec);
let uri_str = uqr_payment.clone().unwrap();
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str) {
let offer_payment_id: PaymentId = match node_a.unified_qr_payment().send(&uri_str, None) {
Ok(QrPaymentResult::Bolt12 { payment_id }) => {
println!("\nBolt12 payment sent successfully with PaymentID: {:?}", payment_id);
payment_id
Expand All@@ -1494,7 +1501,7 @@ async fn unified_qr_send_receive() {
// Cut off the BOLT12 part to fallback to BOLT11.
let uri_str_without_offer = uri_str.split("&lno=").next().unwrap();
let invoice_payment_id: PaymentId =
match node_a.unified_qr_payment().send(uri_str_without_offer) {
match node_a.unified_qr_payment().send(uri_str_without_offer, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected Bolt11 payment but got Bolt12");
},
Expand All@@ -1517,7 +1524,7 @@ async fn unified_qr_send_receive() {

// Cut off any lightning part to fallback to on-chain only.
let uri_str_without_lightning = onchain_uqr_payment.split("&lightning=").next().unwrap();
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning) {
let txid = match node_a.unified_qr_payment().send(&uri_str_without_lightning, None) {
Ok(QrPaymentResult::Bolt12 { payment_id: _ }) => {
panic!("Expected on-chain payment but got Bolt12")
},
Expand Down