diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 6420200..0756edc 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -7,52 +7,50 @@ jobs: runs-on: ubuntu-latest steps: - name: Set up Rust - uses: hecrj/setup-rust-action@v1 + uses: dtolnay/rust-toolchain@stable with: components: rustfmt - rust-version: stable - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - run: cargo fmt --all -- --check lint: runs-on: ubuntu-latest steps: - name: Set up Rust - uses: hecrj/setup-rust-action@v1 + uses: dtolnay/rust-toolchain@stable with: components: clippy - - uses: actions/checkout@v2 + - uses: actions/checkout@v6 - run: cargo clippy --all-targets --all-features -- -D clippy::all compile: runs-on: ubuntu-latest steps: - name: Set up Rust - uses: hecrj/setup-rust-action@v1 - - uses: actions/checkout@v2 + uses: dtolnay/rust-toolchain@stable + - uses: actions/checkout@v6 - run: cargo check --all test: needs: [codestyle, lint, compile] strategy: matrix: - os: [ubuntu-latest, windows-latest, macOS-latest] - rust: [stable, 1.63.0] + os: [ubuntu-latest, macOS-latest] + rust: [stable, "1.63"] exclude: - os: macOS-latest - rust: 1.63.0 + rust: "1.63" runs-on: ${{ matrix.os }} steps: - name: Setup Rust - uses: hecrj/setup-rust-action@v1 + uses: dtolnay/rust-toolchain@master with: - rust-version: ${{ matrix.rust }} + toolchain: ${{ matrix.rust }} - name: Checkout - uses: actions/checkout@v2 - - name: Fixes for MSRV - if: matrix.rust == '1.63.0' - run: | - cargo update + uses: actions/checkout@v6 + - name: Pin dependencies for MSRV + if: matrix.rust == '1.63' + run: cargo update -p cc --precise 1.1.31 - name: Test run: cargo test diff --git a/CHANGELOG.md b/CHANGELOG.md index 0afdbf9..4cf9c28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,52 @@ # bitcoin_uri Changelog +## Unreleased + +### Breaking changes + +- MSRV is 1.63, now declared in `rust-version`, and `bitcoin` must be at + least 0.32.102. 1.63 matches `bitcoin-payment-instructions`, which this + crate is meant to be a dependency of. +- The body address is now optional, so a body-less URI such as + `bitcoin:?sp=...` parses. `Uri::body` returns `Option<&Address>`. +- `Uri` is now owned and has no lifetime parameter: `Uri` instead of + `Uri<'a, NetVal, Extras>`. +- Removed the `Extras` type parameter and the `DeserializeParams`, + `DeserializationState`, `SerializeParams`, and `Param` traits/types. An + extension now reads its parameters straight off the parsed `Uri` via the + `Params` multimap instead of plugging a type into the parser. +- Removed the `non-compliant-bytes` feature and the optional `either` + dependency. A non-UTF-8 parameter value is now an access-time error on the + typed accessor that needs it, not a separate API. + +### Added + +- `Params`/`ParamEntry`: an ordered, case-insensitive multimap of the raw + query parameters, preserving source order and percent-encoding, with + `ParamEntry::decoded_value` for on-demand RFC 3986 decoding. +- `AccessError`, returned when a value is read: its percent-decoded bytes + may not be valid UTF-8. +- Parse-time `Error`, separate from `AccessError`. Invalid + percent-encoding in any value fails the parse; a value that decodes to + bytes that are not UTF-8 fails only when it is read. +- `Uri::require_network`/`is_valid_for_network` over the body and the + `bc`/`tb`/`bcrt` parameters. A value under one of those keys must be a + segwit address of the key's network, or parsing fails with + `Error::InvalidHrpValue`. +- `NetworkError`, kept separate from the parse `Error`. +- `Uri::unsatisfied_requirements`, reporting the `req-` parameters a client + does not understand, plus `ParamEntry::requirement`/`is_required`. +- An `extension_params` example showing a consumer reading `pj`/`sp`/ + `lightning` off a parsed URI with `get` + `decoded_value`. +- `Display` of a parsed `Uri` writes back the exact string it was parsed + from, and `Uri::source_str` returns it. +- `UriBuilder`, assembling a `Uri` from typed parts. Its output parses back + to the same parameters: keys and raw values must be RFC 3986 query + characters, and `build` checks each `bc`/`tb`/`bcrt` address against the + network its key names and the body against that network, rejecting a + URI that mixes networks. +- `BuildError`, wrapping `NetworkError` for build-time network mismatch. + ## 0.1.0 - Fork from [Kixunil/bip21 @ `eae7201`](https://github.com/Kixunil/bip21/commit/eae72026cc5838bb169949641948b8c1cef99cbe) v0.5.0. diff --git a/Cargo.toml b/Cargo.toml index 80d10de..5629e5e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,8 +1,9 @@ [package] name = "bitcoin_uri" -version = "0.1.0" +version = "0.2.0" authors = ["Dan Gould "] -edition = "2018" +edition = "2021" +rust-version = "1.63" description = "Rust-idiomatic, compliant, flexible and performant bitcoin URI crate." repository = "https://github.com/payjoin/bitcoin_uri" readme = "README.md" @@ -11,19 +12,16 @@ categories = ["cryptography::cryptocurrencies", "encoding", "rust-patterns", "va license = "MITNFA" [package.metadata.docs.rs] -features = ["std", "non-compliant-bytes"] +features = ["std"] rustdoc-args = ["--cfg", "docsrs"] [features] # Implements std::error::Error for error types std = ["percent-encoding-rfc3986/std", "bitcoin/std"] -# Enables non-BIP21-compliant feature of using raw bytes instead of validated UTF-8 strings. -non-compliant-bytes = ["either"] [dependencies] -either = { version = "1.6.1", optional = true } percent-encoding-rfc3986 = "0.1.3" -bitcoin = { version = "0.32.0", default-features = false } +bitcoin = { version = "0.32.102", default-features = false } [dev-dependencies] -bitcoin = { version = "0.32.0", features = ["std"] } +bitcoin = { version = "0.32.102", features = ["std"] } diff --git a/README.md b/README.md index bdbc8f8..0f89b23 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,30 @@ -# Rust implementation of BIP21 bitcoin URIs +# Rust implementation of BIP 321 bitcoin URIs Rust-idiomatic, compliant, flexible and performant bitcoin URI crate. ## About -**Important:** while lot of work went into polishing the crate it's still considered -early-development! +**Important:** this is the 0.2 line, a rewrite against +[issue #12](https://github.com/payjoin/bitcoin_uri/issues/12). Its API is not +yet stable. 0.1 remains the published, stable crate. -* Rust-idiomatic: uses strong types, standard traits and other things -* Compliant: implements all requirements of BIP21, including protections to not forget about - `req-`. (But see features.) -* Flexible: enables parsing/serializing additional arguments not defined by BIP21. -* Performant: uses zero-copy deserialization and lazy evaluation wherever possible. - -Serialization and deserialization is inspired by `serde` with these important differences: - -* Deserialization signals if the field is known so that `req-` fields can be rejected. -* Much simpler API - we don't need all the features. -* Use of [`Param<'a>`] to enable lazy evaluation. +* Rust-idiomatic: owned types, no lifetime parameter. +* Compliant: parses the full BIP 321 shape, including a body-less URI, and + reports `req-` parameters a client does not understand through + `Uri::unsatisfied_requirements` rather than enforcing them itself. +* Flexible: an extension reads whatever parameters it needs straight off the + parsed `Uri`; this crate never needs to know what they mean. +* Performant: values stay percent-encoded until something decodes them. The crate is `no_std` but does require `alloc`. -## Features +## Features * `std` enables integration with `std` - mainly `std::error::Error`. -* `non-compliant-bytes` - enables use of non-compliant API that can parse non-UTF-8 URI values. ## MSRV -1.63.0 +1.63 ## License diff --git a/examples/extension_params.rs b/examples/extension_params.rs new file mode 100644 index 0000000..38aa87b --- /dev/null +++ b/examples/extension_params.rs @@ -0,0 +1,56 @@ +//! Reading extension parameters off a parsed URI. +//! +//! `bitcoin_uri` is a tokenizer: it parses the BIP 321 shape and hands back +//! every parameter still percent-encoded, without knowing what any of them +//! mean. An extension (payjoin's `pj`, a silent-payment `sp`, a BOLT 11 +//! `lightning` invoice, anything else) reads whatever it needs straight off +//! the parsed [`Uri`] with [`Uri::get`]/[`Uri::get_all`] and decodes it with +//! [`ParamEntry::decoded_value`]. This example walks a body-less URI that +//! carries three unrelated extensions at once. +//! +//! Run with: `cargo run --example extension_params` + +use bitcoin_uri::Uri; + +fn main() { + // A body-less URI (BIP 321 allows one): no on-chain address, just three + // extension parameters, one of them marked `req-`. + let input = "bitcoin:?sp=sp1qsilentpaymentaddress\ + &lightning=lnbc420bogusinvoice\ + &req-pj=https://example.com/pay%3Ftoken%3Dabc"; + + let uri: Uri<_> = input.parse().expect("valid BIP 321 URI"); + + // No body, so this is an extension-only payment request. + assert!(uri.body().is_none()); + + // A silent-payment wallet reads `sp` without the crate knowing what it is. + if let Some(entry) = uri.get("sp") { + let address = entry.decoded_value().expect("sp has a value").expect("valid UTF-8"); + println!("sp: {address}"); + } + + // `lightning` carries a BOLT 11 invoice (BOLT 12 offers use `lno`). The + // value comes back in the case it arrived in, which is uppercase if it + // came from a QR code. + if let Some(entry) = uri.get("lightning") { + let invoice = entry.decoded_value().expect("lightning has a value").expect("valid UTF-8"); + println!("lightning: {invoice}"); + } + + // `get` matches by base key, so it finds `req-pj` when asked for `pj`. + // `decoded_value` applies RFC 3986 percent-decoding on demand, turning + // `%3F` back into `?` and `%3D` into `=`. + if let Some(entry) = uri.get("pj") { + let endpoint = entry.decoded_value().expect("pj has a value").expect("valid UTF-8"); + println!("pj endpoint: {endpoint} (required: {})", entry.is_required()); + } + + // A consumer declares the extensions it understands; anything `req-` it + // does not understand means it MUST reject the URI. Here it handles `pj` + // and `sp` but not, say, a hypothetical `req-foo`. + let understood = ["pj", "sp", "lightning"]; + let unsatisfied = uri.unsatisfied_requirements(&understood).count(); + assert_eq!(unsatisfied, 0, "every required extension is understood"); + println!("all {} parameters understood; safe to act on", uri.params().len()); +} diff --git a/src/builder.rs b/src/builder.rs new file mode 100644 index 0000000..1c10b63 --- /dev/null +++ b/src/builder.rs @@ -0,0 +1,589 @@ +//! Assembling a `bitcoin:` URI from typed parts. +//! +//! [`UriBuilder`] is the counterpart to parsing: it takes an address, an +//! amount, labels, and any extension parameters and produces a [`Uri`] whose +//! [`Display`](core::fmt::Display) re-parses to the same parameters. +//! +//! Values handed to the typed setters and to [`UriBuilder::param`] are +//! percent-encoded for you; [`UriBuilder::raw_param`] takes a value that is +//! already encoded and passes it through untouched. Encoding is RFC 3986: a +//! literal `+` becomes `%2B` rather than being left to a reader that might +//! read it as a space. + +use alloc::string::{String, ToString}; +use alloc::vec::Vec; + +use percent_encoding_rfc3986::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC}; + +use crate::error::{BuildError, NetworkError}; +use crate::params::{self, ParamEntry, Params, NON_REPEATABLE_KEYS}; +use crate::{Uri, HRP_ADDRESS_KEYS}; + +/// The bytes a parameter value is percent-encoded against. +/// +/// Starts from [`NON_ALPHANUMERIC`] and allows back the `unreserved` +/// characters and the `sub-delims` / `pchar` extras that are safe inside a +/// BIP 321 query value - but keeps `&` and `=` (the parameter separators) +/// encoded, and deliberately keeps `+` encoded as `%2B` so no reader can +/// mistake it for a space. +const VALUE_ASCII_SET: AsciiSet = NON_ALPHANUMERIC + .remove(b'-') + .remove(b'.') + .remove(b'_') + .remove(b'~') + .remove(b'!') + .remove(b'$') + .remove(b'\'') + .remove(b'(') + .remove(b')') + .remove(b'*') + .remove(b',') + .remove(b';') + .remove(b':') + .remove(b'@') + .remove(b'/') + .remove(b'?'); + +fn encode(value: &str) -> String { + utf8_percent_encode(value, &VALUE_ASCII_SET).to_string() +} + +/// `true` if every byte of `s` is a BIP 321 `qchar`: an RFC 3986 query +/// character other than `&` and `=`, with every `%` starting a valid escape. +fn is_qchars(s: &str) -> bool { + s.bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"-._~!$'()*+,;:@/?%".contains(&byte)) + && percent_encoding_rfc3986::percent_decode_str(s).is_ok() +} + +/// BIP 321 has `otherparam = qchar *qchar ...` and `reqparam = "req-" qchar +/// *qchar ...`, so a key and its base key are both non-empty. +fn key_round_trips(key: &str) -> bool { + is_qchars(key) && !params::base_key(key).is_empty() +} + +fn raw_value_round_trips(value: &str) -> bool { + is_qchars(value) +} + +fn is_non_repeatable_base_key(key: &str, base_key: &str) -> bool { + params::base_key(key).eq_ignore_ascii_case(base_key) +} + +/// Builds a [`Uri`] from typed parts. +/// +/// The setters are chainable and consume `self`. A non-repeatable parameter +/// (`amount`, `label`, `message`) set more than once through its own setter +/// keeps only the last value; a duplicate introduced through [`param`] or +/// [`raw_param`] is caught by [`build`] instead. +/// +/// [`param`]: UriBuilder::param +/// [`raw_param`]: UriBuilder::raw_param +/// [`build`]: UriBuilder::build +/// +/// ``` +/// # use bitcoin_uri::{UriBuilder, Uri}; +/// let address = "1andreas3batLhQa2FawWjeyjCqyBzypd".parse::>().unwrap().assume_checked(); +/// let uri = UriBuilder::new() +/// .address(address) +/// .amount(bitcoin::Amount::from_sat(100_000)) +/// .label("Luke-Jr") +/// .build() +/// .unwrap(); +/// assert!(uri.to_string().starts_with("bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?")); +/// ``` +#[derive(Debug, Clone, Default)] +#[must_use = "a UriBuilder builds nothing until `.build()` is called"] +pub struct UriBuilder { + body: Option, + entries: Vec, +} + +impl UriBuilder { + /// A builder for a URI with no body and no parameters. + pub fn new() -> Self { + Self::default() + } + + /// Sets the body address (the part before the `?`), replacing any + /// previously set one. + pub fn address(mut self, address: bitcoin::Address) -> Self { + self.body = Some(address); + self + } + + /// Sets the `amount` parameter, formatted in BTC, replacing any previous + /// one. + pub fn amount(mut self, amount: bitcoin::Amount) -> Self { + let value = amount.to_string_in(bitcoin::amount::Denomination::Bitcoin); + self.set_unique("amount", value); + self + } + + /// Sets the `label` parameter, percent-encoding the value and replacing + /// any previous one. + pub fn label(mut self, label: &str) -> Self { + self.set_unique("label", encode(label)); + self + } + + /// Sets the `message` parameter, percent-encoding the value and + /// replacing any previous one. + pub fn message(mut self, message: &str) -> Self { + self.set_unique("message", encode(message)); + self + } + + /// Appends an extension parameter, percent-encoding the value. + /// + /// Use this for any key this crate has no typed setter for - a payment + /// key such as `bc`, `tb`, `bcrt`, `lightning`, or `sp`, or any other + /// extension. A `bc`/`tb`/`bcrt` value must be a segwit address of the + /// network its key names, which [`build`](Self::build) checks, so the + /// built URI parses back. The value is treated as decoded text and + /// encoded for you. The key is used as given. It must be non-empty, not a + /// bare `req-`, and made of RFC 3986 query characters other than `&` and + /// `=`, with valid `%` escapes. + pub fn param(mut self, key: &str, value: &str) -> Self { + self.push(key, encode(value)); + self + } + + /// Appends an arbitrary parameter whose value is already percent-encoded. + /// + /// The value is written verbatim, so the caller owns its encoding, and + /// [`build`](Self::build) rejects it unless it is made of RFC 3986 query + /// characters other than `&` and `=`, with valid `%` escapes. An empty + /// string produces a `key=` parameter with an empty value, not a + /// value-less `key`. + pub fn raw_param(mut self, key: &str, raw_value: &str) -> Self { + self.push(key, raw_value.to_string()); + self + } + + /// Finishes building, or reports why the parts do not form a valid URI. + /// + /// Fails if a key is empty or a bare `req-`, if a key or raw value is not + /// made of RFC 3986 query characters other than `&` and `=` with valid `%` + /// escapes, if a non-repeatable parameter + /// (`amount`/`label`/`message`/`pop`) was set more than once, or if an + /// `amount` does not parse. + /// + /// A `bc`/`tb`/`bcrt` value must be a segwit address of the network its + /// key names, as when parsing. All of them must name the same network, + /// and the body must belong to it, so a built URI never mixes networks. + /// [`Uri::require_network`] gives a parsed one the same guarantee. A URI + /// with no HRP-keyed parameter takes the body's network as given. + pub fn build(self) -> Result { + for entry in &self.entries { + if !key_round_trips(&entry.key) { + return Err(BuildError::InvalidKey(entry.key.clone())); + } + if let Some(raw_value) = entry.raw_value.as_deref() { + if !raw_value_round_trips(raw_value) { + return Err(BuildError::InvalidRawValue { key: entry.key.clone() }); + } + } + } + + for &key in &NON_REPEATABLE_KEYS { + if self.entries.iter().filter(|entry| entry.base_key_eq(key)).count() > 1 { + return Err(BuildError::DuplicateParameter(key.to_string())); + } + } + + for entry in &self.entries { + if is_non_repeatable_base_key(&entry.key, "amount") { + let raw = entry.raw_value.as_deref().unwrap_or(""); + bitcoin::Amount::from_str_in(raw, bitcoin::amount::Denomination::Bitcoin) + .map_err(|_| BuildError::InvalidRawValue { key: entry.key.clone() })?; + } + } + + let mut network = None; + for entry in &self.entries { + let base_key = params::base_key(&entry.key); + if let Some(&(_, key_network)) = HRP_ADDRESS_KEYS.iter().find(|(hrp, _)| base_key.eq_ignore_ascii_case(hrp)) { + crate::validate_hrp_param(&entry.key, entry.raw_value.as_deref().unwrap_or(""), key_network) + .map_err(|_| BuildError::InvalidHrpValue { key: entry.key.clone() })?; + match network { + Some(network) if network != key_network => return Err(BuildError::Network(NetworkError::NetworkMismatch)), + _ => network = Some(key_network), + } + } + } + if let (Some(body), Some(network)) = (&self.body, network) { + if !body.as_unchecked().is_valid_for_network(network) { + return Err(BuildError::Network(NetworkError::NetworkMismatch)); + } + } + + let mut params = Params::new(); + for entry in self.entries { + params.push(entry); + } + Ok(Uri::from_checked_parts(self.body, params)) + } + + fn push(&mut self, key: &str, value: String) { + self.entries.push(ParamEntry { + key: key.to_string(), + raw_value: Some(value), + }); + } + + fn set_unique(&mut self, key: &str, value: String) { + match self.entries.iter_mut().find(|entry| entry.key.eq_ignore_ascii_case(key)) { + Some(entry) => entry.raw_value = Some(value), + None => self.push(key, value), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::AccessError; + + const LEGACY_MAINNET: &str = "1andreas3batLhQa2FawWjeyjCqyBzypd"; + const BECH32_MAINNET: &str = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"; + const BECH32_TESTNET: &str = "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx"; + + fn mainnet_body() -> bitcoin::Address { + LEGACY_MAINNET.parse::>().unwrap().assume_checked() + } + + #[test] + fn an_empty_builder_produces_the_bare_scheme() { + let uri = UriBuilder::new().build().unwrap(); + assert_eq!(uri.to_string(), "bitcoin:"); + assert!(uri.body().is_none()); + assert!(uri.params().is_empty()); + } + + #[test] + fn a_built_uri_has_no_source_string() { + let uri = UriBuilder::new().address(mainnet_body()).build().unwrap(); + assert!(uri.source_str().is_none()); + } + + #[test] + fn the_typed_setters_land_as_their_parameters() { + let uri = UriBuilder::new() + .address(mainnet_body()) + .amount(bitcoin::Amount::from_sat(20_300_000)) + .label("Luke-Jr") + .message("Donation") + .build() + .unwrap(); + assert_eq!(uri.body().unwrap().to_string(), LEGACY_MAINNET); + assert_eq!(uri.amount().unwrap(), bitcoin::Amount::from_sat(20_300_000)); + assert_eq!(uri.label().unwrap().unwrap(), "Luke-Jr"); + assert_eq!(uri.message().unwrap().unwrap(), "Donation"); + } + + #[test] + fn a_value_is_percent_encoded_but_raw_value_is_not() { + let uri = UriBuilder::new().param("x", "a b&c").raw_param("y", "a%20b").build().unwrap(); + assert_eq!(uri.get("x").unwrap().raw_value.as_deref(), Some("a%20b%26c")); + assert_eq!(uri.get("y").unwrap().raw_value.as_deref(), Some("a%20b")); + } + + #[test] + fn a_literal_plus_is_encoded_as_percent_2b() { + let uri = UriBuilder::new().param("pj", "https://ex.com/?x=a+b").build().unwrap(); + let raw = uri.get("pj").unwrap().raw_value.as_deref().unwrap(); + assert!(raw.contains("%2B"), "expected + to encode as %2B, got {}", raw); + assert!(!raw.contains('+'), "no literal + should remain, got {}", raw); + } + + #[test] + fn setting_a_unique_key_twice_keeps_the_last_value() { + let uri = UriBuilder::new().label("first").label("second").build().unwrap(); + assert_eq!(uri.get_all("label").count(), 1); + assert_eq!(uri.label().unwrap().unwrap(), "second"); + } + + #[test] + fn a_duplicate_non_repeatable_key_via_raw_param_fails_to_build() { + let result = UriBuilder::new().label("ok").raw_param("label", "again").build(); + assert!(matches!(result, Err(BuildError::DuplicateParameter(ref key)) if key == "label")); + } + + #[test] + fn a_duplicate_required_non_repeatable_key_fails_to_build() { + let result = UriBuilder::new().label("ok").raw_param("req-label", "again").build(); + assert!(matches!(result, Err(BuildError::DuplicateParameter(ref key)) if key == "label")); + } + + #[test] + fn ambiguous_keys_fail_to_build() { + let result = UriBuilder::new().param("a&b", "x").build(); + assert!(matches!(result, Err(BuildError::InvalidKey(ref key)) if key == "a&b")); + + let result = UriBuilder::new().param("a=b", "x").build(); + assert!(matches!(result, Err(BuildError::InvalidKey(ref key)) if key == "a=b")); + } + + #[test] + fn raw_values_that_would_not_round_trip_fail_to_build() { + let result = UriBuilder::new().raw_param("x", "a&b").build(); + assert!(matches!(result, Err(BuildError::InvalidRawValue { ref key }) if key == "x")); + + let result = UriBuilder::new().raw_param("x", "%zz").build(); + assert!(matches!(result, Err(BuildError::InvalidRawValue { ref key }) if key == "x")); + } + + #[test] + fn a_manually_added_invalid_amount_fails_to_build() { + let result = UriBuilder::new().raw_param("amount", "not-an-amount").build(); + assert!(matches!(result, Err(BuildError::InvalidRawValue { ref key }) if key == "amount")); + } + + #[test] + fn an_hrp_param_lands_under_its_key() { + let uri = UriBuilder::new().param("bc", BECH32_MAINNET).build().unwrap(); + assert_eq!(uri.get("bc").unwrap().raw_value.as_deref(), Some(BECH32_MAINNET)); + } + + #[test] + fn mixed_networks_fail_to_build() { + // A checked URI never mixes networks: `bc=` (mainnet) and `tb=` + // (testnet) cannot both belong to one network, so the build fails. + let result = UriBuilder::new().param("bc", BECH32_MAINNET).param("tb", BECH32_TESTNET).build(); + assert!(matches!(result, Err(BuildError::Network(_)))); + } + + fn address_on(address: &str, network: bitcoin::Network) -> bitcoin::Address { + let script = address.parse::>().unwrap().assume_checked().script_pubkey(); + bitcoin::Address::from_script(&script, network).unwrap() + } + + #[test] + fn an_hrp_value_must_be_a_segwit_address_of_its_keys_network() { + let regtest = address_on(BECH32_MAINNET, bitcoin::Network::Regtest).to_string(); + let testnet_base58 = address_on(LEGACY_MAINNET, bitcoin::Network::Testnet).to_string(); + for (key, value) in [ + // BIP 321's own invalid example: a testnet address under the `bc` key. + ("bc", BECH32_TESTNET), + ("tb", BECH32_MAINNET), + ("bc", LEGACY_MAINNET), + ("tb", testnet_base58.as_str()), + ("tb", regtest.as_str()), + ("bcrt", BECH32_TESTNET), + ("req-bc", BECH32_TESTNET), + ] { + let result = UriBuilder::new().param(key, value).build(); + assert!( + matches!(result, Err(BuildError::InvalidHrpValue { key: ref reported }) if reported == key), + "{}={} should fail with InvalidHrpValue, got {:?}", + key, + value, + result + ); + } + } + + #[test] + fn several_hrp_params_on_one_network_build() { + // BIP 321's example of one segwit v0 and one taproot address under `bc`. + let taproot = "bc1p5swkugezn97763tl0yty6556856uug0q6jflljvep9m4p7339x5qzyrh4g"; + let built = UriBuilder::new().param("bc", BECH32_MAINNET).param("req-BC", taproot).build().unwrap(); + assert_eq!(built.get_all("bc").count(), 2); + } + + #[test] + fn the_body_must_belong_to_the_network_the_hrp_keys_name() { + let regtest = address_on(BECH32_MAINNET, bitcoin::Network::Regtest); + let testnet = address_on(BECH32_MAINNET, bitcoin::Network::Testnet); + let ok = [ + (mainnet_body(), "bc", BECH32_MAINNET.to_string()), + (testnet.clone(), "tb", BECH32_TESTNET.to_string()), + (regtest.clone(), "bcrt", regtest.to_string()), + // A base58 test address is valid on every test network. + (address_on(LEGACY_MAINNET, bitcoin::Network::Testnet), "bcrt", regtest.to_string()), + ]; + for (body, key, value) in ok { + let built = UriBuilder::new().address(body).param(key, &value).build(); + assert!(built.is_ok(), "{}={} should build: {:?}", key, value, built); + } + let mismatched = [ + (mainnet_body(), "tb", BECH32_TESTNET.to_string()), + (testnet.clone(), "bc", BECH32_MAINNET.to_string()), + (testnet, "bcrt", regtest.to_string()), + (regtest, "tb", BECH32_TESTNET.to_string()), + ]; + for (body, key, value) in mismatched { + let built = UriBuilder::new().address(body).param(key, &value).build(); + assert!( + matches!(built, Err(BuildError::Network(_))), + "{}={} should not build: {:?}", + key, + value, + built + ); + } + } + + #[test] + fn a_body_with_no_hrp_params_builds_on_any_network() { + for network in [bitcoin::Network::Bitcoin, bitcoin::Network::Testnet, bitcoin::Network::Regtest] { + let body = address_on(BECH32_MAINNET, network); + let built = UriBuilder::new().address(body).build().unwrap(); + assert!(Uri::parse(&built.to_string()).unwrap().require_network(network).is_ok()); + } + } + + #[test] + fn keys_and_raw_values_must_be_qchars() { + for key in ["", "req-", "k e y", "ké", "%zz", "a\nb", "a#b", "a\"b", "a = built.params().iter().map(|e| (e.key.clone(), e.raw_value.clone())).collect(); + let reparsed_params: Vec<_> = reparsed.params().iter().map(|e| (e.key.clone(), e.raw_value.clone())).collect(); + assert_eq!(built_params, reparsed_params); + + assert_eq!(built.to_string(), reparsed.to_string()); + } + + #[test] + fn a_label_value_needing_encoding_round_trips_through_display_and_parse() { + let built = UriBuilder::new().address(mainnet_body()).label("Coffee & Pie").build().unwrap(); + let reparsed = Uri::parse(&built.to_string()) + .unwrap() + .require_network(bitcoin::Network::Bitcoin) + .unwrap(); + // The '&' was encoded, so it did not split into a second parameter. + assert_eq!(reparsed.params().len(), 1); + assert_eq!(reparsed.label().unwrap().unwrap(), "Coffee & Pie"); + } + + #[test] + fn an_extension_value_survives_round_trip_verbatim() { + // The builder encodes `a+b c` to `a%2Bb%20c`; parsing keeps it encoded, + // and `decoded_value` recovers the original on demand. + let built = UriBuilder::new().param("lightning", "a+b c").build().unwrap(); + let reparsed = Uri::parse(&built.to_string()) + .unwrap() + .require_network(bitcoin::Network::Bitcoin) + .unwrap(); + let entry = reparsed.get("lightning").unwrap(); + assert_eq!(entry.raw_value.as_deref(), Some("a%2Bb%20c")); + assert_eq!(entry.decoded_value().unwrap().unwrap(), "a+b c"); + } + + #[test] + fn build_error_display_messages_are_distinct_and_mention_the_key() { + let duplicate = BuildError::DuplicateParameter("label".to_string()).to_string(); + let invalid = BuildError::InvalidHrpValue { key: "bc".to_string() }.to_string(); + assert!(duplicate.contains("label")); + assert!(invalid.contains("bc")); + assert_ne!(duplicate, invalid); + } + + #[test] + fn a_param_value_that_is_not_utf8_once_decoded_is_an_access_error_not_a_build_error() { + // raw_param passes bytes through; %ff is valid percent-encoding but + // not UTF-8, so building succeeds and the failure only shows up when + // something tries to decode it as text. + let uri = UriBuilder::new().raw_param("label", "%ff").build().unwrap(); + assert!(matches!(uri.label(), Some(Err(AccessError::NotUtf8)))); + } + + #[test] + fn build_network_checks_req_prefixed_hrp_params() { + // `req-bc` must be network-checked like `bc`: a testnet value fails to + // build rather than slipping through because of the `req-` prefix. + let result = UriBuilder::new() + .raw_param("req-bc", "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx") + .build(); + assert!(result.is_err()); + } +} diff --git a/src/de.rs b/src/de.rs deleted file mode 100644 index 9a44b77..0000000 --- a/src/de.rs +++ /dev/null @@ -1,371 +0,0 @@ -//! Types and traits related to deserialization (parsing) of BIP21 -//! -//! This module provides mainly the infrastructure required to parse extra BIP21 arguments. -//! It's inspired by `serde` with main differences being handling of `req-` arguments and -//! simplicity. -//! -//! Check [`DeserializeParams`] to get started. - -use alloc::borrow::ToOwned; -use alloc::borrow::Cow; -use alloc::string::String; -use core::convert::{TryFrom, TryInto}; -use bitcoin::amount::{Denomination, ParseAmountError}; -use bitcoin::address::ParseError as AddressError; -use bitcoin::address::NetworkValidation; -use core::fmt; -use super::{Uri, Param}; -use percent_encoding_rfc3986::PercentDecodeError; - -impl<'a, T: DeserializeParams<'a>> Uri<'a, bitcoin::address::NetworkUnchecked, T> { - /// Implements deserialization. - fn deserialize_raw(string: &'a str) -> Result> { - const SCHEME: &str = "bitcoin:"; - if string.len() < SCHEME.len() { - return Err(Error::Uri(UriError(UriErrorInner::TooShort))); - } - - if !string.get(..SCHEME.len()).is_some_and(|s| s.eq_ignore_ascii_case(SCHEME)) { - return Err(Error::Uri(UriError(UriErrorInner::InvalidScheme))); - } - - let string = &string[SCHEME.len()..]; - - let (address, params) = match string.find('?') { - Some(pos) => (&string[..pos], Some(&string[(pos + 1)..])), - None => (string, None), - }; - - let address = address.parse().map_err(Error::uri)?; - let mut deserializer = T::DeserializationState::default(); - let mut amount = None; - let mut label = None; - let mut message = None; - if let Some(params) = params { - // [RFC 3986 § 3.4](https://www.rfc-editor.org/rfc/rfc3986#section-3.4): - // - // > The query component is indicated by the first question - // > mark ("?") character and terminated by a number sign ("#") character - // > or by the end of the URI. - let params = match params.find('#') { - Some(pos) => ¶ms[..pos], - None => params, - }; - - for param in params.split('&') { - let pos = param - .find('=') - .ok_or_else(|| Error::Uri(UriError(UriErrorInner::MissingEquals(param.to_owned()))))?; - let key = ¶m[..pos]; - let value = ¶m[(pos + 1)..]; - match key { - "amount" => { - if amount.is_some() { - return Err(Error::Uri(UriError(UriErrorInner::DuplicateParameter(key.to_owned())))); - } - let parsed_amount = bitcoin::Amount::from_str_in(value, Denomination::Bitcoin).map_err(Error::uri)?; - amount = Some(parsed_amount); - }, - "label" => { - if label.is_some() { - return Err(Error::Uri(UriError(UriErrorInner::DuplicateParameter(key.to_owned())))); - } - let label_decoder = Param::decode(value).map_err(Error::percent_decode_static("label"))?; - label = Some(label_decoder); - }, - "message" => { - if message.is_some() { - return Err(Error::Uri(UriError(UriErrorInner::DuplicateParameter(key.to_owned())))); - } - let message_decoder = Param::decode(value).map_err(Error::percent_decode_static("message"))?; - message = Some(message_decoder); - }, - extra_key => { - let decoder = Param::decode(value).map_err(Error::percent_decode(key))?; - let is_known = deserializer.deserialize_borrowed(extra_key, decoder).map_err(Error::Extras)?; - if is_known == ParamKind::Unknown && extra_key.starts_with("req-") { - return Err(Error::Uri(UriError(UriErrorInner::UnknownRequiredParameter(extra_key.to_owned())))); - } - }, - } - } - } - let extras = deserializer.finalize().map_err(Error::Extras)?; - - Ok(Uri { - address, - amount, - label, - message, - extras, - }) - } -} - -impl Uri<'_, NetVal, T> { - /// Makes the lifetime `'static` by converting all fields to owned. - /// - /// Note that this does **not** affect `extras`! - fn into_static(self) -> Uri<'static, NetVal, T> { - Uri { - address: self.address, - amount: self.amount, - label: self.label.map(|label| label.decode_into_owned()), - message: self.message.map(|message| message.decode_into_owned()), - extras: self.extras, - } - } -} - -/// Indicates whether a parameter with this name is known. -/// -/// This is a semantically clear version of `bool` that also contains `#[must_use]` -#[must_use = "param kind MUST be checked because URI with unknown req- param MUST be rejected"] -#[derive(Copy, Clone, Eq, PartialEq, Hash)] -pub enum ParamKind { - /// Signals that this parameter is known to the type being deserialized. - Known, - - /// Signals that this parameter is **not** known to the type being deserialized. - /// - /// Parsing error will be reported if this is returned from `req-` parameter as mandated by - /// BIP21. - Unknown, -} - -/// Defines error type of deserialization. -/// -/// This is a separate trait to ensure the error is same for all lifetimes. -pub trait DeserializationError { - /// The error returned when deserialization fails. - type Error; -} - -/// Represents the state of deserialization of extras. -pub trait DeserializationState<'de>: Default { - /// Value returned when deserialization finishes. - type Value: DeserializationError; - - /// Returns `true` if the parameter is known. - /// - /// Required parameters include the `req-` prefix. - fn is_param_known(&self, key: &str) -> bool; - - /// Deserializes a temporary. - /// - /// This can not borrow the key nor value, so has to clone them or throw away. - /// Required parameters include the `req-` prefix. - fn deserialize_temp(&mut self, key: &str, value: Param<'_>) -> Result::Error>; - - /// Deserializes a borrowed value possibly avoiding cloning. - /// - /// Implementing this can enable zero-copy deserialization. - /// Required parameters include the `req-` prefix. - /// - /// The default implementation forwards to `deserialize_temp` - fn deserialize_borrowed(&mut self, key: &'de str, value: Param<'de>) -> Result::Error> { - self.deserialize_temp(key, value) - } - - /// Signals that all parameters were processed. - /// - /// This function may perform additional validation - e.g. checking if some mandatory fields are missing. - fn finalize(self) -> Result::Error>; -} - -/// Represents a value that can be deserialized. -/// -/// All values passed in `Extras` type parameter of [`Uri`] must implement this trait to allow -/// deserialization. -pub trait DeserializeParams<'de>: Sized + DeserializationError { - /// State used when deserializing. - type DeserializationState: DeserializationState<'de, Value = Self>; -} - -/// Error returned when parsing URI. -#[derive(Clone, Debug)] -pub enum Error { - /// Parsing of BIP21 URI failed. - /// - /// This reports failures related to BIP21 requirements including parse error for address. - Uri(UriError), - /// Parsing of extras failed. - /// - /// This only directly forwards parsing error from extras. - Extras(T), -} - -impl Error { - fn uri>(error: U) -> Self { - Error::Uri(UriError(error.into())) - } - - fn percent_decode_static(parameter: &'static str) -> impl FnOnce(PercentDecodeError) -> Self { - move |error| { - Self::uri(UriErrorInner::PercentDecode { - parameter: Cow::Borrowed(parameter), - error, - }) - } - } - - fn percent_decode(parameter: &str) -> impl '_ + FnOnce(PercentDecodeError) -> Self { - move |error| { - Self::uri(UriErrorInner::PercentDecode { - parameter: parameter.to_owned().into(), - error, - }) - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - Error::Uri(_) => write!(f, "invalid BIP21 URI"), - Error::Extras(_) => write!(f, "failed to parse extra argument(s)"), - } - } -} - -#[cfg(feature = "std")] -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Error::Uri(error) => Some(error), - Error::Extras(error) => Some(error), - } - } -} - -/// Error returned when parsing non-extras parts of URI. -#[derive(Debug, Clone)] -pub struct UriError(UriErrorInner); - -#[derive(Debug, Clone)] -#[cfg_attr(not(feature = "std"), allow(dead_code))] -enum UriErrorInner { - TooShort, - InvalidScheme, - Address(AddressError), - Amount(ParseAmountError), - DuplicateParameter(String), - UnknownRequiredParameter(String), - PercentDecode { - parameter: Cow<'static, str>, - error: PercentDecodeError, - }, - MissingEquals(String), -} - -impl From for UriErrorInner { - fn from(value: AddressError) -> Self { - UriErrorInner::Address(value) - } -} - -impl From for UriErrorInner { - fn from(value: ParseAmountError) -> Self { - UriErrorInner::Amount(value) - } -} - -impl fmt::Display for UriError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match &self.0 { - UriErrorInner::TooShort => write!(f, "the URI is too short"), - UriErrorInner::InvalidScheme => write!(f, "the URI has invalid scheme"), - UriErrorInner::Address(_) => write!(f, "the address is invalid"), - UriErrorInner::Amount(_) => write!(f, "the amount is invalid"), - UriErrorInner::DuplicateParameter(parameter) => write!(f, "the URI contains a duplicate parameter '{}'", parameter), - UriErrorInner::UnknownRequiredParameter(parameter) => write!(f, "the URI contains unknown required parameter '{}'", parameter), - #[cfg(feature = "std")] - UriErrorInner::PercentDecode { parameter, error: _ } => write!(f, "can not percent-decode parameter {}", parameter), - #[cfg(not(feature = "std"))] - UriErrorInner::PercentDecode { parameter, error } => write!(f, "can not percent-decode parameter {}: {}", parameter, error), - UriErrorInner::MissingEquals(parameter) => write!(f, "the parameter '{}' is missing a value", parameter), - } - } -} - -#[cfg(feature = "std")] -#[cfg_attr(docsrs, doc(cfg(feature = "std")))] -impl std::error::Error for UriError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match &self.0 { - UriErrorInner::TooShort => None, - UriErrorInner::InvalidScheme => None, - UriErrorInner::Address(error) => Some(error), - UriErrorInner::Amount(error) => Some(error), - UriErrorInner::DuplicateParameter(_) => None, - UriErrorInner::UnknownRequiredParameter(_) => None, - UriErrorInner::PercentDecode { parameter: _, error } => Some(error), - UriErrorInner::MissingEquals(_) => None, - } - } -} - -/// **Warning**: this implementation may needlessly allocate, consider using `TryFrom<&str>` instead. -impl DeserializeParams<'de>> core::str::FromStr for Uri<'_, bitcoin::address::NetworkUnchecked, T> { - type Err = Error; - - fn from_str(s: &str) -> Result { - Uri::deserialize_raw(s).map(Uri::into_static) - } -} - -impl<'a, T: DeserializeParams<'a>> TryFrom<&'a str> for Uri<'a, bitcoin::address::NetworkUnchecked, T> { - type Error = Error; - - fn try_from(s: &'a str) -> Result { - Self::deserialize_raw(s) - } -} - -/// **Warning**: this implementation may needlessly allocate, consider using `TryFrom<&str>` instead. -impl DeserializeParams<'de>> TryFrom for Uri<'_, bitcoin::address::NetworkUnchecked, T> { - type Error = Error; - - fn try_from(s: String) -> Result { - s.parse() - } -} - -/// **Warning**: this implementation may needlessly allocate, consider using `TryFrom<&str>` instead. -impl<'a, T: for<'de> DeserializeParams<'de>> TryFrom> for Uri<'a, bitcoin::address::NetworkUnchecked, T> { - type Error = Error; - - fn try_from(s: Cow<'a, str>) -> Result { - match s { - Cow::Borrowed(s) => s.try_into(), - Cow::Owned(s) => s.parse(), - } - } -} - -impl<'a, T: DeserializeParams<'a>> Uri<'a, bitcoin::address::NetworkUnchecked, T> { - /// Checks whether network of this address is as required. - /// - /// For details about this mechanism, see section [*parsing addresses*](bitcoin::Address#parsing-addresses) on [`bitcoin::Address`]. - pub fn require_network(self, network: bitcoin::Network) -> Result, Error> { - let address = self.address.require_network(network).map_err(Error::uri)?; - Ok(Uri { - address, - amount: self.amount, - label: self.label, - message: self.message, - extras: self.extras, - }) - } - - /// Marks URI validated without checks. - pub fn assume_checked(self) -> Uri<'a, bitcoin::address::NetworkChecked, T> { - Uri { - address: self.address.assume_checked(), - amount: self.amount, - label: self.label, - message: self.message, - extras: self.extras, - } - } -} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..23f2c4b --- /dev/null +++ b/src/error.rs @@ -0,0 +1,188 @@ +//! The crate's error types. +//! +//! A parse [`Error`] means there is no `Uri`. A value whose percent-decoded +//! bytes are not UTF-8 is an [`AccessError`] from whichever accessor reads +//! it, not a parse error. + +use alloc::borrow::ToOwned; +use alloc::string::String; +use core::fmt; +use percent_encoding_rfc3986::PercentDecodeError; + +/// Why parsing a `bitcoin:` URI into a [`crate::Uri`] failed. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub enum Error { + /// The string does not start with the `bitcoin:` scheme + /// (case-insensitively). + InvalidScheme, + /// The body address (before the `?`) failed to parse. + InvalidBodyAddress(bitcoin::address::ParseError), + /// A `bc`, `tb` or `bcrt` parameter's value is not a segwit address of + /// the network its key names. + InvalidHrpValue { + /// The parameter key as it appeared, e.g. `"req-bc"`. + key: String, + }, + /// The `amount` parameter failed to parse. + InvalidAmount(bitcoin::amount::ParseAmountError), + /// A `label`, `message`, `pop`, or `amount` parameter appeared more than + /// once. BIP 321 forbids repeating any of these four. + DuplicateParameter(String), + /// A percent-encoded parameter value contained invalid percent-encoding. + InvalidPercentEncoding { + /// The parameter key whose value failed to decode. + key: String, + /// The underlying decode failure. + error: PercentDecodeError, + }, +} + +impl Error { + pub(crate) fn percent_decode(key: &str) -> impl '_ + FnOnce(PercentDecodeError) -> Self { + move |error| Error::InvalidPercentEncoding { key: key.to_owned(), error } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::InvalidScheme => write!(f, "the URI has an invalid scheme"), + Error::InvalidBodyAddress(_) => write!(f, "the URI contains an invalid address"), + Error::InvalidHrpValue { key } => { + write!(f, "the '{}' parameter's value is not a segwit address for its network", key) + }, + Error::InvalidAmount(_) => write!(f, "the amount parameter is invalid"), + Error::DuplicateParameter(key) => write!(f, "the URI contains a duplicate '{}' parameter", key), + Error::InvalidPercentEncoding { key, .. } => write!(f, "can not percent-decode parameter '{}'", key), + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::InvalidScheme => None, + Error::InvalidBodyAddress(error) => Some(error), + Error::InvalidHrpValue { .. } => None, + Error::InvalidAmount(error) => Some(error), + Error::DuplicateParameter(_) => None, + Error::InvalidPercentEncoding { error, .. } => Some(error), + } + } +} + +/// Why network validation failed after parsing. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub enum NetworkError { + /// [`crate::Uri::require_network`] found the body address, or a + /// `bc=`/`tb=`/`bcrt=` parameter, that does not belong to the requested + /// network. + NetworkMismatch, +} + +impl fmt::Display for NetworkError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + NetworkError::NetworkMismatch => write!(f, "the URI is not valid for the requested network"), + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for NetworkError {} + +/// Why decoding an already-parsed parameter's value failed. +/// +/// This is distinct from [`Error`]: the parameter itself parsed fine (it is +/// right there in [`crate::Uri::params`]), it is only the typed, decoded +/// view of it - [`crate::Uri::label`], [`crate::Uri::message`], +/// [`crate::Uri::pop`] - that failed. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub enum AccessError { + /// The value's percent-encoding was invalid. Parsing already rejects + /// such a value, so only a hand-built [`crate::ParamEntry`] gets here. + PercentDecode(PercentDecodeError), + /// The value decoded to bytes that are not valid UTF-8. + NotUtf8, +} + +impl fmt::Display for AccessError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + AccessError::PercentDecode(_) => write!(f, "invalid percent-encoding"), + AccessError::NotUtf8 => write!(f, "value is not valid UTF-8"), + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for AccessError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + AccessError::PercentDecode(error) => Some(error), + AccessError::NotUtf8 => None, + } + } +} + +/// Why [`crate::UriBuilder::build`] could not produce a valid URI. +/// +/// Distinct from [`Error`], which is about parsing a string: these are the +/// ways a `Uri` assembled from typed parts can still be ill-formed. +#[derive(Debug, Clone)] +#[non_exhaustive] +pub enum BuildError { + /// A parameter key is empty, is a bare `req-`, is not made of RFC 3986 + /// query characters other than `&` and `=`, or has an invalid `%` escape. + InvalidKey(String), + /// A raw parameter value is not made of RFC 3986 query characters other + /// than `&` and `=`, or has an invalid `%` escape. + InvalidRawValue { + /// The parameter key whose raw value is invalid. + key: String, + }, + /// A parameter BIP 321 forbids from repeating (`amount`, `label`, + /// `message`, or `pop`) was added more than once - typically by also + /// setting it through [`crate::UriBuilder::param`] or + /// [`crate::UriBuilder::raw_param`]. + DuplicateParameter(String), + /// A `bc`, `tb` or `bcrt` parameter's value is not a segwit address of the + /// network its key names, so the built URI would not parse back. + InvalidHrpValue { + /// The HRP parameter key, e.g. `"bc"`. + key: String, + }, + /// The HRP-keyed parameters name different networks, or the body does not + /// belong to the network they name. A checked URI never mixes networks. + Network(NetworkError), +} + +impl fmt::Display for BuildError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BuildError::InvalidKey(key) => write!(f, "the '{}' parameter key is invalid", key), + BuildError::InvalidRawValue { key } => write!(f, "the '{}' parameter's raw value is invalid", key), + BuildError::DuplicateParameter(key) => { + write!(f, "the '{}' parameter was set more than once", key) + }, + BuildError::InvalidHrpValue { key } => { + write!(f, "the '{}' parameter's value is not a valid address for its network", key) + }, + BuildError::Network(error) => write!(f, "{}", error), + } + } +} + +#[cfg(feature = "std")] +impl std::error::Error for BuildError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + BuildError::Network(error) => Some(error), + _ => None, + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 7a37b7e..adc1520 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,35 +1,20 @@ //! Rust-idiomatic, compliant, flexible and performant bitcoin URI crate. //! -//! **Important:** while lot of work went into polishing the crate it's still considered -//! early-development! -//! -//! * Rust-idiomatic: uses strong types, standard traits and other things -//! * Compliant: implements all requirements of BIP21, including protections to not forget about -//! `req-`. (But see features.) -//! * Flexible: enables parsing/serializing additional arguments not defined by BIP21 -//! * Performant: uses zero-copy deserialization and lazy evaluation wherever possible. -//! -//! Serialization and deserialization is inspired by `serde` with these important differences: -//! -//! * Deserialization signals if the field is known so that `req-` fields can be rejected. -//! * Much simpler API - we don't need all the features. -//! * Use of [`Param<'a>`] to enable lazy evaluation. +//! * Rust-idiomatic: owned types, no lifetime parameter. +//! * Compliant: parses the full BIP 321 shape, including a body-less URI. +//! * Flexible: an extension reads whatever params it needs straight off the +//! parsed [`Uri`]; this crate never needs to know what they mean. +//! * Performant: values stay percent-encoded until something decodes them. //! //! The crate is `no_std` but does require `alloc`. //! //! ## Features //! //! * `std` enables integration with `std` - mainly `std::error::Error`. -//! * `non-compliant-bytes` - enables use of non-compliant API that can parse non-UTF-8 URI values. -//! -//! ## Stabilization roadmap -//! -//! The crate can not (and will not) be stabilized until either [`bitcoin`] is stabilized or -//! [`bitcoin::Address`] and [`bitcoin::Amount`] are moved to (a) separate stable crate(s). //! //! ## MSRV //! -//! 1.56.1 +//! 1.63 #![cfg_attr(docsrs, feature(doc_cfg))] #![no_std] @@ -41,466 +26,949 @@ extern crate std; extern crate alloc; -pub mod de; -pub mod ser; +mod builder; +mod error; +mod params; use alloc::borrow::ToOwned; -use alloc::borrow::Cow; -#[cfg(feature = "non-compliant-bytes")] -use alloc::vec::Vec; use alloc::string::String; -use percent_encoding_rfc3986::{PercentDecode, PercentDecodeError}; -#[cfg(feature = "non-compliant-bytes")] -use either::Either; -use core::convert::{TryFrom, TryInto}; -use bitcoin::address::NetworkValidation; +use alloc::vec::Vec; +use core::fmt; -pub use de::{DeserializeParams, DeserializationState, DeserializationError}; -pub use ser::SerializeParams; +use bitcoin::address::NetworkValidation; +pub use builder::UriBuilder; +pub use error::{AccessError, BuildError, Error, NetworkError}; +pub use params::{ParamEntry, Params}; -/// Parsed BIP21 URI. +/// A parsed `bitcoin:` URI. /// -/// This struct represents all fields of BIP21 URI with the ability to add more extra fields using -/// the `extras` field. By default there are no extra fields so an empty implementation is used. +/// Owned, with no lifetime parameter: every value a [`Uri`] hands back is +/// either copied out of the source string or borrowed from `self`. Query +/// parameters stay percent-encoded and in their original key case in +/// [`Uri::params`] until a typed accessor ([`Uri::label`], [`Uri::amount`], +/// ...) or [`Uri::get`]/[`Uri::get_all`] decodes the ones it needs. /// /// ## Parsing /// -/// `Uri` implements `FromStr` so you can simply use `s.parse::>()`. However that is -/// not zero-copy. If you wish to use zero-copy parsing call `try_into()` instead. +/// `Uri` implements `FromStr` and `TryFrom<&str>` (equivalent to one +/// another - there is no borrowed/zero-copy parse path in this owned +/// design), producing a [`bitcoin::address::NetworkUnchecked`] `Uri`. Call +/// [`Uri::require_network`] or [`Uri::assume_checked`] to get a +/// `Uri`. /// /// ## Displaying /// -/// `Display` is implemented for `Uri` so you can format it naturally. However it currently does -/// **not** support alignment. -/// -/// The code does _not_ assume strict BIP-21, so it displays the schema lower case -/// instead as upper case. -/// This makes it compatible with some (buggy) wallets but does not create the most optimal QR codes. -/// -/// [See compatibility table.](https://github.com/btcpayserver/btcpayserver/issues/2110) -#[non_exhaustive] +/// `Display` with `{}` writes a parsed `Uri` back as exactly +/// the string it was parsed from, which [`Uri::source_str`] also returns. #[derive(Debug, Clone)] -pub struct Uri<'a, NetVal = bitcoin::address::NetworkChecked, Extras = NoExtras> +pub struct Uri where - NetVal: NetworkValidation, + V: NetworkValidation, { - /// The address provided in the URI. + body: Option>, + params: Params, + source: Option, +} + +/// Two `Uri`s are equal when their body and parameters are, regardless of +/// where each came from. `source` is excluded deliberately: a `Uri` parsed +/// from a string and one built from the same parts are the same URI, even +/// though only the former carries the original text. Everything `source` +/// affects - how `Display` writes a parsed URI, [`Uri::source_str`] - is observable through +/// the other fields or is explicitly a provenance detail, so leaving it out +/// keeps equality meaning "the same URI" rather than "parsed from the same +/// bytes". +impl PartialEq for Uri +where + bitcoin::Address: PartialEq, +{ + fn eq(&self, other: &Self) -> bool { + self.body == other.body && self.params == other.params + } +} + +impl Eq for Uri where bitcoin::Address: Eq {} + +/// Query parameter keys this crate validates as an address with a +/// network-specific Human Readable Part, per BIP 321's +/// "New payment instructions using bech32 or bech32m encodings SHOULD reuse +/// their address format's Human Readable Part as the parameter key" rule. +/// +/// These are the segwit HRPs `bitcoin` knows. A value under one of these keys +/// must be a segwit address whose HRP is the key, so `bc=1...` (base58) and +/// `tb=bcrt1...` are rejected. Adding a key changes which URIs parse, so it is +/// a breaking change. Signet shares `tb` with testnet. +pub(crate) const HRP_ADDRESS_KEYS: [(&str, bitcoin::Network); 3] = [ + ("bc", bitcoin::Network::Bitcoin), + ("tb", bitcoin::Network::Testnet), + ("bcrt", bitcoin::Network::Regtest), +]; + +impl Uri { + /// Parses a `bitcoin:` URI per BIP 321. + /// + /// The body address (before the `?`) is optional - BIP 321 allows a + /// body-less URI such as `bitcoin:?sp=...` - and a query parameter may + /// be value-less (`?foo` rather than `?foo=`). `label`, `message`, + /// `pop`, and `amount` may not repeat. A `bc=`/`tb=`/`bcrt=` parameter's + /// value must be a segwit address of the network its key names. BIP 321's + /// invalid example `bitcoin:?bc=tb1...` fails this check. /// - /// This field is mandatory because the address is mandatory in BIP21. - pub address: bitcoin::Address, + /// This does not check the body address, or any HRP-keyed parameter, + /// against a *specific* network - that is [`Uri::require_network`]'s + /// job. A `tb1...` body address and a `bc=`-keyed mainnet address can + /// both parse out of the same URI; whether that combination is usable + /// is for the caller to decide once it knows which network it wants. + pub fn parse(s: &str) -> Result { + const SCHEME: &str = "bitcoin:"; + + if !s.get(..SCHEME.len()).map_or(false, |prefix| prefix.eq_ignore_ascii_case(SCHEME)) { + return Err(Error::InvalidScheme); + } + let rest = &s[SCHEME.len()..]; - /// Number of satoshis requested as payment. - pub amount: Option, + let (body_str, query) = match rest.find('?') { + Some(pos) => (&rest[..pos], Some(&rest[(pos + 1)..])), + None => (rest, None), + }; - /// The label of the address - e.g. name of the receiver. - pub label: Option>, + // BIP 321: the body is optional (`[ bitcoinaddress ]`). + let body = if body_str.is_empty() { + None + } else { + Some(body_str.parse::>().map_err(Error::InvalidBodyAddress)?) + }; - /// Message that describes the transaction to the user. - pub message: Option>, + let mut params = Params::new(); + if let Some(query) = query { + // RFC 3986 §3.4: the query ends at the first '#', if any. + let query = match query.find('#') { + Some(pos) => &query[..pos], + None => query, + }; + + for segment in query.split('&') { + // `bitcoinparam = [ ... ]`: an empty segment (e.g. a stray + // "&&") is a legal, empty parameter that contributes + // nothing. + if segment.is_empty() { + continue; + } + + let (key, raw_value) = match segment.find('=') { + // `otherparam = qchar *qchar [ "=" *qchar ]`: the value + // is optional, so a value-less param is legal. + Some(pos) => (&segment[..pos], Some(segment[(pos + 1)..].to_owned())), + None => (segment, None), + }; + + if let Some(raw) = raw_value.as_deref() { + validate_percent_encoding(key, raw)?; + } + + let base_key = params::base_key(key); + if params::NON_REPEATABLE_KEYS + .iter() + .any(|&non_repeatable| base_key.eq_ignore_ascii_case(non_repeatable)) + && params.get(base_key).is_some() + { + return Err(Error::DuplicateParameter(key.to_owned())); + } + + if base_key.eq_ignore_ascii_case("amount") { + let raw = raw_value.as_deref().unwrap_or(""); + bitcoin::Amount::from_str_in(raw, bitcoin::amount::Denomination::Bitcoin).map_err(Error::InvalidAmount)?; + } + + // Match the base key so a `req-` prefix cannot bypass the + // network check: `req-bc=tb1...` must still be rejected. + if let Some(&(_, network)) = HRP_ADDRESS_KEYS.iter().find(|(hrp, _)| base_key.eq_ignore_ascii_case(hrp)) { + validate_hrp_param(key, raw_value.as_deref().unwrap_or(""), network)?; + } + + params.push(ParamEntry { + key: key.to_owned(), + raw_value, + }); + } + } - /// Extra fields that can occur in a BIP21 URI. - pub extras: Extras, -} + Ok(Uri { + body, + params, + source: Some(s.to_owned()), + }) + } -impl Uri<'_, NetVal, T> { - /// Creates an URI with defaults. - /// - /// This sets all fields except `address` to default values. - /// They can be overwritten in subsequent assignments before displaying the URI. - pub fn new(address: bitcoin::Address) -> Self { - Uri { - address, - amount: None, - label: None, - message: None, - extras: Default::default(), + /// `true` if the body address, and every `bc=`/`tb=`/`bcrt=` parameter, belongs + /// to `network`. A URI with no body and no HRP-keyed address parameters + /// is valid for every network. + pub fn is_valid_for_network(&self, network: bitcoin::Network) -> bool { + if let Some(body) = &self.body { + if !body.is_valid_for_network(network) { + return false; + } } + + HRP_ADDRESS_KEYS.iter().all(|(hrp, _)| { + self.params.get_all(hrp).all(|entry| { + let raw = entry.raw_value.as_deref().unwrap_or(""); + match raw.parse::>().ok() { + Some(address) => address.is_valid_for_network(network), + None => false, + } + }) + }) } -} -impl Uri<'_, NetVal, T> { - /// Creates an URI with defaults. + /// Checks whether this `Uri` - its body address and every + /// `bc=`/`tb=`/`bcrt=` parameter - is valid for `network`, and if so, + /// marks it checked. /// - /// This sets all fields except `address` and `extras` to default values. - /// They can be overwritten in subsequent assignments before displaying the URI. - pub fn with_extras(address: bitcoin::Address, extras: T) -> Self { + /// For details about this mechanism, see section [*parsing + /// addresses*](bitcoin::Address#parsing-addresses) on + /// [`bitcoin::Address`]. + pub fn require_network(self, network: bitcoin::Network) -> Result, NetworkError> { + if !self.is_valid_for_network(network) { + return Err(NetworkError::NetworkMismatch); + } + Ok(self.assume_checked()) + } + + /// Marks this `Uri` validated without checking its network. + pub fn assume_checked(self) -> Uri { Uri { - address, - amount: None, - label: None, - message: None, - extras, + body: self.body.map(bitcoin::Address::assume_checked), + params: self.params, + source: self.source, } } } -/// Abstracted stringly parameter in the URI. -/// -/// This type abstracts the parameter that may be encoded allowing lazy decoding, possibly even -/// without allocation. -/// When constructing [`Uri`] to be displayed you may use `From` where `S` is one of various -/// stringly types. The conversion is always cheap. -#[derive(Debug, Clone)] -pub struct Param<'a>(ParamInner<'a>); - -impl<'a> Param<'a> { - /// Convenience constructor. - fn decode(s: &'a str) -> Result { - Ok(Param(ParamInner::EncodedBorrowed(percent_encoding_rfc3986::percent_decode_str(s)?))) - } - - /// Creates a byte iterator yielding decoded bytes. - #[cfg(feature = "non-compliant-bytes")] - #[cfg_attr(docsrs, doc(cfg(feature = "non-compliant-bytes")))] - pub fn bytes(&self) -> ParamBytes<'_> { - ParamBytes(match &self.0 { - ParamInner::EncodedBorrowed(decoder) => Either::Left(decoder.clone()), - ParamInner::UnencodedBytes(bytes) => Either::Right(bytes.iter().cloned()), - ParamInner::UnencodedString(string) => Either::Right(string.as_bytes().iter().cloned()), +impl core::str::FromStr for Uri { + type Err = Error; + + fn from_str(s: &str) -> Result { + Self::parse(s) + } +} + +impl<'a> core::convert::TryFrom<&'a str> for Uri { + type Error = Error; + + fn try_from(s: &'a str) -> Result { + Self::parse(s) + } +} + +impl Uri { + /// The body address (before the `?`), if the URI had one. BIP 321 makes + /// this optional, unlike BIP 21. + pub fn body(&self) -> Option<&bitcoin::Address> { + self.body.as_ref() + } + + /// The raw, ordered multimap of every query parameter. + pub fn params(&self) -> &Params { + &self.params + } + + /// The first parameter whose base key matches `key` case-insensitively. + /// + /// `req-foo` has base key `foo`, so `get("foo")` finds both `foo` and + /// `req-foo`; source order decides which entry is first. + pub fn get(&self, key: &str) -> Option<&ParamEntry> { + self.params.get(key) + } + + /// Every parameter whose base key matches `key` case-insensitively, in + /// source order. + pub fn get_all<'a>(&'a self, key: &'a str) -> impl Iterator + 'a { + self.params.get_all(key) + } + + /// The `req-` parameters this URI requires but the caller does not + /// understand, in source order. + /// + /// BIP 321 says a client MUST reject a URI carrying a `req-` parameter it + /// cannot handle. `understood` is the set of keys the caller does handle, + /// given without the `req-` prefix (`["pj", "sp"]`, not `["req-pj"]`) and + /// matched case-insensitively; every `req-` parameter whose stripped key + /// is absent from it is returned. An empty iterator means the URI is safe + /// to act on. + /// + /// This crate never enforces the rule itself - it only reports it - so a + /// `Uri` always parses regardless of its `req-` parameters, and the + /// caller decides what to do with any this returns. + #[must_use = "callers must reject a URI when this iterator is non-empty"] + pub fn unsatisfied_requirements<'a>(&'a self, understood: &'a [&str]) -> impl Iterator + 'a { + self.params.iter().filter(move |entry| match entry.requirement() { + Some(requirement) => !understood.iter().any(|key| key.eq_ignore_ascii_case(requirement)), + None => false, }) } - /// Converts the parameter into iterator yielding decoded bytes. - #[cfg(feature = "non-compliant-bytes")] - #[cfg_attr(docsrs, doc(cfg(feature = "non-compliant-bytes")))] - pub fn into_bytes(self) -> ParamBytesOwned<'a> { - ParamBytesOwned(match self.0 { - ParamInner::EncodedBorrowed(decoder) => Either::Left(decoder), - ParamInner::UnencodedBytes(Cow::Borrowed(bytes)) => Either::Right(Either::Left(bytes.iter().cloned())), - ParamInner::UnencodedBytes(Cow::Owned(bytes)) => Either::Right(Either::Right(bytes.into_iter())), - ParamInner::UnencodedString(Cow::Borrowed(string)) => Either::Right(Either::Left(string.as_bytes().iter().cloned())), - ParamInner::UnencodedString(Cow::Owned(string)) => Either::Right(Either::Right(Vec::from(string).into_iter())), + /// The exact string this `Uri` was parsed from, when it was parsed + /// rather than built. `None` for a `Uri` assembled by hand. + pub fn source_str(&self) -> Option<&str> { + self.source.as_deref() + } + + /// The parsed `amount` parameter, if present. + pub fn amount(&self) -> Option { + self.params.get("amount").and_then(|entry| { + let raw = entry.raw_value.as_deref().unwrap_or(""); + bitcoin::Amount::from_str_in(raw, bitcoin::amount::Denomination::Bitcoin).ok() }) } - /// Decodes the param if encoded making the lifetime static. - fn decode_into_owned<'b>(self) -> Param<'b> { - let owned = match self.0 { - ParamInner::EncodedBorrowed(decoder) => ParamInner::UnencodedBytes(decoder.collect()), - ParamInner::UnencodedString(Cow::Borrowed(value)) => ParamInner::UnencodedString(Cow::Owned(value.to_owned())), - ParamInner::UnencodedString(Cow::Owned(value)) => ParamInner::UnencodedString(Cow::Owned(value)), - ParamInner::UnencodedBytes(Cow::Borrowed(value)) => ParamInner::UnencodedBytes(Cow::Owned(value.to_owned())), - ParamInner::UnencodedBytes(Cow::Owned(value)) => ParamInner::UnencodedBytes(Cow::Owned(value)), - }; - Param(owned) + /// The decoded `label` parameter, if present. + pub fn label(&self) -> Option> { + self.decoded_string_param("label") } -} -/// Cheap conversion -impl<'a> From<&'a str> for Param<'a> { - fn from(value: &'a str) -> Self { - Param(ParamInner::UnencodedString(Cow::Borrowed(value))) + /// The decoded `message` parameter, if present. + pub fn message(&self) -> Option> { + self.decoded_string_param("message") } -} -/// Cheap conversion -impl From for Param<'_> { - fn from(value: String) -> Self { - Param(ParamInner::UnencodedString(Cow::Owned(value))) + /// The decoded `pop` parameter, if present. + pub fn pop(&self) -> Option> { + self.decoded_string_param("pop") } -} -/// Cheap conversion -#[cfg(feature = "non-compliant-bytes")] -#[cfg_attr(docsrs, doc(cfg(feature = "non-compliant-bytes")))] -impl<'a> From<&'a [u8]> for Param<'a> { - fn from(value: &'a [u8]) -> Self { - Param(ParamInner::UnencodedBytes(Cow::Borrowed(value))) + fn decoded_string_param(&self, key: &str) -> Option> { + self.params.get(key).and_then(ParamEntry::decoded_value) } } -/// Cheap conversion -#[cfg(feature = "non-compliant-bytes")] -#[cfg_attr(docsrs, doc(cfg(feature = "non-compliant-bytes")))] -impl From> for Param<'_> { - fn from(value: Vec) -> Self { - Param(ParamInner::UnencodedBytes(Cow::Owned(value))) +impl Uri { + /// Assembles a checked `Uri` from parts, with no source string. + /// + /// The only constructor of a built (as opposed to parsed) `Uri`; used by + /// [`UriBuilder::build`]. `source` is `None`, so + /// [`source_str`](Self::source_str) returns `None` and callers fall back + /// to [`Display`](fmt::Display) for the string form. + pub(crate) fn from_checked_parts(body: Option, params: Params) -> Self { + Uri { body, params, source: None } } } -/// Cheap conversion -#[cfg(feature = "non-compliant-bytes")] -#[cfg_attr(docsrs, doc(cfg(feature = "non-compliant-bytes")))] -impl<'a> From> for Vec { - fn from(value: Param<'a>) -> Self { - match value.0 { - ParamInner::EncodedBorrowed(decoder) => decoder.collect(), - ParamInner::UnencodedString(Cow::Borrowed(value)) => value.as_bytes().to_owned(), - ParamInner::UnencodedString(Cow::Owned(value)) => value.into(), - ParamInner::UnencodedBytes(value) => value.into(), +/// Formats a `Uri`. +/// +/// A parsed `Uri` is written back byte for byte: scheme case, an uppercase +/// bech32 body, empty parameters, a trailing `&` or `?` and any `#fragment` +/// all survive. A `Uri` cannot be changed after parsing, so its source is +/// always the URI it describes. +/// +/// A `Uri` with no source (one from [`UriBuilder::build`]) is written as +/// `bitcoin:?`, with its parameters in order. The body goes +/// through the [`bitcoin::Address`] `Display`, which is lowercase for `{}` +/// and uppercase for the alternate `{:#}` (QR alphanumeric mode). `{:#}` +/// always formats this way, even for a parsed `Uri`. +impl fmt::Display for Uri { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if let Some(source) = self.source.as_deref().filter(|_| !f.alternate()) { + return f.write_str(source); } + f.write_str("bitcoin:")?; + match &self.body { + Some(body) if f.alternate() => write!(f, "{:#}", body)?, + Some(body) => write!(f, "{}", body)?, + None => {}, + } + if !self.params.is_empty() { + write!(f, "?{}", self.params)?; + } + Ok(()) } } -/// Cheap conversion -#[cfg(feature = "non-compliant-bytes")] -#[cfg_attr(docsrs, doc(cfg(feature = "non-compliant-bytes")))] -impl<'a> From> for Cow<'a, [u8]> { - fn from(value: Param<'a>) -> Self { - match value.0 { - ParamInner::EncodedBorrowed(decoder) => decoder.into(), - ParamInner::UnencodedString(Cow::Borrowed(value)) => Cow::Borrowed(value.as_bytes()), - ParamInner::UnencodedString(Cow::Owned(value)) => Cow::Owned(value.into()), - ParamInner::UnencodedBytes(value) => value, - } +/// Percent-decodes `s` and validates the result as UTF-8. +/// +/// This is the strict decode: a byte sequence that isn't valid UTF-8 is +/// itself the error, for an accessor like [`Uri::label`] where that +/// distinction is the whole point. +pub(crate) fn decode_to_string(s: &str) -> Result { + let bytes: Vec = percent_encoding_rfc3986::percent_decode_str(s) + .map_err(AccessError::PercentDecode)? + .collect(); + String::from_utf8(bytes).map_err(|_| AccessError::NotUtf8) +} + +/// Validates percent escapes without keeping the decoded value. +fn validate_percent_encoding(key: &str, s: &str) -> Result<(), Error> { + let _: Vec = percent_encoding_rfc3986::percent_decode_str(s) + .map_err(Error::percent_decode(key))? + .collect(); + Ok(()) +} + +/// Validates an HRP-keyed address parameter: its value must be a segwit +/// address of `network`, the network its key names. +/// +/// `require_network` alone is not enough, since a base58 address only carries +/// mainnet or "test", so `1...` would pass for `bc` and `m...` for `tb` and +/// `bcrt`. Requiring a witness program rules out base58, and for a segwit +/// address `require_network` checks the HRP: `tb1...` is not valid for +/// regtest, nor `bcrt1...` for testnet. +/// +/// Used both at parse time and by [`UriBuilder::build`], so a built URI is +/// held to the same rule a parsed one is and round-trips. +pub(crate) fn validate_hrp_param(key: &str, raw_value: &str, network: bitcoin::Network) -> Result<(), Error> { + let is_segwit_on_network = raw_value + .parse::>() + .ok() + .and_then(|address| address.require_network(network).ok()) + .map_or(false, |address| address.witness_program().is_some()); + if is_segwit_on_network { + Ok(()) + } else { + Err(Error::InvalidHrpValue { key: key.to_owned() }) } } -impl<'a> TryFrom> for String { - type Error = core::str::Utf8Error; +#[cfg(test)] +mod tests { + use super::*; + use alloc::string::ToString; + + const LEGACY_MAINNET: &str = "1andreas3batLhQa2FawWjeyjCqyBzypd"; + const BECH32_MAINNET: &str = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"; + const BECH32_TESTNET: &str = "tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx"; + + #[test] + fn just_address_parses_with_a_body() { + let input = alloc::format!("bitcoin:{}", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap().assume_checked(); + assert_eq!(uri.body().unwrap().to_string(), LEGACY_MAINNET); + assert!(uri.params().is_empty()); + } + + #[test] + fn a_body_less_uri_parses() { + // BIP 321's own example: a silent-payment-only URI has no body. + let uri = Uri::parse("bitcoin:?sp=sp1qsilentpaymentaddress").unwrap().assume_checked(); + assert!(uri.body().is_none()); + assert_eq!(uri.get("sp").unwrap().raw_value.as_deref(), Some("sp1qsilentpaymentaddress")); + } + + #[test] + fn the_bare_scheme_parses_with_no_body() { + let uri = Uri::parse("bitcoin:").unwrap(); + assert!(uri.body().is_none()); + assert!(uri.params().is_empty()); + } + + #[test] + fn display_of_a_body_less_uri_has_no_address_before_the_question_mark() { + let input = "bitcoin:?sp=sp1qsilentpaymentaddress"; + let uri = Uri::parse(input).unwrap().assume_checked(); + assert_eq!(uri.to_string(), input); + } + + #[test] + fn a_value_less_param_parses() { + let input = alloc::format!("bitcoin:{}?foo", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.get("foo").unwrap().raw_value, None); + } - fn try_from(value: Param<'a>) -> Result { - match value.0 { - ParamInner::EncodedBorrowed(decoder) => >::try_from(decoder).map(Into::into), - ParamInner::UnencodedString(value) => Ok(value.into()), - ParamInner::UnencodedBytes(Cow::Borrowed(value)) => Ok(core::str::from_utf8(value)?.to_owned()), - ParamInner::UnencodedBytes(Cow::Owned(value)) => String::from_utf8(value).map_err(|error| error.utf8_error()), + #[test] + fn duplicate_label_message_amount_pop_are_rejected() { + for key in ["label", "message", "amount", "pop"] { + let input = alloc::format!("bitcoin:{}?{key}=a&{key}=b", LEGACY_MAINNET, key = key); + assert!(Uri::parse(&input).is_err(), "expected '{}' to be rejected when duplicated", key); } } -} -impl<'a> TryFrom> for Cow<'a, str> { - type Error = core::str::Utf8Error; + #[test] + fn duplicate_required_non_repeatable_params_are_rejected_by_base_key() { + for key in ["label", "message", "amount", "pop"] { + let input = alloc::format!("bitcoin:{}?{key}=a&req-{key}=b", LEGACY_MAINNET, key = key); + assert!(Uri::parse(&input).is_err(), "expected '{}' to be rejected when duplicated", key); + } + } + + #[test] + fn duplicate_non_special_keys_are_allowed() { + let input = alloc::format!("bitcoin:{}?bc={}&bc={}", LEGACY_MAINNET, BECH32_MAINNET, BECH32_MAINNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.get_all("bc").count(), 2); + } - fn try_from(value: Param<'a>) -> Result { - match value.0 { - ParamInner::EncodedBorrowed(decoder) => decoder.try_into(), - ParamInner::UnencodedString(value) => Ok(value), - ParamInner::UnencodedBytes(Cow::Borrowed(value)) => Ok(Cow::Borrowed(core::str::from_utf8(value)?)), - ParamInner::UnencodedBytes(Cow::Owned(value)) => Ok(Cow::Owned(String::from_utf8(value).map_err(|error| error.utf8_error())?)), + #[test] + fn amount_label_message_decode() { + let input = alloc::format!( + "bitcoin:{}?amount=20.3&label=Luke-Jr&message=Donation%20for%20project%20xyz", + LEGACY_MAINNET + ); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.amount().unwrap(), bitcoin::Amount::from_sat(2_030_000_000)); + assert_eq!(uri.label().unwrap().unwrap(), "Luke-Jr"); + assert_eq!(uri.message().unwrap().unwrap(), "Donation for project xyz"); + } + + #[test] + fn invalid_amount_is_a_parse_error() { + let input = alloc::format!("bitcoin:{}?amount=not-an-amount", LEGACY_MAINNET); + let err = Uri::parse(&input).unwrap_err(); + assert!(matches!(err, Error::InvalidAmount(_))); + } + + #[test] + fn invalid_percent_encoding_is_a_parse_error() { + let input = alloc::format!("bitcoin:{}?label=%zz", LEGACY_MAINNET); + let err = Uri::parse(&input).unwrap_err(); + assert!(matches!(err, Error::InvalidPercentEncoding { ref key, .. } if key == "label")); + } + + #[test] + fn a_literal_plus_is_never_treated_as_a_space() { + let input = alloc::format!("bitcoin:{}?label=a+b", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.label().unwrap().unwrap(), "a+b"); + } + + #[test] + fn an_unknown_param_parses_with_no_error() { + let input = alloc::format!("bitcoin:{}?unknown=x", LEGACY_MAINNET); + assert!(Uri::parse(&input).is_ok()); + } + + #[test] + fn get_and_get_all_match_required_params_by_base_key() { + let input = alloc::format!("bitcoin:{}?req-pj=a&pj=b&REQ-SP=c", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.get("pj").unwrap().key, "req-pj"); + let pj_keys: Vec<&str> = uri.get_all("pj").map(|entry| entry.key.as_str()).collect(); + assert_eq!(pj_keys, ["req-pj", "pj"]); + assert_eq!(uri.get("sp").unwrap().key, "REQ-SP"); + } + + #[test] + fn display_re_emits_body_and_params() { + let input = alloc::format!("bitcoin:{}?amount=20.3&label=Luke-Jr", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap().assume_checked(); + assert_eq!(uri.to_string(), input); + } + + #[test] + fn a_string_shorter_than_the_scheme_has_an_invalid_scheme() { + assert!(matches!(Uri::parse("bitcoin"), Err(Error::InvalidScheme))); + } + + #[test] + fn empty_segments_between_ampersands_are_ignored() { + let input = alloc::format!("bitcoin:{}?label=foo&&message=bar", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.params().len(), 2); + } + + #[test] + fn not_utf8_value_is_an_access_error() { + let input = alloc::format!("bitcoin:{}?label=%ff%fe", LEGACY_MAINNET); + match Uri::parse(&input).unwrap().label() { + Some(Err(AccessError::NotUtf8)) => {}, + other => panic!("expected NotUtf8, got {:?}", other), } } -} -#[derive(Debug, Clone)] -enum ParamInner<'a> { - EncodedBorrowed(PercentDecode<'a>), - UnencodedBytes(Cow<'a, [u8]>), - UnencodedString(Cow<'a, str>), -} + #[test] + #[cfg(feature = "std")] + fn error_source_is_present_only_for_wrapping_variants() { + use std::error::Error as _; + assert!(Error::InvalidScheme.source().is_none()); + let input = alloc::format!("bitcoin:{}?amount=nope", LEGACY_MAINNET); + assert!(Uri::parse(&input).unwrap_err().source().is_some()); + } -/// Iterator over decoded bytes inside paramter. -/// -/// The lifetime of this may be shorter than that of [`Param<'a>`]. -#[cfg(feature = "non-compliant-bytes")] -#[cfg_attr(docsrs, doc(cfg(feature = "non-compliant-bytes")))] -#[cfg_attr(feature = "non-compliant-bytes", allow(dead_code))] -pub struct ParamBytes<'a>(ParamIterInner<'a, core::iter::Cloned>>); + #[test] + fn a_mainnet_address_under_the_bc_key_parses() { + let input = alloc::format!("bitcoin:?bc={}", BECH32_MAINNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.get("bc").unwrap().raw_value.as_deref(), Some(BECH32_MAINNET)); + } -/// Iterator over decoded bytes inside paramter. -/// -/// The lifetime of this is same as that of [`Param<'a>`]. -#[cfg(feature = "non-compliant-bytes")] -#[cfg_attr(docsrs, doc(cfg(feature = "non-compliant-bytes")))] -#[cfg_attr(feature = "non-compliant-bytes", allow(dead_code))] -pub struct ParamBytesOwned<'a>(ParamIterInner<'a, Either>, alloc::vec::IntoIter>>); + #[test] + fn a_testnet_address_under_the_bc_key_is_rejected() { + // BIP 321's own invalid example: `bitcoin:?bc=tb1...`. + let input = alloc::format!("bitcoin:?bc={}", BECH32_TESTNET); + assert!(Uri::parse(&input).is_err()); + } -#[cfg(feature = "non-compliant-bytes")] -type ParamIterInner<'a, T> = either::Either, T>; + #[test] + fn a_testnet_address_under_the_tb_key_parses() { + let input = alloc::format!("bitcoin:?tb={}", BECH32_TESTNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.get("tb").unwrap().raw_value.as_deref(), Some(BECH32_TESTNET)); + } -/// Empty extras. -/// -/// This type can be used if extras are not required. -/// It is also the default type parameter of [`Uri`]. -#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] -pub struct NoExtras; + #[test] + fn a_req_prefixed_hrp_param_is_still_network_checked() { + // `req-bc` has base key `bc` (mainnet); a testnet value must not slip + // through because of the `req-` prefix. + let input = alloc::format!("bitcoin:?req-bc={}", BECH32_TESTNET); + assert!(Uri::parse(&input).is_err()); + } -/// This is a state used to deserialize `NoExtras` - it doesn't expect any parameters. -#[derive(Debug, Default, Copy, Clone)] -pub struct EmptyState; + fn address_on(address: &str, network: bitcoin::Network) -> String { + let script = address.parse::>().unwrap().assume_checked().script_pubkey(); + bitcoin::Address::from_script(&script, network).unwrap().to_string() + } -impl DeserializeParams<'_> for NoExtras { - type DeserializationState = EmptyState; -} + #[test] + fn a_regtest_address_under_the_bcrt_key_parses() { + let regtest = address_on(BECH32_MAINNET, bitcoin::Network::Regtest); + assert!(regtest.starts_with("bcrt1")); + let uri = Uri::parse(&alloc::format!("bitcoin:?bcrt={}", regtest)).unwrap(); + assert!(uri.is_valid_for_network(bitcoin::Network::Regtest)); + assert!(uri.clone().require_network(bitcoin::Network::Bitcoin).is_err()); + assert!(uri.require_network(bitcoin::Network::Testnet).is_err()); + } -impl DeserializationError for NoExtras { - type Error = core::convert::Infallible; -} + #[test] + fn an_hrp_key_takes_only_a_segwit_address_whose_hrp_is_the_key() { + let regtest = address_on(BECH32_MAINNET, bitcoin::Network::Regtest); + let testnet_base58 = address_on(LEGACY_MAINNET, bitcoin::Network::Testnet); + for (key, value) in [ + ("bc", LEGACY_MAINNET), + ("bc", BECH32_TESTNET), + ("bc", regtest.as_str()), + ("tb", testnet_base58.as_str()), + ("tb", regtest.as_str()), + ("tb", BECH32_MAINNET), + ("bcrt", BECH32_TESTNET), + ("bcrt", testnet_base58.as_str()), + ("bcrt", "garbage"), + ("REQ-BCRT", BECH32_TESTNET), + ] { + let input = alloc::format!("bitcoin:?{}={}", key, value); + match Uri::parse(&input) { + Err(Error::InvalidHrpValue { key: ref reported }) => assert_eq!(reported, key), + other => panic!("{} should fail with InvalidHrpValue, got {:?}", input, other), + } + } + } -impl DeserializationState<'_> for EmptyState { - type Value = NoExtras; + #[test] + fn hrp_keys_and_values_are_case_insensitive() { + // BIP 321's all-uppercase QR example. + let uri = Uri::parse("BITCOIN:?BC=BC1QUFGY354J3KMVUCH987XE4S40836X3H0LG8F5N2").unwrap(); + assert!(uri.is_valid_for_network(bitcoin::Network::Bitcoin)); + } - fn is_param_known(&self, _key: &str) -> bool { - false + #[test] + fn require_network_rejects_a_body_on_the_wrong_network() { + let input = alloc::format!("bitcoin:{}", BECH32_TESTNET); + let uri = Uri::parse(&input).unwrap(); + assert!(uri.require_network(bitcoin::Network::Bitcoin).is_err()); } - fn deserialize_temp(&mut self, _key: &str, _value: Param<'_>) -> Result::Error> { - Ok(de::ParamKind::Unknown) + #[test] + fn require_network_accepts_a_matching_body_and_hrp_param() { + let input = alloc::format!("bitcoin:{}?bc={}", BECH32_MAINNET, BECH32_MAINNET); + let uri = Uri::parse(&input).unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); + assert!(uri.body().is_some()); } - fn finalize(self) -> Result::Error> { - Ok(Default::default()) + #[test] + fn require_network_rejects_a_mismatched_hrp_param_even_with_a_matching_body() { + let input = alloc::format!("bitcoin:{}?tb={}", BECH32_MAINNET, BECH32_TESTNET); + let uri = Uri::parse(&input).unwrap(); + assert!(uri.require_network(bitcoin::Network::Bitcoin).is_err()); } -} -impl SerializeParams for &NoExtras { - type Key = core::convert::Infallible; - type Value = core::convert::Infallible; - type Iterator = core::iter::Empty<(Self::Key, Self::Value)>; + #[test] + fn network_error_display_message_is_specific() { + assert_eq!( + NetworkError::NetworkMismatch.to_string(), + "the URI is not valid for the requested network" + ); + } - fn serialize_params(self) -> Self::Iterator { - core::iter::empty() + #[test] + fn an_unclaimed_req_param_does_not_fail_parsing() { + // Unlike 0.1, the parser never enforces `req-` itself; it is + // reported by `unsatisfied_requirements` and left to the caller. + let input = alloc::format!("bitcoin:{}?req-somethingyoudontunderstand=50", LEGACY_MAINNET); + assert!(Uri::parse(&input).is_ok()); } -} -#[cfg(test)] -mod tests { - use crate::Uri; - use alloc::string::ToString; - use alloc::borrow::Cow; - use core::convert::TryInto; + #[test] + fn an_unknown_req_param_is_unsatisfied() { + let input = alloc::format!("bitcoin:{}?req-foo=bar", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + let unsatisfied: Vec<&str> = uri.unsatisfied_requirements(&[]).map(|e| e.key.as_str()).collect(); + assert_eq!(unsatisfied, ["req-foo"]); + } - fn check_send_sync() {} + #[test] + fn a_req_param_the_caller_understands_is_satisfied() { + let input = alloc::format!("bitcoin:{}?req-pj=https://example.com", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.unsatisfied_requirements(&["pj"]).count(), 0); + } #[test] - fn send_sync() { - check_send_sync::(); + fn understood_keys_are_matched_case_insensitively_and_without_the_prefix() { + let input = alloc::format!("bitcoin:{}?REQ-PJ=x", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + // Given without the `req-` prefix, matched ignoring case. + assert_eq!(uri.unsatisfied_requirements(&["pj"]).count(), 0); + assert_eq!(uri.unsatisfied_requirements(&[]).count(), 1); } - // Note: the official test vectors contained an invalid address so it was replaced with the address of Andreas Antonopoulos. + #[test] + fn plain_params_are_never_unsatisfied_requirements() { + let input = alloc::format!("bitcoin:{}?label=foo&pj=x&amount=1", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + // None of these carry a `req-` prefix, so none are requirements. + assert_eq!(uri.unsatisfied_requirements(&[]).count(), 0); + } #[test] - fn just_address() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd"; - let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); - assert_eq!(uri.address.to_string(), "1andreas3batLhQa2FawWjeyjCqyBzypd"); - assert!(uri.amount.is_none()); - assert!(uri.label.is_none()); - assert!(uri.message.is_none()); + fn only_the_unsatisfied_requirements_surface_in_source_order() { + let input = alloc::format!("bitcoin:{}?req-pj=a&req-foo=b&sp=c&req-bar=d", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + let unsatisfied: Vec<&str> = uri.unsatisfied_requirements(&["pj"]).map(|e| e.key.as_str()).collect(); + assert_eq!(unsatisfied, ["req-foo", "req-bar"]); + } - assert_eq!(uri.to_string(), input); + #[test] + fn a_required_pop_is_reported_like_any_other_requirement() { + let input = alloc::format!("bitcoin:{}?req-pop=https://example.com/pop", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.unsatisfied_requirements(&[]).count(), 1); + assert_eq!(uri.unsatisfied_requirements(&["pop"]).count(), 0); } #[test] - fn address_with_name() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=Luke-Jr"; - let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); - let label: Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap(); - assert_eq!(uri.address.to_string(), "1andreas3batLhQa2FawWjeyjCqyBzypd"); - assert_eq!(label, "Luke-Jr"); - assert!(uri.amount.is_none()); - assert!(uri.message.is_none()); + fn get_finds_a_req_prefixed_key_by_base_key() { + // `req-` is only a prefix, so a consumer that understands `sp` finds it + // whether or not it is required. + let uri = Uri::parse("bitcoin:?req-sp=sp1silent").unwrap(); + assert_eq!(uri.get("sp").expect("get should match req-sp").key, "req-sp"); + } - assert_eq!(uri.to_string(), input); + #[test] + fn display_of_a_parsed_uri_is_its_input() { + let bodies = ["", LEGACY_MAINNET, BECH32_MAINNET, "BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4"]; + let queries = [ + None, + Some(""), + Some("&"), + Some("a"), + Some("a="), + Some("a=b"), + Some("a&&b"), + Some("label=x&"), + Some("LABEL=Luke-Jr&Amount=1.5&req-pj=https://e.com/?x=a+b%23c"), + Some("bc=bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4&bc=bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"), + ]; + for scheme in ["bitcoin:", "BITCOIN:", "BitCoin:"] { + for body in bodies { + for query in queries { + for fragment in [None, Some(""), Some("frag")] { + let mut input = alloc::format!("{}{}", scheme, body); + if let Some(query) = query { + input = alloc::format!("{}?{}", input, query); + // Without a query, a `#` would end up in the body. + if let Some(fragment) = fragment { + input = alloc::format!("{}#{}", input, fragment); + } + } + let uri = Uri::parse(&input).unwrap_or_else(|e| panic!("{} should parse: {:?}", input, e)); + assert_eq!(uri.assume_checked().to_string(), input); + } + } + } + } } - #[allow(clippy::inconsistent_digit_grouping)] // Use sats/bitcoin when grouping. #[test] - fn request_20_point_30_btc_to_luke_dash_jr() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?amount=20.3&label=Luke-Jr"; - let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); - let label: Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap(); - assert_eq!(uri.address.to_string(), "1andreas3batLhQa2FawWjeyjCqyBzypd"); - assert_eq!(label, "Luke-Jr"); - assert_eq!(uri.amount, Some(bitcoin::Amount::from_sat(20_30_000_000))); - assert!(uri.message.is_none()); + fn alternate_display_of_a_parsed_uri_uppercases_the_body() { + let input = alloc::format!("BITCOIN:{}?label=Luke-Jr", BECH32_MAINNET); + let uri = Uri::parse(&input).unwrap().assume_checked(); + let expected = alloc::format!("bitcoin:{}?label=Luke-Jr", BECH32_MAINNET.to_uppercase()); + assert_eq!(alloc::format!("{:#}", uri), expected); + } - assert_eq!(uri.to_string(), input); + #[test] + fn source_str_returns_the_exact_input() { + let input = alloc::format!("bitcoin:{}?label=Luke-Jr", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + assert_eq!(uri.source_str(), Some(input.as_str())); } - #[allow(clippy::inconsistent_digit_grouping)] // Use sats/bitcoin when grouping. #[test] - fn request_50_btc_with_message() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz"; - let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); - let label: Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap(); - let message: Cow<'_, str> = uri.message.clone().unwrap().try_into().unwrap(); - assert_eq!(uri.address.to_string(), "1andreas3batLhQa2FawWjeyjCqyBzypd"); - assert_eq!(uri.amount, Some(bitcoin::Amount::from_sat(50_00_000_000))); - assert_eq!(label, "Luke-Jr"); - assert_eq!(message, "Donation for project xyz"); + fn uppercase_bech32_body_survives_the_round_trip() { + // QR alphanumeric mode carries a bech32 address in uppercase. The + // `Address` Display would lowercase it, so the body must come back as + // written. + let input = alloc::format!("BITCOIN:{}", BECH32_MAINNET.to_uppercase()); + let uri = Uri::parse(&input).unwrap().assume_checked(); + assert_eq!(uri.to_string(), input); + } + #[test] + fn a_literal_plus_inside_pj_survives_parse_and_re_emission() { + let input = "bitcoin:?pj=https://example.com/?x=a+b"; + let uri = Uri::parse(input).unwrap().assume_checked(); + assert_eq!(uri.get("pj").unwrap().raw_value.as_deref(), Some("https://example.com/?x=a+b")); assert_eq!(uri.to_string(), input); } #[test] - fn required_not_understood() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?req-somethingyoudontunderstand=50&req-somethingelseyoudontget=999"; - let uri = input.parse::>(); - assert!(uri.is_err()); + fn issue_10_round_trip_regression_passes() { + let valid_uri = "bitcoin:12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX?amount=0.01&pjos=0&pj=HTTPS://EXAMPLE.COM/%23OH1QYPM5JXYNS754Y4R45QWE336QFX6ZR8DQGVQCULVZTV20TFVEYDMFQC"; + let round_trip = valid_uri.parse::>().unwrap().assume_checked().to_string(); + assert_eq!(valid_uri, round_trip); + + let uri = "Bitcoin:12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX?6=q3Ҁf&pj=\u{3}\0\0\0\0\0\0http\r\r\r\r\r\r\r\r\r:\r\r\\.onion\\\\\\\\\\q3"; + let round_trip = uri.parse::>().unwrap().assume_checked().to_string(); + assert_eq!(uri, round_trip); } #[test] - fn required_understood() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?somethingyoudontunderstand=50&somethingelseyoudontget=999"; - let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); - assert_eq!(uri.address.to_string(), "1andreas3batLhQa2FawWjeyjCqyBzypd"); - assert!(uri.amount.is_none()); - assert!(uri.label.is_none()); - assert!(uri.message.is_none()); + fn equality_is_by_body_and_params_not_provenance() { + let input = alloc::format!("bitcoin:{}", BECH32_MAINNET); + let parsed = Uri::parse(&input).unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); + let address = BECH32_MAINNET + .parse::>() + .unwrap() + .assume_checked(); + let built = UriBuilder::new().address(address).build().unwrap(); + // Different provenance (parsed carries a source, built does not) but + // the same body and params: equal. + assert!(parsed.source_str().is_some()); + assert!(built.source_str().is_none()); + assert_eq!(parsed, built); + + // Same params, different body: not equal. + let other_body = Uri::parse(&alloc::format!("bitcoin:{}", LEGACY_MAINNET)) + .unwrap() + .require_network(bitcoin::Network::Bitcoin) + .unwrap(); + assert_ne!(parsed, other_body); + + // Same body, different params: not equal. + let with_param = Uri::parse(&alloc::format!("bitcoin:{}?label=x", BECH32_MAINNET)) + .unwrap() + .require_network(bitcoin::Network::Bitcoin) + .unwrap(); + assert_ne!(parsed, with_param); + } - assert_eq!(uri.to_string(), "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd"); + #[test] + #[cfg(feature = "std")] + fn build_error_source_is_present_only_for_the_network_variant() { + use std::error::Error as _; + assert!(BuildError::Network(NetworkError::NetworkMismatch).source().is_some()); + assert!(BuildError::InvalidKey("x".to_string()).source().is_none()); } #[test] - fn label_with_rfc3986_param_separator() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=foo%26bar%20%3D%20baz/blah?;:@"; - let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); - let label: Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap(); - assert_eq!(uri.address.to_string(), "1andreas3batLhQa2FawWjeyjCqyBzypd"); - assert_eq!(label, "foo&bar = baz/blah?;:@"); - assert!(uri.amount.is_none()); - assert!(uri.message.is_none()); + fn alternate_display_of_a_built_uri_uppercases_the_body() { + // A built URI has no source, so the body goes through the `Address` + // Display: `{}` is lowercase, `{:#}` is uppercase (QR alphanumeric + // mode). The alternate flag must pick between them. + let address = BECH32_MAINNET + .parse::>() + .unwrap() + .assume_checked(); + let uri = UriBuilder::new().address(address).build().unwrap(); + assert_eq!(alloc::format!("{}", uri), alloc::format!("bitcoin:{}", BECH32_MAINNET)); + assert_eq!(alloc::format!("{:#}", uri), alloc::format!("bitcoin:{}", BECH32_MAINNET.to_uppercase())); + } - assert_eq!(uri.to_string(), input); + #[test] + fn error_display_messages_are_distinct_and_mention_the_key() { + let bad_scheme = Error::InvalidScheme.to_string(); + let dup = Error::DuplicateParameter("label".to_owned()).to_string(); + let amount = Uri::parse("bitcoin:?amount=nope").unwrap_err().to_string(); + assert_ne!(bad_scheme, amount); + assert!(dup.contains("label")); } #[test] - fn label_with_rfc3986_fragment_separator() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=foo%23bar"; - let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); - let label: Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap(); - assert_eq!(uri.address.to_string(), "1andreas3batLhQa2FawWjeyjCqyBzypd"); - assert_eq!(label, "foo#bar"); - assert!(uri.amount.is_none()); - assert!(uri.message.is_none()); + fn access_error_display_messages_are_specific() { + assert_eq!(AccessError::NotUtf8.to_string(), "value is not valid UTF-8"); + let decode_err = percent_encoding_rfc3986::percent_decode_str("%zz").unwrap_err(); + assert_eq!(AccessError::PercentDecode(decode_err).to_string(), "invalid percent-encoding"); + } - assert_eq!(uri.to_string(), input); + #[test] + #[cfg(feature = "std")] + fn access_error_source_matches_its_variant() { + use std::error::Error as _; + assert!(AccessError::NotUtf8.source().is_none()); + let decode_error = percent_encoding_rfc3986::percent_decode_str("%zz").unwrap_err(); + assert!(AccessError::PercentDecode(decode_error).source().is_some()); } #[test] - fn rfc3986_empty_fragment_not_defined_in_bip21() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=foo#"; - let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); - let label: Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap(); - assert_eq!(uri.address.to_string(), "1andreas3batLhQa2FawWjeyjCqyBzypd"); - assert_eq!(label, "foo"); - assert!(uri.amount.is_none()); - assert!(uri.message.is_none()); - assert_eq!(uri.to_string(), "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=foo"); + fn params_iter_and_into_iter_agree_and_see_every_entry() { + let input = alloc::format!("bitcoin:{}?label=foo&message=bar", LEGACY_MAINNET); + let uri = Uri::parse(&input).unwrap(); + let via_iter: Vec<&str> = uri.params().iter().map(|entry| entry.key.as_str()).collect(); + let via_into_iter: Vec<&str> = uri.params().into_iter().map(|entry| entry.key.as_str()).collect(); + assert_eq!(via_iter, ["label", "message"]); + assert_eq!(via_iter, via_into_iter); } #[test] - fn rfc3986_non_empty_fragment_not_defined_in_bip21() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=foo#&message=not%20part%20of%20a%20message"; - let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); - let label: Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap(); - assert_eq!(uri.address.to_string(), "1andreas3batLhQa2FawWjeyjCqyBzypd"); - assert_eq!(label, "foo"); - assert!(uri.amount.is_none()); - assert!(uri.message.is_none()); - assert_eq!(uri.to_string(), "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=foo"); + fn a_param_value_is_tokenized_verbatim_and_decoded_on_demand() { + // The crate tokenizes: the raw value stays percent-encoded and the + // consumer decodes with `decoded_value` when it wants the text. `+` is + // a literal plus, never a space. + let uri = Uri::parse("bitcoin:?lightning=a+b%20c").unwrap(); + let entry = uri.get("lightning").unwrap(); + assert_eq!(entry.raw_value.as_deref(), Some("a+b%20c")); + assert_eq!(entry.decoded_value().unwrap().unwrap(), "a+b c"); } #[test] - fn bad_unicode_scheme() { - let input = "bitcoinö:1andreas3batLhQa2FawWjeyjCqyBzypd"; - let uri = input.parse::>(); - assert!(uri.is_err()); + fn decoded_value_is_none_for_a_value_less_param() { + let uri = Uri::parse("bitcoin:?flag").unwrap(); + assert!(uri.get("flag").unwrap().decoded_value().is_none()); } #[test] - fn duplicate_params() { - let duplicate_label = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=foo&label=bar"; - let uri = duplicate_label.parse::>(); - assert!(uri.is_err()); + fn pop_decodes_its_percent_encoded_value() { + let input = "bitcoin:?pop=hello%20world"; + let uri = Uri::parse(input).unwrap(); + assert_eq!(uri.pop().unwrap().unwrap(), "hello world"); + } - let duplicate_amount = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?amount=123&amount=456"; - let uri = duplicate_amount.parse::>(); - assert!(uri.is_err()); + #[test] + fn pop_is_none_when_absent() { + let uri = Uri::parse("bitcoin:?label=Luke-Jr").unwrap(); + assert!(uri.pop().is_none()); + } - let duplicate_message = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?message=foo&message=bar"; - let uri = duplicate_message.parse::>(); - assert!(uri.is_err()); + #[test] + fn bad_unicode_scheme_is_rejected() { + let input = "bitcoinö:1andreas3batLhQa2FawWjeyjCqyBzypd"; + assert!(Uri::parse(input).is_err()); + } + + #[test] + fn a_bodyless_uri_with_only_unknown_params_parses() { + let uri = Uri::parse("bitcoin:?unknown=x") + .unwrap() + .require_network(bitcoin::Network::Bitcoin) + .unwrap(); + assert!(uri.body().is_none()); + assert_eq!(uri.get("unknown").unwrap().raw_value.as_deref(), Some("x")); + } + + #[test] + fn mixed_extension_keys_all_survive_parsing() { + let input = "bitcoin:?lno=lno1bogusoffer&sp=sp1qsilentpaymentaddress"; + let uri = Uri::parse(input).unwrap(); + assert!(uri.body().is_none()); + assert_eq!(uri.get("lno").unwrap().raw_value.as_deref(), Some("lno1bogusoffer")); + assert_eq!(uri.get("sp").unwrap().raw_value.as_deref(), Some("sp1qsilentpaymentaddress")); } } diff --git a/src/params.rs b/src/params.rs new file mode 100644 index 0000000..455ab18 --- /dev/null +++ b/src/params.rs @@ -0,0 +1,221 @@ +//! The ordered multimap of raw query parameters that backs [`crate::Uri`]. +//! +//! Values are kept exactly as they appeared in the source URI - still +//! percent-encoded, still in their original key case - until something asks +//! for a decoded view. This is what lets re-emission be byte-exact and lets +//! every extension (payjoin's `pj`, a silent-payment `sp`, anything else) +//! read whatever it needs without this crate knowing what the value means. + +use alloc::string::String; +use alloc::vec::Vec; +use core::fmt; + +/// One `key[=value]` pair from a BIP 321 query string, in source order. +/// +/// `otherparam = qchar *qchar [ "=" *qchar ]` (BIP 321): the `=value` part +/// is optional, so `raw_value` is `None` for a value-less parameter such as +/// a bare `?foo` rather than `?foo=`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ParamEntry { + /// The parameter key, in the exact case it appeared in the source URI. + pub key: String, + /// The parameter value, still percent-encoded. `None` for a value-less + /// parameter, `Some("")` for a parameter with an empty value (`?foo=`). + pub raw_value: Option, +} + +pub(crate) fn requirement_key(key: &str) -> Option<&str> { + let prefix = key.get(..4)?; + if prefix.eq_ignore_ascii_case("req-") { + Some(&key[4..]) + } else { + None + } +} + +pub(crate) fn base_key(key: &str) -> &str { + requirement_key(key).unwrap_or(key) +} + +impl ParamEntry { + /// `true` if `key` and this entry's key have the same base key, + /// case-insensitively. + /// + /// A required key such as `req-pj` has base key `pj`; plain keys use the + /// key itself. `req-` is only a prefix, so it is stripped from both sides: + /// `pj` and `req-pj` each match both `pj` and `req-pj` entries. + pub(crate) fn base_key_eq(&self, key: &str) -> bool { + base_key(&self.key).eq_ignore_ascii_case(base_key(key)) + } + + /// The requirement key if this is a `req-` parameter, otherwise `None`. + /// + /// BIP 321's `reqparam = "req-" qchar *qchar [ "=" *qchar ]`: a `req-` prefix (matched + /// case-insensitively) marks a parameter a client MUST understand or + /// reject the whole URI. This returns the key without that prefix - + /// `req-pj` yields `Some("pj")` - which is what a client compares against + /// the keys it understands. + pub fn requirement(&self) -> Option<&str> { + requirement_key(&self.key) + } + + /// `true` if this is a `req-` parameter (see [`requirement`]). + /// + /// [`requirement`]: ParamEntry::requirement + pub fn is_required(&self) -> bool { + self.requirement().is_some() + } + + /// The value percent-decoded to a UTF-8 string, or `None` for a value-less + /// parameter. + /// + /// Decoding is RFC 3986, so `+` stays a literal plus. `Some(Err(_))` when + /// the value is not valid percent-encoding or not UTF-8 - the same + /// access-time distinction the typed accessors + /// ([`Uri::label`](crate::Uri::label) and friends) rely on, since they are + /// built on this. An extension reading `pj`, `sp`, or another key gets the + /// decoded text from here and only has to parse it. + pub fn decoded_value(&self) -> Option> { + self.raw_value.as_deref().map(crate::decode_to_string) + } +} + +/// An ordered multimap of [`ParamEntry`], preserving source order and +/// allowing repeats except where BIP 321 forbids them. +/// +/// `amount`, `label`, `message`, and `pop` may not repeat (BIP 321); any +/// other key may, and every occurrence is kept. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Params { + entries: Vec, +} + +/// Keys that BIP 321 forbids from repeating, matched case-insensitively. +pub(crate) const NON_REPEATABLE_KEYS: [&str; 4] = ["amount", "label", "message", "pop"]; + +impl Params { + /// An empty parameter list. + pub(crate) fn new() -> Self { + Self::default() + } + + /// Appends an entry, without any uniqueness check. + /// + /// Parsing and [`crate::UriBuilder`] enforce the BIP 321 non-repeat rule + /// themselves before this is called. + pub(crate) fn push(&mut self, entry: ParamEntry) { + self.entries.push(entry); + } + + /// The first entry whose base key matches `key`'s base key + /// case-insensitively, so `get("pj")` and `get("req-pj")` both find + /// `pj` and `req-pj`. + pub fn get(&self, key: &str) -> Option<&ParamEntry> { + self.entries.iter().find(|entry| entry.base_key_eq(key)) + } + + /// Every entry whose base key matches `key`'s base key + /// case-insensitively, in source order. + pub fn get_all<'a>(&'a self, key: &'a str) -> impl Iterator + 'a { + self.entries.iter().filter(move |entry| entry.base_key_eq(key)) + } + + /// All entries, in source order. + pub fn iter(&self) -> impl Iterator { + self.entries.iter() + } + + /// `true` if there are no parameters at all. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// The number of entries, counting every repeat. + pub fn len(&self) -> usize { + self.entries.len() + } +} + +impl fmt::Display for Params { + /// Re-emits every entry as `key=value` (or bare `key` for a value-less + /// one), joined by `&`, in source order. Does not write a leading `?`. + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut first = true; + for entry in &self.entries { + if first { + first = false; + } else { + write!(f, "&")?; + } + write!(f, "{}", entry.key)?; + if let Some(value) = &entry.raw_value { + write!(f, "={}", value)?; + } + } + Ok(()) + } +} + +impl<'a> IntoIterator for &'a Params { + type Item = &'a ParamEntry; + type IntoIter = core::slice::Iter<'a, ParamEntry>; + + fn into_iter(self) -> Self::IntoIter { + self.entries.iter() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(key: &str) -> ParamEntry { + ParamEntry { + key: key.into(), + raw_value: None, + } + } + + #[test] + fn requirement_strips_a_case_insensitive_req_prefix() { + assert_eq!(entry("req-pj").requirement(), Some("pj")); + assert_eq!(entry("REQ-pj").requirement(), Some("pj")); + assert_eq!(entry("Req-Pop").requirement(), Some("Pop")); + } + + #[test] + fn requirement_is_none_for_a_plain_key() { + assert_eq!(entry("pj").requirement(), None); + assert_eq!(entry("label").requirement(), None); + // A key that merely starts with "req" but not "req-". + assert_eq!(entry("require").requirement(), None); + } + + #[test] + fn a_bare_req_prefix_has_an_empty_requirement() { + assert_eq!(entry("req-").requirement(), Some("")); + } + + #[test] + fn a_short_or_non_ascii_key_is_not_a_requirement() { + // Shorter than "req-". + assert_eq!(entry("re").requirement(), None); + // First four bytes decode to "réq", which is not "req-". + assert_eq!(entry("réq-pj").requirement(), None); + } + + #[test] + fn base_key_eq_strips_req_from_both_sides() { + for (entry_key, lookup) in [("pj", "pj"), ("pj", "req-pj"), ("req-pj", "pj"), ("REQ-PJ", "req-pj"), ("Pj", "REQ-pj")] { + assert!(entry(entry_key).base_key_eq(lookup), "{} should match {}", entry_key, lookup); + } + assert!(!entry("pj").base_key_eq("sp")); + assert!(!entry("req-pj").base_key_eq("req-sp")); + } + + #[test] + fn is_required_reflects_the_req_prefix() { + assert!(entry("req-pj").is_required()); + assert!(!entry("pj").is_required()); + } +} diff --git a/src/ser.rs b/src/ser.rs deleted file mode 100644 index 9451097..0000000 --- a/src/ser.rs +++ /dev/null @@ -1,197 +0,0 @@ -//! Types and traits related to serialization (displaying) of BIP21 -//! -//! This module provides mainly the infrastructure required to display extra BIP21 arguments. -//! -//! Check [`SerializeParams`] to get started. - -use alloc::borrow::Cow; -use bitcoin::amount::Denomination; -use core::fmt; -use super::{Uri, Param, ParamInner}; - -/// Represents a value that can be serialized. -/// -/// The `Extras` type parameter must implement this for [`Uri`] to be displayable. -pub trait SerializeParams { - /// Parameter name. - /// - /// **Warning**: displaying [`Uri`] will panic if the key contains `=` character! - type Key: fmt::Display; - /// Parameter value. - type Value: fmt::Display; - - /// Iterator over key-value pairs - type Iterator: Iterator; - - /// Constructs the iterator over key-value pairs. - fn serialize_params(self) -> Self::Iterator; -} - -/// Checks if the display implementation outputs `=` character. -struct EqSignChecker<'a, W: fmt::Write>(W, &'a dyn fmt::Display); - -impl fmt::Write for EqSignChecker<'_, W> { - fn write_str(&mut self, s: &str) -> fmt::Result { - if s.contains('=') { - panic!("key '{}' contains equal sign", self.1); - } - self.0.write_str(s) - } - - fn write_char(&mut self, c: char) -> fmt::Result { - if c == '=' { - panic!("key '{}' contains equal sign", self.1); - } - self.0.write_char(c) - } -} - -/// Set of characters that will be percent-encoded -/// -/// This contains anything not in `query` (i.e. ``gen-delim` from the quoted -/// definitions`) as per RFC 3986, as well as '&' and '=' as per BIP 21. -/// -/// [BIP 21](https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki#abnf-grammar): -/// -/// > ```text -/// > labelparam = "label=" *qchar -/// > messageparam = "message=" *qchar -/// > otherparam = qchar *qchar [ "=" *qchar ] -/// > ``` -/// ... -/// > Here, "qchar" corresponds to valid characters of an RFC 3986 URI query -/// > component, excluding the "=" and "&" characters, which this BIP takes as -/// > separators. -/// -/// [RFC 3986 Appendix A](https://www.rfc-editor.org/rfc/rfc3986#appendix-A): -/// -/// > ```text -/// > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" -/// > query = *( pchar / "/" / "?" ) -/// > ``` -/// ... -/// > ```text -/// > pct-encoded = "%" HEXDIG HEXDIG -/// > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" -/// > ``` -/// ... -/// > ```text -/// > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" -/// > / "*" / "+" / "," / ";" / "=" -/// > ``` -const ASCII_SET: percent_encoding_rfc3986::AsciiSet = percent_encoding_rfc3986::NON_ALPHANUMERIC - // allow non-alphanumeric characters from `unreserved` - .remove(b'-') - .remove(b'.') - .remove(b'_') - .remove(b'~') - // allow non-alphanumeric characters from `sub-delims` excluding bip-21 - // separators ("&", and "=") - .remove(b'!') - .remove(b'$') - .remove(b'\'') - .remove(b'(') - .remove(b')') - .remove(b'*') - .remove(b'+') - .remove(b',') - .remove(b';') - // allow pchar extra chars - .remove(b':') - .remove(b'@') - // allow query extra chars - .remove(b'/') - .remove(b'?'); - -/// Percent-encodes writes. -struct WriterEncoder(W); - -impl fmt::Write for WriterEncoder { - fn write_str(&mut self, s: &str) -> fmt::Result { - write!(self.0, "{}", percent_encoding_rfc3986::utf8_percent_encode(s, &ASCII_SET)) - } -} - -/// Percent-encodes `Display` impl. -struct DisplayEncoder(T); - -impl fmt::Display for DisplayEncoder { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use fmt::Write; - - write!(WriterEncoder(f), "{}", self.0) - } -} - -/// Displays [`Param`] as encoded -/// -/// This is private because people should generally only display values as decoded -struct DisplayParam<'a>(&'a Param<'a>); - -impl fmt::Display for DisplayParam<'_> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match &(self.0).0 { - // TODO: improve percent_encoding_rfc_3986 so that allocation can be avoided - ParamInner::EncodedBorrowed(decoder) => { - let decoded = >::from(decoder.clone()); - write!(f, "{}", percent_encoding_rfc3986::percent_encode(&decoded, &ASCII_SET)) - }, - ParamInner::UnencodedBytes(bytes) => write!(f, "{}", percent_encoding_rfc3986::percent_encode(bytes, &ASCII_SET)), - ParamInner::UnencodedString(string) => write!(f, "{}", percent_encoding_rfc3986::utf8_percent_encode(string, &ASCII_SET)), - } - } -} - -/// Writes key-value pair with all required symbols around them. -/// -/// `value` is **not** percent-encoded - this must be done from the caller. -fn write_param(writer: &mut impl fmt::Write, key: impl fmt::Display, value: impl fmt::Display, no_params: &mut bool) -> fmt::Result { - use core::fmt::Write; - - if *no_params { - write!(EqSignChecker(&mut *writer, &key), "?{}", key)?; - *no_params = false; - } else { - write!(EqSignChecker(&mut *writer, &key), "&{}", key)?; - } - write!(writer, "={}", value) -} - -/// Write key-value pair if `value` is `Some`. -fn maybe_write_param(writer: &mut impl fmt::Write, key: impl fmt::Display, value: Option<&Param<'_>>, no_params: &mut bool) -> fmt::Result { - match value { - Some(value) => write_param(writer, key, DisplayParam(value), no_params), - None => Ok(()), - } -} - -/// Write key-value pair if `value` is `Some`. -fn maybe_display_param(writer: &mut impl fmt::Write, key: impl fmt::Display, value: Option, no_params: &mut bool) -> fmt::Result { - match value { - Some(value) => write_param(writer, key, DisplayEncoder(value), no_params), - None => Ok(()), - } -} - -/// Formats QR-code-optimized URI if alternate form (`{:#}`) is used. -#[rustfmt::skip] -impl fmt::Display for Uri<'_, bitcoin::address::NetworkChecked, T> where for<'a> &'a T: SerializeParams { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if f.alternate() { - write!(f, "bitcoin:{:#}", self.address)?; - } else { - write!(f, "bitcoin:{}", self.address)?; - } - let mut no_params = true; - let display_amount = self.amount.as_ref().map(|amount| amount.display_in(Denomination::Bitcoin)); - - maybe_display_param(f, "amount", display_amount, &mut no_params)?; - maybe_write_param(f, "label", self.label.as_ref(), &mut no_params)?; - maybe_write_param(f, "message", self.message.as_ref(), &mut no_params)?; - - for (key, value) in self.extras.serialize_params() { - write_param(f, key, DisplayEncoder(value), &mut no_params)?; - } - Ok(()) - } -} diff --git a/tests/bip321.rs b/tests/bip321.rs new file mode 100644 index 0000000..c773383 --- /dev/null +++ b/tests/bip321.rs @@ -0,0 +1,148 @@ +//! The example URIs from BIP 321's appendix, copied verbatim. +//! +//! The examples' body address, inherited from BIP 21, has a bad base58 +//! checksum, so a parser that validates the body rejects every example that +//! uses it. The tests swap in a valid mainnet address before parsing. + +use bitcoin::{Amount, Network}; +use bitcoin_uri::{Error, Uri}; + +const BIP_ADDRESS: &str = "175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"; +const ADDRESS: &str = "1andreas3batLhQa2FawWjeyjCqyBzypd"; + +fn with_valid_address(example: &str) -> String { + example.replace(BIP_ADDRESS, ADDRESS) +} + +fn parse(example: &str) -> Uri { + let input = with_valid_address(example); + input.parse().unwrap_or_else(|e| panic!("{} should parse: {:?}", input, e)) +} + +#[test] +fn the_bip_example_address_has_a_bad_checksum() { + let error = BIP_ADDRESS.parse::>().unwrap_err(); + assert!(matches!(error, bitcoin::address::ParseError::Base58(_)), "{:?}", error); + assert!(matches!( + format!("bitcoin:{}", BIP_ADDRESS).parse::>(), + Err(Error::InvalidBodyAddress(_)) + )); +} + +fn decoded(uri: &Uri, key: &str) -> String { + uri.get(key).unwrap().decoded_value().unwrap().unwrap() +} + +#[test] +fn every_valid_example_parses_and_displays_as_written() { + let mainnet = [ + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?label=Luke-Jr", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=20.3&label=Luke-Jr", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?lightning=lnbc420bogusinvoice", + "bitcoin:?lightning=lnbc420bogusinvoice", + "bitcoin:?lno=lno1bogusoffer", + "bitcoin:?lno=lno1bogusoffer&sp=sp1qsilentpayment", + "bitcoin:?sp=sp1qsilentpayment", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?sp=sp1qsilentpayment", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-somethingyoudontunderstand=50&req-somethingelseyoudontget=999", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?somethingyoudontunderstand=50&somethingelseyoudontget=999", + "bitcoin:?bc=bc1qufgy354j3kmvuch987xe4s40836x3h0lg8f5n2&bc=bc1p5swkugezn97763tl0yty6556856uug0q6jflljvep9m4p7339x5qzyrh4g", + "BITCOIN:BC1QUFGY354J3KMVUCH987XE4S40836X3H0LG8F5N2?BC=BC1P5SWKUGEZN97763TL0YTY6556856UUG0Q6JFLLJVEP9M4P7339X5QZYRH4G", + "BITCOIN:?BC=BC1QUFGY354J3KMVUCH987XE4S40836X3H0LG8F5N2&BC=BC1P5SWKUGEZN97763TL0YTY6556856UUG0Q6JFLLJVEP9M4P7339X5QZYRH4G", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?pop=initiatingapp%3a", + "bitcoin:?lightning=lnbc420bogusinvoice&pop=callbackuri%3abody%3fpop=", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?lightning=lnbc420bogusinvoice&pop=app%3a%3f", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?pop=https%3aiwantyouripaddress.com", + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-pop=https%3aevilwebsite.com", + ]; + for example in mainnet { + let uri = parse(example).require_network(Network::Bitcoin).unwrap(); + assert_eq!(uri.to_string(), with_valid_address(example)); + } + + let testnet = "bitcoin:?tb=tb1qghfhmd4zh7ncpmxl3qzhmq566jk8ckq4gafnmg"; + let uri = parse(testnet); + assert!(!uri.is_valid_for_network(Network::Bitcoin)); + assert_eq!(uri.require_network(Network::Testnet).unwrap().to_string(), testnet); +} + +#[test] +fn every_invalid_example_fails_to_parse() { + let duplicates = [ + ("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?label=Luke-Jr&label=Matt", "label"), + ("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=42&amount=10", "amount"), + ("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=42&amount=42", "amount"), + ( + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?pop=callback%3a&req-pop=callback%3a", + "req-pop", + ), + ]; + for (example, key) in duplicates { + let input = with_valid_address(example); + match input.parse::>() { + Err(Error::DuplicateParameter(ref duplicate)) => assert_eq!(duplicate, key), + other => panic!("{} should be a duplicate {}, got {:?}", input, key, other), + } + } + + let input = "bitcoin:?bc=tb1qghfhmd4zh7ncpmxl3qzhmq566jk8ckq4gafnmg"; + assert!(matches!(input.parse::>(), Err(Error::InvalidHrpValue { ref key }) if key == "bc")); +} + +#[test] +fn the_examples_carry_the_values_they_describe() { + let uri = parse("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=20.3&label=Luke-Jr"); + assert_eq!(uri.body().unwrap().clone().assume_checked().to_string(), ADDRESS); + assert_eq!(uri.amount(), Some(Amount::from_sat(2_030_000_000))); + assert_eq!(uri.label().unwrap().unwrap(), "Luke-Jr"); + + let uri = parse("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?amount=50&label=Luke-Jr&message=Donation%20for%20project%20xyz"); + assert_eq!(uri.amount(), Some(Amount::from_int_btc(50))); + assert_eq!(uri.message().unwrap().unwrap(), "Donation for project xyz"); + + let uri = parse("bitcoin:?lno=lno1bogusoffer&sp=sp1qsilentpayment"); + assert!(uri.body().is_none()); + assert_eq!(decoded(&uri, "lno"), "lno1bogusoffer"); + assert_eq!(decoded(&uri, "sp"), "sp1qsilentpayment"); + + let uri = parse("BITCOIN:?BC=BC1QUFGY354J3KMVUCH987XE4S40836X3H0LG8F5N2&BC=BC1P5SWKUGEZN97763TL0YTY6556856UUG0Q6JFLLJVEP9M4P7339X5QZYRH4G"); + assert_eq!(uri.get_all("bc").count(), 2); +} + +#[test] +fn only_the_req_prefixed_unknown_params_are_unsatisfied() { + let required = parse("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-somethingyoudontunderstand=50&req-somethingelseyoudontget=999"); + let unsatisfied: Vec<&str> = required.unsatisfied_requirements(&[]).map(|entry| entry.key.as_str()).collect(); + assert_eq!(unsatisfied, ["req-somethingyoudontunderstand", "req-somethingelseyoudontget"]); + + let optional = parse("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?somethingyoudontunderstand=50&somethingelseyoudontget=999"); + assert_eq!(optional.unsatisfied_requirements(&[]).count(), 0); + + // "the wallet MUST NOT make a payment" unless it understands pop. + let uri = parse("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?req-pop=https%3aevilwebsite.com"); + assert_eq!(uri.unsatisfied_requirements(&[]).count(), 1); + assert_eq!(uri.unsatisfied_requirements(&["pop"]).count(), 0); +} + +#[test] +fn pop_callbacks_decode_to_the_uri_the_wallet_opens() { + for (input, callback) in [ + ("bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?pop=initiatingapp%3a", "initiatingapp:"), + ( + "bitcoin:?lightning=lnbc420bogusinvoice&pop=callbackuri%3abody%3fpop=", + "callbackuri:body?pop=", + ), + ( + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?lightning=lnbc420bogusinvoice&pop=app%3a%3f", + "app:?", + ), + ( + "bitcoin:175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W?pop=https%3aiwantyouripaddress.com", + "https:iwantyouripaddress.com", + ), + ] { + assert_eq!(parse(input).pop().unwrap().unwrap(), callback); + } +}