Skip to content

0.2: BIP 321-shaped parser core, and make the body address optional #12

Closed

Description

@DanGould

bitcoin_uri 0.1.0 was published in December 2024 and has not been updated since. Meanwhile every wallet integrating payjoin runs two parsers over one URI string, and the bugs that produces are consistent across implementations: + decoded as a space, endpoints lost on reparse, and payjoin parameters emitted by string concatenation rather than by a serializer.

0.2 is the release that will make this crate the single parser. It accepts BIP 321 shape in time now. This issue is the scope. It also answers the composability question I opened in Kixunil/bip21#22and the "BIP 21 crate that exposes a list of payment instructions" thread in rust-bitcoin/rust-bitcoin#5715. That list now lives in bitcoin-payment-instructions, and this crate is meant to fit as a dependency of that.

Why now

BIP 321's rule is that a new address type rides its own query parameter, not the body. A silent payment URI is therefore body-less:

bitcoin:?sp=sp1q…&pj=…

Uri.address is a required field today (src/lib.rs:90), so that string cannot parse at all.

Data model

Owned types. No lifetime parameter, no Extras type parameter. The shape is chosen to flatten through uniffi: the wallets this is for consume it from Dart, C#, Kotlin, and Swift, not from Rust, so anything that does not survive a bindings boundary is not in the core.

pub struct Uri<V: NetworkValidation = NetworkChecked> {
    body: Option<Address<V>>,   // BIP 321: MAY be empty
    params: Params,             // ordered multimap of raw entries
    source: Option<String>,     // exact input when constructed by parsing
}

pub struct ParamEntry {
    key: String,                // original case
    raw_value: Option<String>,  // still percent-encoded; None for value-less params
}

Values stay percent-encoded until accessed. Decoding is RFC 3986 and nothing else: + is a literal plus, never a space. That one rule, enforced in one place, is the fix for the +/space corruption wallets currently work around by hand. Value-less params are legal (otherparam = qchar *qchar [ "=" *qchar ]). Keys match case-insensitively and original case is preserved for re-emission. amount, label, message, and pop may not repeat; any other key may, and every occurrence is kept in order.

Typed accessors over the multimap: amount(), label(), message(), pop(), get(base_key), get_all(base_key), params(). get and get_all match req-pj as well as pj, since req- is only a prefix. Every entry has a public decoded_value(), and the typed accessors use it, so an extension reading pj or sp gets decoded text from this crate and only parses it.

Payment instructions

This crate doesn't list payment instructions. A wallet reads the body with body() and each instruction it supports with get_all(key), then hands the value to the crate that owns that key (see below). Which keys count as instructions is for the wallet, or bitcoin-payment-instructions, to decide. So is BIP 321's rule that a body-less URI needs at least one instruction, because a fixed list here would reject URIs carrying newer keys like ark. A list method can be added later without a breaking change.

This crate does not decode invoices, offers, or silent payment keys, and it does not depend on LDK or any silent payments crate. That is deliberate. It keeps the crate no_std with a small dependency tree, and it is what makes it usable underneath bitcoin-payment-instructions, BIP 321's reference implementation, which decodes and resolves. This crate tokenizes while that one interprets and lists. This lets the two compose and complement one another.

Extensions compose as functions over data

0.1 inherited bip21's generic Extras parameter with a serde-style DeserializationState. Composing two extensions meant hand-writing a combined state, and a bad pj failed the whole URI, which is why Cove parses every string twice. I propose 0.2 replaces the trait machinery with a fallible function over the parsed params, owned by whichever crate defines the parameter:

// in the payjoin crate
impl PjParam {
    pub fn from_uri(uri: &bitcoin_uri::Uri<impl NetworkValidation>) -> Result<Option<Self>, PjParseError>;
}

Any number of these run over one parsed Uri. A wallet supporting payjoin, lightning, and silent payments calls three of them; none knows about the others. How the instructions interact once decoded is the wallet's policy, on top of independently decoded params. No trait, no macros: almost every consumer of this crate reaches it through uniffi bindings, where a trait would not be visible anyway.

Where the function lives: in the crate that owns the parameter, behind an optional bitcoin_uri feature, the same way types implement serde traits in their own crate. Producing needs no dependency at all, since UriBuilder takes strings. This crate never learns what a pj or sp value means.

req- handling

The parser cannot know what the caller understands, so it does not reject unknown req- keys itself. uri.unsatisfied_requirements(understood) returns the req- entries nobody claimed, behind a #[must_use] guard. Each extension contributes the keys it handled. If the list is non-empty the wallet must treat the URI as invalid, per BIP 321.

Builder

UriBuilder with address, amount, label, message, param(key, value), param(key, value), raw_param(key, pre_encoded), and build(network). Encoding follows the BIP 21/321 qchar set, and build rejects a key or raw value outside it. build checks the body and every HRP-keyed address against network the same way require_network does, so a checked Uri never mixes networks. This replaces string-concatenated pj= in wallets.

