Skip to content
Closed
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
36 changes: 31 additions & 5 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,26 @@ impl<'a, T: DeserializeParams<'a>> Uri<'a, bitcoin::address::NetworkUnchecked, T
.ok_or_else(|| Error::Uri(UriError(UriErrorInner::MissingEquals(param.to_owned()))))?;
let key = &param[..pos];
let value = &param[(pos + 1)..];
match key {
// BIP 21 / BIP 321 keys are case-insensitive. QR codes in
// alphanumeric mode are uppercase-only, so wallets do scan
// URIs shaped like `?AMOUNT=1&PJ=...`; matching `key`
// verbatim silently drops every parameter in that shape
// instead of erroring. Extras get the lowercased key too, so
// an `Extras` impl matching "pj"/"pjos" literally does not
// need its own case handling to see "PJ"/"PJOS".
//
// The common case is already-lowercase input, so only
// allocate when `key` actually contains an uppercase ASCII
// byte; that keeps the zero-copy `deserialize_borrowed` path
// for the common case instead of always paying for a clone
// via `deserialize_temp`.
let lower_key = if key.bytes().any(|b| b.is_ascii_uppercase()) {
Some(key.to_ascii_lowercase())
} else {
None
};
let matched_key = lower_key.as_deref().unwrap_or(key);
match matched_key {
"amount" => {
if amount.is_some() {
return Err(Error::Uri(UriError(UriErrorInner::DuplicateParameter(key.to_owned()))));
Expand All @@ -80,11 +99,18 @@ impl<'a, T: DeserializeParams<'a>> Uri<'a, bitcoin::address::NetworkUnchecked, T
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 is_known = match &lower_key {
// Not borrowed from the source string, so this
// must go through `deserialize_temp` rather than
// `deserialize_borrowed` (which requires a `key`
// borrowed for `'de`).
Some(lower_key) => deserializer.deserialize_temp(lower_key, decoder).map_err(Error::Extras)?,
None => deserializer.deserialize_borrowed(key, decoder).map_err(Error::Extras)?,
};
if is_known == ParamKind::Unknown && matched_key.starts_with("req-") {
return Err(Error::Uri(UriError(UriErrorInner::UnknownRequiredParameter(key.to_owned()))));
}
},
}
Expand Down
104 changes: 103 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,8 @@ impl SerializeParams for &NoExtras {

#[cfg(test)]
mod tests {
use crate::Uri;
use crate::{de, Param, Uri};
use crate::de::{DeserializationError, DeserializationState, DeserializeParams};
use alloc::string::ToString;
use alloc::borrow::Cow;
use core::convert::TryInto;
Expand Down Expand Up @@ -503,4 +504,105 @@ mod tests {
let uri = duplicate_message.parse::<Uri<'_, _>>();
assert!(uri.is_err());
}

#[test]
fn a_literal_plus_round_trips_as_percent_2b() {
// `a%2Bb` decodes to the literal string "a+b" (RFC 3986: '+' is not
// special). Re-serializing must escape that '+' back to `%2B`, or a
// reader that treats '+' as a space (the application/x-www-form-
// urlencoded convention, which many BIP21 wallets mistakenly apply)
// will see "a b" instead.
let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=a%2Bb";
let uri = input.parse::<Uri<'_, _>>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap();
let label: alloc::borrow::Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap();
assert_eq!(label, "a+b");
assert_eq!(uri.to_string(), input);
}

#[test]
fn a_bare_plus_in_input_is_never_treated_as_a_space() {
// A literal, unencoded '+' in the input must decode to '+', never to
// a space, and must round-trip as `%2B` per the previous test.
let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=a+b";
let uri = input.parse::<Uri<'_, _>>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap();
let label: alloc::borrow::Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap();
assert_eq!(label, "a+b");
assert_eq!(uri.to_string(), "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=a%2Bb");
}

/// A minimal `Extras` that only knows the lowercase key `pj`, the same
/// way a real extension (such as payjoin's `PayjoinExtras`) matches its
/// own parameter names. It exists to prove that case-insensitive
/// matching for known top-level keys and `req-` does not require any
/// change on the `Extras` implementor's side: `bitcoin_uri` already
/// normalizes the key it hands to `deserialize_temp`/`deserialize_borrowed`.
#[derive(Debug, Default, Clone)]
struct PjLike {
pj: Option<alloc::string::String>,
}

impl DeserializationError for PjLike {
type Error = core::convert::Infallible;
}

impl DeserializeParams<'_> for PjLike {
type DeserializationState = PjLikeState;
}

#[derive(Debug, Default, Clone)]
struct PjLikeState {
pj: Option<alloc::string::String>,
}

impl DeserializationState<'_> for PjLikeState {
type Value = PjLike;

fn is_param_known(&self, key: &str) -> bool {
key == "pj"
}

fn deserialize_temp(&mut self, key: &str, value: Param<'_>) -> Result<de::ParamKind, core::convert::Infallible> {
if key == "pj" {
let value: alloc::string::String = value.try_into().unwrap();
self.pj = Some(value);
Ok(de::ParamKind::Known)
} else {
Ok(de::ParamKind::Unknown)
}
}

fn finalize(self) -> Result<Self::Value, core::convert::Infallible> {
Ok(PjLike { pj: self.pj })
}
}

#[test]
fn an_uppercase_known_extra_param_is_still_recognized() {
// A QR code in alphanumeric mode is uppercase-only, so wallets do
// scan URIs shaped like this. Before the fix, `PJ` did not match the
// lowercase-only `PjLike` extras and was silently dropped, with no
// error and no indication the payjoin parameter was ever there.
//
// Bech32 (BIP 173) is defined to accept an address in all-uppercase
// form; legacy base58 addresses are not (base58 is case-sensitive,
// so uppercasing one breaks its checksum), which is why this uses a
// bech32 address rather than the base58 one the other tests share.
let input = "BITCOIN:BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4?PJ=HTTPS://EXAMPLE.COM";
let uri = input
.parse::<Uri<'_, _, PjLike>>()
.unwrap()
.require_network(bitcoin::Network::Bitcoin)
.unwrap();
assert_eq!(uri.extras.pj.as_deref(), Some("HTTPS://EXAMPLE.COM"));
}

#[test]
fn an_uppercase_unclaimed_req_key_is_still_rejected() {
// Lowercase `req-` is already rejected by `required_not_understood`
// above; this is the same guarantee for the uppercase shape a QR
// code in alphanumeric mode produces.
let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?REQ-SOMETHINGYOUDONTUNDERSTAND=50";
let uri = input.parse::<Uri<'_, _, PjLike>>();
assert!(uri.is_err());
}
}
11 changes: 9 additions & 2 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,21 +79,28 @@ impl<W: fmt::Write> fmt::Write for EqSignChecker<'_, W> {
/// > sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/// > / "*" / "+" / "," / ";" / "="
/// > ```
///
/// `+` is a `sub-delim` and would be legal unescaped, but is percent-encoded
/// here anyway: see the comment on `.remove(b'+')`'s absence below.
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 "=")
// separators ("&", and "=") and excluding '+': RFC 3986 permits a
// literal '+' unescaped in a query, but many BIP21 readers apply the
// application/x-www-form-urlencoded convention where '+' decodes to a
// space. Always percent-encoding '+' as %2B keeps re-emitted URIs safe
// for those readers even though this crate itself never does that
// decoding.
.remove(b'!')
.remove(b'$')
.remove(b'\'')
.remove(b'(')
.remove(b')')
.remove(b'*')
.remove(b'+')
.remove(b',')
.remove(b';')
// allow pchar extra chars
Expand Down