• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

payjoin / rust-payjoin / 13355765003

16 Feb 2025 02:07PM UTC coverage: 78.956% (-0.2%) from 79.127%
13355765003

Pull #520

github

web-flow
Merge d022978d4 into 39cfaff2a
Pull Request #520: Use IntoUrl for more ergonomic function signatures

62 of 94 new or added lines in 10 files covered. (65.96%)

2 existing lines in 1 file now uncovered.

4037 of 5113 relevant lines covered (78.96%)

899.72 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

15.33
/payjoin/src/receive/error.rs
1
use std::{error, fmt};
2

3
use crate::error_codes::{
4
    NOT_ENOUGH_MONEY, ORIGINAL_PSBT_REJECTED, UNAVAILABLE, VERSION_UNSUPPORTED,
5
};
6

7
pub type ImplementationError = Box<dyn error::Error + Send + Sync>;
8

9
/// The top-level error type for the payjoin receiver
10
#[derive(Debug)]
11
#[non_exhaustive]
12
pub enum Error {
13
    /// Errors that can be replied to the sender
14
    ReplyToSender(ReplyableError),
15
    #[cfg(feature = "v2")]
16
    /// V2-specific errors that are infeasable to reply to the sender
17
    V2(crate::receive::v2::SessionError),
18
}
19

20
impl From<ReplyableError> for Error {
21
    fn from(e: ReplyableError) -> Self { Error::ReplyToSender(e) }
×
22
}
23

24
impl fmt::Display for Error {
25
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1✔
26
        match self {
1✔
27
            Error::ReplyToSender(e) => write!(f, "replyable error: {}", e),
×
28
            #[cfg(feature = "v2")]
29
            Error::V2(e) => write!(f, "unreplyable error: {}", e),
1✔
30
        }
31
    }
1✔
32
}
33

34
impl error::Error for Error {
35
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
36
        match self {
×
37
            Error::ReplyToSender(e) => e.source(),
×
38
            #[cfg(feature = "v2")]
39
            Error::V2(e) => e.source(),
×
40
        }
41
    }
×
42
}
43

44
/// The replyable error type for the payjoin receiver, representing failures need to be
45
/// returned to the sender.
46
///
47
/// The error handling is designed to:
48
/// 1. Provide structured error responses for protocol-level failures
49
/// 2. Hide implementation details of external errors for security
50
/// 3. Support proper error propagation through the receiver stack
51
/// 4. Provide errors according to BIP-78 JSON error specifications for return using [`JsonError::to_json`]
52
#[derive(Debug)]
53
pub enum ReplyableError {
54
    /// Error arising from validation of the original PSBT payload
55
    Payload(PayloadError),
56
    /// Protocol-specific errors for BIP-78 v1 requests (e.g. HTTP request validation, parameter checks)
57
    #[cfg(feature = "v1")]
58
    V1(crate::receive::v1::RequestError),
59
    /// Error arising due to the specific receiver implementation
60
    ///
61
    /// e.g. database errors, network failures, wallet errors
62
    Implementation(ImplementationError),
63
    /// Error parsing a URL
64
    ParseUrl(crate::into_url::Error),
65
}
66

67
/// A trait for errors that can be serialized to JSON in a standardized format.
68
///
69
/// The JSON output follows the structure:
70
/// ```json
71
/// {
72
///     "errorCode": "specific-error-code",
73
///     "message": "Human readable error message"
74
/// }
75
/// ```
76
pub trait JsonError {
77
    /// Converts the error into a JSON string representation.
78
    fn to_json(&self) -> String;
79
}
80

81
impl JsonError for ReplyableError {
82
    fn to_json(&self) -> String {
3✔
83
        match self {
3✔
84
            Self::Payload(e) => e.to_json(),
1✔
85
            #[cfg(feature = "v1")]
86
            Self::V1(e) => e.to_json(),
×
87
            Self::Implementation(_) => serialize_json_error(UNAVAILABLE, "Receiver error"),
2✔
NEW
88
            Self::ParseUrl(_) => unimplemented!(),
×
89
        }
90
    }
3✔
91
}
92

