Skip to content
Open
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
62 changes: 60 additions & 2 deletions src/modules/scanner/bip321_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64>) -> 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]))
Expand Down Expand Up @@ -422,3 +431,52 @@ 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()),
// 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)),
"{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"] {
let invoice = onchain(&format!("bitcoin:{ADDRESS}?amount={amount}")).await;
assert_eq!(invoice.amount_satoshis, 0, "{amount}");
}
}
24 changes: 18 additions & 6 deletions src/modules/scanner/implementation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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());
let uri_msat = parse_amount_as_satoshis(amount)?.checked_mul(1000);
if invoice_msat.is_none() || uri_msat != invoice_msat {
return Err(DecodingError::InvalidAmount);
}
}
return Ok(decoded);
}

if instructions
Expand Down
135 changes: 131 additions & 4 deletions src/modules/scanner/utils.rs
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() {
Comment thread
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}"
);
}
}
}
Loading