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

payjoin / rust-payjoin / 14111798823

27 Mar 2025 04:29PM UTC coverage: 81.667% (+0.2%) from 81.45%
14111798823

Pull #606

github

web-flow
Merge 28f41b350 into 752fceebf
Pull Request #606: Reply json

57 of 91 new or added lines in 6 files covered. (62.64%)

4 existing lines in 2 files now uncovered.

5114 of 6262 relevant lines covered (81.67%)

738.19 hits per line

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

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

3
use crate::error_codes::ErrorCode::{
4
    self, NotEnoughMoney, OriginalPsbtRejected, Unavailable, VersionUnsupported,
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
52
///    after conversion into [`JsonReply`]
53
#[derive(Debug)]
54
pub enum ReplyableError {
55
    /// Error arising from validation of the original PSBT payload
56
    Payload(PayloadError),
57
    /// Protocol-specific errors for BIP-78 v1 requests (e.g. HTTP request validation, parameter checks)
58
    #[cfg(feature = "v1")]
59
    V1(crate::receive::v1::RequestError),
60
    /// Error arising due to the specific receiver implementation
61
    ///
62
    /// e.g. database errors, network failures, wallet errors
63
    Implementation(ImplementationError),
64
}
65

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

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

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

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

3✔
103
        serde_json::Value::Object(map)
3✔
104
    }
3✔
105
}
106

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

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

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

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

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

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

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

200
impl From<PayloadError> for JsonReply {
201
    fn from(e: PayloadError) -> Self {
1✔
202
        use InternalPayloadError::*;
203

204
        match &e.0 {
1✔
205
            Utf8(_)
206
            | ParsePsbt(_)
207
            | InconsistentPsbt(_)
208
            | PrevTxOut(_)
209
            | MissingPayment
210
            | OriginalPsbtNotBroadcastable
211
            | InputOwned(_)
212
            | InputWeight(_)
213
            | InputSeen(_)
214
            | PsbtBelowFeeRate(_, _) => JsonReply::new(OriginalPsbtRejected, e),
1✔
215

NEW
216
            FeeTooHigh(_, _) => JsonReply::new(NotEnoughMoney, e),
×
217

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

232
impl fmt::Display for PayloadError {
233
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1✔
234
        use InternalPayloadError::*;
235

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

261
impl std::error::Error for PayloadError {
262
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
×
263
        use InternalPayloadError::*;
264
        match &self.0 {
×
265
            Utf8(e) => Some(e),
×
266
            ParsePsbt(e) => Some(e),
×
267
            SenderParams(e) => Some(e),
×
268
            InconsistentPsbt(e) => Some(e),
×
269
            PrevTxOut(e) => Some(e),
×
270
            InputWeight(e) => Some(e),
×
271
            PsbtBelowFeeRate(_, _) => None,
×
272
            FeeTooHigh(_, _) => None,
×
273
            MissingPayment => None,
×
274
            OriginalPsbtNotBroadcastable => None,
×
275
            InputOwned(_) => None,
×
276
            InputSeen(_) => None,
×
277
        }
278
    }
×
279
}
280

281
/// Error that may occur when output substitution fails.
282
///
283
/// This is currently opaque type because we aren't sure which variants will stay.
284
/// You can only display it.
285
#[derive(Debug, PartialEq)]
286
pub struct OutputSubstitutionError(InternalOutputSubstitutionError);
287

288
#[derive(Debug, PartialEq)]
289
pub(crate) enum InternalOutputSubstitutionError {
290
    /// Output substitution is disabled and output value was decreased
291
    DecreasedValueWhenDisabled,
292
    /// Output substitution is disabled and script pubkey was changed
293
    ScriptPubKeyChangedWhenDisabled,
294
    /// Current output substitution implementation doesn't support reducing the number of outputs
295
    NotEnoughOutputs,
296
    /// The provided drain script could not be identified in the provided replacement outputs
297
    InvalidDrainScript,
298
}
299

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

315
impl From<InternalOutputSubstitutionError> for OutputSubstitutionError {
316
    fn from(value: InternalOutputSubstitutionError) -> Self { OutputSubstitutionError(value) }
4✔
317
}
318

319
impl std::error::Error for OutputSubstitutionError {
320
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
×
321
        match &self.0 {
×
322
            InternalOutputSubstitutionError::DecreasedValueWhenDisabled => None,
×
323
            InternalOutputSubstitutionError::ScriptPubKeyChangedWhenDisabled => None,
×
324
            InternalOutputSubstitutionError::NotEnoughOutputs => None,
×
325
            InternalOutputSubstitutionError::InvalidDrainScript => None,
×
326
        }
327
    }
×
328
}
329

330
/// Error that may occur when coin selection fails.
331
///
332
/// This is currently opaque type because we aren't sure which variants will stay.
333
/// You can only display it.
334
#[derive(Debug)]
335
pub struct SelectionError(InternalSelectionError);
336

337
#[derive(Debug)]
338
pub(crate) enum InternalSelectionError {
339
    /// No candidates available for selection
340
    Empty,
341
    /// Current privacy selection implementation only supports 2-output transactions
342
    UnsupportedOutputLength,
343
    /// No selection candidates improve privacy
344
    NotFound,
345
}
346

347
impl fmt::Display for SelectionError {
348
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
349
        match &self.0 {
×
350
            InternalSelectionError::Empty => write!(f, "No candidates available for selection"),
×
351
            InternalSelectionError::UnsupportedOutputLength => write!(
×
352
                f,
×
353
                "Current privacy selection implementation only supports 2-output transactions"
×
354
            ),
×
355
            InternalSelectionError::NotFound =>
356
                write!(f, "No selection candidates improve privacy"),
×
357
        }
358
    }
×
359
}
360

361
impl error::Error for SelectionError {
362
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
363
        use InternalSelectionError::*;
364

365
        match &self.0 {
×
366
            Empty => None,
×
367
            UnsupportedOutputLength => None,
×
368
            NotFound => None,
×
369
        }
370
    }
×
371
}
372
impl From<InternalSelectionError> for SelectionError {
373
    fn from(value: InternalSelectionError) -> Self { SelectionError(value) }
4✔
374
}
375

376
/// Error that may occur when input contribution fails.
377
///
378
/// This is currently opaque type because we aren't sure which variants will stay.
379
/// You can only display it.
380
#[derive(Debug)]
381
pub struct InputContributionError(InternalInputContributionError);
382

383
#[derive(Debug)]
384
pub(crate) enum InternalInputContributionError {
385
    /// Total input value is not enough to cover additional output value
386
    ValueTooLow,
387
}
388

389
impl fmt::Display for InputContributionError {
390
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
×
391
        match &self.0 {
×
392
            InternalInputContributionError::ValueTooLow =>
×
393
                write!(f, "Total input value is not enough to cover additional output value"),
×
394
        }
×
395
    }
×
396
}
397

398
impl error::Error for InputContributionError {
399
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
×
400
        match &self.0 {
×
401
            InternalInputContributionError::ValueTooLow => None,
×
402
        }
×
403
    }
×
404
}
405

406
impl From<InternalInputContributionError> for InputContributionError {
407
    fn from(value: InternalInputContributionError) -> Self { InputContributionError(value) }
×
408
}
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