93
pub(crate) fn serialize_json_error(code: &str, message: impl fmt::Display) -> String {
3✔
94
    format!(r#"{{ "errorCode": "{}", "message": "{}" }}"#, code, message)
3✔
95
}
3✔
96

97
pub(crate) fn serialize_json_plus_fields(
×
98
    code: &str,
×
99
    message: impl fmt::Display,
×
100
    additional_fields: &str,
×
101
) -> String {
×
102
    format!(r#"{{ "errorCode": "{}", "message": "{}", {} }}"#, code, message, additional_fields)
×
103
}
×
104

105
impl fmt::Display for ReplyableError {
106
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
107
        match &self {
×
108
            Self::Payload(e) => e.fmt(f),
×
109
            #[cfg(feature = "v1")]
110
            Self::V1(e) => e.fmt(f),
×
111
            Self::Implementation(e) => write!(f, "Internal Server Error: {}", e),
×
NEW
112
            Self::ParseUrl(e) => write!(f, "Error parsing URL: {}", e),
×
113
        }
114
    }
×
115
}
116

117
impl error::Error for ReplyableError {
118
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
119
        match &self {
×
120
            Self::Payload(e) => e.source(),
×
121
            #[cfg(feature = "v1")]
122
            Self::V1(e) => e.source(),
×
123
            Self::Implementation(e) => Some(e.as_ref()),
×
NEW
124
            Self::ParseUrl(e) => Some(e),
×
125
        }
126
    }
×
127
}
128

129
impl From<InternalPayloadError> for ReplyableError {
130
    fn from(e: InternalPayloadError) -> Self { ReplyableError::Payload(e.into()) }
1✔
131
}
132

133
/// An error that occurs during validation of the original PSBT payload sent by the sender.
134
///
135
/// This type provides a public abstraction over internal validation errors while maintaining a stable public API.
136
/// It handles various failure modes like:
137
/// - Invalid UTF-8 encoding
138
/// - PSBT parsing errors
139
/// - BIP-78 specific PSBT validation failures
140
/// - Fee rate validation
141
/// - Input ownership validation
142
/// - Previous transaction output validation
143
///
144
/// The error messages are formatted as JSON strings suitable for HTTP responses according to the BIP-78 spec,
145
/// with appropriate error codes and human-readable messages.
146
#[derive(Debug)]
147
pub struct PayloadError(pub(crate) InternalPayloadError);
148

149
impl From<InternalPayloadError> for PayloadError {
150
    fn from(value: InternalPayloadError) -> Self { PayloadError(value) }
1✔
151
}
152

153
#[derive(Debug)]
154
pub(crate) enum InternalPayloadError {
155
    /// The payload is not valid utf-8
156
    Utf8(std::string::FromUtf8Error),
157
    /// The payload is not a valid PSBT
158
    ParsePsbt(bitcoin::psbt::PsbtParseError),
159
    /// Invalid sender parameters
160
    SenderParams(super::optional_parameters::Error),
161
    /// The raw PSBT fails bip78-specific validation.
162
    InconsistentPsbt(crate::psbt::InconsistentPsbt),
163
    /// The prevtxout is missing
164
    PrevTxOut(crate::psbt::PrevTxOutError),
165
    /// The Original PSBT has no output for the receiver.
166
    MissingPayment,
167
    /// The original PSBT transaction fails the broadcast check
168
    OriginalPsbtNotBroadcastable,
169
    #[allow(dead_code)]
170
    /// The sender is trying to spend the receiver input
171
    InputOwned(bitcoin::ScriptBuf),
172
    /// The expected input weight cannot be determined
173
    InputWeight(crate::psbt::InputWeightError),
174
    #[allow(dead_code)]
175
    /// Original PSBT input has been seen before. Only automatic receivers, aka "interactive" in the spec
176
    /// look out for these to prevent probing attacks.
177
    InputSeen(bitcoin::OutPoint),
178
    /// Original PSBT fee rate is below minimum fee rate set by the receiver.
179
    ///
180
    /// First argument is the calculated fee rate of the original PSBT.
181
    ///
182
    /// Second argument is the minimum fee rate optionaly set by the receiver.
183
    PsbtBelowFeeRate(bitcoin::FeeRate, bitcoin::FeeRate),
184
    /// Effective receiver feerate exceeds maximum allowed feerate
185
    FeeTooHigh(bitcoin::FeeRate, bitcoin::FeeRate),
186
}
187

