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

payjoin / rust-payjoin / 18168527676

01 Oct 2025 04:16PM UTC coverage: 84.751% (+0.1%) from 84.647%
18168527676

push

github

web-flow
Update sender `process_res` to parse and process error response (#1114)

41 of 41 new or added lines in 2 files covered. (100.0%)

6 existing lines in 4 files now uncovered.

8620 of 10171 relevant lines covered (84.75%)

485.49 hits per line

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

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

3
use crate::error_codes::ErrorCode::{
4
    self, NotEnoughMoney, OriginalPsbtRejected, Unavailable, VersionUnsupported,
5
};
6

7
/// The top-level error type for the payjoin receiver
8
#[derive(Debug)]
9
#[non_exhaustive]
10
pub enum Error {
11
    /// Error in underlying protocol function
12
    Protocol(ProtocolError),
13
    /// Error arising due to the specific receiver implementation
14
    ///
15
    /// e.g. database errors, network failures, wallet errors
16
    Implementation(crate::ImplementationError),
17
}
18

19
impl From<&Error> for JsonReply {
20
    fn from(e: &Error) -> Self {
9✔
21
        match e {
9✔
22
            Error::Protocol(e) => e.into(),
3✔
23
            Error::Implementation(_) => JsonReply::new(Unavailable, "Receiver error"),
6✔
24
        }
25
    }
9✔
26
}
27

28
impl From<ProtocolError> for Error {
29
    fn from(e: ProtocolError) -> Self { Error::Protocol(e) }
×
30
}
31

32
impl fmt::Display for Error {
33
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
15✔
34
        match self {
15✔
35
            Error::Protocol(e) => write!(f, "Protocol error: {e}"),
3✔
36
            Error::Implementation(e) => write!(f, "Implementation error: {e}"),
12✔
37
        }
38
    }
15✔
39
}
40

41
impl error::Error for Error {
42
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
43
        match self {
×
44
            Error::Protocol(e) => e.source(),
×
45
            Error::Implementation(e) => e.source(),
×
46
        }
47
    }
×
48
}
49

50
/// The protocol error type for the payjoin receiver, representing failures in
51
/// the internal protocol operation.
52
///
53
/// The error handling is designed to:
54
/// 1. Provide structured error responses for protocol-level failures
55
/// 2. Hide implementation details of external errors for security
56
/// 3. Support proper error propagation through the receiver stack
57
/// 4. Provide errors according to BIP-78 JSON error specifications for return
58
///    after conversion into [`JsonReply`]
59
#[derive(Debug)]
60
pub enum ProtocolError {
61
    /// Error arising from validation of the original PSBT payload
62
    OriginalPayload(PayloadError),
63
    /// Protocol-specific errors for BIP-78 v1 requests (e.g. HTTP request validation, parameter checks)
64
    #[cfg(feature = "v1")]
65
    V1(crate::receive::v1::RequestError),
66
    #[cfg(feature = "v2")]
67
    /// V2-specific errors that are infeasable to reply to the sender
68
    V2(crate::receive::v2::SessionError),
69
}
70

71
/// The standard format for errors that can be replied as JSON.
72
///
73
/// The JSON output includes the following fields:
74
/// ```json
75
/// {
76
///     "errorCode": "specific-error-code",
77
///     "message": "Human readable error message"
78
/// }
79
/// ```
80
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
81
pub struct JsonReply {
82
    /// The error code
83
    error_code: ErrorCode,
84
    /// The error message to be displayed only in debug logs
85
    message: String,
86
    /// Additional fields to be included in the JSON response
87
    extra: serde_json::Map<String, serde_json::Value>,
88
}
89

