diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 6420200..3f8b799 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -7,29 +7,28 @@ 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: @@ -37,22 +36,15 @@ jobs: strategy: matrix: os: [ubuntu-latest, windows-latest, macOS-latest] - rust: [stable, 1.63.0] - exclude: - - os: macOS-latest - rust: 1.63.0 + rust: [stable, "1.85"] 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: Test run: cargo test diff --git a/CHANGELOG.md b/CHANGELOG.md index 0afdbf9..6934749 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,45 @@ # bitcoin_uri Changelog +## Unreleased + +### Breaking changes + +- MSRV is now 1.85, and the `bitcoin` dependency is 0.32.102, to track + rust-payjoin. +- The body address is now optional, so a body-less URI such as + `bitcoin:?sp=...` parses. `Uri::body` returns `Option>`. +- `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. +- Parse-time `Error` and access-time `AccessError`, kept separate: a `Uri` + parses as long as it is structurally valid, and decoding an individual + value can fail later without failing the parse. +- `Uri::require_network`/`is_valid_for_network` over the body and `bc=`/`tb=` + addresses, with parse-time rejection of an HRP param on the wrong network. +- `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`. +- Byte-exact `Display` for a parsed `Uri` (bech32 bodies survive QR + uppercase), plus `Uri::source_str` for the original string. +- `UriBuilder`, assembling a `Uri` from typed parts whose `Display` + re-parses to the same parameters. `build` takes a network and rejects + mixed-network URIs. +- `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..3eb850e 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" +rust-version = "1.85" 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..7813733 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.85 ## License diff --git a/examples/extension_params.rs b/examples/extension_params.rs new file mode 100644 index 0000000..6281d15 --- /dev/null +++ b/examples/extension_params.rs @@ -0,0 +1,53 @@ +//! 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` offer, 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=LNO1BOGUSOFFER\ + &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") { + println!("sp: {}", entry.raw_value.as_deref().unwrap_or("")); + } + + // `lightning` carries a BOLT 12 offer; bech32 is case-sensitive, so the + // value is handed back in the exact case it arrived. + if let Some(entry) = uri.get("lightning") { + println!("lightning: {}", entry.raw_value.as_deref().unwrap_or("")); + } + + // `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..ff23529 --- /dev/null +++ b/src/builder.rs @@ -0,0 +1,466 @@ +//! 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() +} + +fn key_round_trips(key: &str) -> bool { + !key.is_empty() && !key.bytes().any(|byte| matches!(byte, b'&' | b'=' | b'#')) +} + +fn raw_value_round_trips(value: &str) -> bool { + !value.bytes().any(|byte| matches!(byte, b'&' | b'#')) && percent_encoding_rfc3986::percent_decode_str(value).is_ok() +} + +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(bitcoin::Network::Bitcoin) +/// .unwrap(); +/// assert!(uri.to_string().starts_with("bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?")); +/// ``` +#[derive(Debug, Clone, Default)] +#[must_use = "a UriBuilder builds nothing until `.build(bitcoin::Network::Bitcoin)` 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`, `lightning`, or `sp`, or any other extension. + /// A `bc=`/`tb=` value is validated as an address of that network by + /// [`build`](Self::build), so the built URI parses back. The value is + /// treated as decoded text and encoded for you. + 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. 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 for `network`, or reports why the parts do not form a + /// valid URI. + /// + /// Fails if a non-repeatable parameter (`amount`/`label`/`message`/`pop`) + /// was set more than once, or if a key or raw value would not round-trip. + /// The body and every `bc=`/`tb=` address must belong to `network`, so a + /// built URI never mixes networks - the same guarantee + /// [`Uri::require_network`] gives a parsed one. + pub fn build(self, network: bitcoin::Network) -> 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() })?; + } + } + + // The body and every HRP-keyed address must belong to `network`, so a + // checked URI never mixes networks and parses back unchanged. + if let Some(body) = &self.body { + if !body.as_unchecked().is_valid_for_network(network) { + return Err(BuildError::Network(NetworkError::NetworkMismatch)); + } + } + for entry in &self.entries { + if HRP_ADDRESS_KEYS.iter().any(|(hrp, _)| entry.base_key_eq(hrp)) { + let raw = entry.raw_value.as_deref().unwrap_or(""); + let address = raw + .parse::>() + .map_err(|_| BuildError::InvalidHrpValue { key: entry.key.clone() })?; + if !address.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(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(bitcoin::Network::Bitcoin).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(bitcoin::Network::Bitcoin).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(bitcoin::Network::Bitcoin) + .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(bitcoin::Network::Bitcoin) + .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(bitcoin::Network::Bitcoin) + .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(bitcoin::Network::Bitcoin).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(bitcoin::Network::Bitcoin); + 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(bitcoin::Network::Bitcoin); + 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(bitcoin::Network::Bitcoin); + assert!(matches!(result, Err(BuildError::InvalidKey(ref key)) if key == "a&b")); + + let result = UriBuilder::new().param("a=b", "x").build(bitcoin::Network::Bitcoin); + 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(bitcoin::Network::Bitcoin); + assert!(matches!(result, Err(BuildError::InvalidRawValue { ref key }) if key == "x")); + + let result = UriBuilder::new().raw_param("x", "%zz").build(bitcoin::Network::Bitcoin); + 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(bitcoin::Network::Bitcoin); + 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(bitcoin::Network::Bitcoin).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(bitcoin::Network::Bitcoin); + assert!(matches!(result, Err(BuildError::Network(_)))); + } + + #[test] + fn an_hrp_value_on_the_wrong_network_fails_to_build() { + // BIP 321's own invalid example: a testnet address under the `bc` key. + let result = UriBuilder::new().param("bc", BECH32_TESTNET).build(bitcoin::Network::Bitcoin); + assert!(matches!(result, Err(BuildError::Network(_)))); + } + + #[test] + fn the_extension_params_become_their_keys_with_encoded_values() { + let uri = UriBuilder::new() + .param("lightning", "ln bc") + .param("lno", "lno1") + .param("pay", "pay1") + .param("sp", "sp1") + .build(bitcoin::Network::Bitcoin) + .unwrap(); + assert_eq!(uri.get("lightning").unwrap().raw_value.as_deref(), Some("ln%20bc")); + assert_eq!(uri.get("lno").unwrap().raw_value.as_deref(), Some("lno1")); + assert_eq!(uri.get("pay").unwrap().raw_value.as_deref(), Some("pay1")); + assert_eq!(uri.get("sp").unwrap().raw_value.as_deref(), Some("sp1")); + } + + #[test] + fn a_duplicate_is_reported_before_an_hrp_check() { + // build() checks the non-repeat rule first, then HRP validity. + let result = UriBuilder::new() + .param("bc", BECH32_TESTNET) + .label("a") + .raw_param("label", "b") + .build(bitcoin::Network::Bitcoin); + assert!(matches!(result, Err(BuildError::DuplicateParameter(ref key)) if key == "label")); + } + + #[test] + fn built_output_reparses_to_identical_params() { + let built = UriBuilder::new() + .address(mainnet_body()) + .amount(bitcoin::Amount::from_sat(100_000)) + .label("Luke-Jr") + .param("bc", BECH32_MAINNET) + .param("lightning", "lnbc1invoice") + .param("extra", "a b") + .build(bitcoin::Network::Bitcoin) + .unwrap(); + + let reparsed = Uri::parse(&built.to_string()) + .unwrap() + .require_network(bitcoin::Network::Bitcoin) + .unwrap(); + + // Params are identical, in the same order and case. + let built_params: Vec<_> = 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(bitcoin::Network::Bitcoin) + .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(bitcoin::Network::Bitcoin).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(bitcoin::Network::Bitcoin).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(bitcoin::Network::Bitcoin); + 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..f57f637 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,178 @@ +//! Parse-time errors for [`crate::Uri`]. +//! +//! Only failures that must be known before a `Uri` can exist live here. +//! Anything else - including a non-UTF-8 or otherwise malformed value for a +//! param nobody asked for yet - is an access-time error on whichever typed +//! accessor needs 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 `?`), or an HRP-keyed address parameter, + /// failed to parse. + InvalidBodyAddress(bitcoin::address::ParseError), + /// 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::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::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=` 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. + 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 would not round-trip through a URI query string. + InvalidKey(String), + /// A raw parameter value would not round-trip through a URI query string. + 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=` HRP-keyed parameter's value is not a valid 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 body, or an HRP-keyed address, does not belong to the network + /// passed to [`crate::UriBuilder::build`]. A checked URI never mixes + /// networks, so building one with addresses on different networks fails + /// here. + 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..c4f1f31 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.85 (tracks `bitcoin` / rust-payjoin). #![cfg_attr(docsrs, feature(doc_cfg))] #![no_std] @@ -41,466 +26,853 @@ 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` re-emits a `Uri` with parameters in their +/// original order and case. [`Uri::source_str`] returns the exact string +/// that was parsed, when available, for byte-exact round-tripping. #[derive(Debug, Clone)] -pub struct Uri<'a, NetVal = bitcoin::address::NetworkChecked, Extras = NoExtras> +pub struct Uri +where + V: NetworkValidation, +{ + 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 - re-emission casing, [`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 - NetVal: NetworkValidation, + bitcoin::Address: PartialEq, { - /// The address provided in the URI. + 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. +/// +/// Only the two HRPs `bitcoin`'s own address types use today are handled; +/// a future address type's HRP can be added here without being a breaking +/// change to callers, since this list is an implementation detail. +pub(crate) const HRP_ADDRESS_KEYS: [(&str, bitcoin::Network); 2] = [("bc", bitcoin::Network::Bitcoin), ("tb", bitcoin::Network::Testnet)]; + +impl Uri { + /// Parses a `bitcoin:` URI per BIP 321. /// - /// This field is mandatory because the address is mandatory in BIP21. - pub address: bitcoin::Address, + /// 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=` parameter's value + /// must itself be a valid address belonging to the network its key + /// names - `bitcoin:?bc=tb1...` is rejected for exactly this reason, + /// per BIP 321's own invalid example. + /// + /// This does not check the body address, or any `bc=`/`tb=` 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()).is_some_and(|prefix| prefix.eq_ignore_ascii_case(SCHEME)) { + return Err(Error::InvalidScheme); + } + let rest = &s[SCHEME.len()..]; + + let (body_str, query) = match rest.find('?') { + Some(pos) => (&rest[..pos], Some(&rest[(pos + 1)..])), + None => (rest, None), + }; - /// Number of satoshis requested as payment. - pub amount: 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)?) + }; - /// The label of the address - e.g. name of the receiver. - pub label: 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, + }); + } + } - /// Message that describes the transaction to the user. - pub message: Option>, + Ok(Uri { + body, + params, + source: Some(s.to_owned()), + }) + } - /// Extra fields that can occur in a BIP21 URI. - pub extras: Extras, -} + /// `true` if the body address, and every `bc=`/`tb=` 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=` + /// parameter - is valid for `network`, and if so, marks it checked. /// - /// 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(), + /// 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()) } -} -impl Uri<'_, NetVal, T> { - /// Creates an URI with defaults. - /// - /// 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 { + /// 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` as `bitcoin:?`, with +/// parameters in their original order and key case. +/// +/// A parsed `Uri` re-emits byte-for-byte: the body is written verbatim from +/// the source (bech32 is case-sensitive, so an uppercase address survives the +/// round trip) and the parameters keep their original encoding. A `Uri` built +/// by hand has no source, so its body goes through the [`bitcoin::Address`] +/// `Display`, which is lowercase for `{}` and uppercase for the alternate +/// `{:#}` (QR alphanumeric mode). +impl fmt::Display for Uri { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let scheme = self + .source + .as_deref() + .and_then(|source| source.find(':').map(|end| &source[..=end])) + .unwrap_or("bitcoin:"); + write!(f, "{}", scheme)?; + if let Some(body) = &self.body { + // Re-emit the body exactly as parsed. bech32 is case-sensitive, so + // an uppercase address must survive the round trip (QR alphanumeric + // mode); the `Address` Display would lowercase it. A URI built by + // hand has no source, so it falls back to the `Address` Display. + match self.source.as_deref().filter(|_| !f.alternate()) { + Some(source) => { + let start = source.find(':').map_or(0, |colon| colon + 1); + let end = source[start..].find('?').map_or(source.len(), |pos| start + pos); + f.write_str(&source[start..end])?; + }, + None if f.alternate() => write!(f, "{:#}", body)?, + None => write!(f, "{}", body)?, + } } + 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) } -impl<'a> TryFrom> for String { - type Error = core::str::Utf8Error; +/// 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(()) +} - 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()), - } - } +/// Validates a `bc=`/`tb=`-style HRP-keyed address parameter: its value must +/// itself be a valid address belonging to `network`. +/// +/// 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 address = raw_value + .parse::>() + .map_err(Error::InvalidBodyAddress)?; + address.require_network(network).map(|_| ()).map_err(Error::InvalidBodyAddress) } -impl<'a> TryFrom> for Cow<'a, str> { - 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) => 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 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); } } -} -#[derive(Debug, Clone)] -enum ParamInner<'a> { - EncodedBorrowed(PercentDecode<'a>), - UnencodedBytes(Cow<'a, [u8]>), - UnencodedString(Cow<'a, str>), -} + #[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); + } + } -/// 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 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); + } -/// 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 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"); + } -#[cfg(feature = "non-compliant-bytes")] -type ParamIterInner<'a, T> = either::Either, T>; + #[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(_))); + } -/// 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 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")); + } -/// This is a state used to deserialize `NoExtras` - it doesn't expect any parameters. -#[derive(Debug, Default, Copy, Clone)] -pub struct EmptyState; + #[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"); + } -impl DeserializeParams<'_> for NoExtras { - type DeserializationState = EmptyState; -} + #[test] + fn an_unknown_param_parses_with_no_error() { + let input = alloc::format!("bitcoin:{}?unknown=x", LEGACY_MAINNET); + assert!(Uri::parse(&input).is_ok()); + } -impl DeserializationError for NoExtras { - type Error = core::convert::Infallible; -} + #[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"); + } -impl DeserializationState<'_> for EmptyState { - type Value = NoExtras; + #[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); + } - fn is_param_known(&self, _key: &str) -> bool { - false + #[test] + fn a_string_shorter_than_the_scheme_has_an_invalid_scheme() { + assert!(matches!(Uri::parse("bitcoin"), Err(Error::InvalidScheme))); } - fn deserialize_temp(&mut self, _key: &str, _value: Param<'_>) -> Result::Error> { - Ok(de::ParamKind::Unknown) + #[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); } - fn finalize(self) -> Result::Error> { - Ok(Default::default()) + #[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), + } } -} -impl SerializeParams for &NoExtras { - type Key = core::convert::Infallible; - type Value = core::convert::Infallible; - type Iterator = core::iter::Empty<(Self::Key, Self::Value)>; + #[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()); + } - fn serialize_params(self) -> Self::Iterator { - core::iter::empty() + #[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)); } -} -#[cfg(test)] -mod tests { - use crate::Uri; - use alloc::string::ToString; - use alloc::borrow::Cow; - use core::convert::TryInto; + #[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()); + } - fn check_send_sync() {} + #[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)); + } #[test] - fn send_sync() { - check_send_sync::(); + 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()); } - // Note: the official test vectors contained an invalid address so it was replaced with the address of Andreas Antonopoulos. + #[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()); + } #[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 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()); + } - assert_eq!(uri.to_string(), input); + #[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()); } #[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 network_error_display_message_is_specific() { + assert_eq!( + NetworkError::NetworkMismatch.to_string(), + "the URI is not valid for the requested network" + ); + } - assert_eq!(uri.to_string(), input); + #[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()); } - #[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 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"]); + } - assert_eq!(uri.to_string(), input); + #[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); } - #[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 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); + } - assert_eq!(uri.to_string(), input); + #[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 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"]); } #[test] - fn required_not_understood() { - let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?req-somethingyoudontunderstand=50&req-somethingelseyoudontget=999"; - let uri = input.parse::>(); - assert!(uri.is_err()); + 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 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 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(), "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd"); + #[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())); } #[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 uppercase_bech32_body_survives_the_round_trip() { + // bech32 is case-sensitive for QR alphanumeric mode, so an uppercase + // body must re-emit verbatim rather than being lowercased by the + // `Address` Display. The #10 test uses base58, which hid this. + 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 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 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); + } - assert_eq!(uri.to_string(), input); + #[test] + 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(bitcoin::Network::Bitcoin).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); } #[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"); + #[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 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 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(bitcoin::Network::Bitcoin).unwrap(); + assert_eq!(alloc::format!("{}", uri), alloc::format!("bitcoin:{}", BECH32_MAINNET)); + assert_eq!(alloc::format!("{:#}", uri), alloc::format!("bitcoin:{}", BECH32_MAINNET.to_uppercase())); } #[test] - fn bad_unicode_scheme() { - let input = "bitcoinö:1andreas3batLhQa2FawWjeyjCqyBzypd"; - let uri = input.parse::>(); - assert!(uri.is_err()); + 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 duplicate_params() { - let duplicate_label = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=foo&label=bar"; - let uri = duplicate_label.parse::>(); - assert!(uri.is_err()); + 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"); + } - let duplicate_amount = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?amount=123&amount=456"; - let uri = duplicate_amount.parse::>(); - assert!(uri.is_err()); + #[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()); + } - let duplicate_message = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?message=foo&message=bar"; - let uri = duplicate_message.parse::>(); - assert!(uri.is_err()); + #[test] + 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 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 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 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"); + } + + #[test] + fn pop_is_none_when_absent() { + let uri = Uri::parse("bitcoin:?label=Luke-Jr").unwrap(); + assert!(uri.pop().is_none()); + } + + #[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..3b626ee --- /dev/null +++ b/src/params.rs @@ -0,0 +1,218 @@ +//! 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` matches this entry's key ASCII-case-insensitively. + /// + /// BIP 321 keys are case-insensitive; this is the single place that + /// comparison happens so every lookup agrees on it. + pub(crate) fn key_eq(&self, key: &str) -> bool { + self.key.eq_ignore_ascii_case(key) + } + + /// `true` if `key` matches this entry's base key case-insensitively. + /// + /// A required key such as `req-pj` has base key `pj`; plain keys use the + /// key itself. A full-key match is also accepted for callers that already + /// include the prefix. + pub(crate) fn base_key_eq(&self, key: &str) -> bool { + self.key_eq(key) || self.requirement().is_some_and(|requirement| requirement.eq_ignore_ascii_case(key)) + } + + /// The requirement key if this is a `req-` parameter, otherwise `None`. + /// + /// BIP 321's `reqparam = "req-" otherparam`: 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 + /// [`Uri::unsatisfied_requirements`](crate::Uri::unsatisfied_requirements) + /// compares against the keys a client 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` case-insensitively. + 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` 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 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(()) - } -}