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
7 changes: 6 additions & 1 deletion lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -237,7 +237,12 @@ impl From<&ClaimableHTLC> for events::ClaimedHTLC {
///
/// This is not exported to bindings users as we just use [u8; 32] directly
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct PaymentId(pub [u8; 32]);
pub struct PaymentId(pub [u8; Self::LENGTH]);

impl PaymentId {
/// Number of bytes in the id.
pub const LENGTH: usize = 32;
}

impl Writeable for PaymentId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
Expand Down
37 changes: 24 additions & 13 deletions lightning/src/ln/inbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::msgs;
use crate::ln::msgs::MAX_VALUE_MSAT;
use crate::util::chacha20::ChaCha20;
use crate::util::crypto::hkdf_extract_expand_4x;
use crate::util::crypto::hkdf_extract_expand_5x;
use crate::util::errors::APIError;
use crate::util::logger::Logger;

Expand DownExpand Up@@ -50,27 +50,34 @@ pub struct ExpandedKey {
user_pmt_hash_key: [u8; 32],
/// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
offers_base_key: [u8; 32],
/// The key used to encrypt message metadata for BOLT 12 Offers.
offers_encryption_key: [u8; 32],
}

impl ExpandedKey {
/// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret.
///
/// It is recommended to cache this value and not regenerate it for each new inbound payment.
pub fn new(key_material: &KeyMaterial) -> ExpandedKey {
let (metadata_key, ldk_pmt_hash_key, user_pmt_hash_key, offers_base_key) =
hkdf_extract_expand_4x(b"LDK Inbound Payment Key Expansion", &key_material.0);
let (
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
) = hkdf_extract_expand_5x(b"LDK Inbound Payment Key Expansion", &key_material.0);
Self {
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
}
}

/// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
#[allow(unused)]
pub(crate) fn hmac_for_offer(
&self, nonce: Nonce, iv_bytes: &[u8; IV_LEN]
) -> HmacEngine<Sha256> {
Expand All@@ -79,6 +86,13 @@ impl ExpandedKey {
hmac.input(&nonce.0);
hmac
}

/// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
/// metadata (e.g., payment id).
pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
bytes
}
}

/// A 128-bit number used only once.
Expand All@@ -88,7 +102,6 @@ impl ExpandedKey {
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
/// [`Offer::signing_pubkey`]: crate::offers::offer::Offer::signing_pubkey
#[allow(unused)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Nonce(pub(crate) [u8; Self::LENGTH]);

Expand DownExpand Up@@ -271,10 +284,9 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
iv_slice.copy_from_slice(iv_bytes);

let chacha_block = ChaCha20::get_single_block(metadata_key, iv_bytes);
for i in 0..METADATA_LEN {
encrypted_metadata_slice[i] = chacha_block[i] ^ metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
);
PaymentSecret(payment_secret_bytes)
}

Expand DownExpand Up@@ -406,11 +418,10 @@ fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8;
let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
iv_bytes.copy_from_slice(iv_slice);

let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
for i in 0..METADATA_LEN {
metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
);

(iv_bytes, metadata_bytes)
}
Expand Down
36 changes: 15 additions & 21 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,7 @@ use core::time::Duration;
use crate::io;
use crate::blinded_path::BlindedPath;
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
use crate::ln::inbound_payment::ExpandedKey;
use crate::ln::msgs::DecodeError;
Expand DownExpand Up@@ -695,10 +696,11 @@ impl Bolt12Invoice {
merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
}

/// Verifies that the invoice was for a request or refund created using the given key.
/// Verifies that the invoice was for a request or refund created using the given key. Returns
/// the associated [`PaymentId`] to use when sending the payment.
pub fn verify<T: secp256k1::Signing>(
&self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
}

Expand DownExpand Up@@ -947,7 +949,7 @@ impl InvoiceContents {

fn verify<T: secp256k1::Signing>(
&self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
let offer_records = tlv_stream.clone().range(OFFER_TYPES);
let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
match record.r#type {
Expand All@@ -967,10 +969,7 @@ impl InvoiceContents {
},
};

match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
Ok(_) => true,
Err(()) => false,
}
signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
}

fn derives_keys(&self) -> bool {
Expand DownExpand Up@@ -1642,36 +1641,31 @@ mod tests {
.build().unwrap()
.sign(payer_sign).unwrap();

if let Err(e) = invoice_request
.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
)
.unwrap()
if let Err(e) = invoice_request.clone()
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
.build_and_sign(&secp_ctx)
{
panic!("error building invoice: {:?}", e);
}

let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());

let desc = "foo".to_string();
let offer = OfferBuilder
::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
.amount_msats(1000)
// Omit the path so that node_id is used for the signing pubkey instead of deriving
.build().unwrap();
let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
.build().unwrap()
.sign(payer_sign).unwrap();