90
impl JsonReply {
91
    /// Create a new Reply
92
    pub(crate) fn new(error_code: ErrorCode, message: impl fmt::Display) -> Self {
11✔
93
        Self { error_code, message: message.to_string(), extra: serde_json::Map::new() }
11✔
94
    }
11✔
95

96
    /// Add an additional field to the JSON response
97
    pub fn with_extra(mut self, key: &str, value: impl Into<serde_json::Value>) -> Self {
×
98
        self.extra.insert(key.to_string(), value.into());
×
99
        self
×
100
    }
×
101

102
    /// Serialize the Reply to a JSON string
103
    pub fn to_json(&self) -> serde_json::Value {
9✔
104
        let mut map = serde_json::Map::new();
9✔
105
        map.insert("errorCode".to_string(), self.error_code.to_string().into());
9✔
106
        map.insert("message".to_string(), self.message.clone().into());
9✔
107
        map.extend(self.extra.clone());
9✔
108

109
        serde_json::Value::Object(map)
9✔
110
    }
9✔
111

112
    /// Get the HTTP status code for the error
113
    pub fn status_code(&self) -> u16 {
2✔
114
        match self.error_code {
2✔
115
            ErrorCode::Unavailable => http::StatusCode::INTERNAL_SERVER_ERROR,
1✔
116
            ErrorCode::NotEnoughMoney
117
            | ErrorCode::VersionUnsupported
118
            | ErrorCode::OriginalPsbtRejected => http::StatusCode::BAD_REQUEST,
1✔
119
        }
120
        .as_u16()
2✔
121
    }
2✔
122
}
123

124
impl From<&ProtocolError> for JsonReply {
125
    fn from(e: &ProtocolError) -> Self {
3✔
126
        use ProtocolError::*;
127
        match e {
3✔
128
            OriginalPayload(e) => e.into(),
3✔
129
            #[cfg(feature = "v1")]
130
            V1(e) => JsonReply::new(OriginalPsbtRejected, e),
×
131
            #[cfg(feature = "v2")]
132
            V2(_) => JsonReply::new(Unavailable, "Receiver error"),
×
133
        }
134
    }
3✔
135
}
136

137
impl fmt::Display for ProtocolError {
138
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3✔
139
        match &self {
3✔
140
            Self::OriginalPayload(e) => e.fmt(f),
2✔
141
            #[cfg(feature = "v1")]
142
            Self::V1(e) => e.fmt(f),
×
143
            #[cfg(feature = "v2")]
144
            Self::V2(e) => e.fmt(f),
1✔
145
        }
146
    }
3✔
147
}
148

149
impl error::Error for ProtocolError {
150
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
151
        match &self {
×
152
            Self::OriginalPayload(e) => e.source(),
×
153
            #[cfg(feature = "v1")]
154
            Self::V1(e) => e.source(),
×
155
            #[cfg(feature = "v2")]
156
            Self::V2(e) => e.source(),
×
157
        }
158
    }
×
159
}
160

161
impl From<InternalPayloadError> for Error {
162
    fn from(e: InternalPayloadError) -> Self {
3✔
163
        Error::Protocol(ProtocolError::OriginalPayload(e.into()))
3✔
164
    }
3✔
165
}
166

167
/// An error that occurs during validation of the original PSBT payload sent by the sender.
168
///
169
/// This type provides a public abstraction over internal validation errors while maintaining a stable public API.
170
/// It handles various failure modes like:
171
/// - Invalid UTF-8 encoding
172
/// - PSBT parsing errors
173
/// - BIP-78 specific PSBT validation failures
174
/// - Fee rate validation
175
/// - Input ownership validation
176
/// - Previous transaction output validation
177
///
178
/// The error messages are formatted as JSON strings suitable for HTTP responses according to the BIP-78 spec,
179
/// with appropriate error codes and human-readable messages.
180
#[derive(Debug)]
181
pub struct PayloadError(pub(crate) InternalPayloadError);
182

183
impl From<InternalPayloadError> for PayloadError {
184
    fn from(value: InternalPayloadError) -> Self { PayloadError(value) }
3✔
185
}
186

