Repository navigation
fix: check bip 321 amounts against the bip #225
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
7007458
2688084
e644cb3
5444cf3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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. | ||
| // 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 invoice_msat = Bolt11Invoice::from_str(&request) | ||
| .ok() | ||
| .and_then(|invoice| invoice.amount_milli_satoshis()); | ||
|
Comment on lines
+197
to
+203
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: The lightning instruction is parsed and signature-checked twice
|
||
| let uri_msat = parse_amount_as_satoshis(amount)?.checked_mul(1000); | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the reviewers disagree, your call: An exact URI amount can never match an invoice priced in fractions of a satoshi The address-less Lightning check compares amounts in millisatoshis, but it first parses the URI amount with Objection: Real, but blocking rather than non-blocking: The whole-satoshi parser rejects
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. worth doing, does not block: Matching fractional-satoshi Lightning amounts are rejected A Lightning-only URI now fails when its decimal amount exactly matches a fractional-satoshi invoice. I tested |
||
| if invoice_msat.is_none() || uri_msat != invoice_msat { | ||
| return Err(DecodingError::InvalidAmount); | ||
| } | ||
| } | ||
| return Ok(decoded); | ||
| } | ||
|
|
||
| if instructions | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,135 @@ | ||
| 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<u64, DecodingError> { | ||
| amount | ||
| .parse::<f64>() | ||
| .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<SAT_DIGITS$}") | ||
| .parse() | ||
| .map_err(|_| DecodingError::InvalidAmount)?; | ||
| whole | ||
| .checked_mul(SATS_PER_BTC) | ||
| .and_then(|btc| btc.checked_add(sats)) | ||
| .ok_or(DecodingError::InvalidAmount) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn bip321_amounts_parse_exactly() { | ||
|
jvsena42 marked this conversation as resolved.
Resolved
|
||
| for (amount, sats) in [ | ||
| ("50", 5_000_000_000), | ||
| ("50.00", 5_000_000_000), | ||
| ("20.3", 2_030_000_000), | ||
| ("0.0000799", 7_990), | ||
| ("0.00000001", 1), | ||
| ("0.000000010", 1), | ||
| (".5", 50_000_000), | ||
| ("5.", 500_000_000), | ||
| ("0.1", 10_000_000), | ||
| ] { | ||
| assert_eq!( | ||
| parse_amount_as_satoshis(amount).ok(), | ||
| Some(sats), | ||
| "{amount}" | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| /// 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 [ | ||
| "", | ||
| ".", | ||
| "0.0000799BTC", | ||
| "0.0000799,50", | ||
| "50,000.00", | ||
| "1e3", | ||
| "-1", | ||
| "+1", | ||
| " 1", | ||
| "inf", | ||
| "NaN", | ||
| "0.000000015", | ||
| "1.2.3", | ||
| "184467440738", | ||
| ] { | ||
| assert!( | ||
| matches!( | ||
| parse_amount_as_satoshis(amount), | ||
| Err(DecodingError::InvalidAmount) | ||
| ), | ||
| "{amount}" | ||
| ); | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
worth doing, does not block: The amount check verifies the same invoice twice
Every addressless BOLT11 URI with an amount incurs a second signature verification.
decode_lightningalready parsed and verified the same invoice at line 339. Check the expected amount there while the signed millisatoshi value is available.