match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
match invoice_request
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
{
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
BOLT 12 outbound `PaymentId` by jkczyz · Pull Request #2468 · lightningdevkit/rust-lightning · GitHub
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
7 changes: 6 additions & 1 deletion lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -237,7 +237,12 @@ impl From<&ClaimableHTLC> for events::ClaimedHTLC {
///
/// This is not exported to bindings users as we just use [u8; 32] directly
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct PaymentId(pub [u8; 32]);
pub struct PaymentId(pub [u8; Self::LENGTH]);

impl PaymentId {
/// Number of bytes in the id.
pub const LENGTH: usize = 32;
}

impl Writeable for PaymentId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
Expand Down
37 changes: 24 additions & 13 deletions lightning/src/ln/inbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::msgs;
use crate::ln::msgs::MAX_VALUE_MSAT;
use crate::util::chacha20::ChaCha20;
use crate::util::crypto::hkdf_extract_expand_4x;
use crate::util::crypto::hkdf_extract_expand_5x;
use crate::util::errors::APIError;
use crate::util::logger::Logger;

Expand DownExpand Up@@ -50,27 +50,34 @@ pub struct ExpandedKey {
user_pmt_hash_key: [u8; 32],
/// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
offers_base_key: [u8; 32],
/// The key used to encrypt message metadata for BOLT 12 Offers.
offers_encryption_key: [u8; 32],
}

impl ExpandedKey {
/// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret.
///
/// It is recommended to cache this value and not regenerate it for each new inbound payment.
pub fn new(key_material: &KeyMaterial) -> ExpandedKey {
let (metadata_key, ldk_pmt_hash_key, user_pmt_hash_key, offers_base_key) =
hkdf_extract_expand_4x(b"LDK Inbound Payment Key Expansion", &key_material.0);
let (
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
) = hkdf_extract_expand_5x(b"LDK Inbound Payment Key Expansion", &key_material.0);
Self {
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
}
}

/// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
#[allow(unused)]
pub(crate) fn hmac_for_offer(
&self, nonce: Nonce, iv_bytes: &[u8; IV_LEN]
) -> HmacEngine<Sha256> {
Expand All@@ -79,6 +86,13 @@ impl ExpandedKey {
hmac.input(&nonce.0);
hmac
}

/// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
/// metadata (e.g., payment id).
pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
bytes
}
}

/// A 128-bit number used only once.
Expand All@@ -88,7 +102,6 @@ impl ExpandedKey {
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
/// [`Offer::signing_pubkey`]: crate::offers::offer::Offer::signing_pubkey
#[allow(unused)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Nonce(pub(crate) [u8; Self::LENGTH]);

Expand DownExpand Up@@ -271,10 +284,9 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
iv_slice.copy_from_slice(iv_bytes);

let chacha_block = ChaCha20::get_single_block(metadata_key, iv_bytes);
for i in 0..METADATA_LEN {
encrypted_metadata_slice[i] = chacha_block[i] ^ metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
);
PaymentSecret(payment_secret_bytes)
}

Expand DownExpand Up@@ -406,11 +418,10 @@ fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8;
let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
iv_bytes.copy_from_slice(iv_slice);

let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
for i in 0..METADATA_LEN {
metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
);

(iv_bytes, metadata_bytes)
}
Expand Down
36 changes: 15 additions & 21 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,7 @@ use core::time::Duration;
use crate::io;
use crate::blinded_path::BlindedPath;
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
use crate::ln::inbound_payment::ExpandedKey;
use crate::ln::msgs::DecodeError;
Expand DownExpand Up@@ -695,10 +696,11 @@ impl Bolt12Invoice {
merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
}

/// Verifies that the invoice was for a request or refund created using the given key.
/// Verifies that the invoice was for a request or refund created using the given key. Returns
/// the associated [`PaymentId`] to use when sending the payment.
pub fn verify<T: secp256k1::Signing>(
&self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
}

Expand DownExpand Up@@ -947,7 +949,7 @@ impl InvoiceContents {

fn verify<T: secp256k1::Signing>(
&self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
let offer_records = tlv_stream.clone().range(OFFER_TYPES);
let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
match record.r#type {
Expand All@@ -967,10 +969,7 @@ impl InvoiceContents {
},
};

match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
Ok(_) => true,
Err(()) => false,
}
signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
}

fn derives_keys(&self) -> bool {
Expand DownExpand Up@@ -1642,36 +1641,31 @@ mod tests {
.build().unwrap()
.sign(payer_sign).unwrap();

if let Err(e) = invoice_request
.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
)
.unwrap()
if let Err(e) = invoice_request.clone()
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
.build_and_sign(&secp_ctx)
{
panic!("error building invoice: {:?}", e);
}

let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());

let desc = "foo".to_string();
let offer = OfferBuilder
::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
.amount_msats(1000)
// Omit the path so that node_id is used for the signing pubkey instead of deriving
.build().unwrap();
let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
.build().unwrap()
.sign(payer_sign).unwrap();

