Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,5 @@ jobs:
run: cargo update -p cc --precise 1.1.31
- name: Test
run: cargo test
- name: Test with all features
run: cargo test --all-features
80 changes: 42 additions & 38 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,51 +1,55 @@
# bitcoin_uri Changelog

## Unreleased
## 0.2.0

0.2 parses BIP 321, the successor to BIP 21, and replaces the 0.1 API. `Uri`
is owned, an extension reads its parameters off the parsed URI instead of
plugging an `Extras` type into the parser, and `UriBuilder` assembles new
URIs.

### Breaking changes

- MSRV is 1.63, now declared in `rust-version`, and `bitcoin` must be at
least 0.32.102. 1.63 matches `bitcoin-payment-instructions`, which this
crate is meant to be a dependency of.
- The body address is now optional, so a body-less URI such as
`bitcoin:?sp=...` parses. `Uri::body` returns `Option<&Address<V>>`.
- `Uri` is now owned and has no lifetime parameter: `Uri<V>` instead of
- A URI with a `req-` parameter the caller does not understand now parses.
0.1 rejected it at parse time. Pass the keys you handle to
`Uri::unsatisfied_requirements` and reject the URI if it returns anything.
- `Uri` is owned and has no lifetime parameter: `Uri<V>` 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.
- `Uri`'s public fields, `Uri::new` and `Uri::with_extras` are gone. Read a
parsed URI with `body`, `amount`, `label`, `message`, `pop`, `get` and
`get_all`, and assemble one with `UriBuilder`.
- The body address is optional, so a body-less URI such as
`bitcoin:?sp=...` parses. `Uri::body` returns `Option<&Address<V>>`.
- Removed the `de` and `ser` modules along with `DeserializeParams`,
`DeserializationState`, `DeserializationError`, `SerializeParams`,
`Param`, `ParamKind` and `NoExtras`. Parse failures are a single `Error`
enum instead of `de::Error` and `UriError`.
- 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.
dependency. A value whose decoded bytes are not UTF-8 fails with
`AccessError` when an accessor reads it, not at parse time.
- Parameter keys match case-insensitively, as BIP 321 requires, so
`LABEL=` is the label.
- A `bc`/`tb`/`bcrt` parameter must be a segwit address of the network its
key names, or parsing fails with `Error::InvalidHrpValue`.
- `Uri::require_network` checks those parameters as well as the body, and
fails with `NetworkError`.
- `Display` of a parsed `Uri` writes back the exact string it was parsed
from. `{:#}` still writes the QR form, with an uppercase body.
- `bitcoin` must be at least 0.32.102. The MSRV is still 1.63 and is now
declared in `rust-version`.

### Added

- `Params`/`ParamEntry`: an ordered, case-insensitive multimap of the raw
query parameters, preserving source order and percent-encoding, with
`ParamEntry::decoded_value` for on-demand RFC 3986 decoding.
- `AccessError`, returned when a value is read: its percent-decoded bytes
may not be valid UTF-8.
- Parse-time `Error`, separate from `AccessError`. Invalid
percent-encoding in any value fails the parse; a value that decodes to
bytes that are not UTF-8 fails only when it is read.
- `Uri::require_network`/`is_valid_for_network` over the body and the
`bc`/`tb`/`bcrt` parameters. A value under one of those keys must be a
segwit address of the key's network, or parsing fails with
`Error::InvalidHrpValue`.
- `NetworkError`, kept separate from the parse `Error`.
- `Uri::unsatisfied_requirements`, reporting the `req-` parameters a client
does not understand, plus `ParamEntry::requirement`/`is_required`.
- An `extension_params` example showing a consumer reading `pj`/`sp`/
`lightning` off a parsed URI with `get` + `decoded_value`.
- `Display` of a parsed `Uri` writes back the exact string it was parsed
from, and `Uri::source_str` returns it.
- `UriBuilder`, assembling a `Uri` from typed parts. Its output parses back
to the same parameters: keys and raw values must be RFC 3986 query
characters, and `build` checks each `bc`/`tb`/`bcrt` address against the
network its key names and the body against that network, rejecting a
URI that mixes networks.
- `BuildError`, wrapping `NetworkError` for build-time network mismatch.
- `Params` and `ParamEntry`, the query parameters in source order and
still percent-encoded. `ParamEntry::decoded_value` decodes a value on
demand.
- `Uri::unsatisfied_requirements`, `ParamEntry::requirement` and
`ParamEntry::is_required`.
- `Uri::is_valid_for_network`, `Uri::pop` and `Uri::source_str`.
- `UriBuilder` and `BuildError`. A built URI parses back to the same
parameters. Keys and raw values must be RFC 3986 query characters, keys
may not contain `%`, and `build` rejects a URI that mixes networks.
- An `extension_params` example that reads `pj`, `sp` and `lightning` off a
parsed URI.

