Merge PR 'Report bare BOLT 11 invoice amounts that overflow pico BTC' (#5338)
What changed, and why it matters
This change fixes a bug in how BOLT 11 Lightning invoices handle very large amounts written without a unit suffix (like 'lnbc18446745...'). Previously, such invoices could bypass an overflow check and later cause arithmetic errors or unexpected behavior when the code tried to convert the amount into smaller units. The patch now rejects these oversized amounts both during parsing and when constructing a signed invoice, returning a clear error instead.
Review callers that parse or construct BOLT 11 invoices to ensure they handle `Bolt11ParseError::IntegerOverflowError` and the new `Bolt11SemanticError::AmountOverflow` gracefully. Consider auditing other numeric conversions in invoice handling for similar overflow gaps.
Security signals we found
Integer overflow in amount parsing
Missing validation for bare-amount invoices
New semantic error variant for amount overflow
Test case demonstrates overflow rejection
Evidence from the diff
The patch addresses an integer overflow in BOLT 11 invoice amount handling. In RawHrp::from_str, the overflow check only multiplied raw_amount by the SI prefix multiplier, so a bare amount (no SI prefix, implicitly BTC) was not validated against pico-BTC overflow. The fix applies a default multiplier of 1,000,000,000,000 (pico BTC per BTC) when no SI prefix is present. Additionally, Bolt11Invoice::check_amount now returns a new Bolt11SemanticError::AmountOverflow when amount_pico_btc() returns None despite a raw amount being present, catching invoices constructed programmatically that bypass FromStr. A test demonstrates that lnbc18446745 is rejected and that a manually built invoice with raw_amount: Some(184_467_441) and no SI prefix fails with AmountOverflow.
Changed components
lightning-invoice/src/de.rslightning-invoice/src/lib.rslightning/src/ln/invoice_utils.rsInspect captured patch +72 / −12
### lightning-invoice/src/de.rs
@@ -423,17 +423,15 @@ impl FromStr for RawHrp {
let amount = if !parts.1.is_empty() { Some(parts.1.parse::<u64>()?) } else { None };
- let si_prefix: Option<SiPrefix> = if parts.2.is_empty() {
- None
- } else {
- let si: SiPrefix = parts.2.parse()?;
- if let Some(amt) = amount {
- if amt.checked_mul(si.multiplier()).is_none() {
- return Err(Bolt11ParseError::IntegerOverflowError);
- }
+ let si_prefix = if parts.2.is_empty() { None } else { Some(parts.2.parse()?) };
+
+ if let Some(amt) = amount {
+ let multiplier =
+ si_prefix.as_ref().map_or(1_000_000_000_000, |si: &SiPrefix| si.multiplier());
+ if amt.checked_mul(multiplier).is_none() {
+ return Err(Bolt11ParseError::IntegerOverflowError);
}
- Some(si)
- };
+ }
Ok(RawHrp { currency, raw_amount: amount, si_prefix })
}
### lightning-invoice/src/lib.rs
@@ -1406,12 +1406,14 @@ impl Bolt11Invoice {
Ok(())
}
- /// Check that amount is a whole number of millisatoshis
+ /// Check that amount is a whole number of millisatoshis and can be represented
fn check_amount(&self) -> Result<(), Bolt11SemanticError> {
if let Some(amount_pico_btc) = self.amount_pico_btc() {
if amount_pico_btc % 10 != 0 {
return Err(Bolt11SemanticError::ImpreciseAmount);
}
+ } else if self.signed_invoice.hrp.raw_amount.is_some() {
+ return Err(Bolt11SemanticError::AmountOverflow);
}
Ok(())
}
@@ -1941,6 +1943,9 @@ pub enum Bolt11SemanticError {
/// The invoice's amount was not a whole number of millisatoshis
ImpreciseAmount,
+ /// The invoice's amount is too large to be represented
+ AmountOverflow,
+
/// The invoice is longer than [`MAX_LENGTH`] once encoded
InvoiceTooLong,
}
@@ -1957,6 +1962,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::AmountOverflow => f.write_str("The invoice's amount is too large to be represented"),
Bolt11SemanticError::InvoiceTooLong => f.write_str("The invoice is longer than 7089 bytes once encoded"),
}
}
@@ -2339,6 +2345,61 @@ mod test {
assert_eq!(invoice.hrp.raw_amount, Some(1500));
}
+ #[test]
+ fn test_amount_without_si_prefix() {
+ use crate::TaggedField::*;
+ use crate::{
+ Bolt11Invoice, Bolt11ParseError, Bolt11SemanticError, Currency, PaymentHash,
+ PositiveTimestamp, RawBolt11Invoice, RawDataPart, RawHrp,
+ };
+ use bitcoin::hex::FromHex;
+ use bitcoin::secp256k1::{Secp256k1, SecretKey};
+ use lightning_types::features::Bolt11InvoiceFeatures;
+
+ let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
+ let mut payment_secret_features = Bolt11InvoiceFeatures::empty();
+ payment_secret_features.set_payment_secret_required();
+
+ // An amount without an SI prefix that overflows pico BTC cannot be reported in
+ // millisatoshis either, so `from_signed` needs to reject it even though invoices built
+ // this way bypass the overflow check in `RawHrp::from_str`.
+ let invoice =
+ RawBolt11Invoice {
+ hrp: RawHrp {
+ currency: Currency::Bitcoin,
+ raw_amount: Some(184_467_441),
+ si_prefix: None,
+ },
+ data: RawDataPart {
+ timestamp: PositiveTimestamp::from_unix_timestamp(1496314658).unwrap(),
+ tagged_fields: vec![
+ crate::TaggedField::PaymentHash(PaymentHash(
+ <[u8; 32]>::try_from(
+ Vec::from_hex(
+ "0001020304050607080900010203040506070809000102030405060708090102",
+ )
+ .unwrap(),
+ )
+ .unwrap(),
+ ))
+ .into(),
+ Description(crate::Description::new("Test".to_owned()).unwrap()).into(),
+ crate::TaggedField::PaymentSecret(lightning_types::payment::PaymentSecret([21; 32]))
+ .into(),
+ crate::TaggedField::Features(payment_secret_features).into(),
+ ],
+ },
+ }
+ .sign::<_, ()>(|hash| Ok(Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)))
+ .unwrap();
+ assert_eq!(Bolt11Invoice::from_signed(invoice), Err(Bolt11SemanticError::AmountOverflow));
+
+ // Amounts without an SI prefix are denominated in BTC and converted to pico BTC just like
+ // amounts carrying one, so anything above `u64::MAX / 1_000_000_000_000` BTC is rejected.
+ assert_eq!("lnbc18446744".parse::<RawHrp>().unwrap().raw_amount, Some(18_446_744));
+ assert_eq!("lnbc18446745".parse::<RawHrp>(), Err(Bolt11ParseError::IntegerOverflowError));
+ }
+
#[test]
fn test_builder_fail() {
use crate::*;
### lightning/src/ln/invoice_utils.rs
@@ -269,7 +269,8 @@ pub(super) fn sign_invoice<NS: NodeSigner>(
| Bolt11SemanticError::NoPaymentSecret
| Bolt11SemanticError::MultiplePaymentSecrets
| Bolt11SemanticError::InvalidFeatures
- | Bolt11SemanticError::ImpreciseAmount => {
+ | Bolt11SemanticError::ImpreciseAmount
+ | Bolt11SemanticError::AmountOverflow => {
unreachable!("Ensured by the type signature of the invoice builder")
},
})Why this scored 48/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.