Merge PR 'Verify built invoice signatures and length' (#5306)
What changed, and why it matters
This commit hardens how Lightning invoices are created and validated in rust-lightning. It now checks that the digital signature on a freshly built invoice actually matches the invoice contents, and it rejects invoices that would become too long once encoded. Previously, a buggy or malicious signer could produce an invoice with an invalid signature or one that exceeded protocol size limits, which could cause parsing failures or denial-of-service issues for other nodes.
Treat as a security hardening fix and include in the next release. Users building or parsing BOLT11 invoices with LDK should upgrade so that invalid-signature and over-long invoices are rejected at construction time rather than propagating to peers. No immediate emergency response is indicated because the issue is defensive and the commit does not describe an active exploit.
Security signals we found
New signature verification after invoice construction
New length enforcement at invoice construction and parsing boundaries
Refactoring of invoice signing path to share validation logic
Addition of regression tests for wrong signing key, max-length boundary, and too-long signed invoices
Evidence from the diff
The patch adds two main defenses in the lightning-invoice crate: (1) InvoiceBuilder::build_signed/try_build_signed now call check_signature() on the resulting Bolt11Invoice and fail with CreationError::InvalidSignature if the supplied signing callback returns a bad signature; (2) InvoiceBuilder::build_raw, RawBolt11Invoice::from_raw, and Bolt11Invoice::from_signed now enforce the existing MAX_LENGTH (7089 byte) limit, failing with new InvoiceTooLong errors. A shared sign_invoice helper is introduced in lightning/src/ln/invoice_utils.rs and used by ChannelManager so that node-generated invoices also get these checks. The signature length constant is centralized as SIGNATURE_LEN_5.
Changed components
lightning-invoice/src/lib.rslightning-invoice/src/de.rslightning/src/ln/invoice_utils.rslightning/src/ln/channelmanager.rsInspect captured patch +167 / −23
### lightning-invoice/src/de.rs
@@ -12,7 +12,7 @@ use bech32::primitives::decode::{CheckedHrpstring, CheckedHrpstringError};
use bech32::{Fe32, Fe32IterExt};
use crate::prelude::*;
-use crate::Bolt11Bech32;
+use crate::{Bolt11Bech32, SIGNATURE_LEN_5};
use bitcoin::hashes::sha256;
use bitcoin::hashes::Hash;
use bitcoin::{PubkeyHash, ScriptHash, WitnessVersion};
@@ -396,7 +396,6 @@ impl FromStr for SignedRawBolt11Invoice {
// Note: the type argument is needed due to the API peculiarities, but it's not used
let data: Vec<_> = parsed.fe32_iter::<&mut dyn Iterator<Item = u8>>().collect();
- const SIGNATURE_LEN_5: usize = 104; // number of the 5-bit values (equals to 65 bytes)
if data.len() < SIGNATURE_LEN_5 {
return Err(Bolt11ParseError::TooShortDataPart);
}
@@ -474,10 +473,10 @@ impl FromBase32 for PositiveTimestamp {
impl FromBase32 for Bolt11InvoiceSignature {
type Err = Bolt11ParseError;
fn from_base32(signature: &[Fe32]) -> Result<Self, Self::Err> {
- if signature.len() != 104 {
+ if signature.len() != SIGNATURE_LEN_5 {
return Err(Bolt11ParseError::InvalidSliceLength(
signature.len(),
- 104,
+ SIGNATURE_LEN_5,
"Bolt11InvoiceSignature",
));
}
@@ -1315,8 +1314,8 @@ mod test {
fn test_serde_long_invoice() {
use crate::TaggedField::*;
use crate::{
- Bolt11Invoice, Bolt11InvoiceFeatures, Bolt11InvoiceSignature, Currency,
- PositiveTimestamp, RawBolt11Invoice, RawDataPart, RawHrp, RawTaggedField,
+ Bolt11Invoice, Bolt11InvoiceFeatures, Bolt11InvoiceSignature, Bolt11SemanticError,
+ Currency, PositiveTimestamp, RawBolt11Invoice, RawDataPart, RawHrp, RawTaggedField,
SignedRawBolt11Invoice,
};
use bitcoin::hex::FromHex;
@@ -1420,6 +1419,38 @@ mod test {
let invoice_str = invoice.to_string();
assert_eq!(invoice_str.len(), crate::MAX_LENGTH);
assert_eq!(invoice, Bolt11Invoice::from_str(&invoice_str).unwrap());
+
+ // Ensure the unsigned invoice roundtrips through the remote signing format, but that
+ // adding a single character to it exceeds `MAX_LENGTH`.
+ let raw_invoice = invoice.signed_invoice.raw_invoice();
+ let (hrp, mut data) = raw_invoice.to_raw();
+ assert_eq!(RawBolt11Invoice::from_raw(&hrp, &data).as_ref(), Ok(raw_invoice));
+ data.push(Fe32::Q);
+ assert_eq!(
+ RawBolt11Invoice::from_raw(&hrp, &data),
+ Err(Bolt11ParseError::InvalidSliceLength(
+ crate::MAX_LENGTH + 1,
+ crate::MAX_LENGTH,
+ "RawBolt11Invoice"
+ ))
+ );
+
+ // Ensure that a signed invoice exceeding `MAX_LENGTH` by a single character is rejected.
+ // The original hash is kept so that the signature remains valid.
+ let mut too_long_raw_invoice = raw_invoice.clone();
+ too_long_raw_invoice
+ .data
+ .tagged_fields
+ .push(RawTaggedField::UnknownSemantics(vec![Fe32::Q]));
+ let too_long_signed_invoice = SignedRawBolt11Invoice {
+ raw_invoice: too_long_raw_invoice,
+ hash,
+ signature: invoice.signed_invoice.signature().clone(),
+ };
+ assert_eq!(
+ Bolt11Invoice::from_signed(too_long_signed_invoice),
+ Err(Bolt11SemanticError::InvoiceTooLong)
+ );
}
// Test that invoices above the maximum length fail to parse with the expected error.
### lightning-invoice/src/lib.rs
@@ -159,6 +159,17 @@ pub const DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA: u64 = 18;
/// consistency is more important.
pub const MAX_LENGTH: usize = 7089;
+/// The number of 5-bit values used to encode an invoice's 65-byte recoverable signature.
+const SIGNATURE_LEN_5: usize = 104;
+
+/// Returns the length of a signed invoice's string encoding, given the lengths of its HRP and of
+/// its data part excluding the signature.
+fn signed_invoice_encoded_len(hrp_len: usize, data_len: usize) -> usize {
+ // The encoded invoice consists of the HRP, the separator, the data, the signature and the
+ // checksum.
+ hrp_len + 1 + data_len + SIGNATURE_LEN_5 + Bolt11Bech32::CHECKSUM_LENGTH
+}
+
/// The maximum length of a tagged field in a BOLT11 invoice. This is 1023 * 5 bits (i.e., 639
/// bytes).
pub const MAX_TAGGED_FIELD_DATA_BYTES: usize = 639;
@@ -728,7 +739,7 @@ impl<D: tb::Bool, H: tb::Bool, C: tb::Bool, S: tb::Bool, M: tb::Bool>
InvoiceBuilder<D, H, tb::True, C, S, M>
{
/// Builds a [`RawBolt11Invoice`] if no [`CreationError`] occurred while construction any of the
- /// fields.
+ /// fields and the invoice will not exceed [`MAX_LENGTH`] once signed and encoded.
pub fn build_raw(self) -> Result<RawBolt11Invoice, CreationError> {
// If an error occurred at any time before, return it now
if let Some(e) = self.error {
@@ -748,7 +759,12 @@ impl<D: tb::Bool, H: tb::Bool, C: tb::Bool, S: tb::Bool, M: tb::Bool>
let data = RawDataPart { timestamp, tagged_fields };
- Ok(RawBolt11Invoice { hrp, data })
+ let invoice = RawBolt11Invoice { hrp, data };
+ if invoice.signed_encoded_len() > MAX_LENGTH {
+ return Err(CreationError::InvoiceTooLong);
+ }
+
+ Ok(invoice)
}
}
@@ -981,6 +997,10 @@ impl<M: tb::Bool> InvoiceBuilder<tb::True, tb::True, tb::True, tb::True, tb::Tru
let invoice = Bolt11Invoice { signed_invoice: signed };
+ if invoice.check_signature().is_err() {
+ return Err(SignOrCreationError::CreationError(CreationError::InvalidSignature));
+ }
+
invoice.check_field_counts().expect("should be ensured by type signature of builder");
invoice.check_feature_bits().expect("should be ensured by type signature of builder");
invoice.check_amount().expect("should be ensured by type signature of builder");
@@ -1123,6 +1143,11 @@ impl RawBolt11Invoice {
hash
}
+ /// Returns the length of the string encoding of this invoice once signed.
+ fn signed_encoded_len(&self) -> usize {
+ signed_invoice_encoded_len(self.hrp.to_string().len(), self.data.fe_iter().count())
+ }
+
/// Calculate the hash of the encoded `RawBolt11Invoice` which should be signed.
pub fn signable_hash(&self) -> [u8; 32] {
Self::hash_from_parts(self.hrp.to_string().as_bytes(), self.data.fe_iter())
@@ -1235,6 +1260,15 @@ impl RawBolt11Invoice {
/// Convert from HRP prefix and Fe32 encoded data part.
/// Can be used to receive unsigned invoices for remote signing.
pub fn from_raw(hrp: &str, data: &[Fe32]) -> Result<Self, Bolt11ParseError> {
+ let encoded_len = signed_invoice_encoded_len(hrp.len(), data.len());
+ if encoded_len > MAX_LENGTH {
+ return Err(Bolt11ParseError::InvalidSliceLength(
+ encoded_len,
+ MAX_LENGTH,
+ "RawBolt11Invoice",
+ ));
+ }
+
let raw_hrp: RawHrp = RawHrp::from_str(hrp)?;
let data_part = RawDataPart::from_base32(data)?;
@@ -1382,6 +1416,14 @@ impl Bolt11Invoice {
Ok(())
}
+ /// Check that the invoice does not exceed [`MAX_LENGTH`] once encoded
+ fn check_length(&self) -> Result<(), Bolt11SemanticError> {
+ if self.signed_invoice.raw_invoice().signed_encoded_len() > MAX_LENGTH {
+ return Err(Bolt11SemanticError::InvoiceTooLong);
+ }
+ Ok(())
+ }
+
/// Check that feature bits are set as required
fn check_feature_bits(&self) -> Result<(), Bolt11SemanticError> {
self.check_payment_secret()?;
@@ -1445,6 +1487,7 @@ impl Bolt11Invoice {
invoice.check_feature_bits()?;
invoice.check_signature()?;
invoice.check_amount()?;
+ invoice.check_length()?;
Ok(invoice)
}
@@ -1838,6 +1881,12 @@ pub enum CreationError {
/// The provided `min_final_cltv_expiry_delta` was less than rust-lightning's minimum.
MinFinalCltvExpiryDeltaTooShort,
+
+ /// The signature produced by the signing function was not valid for the invoice.
+ InvalidSignature,
+
+ /// The invoice would be longer than [`MAX_LENGTH`] once signed and encoded.
+ InvoiceTooLong,
}
impl Display for CreationError {
@@ -1851,6 +1900,8 @@ impl Display for CreationError {
CreationError::MissingRouteHints => f.write_str("The invoice required route hints and they weren't provided"),
CreationError::MinFinalCltvExpiryDeltaTooShort => f.write_str(
"The supplied final CLTV expiry delta was less than LDK's `MIN_FINAL_CLTV_EXPIRY_DELTA`"),
+ CreationError::InvalidSignature => f.write_str("The signature produced by the signing function was not valid for the invoice"),
+ CreationError::InvoiceTooLong => f.write_str("The invoice would be longer than 7089 bytes once signed and encoded"),
}
}
}
@@ -1889,6 +1940,9 @@ pub enum Bolt11SemanticError {
/// The invoice's amount was not a whole number of millisatoshis
ImpreciseAmount,
+
+ /// The invoice is longer than [`MAX_LENGTH`] once encoded
+ InvoiceTooLong,
}
impl Display for Bolt11SemanticError {
@@ -1903,6 +1957,7 @@ impl Display for Bolt11SemanticError {
Bolt11SemanticError::InvalidFeatures => f.write_str("The invoice's features are invalid"),
Bolt11SemanticError::InvalidSignature => f.write_str("The invoice's signature is invalid"),
Bolt11SemanticError::ImpreciseAmount => f.write_str("The invoice's amount was not a whole number of millisatoshis"),
+ Bolt11SemanticError::InvoiceTooLong => f.write_str("The invoice is longer than 7089 bytes once encoded"),
}
}
}
@@ -2287,7 +2342,7 @@ mod test {
#[test]
fn test_builder_fail() {
use crate::*;
- use bitcoin::secp256k1::PublicKey;
+ use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
use lightning_types::routing::RouteHintHop;
use std::iter::FromIterator;
@@ -2320,16 +2375,48 @@ mod test {
htlc_minimum_msat: None,
htlc_maximum_msat: None,
};
- let too_long_route = RouteHint(vec![route_hop; 13]);
+ let too_long_route = RouteHint(vec![route_hop.clone(); 13]);
let long_route_res =
builder.clone().description("Test".into()).private_route(too_long_route).build_raw();
assert_eq!(long_route_res, Err(CreationError::RouteTooLong));
let sign_error_res = builder
+ .clone()
.description("Test".into())
.payment_secret(PaymentSecret([0; 32]))
.try_build_signed(|_| Err("ImaginaryError"));
assert_eq!(sign_error_res, Err(SignOrCreationError::SignError("ImaginaryError")));
+
+ let secp_ctx = Secp256k1::new();
+ let payee_key = SecretKey::from_slice(&[41; 32]).unwrap();
+ let other_key = SecretKey::from_slice(&[42; 32]).unwrap();
+ let wrong_key_res = builder
+ .clone()
+ .description("Test".into())
+ .payment_secret(PaymentSecret([0; 32]))
+ .payee_pub_key(PublicKey::from_secret_key(&secp_ctx, &payee_key))
+ .build_signed(|hash| secp_ctx.sign_ecdsa_recoverable(hash, &other_key));
+ assert_eq!(wrong_key_res, Err(CreationError::InvalidSignature));
+
+ // An invoice with a 1 second expiry time and a 588 byte description encodes to exactly
+ // `MAX_LENGTH`, while a 32 second expiry time takes one more character to encode.
+ let max_length_route = RouteHint(vec![route_hop; 12]);
+ let max_length_builder = |expiry_secs| {
+ let mut builder = builder
+ .clone()
+ .description("a".repeat(588))
+ .payment_secret(PaymentSecret([0; 32]))
+ .expiry_time(Duration::from_secs(expiry_secs));
+ for _ in 0..6 {
+ builder = builder.private_route(max_length_route.clone());
+ }
+ builder
+ };
+ let max_length_invoice = max_length_builder(1)
+ .build_signed(|hash| secp_ctx.sign_ecdsa_recoverable(hash, &payee_key))
+ .unwrap();
+ assert_eq!(max_length_invoice.to_string().len(), MAX_LENGTH);
+ assert_eq!(max_length_builder(32).build_raw(), Err(CreationError::InvoiceTooLong));
}
#[test]
### lightning/src/ln/channelmanager.rs
@@ -15289,12 +15289,7 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
} else {
invoice.build_raw()
}.map_err(|e| SignOrCreationError::CreationError(e))?;
- let signature = self.node_signer.sign_invoice(&raw_invoice, Recipient::Node);
-
- raw_invoice
- .sign(|_| signature)
- .map(|invoice| Bolt11Invoice::from_signed(invoice).unwrap())
- .map_err(|e| SignOrCreationError::SignError(e))
+ super::invoice_utils::sign_invoice(raw_invoice, &self.node_signer, Recipient::Node)
}
}
### lightning/src/ln/invoice_utils.rs
@@ -1,7 +1,8 @@
//! Convenient utilities to create an invoice.
use lightning_invoice::{
- Bolt11Invoice, CreationError, Currency, InvoiceBuilder, SignOrCreationError,
+ Bolt11Invoice, Bolt11SemanticError, CreationError, Currency, InvoiceBuilder, RawBolt11Invoice,
+ SignOrCreationError,
};
use lightning_invoice::{Bolt11InvoiceDescription, Description, Sha256};
@@ -243,12 +244,35 @@ fn _create_phantom_invoice<ES: EntropySource, NS: NodeSigner, L: Logger>(
Ok(inv) => inv,
Err(e) => return Err(SignOrCreationError::CreationError(e)),
};
- let signature = node_signer.sign_invoice(&raw_invoice, Recipient::PhantomNode);
- let signed_raw_invoice = raw_invoice.sign(|_| signature);
- match signed_raw_invoice {
- Ok(inv) => Ok(Bolt11Invoice::from_signed(inv).unwrap()),
- Err(e) => Err(SignOrCreationError::SignError(e)),
- }
+ sign_invoice(raw_invoice, &node_signer, Recipient::PhantomNode)
+}
+
+/// Signs an invoice built by an [`InvoiceBuilder`] with the given [`NodeSigner`], checking that
+/// the produced signature is valid for it.
+pub(super) fn sign_invoice<NS: NodeSigner>(
+ raw_invoice: RawBolt11Invoice, node_signer: &NS, recipient: Recipient,
+) -> Result<Bolt11Invoice, SignOrCreationError<()>> {
+ let signature = node_signer.sign_invoice(&raw_invoice, recipient);
+ let signed_raw_invoice =
+ raw_invoice.sign(|_| signature).map_err(SignOrCreationError::SignError)?;
+ Bolt11Invoice::from_signed(signed_raw_invoice).map_err(|e| match e {
+ Bolt11SemanticError::InvalidSignature => {
+ SignOrCreationError::CreationError(CreationError::InvalidSignature)
+ },
+ Bolt11SemanticError::InvoiceTooLong => {
+ SignOrCreationError::CreationError(CreationError::InvoiceTooLong)
+ },
+ Bolt11SemanticError::NoPaymentHash
+ | Bolt11SemanticError::MultiplePaymentHashes
+ | Bolt11SemanticError::NoDescription
+ | Bolt11SemanticError::MultipleDescriptions
+ | Bolt11SemanticError::NoPaymentSecret
+ | Bolt11SemanticError::MultiplePaymentSecrets
+ | Bolt11SemanticError::InvalidFeatures
+ | Bolt11SemanticError::ImpreciseAmount => {
+ unreachable!("Ensured by the type signature of the invoice builder")
+ },
+ })
}
/// Utility to select route hints for phantom invoices.
### pending_changelog/5306-invoice-invalid-signature.txt
@@ -0,0 +1,7 @@
+# API Updates
+ * `InvoiceBuilder::build_signed` and `try_build_signed` now verify the signature produced by the
+ signing function, failing with the new `CreationError::InvalidSignature` if it isn't valid
+ (#5306).
+ * `InvoiceBuilder::build_raw` and `Bolt11Invoice::from_signed` now reject invoices which would be
+ longer than `MAX_LENGTH` once encoded, failing with the new `CreationError::InvoiceTooLong` and
+ `Bolt11SemanticError::InvoiceTooLong`, respectively (#5306).Why this scored 62/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.