match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
match invoice_request
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
{
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT 12 outbound `PaymentId` by jkczyz · Pull Request #2468 · lightningdevkit/rust-lightning · GitHub
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
7 changes: 6 additions & 1 deletion lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -237,7 +237,12 @@ impl From<&ClaimableHTLC> for events::ClaimedHTLC {
///
/// This is not exported to bindings users as we just use [u8; 32] directly
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct PaymentId(pub [u8; 32]);
pub struct PaymentId(pub [u8; Self::LENGTH]);

impl PaymentId {
/// Number of bytes in the id.
pub const LENGTH: usize = 32;
}

impl Writeable for PaymentId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
Expand Down
37 changes: 24 additions & 13 deletions lightning/src/ln/inbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::msgs;
use crate::ln::msgs::MAX_VALUE_MSAT;
use crate::util::chacha20::ChaCha20;
use crate::util::crypto::hkdf_extract_expand_4x;
use crate::util::crypto::hkdf_extract_expand_5x;
use crate::util::errors::APIError;
use crate::util::logger::Logger;

Expand DownExpand Up@@ -50,27 +50,34 @@ pub struct ExpandedKey {
user_pmt_hash_key: [u8; 32],
/// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
offers_base_key: [u8; 32],
/// The key used to encrypt message metadata for BOLT 12 Offers.
offers_encryption_key: [u8; 32],
}

impl ExpandedKey {
/// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret.
///
/// It is recommended to cache this value and not regenerate it for each new inbound payment.
pub fn new(key_material: &KeyMaterial) -> ExpandedKey {
let (metadata_key, ldk_pmt_hash_key, user_pmt_hash_key, offers_base_key) =
hkdf_extract_expand_4x(b"LDK Inbound Payment Key Expansion", &key_material.0);
let (
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
) = hkdf_extract_expand_5x(b"LDK Inbound Payment Key Expansion", &key_material.0);
Self {
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
}
}

/// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
#[allow(unused)]
pub(crate) fn hmac_for_offer(
&self, nonce: Nonce, iv_bytes: &[u8; IV_LEN]
) -> HmacEngine<Sha256> {
Expand All@@ -79,6 +86,13 @@ impl ExpandedKey {
hmac.input(&nonce.0);
hmac
}

/// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
/// metadata (e.g., payment id).
pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
bytes
}
}

/// A 128-bit number used only once.
Expand All@@ -88,7 +102,6 @@ impl ExpandedKey {
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
/// [`Offer::signing_pubkey`]: crate::offers::offer::Offer::signing_pubkey
#[allow(unused)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Nonce(pub(crate) [u8; Self::LENGTH]);

Expand DownExpand Up@@ -271,10 +284,9 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
iv_slice.copy_from_slice(iv_bytes);

let chacha_block = ChaCha20::get_single_block(metadata_key, iv_bytes);
for i in 0..METADATA_LEN {
encrypted_metadata_slice[i] = chacha_block[i] ^ metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
);
PaymentSecret(payment_secret_bytes)
}

Expand DownExpand Up@@ -406,11 +418,10 @@ fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8;
let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
iv_bytes.copy_from_slice(iv_slice);

let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
for i in 0..METADATA_LEN {
metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
);

(iv_bytes, metadata_bytes)
}
Expand Down
36 changes: 15 additions & 21 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,7 @@ use core::time::Duration;
use crate::io;
use crate::blinded_path::BlindedPath;
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
use crate::ln::inbound_payment::ExpandedKey;
use crate::ln::msgs::DecodeError;
Expand DownExpand Up@@ -695,10 +696,11 @@ impl Bolt12Invoice {
merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
}

/// Verifies that the invoice was for a request or refund created using the given key.
/// Verifies that the invoice was for a request or refund created using the given key. Returns
/// the associated [`PaymentId`] to use when sending the payment.
pub fn verify<T: secp256k1::Signing>(
&self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
}

Expand DownExpand Up@@ -947,7 +949,7 @@ impl InvoiceContents {

fn verify<T: secp256k1::Signing>(
&self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
let offer_records = tlv_stream.clone().range(OFFER_TYPES);
let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
match record.r#type {
Expand All@@ -967,10 +969,7 @@ impl InvoiceContents {
},
};

match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
Ok(_) => true,
Err(()) => false,
}
signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
}

fn derives_keys(&self) -> bool {
Expand DownExpand Up@@ -1642,36 +1641,31 @@ mod tests {
.build().unwrap()
.sign(payer_sign).unwrap();

if let Err(e) = invoice_request
.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
)
.unwrap()
if let Err(e) = invoice_request.clone()
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
.build_and_sign(&secp_ctx)
{
panic!("error building invoice: {:?}", e);
}

let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());

let desc = "foo".to_string();
let offer = OfferBuilder
::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
.amount_msats(1000)
// Omit the path so that node_id is used for the signing pubkey instead of deriving
.build().unwrap();
let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
.build().unwrap()
.sign(payer_sign).unwrap();