187
#[derive(Debug)]
188
pub(crate) enum InternalPayloadError {
189
    /// The payload is not valid utf-8
190
    Utf8(std::str::Utf8Error),
191
    /// The payload is not a valid PSBT
192
    ParsePsbt(bitcoin::psbt::PsbtParseError),
193
    /// Invalid sender parameters
194
    SenderParams(super::optional_parameters::Error),
195
    /// The raw PSBT fails bip78-specific validation.
196
    InconsistentPsbt(crate::psbt::InconsistentPsbt),
197
    /// The prevtxout is missing
198
    PrevTxOut(crate::psbt::PrevTxOutError),
199
    /// The Original PSBT has no output for the receiver.
200
    MissingPayment,
201
    /// The original PSBT transaction fails the broadcast check
202
    OriginalPsbtNotBroadcastable,
203
    #[allow(dead_code)]
204
    /// The sender is trying to spend the receiver input
205
    InputOwned(bitcoin::ScriptBuf),
206
    #[allow(dead_code)]
207
    /// Original PSBT input has been seen before. Only automatic receivers, aka "interactive" in the spec
208
    /// look out for these to prevent probing attacks.
209
    InputSeen(bitcoin::OutPoint),
210
    /// Original PSBT fee rate is below minimum fee rate set by the receiver.
211
    ///
212
    /// First argument is the calculated fee rate of the original PSBT.
213
    ///
214
    /// Second argument is the minimum fee rate optionally set by the receiver.
215
    PsbtBelowFeeRate(bitcoin::FeeRate, bitcoin::FeeRate),
216
    /// Effective receiver feerate exceeds maximum allowed feerate
217
    FeeTooHigh(bitcoin::FeeRate, bitcoin::FeeRate),
218
}
219

220
impl From<&PayloadError> for JsonReply {
221
    fn from(e: &PayloadError) -> Self {
3✔
222
        use InternalPayloadError::*;
223

224
        match &e.0 {
3✔
225
            Utf8(_)
226
            | ParsePsbt(_)
227
            | InconsistentPsbt(_)
228
            | PrevTxOut(_)
229
            | MissingPayment
230
            | OriginalPsbtNotBroadcastable
231
            | InputOwned(_)
232
            | InputSeen(_)
233
            | PsbtBelowFeeRate(_, _) => JsonReply::new(OriginalPsbtRejected, e),
3✔
234

235
            FeeTooHigh(_, _) => JsonReply::new(NotEnoughMoney, e),
×
236

237
            SenderParams(e) => match e {
×
238
                super::optional_parameters::Error::UnknownVersion { supported_versions } => {
×
239
                    let supported_versions_json =
×
240
                        serde_json::to_string(supported_versions).unwrap_or_default();
×
241
                    JsonReply::new(VersionUnsupported, "This version of payjoin is not supported.")
×
242
                        .with_extra("supported", supported_versions_json)
×
243
                }
244
                super::optional_parameters::Error::FeeRate =>
245
                    JsonReply::new(OriginalPsbtRejected, e),
×
246
            },
247
        }
248
    }
3✔
249
}
250

251
impl fmt::Display for PayloadError {
252
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) }
5✔
253
}
254

255
impl fmt::Display for InternalPayloadError {
256
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5✔
257
        use InternalPayloadError::*;
258

259
        match &self {
5✔
260
            Utf8(e) => write!(f, "{e}"),
×
261
            ParsePsbt(e) => write!(f, "{e}"),
×
262
            SenderParams(e) => write!(f, "{e}"),
×
263
            InconsistentPsbt(e) => write!(f, "{e}"),
×
264
            PrevTxOut(e) => write!(f, "PrevTxOut Error: {e}"),
×
265
            MissingPayment => write!(f, "Missing payment."),
2✔
UNCOV
266
            OriginalPsbtNotBroadcastable => write!(f, "Can't broadcast. PSBT rejected by mempool."),
×
267
            InputOwned(_) => write!(f, "The receiver rejected the original PSBT."),
3✔
268
            InputSeen(_) => write!(f, "The receiver rejected the original PSBT."),
×
269
            PsbtBelowFeeRate(original_psbt_fee_rate, receiver_min_fee_rate) => write!(
×
270
                f,
×
271
                "Original PSBT fee rate too low: {original_psbt_fee_rate} < {receiver_min_fee_rate}."
×
272
            ),
273
            FeeTooHigh(proposed_fee_rate, max_fee_rate) => write!(
×
274
                f,
×
275
                "Effective receiver feerate exceeds maximum allowed feerate: {proposed_fee_rate} > {max_fee_rate}"
×
276
            ),
277
        }
278
    }
5✔
279
}
280

281
impl std::error::Error for PayloadError {
282
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
×
283
        use InternalPayloadError::*;
284
        match &self.0 {
×
285
            Utf8(e) => Some(e),
×
286
            ParsePsbt(e) => Some(e),
×
287
            SenderParams(e) => Some(e),
×
288
            InconsistentPsbt(e) => Some(e),
×
289
            PrevTxOut(e) => Some(e),
×
290
            PsbtBelowFeeRate(_, _) => None,
×
291
            FeeTooHigh(_, _) => None,
×
292
            MissingPayment => None,
×
293
            OriginalPsbtNotBroadcastable => None,
×
294
            InputOwned(_) => None,
×
295
            InputSeen(_) => None,
×
296
        }
297
    }
