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

payjoin / rust-payjoin / 16392628297

19 Jul 2025 08:51PM UTC coverage: 85.708% (-0.09%) from 85.8%
16392628297

Pull #768

github

web-flow
Merge deeb8489d into 16c13d6e1
Pull Request #768: Add PartialEq/Eq to errors for easier comparison

74 of 100 new or added lines in 9 files covered. (74.0%)

2 existing lines in 2 files now uncovered.

7742 of 9033 relevant lines covered (85.71%)

518.61 hits per line

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

28.46
/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
    /// Errors that can be replied to the sender
12
    ReplyToSender(ReplyableError),
13
    #[cfg(feature = "v2")]
14
    /// V2-specific errors that are infeasable to reply to the sender
15
    V2(crate::receive::v2::SessionError),
16
}
17

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

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

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

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

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

83
impl JsonReply {
84
    /// Create a new Reply
85
    pub fn new(error_code: ErrorCode, message: impl fmt::Display) -> Self {
4✔
86
        Self { error_code, message: message.to_string(), extra: serde_json::Map::new() }
4✔
87
    }
4✔
88

89
    /// Add an additional field to the JSON response
90
    pub fn with_extra(mut self, key: &str, value: impl Into<serde_json::Value>) -> Self {
×
91
        self.extra.insert(key.to_string(), value.into());
×
92
        self
×
93
    }
×
94

95
    /// Serialize the Reply to a JSON string
96
    pub fn to_json(&self) -> serde_json::Value {
4✔
97
        let mut map = serde_json::Map::new();
4✔
98
        map.insert("errorCode".to_string(), self.error_code.to_string().into());
4✔
99
        map.insert("message".to_string(), self.message.clone().into());
4✔
100
        map.extend(self.extra.clone());
4✔
101

102
        serde_json::Value::Object(map)
4✔
103
    }
4✔
104
}
105

106
impl From<&ReplyableError> for JsonReply {
107
    fn from(e: &ReplyableError) -> Self {
4✔
108
        use ReplyableError::*;
109
        match e {
4✔
110
            Payload(e) => e.into(),
2✔
111
            #[cfg(feature = "v1")]
112
            V1(e) => e.into(),
×
113
            Implementation(_) => JsonReply::new(Unavailable, "Receiver error"),
2✔
114
        }
115
    }
4✔
116
}
117

118
impl fmt::Display for ReplyableError {
119
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
10✔
120
        match &self {
10✔
121
            Self::Payload(e) => e.fmt(f),
2✔
122
            #[cfg(feature = "v1")]
123
            Self::V1(e) => e.fmt(f),
×
124
            Self::Implementation(e) => write!(f, "Internal Server Error: {e}"),
8✔
125
        }
126
    }
10✔
127
}
128

129
impl error::Error for ReplyableError {
130
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
131
        match &self {
×
132
            Self::Payload(e) => e.source(),
×
133
            #[cfg(feature = "v1")]
134
            Self::V1(e) => e.source(),
×
NEW
135
            Self::Implementation(e) => e.source(),
×
136
        }
137
    }
×
138
}
139

140
impl From<InternalPayloadError> for ReplyableError {
141
    fn from(e: InternalPayloadError) -> Self { ReplyableError::Payload(e.into()) }
3✔
142
}
143

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

160
impl From<InternalPayloadError> for PayloadError {
161
    fn from(value: InternalPayloadError) -> Self { PayloadError(value) }
3✔
162
}
163

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

197
impl From<&PayloadError> for JsonReply {
198
    fn from(e: &PayloadError) -> Self {
2✔
199
        use InternalPayloadError::*;
200

201
        match &e.0 {
2✔
202
            Utf8(_)
203
            | ParsePsbt(_)
204
            | InconsistentPsbt(_)
205
            | PrevTxOut(_)
206
            | MissingPayment
207
            | OriginalPsbtNotBroadcastable
208
            | InputOwned(_)
209
            | InputSeen(_)
210
            | PsbtBelowFeeRate(_, _) => JsonReply::new(OriginalPsbtRejected, e),
2✔
211

212
            FeeTooHigh(_, _) => JsonReply::new(NotEnoughMoney, e),
×
213

214
            SenderParams(e) => match e {
×
215
                super::optional_parameters::Error::UnknownVersion { supported_versions } => {
×
216
                    let supported_versions_json =
×
217
                        serde_json::to_string(supported_versions).unwrap_or_default();
×
218
                    JsonReply::new(VersionUnsupported, "This version of payjoin is not supported.")
×
219
                        .with_extra("supported", supported_versions_json)
×
220
                }
221
                super::optional_parameters::Error::FeeRate =>
222
                    JsonReply::new(OriginalPsbtRejected, e),
×
223
            },
224
        }
225
    }
2✔
226
}
227

