From 7007458edd62ecc30abff218267095e5717be9f0 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Mon, 23 Nov 2026 06:16:02 -0300 Subject: [PATCH 1/4] fix: parse bip 321 amounts by the bip grammar Co-Authored-By: Claude Opus 5.5 --- src/modules/scanner/bip321_tests.rs | 8 +++ src/modules/scanner/utils.rs | 87 +++++++++++++++++++++++++++-- 2 files changed, 91 insertions(+), 4 deletions(-) diff --git a/src/modules/scanner/bip321_tests.rs b/src/modules/scanner/bip321_tests.rs index 3c9bdfc6..9560b07f 100644 --- a/src/modules/scanner/bip321_tests.rs +++ b/src/modules/scanner/bip321_tests.rs @@ -422,3 +422,11 @@ async fn invalid_segwit_instruction_is_invalid() { ); } } + +#[tokio::test] +async fn invalid_onchain_amount_is_not_read_as_another_amount() { + for amount in ["1e3", "inf", "0.001BTC"] { + let invoice = onchain(&format!("bitcoin:{ADDRESS}?amount={amount}")).await; + assert_eq!(invoice.amount_satoshis, 0, "{amount}"); + } +} diff --git a/src/modules/scanner/utils.rs b/src/modules/scanner/utils.rs index 447b83c6..0db82270 100644 --- a/src/modules/scanner/utils.rs +++ b/src/modules/scanner/utils.rs @@ -1,8 +1,87 @@ use crate::DecodingError; +/// Parses a BIP 321 amount into satoshis. +/// +/// BIP 321 allows only decimal BTC: digits, optionally followed by a period and digits +/// (`*digit [ "." *digit ]`). Units, commas, signs and exponents are invalid, as are digits below one satoshi. pub fn parse_amount_as_satoshis(amount: &str) -> Result { - amount - .parse::() - .map_err(|_| DecodingError::InvalidAmount) - .map(|btc| (btc * 100_000_000.0).round() as u64) + const SATS_PER_BTC: u64 = 100_000_000; + const SAT_DIGITS: usize = 8; + + let (whole, fraction) = amount.split_once('.').unwrap_or((amount, "")); + let is_digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit()); + if (whole.is_empty() && fraction.is_empty()) || !is_digits(whole) || !is_digits(fraction) { + return Err(DecodingError::InvalidAmount); + } + let (sat_digits, below_a_sat) = fraction.split_at(fraction.len().min(SAT_DIGITS)); + if below_a_sat.bytes().any(|byte| byte != b'0') { + return Err(DecodingError::InvalidAmount); + } + + let whole: u64 = if whole.is_empty() { + 0 + } else { + whole.parse().map_err(|_| DecodingError::InvalidAmount)? + }; + let sats: u64 = format!("{sat_digits:0 Date: Mon, 23 Nov 2026 06:16:03 -0300 Subject: [PATCH 2/4] fix: reject a bip 321 amount its lightning invoice lacks Co-Authored-By: Claude Opus 5.5 --- src/modules/scanner/bip321_tests.rs | 45 +++++++++++++++++++++++++-- src/modules/scanner/implementation.rs | 24 ++++++++++---- 2 files changed, 61 insertions(+), 8 deletions(-) diff --git a/src/modules/scanner/bip321_tests.rs b/src/modules/scanner/bip321_tests.rs index 9560b07f..24263916 100644 --- a/src/modules/scanner/bip321_tests.rs +++ b/src/modules/scanner/bip321_tests.rs @@ -33,14 +33,23 @@ const POS_INVOICE: &str = concat!( /// Stands in for the BIP's `lnbc420bogusinvoice`: a signed mainnet invoice for 42,000 sats. fn bip_invoice() -> String { + invoice_for(Some(42_000_000)) +} + +/// A signed mainnet invoice for `amount_msat`, or without an amount. +fn invoice_for(amount_msat: Option) -> String { use bitcoin::hashes::Hash; use bitcoin::secp256k1::{Secp256k1, SecretKey}; use lightning_invoice::{Currency, InvoiceBuilder}; let secp = Secp256k1::new(); let secret_key = SecretKey::from_slice(&[0x21; 32]).unwrap(); - InvoiceBuilder::new(Currency::Bitcoin) - .amount_milli_satoshis(42_000_000) + let builder = InvoiceBuilder::new(Currency::Bitcoin); + let builder = match amount_msat { + Some(amount_msat) => builder.amount_milli_satoshis(amount_msat), + None => builder, + }; + builder .description("BIP 321".to_string()) .payment_hash(bitcoin::hashes::sha256::Hash::from_byte_array([1; 32])) .payment_secret(lightning_invoice::PaymentSecret([2; 32])) @@ -423,6 +432,38 @@ async fn invalid_segwit_instruction_is_invalid() { } } +#[tokio::test] +async fn uri_without_address_keeps_an_amount_its_invoice_states() { + for amount in ["0.00042", "0.000420", ".00042"] { + let uri = format!("bitcoin:?amount={amount}&lightning={}", bip_invoice()); + let (_, sats, _) = lightning_bolt11(&uri).await; + assert_eq!(sats, 42_000, "{uri}"); + } +} + +#[tokio::test] +async fn uri_without_address_rejects_an_amount_its_invoice_does_not_state() { + for uri in [ + format!("bitcoin:?amount=0.00043&lightning={}", bip_invoice()), + format!("bitcoin:?amount=0.001&lightning={}", invoice_for(None)), + format!("bitcoin:?amount=0.00042BTC&lightning={}", bip_invoice()), + format!("bitcoin:?amount=0.00042,50&lightning={}", bip_invoice()), + format!("bitcoin:?AMOUNT=0.00043&lightning={}", bip_invoice()), + ] { + assert!( + matches!(decode(&uri).await, Err(DecodingError::InvalidAmount)), + "{uri}" + ); + } +} + +#[tokio::test] +async fn uri_without_address_allows_repeated_unknown_parameters() { + let uri = format!("bitcoin:?lightning={}&custom=a&custom=b", bip_invoice()); + let (_, sats, _) = lightning_bolt11(&uri).await; + assert_eq!(sats, 42_000); +} + #[tokio::test] async fn invalid_onchain_amount_is_not_read_as_another_amount() { for amount in ["1e3", "inf", "0.001BTC"] { diff --git a/src/modules/scanner/implementation.rs b/src/modules/scanner/implementation.rs index 2272dca7..645582b4 100644 --- a/src/modules/scanner/implementation.rs +++ b/src/modules/scanner/implementation.rs @@ -140,7 +140,8 @@ impl Scanner { /// `params`. Without one, the URI must carry a payment instruction in its query: /// - a segwit address in the parameter named after its human-readable part (`bc`, `tb`, `bcrt`), decoded /// as on-chain with that address, - /// - otherwise a `lightning` BOLT11 invoice (or LNURL), decoded as Lightning. + /// - otherwise a `lightning` BOLT11 invoice (or LNURL), decoded as Lightning. A BOLT11 invoice must state + /// the URI's `amount`, if it has one. /// /// Instructions Bitkit cannot pay (`lno`, `sp`, `pay`) give `UnsupportedType`, and no instruction at all /// gives `InvalidAddress`. @@ -190,11 +191,22 @@ impl Scanner { if let Some((_, value)) = instructions.iter().find(|(key, _)| key == "lightning") { let request = value.to_lowercase(); - return if request.starts_with("lnurl") { - Self::decode_lnurl(&request).await - } else { - Self::decode_lightning(&request) - }; + if request.starts_with("lnurl") { + return Self::decode_lnurl(&request).await; + } + let decoded = Self::decode_lightning(&request)?; + // The result carries only the invoice, so a URI amount it does not match would be lost. + if let Some((_, amount)) = instructions.iter().find(|(key, _)| key == "amount") { + let Scanner::Lightning { invoice } = &decoded else { + unreachable!("decode_lightning returns Lightning"); + }; + if invoice.amount_satoshis == 0 + || parse_amount_as_satoshis(amount)? != invoice.amount_satoshis + { + return Err(DecodingError::InvalidAmount); + } + } + return Ok(decoded); } if instructions From e644cb379396978c239b3715a4fcd127b6bf7589 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Mon, 23 Nov 2026 09:06:19 -0300 Subject: [PATCH 3/4] fix: compare a bip 321 amount with the signed invoice amount Co-Authored-By: Claude Opus 5.5 --- src/modules/scanner/bip321_tests.rs | 9 +++++++++ src/modules/scanner/implementation.rs | 12 ++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/modules/scanner/bip321_tests.rs b/src/modules/scanner/bip321_tests.rs index 24263916..d8b4a1f7 100644 --- a/src/modules/scanner/bip321_tests.rs +++ b/src/modules/scanner/bip321_tests.rs @@ -449,6 +449,15 @@ async fn uri_without_address_rejects_an_amount_its_invoice_does_not_state() { format!("bitcoin:?amount=0.00042BTC&lightning={}", bip_invoice()), format!("bitcoin:?amount=0.00042,50&lightning={}", bip_invoice()), format!("bitcoin:?AMOUNT=0.00043&lightning={}", bip_invoice()), + // 42,000.5 sats decodes as 42,001, but the invoice asks for neither amount. + format!( + "bitcoin:?amount=0.00042001&lightning={}", + invoice_for(Some(42_000_500)) + ), + format!( + "bitcoin:?amount=0.00042&lightning={}", + invoice_for(Some(42_000_500)) + ), ] { assert!( matches!(decode(&uri).await, Err(DecodingError::InvalidAmount)), diff --git a/src/modules/scanner/implementation.rs b/src/modules/scanner/implementation.rs index 645582b4..084d6884 100644 --- a/src/modules/scanner/implementation.rs +++ b/src/modules/scanner/implementation.rs @@ -196,13 +196,13 @@ impl Scanner { } let decoded = Self::decode_lightning(&request)?; // The result carries only the invoice, so a URI amount it does not match would be lost. + // Compare with the signed amount, since the decoded one is rounded up to whole sats. if let Some((_, amount)) = instructions.iter().find(|(key, _)| key == "amount") { - let Scanner::Lightning { invoice } = &decoded else { - unreachable!("decode_lightning returns Lightning"); - }; - if invoice.amount_satoshis == 0 - || parse_amount_as_satoshis(amount)? != invoice.amount_satoshis - { + let invoice_msat = Bolt11Invoice::from_str(&request) + .ok() + .and_then(|invoice| invoice.amount_milli_satoshis()); + let uri_msat = parse_amount_as_satoshis(amount)?.checked_mul(1000); + if invoice_msat.is_none() || uri_msat != invoice_msat { return Err(DecodingError::InvalidAmount); } } From 5444cf34c7d3d8322f9b4c2b2aeb21f52a1320b5 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Mon, 23 Nov 2026 09:06:19 -0300 Subject: [PATCH 4/4] test: round-trip bip 321 amounts across the satoshi range Co-Authored-By: Claude Opus 5.5 --- src/modules/scanner/utils.rs | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/modules/scanner/utils.rs b/src/modules/scanner/utils.rs index 0db82270..ca5d33ca 100644 --- a/src/modules/scanner/utils.rs +++ b/src/modules/scanner/utils.rs @@ -57,6 +57,54 @@ mod tests { } } + /// Writes `sats` as decimal BTC, with all eight fraction digits or with trailing zeros trimmed. + fn btc(sats: u64, trim: bool) -> String { + let fraction = format!("{:08}", sats % 100_000_000); + let fraction = if trim { + fraction.trim_end_matches('0') + } else { + &fraction + }; + match fraction { + "" => (sats / 100_000_000).to_string(), + fraction => format!("{}.{fraction}", sats / 100_000_000), + } + } + + #[test] + fn every_satoshi_amount_round_trips() { + let mut sats_values = vec![ + 0, + 1, + 99_999_999, + 100_000_000, + 100_000_001, + u64::MAX - 1, + u64::MAX, + ]; + // A fixed linear congruential sequence spreads samples over the whole u64 range. + let mut state: u64 = 0x2545_f491_4f6c_dd1d; + for _ in 0..20_000 { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + sats_values.push(state >> (state % 64)); + } + for sats in sats_values { + for trim in [false, true] { + let amount = btc(sats, trim); + assert_eq!( + parse_amount_as_satoshis(&amount).ok(), + Some(sats), + "{amount}" + ); + } + } + assert_eq!(btc(u64::MAX, false), "184467440737.09551615"); + assert!(parse_amount_as_satoshis("184467440737.09551616").is_err()); + assert!(parse_amount_as_satoshis("184467440738").is_err()); + } + #[test] fn amounts_outside_the_bip321_grammar_are_invalid() { for amount in [