Round-trip

Display re-emits a parsed URI exactly as it was parsed, uppercase bech32 body included, and a built one with entries in order and encoded values intact. source_str() returns the exact parsed input. Byte-exactness matters because uppercase URIs fit QR alphanumeric mode. Closes #10.

Network

require_network checks the body and the HRP-keyed params, req- prefixed ones included (bc=tb1… is one of BIP 321's invalid examples, and req-bc=tb1… is just as invalid). is_valid_for_network for multi-network wallets. assume_checked as today. A network mismatch is a NetworkError, separate from parse errors.

Errors

Parse-time: InvalidScheme, InvalidBodyAddress, InvalidAmount, DuplicateParameter, InvalidPercentEncoding. Everything else, including a non-UTF-8 value, is an access-time error on the accessor that needs it. The non-compliant-bytes feature goes away. std::error::Error is implemented on every error type (closes #6).

Breaking changes

  • Body address becomes optional.
  • The 'a lifetime, the Extras type parameter, DeserializeParams, DeserializationState, SerializeParams, and Param are removed.
  • The non-compliant-bytes feature is removed.
  • MSRV moves to 1.85 and bitcoin to match rust-payjoin.

0.1 stays published. Migration for an existing Extras impl is to write a from_uri function.

Acceptance

  • BIP 321's valid example URIs parse and the invalid ones are rejected, including bitcoin:?sp=…, bitcoin:?lno=…&sp=…, the bc=/tb= cases, the duplicate label/amount/pop cases, and bitcoin:?bc=tb1…
  • Existing body-address BIP 21 URIs parse unchanged
  • A + inside a pj value survives parse and re-emission unchanged
  • A value-less param parses
  • bitcoin:?unknown=x parses
  • Unknown req- keys surface through unsatisfied_requirements, and the test in no test coverage for required parameters #7 exists
  • The round-trip test from Bitcoin-uri fuzzing crash #10 passes
  • UriBuilder emits a URI that parses back to the same body and params
  • UriBuilder rejects a key or raw value outside qchar, and a body and HRP address on different networks
  • get("sp") finds req-sp=…, and bitcoin:?req-bc=tb1… is rejected the same way bitcoin:?bc=tb1… is
  • Display of an uppercase bech32 URI is byte-identical to the input
  • examples/ reads pj, sp with pj, and lightning from outside the crate using get and decoded_value, with no code for those instruction types in this crate
  • A branch of bitcoin-payment-instructions replaces its own URI tokenizing and percent-decoding with this crate, and its tests pass. It doesn't need to be merged or even have a PR open, but this proves the design.
  • CHANGELOG lists every breaking change above

Related

Subsumes #8 (the multimap is the tokenizer/handler split proposed there), #7, #6, #10. #11 stays out of scope: amount bounds are the wallet's concern.

This release on its own fixes Rust consumers, of which there are few. The deliverable that fixes wallets is the bindings surface built on it, tracked in payjoin/rust-payjoin#1867: payjoin-ffi's Uri gains the full parser API, since every wallet in question already loads that library. A standalone bitcoin-uri-ffi waits until a wallet that does not use payjoin asks for one.

Activity

  1. caarloshenriq commented on Sep 30, 2026

    @caarloshenriq

    Been chipping away at the acceptance checklist here with a few small, independent, non-breaking pieces on top of the current 0.1 architecture — three PRs open so far: #13 (percent-encoding + case-insensitive key matching), #14 (unsatisfied_requirements() + parse_permissive), and #15 (req- coverage for #7).

    That's about as far as I can go without the 0.2 rewrite itself, since the remaining acceptance items (valid/invalid BIP 321 parsing, value-less params, instructions(), the #10 round-trip, UriBuilder) all need the new owned data model, not something that can be layered on 0.1 without breaking it. A couple of questions before I start on that:

    1. Sequencing. The design above covers a lot of ground in one issue (data model, multimap, instructions(), extensions-as-functions, unsatisfied_requirements, UriBuilder, round-trip, errors). Do you want this as one PR, or would staged pieces (e.g. core data model + multimap first, then instructions()/UriBuilder on top) be easier to review?

    2. unsatisfied_requirements() signature. Add unsatisfied_requirements() for unclaimed req- params #14 shipped Uri::unsatisfied_requirements() with no argument, since in the current 0.1 architecture "understood" is already resolved during parsing by whichever Extras implementation the caller supplied. The design above calls for unsatisfied_requirements(understood) instead, taking the understood keys explicitly, which fits the function-based extensions replacing Extras/DeserializationState. Should I treat Add unsatisfied_requirements() for unclaimed req- params #14's version as throwaway scaffolding that 0.2 replaces outright, or would it help to reshape it toward the (understood: &[...]) signature now, ahead of the rest of the rewrite?

    3. Should I start on the 0.2 rewrite now (even staged, on its own branch), or would you rather I hold off until the three open PRs get a look first?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions