forked from payjoin/rust-payjoin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.rs
More file actions
405 lines (365 loc) · 14.7 KB
/
Copy patherror.rs
File metadata and controls
405 lines (365 loc) · 14.7 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use std::{error, fmt};
use crate::error_codes::ErrorCode::{
self, NotEnoughMoney, OriginalPsbtRejected, Unavailable, VersionUnsupported,
};
/// The top-level error type for the payjoin receiver
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
/// Errors that can be replied to the sender
ReplyToSender(ReplyableError),
#[cfg(feature = "v2")]
/// V2-specific errors that are infeasable to reply to the sender
V2(crate::receive::v2::SessionError),
}
impl From<ReplyableError> for Error {
fn from(e: ReplyableError) -> Self { Error::ReplyToSender(e) }
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::ReplyToSender(e) => write!(f, "replyable error: {e}"),
#[cfg(feature = "v2")]
Error::V2(e) => write!(f, "unreplyable error: {e}"),
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Error::ReplyToSender(e) => e.source(),
#[cfg(feature = "v2")]
Error::V2(e) => e.source(),
}
}
}
/// The replyable error type for the payjoin receiver, representing failures need to be
/// returned to the sender.
///
/// The error handling is designed to:
/// 1. Provide structured error responses for protocol-level failures
/// 2. Hide implementation details of external errors for security
/// 3. Support proper error propagation through the receiver stack
/// 4. Provide errors according to BIP-78 JSON error specifications for return
/// after conversion into [`JsonReply`]
#[derive(Debug)]
pub enum ReplyableError {
/// Error arising from validation of the original PSBT payload
Payload(PayloadError),
/// Protocol-specific errors for BIP-78 v1 requests (e.g. HTTP request validation, parameter checks)
#[cfg(feature = "v1")]
V1(crate::receive::v1::RequestError),
/// Error arising due to the specific receiver implementation
///
/// e.g. database errors, network failures, wallet errors
Implementation(crate::ImplementationError),
}
/// The standard format for errors that can be replied as JSON.
///
/// The JSON output includes the following fields:
/// ```json
/// {
/// "errorCode": "specific-error-code",
/// "message": "Human readable error message"
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JsonReply {
/// The error code
error_code: ErrorCode,
/// The error message to be displayed only in debug logs
message: String,
/// Additional fields to be included in the JSON response
extra: serde_json::Map<String, serde_json::Value>,
}
impl JsonReply {
/// Create a new Reply
pub fn new(error_code: ErrorCode, message: impl fmt::Display) -> Self {
Self { error_code, message: message.to_string(), extra: serde_json::Map::new() }
}
/// Add an additional field to the JSON response
pub fn with_extra(mut self, key: &str, value: impl Into<serde_json::Value>) -> Self {
self.extra.insert(key.to_string(), value.into());
self
}
/// Serialize the Reply to a JSON string
pub fn to_json(&self) -> serde_json::Value {
let mut map = serde_json::Map::new();
map.insert("errorCode".to_string(), self.error_code.to_string().into());
map.insert("message".to_string(), self.message.clone().into());
map.extend(self.extra.clone());
serde_json::Value::Object(map)
}
}
impl From<ReplyableError> for JsonReply {
fn from(e: ReplyableError) -> Self {
use ReplyableError::*;
match e {
Payload(e) => e.into(),
#[cfg(feature = "v1")]
V1(e) => e.into(),
Implementation(_) => JsonReply::new(Unavailable, "Receiver error"),
}
}
}
impl fmt::Display for ReplyableError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self {
Self::Payload(e) => e.fmt(f),
#[cfg(feature = "v1")]
Self::V1(e) => e.fmt(f),
Self::Implementation(e) => write!(f, "Internal Server Error: {e}"),
}
}
}
impl error::Error for ReplyableError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match &self {
Self::Payload(e) => e.source(),
#[cfg(feature = "v1")]
Self::V1(e) => e.source(),
Self::Implementation(e) => Some(e.as_ref()),
}
}
}
impl From<InternalPayloadError> for ReplyableError {
fn from(e: InternalPayloadError) -> Self { ReplyableError::Payload(e.into()) }
}
/// An error that occurs during validation of the original PSBT payload sent by the sender.
///
/// This type provides a public abstraction over internal validation errors while maintaining a stable public API.
/// It handles various failure modes like:
/// - Invalid UTF-8 encoding
/// - PSBT parsing errors
/// - BIP-78 specific PSBT validation failures
/// - Fee rate validation
/// - Input ownership validation
/// - Previous transaction output validation
///
/// The error messages are formatted as JSON strings suitable for HTTP responses according to the BIP-78 spec,
/// with appropriate error codes and human-readable messages.
#[derive(Debug)]
pub struct PayloadError(pub(crate) InternalPayloadError);
impl From<InternalPayloadError> for PayloadError {
fn from(value: InternalPayloadError) -> Self { PayloadError(value) }
}
#[derive(Debug)]
pub(crate) enum InternalPayloadError {
/// The payload is not valid utf-8
Utf8(std::str::Utf8Error),
/// The payload is not a valid PSBT
ParsePsbt(bitcoin::psbt::PsbtParseError),
/// Invalid sender parameters
SenderParams(super::optional_parameters::Error),
/// The raw PSBT fails bip78-specific validation.
InconsistentPsbt(crate::psbt::InconsistentPsbt),
/// The prevtxout is missing
PrevTxOut(crate::psbt::PrevTxOutError),
/// The Original PSBT has no output for the receiver.
MissingPayment,
/// The original PSBT transaction fails the broadcast check
OriginalPsbtNotBroadcastable,
#[allow(dead_code)]
/// The sender is trying to spend the receiver input
InputOwned(bitcoin::ScriptBuf),
/// The expected input weight cannot be determined
InputWeight(crate::psbt::InputWeightError),
#[allow(dead_code)]
/// Original PSBT input has been seen before. Only automatic receivers, aka "interactive" in the spec
/// look out for these to prevent probing attacks.
InputSeen(bitcoin::OutPoint),
/// Original PSBT fee rate is below minimum fee rate set by the receiver.
///
/// First argument is the calculated fee rate of the original PSBT.
///
/// Second argument is the minimum fee rate optionally set by the receiver.
PsbtBelowFeeRate(bitcoin::FeeRate, bitcoin::FeeRate),
/// Effective receiver feerate exceeds maximum allowed feerate
FeeTooHigh(bitcoin::FeeRate, bitcoin::FeeRate),
}
impl From<PayloadError> for JsonReply {
fn from(e: PayloadError) -> Self {
use InternalPayloadError::*;
match &e.0 {
Utf8(_)
| ParsePsbt(_)
| InconsistentPsbt(_)
| PrevTxOut(_)
| MissingPayment
| OriginalPsbtNotBroadcastable
| InputOwned(_)
| InputWeight(_)
| InputSeen(_)
| PsbtBelowFeeRate(_, _) => JsonReply::new(OriginalPsbtRejected, e),
FeeTooHigh(_, _) => JsonReply::new(NotEnoughMoney, e),
SenderParams(e) => match e {
super::optional_parameters::Error::UnknownVersion { supported_versions } => {
let supported_versions_json =
serde_json::to_string(supported_versions).unwrap_or_default();
JsonReply::new(VersionUnsupported, "This version of payjoin is not supported.")
.with_extra("supported", supported_versions_json)
}
super::optional_parameters::Error::FeeRate =>
JsonReply::new(OriginalPsbtRejected, e),
},
}
}
}
impl fmt::Display for PayloadError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use InternalPayloadError::*;
match &self.0 {
Utf8(e) => write!(f, "{e}"),
ParsePsbt(e) => write!(f, "{e}"),
SenderParams(e) => write!(f, "{e}"),
InconsistentPsbt(e) => write!(f, "{e}"),
PrevTxOut(e) => write!(f, "PrevTxOut Error: {e}"),
MissingPayment => write!(f, "Missing payment."),
OriginalPsbtNotBroadcastable => write!(f, "Can't broadcast. PSBT rejected by mempool."),
InputOwned(_) => write!(f, "The receiver rejected the original PSBT."),
InputWeight(e) => write!(f, "InputWeight Error: {e}"),
InputSeen(_) => write!(f, "The receiver rejected the original PSBT."),
PsbtBelowFeeRate(original_psbt_fee_rate, receiver_min_fee_rate) => write!(
f,
"Original PSBT fee rate too low: {original_psbt_fee_rate} < {receiver_min_fee_rate}."
),
FeeTooHigh(proposed_fee_rate, max_fee_rate) => write!(
f,
"Effective receiver feerate exceeds maximum allowed feerate: {proposed_fee_rate} > {max_fee_rate}"
),
}
}
}
impl std::error::Error for PayloadError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
use InternalPayloadError::*;
match &self.0 {
Utf8(e) => Some(e),
ParsePsbt(e) => Some(e),
SenderParams(e) => Some(e),
InconsistentPsbt(e) => Some(e),
PrevTxOut(e) => Some(e),
InputWeight(e) => Some(e),
PsbtBelowFeeRate(_, _) => None,
FeeTooHigh(_, _) => None,
MissingPayment => None,
OriginalPsbtNotBroadcastable => None,
InputOwned(_) => None,
InputSeen(_) => None,
}
}
}
/// Error that may occur when output substitution fails.
///
/// This is currently opaque type because we aren't sure which variants will stay.
/// You can only display it.
#[derive(Debug, PartialEq)]
pub struct OutputSubstitutionError(InternalOutputSubstitutionError);
#[derive(Debug, PartialEq)]
pub(crate) enum InternalOutputSubstitutionError {
/// Output substitution is disabled and output value was decreased
DecreasedValueWhenDisabled,
/// Output substitution is disabled and script pubkey was changed
ScriptPubKeyChangedWhenDisabled,
/// Current output substitution implementation doesn't support reducing the number of outputs
NotEnoughOutputs,
/// The provided drain script could not be identified in the provided replacement outputs
InvalidDrainScript,
}
impl fmt::Display for OutputSubstitutionError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.0 {
InternalOutputSubstitutionError::DecreasedValueWhenDisabled => write!(f, "Decreasing the receiver output value is not allowed when output substitution is disabled"),
InternalOutputSubstitutionError::ScriptPubKeyChangedWhenDisabled => write!(f, "Changing the receiver output script pubkey is not allowed when output substitution is disabled"),
InternalOutputSubstitutionError::NotEnoughOutputs => write!(
f,
"Current output substitution implementation doesn't support reducing the number of outputs"
),
InternalOutputSubstitutionError::InvalidDrainScript =>
write!(f, "The provided drain script could not be identified in the provided replacement outputs"),
}
}
}
impl From<InternalOutputSubstitutionError> for OutputSubstitutionError {
fn from(value: InternalOutputSubstitutionError) -> Self { OutputSubstitutionError(value) }
}
impl std::error::Error for OutputSubstitutionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.0 {
InternalOutputSubstitutionError::DecreasedValueWhenDisabled => None,
InternalOutputSubstitutionError::ScriptPubKeyChangedWhenDisabled => None,
InternalOutputSubstitutionError::NotEnoughOutputs => None,
InternalOutputSubstitutionError::InvalidDrainScript => None,
}
}
}
/// Error that may occur when coin selection fails.
///
/// This is currently opaque type because we aren't sure which variants will stay.
/// You can only display it.
#[derive(Debug, PartialEq)]
pub struct SelectionError(InternalSelectionError);
#[derive(Debug, PartialEq)]
pub(crate) enum InternalSelectionError {
/// No candidates available for selection
Empty,
/// Current privacy selection implementation only supports 2-output transactions
UnsupportedOutputLength,
/// No selection candidates improve privacy
NotFound,
}
impl fmt::Display for SelectionError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.0 {
InternalSelectionError::Empty => write!(f, "No candidates available for selection"),
InternalSelectionError::UnsupportedOutputLength => write!(
f,
"Current privacy selection implementation only supports 2-output transactions"
),
InternalSelectionError::NotFound =>
write!(f, "No selection candidates improve privacy"),
}
}
}
impl error::Error for SelectionError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
use InternalSelectionError::*;
match &self.0 {
Empty => None,
UnsupportedOutputLength => None,
NotFound => None,
}
}
}
impl From<InternalSelectionError> for SelectionError {
fn from(value: InternalSelectionError) -> Self { SelectionError(value) }
}
/// Error that may occur when input contribution fails.
///
/// This is currently opaque type because we aren't sure which variants will stay.
/// You can only display it.
#[derive(Debug)]
pub struct InputContributionError(InternalInputContributionError);
#[derive(Debug)]
pub(crate) enum InternalInputContributionError {
/// Total input value is not enough to cover additional output value
ValueTooLow,
}
impl fmt::Display for InputContributionError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.0 {
InternalInputContributionError::ValueTooLow =>
write!(f, "Total input value is not enough to cover additional output value"),
}
}
}
impl error::Error for InputContributionError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match &self.0 {
InternalInputContributionError::ValueTooLow => None,
}
}
}
impl From<InternalInputContributionError> for InputContributionError {
fn from(value: InternalInputContributionError) -> Self { InputContributionError(value) }
}