match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
match invoice_request
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
{
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT 12 outbound `PaymentId` by jkczyz · Pull Request #2468 · lightningdevkit/rust-lightning · GitHub
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
7 changes: 6 additions & 1 deletion lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -237,7 +237,12 @@ impl From<&ClaimableHTLC> for events::ClaimedHTLC {
///
/// This is not exported to bindings users as we just use [u8; 32] directly
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct PaymentId(pub [u8; 32]);
pub struct PaymentId(pub [u8; Self::LENGTH]);

impl PaymentId {
/// Number of bytes in the id.
pub const LENGTH: usize = 32;
}

impl Writeable for PaymentId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
Expand Down
37 changes: 24 additions & 13 deletions lightning/src/ln/inbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::msgs;
use crate::ln::msgs::MAX_VALUE_MSAT;
use crate::util::chacha20::ChaCha20;
use crate::util::crypto::hkdf_extract_expand_4x;
use crate::util::crypto::hkdf_extract_expand_5x;
use crate::util::errors::APIError;
use crate::util::logger::Logger;

Expand DownExpand Up@@ -50,27 +50,34 @@ pub struct ExpandedKey {
user_pmt_hash_key: [u8; 32],
/// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
offers_base_key: [u8; 32],
/// The key used to encrypt message metadata for BOLT 12 Offers.
offers_encryption_key: [u8; 32],
}

impl ExpandedKey {
/// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret.
///
/// It is recommended to cache this value and not regenerate it for each new inbound payment.
pub fn new(key_material: &KeyMaterial) -> ExpandedKey {
let (metadata_key, ldk_pmt_hash_key, user_pmt_hash_key, offers_base_key) =
hkdf_extract_expand_4x(b"LDK Inbound Payment Key Expansion", &key_material.0);
let (
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
) = hkdf_extract_expand_5x(b"LDK Inbound Payment Key Expansion", &key_material.0);
Self {
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
}
}

/// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
#[allow(unused)]
pub(crate) fn hmac_for_offer(
&self, nonce: Nonce, iv_bytes: &[u8; IV_LEN]
) -> HmacEngine<Sha256> {
Expand All@@ -79,6 +86,13 @@ impl ExpandedKey {
hmac.input(&nonce.0);
hmac
}

/// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
/// metadata (e.g., payment id).
pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
bytes
}
}

/// A 128-bit number used only once.
Expand All@@ -88,7 +102,6 @@ impl ExpandedKey {
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
/// [`Offer::signing_pubkey`]: crate::offers::offer::Offer::signing_pubkey
#[allow(unused)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Nonce(pub(crate) [u8; Self::LENGTH]);

Expand DownExpand Up@@ -271,10 +284,9 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
iv_slice.copy_from_slice(iv_bytes);

let chacha_block = ChaCha20::get_single_block(metadata_key, iv_bytes);
for i in 0..METADATA_LEN {
encrypted_metadata_slice[i] = chacha_block[i] ^ metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
);
PaymentSecret(payment_secret_bytes)
}

Expand DownExpand Up@@ -406,11 +418,10 @@ fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8;
let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
iv_bytes.copy_from_slice(iv_slice);

let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
for i in 0..METADATA_LEN {
metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
);

(iv_bytes, metadata_bytes)
}
Expand Down
36 changes: 15 additions & 21 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,7 @@ use core::time::Duration;
use crate::io;
use crate::blinded_path::BlindedPath;
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
use crate::ln::inbound_payment::ExpandedKey;
use crate::ln::msgs::DecodeError;
Expand DownExpand Up@@ -695,10 +696,11 @@ impl Bolt12Invoice {
merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
}

/// Verifies that the invoice was for a request or refund created using the given key.
/// Verifies that the invoice was for a request or refund created using the given key. Returns
/// the associated [`PaymentId`] to use when sending the payment.
pub fn verify<T: secp256k1::Signing>(
&self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
}

Expand DownExpand Up@@ -947,7 +949,7 @@ impl InvoiceContents {

fn verify<T: secp256k1::Signing>(
&self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
let offer_records = tlv_stream.clone().range(OFFER_TYPES);
let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
match record.r#type {
Expand All@@ -967,10 +969,7 @@ impl InvoiceContents {
},
};

match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
Ok(_) => true,
Err(()) => false,
}
signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
}

fn derives_keys(&self) -> bool {
Expand DownExpand Up@@ -1642,36 +1641,31 @@ mod tests {
.build().unwrap()
.sign(payer_sign).unwrap();

if let Err(e) = invoice_request
.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
)
.unwrap()
if let Err(e) = invoice_request.clone()
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
.build_and_sign(&secp_ctx)
{
panic!("error building invoice: {:?}", e);
}

let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());

let desc = "foo".to_string();
let offer = OfferBuilder
::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
.amount_msats(1000)
// Omit the path so that node_id is used for the signing pubkey instead of deriving
.build().unwrap();
let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
.build().unwrap()
.sign(payer_sign).unwrap();