×
298
}
299

300
/// Error that may occur when output substitution fails.
301
///
302
/// This is currently opaque type because we aren't sure which variants will stay.
303
/// You can only display it.
304
#[derive(Debug, PartialEq)]
305
pub struct OutputSubstitutionError(InternalOutputSubstitutionError);
306

307
#[derive(Debug, PartialEq, Eq)]
308
pub(crate) enum InternalOutputSubstitutionError {
309
    /// Output substitution is disabled and output value was decreased
310
    DecreasedValueWhenDisabled,
311
    /// Output substitution is disabled and script pubkey was changed
312
    ScriptPubKeyChangedWhenDisabled,
313
    /// Current output substitution implementation doesn't support reducing the number of outputs
314
    NotEnoughOutputs,
315
    /// The provided drain script could not be identified in the provided replacement outputs
316
    InvalidDrainScript,
317
}
318

319
impl fmt::Display for OutputSubstitutionError {
320
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
321
        match &self.0 {
×
322
            InternalOutputSubstitutionError::DecreasedValueWhenDisabled => write!(f, "Decreasing the receiver output value is not allowed when output substitution is disabled"),
×
323
            InternalOutputSubstitutionError::ScriptPubKeyChangedWhenDisabled => write!(f, "Changing the receiver output script pubkey is not allowed when output substitution is disabled"),
×
324
            InternalOutputSubstitutionError::NotEnoughOutputs => write!(
×
325
                f,
×
326
                "Current output substitution implementation doesn't support reducing the number of outputs"
×
327
            ),
328
            InternalOutputSubstitutionError::InvalidDrainScript =>
329
                write!(f, "The provided drain script could not be identified in the provided replacement outputs"),
×
330
        }
331
    }
×
332
}
333

334
impl From<InternalOutputSubstitutionError> for OutputSubstitutionError {
335
    fn from(value: InternalOutputSubstitutionError) -> Self { OutputSubstitutionError(value) }
4✔
336
}
337

338
impl std::error::Error for OutputSubstitutionError {
339
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
×
340
        match &self.0 {
×
341
            InternalOutputSubstitutionError::DecreasedValueWhenDisabled => None,
×
342
            InternalOutputSubstitutionError::ScriptPubKeyChangedWhenDisabled => None,
×
343
            InternalOutputSubstitutionError::NotEnoughOutputs => None,
×
344
            InternalOutputSubstitutionError::InvalidDrainScript => None,
×
345
        }
346
    }
×
347
}
348

349
/// Error that may occur when coin selection fails.
350
///
351
/// This is currently opaque type because we aren't sure which variants will stay.
352
/// You can only display it.
353
#[derive(Debug, PartialEq, Eq)]
354
pub struct SelectionError(InternalSelectionError);
355

356
#[derive(Debug, PartialEq, Eq)]
357
pub(crate) enum InternalSelectionError {
358
    /// No candidates available for selection
359
    Empty,
360
    /// Current privacy selection implementation only supports 2-output transactions
361
    UnsupportedOutputLength,
362
    /// No selection candidates improve privacy
363
    NotFound,
364
}
365

366
impl fmt::Display for SelectionError {
367
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
368
        match &self.0 {
×
369
            InternalSelectionError::Empty => write!(f, "No candidates available for selection"),
×
370
            InternalSelectionError::UnsupportedOutputLength => write!(
×
371
                f,
×
372
                "Current privacy selection implementation only supports 2-output transactions"
×
373
            ),
374
            InternalSelectionError::NotFound =>
375
                write!(f, "No selection candidates improve privacy"),
×
376
        }
377
    }
×
378
}
379

380
impl error::Error for SelectionError {
381
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
382
        use InternalSelectionError::*;
383

384
        match &self.0 {
×
385
            Empty => None,
×
386
            UnsupportedOutputLength => None,
×
387
            NotFound => None,
×
388
        }
389
    }