## 0.1.0

Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ rust-version = "1.63"
description = "Rust-idiomatic, compliant, flexible and performant bitcoin URI crate."
repository = "https://github.com/payjoin/bitcoin_uri"
readme = "README.md"
keywords = ["bitcoin", "bip21", "parsing", "newtypes"]
keywords = ["bitcoin", "bip21", "bip321", "parsing", "newtypes"]
categories = ["cryptography::cryptocurrencies", "encoding", "rust-patterns", "value-formatting"]
license = "MITNFA"

Expand Down
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ Rust-idiomatic, compliant, flexible and performant bitcoin URI crate.

## About

**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.
0.2 replaces the 0.1 API. [CHANGELOG.md](CHANGELOG.md) lists what changed
for a 0.1 user.

* Rust-idiomatic: owned types, no lifetime parameter.
* Compliant: parses the full BIP 321 shape, including a body-less URI, and
Expand Down
6 changes: 4 additions & 2 deletions examples/extension_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ fn main() {
}

// 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`.
// does not understand means it MUST reject the URI. Here it handles `pj`,
// `sp` and `lightning` but not, say, a hypothetical `req-foo`. A wallet
// that also acts on `amount` or `label` lists them too, or it rejects
// `req-amount`.
let understood = ["pj", "sp", "lightning"];
let unsatisfied = uri.unsatisfied_requirements(&understood).count();
assert_eq!(unsatisfied, 0, "every required extension is understood");
Expand Down
32 changes: 22 additions & 10 deletions src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,13 @@ fn is_qchars(s: &str) -> bool {

/// BIP 321 has `otherparam = qchar *qchar ...` and `reqparam = "req-" qchar
/// *qchar ...`, so a key and its base key are both non-empty.
///
/// A key may not contain `%`. Parsing matches keys literally, so
/// `%61mount` is an unknown key and not `amount`, but RFC 3986 makes the two
/// equivalent and a reader that decodes keys would see `amount`. Never
/// emitting an escape in a key keeps every reader on the same meaning.
fn key_round_trips(key: &str) -> bool {
is_qchars(key) && !params::base_key(key).is_empty()
is_qchars(key) && !key.contains('%') && !params::base_key(key).is_empty()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense for the builder. On the parse side, Uri::parse still takes %61mount=1 as an unknown key, so this crate ignores it while a reader that decodes keys sees an amount. Rejecting it at parse time would probably go against BIP 321’s grammar, but a line in the parse docs, like the new one about #, would tell consumers about that divergence. Not blocking.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please feel free to pr as a follow-up since this can be in a patch release

}

fn raw_value_round_trips(value: &str) -> bool {
Expand Down Expand Up @@ -142,8 +147,8 @@ impl UriBuilder {
/// network its key names, which [`build`](Self::build) checks, so the
/// built URI parses back. The value is treated as decoded text and
/// encoded for you. The key is used as given. It must be non-empty, not a
/// bare `req-`, and made of RFC 3986 query characters other than `&` and
/// `=`, with valid `%` escapes.
/// bare `req-`, and made of RFC 3986 query characters other than `&`, `=`
/// and `%`.
pub fn param(mut self, key: &str, value: &str) -> Self {
self.push(key, encode(value));
self
Expand All @@ -163,9 +168,10 @@ impl UriBuilder {

/// Finishes building, or reports why the parts do not form a valid URI.
///
/// Fails if a key is empty or a bare `req-`, if a key or raw value is not
/// made of RFC 3986 query characters other than `&` and `=` with valid `%`
/// escapes, if a non-repeatable parameter
/// Fails if a key is empty, is a bare `req-`, or is not made of RFC 3986
/// query characters other than `&`, `=` and `%`. Fails if a raw value is
/// not made of RFC 3986 query characters other than `&` and `=`, with
/// valid `%` escapes. Fails if a non-repeatable parameter
/// (`amount`/`label`/`message`/`pop`) was set more than once, or if an
/// `amount` does not parse.
///
Expand Down Expand Up @@ -325,6 +331,15 @@ mod tests {
assert!(matches!(result, Err(BuildError::InvalidKey(ref key)) if key == "a=b"));
}

#[test]
fn percent_encoded_keys_fail_to_build() {
let result = UriBuilder::new().raw_param("%61mount", "1").build();
assert!(matches!(result, Err(BuildError::InvalidKey(ref key)) if key == "%61mount"));

let result = UriBuilder::new().param("req-%70j", "x").build();
assert!(matches!(result, Err(BuildError::InvalidKey(ref key)) if key == "req-%70j"));
}

#[test]
fn raw_values_that_would_not_round_trip_fail_to_build() {
let result = UriBuilder::new().raw_param("x", "a&b").build();
Expand Down Expand Up @@ -454,10 +469,7 @@ mod tests {
result
);
}
let built = UriBuilder::new()
.raw_param("k-._~!$'()*+,;:@/?%41", "-._~!$'()*+,;:@/?%41")
.build()
.unwrap();
let built = UriBuilder::new().raw_param("k-._~!$'()*+,;:@/?", "-._~!$'()*+,;:@/?%41").build().unwrap();
assert_eq!(Uri::parse(&built.to_string()).unwrap().assume_checked(), built);
}

Expand Down
4 changes: 2 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ impl std::error::Error for AccessError {
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum BuildError {
/// A parameter key is empty, is a bare `req-`, is not made of RFC 3986
/// query characters other than `&` and `=`, or has an invalid `%` escape.
/// A parameter key is empty, is a bare `req-`, or is not made of RFC 3986
/// query characters other than `&`, `=` and `%`.
InvalidKey(String),
/// A raw parameter value is not made of RFC 3986 query characters other
/// than `&` and `=`, or has an invalid `%` escape.
Expand Down
11 changes: 11 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@ impl Uri<bitcoin::address::NetworkUnchecked> {
/// value must be a segwit address of the network its key names. BIP 321's
/// invalid example `bitcoin:?bc=tb1...` fails this check.
///
/// The parameters end at the first `#` after the `?`, as an RFC 3986
/// query does, and the fragment after it is ignored. A value containing
/// `#`, such as a `pj` URL with a fragment, must encode it as `%23`.
/// Otherwise that value is cut short and every parameter after it is
/// dropped without an error.
///
/// This does not check the body address, or any HRP-keyed parameter,
/// against a *specific* network - that is [`Uri::require_network`]'s
/// job. A `tb1...` body address and a `bc=`-keyed mainnet address can
Expand Down Expand Up @@ -297,6 +303,11 @@ impl<V: NetworkValidation> Uri<V> {
/// is absent from it is returned. An empty iterator means the URI is safe
/// to act on.
///
/// That includes the keys this crate parses itself (`amount`, `label`,
/// `message`, `pop`, `bc`, `tb`, `bcrt`). Parsing a value does not mean
/// the caller acts on it, so a caller that honors `req-amount` lists
/// `"amount"` too.
///
/// 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.
Expand Down
Loading