match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
match invoice_request
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
{
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' BOLT 12 outbound `PaymentId` by jkczyz · Pull Request #2468 · lightningdevkit/rust-lightning · GitHub
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
7 changes: 6 additions & 1 deletion lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -237,7 +237,12 @@ impl From<&ClaimableHTLC> for events::ClaimedHTLC {
///
/// This is not exported to bindings users as we just use [u8; 32] directly
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct PaymentId(pub [u8; 32]);
pub struct PaymentId(pub [u8; Self::LENGTH]);

impl PaymentId {
/// Number of bytes in the id.
pub const LENGTH: usize = 32;
}

impl Writeable for PaymentId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
Expand Down
37 changes: 24 additions & 13 deletions lightning/src/ln/inbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::msgs;
use crate::ln::msgs::MAX_VALUE_MSAT;
use crate::util::chacha20::ChaCha20;
use crate::util::crypto::hkdf_extract_expand_4x;
use crate::util::crypto::hkdf_extract_expand_5x;
use crate::util::errors::APIError;
use crate::util::logger::Logger;

Expand DownExpand Up@@ -50,27 +50,34 @@ pub struct ExpandedKey {
user_pmt_hash_key: [u8; 32],
/// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
offers_base_key: [u8; 32],
/// The key used to encrypt message metadata for BOLT 12 Offers.
offers_encryption_key: [u8; 32],
}

impl ExpandedKey {
/// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret.
///
/// It is recommended to cache this value and not regenerate it for each new inbound payment.
pub fn new(key_material: &KeyMaterial) -> ExpandedKey {
let (metadata_key, ldk_pmt_hash_key, user_pmt_hash_key, offers_base_key) =
hkdf_extract_expand_4x(b"LDK Inbound Payment Key Expansion", &key_material.0);
let (
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
) = hkdf_extract_expand_5x(b"LDK Inbound Payment Key Expansion", &key_material.0);
Self {
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
}
}

/// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
#[allow(unused)]
pub(crate) fn hmac_for_offer(
&self, nonce: Nonce, iv_bytes: &[u8; IV_LEN]
) -> HmacEngine<Sha256> {
Expand All@@ -79,6 +86,13 @@ impl ExpandedKey {
hmac.input(&nonce.0);
hmac
}

/// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
/// metadata (e.g., payment id).
pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
bytes
}
}

/// A 128-bit number used only once.
Expand All@@ -88,7 +102,6 @@ impl ExpandedKey {
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
/// [`Offer::signing_pubkey`]: crate::offers::offer::Offer::signing_pubkey
#[allow(unused)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Nonce(pub(crate) [u8; Self::LENGTH]);

Expand DownExpand Up@@ -271,10 +284,9 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
iv_slice.copy_from_slice(iv_bytes);

let chacha_block = ChaCha20::get_single_block(metadata_key, iv_bytes);
for i in 0..METADATA_LEN {
encrypted_metadata_slice[i] = chacha_block[i] ^ metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
);
PaymentSecret(payment_secret_bytes)
}

Expand DownExpand Up@@ -406,11 +418,10 @@ fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8;
let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
iv_bytes.copy_from_slice(iv_slice);

let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
for i in 0..METADATA_LEN {
metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
);

(iv_bytes, metadata_bytes)
}
Expand Down
36 changes: 15 additions & 21 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,7 @@ use core::time::Duration;
use crate::io;
use crate::blinded_path::BlindedPath;
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
use crate::ln::inbound_payment::ExpandedKey;
use crate::ln::msgs::DecodeError;
Expand DownExpand Up@@ -695,10 +696,11 @@ impl Bolt12Invoice {
merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
}

/// Verifies that the invoice was for a request or refund created using the given key.
/// Verifies that the invoice was for a request or refund created using the given key. Returns
/// the associated [`PaymentId`] to use when sending the payment.
pub fn verify<T: secp256k1::Signing>(
&self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
}

Expand DownExpand Up@@ -947,7 +949,7 @@ impl InvoiceContents {

fn verify<T: secp256k1::Signing>(
&self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
let offer_records = tlv_stream.clone().range(OFFER_TYPES);
let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
match record.r#type {
Expand All@@ -967,10 +969,7 @@ impl InvoiceContents {
},
};

match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
Ok(_) => true,
Err(()) => false,
}
signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
}

fn derives_keys(&self) -> bool {
Expand DownExpand Up@@ -1642,36 +1641,31 @@ mod tests {
.build().unwrap()
.sign(payer_sign).unwrap();

if let Err(e) = invoice_request
.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
)
.unwrap()
if let Err(e) = invoice_request.clone()
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
.build_and_sign(&secp_ctx)
{
panic!("error building invoice: {:?}", e);
}

let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());

let desc = "foo".to_string();
let offer = OfferBuilder
::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
.amount_msats(1000)
// Omit the path so that node_id is used for the signing pubkey instead of deriving
.build().unwrap();
let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
.build().unwrap()
.sign(payer_sign).unwrap();