188
impl JsonError for PayloadError {
189
    fn to_json(&self) -> String {
1✔
190
        use InternalPayloadError::*;
191

192
        match &self.0 {
1✔
193
            Utf8(_) => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
×
194
            ParsePsbt(_) => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
×
195
            SenderParams(e) => match e {
×
196
                super::optional_parameters::Error::UnknownVersion { supported_versions } => {
×
197
                    let supported_versions_json =
×
198
                        serde_json::to_string(supported_versions).unwrap_or_default();
×
199
                    serialize_json_plus_fields(
×
200
                        VERSION_UNSUPPORTED,
×
201
                        "This version of payjoin is not supported.",
×
202
                        &format!(r#""supported": {}"#, supported_versions_json),
×
203
                    )
×
204
                }
205
                _ => serialize_json_error("sender-params-error", self),
×
206
            },
207
            InconsistentPsbt(_) => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
×
208
            PrevTxOut(_) => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
×
209
            MissingPayment => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
1✔
210
            OriginalPsbtNotBroadcastable => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
×
211
            InputOwned(_) => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
×
212
            InputWeight(_) => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
×
213
            InputSeen(_) => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
×
214
            PsbtBelowFeeRate(_, _) => serialize_json_error(ORIGINAL_PSBT_REJECTED, self),
×
215
            FeeTooHigh(_, _) => serialize_json_error(NOT_ENOUGH_MONEY, self),
×
216
        }
217
    }
1✔
218
}
219

220
impl fmt::Display for PayloadError {
221
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1✔
222
        use InternalPayloadError::*;
223

224
        match &self.0 {
1✔
225
            Utf8(e) => write!(f, "{}", e),
×
226
            ParsePsbt(e) => write!(f, "{}", e),
×
227
            SenderParams(e) => write!(f, "{}", e),
×
228
            InconsistentPsbt(e) => write!(f, "{}", e),
×
229
            PrevTxOut(e) => write!(f, "PrevTxOut Error: {}", e),
×
230
            MissingPayment => write!(f, "Missing payment."),
1✔
231
            OriginalPsbtNotBroadcastable => write!(f, "Can't broadcast. PSBT rejected by mempool."),
×
232
            InputOwned(_) => write!(f, "The receiver rejected the original PSBT."),
×
233
            InputWeight(e) => write!(f, "InputWeight Error: {}", e),
×
234
            InputSeen(_) => write!(f, "The receiver rejected the original PSBT."),
×
235
            PsbtBelowFeeRate(original_psbt_fee_rate, receiver_min_fee_rate) => write!(
×
236
                f,
×
237
                "Original PSBT fee rate too low: {} < {}.",
×
238
                original_psbt_fee_rate, receiver_min_fee_rate
×
239
            ),
×
240
            FeeTooHigh(proposed_fee_rate, max_fee_rate) => write!(
×
241
                f,
×
242
                "Effective receiver feerate exceeds maximum allowed feerate: {} > {}",
×
243
                proposed_fee_rate, max_fee_rate
×
244
            ),
×
245
        }
246
    }
1✔
247
}
248

249
impl std::error::Error for PayloadError {
250
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
×
251
        use InternalPayloadError::*;
252
        match &self.0 {
×
253
            Utf8(e) => Some(e),
×
254
            ParsePsbt(e) => Some(e),
×
255
            SenderParams(e) => Some(e),
×
256
            InconsistentPsbt(e) => Some(e),
×
257
            PrevTxOut(e) => Some(e),
×
258
            InputWeight(e) => Some(e),
×
259
            PsbtBelowFeeRate(_, _) => None,
×
260
            FeeTooHigh(_, _) => None,
×
261
            MissingPayment => None,
×
262
            OriginalPsbtNotBroadcastable => None,
×
263
            InputOwned(_) => None,
×
264
            InputSeen(_) => None,
×
265
        }
266
    }
×
267
}
268

269
/// Error that may occur when output substitution fails.
270
///
271
/// This is currently opaque type because we aren't sure which variants will stay.
272
/// You can only display it.
273
#[derive(Debug)]
274
pub struct OutputSubstitutionError(InternalOutputSubstitutionError);
275

