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
34 changes: 18 additions & 16 deletions lightning/src/blinded_path/message.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -466,15 +466,17 @@ pub enum OffersContext {
OutboundPaymentForRefund {
/// Payment ID used when creating a [`Refund`].
///
/// [`Refund`]: crate::offers::refund::Refund
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid [`Refund`] and
/// for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the blinded path included in the
/// refund for this payment. Without that check, an attacker holding that path could deliver
/// a different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for a refund we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Refund`]: crate::offers::refund::Refund
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for an [`InvoiceRequest`].
///
Expand All@@ -487,15 +489,17 @@ pub enum OffersContext {
OutboundPaymentForOffer {
/// Payment ID used when creating an [`InvoiceRequest`].
///
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid
/// [`InvoiceRequest`] and for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the reply path created for this
/// payment. Without that check, an attacker holding this reply path could deliver a
/// different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for an invoice request we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for a [`Bolt12Invoice`].
///
Expand DownExpand Up@@ -678,7 +682,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(1, OutboundPaymentForRefund) => {
(0, payment_id, required),
(1, nonce, required),
},
(2, InboundPayment) => {
(0, payment_hash, required),
Expand All@@ -690,7 +693,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(4, OutboundPaymentForOffer) => {
(0, payment_id, required),
(1, nonce, required),
},
);

Expand Down
8 changes: 4 additions & 4 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -15075,13 +15075,13 @@ impl<
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);

self.flow.enqueue_invoice_request(
invoice_request.clone(), payment_id, nonce,
invoice_request.clone(), payment_id,
self.get_peers_for_blinded_path()
)?;

let retryable_invoice_request = RetryableInvoiceRequest {
invoice_request: invoice_request.clone(),
nonce,
nonce: Some(nonce),
needs_retry: true,
};

Expand DownExpand Up@@ -17231,11 +17231,11 @@ impl<
for (payment_id, retryable_invoice_request) in
self.pending_outbound_payments.release_invoice_requests_awaiting_invoice()
{
let RetryableInvoiceRequest { invoice_request, nonce, .. } = retryable_invoice_request;
let RetryableInvoiceRequest { invoice_request, .. } = retryable_invoice_request;

let peers = self.get_peers_for_blinded_path();
let enqueue_invreq_res =
self.flow.enqueue_invoice_request(invoice_request, payment_id, nonce, peers);
self.flow.enqueue_invoice_request(invoice_request, payment_id, peers);
if enqueue_invreq_res.is_err() {
log_warn!(
self.logger,
Expand Down
8 changes: 6 additions & 2 deletions lightning/src/ln/outbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -173,14 +173,18 @@ pub(crate) enum PendingOutboundPayment {
#[derive(Clone)]
pub(crate) struct RetryableInvoiceRequest {
pub(crate) invoice_request: InvoiceRequest,
pub(crate) nonce: Nonce,
// No longer used, but written so that the payment can be retried after downgrading to a
// version that verifies invoices using the nonce instead of the payer metadata. Set when
// creating an invoice request and otherwise retains the value read from disk, which may have
// been written by such a version.
pub(crate) nonce: Option<Nonce>,
pub(super) needs_retry: bool,
}

impl_ser_tlv_based!(RetryableInvoiceRequest, {
(0, invoice_request, required),
(1, needs_retry, (default_value, true)),
(2, nonce, required),
(2, nonce, option),
});

impl PendingOutboundPayment {
Expand Down
38 changes: 17 additions & 21 deletions lightning/src/offers/flow.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -484,14 +484,14 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
Ok(InvreqResponseInstructions::SendInvoice(invoice_request))
}

/// Verifies a [`Bolt12Invoice`] using the provided [`OffersContext`] or the invoice's payer
/// metadata, returning the corresponding [`PaymentId`] if successful.
/// Verifies a [`Bolt12Invoice`] using the invoice's payer metadata, returning the
/// corresponding [`PaymentId`] if successful.
///
/// - If an [`OffersContext::OutboundPaymentForOffer`] or
/// [`OffersContext::OutboundPaymentForRefund`] with a `nonce` is provided, verification is
/// performed using this to form the payer metadata.
/// - If no context is provided and the invoice corresponds to a [`Refund`] without blinded paths,
/// verification is performed using the [`Bolt12Invoice::payer_metadata`].
/// [`OffersContext::OutboundPaymentForRefund`] is provided, the extracted [`PaymentId`] must
/// also match the context's `payment_id`.
/// - If no context is provided, the invoice must correspond to a [`Refund`] without blinded
/// paths.
/// - If neither condition is met, verification fails.
pub fn verify_bolt12_invoice(
&self, invoice: &Bolt12Invoice, context: Option<&OffersContext>,
Expand All@@ -503,16 +503,20 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
None if invoice.is_for_refund_without_paths() => {
invoice.verify_using_metadata(expanded_key, secp_ctx)
},
Some(&OffersContext::OutboundPaymentForOffer { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForOffer { payment_id }) => {
if invoice.is_for_offer() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
},
Some(&OffersContext::OutboundPaymentForRefund { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForRefund { payment_id }) => {
if invoice.is_for_refund() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
Expand DownExpand Up@@ -689,7 +693,7 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {

let nonce = Nonce::from_entropy_source(entropy);
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id, nonce });
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id });

// Create the base builder with common properties
let mut builder = RefundBuilder::deriving_signing_pubkey(
Expand DownExpand Up@@ -1085,13 +1089,6 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// over those blinded paths, which can be verified against the intended outbound payment,
/// ensuring the invoice corresponds to a payment we actually want to make.
///
/// # Nonce
/// The nonce is used to create a unique [`MessageContext`] for the reply paths.
/// These will be used to verify the corresponding [`Bolt12Invoice`] when it is received.
///
/// Note: The provided [`Nonce`] MUST be the same as the [`Nonce`] used for creating the
/// [`InvoiceRequest`] to ensure correct verification of the corresponding [`Bolt12Invoice`].
///
/// See [`OffersMessageFlow::create_invoice_request_builder`] for more details.
///
/// # Peers
Expand All@@ -1103,11 +1100,10 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
/// [`supports_onion_messages`]: crate::types::features::Features::supports_onion_messages
pub fn enqueue_invoice_request(
&self, invoice_request: InvoiceRequest, payment_id: PaymentId, nonce: Nonce,
&self, invoice_request: InvoiceRequest, payment_id: PaymentId,
peers: Vec<MessageForwardNode>,
) -> Result<(), Bolt12SemanticError> {
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id, nonce });
let context = MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id });
let reply_paths = self
.create_blinded_paths(peers, context)
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
Expand Down
39 changes: 12 additions & 27 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -133,7 +133,6 @@ use crate::offers::invoice_request::{
use crate::offers::merkle::{
self, SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream,
};
use crate::offers::nonce::Nonce;
use crate::offers::offer::{
Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferId, OfferTlvStream,
OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES,
Expand DownExpand Up@@ -1008,30 +1007,17 @@ impl Bolt12Invoice {
(&invoice_request.inner.payer.0, INVOICE_REQUEST_IV_BYTES)
},
InvoiceContents::ForRefund { refund, .. } => {
(&refund.payer.0, REFUND_IV_BYTES_WITH_METADATA)
let iv_bytes = if refund.paths().is_empty() {
REFUND_IV_BYTES_WITH_METADATA
} else {
REFUND_IV_BYTES_WITHOUT_METADATA
};
(&refund.payer.0, iv_bytes)
},
};
self.contents.verify(&self.bytes, metadata, key, iv_bytes, secp_ctx)
}

/// Verifies that the invoice was for a request or refund created using the given key by
/// checking a payment id and nonce included with the [`BlindedMessagePath`] for which the invoice was
/// sent through.
pub fn verify_using_payer_data<T: secp256k1::Signing>(
&self, payment_id: PaymentId, nonce: Nonce, key: &ExpandedKey, secp_ctx: &Secp256k1<T>,
) -> Result<PaymentId, ()> {
let metadata = Metadata::payer_data(payment_id, nonce, key);
let iv_bytes = match &self.contents {
InvoiceContents::ForOffer { .. } => INVOICE_REQUEST_IV_BYTES,
InvoiceContents::ForRefund { .. } => REFUND_IV_BYTES_WITHOUT_METADATA,
};
self.contents.verify(&self.bytes, &metadata, key, iv_bytes, secp_ctx).and_then(
|extracted_payment_id| {
(payment_id == extracted_payment_id).then(|| payment_id).ok_or(())
},
)
}

pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef<'_> {
let (
payer_tlv_stream,
Expand DownExpand Up@@ -1892,6 +1878,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let payment_paths = payment_paths();
let payment_hash = payment_hash();
Expand All@@ -1913,7 +1901,7 @@ mod tests {
unsigned_invoice.write(&mut buffer).unwrap();

assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
assert_eq!(unsigned_invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(unsigned_invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
unsigned_invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand DownExpand Up@@ -1957,7 +1945,7 @@ mod tests {
invoice.write(&mut buffer).unwrap();

assert_eq!(invoice.bytes, buffer.as_slice());
assert_eq!(invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand All@@ -1975,10 +1963,7 @@ mod tests {
assert_eq!(invoice.amount_msats(), 1000);
assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
assert_eq!(invoice.quantity(), None);
assert_eq!(
invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx),
Ok(payment_id),
);
assert_eq!(invoice.verify_using_metadata(&expanded_key, &secp_ctx), Ok(payment_id));
assert_eq!(invoice.payer_note(), None);
assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
assert_eq!(invoice.created_at(), now);
Expand All@@ -2001,7 +1986,7 @@ mod tests {
assert_eq!(
invoice.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand Down
22 changes: 10 additions & 12 deletions lightning/src/offers/invoice_request.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1588,6 +1588,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let invoice_request = OfferBuilder::new(recipient_pubkey())
.amount_msats(1000)
Expand All@@ -1602,7 +1604,7 @@ mod tests {
invoice_request.write(&mut buffer).unwrap();

assert_eq!(invoice_request.bytes, buffer.as_slice());
assert_eq!(invoice_request.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice_request.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice_request.chains(),
vec![ChainHash::using_genesis_block(Network::Bitcoin)]
Expand DownExpand Up@@ -1634,7 +1636,7 @@ mod tests {
assert_eq!(
invoice_request.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand DownExpand Up@@ -1735,10 +1737,10 @@ mod tests {
.unwrap()
.sign(recipient_sign)
.unwrap();
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_ok());
match invoice.verify_using_metadata(&expanded_key, &secp_ctx) {
Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
Err(()) => panic!("verification failed"),
}

// Fails verification with altered fields
let (
Expand DownExpand Up@@ -1774,9 +1776,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());

// Fails verification with altered payer id
let (
Expand DownExpand Up@@ -1812,9 +1812,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
}

#[test]
Expand Down
Loading
, '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
34 changes: 18 additions & 16 deletions lightning/src/blinded_path/message.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -466,15 +466,17 @@ pub enum OffersContext {
OutboundPaymentForRefund {
/// Payment ID used when creating a [`Refund`].
///
/// [`Refund`]: crate::offers::refund::Refund
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid [`Refund`] and
/// for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the blinded path included in the
/// refund for this payment. Without that check, an attacker holding that path could deliver
/// a different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for a refund we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Refund`]: crate::offers::refund::Refund
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for an [`InvoiceRequest`].
///
Expand All@@ -487,15 +489,17 @@ pub enum OffersContext {
OutboundPaymentForOffer {
/// Payment ID used when creating an [`InvoiceRequest`].
///
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid
/// [`InvoiceRequest`] and for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the reply path created for this
/// payment. Without that check, an attacker holding this reply path could deliver a
/// different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for an invoice request we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for a [`Bolt12Invoice`].
///
Expand DownExpand Up@@ -678,7 +682,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(1, OutboundPaymentForRefund) => {
(0, payment_id, required),
(1, nonce, required),
},
(2, InboundPayment) => {
(0, payment_hash, required),
Expand All@@ -690,7 +693,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(4, OutboundPaymentForOffer) => {
(0, payment_id, required),
(1, nonce, required),
},
);

Expand Down
8 changes: 4 additions & 4 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -15075,13 +15075,13 @@ impl<
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);

self.flow.enqueue_invoice_request(
invoice_request.clone(), payment_id, nonce,
invoice_request.clone(), payment_id,
self.get_peers_for_blinded_path()
)?;

let retryable_invoice_request = RetryableInvoiceRequest {
invoice_request: invoice_request.clone(),
nonce,
nonce: Some(nonce),
needs_retry: true,
};

Expand DownExpand Up@@ -17231,11 +17231,11 @@ impl<
for (payment_id, retryable_invoice_request) in
self.pending_outbound_payments.release_invoice_requests_awaiting_invoice()
{
let RetryableInvoiceRequest { invoice_request, nonce, .. } = retryable_invoice_request;
let RetryableInvoiceRequest { invoice_request, .. } = retryable_invoice_request;

let peers = self.get_peers_for_blinded_path();
let enqueue_invreq_res =
self.flow.enqueue_invoice_request(invoice_request, payment_id, nonce, peers);
self.flow.enqueue_invoice_request(invoice_request, payment_id, peers);
if enqueue_invreq_res.is_err() {
log_warn!(
self.logger,
Expand Down
8 changes: 6 additions & 2 deletions lightning/src/ln/outbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -173,14 +173,18 @@ pub(crate) enum PendingOutboundPayment {
#[derive(Clone)]
pub(crate) struct RetryableInvoiceRequest {
pub(crate) invoice_request: InvoiceRequest,
pub(crate) nonce: Nonce,
// No longer used, but written so that the payment can be retried after downgrading to a
// version that verifies invoices using the nonce instead of the payer metadata. Set when
// creating an invoice request and otherwise retains the value read from disk, which may have
// been written by such a version.
pub(crate) nonce: Option<Nonce>,
pub(super) needs_retry: bool,
}

impl_ser_tlv_based!(RetryableInvoiceRequest, {
(0, invoice_request, required),
(1, needs_retry, (default_value, true)),
(2, nonce, required),
(2, nonce, option),
});

impl PendingOutboundPayment {
Expand Down
38 changes: 17 additions & 21 deletions lightning/src/offers/flow.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -484,14 +484,14 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
Ok(InvreqResponseInstructions::SendInvoice(invoice_request))
}

/// Verifies a [`Bolt12Invoice`] using the provided [`OffersContext`] or the invoice's payer
/// metadata, returning the corresponding [`PaymentId`] if successful.
/// Verifies a [`Bolt12Invoice`] using the invoice's payer metadata, returning the
/// corresponding [`PaymentId`] if successful.
///
/// - If an [`OffersContext::OutboundPaymentForOffer`] or
/// [`OffersContext::OutboundPaymentForRefund`] with a `nonce` is provided, verification is
/// performed using this to form the payer metadata.
/// - If no context is provided and the invoice corresponds to a [`Refund`] without blinded paths,
/// verification is performed using the [`Bolt12Invoice::payer_metadata`].
/// [`OffersContext::OutboundPaymentForRefund`] is provided, the extracted [`PaymentId`] must
/// also match the context's `payment_id`.
/// - If no context is provided, the invoice must correspond to a [`Refund`] without blinded
/// paths.
/// - If neither condition is met, verification fails.
pub fn verify_bolt12_invoice(
&self, invoice: &Bolt12Invoice, context: Option<&OffersContext>,
Expand All@@ -503,16 +503,20 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
None if invoice.is_for_refund_without_paths() => {
invoice.verify_using_metadata(expanded_key, secp_ctx)
},
Some(&OffersContext::OutboundPaymentForOffer { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForOffer { payment_id }) => {
if invoice.is_for_offer() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
},
Some(&OffersContext::OutboundPaymentForRefund { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForRefund { payment_id }) => {
if invoice.is_for_refund() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
Expand DownExpand Up@@ -689,7 +693,7 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {

let nonce = Nonce::from_entropy_source(entropy);
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id, nonce });
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id });

// Create the base builder with common properties
let mut builder = RefundBuilder::deriving_signing_pubkey(
Expand DownExpand Up@@ -1085,13 +1089,6 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// over those blinded paths, which can be verified against the intended outbound payment,
/// ensuring the invoice corresponds to a payment we actually want to make.
///
/// # Nonce
/// The nonce is used to create a unique [`MessageContext`] for the reply paths.
/// These will be used to verify the corresponding [`Bolt12Invoice`] when it is received.
///
/// Note: The provided [`Nonce`] MUST be the same as the [`Nonce`] used for creating the
/// [`InvoiceRequest`] to ensure correct verification of the corresponding [`Bolt12Invoice`].
///
/// See [`OffersMessageFlow::create_invoice_request_builder`] for more details.
///
/// # Peers
Expand All@@ -1103,11 +1100,10 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
/// [`supports_onion_messages`]: crate::types::features::Features::supports_onion_messages
pub fn enqueue_invoice_request(
&self, invoice_request: InvoiceRequest, payment_id: PaymentId, nonce: Nonce,
&self, invoice_request: InvoiceRequest, payment_id: PaymentId,
peers: Vec<MessageForwardNode>,
) -> Result<(), Bolt12SemanticError> {
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id, nonce });
let context = MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id });
let reply_paths = self
.create_blinded_paths(peers, context)
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
Expand Down
39 changes: 12 additions & 27 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -133,7 +133,6 @@ use crate::offers::invoice_request::{
use crate::offers::merkle::{
self, SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream,
};
use crate::offers::nonce::Nonce;
use crate::offers::offer::{
Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferId, OfferTlvStream,
OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES,
Expand DownExpand Up@@ -1008,30 +1007,17 @@ impl Bolt12Invoice {
(&invoice_request.inner.payer.0, INVOICE_REQUEST_IV_BYTES)
},
InvoiceContents::ForRefund { refund, .. } => {
(&refund.payer.0, REFUND_IV_BYTES_WITH_METADATA)
let iv_bytes = if refund.paths().is_empty() {
REFUND_IV_BYTES_WITH_METADATA
} else {
REFUND_IV_BYTES_WITHOUT_METADATA
};
(&refund.payer.0, iv_bytes)
},
};
self.contents.verify(&self.bytes, metadata, key, iv_bytes, secp_ctx)
}

/// Verifies that the invoice was for a request or refund created using the given key by
/// checking a payment id and nonce included with the [`BlindedMessagePath`] for which the invoice was
/// sent through.
pub fn verify_using_payer_data<T: secp256k1::Signing>(
&self, payment_id: PaymentId, nonce: Nonce, key: &ExpandedKey, secp_ctx: &Secp256k1<T>,
) -> Result<PaymentId, ()> {
let metadata = Metadata::payer_data(payment_id, nonce, key);
let iv_bytes = match &self.contents {
InvoiceContents::ForOffer { .. } => INVOICE_REQUEST_IV_BYTES,
InvoiceContents::ForRefund { .. } => REFUND_IV_BYTES_WITHOUT_METADATA,
};
self.contents.verify(&self.bytes, &metadata, key, iv_bytes, secp_ctx).and_then(
|extracted_payment_id| {
(payment_id == extracted_payment_id).then(|| payment_id).ok_or(())
},
)
}

pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef<'_> {
let (
payer_tlv_stream,
Expand DownExpand Up@@ -1892,6 +1878,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let payment_paths = payment_paths();
let payment_hash = payment_hash();
Expand All@@ -1913,7 +1901,7 @@ mod tests {
unsigned_invoice.write(&mut buffer).unwrap();

assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
assert_eq!(unsigned_invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(unsigned_invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
unsigned_invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand DownExpand Up@@ -1957,7 +1945,7 @@ mod tests {
invoice.write(&mut buffer).unwrap();

assert_eq!(invoice.bytes, buffer.as_slice());
assert_eq!(invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand All@@ -1975,10 +1963,7 @@ mod tests {
assert_eq!(invoice.amount_msats(), 1000);
assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
assert_eq!(invoice.quantity(), None);
assert_eq!(
invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx),
Ok(payment_id),
);
assert_eq!(invoice.verify_using_metadata(&expanded_key, &secp_ctx), Ok(payment_id));
assert_eq!(invoice.payer_note(), None);
assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
assert_eq!(invoice.created_at(), now);
Expand All@@ -2001,7 +1986,7 @@ mod tests {
assert_eq!(
invoice.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand Down
22 changes: 10 additions & 12 deletions lightning/src/offers/invoice_request.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1588,6 +1588,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let invoice_request = OfferBuilder::new(recipient_pubkey())
.amount_msats(1000)
Expand All@@ -1602,7 +1604,7 @@ mod tests {
invoice_request.write(&mut buffer).unwrap();

assert_eq!(invoice_request.bytes, buffer.as_slice());
assert_eq!(invoice_request.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice_request.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice_request.chains(),
vec![ChainHash::using_genesis_block(Network::Bitcoin)]
Expand DownExpand Up@@ -1634,7 +1636,7 @@ mod tests {
assert_eq!(
invoice_request.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand DownExpand Up@@ -1735,10 +1737,10 @@ mod tests {
.unwrap()
.sign(recipient_sign)
.unwrap();
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_ok());
match invoice.verify_using_metadata(&expanded_key, &secp_ctx) {
Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
Err(()) => panic!("verification failed"),
}

// Fails verification with altered fields
let (
Expand DownExpand Up@@ -1774,9 +1776,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());

// Fails verification with altered payer id
let (
Expand DownExpand Up@@ -1812,9 +1812,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
}

#[test]
Expand Down
Loading
, '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
34 changes: 18 additions & 16 deletions lightning/src/blinded_path/message.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -466,15 +466,17 @@ pub enum OffersContext {
OutboundPaymentForRefund {
/// Payment ID used when creating a [`Refund`].
///
/// [`Refund`]: crate::offers::refund::Refund
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid [`Refund`] and
/// for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the blinded path included in the
/// refund for this payment. Without that check, an attacker holding that path could deliver
/// a different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for a refund we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Refund`]: crate::offers::refund::Refund
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for an [`InvoiceRequest`].
///
Expand All@@ -487,15 +489,17 @@ pub enum OffersContext {
OutboundPaymentForOffer {
/// Payment ID used when creating an [`InvoiceRequest`].
///
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid
/// [`InvoiceRequest`] and for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the reply path created for this
/// payment. Without that check, an attacker holding this reply path could deliver a
/// different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for an invoice request we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for a [`Bolt12Invoice`].
///
Expand DownExpand Up@@ -678,7 +682,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(1, OutboundPaymentForRefund) => {
(0, payment_id, required),
(1, nonce, required),
},
(2, InboundPayment) => {
(0, payment_hash, required),
Expand All@@ -690,7 +693,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(4, OutboundPaymentForOffer) => {
(0, payment_id, required),
(1, nonce, required),
},
);

Expand Down
8 changes: 4 additions & 4 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -15075,13 +15075,13 @@ impl<
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);

self.flow.enqueue_invoice_request(
invoice_request.clone(), payment_id, nonce,
invoice_request.clone(), payment_id,
self.get_peers_for_blinded_path()
)?;

let retryable_invoice_request = RetryableInvoiceRequest {
invoice_request: invoice_request.clone(),
nonce,
nonce: Some(nonce),
needs_retry: true,
};

Expand DownExpand Up@@ -17231,11 +17231,11 @@ impl<
for (payment_id, retryable_invoice_request) in
self.pending_outbound_payments.release_invoice_requests_awaiting_invoice()
{
let RetryableInvoiceRequest { invoice_request, nonce, .. } = retryable_invoice_request;
let RetryableInvoiceRequest { invoice_request, .. } = retryable_invoice_request;

let peers = self.get_peers_for_blinded_path();
let enqueue_invreq_res =
self.flow.enqueue_invoice_request(invoice_request, payment_id, nonce, peers);
self.flow.enqueue_invoice_request(invoice_request, payment_id, peers);
if enqueue_invreq_res.is_err() {
log_warn!(
self.logger,
Expand Down
8 changes: 6 additions & 2 deletions lightning/src/ln/outbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -173,14 +173,18 @@ pub(crate) enum PendingOutboundPayment {
#[derive(Clone)]
pub(crate) struct RetryableInvoiceRequest {
pub(crate) invoice_request: InvoiceRequest,
pub(crate) nonce: Nonce,
// No longer used, but written so that the payment can be retried after downgrading to a
// version that verifies invoices using the nonce instead of the payer metadata. Set when
// creating an invoice request and otherwise retains the value read from disk, which may have
// been written by such a version.
pub(crate) nonce: Option<Nonce>,
pub(super) needs_retry: bool,
}

impl_ser_tlv_based!(RetryableInvoiceRequest, {
(0, invoice_request, required),
(1, needs_retry, (default_value, true)),
(2, nonce, required),
(2, nonce, option),
});

impl PendingOutboundPayment {
Expand Down
38 changes: 17 additions & 21 deletions lightning/src/offers/flow.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -484,14 +484,14 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
Ok(InvreqResponseInstructions::SendInvoice(invoice_request))
}

/// Verifies a [`Bolt12Invoice`] using the provided [`OffersContext`] or the invoice's payer
/// metadata, returning the corresponding [`PaymentId`] if successful.
/// Verifies a [`Bolt12Invoice`] using the invoice's payer metadata, returning the
/// corresponding [`PaymentId`] if successful.
///
/// - If an [`OffersContext::OutboundPaymentForOffer`] or
/// [`OffersContext::OutboundPaymentForRefund`] with a `nonce` is provided, verification is
/// performed using this to form the payer metadata.
/// - If no context is provided and the invoice corresponds to a [`Refund`] without blinded paths,
/// verification is performed using the [`Bolt12Invoice::payer_metadata`].
/// [`OffersContext::OutboundPaymentForRefund`] is provided, the extracted [`PaymentId`] must
/// also match the context's `payment_id`.
/// - If no context is provided, the invoice must correspond to a [`Refund`] without blinded
/// paths.
/// - If neither condition is met, verification fails.
pub fn verify_bolt12_invoice(
&self, invoice: &Bolt12Invoice, context: Option<&OffersContext>,
Expand All@@ -503,16 +503,20 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
None if invoice.is_for_refund_without_paths() => {
invoice.verify_using_metadata(expanded_key, secp_ctx)
},
Some(&OffersContext::OutboundPaymentForOffer { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForOffer { payment_id }) => {
if invoice.is_for_offer() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
},
Some(&OffersContext::OutboundPaymentForRefund { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForRefund { payment_id }) => {
if invoice.is_for_refund() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
Expand DownExpand Up@@ -689,7 +693,7 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {

let nonce = Nonce::from_entropy_source(entropy);
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id, nonce });
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id });

// Create the base builder with common properties
let mut builder = RefundBuilder::deriving_signing_pubkey(
Expand DownExpand Up@@ -1085,13 +1089,6 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// over those blinded paths, which can be verified against the intended outbound payment,
/// ensuring the invoice corresponds to a payment we actually want to make.
///
/// # Nonce
/// The nonce is used to create a unique [`MessageContext`] for the reply paths.
/// These will be used to verify the corresponding [`Bolt12Invoice`] when it is received.
///
/// Note: The provided [`Nonce`] MUST be the same as the [`Nonce`] used for creating the
/// [`InvoiceRequest`] to ensure correct verification of the corresponding [`Bolt12Invoice`].
///
/// See [`OffersMessageFlow::create_invoice_request_builder`] for more details.
///
/// # Peers
Expand All@@ -1103,11 +1100,10 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
/// [`supports_onion_messages`]: crate::types::features::Features::supports_onion_messages
pub fn enqueue_invoice_request(
&self, invoice_request: InvoiceRequest, payment_id: PaymentId, nonce: Nonce,
&self, invoice_request: InvoiceRequest, payment_id: PaymentId,
peers: Vec<MessageForwardNode>,
) -> Result<(), Bolt12SemanticError> {
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id, nonce });
let context = MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id });
let reply_paths = self
.create_blinded_paths(peers, context)
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
Expand Down
39 changes: 12 additions & 27 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -133,7 +133,6 @@ use crate::offers::invoice_request::{
use crate::offers::merkle::{
self, SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream,
};
use crate::offers::nonce::Nonce;
use crate::offers::offer::{
Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferId, OfferTlvStream,
OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES,
Expand DownExpand Up@@ -1008,30 +1007,17 @@ impl Bolt12Invoice {
(&invoice_request.inner.payer.0, INVOICE_REQUEST_IV_BYTES)
},
InvoiceContents::ForRefund { refund, .. } => {
(&refund.payer.0, REFUND_IV_BYTES_WITH_METADATA)
let iv_bytes = if refund.paths().is_empty() {
REFUND_IV_BYTES_WITH_METADATA
} else {
REFUND_IV_BYTES_WITHOUT_METADATA
};
(&refund.payer.0, iv_bytes)
},
};
self.contents.verify(&self.bytes, metadata, key, iv_bytes, secp_ctx)
}

/// Verifies that the invoice was for a request or refund created using the given key by
/// checking a payment id and nonce included with the [`BlindedMessagePath`] for which the invoice was
/// sent through.
pub fn verify_using_payer_data<T: secp256k1::Signing>(
&self, payment_id: PaymentId, nonce: Nonce, key: &ExpandedKey, secp_ctx: &Secp256k1<T>,
) -> Result<PaymentId, ()> {
let metadata = Metadata::payer_data(payment_id, nonce, key);
let iv_bytes = match &self.contents {
InvoiceContents::ForOffer { .. } => INVOICE_REQUEST_IV_BYTES,
InvoiceContents::ForRefund { .. } => REFUND_IV_BYTES_WITHOUT_METADATA,
};
self.contents.verify(&self.bytes, &metadata, key, iv_bytes, secp_ctx).and_then(
|extracted_payment_id| {
(payment_id == extracted_payment_id).then(|| payment_id).ok_or(())
},
)
}

pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef<'_> {
let (
payer_tlv_stream,
Expand DownExpand Up@@ -1892,6 +1878,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let payment_paths = payment_paths();
let payment_hash = payment_hash();
Expand All@@ -1913,7 +1901,7 @@ mod tests {
unsigned_invoice.write(&mut buffer).unwrap();

assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
assert_eq!(unsigned_invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(unsigned_invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
unsigned_invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand DownExpand Up@@ -1957,7 +1945,7 @@ mod tests {
invoice.write(&mut buffer).unwrap();

assert_eq!(invoice.bytes, buffer.as_slice());
assert_eq!(invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand All@@ -1975,10 +1963,7 @@ mod tests {
assert_eq!(invoice.amount_msats(), 1000);
assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
assert_eq!(invoice.quantity(), None);
assert_eq!(
invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx),
Ok(payment_id),
);
assert_eq!(invoice.verify_using_metadata(&expanded_key, &secp_ctx), Ok(payment_id));
assert_eq!(invoice.payer_note(), None);
assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
assert_eq!(invoice.created_at(), now);
Expand All@@ -2001,7 +1986,7 @@ mod tests {
assert_eq!(
invoice.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand Down
22 changes: 10 additions & 12 deletions lightning/src/offers/invoice_request.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1588,6 +1588,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let invoice_request = OfferBuilder::new(recipient_pubkey())
.amount_msats(1000)
Expand All@@ -1602,7 +1604,7 @@ mod tests {
invoice_request.write(&mut buffer).unwrap();

assert_eq!(invoice_request.bytes, buffer.as_slice());
assert_eq!(invoice_request.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice_request.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice_request.chains(),
vec![ChainHash::using_genesis_block(Network::Bitcoin)]
Expand DownExpand Up@@ -1634,7 +1636,7 @@ mod tests {
assert_eq!(
invoice_request.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand DownExpand Up@@ -1735,10 +1737,10 @@ mod tests {
.unwrap()
.sign(recipient_sign)
.unwrap();
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_ok());
match invoice.verify_using_metadata(&expanded_key, &secp_ctx) {
Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
Err(()) => panic!("verification failed"),
}

// Fails verification with altered fields
let (
Expand DownExpand Up@@ -1774,9 +1776,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());

// Fails verification with altered payer id
let (
Expand DownExpand Up@@ -1812,9 +1812,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
}

#[test]
Expand Down
Loading
, '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
34 changes: 18 additions & 16 deletions lightning/src/blinded_path/message.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -466,15 +466,17 @@ pub enum OffersContext {
OutboundPaymentForRefund {
/// Payment ID used when creating a [`Refund`].
///
/// [`Refund`]: crate::offers::refund::Refund
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid [`Refund`] and
/// for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the blinded path included in the
/// refund for this payment. Without that check, an attacker holding that path could deliver
/// a different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for a refund we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Refund`]: crate::offers::refund::Refund
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for an [`InvoiceRequest`].
///
Expand All@@ -487,15 +489,17 @@ pub enum OffersContext {
OutboundPaymentForOffer {
/// Payment ID used when creating an [`InvoiceRequest`].
///
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid
/// [`InvoiceRequest`] and for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the reply path created for this
/// payment. Without that check, an attacker holding this reply path could deliver a
/// different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for an invoice request we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for a [`Bolt12Invoice`].
///
Expand DownExpand Up@@ -678,7 +682,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(1, OutboundPaymentForRefund) => {
(0, payment_id, required),
(1, nonce, required),
},
(2, InboundPayment) => {
(0, payment_hash, required),
Expand All@@ -690,7 +693,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(4, OutboundPaymentForOffer) => {
(0, payment_id, required),
(1, nonce, required),
},
);

Expand Down
8 changes: 4 additions & 4 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -15075,13 +15075,13 @@ impl<
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);

self.flow.enqueue_invoice_request(
invoice_request.clone(), payment_id, nonce,
invoice_request.clone(), payment_id,
self.get_peers_for_blinded_path()
)?;

let retryable_invoice_request = RetryableInvoiceRequest {
invoice_request: invoice_request.clone(),
nonce,
nonce: Some(nonce),
needs_retry: true,
};

Expand DownExpand Up@@ -17231,11 +17231,11 @@ impl<
for (payment_id, retryable_invoice_request) in
self.pending_outbound_payments.release_invoice_requests_awaiting_invoice()
{
let RetryableInvoiceRequest { invoice_request, nonce, .. } = retryable_invoice_request;
let RetryableInvoiceRequest { invoice_request, .. } = retryable_invoice_request;

let peers = self.get_peers_for_blinded_path();
let enqueue_invreq_res =
self.flow.enqueue_invoice_request(invoice_request, payment_id, nonce, peers);
self.flow.enqueue_invoice_request(invoice_request, payment_id, peers);
if enqueue_invreq_res.is_err() {
log_warn!(
self.logger,
Expand Down
8 changes: 6 additions & 2 deletions lightning/src/ln/outbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -173,14 +173,18 @@ pub(crate) enum PendingOutboundPayment {
#[derive(Clone)]
pub(crate) struct RetryableInvoiceRequest {
pub(crate) invoice_request: InvoiceRequest,
pub(crate) nonce: Nonce,
// No longer used, but written so that the payment can be retried after downgrading to a
// version that verifies invoices using the nonce instead of the payer metadata. Set when
// creating an invoice request and otherwise retains the value read from disk, which may have
// been written by such a version.
pub(crate) nonce: Option<Nonce>,
pub(super) needs_retry: bool,
}

impl_ser_tlv_based!(RetryableInvoiceRequest, {
(0, invoice_request, required),
(1, needs_retry, (default_value, true)),
(2, nonce, required),
(2, nonce, option),
});

impl PendingOutboundPayment {
Expand Down
38 changes: 17 additions & 21 deletions lightning/src/offers/flow.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -484,14 +484,14 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
Ok(InvreqResponseInstructions::SendInvoice(invoice_request))
}

/// Verifies a [`Bolt12Invoice`] using the provided [`OffersContext`] or the invoice's payer
/// metadata, returning the corresponding [`PaymentId`] if successful.
/// Verifies a [`Bolt12Invoice`] using the invoice's payer metadata, returning the
/// corresponding [`PaymentId`] if successful.
///
/// - If an [`OffersContext::OutboundPaymentForOffer`] or
/// [`OffersContext::OutboundPaymentForRefund`] with a `nonce` is provided, verification is
/// performed using this to form the payer metadata.
/// - If no context is provided and the invoice corresponds to a [`Refund`] without blinded paths,
/// verification is performed using the [`Bolt12Invoice::payer_metadata`].
/// [`OffersContext::OutboundPaymentForRefund`] is provided, the extracted [`PaymentId`] must
/// also match the context's `payment_id`.
/// - If no context is provided, the invoice must correspond to a [`Refund`] without blinded
/// paths.
/// - If neither condition is met, verification fails.
pub fn verify_bolt12_invoice(
&self, invoice: &Bolt12Invoice, context: Option<&OffersContext>,
Expand All@@ -503,16 +503,20 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
None if invoice.is_for_refund_without_paths() => {
invoice.verify_using_metadata(expanded_key, secp_ctx)
},
Some(&OffersContext::OutboundPaymentForOffer { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForOffer { payment_id }) => {
if invoice.is_for_offer() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
},
Some(&OffersContext::OutboundPaymentForRefund { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForRefund { payment_id }) => {
if invoice.is_for_refund() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
Expand DownExpand Up@@ -689,7 +693,7 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {

let nonce = Nonce::from_entropy_source(entropy);
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id, nonce });
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id });

// Create the base builder with common properties
let mut builder = RefundBuilder::deriving_signing_pubkey(
Expand DownExpand Up@@ -1085,13 +1089,6 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// over those blinded paths, which can be verified against the intended outbound payment,
/// ensuring the invoice corresponds to a payment we actually want to make.
///
/// # Nonce
/// The nonce is used to create a unique [`MessageContext`] for the reply paths.
/// These will be used to verify the corresponding [`Bolt12Invoice`] when it is received.
///
/// Note: The provided [`Nonce`] MUST be the same as the [`Nonce`] used for creating the
/// [`InvoiceRequest`] to ensure correct verification of the corresponding [`Bolt12Invoice`].
///
/// See [`OffersMessageFlow::create_invoice_request_builder`] for more details.
///
/// # Peers
Expand All@@ -1103,11 +1100,10 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
/// [`supports_onion_messages`]: crate::types::features::Features::supports_onion_messages
pub fn enqueue_invoice_request(
&self, invoice_request: InvoiceRequest, payment_id: PaymentId, nonce: Nonce,
&self, invoice_request: InvoiceRequest, payment_id: PaymentId,
peers: Vec<MessageForwardNode>,
) -> Result<(), Bolt12SemanticError> {
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id, nonce });
let context = MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id });
let reply_paths = self
.create_blinded_paths(peers, context)
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
Expand Down
39 changes: 12 additions & 27 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -133,7 +133,6 @@ use crate::offers::invoice_request::{
use crate::offers::merkle::{
self, SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream,
};
use crate::offers::nonce::Nonce;
use crate::offers::offer::{
Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferId, OfferTlvStream,
OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES,
Expand DownExpand Up@@ -1008,30 +1007,17 @@ impl Bolt12Invoice {
(&invoice_request.inner.payer.0, INVOICE_REQUEST_IV_BYTES)
},
InvoiceContents::ForRefund { refund, .. } => {
(&refund.payer.0, REFUND_IV_BYTES_WITH_METADATA)
let iv_bytes = if refund.paths().is_empty() {
REFUND_IV_BYTES_WITH_METADATA
} else {
REFUND_IV_BYTES_WITHOUT_METADATA
};
(&refund.payer.0, iv_bytes)
},
};
self.contents.verify(&self.bytes, metadata, key, iv_bytes, secp_ctx)
}

/// Verifies that the invoice was for a request or refund created using the given key by
/// checking a payment id and nonce included with the [`BlindedMessagePath`] for which the invoice was
/// sent through.
pub fn verify_using_payer_data<T: secp256k1::Signing>(
&self, payment_id: PaymentId, nonce: Nonce, key: &ExpandedKey, secp_ctx: &Secp256k1<T>,
) -> Result<PaymentId, ()> {
let metadata = Metadata::payer_data(payment_id, nonce, key);
let iv_bytes = match &self.contents {
InvoiceContents::ForOffer { .. } => INVOICE_REQUEST_IV_BYTES,
InvoiceContents::ForRefund { .. } => REFUND_IV_BYTES_WITHOUT_METADATA,
};
self.contents.verify(&self.bytes, &metadata, key, iv_bytes, secp_ctx).and_then(
|extracted_payment_id| {
(payment_id == extracted_payment_id).then(|| payment_id).ok_or(())
},
)
}

pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef<'_> {
let (
payer_tlv_stream,
Expand DownExpand Up@@ -1892,6 +1878,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let payment_paths = payment_paths();
let payment_hash = payment_hash();
Expand All@@ -1913,7 +1901,7 @@ mod tests {
unsigned_invoice.write(&mut buffer).unwrap();

assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
assert_eq!(unsigned_invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(unsigned_invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
unsigned_invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand DownExpand Up@@ -1957,7 +1945,7 @@ mod tests {
invoice.write(&mut buffer).unwrap();

assert_eq!(invoice.bytes, buffer.as_slice());
assert_eq!(invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand All@@ -1975,10 +1963,7 @@ mod tests {
assert_eq!(invoice.amount_msats(), 1000);
assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
assert_eq!(invoice.quantity(), None);
assert_eq!(
invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx),
Ok(payment_id),
);
assert_eq!(invoice.verify_using_metadata(&expanded_key, &secp_ctx), Ok(payment_id));
assert_eq!(invoice.payer_note(), None);
assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
assert_eq!(invoice.created_at(), now);
Expand All@@ -2001,7 +1986,7 @@ mod tests {
assert_eq!(
invoice.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand Down
22 changes: 10 additions & 12 deletions lightning/src/offers/invoice_request.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1588,6 +1588,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let invoice_request = OfferBuilder::new(recipient_pubkey())
.amount_msats(1000)
Expand All@@ -1602,7 +1604,7 @@ mod tests {
invoice_request.write(&mut buffer).unwrap();

assert_eq!(invoice_request.bytes, buffer.as_slice());
assert_eq!(invoice_request.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice_request.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice_request.chains(),
vec![ChainHash::using_genesis_block(Network::Bitcoin)]
Expand DownExpand Up@@ -1634,7 +1636,7 @@ mod tests {
assert_eq!(
invoice_request.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand DownExpand Up@@ -1735,10 +1737,10 @@ mod tests {
.unwrap()
.sign(recipient_sign)
.unwrap();
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_ok());
match invoice.verify_using_metadata(&expanded_key, &secp_ctx) {
Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
Err(()) => panic!("verification failed"),
}

// Fails verification with altered fields
let (
Expand DownExpand Up@@ -1774,9 +1776,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());

// Fails verification with altered payer id
let (
Expand DownExpand Up@@ -1812,9 +1812,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
}

#[test]
Expand Down
Loading
, '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
34 changes: 18 additions & 16 deletions lightning/src/blinded_path/message.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -466,15 +466,17 @@ pub enum OffersContext {
OutboundPaymentForRefund {
/// Payment ID used when creating a [`Refund`].
///
/// [`Refund`]: crate::offers::refund::Refund
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid [`Refund`] and
/// for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the blinded path included in the
/// refund for this payment. Without that check, an attacker holding that path could deliver
/// a different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for a refund we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Refund`]: crate::offers::refund::Refund
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for an [`InvoiceRequest`].
///
Expand All@@ -487,15 +489,17 @@ pub enum OffersContext {
OutboundPaymentForOffer {
/// Payment ID used when creating an [`InvoiceRequest`].
///
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid
/// [`InvoiceRequest`] and for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the reply path created for this
/// payment. Without that check, an attacker holding this reply path could deliver a
/// different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for an invoice request we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for a [`Bolt12Invoice`].
///
Expand DownExpand Up@@ -678,7 +682,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(1, OutboundPaymentForRefund) => {
(0, payment_id, required),
(1, nonce, required),
},
(2, InboundPayment) => {
(0, payment_hash, required),
Expand All@@ -690,7 +693,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(4, OutboundPaymentForOffer) => {
(0, payment_id, required),
(1, nonce, required),
},
);

Expand Down
8 changes: 4 additions & 4 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -15075,13 +15075,13 @@ impl<
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);

self.flow.enqueue_invoice_request(
invoice_request.clone(), payment_id, nonce,
invoice_request.clone(), payment_id,
self.get_peers_for_blinded_path()
)?;

let retryable_invoice_request = RetryableInvoiceRequest {
invoice_request: invoice_request.clone(),
nonce,
nonce: Some(nonce),
needs_retry: true,
};

Expand DownExpand Up@@ -17231,11 +17231,11 @@ impl<
for (payment_id, retryable_invoice_request) in
self.pending_outbound_payments.release_invoice_requests_awaiting_invoice()
{
let RetryableInvoiceRequest { invoice_request, nonce, .. } = retryable_invoice_request;
let RetryableInvoiceRequest { invoice_request, .. } = retryable_invoice_request;

let peers = self.get_peers_for_blinded_path();
let enqueue_invreq_res =
self.flow.enqueue_invoice_request(invoice_request, payment_id, nonce, peers);
self.flow.enqueue_invoice_request(invoice_request, payment_id, peers);
if enqueue_invreq_res.is_err() {
log_warn!(
self.logger,
Expand Down
8 changes: 6 additions & 2 deletions lightning/src/ln/outbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -173,14 +173,18 @@ pub(crate) enum PendingOutboundPayment {
#[derive(Clone)]
pub(crate) struct RetryableInvoiceRequest {
pub(crate) invoice_request: InvoiceRequest,
pub(crate) nonce: Nonce,
// No longer used, but written so that the payment can be retried after downgrading to a
// version that verifies invoices using the nonce instead of the payer metadata. Set when
// creating an invoice request and otherwise retains the value read from disk, which may have
// been written by such a version.
pub(crate) nonce: Option<Nonce>,
pub(super) needs_retry: bool,
}

impl_ser_tlv_based!(RetryableInvoiceRequest, {
(0, invoice_request, required),
(1, needs_retry, (default_value, true)),
(2, nonce, required),
(2, nonce, option),
});

impl PendingOutboundPayment {
Expand Down
38 changes: 17 additions & 21 deletions lightning/src/offers/flow.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -484,14 +484,14 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
Ok(InvreqResponseInstructions::SendInvoice(invoice_request))
}

/// Verifies a [`Bolt12Invoice`] using the provided [`OffersContext`] or the invoice's payer
/// metadata, returning the corresponding [`PaymentId`] if successful.
/// Verifies a [`Bolt12Invoice`] using the invoice's payer metadata, returning the
/// corresponding [`PaymentId`] if successful.
///
/// - If an [`OffersContext::OutboundPaymentForOffer`] or
/// [`OffersContext::OutboundPaymentForRefund`] with a `nonce` is provided, verification is
/// performed using this to form the payer metadata.
/// - If no context is provided and the invoice corresponds to a [`Refund`] without blinded paths,
/// verification is performed using the [`Bolt12Invoice::payer_metadata`].
/// [`OffersContext::OutboundPaymentForRefund`] is provided, the extracted [`PaymentId`] must
/// also match the context's `payment_id`.
/// - If no context is provided, the invoice must correspond to a [`Refund`] without blinded
/// paths.
/// - If neither condition is met, verification fails.
pub fn verify_bolt12_invoice(
&self, invoice: &Bolt12Invoice, context: Option<&OffersContext>,
Expand All@@ -503,16 +503,20 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
None if invoice.is_for_refund_without_paths() => {
invoice.verify_using_metadata(expanded_key, secp_ctx)
},
Some(&OffersContext::OutboundPaymentForOffer { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForOffer { payment_id }) => {
if invoice.is_for_offer() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
},
Some(&OffersContext::OutboundPaymentForRefund { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForRefund { payment_id }) => {
if invoice.is_for_refund() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
Expand DownExpand Up@@ -689,7 +693,7 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {

let nonce = Nonce::from_entropy_source(entropy);
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id, nonce });
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id });

// Create the base builder with common properties
let mut builder = RefundBuilder::deriving_signing_pubkey(
Expand DownExpand Up@@ -1085,13 +1089,6 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// over those blinded paths, which can be verified against the intended outbound payment,
/// ensuring the invoice corresponds to a payment we actually want to make.
///
/// # Nonce
/// The nonce is used to create a unique [`MessageContext`] for the reply paths.
/// These will be used to verify the corresponding [`Bolt12Invoice`] when it is received.
///
/// Note: The provided [`Nonce`] MUST be the same as the [`Nonce`] used for creating the
/// [`InvoiceRequest`] to ensure correct verification of the corresponding [`Bolt12Invoice`].
///
/// See [`OffersMessageFlow::create_invoice_request_builder`] for more details.
///
/// # Peers
Expand All@@ -1103,11 +1100,10 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
/// [`supports_onion_messages`]: crate::types::features::Features::supports_onion_messages
pub fn enqueue_invoice_request(
&self, invoice_request: InvoiceRequest, payment_id: PaymentId, nonce: Nonce,
&self, invoice_request: InvoiceRequest, payment_id: PaymentId,
peers: Vec<MessageForwardNode>,
) -> Result<(), Bolt12SemanticError> {
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id, nonce });
let context = MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id });
let reply_paths = self
.create_blinded_paths(peers, context)
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
Expand Down
39 changes: 12 additions & 27 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -133,7 +133,6 @@ use crate::offers::invoice_request::{
use crate::offers::merkle::{
self, SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream,
};
use crate::offers::nonce::Nonce;
use crate::offers::offer::{
Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferId, OfferTlvStream,
OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES,
Expand DownExpand Up@@ -1008,30 +1007,17 @@ impl Bolt12Invoice {
(&invoice_request.inner.payer.0, INVOICE_REQUEST_IV_BYTES)
},
InvoiceContents::ForRefund { refund, .. } => {
(&refund.payer.0, REFUND_IV_BYTES_WITH_METADATA)
let iv_bytes = if refund.paths().is_empty() {
REFUND_IV_BYTES_WITH_METADATA
} else {
REFUND_IV_BYTES_WITHOUT_METADATA
};
(&refund.payer.0, iv_bytes)
},
};
self.contents.verify(&self.bytes, metadata, key, iv_bytes, secp_ctx)
}

/// Verifies that the invoice was for a request or refund created using the given key by
/// checking a payment id and nonce included with the [`BlindedMessagePath`] for which the invoice was
/// sent through.
pub fn verify_using_payer_data<T: secp256k1::Signing>(
&self, payment_id: PaymentId, nonce: Nonce, key: &ExpandedKey, secp_ctx: &Secp256k1<T>,
) -> Result<PaymentId, ()> {
let metadata = Metadata::payer_data(payment_id, nonce, key);
let iv_bytes = match &self.contents {
InvoiceContents::ForOffer { .. } => INVOICE_REQUEST_IV_BYTES,
InvoiceContents::ForRefund { .. } => REFUND_IV_BYTES_WITHOUT_METADATA,
};
self.contents.verify(&self.bytes, &metadata, key, iv_bytes, secp_ctx).and_then(
|extracted_payment_id| {
(payment_id == extracted_payment_id).then(|| payment_id).ok_or(())
},
)
}

pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef<'_> {
let (
payer_tlv_stream,
Expand DownExpand Up@@ -1892,6 +1878,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let payment_paths = payment_paths();
let payment_hash = payment_hash();
Expand All@@ -1913,7 +1901,7 @@ mod tests {
unsigned_invoice.write(&mut buffer).unwrap();

assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
assert_eq!(unsigned_invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(unsigned_invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
unsigned_invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand DownExpand Up@@ -1957,7 +1945,7 @@ mod tests {
invoice.write(&mut buffer).unwrap();

assert_eq!(invoice.bytes, buffer.as_slice());
assert_eq!(invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand All@@ -1975,10 +1963,7 @@ mod tests {
assert_eq!(invoice.amount_msats(), 1000);
assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
assert_eq!(invoice.quantity(), None);
assert_eq!(
invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx),
Ok(payment_id),
);
assert_eq!(invoice.verify_using_metadata(&expanded_key, &secp_ctx), Ok(payment_id));
assert_eq!(invoice.payer_note(), None);
assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
assert_eq!(invoice.created_at(), now);
Expand All@@ -2001,7 +1986,7 @@ mod tests {
assert_eq!(
invoice.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand Down
22 changes: 10 additions & 12 deletions lightning/src/offers/invoice_request.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1588,6 +1588,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let invoice_request = OfferBuilder::new(recipient_pubkey())
.amount_msats(1000)
Expand All@@ -1602,7 +1604,7 @@ mod tests {
invoice_request.write(&mut buffer).unwrap();

assert_eq!(invoice_request.bytes, buffer.as_slice());
assert_eq!(invoice_request.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice_request.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice_request.chains(),
vec![ChainHash::using_genesis_block(Network::Bitcoin)]
Expand DownExpand Up@@ -1634,7 +1636,7 @@ mod tests {
assert_eq!(
invoice_request.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand DownExpand Up@@ -1735,10 +1737,10 @@ mod tests {
.unwrap()
.sign(recipient_sign)
.unwrap();
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_ok());
match invoice.verify_using_metadata(&expanded_key, &secp_ctx) {
Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
Err(()) => panic!("verification failed"),
}

// Fails verification with altered fields
let (
Expand DownExpand Up@@ -1774,9 +1776,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());

// Fails verification with altered payer id
let (
Expand DownExpand Up@@ -1812,9 +1812,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
}

#[test]
Expand Down
Loading
, '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
34 changes: 18 additions & 16 deletions lightning/src/blinded_path/message.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -466,15 +466,17 @@ pub enum OffersContext {
OutboundPaymentForRefund {
/// Payment ID used when creating a [`Refund`].
///
/// [`Refund`]: crate::offers::refund::Refund
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid [`Refund`] and
/// for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the blinded path included in the
/// refund for this payment. Without that check, an attacker holding that path could deliver
/// a different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for a refund we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Refund`]: crate::offers::refund::Refund
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for an [`InvoiceRequest`].
///
Expand All@@ -487,15 +489,17 @@ pub enum OffersContext {
OutboundPaymentForOffer {
/// Payment ID used when creating an [`InvoiceRequest`].
///
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid
/// [`InvoiceRequest`] and for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the reply path created for this
/// payment. Without that check, an attacker holding this reply path could deliver a
/// different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for an invoice request we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for a [`Bolt12Invoice`].
///
Expand DownExpand Up@@ -678,7 +682,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(1, OutboundPaymentForRefund) => {
(0, payment_id, required),
(1, nonce, required),
},
(2, InboundPayment) => {
(0, payment_hash, required),
Expand All@@ -690,7 +693,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(4, OutboundPaymentForOffer) => {
(0, payment_id, required),
(1, nonce, required),
},
);

Expand Down
8 changes: 4 additions & 4 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -15075,13 +15075,13 @@ impl<
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);

self.flow.enqueue_invoice_request(
invoice_request.clone(), payment_id, nonce,
invoice_request.clone(), payment_id,
self.get_peers_for_blinded_path()
)?;

let retryable_invoice_request = RetryableInvoiceRequest {
invoice_request: invoice_request.clone(),
nonce,
nonce: Some(nonce),
needs_retry: true,
};

Expand DownExpand Up@@ -17231,11 +17231,11 @@ impl<
for (payment_id, retryable_invoice_request) in
self.pending_outbound_payments.release_invoice_requests_awaiting_invoice()
{
let RetryableInvoiceRequest { invoice_request, nonce, .. } = retryable_invoice_request;
let RetryableInvoiceRequest { invoice_request, .. } = retryable_invoice_request;

let peers = self.get_peers_for_blinded_path();
let enqueue_invreq_res =
self.flow.enqueue_invoice_request(invoice_request, payment_id, nonce, peers);
self.flow.enqueue_invoice_request(invoice_request, payment_id, peers);
if enqueue_invreq_res.is_err() {
log_warn!(
self.logger,
Expand Down
8 changes: 6 additions & 2 deletions lightning/src/ln/outbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -173,14 +173,18 @@ pub(crate) enum PendingOutboundPayment {
#[derive(Clone)]
pub(crate) struct RetryableInvoiceRequest {
pub(crate) invoice_request: InvoiceRequest,
pub(crate) nonce: Nonce,
// No longer used, but written so that the payment can be retried after downgrading to a
// version that verifies invoices using the nonce instead of the payer metadata. Set when
// creating an invoice request and otherwise retains the value read from disk, which may have
// been written by such a version.
pub(crate) nonce: Option<Nonce>,
pub(super) needs_retry: bool,
}

impl_ser_tlv_based!(RetryableInvoiceRequest, {
(0, invoice_request, required),
(1, needs_retry, (default_value, true)),
(2, nonce, required),
(2, nonce, option),
});

impl PendingOutboundPayment {
Expand Down
38 changes: 17 additions & 21 deletions lightning/src/offers/flow.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -484,14 +484,14 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
Ok(InvreqResponseInstructions::SendInvoice(invoice_request))
}

/// Verifies a [`Bolt12Invoice`] using the provided [`OffersContext`] or the invoice's payer
/// metadata, returning the corresponding [`PaymentId`] if successful.
/// Verifies a [`Bolt12Invoice`] using the invoice's payer metadata, returning the
/// corresponding [`PaymentId`] if successful.
///
/// - If an [`OffersContext::OutboundPaymentForOffer`] or
/// [`OffersContext::OutboundPaymentForRefund`] with a `nonce` is provided, verification is
/// performed using this to form the payer metadata.
/// - If no context is provided and the invoice corresponds to a [`Refund`] without blinded paths,
/// verification is performed using the [`Bolt12Invoice::payer_metadata`].
/// [`OffersContext::OutboundPaymentForRefund`] is provided, the extracted [`PaymentId`] must
/// also match the context's `payment_id`.
/// - If no context is provided, the invoice must correspond to a [`Refund`] without blinded
/// paths.
/// - If neither condition is met, verification fails.
pub fn verify_bolt12_invoice(
&self, invoice: &Bolt12Invoice, context: Option<&OffersContext>,
Expand All@@ -503,16 +503,20 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
None if invoice.is_for_refund_without_paths() => {
invoice.verify_using_metadata(expanded_key, secp_ctx)
},
Some(&OffersContext::OutboundPaymentForOffer { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForOffer { payment_id }) => {
if invoice.is_for_offer() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
},
Some(&OffersContext::OutboundPaymentForRefund { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForRefund { payment_id }) => {
if invoice.is_for_refund() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
Expand DownExpand Up@@ -689,7 +693,7 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {

let nonce = Nonce::from_entropy_source(entropy);
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id, nonce });
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id });

// Create the base builder with common properties
let mut builder = RefundBuilder::deriving_signing_pubkey(
Expand DownExpand Up@@ -1085,13 +1089,6 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// over those blinded paths, which can be verified against the intended outbound payment,
/// ensuring the invoice corresponds to a payment we actually want to make.
///
/// # Nonce
/// The nonce is used to create a unique [`MessageContext`] for the reply paths.
/// These will be used to verify the corresponding [`Bolt12Invoice`] when it is received.
///
/// Note: The provided [`Nonce`] MUST be the same as the [`Nonce`] used for creating the
/// [`InvoiceRequest`] to ensure correct verification of the corresponding [`Bolt12Invoice`].
///
/// See [`OffersMessageFlow::create_invoice_request_builder`] for more details.
///
/// # Peers
Expand All@@ -1103,11 +1100,10 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
/// [`supports_onion_messages`]: crate::types::features::Features::supports_onion_messages
pub fn enqueue_invoice_request(
&self, invoice_request: InvoiceRequest, payment_id: PaymentId, nonce: Nonce,
&self, invoice_request: InvoiceRequest, payment_id: PaymentId,
peers: Vec<MessageForwardNode>,
) -> Result<(), Bolt12SemanticError> {
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id, nonce });
let context = MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id });
let reply_paths = self
.create_blinded_paths(peers, context)
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
Expand Down
39 changes: 12 additions & 27 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -133,7 +133,6 @@ use crate::offers::invoice_request::{
use crate::offers::merkle::{
self, SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream,
};
use crate::offers::nonce::Nonce;
use crate::offers::offer::{
Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferId, OfferTlvStream,
OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES,
Expand DownExpand Up@@ -1008,30 +1007,17 @@ impl Bolt12Invoice {
(&invoice_request.inner.payer.0, INVOICE_REQUEST_IV_BYTES)
},
InvoiceContents::ForRefund { refund, .. } => {
(&refund.payer.0, REFUND_IV_BYTES_WITH_METADATA)
let iv_bytes = if refund.paths().is_empty() {
REFUND_IV_BYTES_WITH_METADATA
} else {
REFUND_IV_BYTES_WITHOUT_METADATA
};
(&refund.payer.0, iv_bytes)
},
};
self.contents.verify(&self.bytes, metadata, key, iv_bytes, secp_ctx)
}

/// Verifies that the invoice was for a request or refund created using the given key by
/// checking a payment id and nonce included with the [`BlindedMessagePath`] for which the invoice was
/// sent through.
pub fn verify_using_payer_data<T: secp256k1::Signing>(
&self, payment_id: PaymentId, nonce: Nonce, key: &ExpandedKey, secp_ctx: &Secp256k1<T>,
) -> Result<PaymentId, ()> {
let metadata = Metadata::payer_data(payment_id, nonce, key);
let iv_bytes = match &self.contents {
InvoiceContents::ForOffer { .. } => INVOICE_REQUEST_IV_BYTES,
InvoiceContents::ForRefund { .. } => REFUND_IV_BYTES_WITHOUT_METADATA,
};
self.contents.verify(&self.bytes, &metadata, key, iv_bytes, secp_ctx).and_then(
|extracted_payment_id| {
(payment_id == extracted_payment_id).then(|| payment_id).ok_or(())
},
)
}

pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef<'_> {
let (
payer_tlv_stream,
Expand DownExpand Up@@ -1892,6 +1878,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let payment_paths = payment_paths();
let payment_hash = payment_hash();
Expand All@@ -1913,7 +1901,7 @@ mod tests {
unsigned_invoice.write(&mut buffer).unwrap();

assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
assert_eq!(unsigned_invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(unsigned_invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
unsigned_invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand DownExpand Up@@ -1957,7 +1945,7 @@ mod tests {
invoice.write(&mut buffer).unwrap();

assert_eq!(invoice.bytes, buffer.as_slice());
assert_eq!(invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand All@@ -1975,10 +1963,7 @@ mod tests {
assert_eq!(invoice.amount_msats(), 1000);
assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
assert_eq!(invoice.quantity(), None);
assert_eq!(
invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx),
Ok(payment_id),
);
assert_eq!(invoice.verify_using_metadata(&expanded_key, &secp_ctx), Ok(payment_id));
assert_eq!(invoice.payer_note(), None);
assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
assert_eq!(invoice.created_at(), now);
Expand All@@ -2001,7 +1986,7 @@ mod tests {
assert_eq!(
invoice.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand Down
22 changes: 10 additions & 12 deletions lightning/src/offers/invoice_request.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1588,6 +1588,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let invoice_request = OfferBuilder::new(recipient_pubkey())
.amount_msats(1000)
Expand All@@ -1602,7 +1604,7 @@ mod tests {
invoice_request.write(&mut buffer).unwrap();

assert_eq!(invoice_request.bytes, buffer.as_slice());
assert_eq!(invoice_request.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice_request.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice_request.chains(),
vec![ChainHash::using_genesis_block(Network::Bitcoin)]
Expand DownExpand Up@@ -1634,7 +1636,7 @@ mod tests {
assert_eq!(
invoice_request.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand DownExpand Up@@ -1735,10 +1737,10 @@ mod tests {
.unwrap()
.sign(recipient_sign)
.unwrap();
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_ok());
match invoice.verify_using_metadata(&expanded_key, &secp_ctx) {
Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
Err(()) => panic!("verification failed"),
}

// Fails verification with altered fields
let (
Expand DownExpand Up@@ -1774,9 +1776,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());

// Fails verification with altered payer id
let (
Expand DownExpand Up@@ -1812,9 +1812,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
}

#[test]
Expand Down
Loading
, '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
34 changes: 18 additions & 16 deletions lightning/src/blinded_path/message.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -466,15 +466,17 @@ pub enum OffersContext {
OutboundPaymentForRefund {
/// Payment ID used when creating a [`Refund`].
///
/// [`Refund`]: crate::offers::refund::Refund
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid [`Refund`] and
/// for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the blinded path included in the
/// refund for this payment. Without that check, an attacker holding that path could deliver
/// a different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for a refund we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Refund`]: crate::offers::refund::Refund
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for an [`InvoiceRequest`].
///
Expand All@@ -487,15 +489,17 @@ pub enum OffersContext {
OutboundPaymentForOffer {
/// Payment ID used when creating an [`InvoiceRequest`].
///
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid
/// [`InvoiceRequest`] and for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the reply path created for this
/// payment. Without that check, an attacker holding this reply path could deliver a
/// different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for an invoice request we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for a [`Bolt12Invoice`].
///
Expand DownExpand Up@@ -678,7 +682,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(1, OutboundPaymentForRefund) => {
(0, payment_id, required),
(1, nonce, required),
},
(2, InboundPayment) => {
(0, payment_hash, required),
Expand All@@ -690,7 +693,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(4, OutboundPaymentForOffer) => {
(0, payment_id, required),
(1, nonce, required),
},
);

Expand Down
8 changes: 4 additions & 4 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -15075,13 +15075,13 @@ impl<
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);

self.flow.enqueue_invoice_request(
invoice_request.clone(), payment_id, nonce,
invoice_request.clone(), payment_id,
self.get_peers_for_blinded_path()
)?;

let retryable_invoice_request = RetryableInvoiceRequest {
invoice_request: invoice_request.clone(),
nonce,
nonce: Some(nonce),
needs_retry: true,
};

Expand DownExpand Up@@ -17231,11 +17231,11 @@ impl<
for (payment_id, retryable_invoice_request) in
self.pending_outbound_payments.release_invoice_requests_awaiting_invoice()
{
let RetryableInvoiceRequest { invoice_request, nonce, .. } = retryable_invoice_request;
let RetryableInvoiceRequest { invoice_request, .. } = retryable_invoice_request;

let peers = self.get_peers_for_blinded_path();
let enqueue_invreq_res =
self.flow.enqueue_invoice_request(invoice_request, payment_id, nonce, peers);
self.flow.enqueue_invoice_request(invoice_request, payment_id, peers);
if enqueue_invreq_res.is_err() {
log_warn!(
self.logger,
Expand Down
8 changes: 6 additions & 2 deletions lightning/src/ln/outbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -173,14 +173,18 @@ pub(crate) enum PendingOutboundPayment {
#[derive(Clone)]
pub(crate) struct RetryableInvoiceRequest {
pub(crate) invoice_request: InvoiceRequest,
pub(crate) nonce: Nonce,
// No longer used, but written so that the payment can be retried after downgrading to a
// version that verifies invoices using the nonce instead of the payer metadata. Set when
// creating an invoice request and otherwise retains the value read from disk, which may have
// been written by such a version.
pub(crate) nonce: Option<Nonce>,
pub(super) needs_retry: bool,
}

impl_ser_tlv_based!(RetryableInvoiceRequest, {
(0, invoice_request, required),
(1, needs_retry, (default_value, true)),
(2, nonce, required),
(2, nonce, option),
});

impl PendingOutboundPayment {
Expand Down
38 changes: 17 additions & 21 deletions lightning/src/offers/flow.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -484,14 +484,14 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
Ok(InvreqResponseInstructions::SendInvoice(invoice_request))
}

/// Verifies a [`Bolt12Invoice`] using the provided [`OffersContext`] or the invoice's payer
/// metadata, returning the corresponding [`PaymentId`] if successful.
/// Verifies a [`Bolt12Invoice`] using the invoice's payer metadata, returning the
/// corresponding [`PaymentId`] if successful.
///
/// - If an [`OffersContext::OutboundPaymentForOffer`] or
/// [`OffersContext::OutboundPaymentForRefund`] with a `nonce` is provided, verification is
/// performed using this to form the payer metadata.
/// - If no context is provided and the invoice corresponds to a [`Refund`] without blinded paths,
/// verification is performed using the [`Bolt12Invoice::payer_metadata`].
/// [`OffersContext::OutboundPaymentForRefund`] is provided, the extracted [`PaymentId`] must
/// also match the context's `payment_id`.
/// - If no context is provided, the invoice must correspond to a [`Refund`] without blinded
/// paths.
/// - If neither condition is met, verification fails.
pub fn verify_bolt12_invoice(
&self, invoice: &Bolt12Invoice, context: Option<&OffersContext>,
Expand All@@ -503,16 +503,20 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
None if invoice.is_for_refund_without_paths() => {
invoice.verify_using_metadata(expanded_key, secp_ctx)
},
Some(&OffersContext::OutboundPaymentForOffer { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForOffer { payment_id }) => {
if invoice.is_for_offer() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
},
Some(&OffersContext::OutboundPaymentForRefund { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForRefund { payment_id }) => {
if invoice.is_for_refund() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
Expand DownExpand Up@@ -689,7 +693,7 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {

let nonce = Nonce::from_entropy_source(entropy);
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id, nonce });
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id });

// Create the base builder with common properties
let mut builder = RefundBuilder::deriving_signing_pubkey(
Expand DownExpand Up@@ -1085,13 +1089,6 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// over those blinded paths, which can be verified against the intended outbound payment,
/// ensuring the invoice corresponds to a payment we actually want to make.
///
/// # Nonce
/// The nonce is used to create a unique [`MessageContext`] for the reply paths.
/// These will be used to verify the corresponding [`Bolt12Invoice`] when it is received.
///
/// Note: The provided [`Nonce`] MUST be the same as the [`Nonce`] used for creating the
/// [`InvoiceRequest`] to ensure correct verification of the corresponding [`Bolt12Invoice`].
///
/// See [`OffersMessageFlow::create_invoice_request_builder`] for more details.
///
/// # Peers
Expand All@@ -1103,11 +1100,10 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
/// [`supports_onion_messages`]: crate::types::features::Features::supports_onion_messages
pub fn enqueue_invoice_request(
&self, invoice_request: InvoiceRequest, payment_id: PaymentId, nonce: Nonce,
&self, invoice_request: InvoiceRequest, payment_id: PaymentId,
peers: Vec<MessageForwardNode>,
) -> Result<(), Bolt12SemanticError> {
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id, nonce });
let context = MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id });
let reply_paths = self
.create_blinded_paths(peers, context)
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
Expand Down
39 changes: 12 additions & 27 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -133,7 +133,6 @@ use crate::offers::invoice_request::{
use crate::offers::merkle::{
self, SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream,
};
use crate::offers::nonce::Nonce;
use crate::offers::offer::{
Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferId, OfferTlvStream,
OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES,
Expand DownExpand Up@@ -1008,30 +1007,17 @@ impl Bolt12Invoice {
(&invoice_request.inner.payer.0, INVOICE_REQUEST_IV_BYTES)
},
InvoiceContents::ForRefund { refund, .. } => {
(&refund.payer.0, REFUND_IV_BYTES_WITH_METADATA)
let iv_bytes = if refund.paths().is_empty() {
REFUND_IV_BYTES_WITH_METADATA
} else {
REFUND_IV_BYTES_WITHOUT_METADATA
};
(&refund.payer.0, iv_bytes)
},
};
self.contents.verify(&self.bytes, metadata, key, iv_bytes, secp_ctx)
}

/// Verifies that the invoice was for a request or refund created using the given key by
/// checking a payment id and nonce included with the [`BlindedMessagePath`] for which the invoice was
/// sent through.
pub fn verify_using_payer_data<T: secp256k1::Signing>(
&self, payment_id: PaymentId, nonce: Nonce, key: &ExpandedKey, secp_ctx: &Secp256k1<T>,
) -> Result<PaymentId, ()> {
let metadata = Metadata::payer_data(payment_id, nonce, key);
let iv_bytes = match &self.contents {
InvoiceContents::ForOffer { .. } => INVOICE_REQUEST_IV_BYTES,
InvoiceContents::ForRefund { .. } => REFUND_IV_BYTES_WITHOUT_METADATA,
};
self.contents.verify(&self.bytes, &metadata, key, iv_bytes, secp_ctx).and_then(
|extracted_payment_id| {
(payment_id == extracted_payment_id).then(|| payment_id).ok_or(())
},
)
}

pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef<'_> {
let (
payer_tlv_stream,
Expand DownExpand Up@@ -1892,6 +1878,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let payment_paths = payment_paths();
let payment_hash = payment_hash();
Expand All@@ -1913,7 +1901,7 @@ mod tests {
unsigned_invoice.write(&mut buffer).unwrap();

assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
assert_eq!(unsigned_invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(unsigned_invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
unsigned_invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand DownExpand Up@@ -1957,7 +1945,7 @@ mod tests {
invoice.write(&mut buffer).unwrap();

assert_eq!(invoice.bytes, buffer.as_slice());
assert_eq!(invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand All@@ -1975,10 +1963,7 @@ mod tests {
assert_eq!(invoice.amount_msats(), 1000);
assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
assert_eq!(invoice.quantity(), None);
assert_eq!(
invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx),
Ok(payment_id),
);
assert_eq!(invoice.verify_using_metadata(&expanded_key, &secp_ctx), Ok(payment_id));
assert_eq!(invoice.payer_note(), None);
assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
assert_eq!(invoice.created_at(), now);
Expand All@@ -2001,7 +1986,7 @@ mod tests {
assert_eq!(
invoice.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand Down
22 changes: 10 additions & 12 deletions lightning/src/offers/invoice_request.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1588,6 +1588,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let invoice_request = OfferBuilder::new(recipient_pubkey())
.amount_msats(1000)
Expand All@@ -1602,7 +1604,7 @@ mod tests {
invoice_request.write(&mut buffer).unwrap();

assert_eq!(invoice_request.bytes, buffer.as_slice());
assert_eq!(invoice_request.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice_request.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice_request.chains(),
vec![ChainHash::using_genesis_block(Network::Bitcoin)]
Expand DownExpand Up@@ -1634,7 +1636,7 @@ mod tests {
assert_eq!(
invoice_request.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand DownExpand Up@@ -1735,10 +1737,10 @@ mod tests {
.unwrap()
.sign(recipient_sign)
.unwrap();
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_ok());
match invoice.verify_using_metadata(&expanded_key, &secp_ctx) {
Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
Err(()) => panic!("verification failed"),
}

// Fails verification with altered fields
let (
Expand DownExpand Up@@ -1774,9 +1776,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());

// Fails verification with altered payer id
let (
Expand DownExpand Up@@ -1812,9 +1812,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
}

#[test]
Expand Down
Loading
, '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
34 changes: 18 additions & 16 deletions lightning/src/blinded_path/message.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -466,15 +466,17 @@ pub enum OffersContext {
OutboundPaymentForRefund {
/// Payment ID used when creating a [`Refund`].
///
/// [`Refund`]: crate::offers::refund::Refund
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid [`Refund`] and
/// for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the blinded path included in the
/// refund for this payment. Without that check, an attacker holding that path could deliver
/// a different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for a refund we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Refund`]: crate::offers::refund::Refund
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for an [`InvoiceRequest`].
///
Expand All@@ -487,15 +489,17 @@ pub enum OffersContext {
OutboundPaymentForOffer {
/// Payment ID used when creating an [`InvoiceRequest`].
///
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
payment_id: PaymentId,

/// A nonce used for authenticating that a [`Bolt12Invoice`] is for a valid
/// [`InvoiceRequest`] and for deriving its signing keys.
/// When a [`Bolt12Invoice`] is received, the payment id recovered from its payer metadata
/// must equal this one, confirming the invoice arrived over the reply path created for this
/// payment. Without that check, an attacker holding this reply path could deliver a
/// different payment's invoice over it, and our paying it would reveal that both payments
/// came from us. That the invoice is for an invoice request we created is verified by
/// [`Bolt12Invoice::verify_using_metadata`] using its payer metadata.
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
nonce: Nonce,
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
/// [`Bolt12Invoice::verify_using_metadata`]: crate::offers::invoice::Bolt12Invoice::verify_using_metadata
payment_id: PaymentId,
},
/// Context used by a [`BlindedMessagePath`] as a reply path for a [`Bolt12Invoice`].
///
Expand DownExpand Up@@ -678,7 +682,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(1, OutboundPaymentForRefund) => {
(0, payment_id, required),
(1, nonce, required),
},
(2, InboundPayment) => {
(0, payment_hash, required),
Expand All@@ -690,7 +693,6 @@ impl_ser_tlv_based_enum!(OffersContext,
},
(4, OutboundPaymentForOffer) => {
(0, payment_id, required),
(1, nonce, required),
},
);

Expand Down
8 changes: 4 additions & 4 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -15075,13 +15075,13 @@ impl<
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);

self.flow.enqueue_invoice_request(
invoice_request.clone(), payment_id, nonce,
invoice_request.clone(), payment_id,
self.get_peers_for_blinded_path()
)?;

let retryable_invoice_request = RetryableInvoiceRequest {
invoice_request: invoice_request.clone(),
nonce,
nonce: Some(nonce),
needs_retry: true,
};

Expand DownExpand Up@@ -17231,11 +17231,11 @@ impl<
for (payment_id, retryable_invoice_request) in
self.pending_outbound_payments.release_invoice_requests_awaiting_invoice()
{
let RetryableInvoiceRequest { invoice_request, nonce, .. } = retryable_invoice_request;
let RetryableInvoiceRequest { invoice_request, .. } = retryable_invoice_request;

let peers = self.get_peers_for_blinded_path();
let enqueue_invreq_res =
self.flow.enqueue_invoice_request(invoice_request, payment_id, nonce, peers);
self.flow.enqueue_invoice_request(invoice_request, payment_id, peers);
if enqueue_invreq_res.is_err() {
log_warn!(
self.logger,
Expand Down
8 changes: 6 additions & 2 deletions lightning/src/ln/outbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -173,14 +173,18 @@ pub(crate) enum PendingOutboundPayment {
#[derive(Clone)]
pub(crate) struct RetryableInvoiceRequest {
pub(crate) invoice_request: InvoiceRequest,
pub(crate) nonce: Nonce,
// No longer used, but written so that the payment can be retried after downgrading to a
// version that verifies invoices using the nonce instead of the payer metadata. Set when
// creating an invoice request and otherwise retains the value read from disk, which may have
// been written by such a version.
pub(crate) nonce: Option<Nonce>,
pub(super) needs_retry: bool,
}

impl_ser_tlv_based!(RetryableInvoiceRequest, {
(0, invoice_request, required),
(1, needs_retry, (default_value, true)),
(2, nonce, required),
(2, nonce, option),
});

impl PendingOutboundPayment {
Expand Down
38 changes: 17 additions & 21 deletions lightning/src/offers/flow.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -484,14 +484,14 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
Ok(InvreqResponseInstructions::SendInvoice(invoice_request))
}

/// Verifies a [`Bolt12Invoice`] using the provided [`OffersContext`] or the invoice's payer
/// metadata, returning the corresponding [`PaymentId`] if successful.
/// Verifies a [`Bolt12Invoice`] using the invoice's payer metadata, returning the
/// corresponding [`PaymentId`] if successful.
///
/// - If an [`OffersContext::OutboundPaymentForOffer`] or
/// [`OffersContext::OutboundPaymentForRefund`] with a `nonce` is provided, verification is
/// performed using this to form the payer metadata.
/// - If no context is provided and the invoice corresponds to a [`Refund`] without blinded paths,
/// verification is performed using the [`Bolt12Invoice::payer_metadata`].
/// [`OffersContext::OutboundPaymentForRefund`] is provided, the extracted [`PaymentId`] must
/// also match the context's `payment_id`.
/// - If no context is provided, the invoice must correspond to a [`Refund`] without blinded
/// paths.
/// - If neither condition is met, verification fails.
pub fn verify_bolt12_invoice(
&self, invoice: &Bolt12Invoice, context: Option<&OffersContext>,
Expand All@@ -503,16 +503,20 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
None if invoice.is_for_refund_without_paths() => {
invoice.verify_using_metadata(expanded_key, secp_ctx)
},
Some(&OffersContext::OutboundPaymentForOffer { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForOffer { payment_id }) => {
if invoice.is_for_offer() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
},
Some(&OffersContext::OutboundPaymentForRefund { payment_id, nonce, .. }) => {
Some(&OffersContext::OutboundPaymentForRefund { payment_id }) => {
if invoice.is_for_refund() {
invoice.verify_using_payer_data(payment_id, nonce, expanded_key, secp_ctx)
invoice.verify_using_metadata(expanded_key, secp_ctx).and_then(|extracted| {
(extracted == payment_id).then(|| payment_id).ok_or(())
})
} else {
Err(())
}
Expand DownExpand Up@@ -689,7 +693,7 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {

let nonce = Nonce::from_entropy_source(entropy);
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id, nonce });
MessageContext::Offers(OffersContext::OutboundPaymentForRefund { payment_id });

// Create the base builder with common properties
let mut builder = RefundBuilder::deriving_signing_pubkey(
Expand DownExpand Up@@ -1085,13 +1089,6 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// over those blinded paths, which can be verified against the intended outbound payment,
/// ensuring the invoice corresponds to a payment we actually want to make.
///
/// # Nonce
/// The nonce is used to create a unique [`MessageContext`] for the reply paths.
/// These will be used to verify the corresponding [`Bolt12Invoice`] when it is received.
///
/// Note: The provided [`Nonce`] MUST be the same as the [`Nonce`] used for creating the
/// [`InvoiceRequest`] to ensure correct verification of the corresponding [`Bolt12Invoice`].
///
/// See [`OffersMessageFlow::create_invoice_request_builder`] for more details.
///
/// # Peers
Expand All@@ -1103,11 +1100,10 @@ impl<MR: MessageRouter, L: Logger> OffersMessageFlow<MR, L> {
/// [`InvoiceError`]: crate::offers::invoice_error::InvoiceError
/// [`supports_onion_messages`]: crate::types::features::Features::supports_onion_messages
pub fn enqueue_invoice_request(
&self, invoice_request: InvoiceRequest, payment_id: PaymentId, nonce: Nonce,
&self, invoice_request: InvoiceRequest, payment_id: PaymentId,
peers: Vec<MessageForwardNode>,
) -> Result<(), Bolt12SemanticError> {
let context =
MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id, nonce });
let context = MessageContext::Offers(OffersContext::OutboundPaymentForOffer { payment_id });
let reply_paths = self
.create_blinded_paths(peers, context)
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
Expand Down
39 changes: 12 additions & 27 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -133,7 +133,6 @@ use crate::offers::invoice_request::{
use crate::offers::merkle::{
self, SignError, SignFn, SignatureTlvStream, SignatureTlvStreamRef, TaggedHash, TlvStream,
};
use crate::offers::nonce::Nonce;
use crate::offers::offer::{
Amount, ExperimentalOfferTlvStream, ExperimentalOfferTlvStreamRef, OfferId, OfferTlvStream,
OfferTlvStreamRef, Quantity, EXPERIMENTAL_OFFER_TYPES, OFFER_TYPES,
Expand DownExpand Up@@ -1008,30 +1007,17 @@ impl Bolt12Invoice {
(&invoice_request.inner.payer.0, INVOICE_REQUEST_IV_BYTES)
},
InvoiceContents::ForRefund { refund, .. } => {
(&refund.payer.0, REFUND_IV_BYTES_WITH_METADATA)
let iv_bytes = if refund.paths().is_empty() {
REFUND_IV_BYTES_WITH_METADATA
} else {
REFUND_IV_BYTES_WITHOUT_METADATA
};
(&refund.payer.0, iv_bytes)
},
};
self.contents.verify(&self.bytes, metadata, key, iv_bytes, secp_ctx)
}

/// Verifies that the invoice was for a request or refund created using the given key by
/// checking a payment id and nonce included with the [`BlindedMessagePath`] for which the invoice was
/// sent through.
pub fn verify_using_payer_data<T: secp256k1::Signing>(
&self, payment_id: PaymentId, nonce: Nonce, key: &ExpandedKey, secp_ctx: &Secp256k1<T>,
) -> Result<PaymentId, ()> {
let metadata = Metadata::payer_data(payment_id, nonce, key);
let iv_bytes = match &self.contents {
InvoiceContents::ForOffer { .. } => INVOICE_REQUEST_IV_BYTES,
InvoiceContents::ForRefund { .. } => REFUND_IV_BYTES_WITHOUT_METADATA,
};
self.contents.verify(&self.bytes, &metadata, key, iv_bytes, secp_ctx).and_then(
|extracted_payment_id| {
(payment_id == extracted_payment_id).then(|| payment_id).ok_or(())
},
)
}

pub(crate) fn as_tlv_stream(&self) -> FullInvoiceTlvStreamRef<'_> {
let (
payer_tlv_stream,
Expand DownExpand Up@@ -1892,6 +1878,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let payment_paths = payment_paths();
let payment_hash = payment_hash();
Expand All@@ -1913,7 +1901,7 @@ mod tests {
unsigned_invoice.write(&mut buffer).unwrap();

assert_eq!(unsigned_invoice.bytes, buffer.as_slice());
assert_eq!(unsigned_invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(unsigned_invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
unsigned_invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand DownExpand Up@@ -1957,7 +1945,7 @@ mod tests {
invoice.write(&mut buffer).unwrap();

assert_eq!(invoice.bytes, buffer.as_slice());
assert_eq!(invoice.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice.offer_chains(),
Some(vec![ChainHash::using_genesis_block(Network::Bitcoin)])
Expand All@@ -1975,10 +1963,7 @@ mod tests {
assert_eq!(invoice.amount_msats(), 1000);
assert_eq!(invoice.invoice_request_features(), &InvoiceRequestFeatures::empty());
assert_eq!(invoice.quantity(), None);
assert_eq!(
invoice.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx),
Ok(payment_id),
);
assert_eq!(invoice.verify_using_metadata(&expanded_key, &secp_ctx), Ok(payment_id));
assert_eq!(invoice.payer_note(), None);
assert_eq!(invoice.payment_paths(), payment_paths.as_slice());
assert_eq!(invoice.created_at(), now);
Expand All@@ -2001,7 +1986,7 @@ mod tests {
assert_eq!(
invoice.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand Down
22 changes: 10 additions & 12 deletions lightning/src/offers/invoice_request.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1588,6 +1588,8 @@ mod tests {
let secp_ctx = Secp256k1::new();
let payment_id = PaymentId([1; 32]);
let encrypted_payment_id = expanded_key.crypt_for_offer(payment_id.0, nonce);
let mut payer_metadata = encrypted_payment_id.to_vec();
payer_metadata.extend_from_slice(nonce.as_slice());

let invoice_request = OfferBuilder::new(recipient_pubkey())
.amount_msats(1000)
Expand All@@ -1602,7 +1604,7 @@ mod tests {
invoice_request.write(&mut buffer).unwrap();

assert_eq!(invoice_request.bytes, buffer.as_slice());
assert_eq!(invoice_request.payer_metadata(), &encrypted_payment_id);
assert_eq!(invoice_request.payer_metadata(), payer_metadata.as_slice());
assert_eq!(
invoice_request.chains(),
vec![ChainHash::using_genesis_block(Network::Bitcoin)]
Expand DownExpand Up@@ -1634,7 +1636,7 @@ mod tests {
assert_eq!(
invoice_request.as_tlv_stream(),
(
PayerTlvStreamRef { metadata: Some(&encrypted_payment_id.to_vec()) },
PayerTlvStreamRef { metadata: Some(&payer_metadata) },
OfferTlvStreamRef {
chains: None,
metadata: None,
Expand DownExpand Up@@ -1735,10 +1737,10 @@ mod tests {
.unwrap()
.sign(recipient_sign)
.unwrap();
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_ok());
match invoice.verify_using_metadata(&expanded_key, &secp_ctx) {
Ok(payment_id) => assert_eq!(payment_id, PaymentId([1; 32])),
Err(()) => panic!("verification failed"),
}

// Fails verification with altered fields
let (
Expand DownExpand Up@@ -1774,9 +1776,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());

// Fails verification with altered payer id
let (
Expand DownExpand Up@@ -1812,9 +1812,7 @@ mod tests {
.unwrap();

let invoice = Bolt12Invoice::try_from(encoded_invoice).unwrap();
assert!(invoice
.verify_using_payer_data(payment_id, nonce, &expanded_key, &secp_ctx)
.is_err());
assert!(invoice.verify_using_metadata(&expanded_key, &secp_ctx).is_err());
}

#[test]
Expand Down
Loading