match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
match invoice_request
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
{
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT 12 outbound `PaymentId` by jkczyz · Pull Request #2468 · lightningdevkit/rust-lightning · GitHub
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
7 changes: 6 additions & 1 deletion lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -237,7 +237,12 @@ impl From<&ClaimableHTLC> for events::ClaimedHTLC {
///
/// This is not exported to bindings users as we just use [u8; 32] directly
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct PaymentId(pub [u8; 32]);
pub struct PaymentId(pub [u8; Self::LENGTH]);

impl PaymentId {
/// Number of bytes in the id.
pub const LENGTH: usize = 32;
}

impl Writeable for PaymentId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
Expand Down
37 changes: 24 additions & 13 deletions lightning/src/ln/inbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::msgs;
use crate::ln::msgs::MAX_VALUE_MSAT;
use crate::util::chacha20::ChaCha20;
use crate::util::crypto::hkdf_extract_expand_4x;
use crate::util::crypto::hkdf_extract_expand_5x;
use crate::util::errors::APIError;
use crate::util::logger::Logger;

Expand DownExpand Up@@ -50,27 +50,34 @@ pub struct ExpandedKey {
user_pmt_hash_key: [u8; 32],
/// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
offers_base_key: [u8; 32],
/// The key used to encrypt message metadata for BOLT 12 Offers.
offers_encryption_key: [u8; 32],
}

impl ExpandedKey {
/// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret.
///
/// It is recommended to cache this value and not regenerate it for each new inbound payment.
pub fn new(key_material: &KeyMaterial) -> ExpandedKey {
let (metadata_key, ldk_pmt_hash_key, user_pmt_hash_key, offers_base_key) =
hkdf_extract_expand_4x(b"LDK Inbound Payment Key Expansion", &key_material.0);
let (
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
) = hkdf_extract_expand_5x(b"LDK Inbound Payment Key Expansion", &key_material.0);
Self {
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
}
}

/// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
#[allow(unused)]
pub(crate) fn hmac_for_offer(
&self, nonce: Nonce, iv_bytes: &[u8; IV_LEN]
) -> HmacEngine<Sha256> {
Expand All@@ -79,6 +86,13 @@ impl ExpandedKey {
hmac.input(&nonce.0);
hmac
}

/// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
/// metadata (e.g., payment id).
pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
bytes
}
}

/// A 128-bit number used only once.
Expand All@@ -88,7 +102,6 @@ impl ExpandedKey {
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
/// [`Offer::signing_pubkey`]: crate::offers::offer::Offer::signing_pubkey
#[allow(unused)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Nonce(pub(crate) [u8; Self::LENGTH]);

Expand DownExpand Up@@ -271,10 +284,9 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
iv_slice.copy_from_slice(iv_bytes);

let chacha_block = ChaCha20::get_single_block(metadata_key, iv_bytes);
for i in 0..METADATA_LEN {
encrypted_metadata_slice[i] = chacha_block[i] ^ metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
);
PaymentSecret(payment_secret_bytes)
}

Expand DownExpand Up@@ -406,11 +418,10 @@ fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8;
let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
iv_bytes.copy_from_slice(iv_slice);

let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
for i in 0..METADATA_LEN {
metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
);

(iv_bytes, metadata_bytes)
}
Expand Down
36 changes: 15 additions & 21 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,7 @@ use core::time::Duration;
use crate::io;
use crate::blinded_path::BlindedPath;
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
use crate::ln::inbound_payment::ExpandedKey;
use crate::ln::msgs::DecodeError;
Expand DownExpand Up@@ -695,10 +696,11 @@ impl Bolt12Invoice {
merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
}

/// Verifies that the invoice was for a request or refund created using the given key.
/// Verifies that the invoice was for a request or refund created using the given key. Returns
/// the associated [`PaymentId`] to use when sending the payment.
pub fn verify<T: secp256k1::Signing>(
&self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
}

Expand DownExpand Up@@ -947,7 +949,7 @@ impl InvoiceContents {

fn verify<T: secp256k1::Signing>(
&self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
let offer_records = tlv_stream.clone().range(OFFER_TYPES);
let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
match record.r#type {
Expand All@@ -967,10 +969,7 @@ impl InvoiceContents {
},
};

match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
Ok(_) => true,
Err(()) => false,
}
signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
}

fn derives_keys(&self) -> bool {
Expand DownExpand Up@@ -1642,36 +1641,31 @@ mod tests {
.build().unwrap()
.sign(payer_sign).unwrap();

if let Err(e) = invoice_request
.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
)
.unwrap()
if let Err(e) = invoice_request.clone()
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
.build_and_sign(&secp_ctx)
{
panic!("error building invoice: {:?}", e);
}

let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());

let desc = "foo".to_string();
let offer = OfferBuilder
::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
.amount_msats(1000)
// Omit the path so that node_id is used for the signing pubkey instead of deriving
.build().unwrap();
let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
.build().unwrap()
.sign(payer_sign).unwrap();

