forked from payjoin/bitcoin_uri
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathde.rs
More file actions
371 lines (331 loc) · 14 KB
/
Copy pathde.rs
File metadata and controls
371 lines (331 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
//! 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<Self, Error<T::Error>> {
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<NetVal: NetworkValidation, T> 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<ParamKind, <Self::Value as DeserializationError>::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<ParamKind, <Self::Value as DeserializationError>::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<Self::Value, <Self::Value as DeserializationError>::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<T> {
/// 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<T> Error<T> {
fn uri<U: Into<UriErrorInner>>(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<T: fmt::Display> fmt::Display for Error<T> {
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<T: fmt::Display + std::error::Error + 'static> std::error::Error for Error<T> {
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<AddressError> for UriErrorInner {
fn from(value: AddressError) -> Self {
UriErrorInner::Address(value)
}
}
impl From<ParseAmountError> 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<T: for<'de> DeserializeParams<'de>> core::str::FromStr for Uri<'_, bitcoin::address::NetworkUnchecked, T> {
type Err = Error<T::Error>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
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<T::Error>;
fn try_from(s: &'a str) -> Result<Self, Self::Error> {
Self::deserialize_raw(s)
}
}
/// **Warning**: this implementation may needlessly allocate, consider using `TryFrom<&str>` instead.
impl<T: for<'de> DeserializeParams<'de>> TryFrom<String> for Uri<'_, bitcoin::address::NetworkUnchecked, T> {
type Error = Error<T::Error>;
fn try_from(s: String) -> Result<Self, Self::Error> {
s.parse()
}
}
/// **Warning**: this implementation may needlessly allocate, consider using `TryFrom<&str>` instead.
impl<'a, T: for<'de> DeserializeParams<'de>> TryFrom<Cow<'a, str>> for Uri<'a, bitcoin::address::NetworkUnchecked, T> {
type Error = Error<T::Error>;
fn try_from(s: Cow<'a, str>) -> Result<Self, Self::Error> {
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<Uri<'a, bitcoin::address::NetworkChecked, T>, Error<T::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,
}
}
}