×
390
}
391
impl From<InternalSelectionError> for SelectionError {
392
    fn from(value: InternalSelectionError) -> Self { SelectionError(value) }
7✔
393
}
394

395
/// Error that may occur when input contribution fails.
396
///
397
/// This is currently opaque type because we aren't sure which variants will stay.
398
/// You can only display it.
399
#[derive(Debug, PartialEq, Eq)]
400
pub struct InputContributionError(InternalInputContributionError);
401

402
#[derive(Debug, PartialEq, Eq)]
403
pub(crate) enum InternalInputContributionError {
404
    /// Total input value is not enough to cover additional output value
405
    ValueTooLow,
406
}
407

408
impl fmt::Display for InputContributionError {
409
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
410
        match &self.0 {
×
411
            InternalInputContributionError::ValueTooLow =>
412
                write!(f, "Total input value is not enough to cover additional output value"),
×
413
        }
414
    }
×
415
}
416

417
impl error::Error for InputContributionError {
418
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
419
        match &self.0 {
×
420
            InternalInputContributionError::ValueTooLow => None,
×
421
        }
422
    }
×
423
}
424

425
impl From<InternalInputContributionError> for InputContributionError {
426
    fn from(value: InternalInputContributionError) -> Self { InputContributionError(value) }
×
427
}
428

429
#[cfg(test)]
430
mod tests {
431
    use super::*;
432
    use crate::ImplementationError;
433

434
    #[test]
435
    fn test_json_reply_from_implementation_error() {
1✔
436
        struct AlwaysPanics;
437

438
        impl fmt::Display for AlwaysPanics {
439
            fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
440
                panic!("internal error should never display when converting to JsonReply");
×
441
            }
442
        }
443

444
        impl fmt::Debug for AlwaysPanics {
445
            fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
×
446
                panic!("internal error should never debug when converting to JsonReply");
×
447
            }
448
        }
449

450
        impl error::Error for AlwaysPanics {
451
            fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
452
                panic!("internal error should never be examined when converting to JsonReply");
×
453
            }
454
        }
455
        // Use a panicking error to ensure conversion does not touch internal formatting
456
        let internal = AlwaysPanics;
1✔
457
        let error = Error::Implementation(ImplementationError::new(internal));
1✔
458
        let reply = JsonReply::from(&error);
1✔
459
        let expected = JsonReply {
1✔
460
            error_code: ErrorCode::Unavailable,
1✔
461
            message: "Receiver error".to_string(),
1✔
462
            extra: serde_json::Map::new(),
1✔
463
        };
1✔
464
        assert_eq!(reply, expected);
1✔
465

466
        let json = reply.to_json();
1✔
467
        assert_eq!(
1✔
468
            json,
469
            serde_json::json!({
1✔
470
                "errorCode": ErrorCode::Unavailable.to_string(),
1✔
471
                "message": "Receiver error",
1✔
472
            })
473
        );
474
    }
1✔
475

476
    #[test]
477
    /// Create an implementation error that returns INTERNAL_SERVER_ERROR
478
    fn test_json_reply_with_500_status_code() {
1✔
479
        let error = Error::Implementation(ImplementationError::from("test error"));
1✔
480
        let reply = JsonReply::from(&error);
1✔
481

482
        assert_eq!(reply.status_code(), http::StatusCode::INTERNAL_SERVER_ERROR.as_u16());
1✔
483

484
        let json = reply.to_json();
1✔
485
        assert_eq!(json["errorCode"], "unavailable");
1✔
486
        assert_eq!(json["message"], "Receiver error");
1✔
487
    }
1✔
488

489
    #[test]
490
    /// Create a payload error that returns BAD_REQUEST
491
    fn test_json_reply_with_400_status_code() {
1✔
492
        let payload_error = PayloadError(InternalPayloadError::MissingPayment);
1✔
493
        let error = Error::Protocol(ProtocolError::OriginalPayload(payload_error));
1✔
494
        let reply = JsonReply::from(&error);
1✔
495

496
        assert_eq!(reply.status_code(), http::StatusCode::BAD_REQUEST.as_u16());
1✔
497

498
        let json = reply.to_json();
1✔
499
        assert_eq!(json["errorCode"], "original-psbt-rejected");
1✔
500
        assert_eq!(json["message"], "Missing payment.");
1✔
501
    }
1✔
502
}
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