match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
match invoice_request
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
{
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' BOLT 12 outbound `PaymentId` by jkczyz · Pull Request #2468 · lightningdevkit/rust-lightning · GitHub
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
7 changes: 6 additions & 1 deletion lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -237,7 +237,12 @@ impl From<&ClaimableHTLC> for events::ClaimedHTLC {
///
/// This is not exported to bindings users as we just use [u8; 32] directly
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct PaymentId(pub [u8; 32]);
pub struct PaymentId(pub [u8; Self::LENGTH]);

impl PaymentId {
/// Number of bytes in the id.
pub const LENGTH: usize = 32;
}

impl Writeable for PaymentId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
Expand Down
37 changes: 24 additions & 13 deletions lightning/src/ln/inbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::msgs;
use crate::ln::msgs::MAX_VALUE_MSAT;
use crate::util::chacha20::ChaCha20;
use crate::util::crypto::hkdf_extract_expand_4x;
use crate::util::crypto::hkdf_extract_expand_5x;
use crate::util::errors::APIError;
use crate::util::logger::Logger;

Expand DownExpand Up@@ -50,27 +50,34 @@ pub struct ExpandedKey {
user_pmt_hash_key: [u8; 32],
/// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
offers_base_key: [u8; 32],
/// The key used to encrypt message metadata for BOLT 12 Offers.
offers_encryption_key: [u8; 32],
}

impl ExpandedKey {
/// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret.
///
/// It is recommended to cache this value and not regenerate it for each new inbound payment.
pub fn new(key_material: &KeyMaterial) -> ExpandedKey {
let (metadata_key, ldk_pmt_hash_key, user_pmt_hash_key, offers_base_key) =
hkdf_extract_expand_4x(b"LDK Inbound Payment Key Expansion", &key_material.0);
let (
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
) = hkdf_extract_expand_5x(b"LDK Inbound Payment Key Expansion", &key_material.0);
Self {
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
}
}

/// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
#[allow(unused)]
pub(crate) fn hmac_for_offer(
&self, nonce: Nonce, iv_bytes: &[u8; IV_LEN]
) -> HmacEngine<Sha256> {
Expand All@@ -79,6 +86,13 @@ impl ExpandedKey {
hmac.input(&nonce.0);
hmac
}

/// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
/// metadata (e.g., payment id).
pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
bytes
}
}

/// A 128-bit number used only once.
Expand All@@ -88,7 +102,6 @@ impl ExpandedKey {
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
/// [`Offer::signing_pubkey`]: crate::offers::offer::Offer::signing_pubkey
#[allow(unused)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Nonce(pub(crate) [u8; Self::LENGTH]);

Expand DownExpand Up@@ -271,10 +284,9 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
iv_slice.copy_from_slice(iv_bytes);

let chacha_block = ChaCha20::get_single_block(metadata_key, iv_bytes);
for i in 0..METADATA_LEN {
encrypted_metadata_slice[i] = chacha_block[i] ^ metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
);
PaymentSecret(payment_secret_bytes)
}

Expand DownExpand Up@@ -406,11 +418,10 @@ fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8;
let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
iv_bytes.copy_from_slice(iv_slice);

let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
for i in 0..METADATA_LEN {
metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
);

(iv_bytes, metadata_bytes)
}
Expand Down
36 changes: 15 additions & 21 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,7 @@ use core::time::Duration;
use crate::io;
use crate::blinded_path::BlindedPath;
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
use crate::ln::inbound_payment::ExpandedKey;
use crate::ln::msgs::DecodeError;
Expand DownExpand Up@@ -695,10 +696,11 @@ impl Bolt12Invoice {
merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
}

/// Verifies that the invoice was for a request or refund created using the given key.
/// Verifies that the invoice was for a request or refund created using the given key. Returns
/// the associated [`PaymentId`] to use when sending the payment.
pub fn verify<T: secp256k1::Signing>(
&self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
}

Expand DownExpand Up@@ -947,7 +949,7 @@ impl InvoiceContents {

fn verify<T: secp256k1::Signing>(
&self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
let offer_records = tlv_stream.clone().range(OFFER_TYPES);
let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
match record.r#type {
Expand All@@ -967,10 +969,7 @@ impl InvoiceContents {
},
};

match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
Ok(_) => true,
Err(()) => false,
}
signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
}

fn derives_keys(&self) -> bool {
Expand DownExpand Up@@ -1642,36 +1641,31 @@ mod tests {
.build().unwrap()
.sign(payer_sign).unwrap();

if let Err(e) = invoice_request
.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
)
.unwrap()
if let Err(e) = invoice_request.clone()
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
.build_and_sign(&secp_ctx)
{
panic!("error building invoice: {:?}", e);
}

let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());

let desc = "foo".to_string();
let offer = OfferBuilder
::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
.amount_msats(1000)
// Omit the path so that node_id is used for the signing pubkey instead of deriving
.build().unwrap();
let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
.build().unwrap()
.sign(payer_sign).unwrap();