276
#[derive(Debug)]
277
pub(crate) enum InternalOutputSubstitutionError {
278
    /// Output substitution is disabled
279
    OutputSubstitutionDisabled(&'static str),
280
    /// Current output substitution implementation doesn't support reducing the number of outputs
281
    NotEnoughOutputs,
282
    /// The provided drain script could not be identified in the provided replacement outputs
283
    InvalidDrainScript,
284
}
285

286
impl fmt::Display for OutputSubstitutionError {
287
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
288
        match &self.0 {
×
289
            InternalOutputSubstitutionError::OutputSubstitutionDisabled(reason) => write!(f, "{}", &format!("Output substitution is disabled: {}", reason)),
×
290
            InternalOutputSubstitutionError::NotEnoughOutputs => write!(
×
291
                f,
×
292
                "Current output substitution implementation doesn't support reducing the number of outputs"
×
293
            ),
×
294
            InternalOutputSubstitutionError::InvalidDrainScript =>
295
                write!(f, "The provided drain script could not be identified in the provided replacement outputs"),
×
296
        }
297
    }
×
298
}
299

300
impl From<InternalOutputSubstitutionError> for OutputSubstitutionError {
301
    fn from(value: InternalOutputSubstitutionError) -> Self { OutputSubstitutionError(value) }
×
302
}
303

304
impl std::error::Error for OutputSubstitutionError {
305
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
×
306
        match &self.0 {
×
307
            InternalOutputSubstitutionError::OutputSubstitutionDisabled(_) => None,
×
308
            InternalOutputSubstitutionError::NotEnoughOutputs => None,
×
309
            InternalOutputSubstitutionError::InvalidDrainScript => None,
×
310
        }
311
    }
×
312
}
313

314
/// Error that may occur when coin selection fails.
315
///
316
/// This is currently opaque type because we aren't sure which variants will stay.
317
/// You can only display it.
318
#[derive(Debug)]
319
pub struct SelectionError(InternalSelectionError);
320

321
#[derive(Debug)]
322
pub(crate) enum InternalSelectionError {
323
    /// No candidates available for selection
324
    Empty,
325
    /// Current privacy selection implementation only supports 2-output transactions
326
    UnsupportedOutputLength,
327
    /// No selection candidates improve privacy
328
    NotFound,
329
}
330

331
impl fmt::Display for SelectionError {
332
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
333
        match &self.0 {
×
334
            InternalSelectionError::Empty => write!(f, "No candidates available for selection"),
×
335
            InternalSelectionError::UnsupportedOutputLength => write!(
×
336
                f,
×
337
                "Current privacy selection implementation only supports 2-output transactions"
×
338
            ),
×
339
            InternalSelectionError::NotFound =>
340
                write!(f, "No selection candidates improve privacy"),
×
341
        }
342
    }
×
343
}
344

345
impl error::Error for SelectionError {
346
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
347
        use InternalSelectionError::*;
348

349
        match &self.0 {
×
350
            Empty => None,
×
351
            UnsupportedOutputLength => None,
×
352
            NotFound => None,
×
353
        }
354
    }
×
355
}
356
impl From<InternalSelectionError> for SelectionError {
357
    fn from(value: InternalSelectionError) -> Self { SelectionError(value) }
2✔
358
}
359

360
/// Error that may occur when input contribution fails.
361
///
362
/// This is currently opaque type because we aren't sure which variants will stay.
363
/// You can only display it.
364
#[derive(Debug)]
365
pub struct InputContributionError(InternalInputContributionError);
366

367
#[derive(Debug)]
368
pub(crate) enum InternalInputContributionError {
369
    /// Total input value is not enough to cover additional output value
370
    ValueTooLow,
371
}
372

373
impl fmt::Display for InputContributionError {
374
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
375
        match &self.0 {
×
376
            InternalInputContributionError::ValueTooLow =>
×
377
                write!(f, "Total input value is not enough to cover additional output value"),
×
378
        }
×
379
    }
×
380
}
381

382
impl error::Error for InputContributionError {
383
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
384
        match &self.0 {
×
385
            InternalInputContributionError::ValueTooLow => None,
×
386
        }
×
387
    }
×
388
}
389

390
impl From<InternalInputContributionError> for InputContributionError {
391
    fn from(value: InternalInputContributionError) -> Self { InputContributionError(value) }
×
392
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc