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

payjoin / rust-payjoin / 20133889849

11 Dec 2025 12:58PM UTC coverage: 83.176%. Remained the same
20133889849

Pull #1223

github

web-flow
Merge d15022d04 into 92fed12d2
Pull Request #1223: Audit serialization trait implementations

9665 of 11620 relevant lines covered (83.18%)

443.75 hits per line

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

46.45
/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 {
12✔
21
        match e {
12✔
22
            Error::Protocol(e) => e.into(),
7✔
23
            Error::Implementation(_) => JsonReply::new(Unavailable, "Receiver error"),
5✔
24
        }
25
    }
12✔
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 {
12✔
34
        match self {
12✔
35
            Error::Protocol(e) => write!(f, "Protocol error: {e}"),
3✔
36
            Error::Implementation(e) => write!(f, "Implementation error: {e}"),
9✔
37
        }
38
    }
12✔
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)]
81
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
82
pub struct JsonReply {
83
    /// The error code
84
    error_code: ErrorCode,
85
    /// The error message to be displayed only in debug logs
86
    message: String,
87
    /// Additional fields to be included in the JSON response
88
    extra: serde_json::Map<String, serde_json::Value>,
89
}
90

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

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

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

110
        serde_json::Value::Object(map)
7✔
111
    }
7✔
112

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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