match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
match invoice_request
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
{
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); BOLT 12 outbound `PaymentId` by jkczyz · Pull Request #2468 · lightningdevkit/rust-lightning · GitHub
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
7 changes: 6 additions & 1 deletion lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -237,7 +237,12 @@ impl From<&ClaimableHTLC> for events::ClaimedHTLC {
///
/// This is not exported to bindings users as we just use [u8; 32] directly
#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
pub struct PaymentId(pub [u8; 32]);
pub struct PaymentId(pub [u8; Self::LENGTH]);

impl PaymentId {
/// Number of bytes in the id.
pub const LENGTH: usize = 32;
}

impl Writeable for PaymentId {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
Expand Down
37 changes: 24 additions & 13 deletions lightning/src/ln/inbound_payment.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::msgs;
use crate::ln::msgs::MAX_VALUE_MSAT;
use crate::util::chacha20::ChaCha20;
use crate::util::crypto::hkdf_extract_expand_4x;
use crate::util::crypto::hkdf_extract_expand_5x;
use crate::util::errors::APIError;
use crate::util::logger::Logger;

Expand DownExpand Up@@ -50,27 +50,34 @@ pub struct ExpandedKey {
user_pmt_hash_key: [u8; 32],
/// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
offers_base_key: [u8; 32],
/// The key used to encrypt message metadata for BOLT 12 Offers.
offers_encryption_key: [u8; 32],
}

impl ExpandedKey {
/// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret.
///
/// It is recommended to cache this value and not regenerate it for each new inbound payment.
pub fn new(key_material: &KeyMaterial) -> ExpandedKey {
let (metadata_key, ldk_pmt_hash_key, user_pmt_hash_key, offers_base_key) =
hkdf_extract_expand_4x(b"LDK Inbound Payment Key Expansion", &key_material.0);
let (
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
) = hkdf_extract_expand_5x(b"LDK Inbound Payment Key Expansion", &key_material.0);
Self {
metadata_key,
ldk_pmt_hash_key,
user_pmt_hash_key,
offers_base_key,
offers_encryption_key,
}
}

/// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
#[allow(unused)]
pub(crate) fn hmac_for_offer(
&self, nonce: Nonce, iv_bytes: &[u8; IV_LEN]
) -> HmacEngine<Sha256> {
Expand All@@ -79,6 +86,13 @@ impl ExpandedKey {
hmac.input(&nonce.0);
hmac
}

/// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
/// metadata (e.g., payment id).
pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
bytes
}
}

/// A 128-bit number used only once.
Expand All@@ -88,7 +102,6 @@ impl ExpandedKey {
///
/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
/// [`Offer::signing_pubkey`]: crate::offers::offer::Offer::signing_pubkey
#[allow(unused)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Nonce(pub(crate) [u8; Self::LENGTH]);

Expand DownExpand Up@@ -271,10 +284,9 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
iv_slice.copy_from_slice(iv_bytes);

let chacha_block = ChaCha20::get_single_block(metadata_key, iv_bytes);
for i in 0..METADATA_LEN {
encrypted_metadata_slice[i] = chacha_block[i] ^ metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
);
PaymentSecret(payment_secret_bytes)
}

Expand DownExpand Up@@ -406,11 +418,10 @@ fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8;
let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
iv_bytes.copy_from_slice(iv_slice);

let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
for i in 0..METADATA_LEN {
metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
}
ChaCha20::encrypt_single_block(
&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
);

(iv_bytes, metadata_bytes)
}
Expand Down
36 changes: 15 additions & 21 deletions lightning/src/offers/invoice.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -110,6 +110,7 @@ use core::time::Duration;
use crate::io;
use crate::blinded_path::BlindedPath;
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures, InvoiceRequestFeatures, OfferFeatures};
use crate::ln::inbound_payment::ExpandedKey;
use crate::ln::msgs::DecodeError;
Expand DownExpand Up@@ -695,10 +696,11 @@ impl Bolt12Invoice {
merkle::message_digest(SIGNATURE_TAG, &self.bytes).as_ref().clone()
}

/// Verifies that the invoice was for a request or refund created using the given key.
/// Verifies that the invoice was for a request or refund created using the given key. Returns
/// the associated [`PaymentId`] to use when sending the payment.
pub fn verify<T: secp256k1::Signing>(
&self, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
self.contents.verify(TlvStream::new(&self.bytes), key, secp_ctx)
}

Expand DownExpand Up@@ -947,7 +949,7 @@ impl InvoiceContents {

fn verify<T: secp256k1::Signing>(
&self, tlv_stream: TlvStream<'_>, key: &ExpandedKey, secp_ctx: &Secp256k1<T>
) -> bool {
) -> Result<PaymentId, ()> {
let offer_records = tlv_stream.clone().range(OFFER_TYPES);
let invreq_records = tlv_stream.range(INVOICE_REQUEST_TYPES).filter(|record| {
match record.r#type {
Expand All@@ -967,10 +969,7 @@ impl InvoiceContents {
},
};

match signer::verify_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx) {
Ok(_) => true,
Err(()) => false,
}
signer::verify_payer_metadata(metadata, key, iv_bytes, payer_id, tlv_stream, secp_ctx)
}

fn derives_keys(&self) -> bool {
Expand DownExpand Up@@ -1642,36 +1641,31 @@ mod tests {
.build().unwrap()
.sign(payer_sign).unwrap();

if let Err(e) = invoice_request
.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
)
.unwrap()
if let Err(e) = invoice_request.clone()
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now()).unwrap()
.build_and_sign(&secp_ctx)
{
panic!("error building invoice: {:?}", e);
}

let expanded_key = ExpandedKey::new(&KeyMaterial([41; 32]));
match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
assert!(invoice_request.verify(&expanded_key, &secp_ctx).is_err());

let desc = "foo".to_string();
let offer = OfferBuilder
::deriving_signing_pubkey(desc, node_id, &expanded_key, &entropy, &secp_ctx)
.amount_msats(1000)
// Omit the path so that node_id is used for the signing pubkey instead of deriving
.build().unwrap();
let invoice_request = offer.request_invoice(vec![1; 32], payer_pubkey()).unwrap()
.build().unwrap()
.sign(payer_sign).unwrap();

match invoice_request.verify_and_respond_using_derived_keys_no_std(
payment_paths(), payment_hash(), now(), &expanded_key, &secp_ctx
) {
match invoice_request
.verify(&expanded_key, &secp_ctx).unwrap()
.respond_using_derived_keys_no_std(payment_paths(), payment_hash(), now())
{
Ok(_) => panic!("expected error"),
Err(e) => assert_eq!(e, Bolt12SemanticError::InvalidMetadata),
}
Expand Down
Loading