228
impl fmt::Display for PayloadError {
229
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4✔
230
        use InternalPayloadError::*;
231

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

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

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

280
#[derive(Debug, PartialEq, Eq)]
281
pub(crate) enum InternalOutputSubstitutionError {
282
    /// Output substitution is disabled and output value was decreased
283
    DecreasedValueWhenDisabled,
284
    /// Output substitution is disabled and script pubkey was changed
285
    ScriptPubKeyChangedWhenDisabled,
286
    /// Current output substitution implementation doesn't support reducing the number of outputs
287
    NotEnoughOutputs,
288
    /// The provided drain script could not be identified in the provided replacement outputs
289
    InvalidDrainScript,
290
}
291

292
impl fmt::Display for OutputSubstitutionError {
293
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
294
        match &self.0 {
×
295
            InternalOutputSubstitutionError::DecreasedValueWhenDisabled => write!(f, "Decreasing the receiver output value is not allowed when output substitution is disabled"),
×
296
            InternalOutputSubstitutionError::ScriptPubKeyChangedWhenDisabled => write!(f, "Changing the receiver output script pubkey is not allowed when output substitution is disabled"),
×
297
            InternalOutputSubstitutionError::NotEnoughOutputs => write!(
×
298
                f,
×
299
                "Current output substitution implementation doesn't support reducing the number of outputs"
×
300
            ),
301
            InternalOutputSubstitutionError::InvalidDrainScript =>
302
                write!(f, "The provided drain script could not be identified in the provided replacement outputs"),
×
303
        }
304
    }
×
305
}
306

307
impl From<InternalOutputSubstitutionError> for OutputSubstitutionError {
308
    fn from(value: InternalOutputSubstitutionError) -> Self { OutputSubstitutionError(value) }
4✔
309
}
310

311
impl std::error::Error for OutputSubstitutionError {
312
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
×
313
        match &self.0 {
×
314
            InternalOutputSubstitutionError::DecreasedValueWhenDisabled => None,
×
315
            InternalOutputSubstitutionError::ScriptPubKeyChangedWhenDisabled => None,
×
316
            InternalOutputSubstitutionError::NotEnoughOutputs => None,
×
317
            InternalOutputSubstitutionError::InvalidDrainScript => None,
×
318
        }
319
    }
×
320
}
321

322
/// Error that may occur when coin selection fails.
323
///
324
/// This is currently opaque type because we aren't sure which variants will stay.
325
/// You can only display it.
326
#[derive(Debug, PartialEq, Eq)]
327
pub struct SelectionError(InternalSelectionError);
328

329
#[derive(Debug, PartialEq, Eq)]
330
pub(crate) enum InternalSelectionError {
331
    /// No candidates available for selection
332
    Empty,
333
    /// Current privacy selection implementation only supports 2-output transactions
334
    UnsupportedOutputLength,
335
    /// No selection candidates improve privacy
336
    NotFound,
337
}
338

339
impl fmt::Display for SelectionError {
340
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
341
        match &self.0 {
×
342
            InternalSelectionError::Empty => write!(f, "No candidates available for selection"),
×
343
            InternalSelectionError::UnsupportedOutputLength => write!(
×
344
                f,
×
345
                "Current privacy selection implementation only supports 2-output transactions"
×
346
            ),
347
            InternalSelectionError::NotFound =>
348
                write!(f, "No selection candidates improve privacy"),
×
349
        }
350
    }
×
351
}
352

353
impl error::Error for SelectionError {
354
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
355
        use InternalSelectionError::*;
356

357
        match &self.0 {
×
358
            Empty => None,
×
359
            UnsupportedOutputLength => None,
×
360
            NotFound => None,
×
361
        }
362
    }
×
363
}
364
impl From<InternalSelectionError> for SelectionError {
365
    fn from(value: InternalSelectionError) -> Self { SelectionError(value) }
7✔
366
}
367

368
/// Error that may occur when input contribution fails.
369
///
370
/// This is currently opaque type because we aren't sure which variants will stay.
371
/// You can only display it.
372
#[derive(Debug, PartialEq, Eq)]
373
pub struct InputContributionError(InternalInputContributionError);
374

375
#[derive(Debug, PartialEq, Eq)]
376
pub(crate) enum InternalInputContributionError {
377
    /// Total input value is not enough to cover additional output value
378
    ValueTooLow,
379
}
380

381
impl fmt::Display for InputContributionError {
382
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
383
        match &self.0 {
×
384
            InternalInputContributionError::ValueTooLow =>
385
                write!(f, "Total input value is not enough to cover additional output value"),
×
386
        }
387
    }
×
388
}
389

390
impl error::Error for InputContributionError {
391
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
392
        match &self.0 {
×
393
            InternalInputContributionError::ValueTooLow => None,
×
394
        }
395
    }
×
396
}
397

398
impl From<InternalInputContributionError> for InputContributionError {
399
    fn from(value: InternalInputContributionError) -> Self { InputContributionError(value) }
×
400
}
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