Skip to main content

mostro_core/
error.rs

1//! Error taxonomy used across the crate.
2//!
3//! Errors surfaced to clients are modelled as [`MostroError`], which is split
4//! into two branches:
5//!
6//! * [`MostroError::MostroCantDo`] — a "soft" error: the request was
7//!   well-formed but the server refuses to perform the action (e.g. the order
8//!   is not in the right state). Clients should surface the inner
9//!   [`CantDoReason`] to the user.
10//! * [`MostroError::MostroInternalErr`] — a "hard" error: something went
11//!   wrong while processing the request (database failure, Nostr relay
12//!   issue, malformed invoice, etc.). The inner [`ServiceError`] carries the
13//!   diagnostic detail.
14//!
15//! Both inner enums implement [`Display`](std::fmt::Display) with
16//! human-readable messages suited for logging.
17
18use crate::prelude::*;
19
20/// Machine-readable reasons carried by a `CantDo` response.
21///
22/// Serialized in `snake_case` so clients can pattern-match on the value
23/// transported in [`crate::message::Payload::CantDo`].
24#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
25#[serde(rename_all = "snake_case")]
26pub enum CantDoReason {
27    /// The provided signature is invalid or missing.
28    InvalidSignature,
29    /// The specified trade index does not exist or is invalid.
30    InvalidTradeIndex,
31    /// The provided amount is invalid or out of acceptable range.
32    InvalidAmount,
33    /// The provided invoice is malformed or expired.
34    InvalidInvoice,
35    /// The payment request is invalid or cannot be processed.
36    InvalidPaymentRequest,
37    /// The specified peer is invalid or not found.
38    InvalidPeer,
39    /// The rating value is invalid or out of range.
40    InvalidRating,
41    /// The text message is invalid or contains prohibited content.
42    InvalidTextMessage,
43    /// The order kind is invalid.
44    InvalidOrderKind,
45    /// The order status is invalid.
46    InvalidOrderStatus,
47    /// The provided public key is invalid.
48    InvalidPubkey,
49    /// One or more request parameters are invalid.
50    InvalidParameters,
51    /// The provided payload is the wrong shape for this action,
52    /// or carries values that cannot be processed (e.g. a
53    /// `BondResolution` requesting a slash against a side with no
54    /// active bond row). The caller should correct and resend.
55    InvalidPayload,
56    /// The targeted order has already been canceled.
57    OrderAlreadyCanceled,
58    /// User creation failed on the server side.
59    CantCreateUser,
60    /// The caller tried to operate on an order that does not belong to them.
61    IsNotYourOrder,
62    /// The requested action is not allowed in the order's current status.
63    NotAllowedByStatus,
64    /// The fiat amount is outside the allowed range for this order.
65    OutOfRangeFiatAmount,
66    /// The sats amount is outside the allowed range for this order.
67    OutOfRangeSatsAmount,
68    /// No fresh exchange rate is available for the order's fiat currency:
69    /// the last-known-good price is older than the node's staleness window,
70    /// so a market-priced order cannot be created or taken right now. The
71    /// caller should retry once pricing recovers, or use a fixed rate.
72    PriceTooStale,
73    /// The caller tried to operate on a dispute that does not belong to them.
74    IsNotYourDispute,
75    /// A solver is being notified that an admin has taken over their dispute.
76    DisputeTakenByAdmin,
77    /// The caller is authenticated but lacks the permission for this action.
78    NotAuthorized,
79    /// A dispute could not be created (e.g. order not in a disputable state).
80    DisputeCreationError,
81    /// Generic "resource not found" error.
82    NotFound,
83    /// The dispute is in an invalid state for the requested action.
84    InvalidDisputeStatus,
85    /// The requested action is invalid.
86    InvalidAction,
87    /// The caller already has a pending order and cannot create another.
88    PendingOrderExists,
89    /// The fiat currency code is not accepted by this Mostro node.
90    InvalidFiatCurrency,
91    /// The caller is being rate-limited.
92    TooManyRequests,
93    /// The submitted Cashu token is malformed, cannot be parsed, or its
94    /// 2-of-3 spending condition does not match the expected
95    /// buyer/seller/Mostro pubkeys.
96    InvalidCashuToken,
97    /// The configured Cashu mint could not be reached or did not answer the
98    /// state check.
99    CashuMintUnavailable,
100    /// The provided mint URL is malformed or does not match the node's
101    /// configured mint.
102    InvalidMintUrl,
103    /// The requested action needs a locked Cashu escrow, but none has been
104    /// recorded for this order.
105    CashuEscrowNotLocked,
106    /// A required Cashu signature is missing from the request.
107    CashuSignatureMissing,
108    /// Mostro is in maintenance mode (for example draining escrow before a
109    /// Lightning node migration) and is not accepting new orders or takes.
110    /// Actions on already existing orders keep working.
111    MaintenanceMode,
112    /// The `payment_hash` of a payer declaration is not 64 lowercase hex
113    /// characters.
114    InvalidPaymentHash,
115    /// `fiat-sent` was refused because this node requires the buyer to send
116    /// `declare-payer` first.
117    PayerNotDeclared,
118    /// A reputation request carries no identity proof: in full privacy mode
119    /// there is no identity-bound reputation to export or import into.
120    ReputationIdentityRequired,
121    /// The account cannot export its reputation: it is banned, or has fewer
122    /// than 10 completed trades or 5 ratings received.
123    NotEligibleForReputationExport,
124    /// The account is bound to another identity and the export request
125    /// carries no rebind authorisation.
126    ReputationBoundToOtherIdentity,
127    /// The rebind authorisation is malformed, badly signed, not signed by the
128    /// bound identity, names another issuer or has expired.
129    InvalidReputationRebind,
130    /// The attestation does not parse, is badly signed, breaks a tag rule,
131    /// is dated in the future or outlives the destination's lifetime cap.
132    InvalidReputationAttestation,
133    /// The attestation is signed by a key in no trust-list entry, or by the
134    /// destination's own issuer key.
135    UntrustedReputationIssuer,
136    /// The attestation has expired.
137    ExpiredReputationAttestation,
138    /// The attestation names another identity than the one the request
139    /// proves.
140    ReputationIdentityMismatch,
141    /// The source account, or another account from the same issuer for this
142    /// identity, was imported before.
143    ReputationAlreadyImported,
144    /// Catch-all for reasons this build of `mostro-core` does not know yet.
145    ///
146    /// Newer daemons may emit reasons added after this release; without this
147    /// variant the whole `CantDo` payload would fail to deserialize. Never
148    /// emitted by a daemon on purpose.
149    #[serde(other)]
150    Unknown,
151}
152
153/// Internal errors raised by services behind the Mostro API.
154///
155/// Unlike [`CantDoReason`], values of this enum are not expected to be
156/// forwarded verbatim to end users; they are meant for logs, telemetry and
157/// other server-to-server diagnostics.
158#[derive(Debug, PartialEq, Eq)]
159pub enum ServiceError {
160    /// Wraps an error returned by `nostr_sdk`.
161    NostrError(String),
162    /// The invoice string could not be parsed as a valid BOLT-11 invoice.
163    ParsingInvoiceError,
164    /// A numeric value could not be parsed.
165    ParsingNumberError,
166    /// The invoice has expired.
167    InvoiceExpiredError,
168    /// The invoice is otherwise invalid.
169    InvoiceInvalidError,
170    /// The invoice expiration time is below the minimum required.
171    MinExpirationTimeError,
172    /// The invoice amount is below the minimum allowed.
173    MinAmountError,
174    /// The invoice amount does not match the expected value.
175    WrongAmountError,
176    /// The price API did not answer in time.
177    NoAPIResponse,
178    /// The requested currency is not listed by the exchange API.
179    NoCurrency,
180    /// A price exists but is older than the configured staleness window, so
181    /// it must not be used to price an order (the multi-source price
182    /// manager serves last-known-good only up to that TTL).
183    PriceTooStale,
184    /// The exchange API returned a response that could not be parsed.
185    MalformedAPIRes,
186    /// Amount value is negative where only positives are allowed.
187    NegativeAmount,
188    /// A Lightning Address could not be parsed.
189    LnAddressParseError,
190    /// A Lightning Address payment was attempted with a wrong amount.
191    LnAddressWrongAmount,
192    /// A Lightning payment failed; the inner string carries the reason.
193    LnPaymentError(String),
194    /// Communication with the Lightning node failed.
195    LnNodeError(String),
196    /// Order id was not found in the database.
197    InvalidOrderId,
198    /// Database access failed; the inner string carries the detail.
199    DbAccessError(String),
200    /// The provided public key is invalid.
201    InvalidPubkey,
202    /// Hold-invoice operation failed; the inner string carries the detail.
203    HoldInvoiceError(String),
204    /// Could not update the order status in the database.
205    UpdateOrderStatusError,
206    /// The order status is invalid.
207    InvalidOrderStatus,
208    /// The order kind is invalid.
209    InvalidOrderKind,
210    /// A dispute already exists for this order.
211    DisputeAlreadyExists,
212    /// Could not publish the dispute Nostr event.
213    DisputeEventError,
214    /// The rating message itself is invalid.
215    InvalidRating,
216    /// The rating value is outside the accepted range.
217    InvalidRatingValue,
218    /// Failed to serialize or deserialize a [`crate::message::Message`].
219    MessageSerializationError,
220    /// The dispute id is invalid or unknown.
221    InvalidDisputeId,
222    /// The dispute status is invalid.
223    InvalidDisputeStatus,
224    /// The payload does not match the action.
225    InvalidPayload,
226    /// Any other unexpected error; inner string carries the detail.
227    UnexpectedError(String),
228    /// An environment variable could not be read or parsed.
229    EnvVarError(String),
230    /// Underlying I/O error.
231    IOError(String),
232    /// NIP-44/NIP-59 encryption failed.
233    EncryptionError(String),
234    /// NIP-44/NIP-59 decryption failed.
235    DecryptionError(String),
236}
237
238/// Top-level error type returned by the Mostro API surface.
239///
240/// Most public functions in this crate return `Result<T, MostroError>`.
241/// Match on the variants to distinguish between user-actionable "can't do"
242/// responses and internal service errors.
243#[derive(Debug, PartialEq, Eq)]
244pub enum MostroError {
245    /// An internal service-level error; diagnostic only.
246    MostroInternalErr(ServiceError),
247    /// A structured "can't do" response to surface to the user.
248    MostroCantDo(CantDoReason),
249}
250
251impl std::error::Error for MostroError {}
252
253impl std::fmt::Display for MostroError {
254    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255        match self {
256            MostroError::MostroInternalErr(m) => write!(f, "Error caused by {}", m),
257            MostroError::MostroCantDo(m) => write!(f, "Sending cantDo message to user for {:?}", m),
258        }
259    }
260}
261
262impl std::fmt::Display for ServiceError {
263    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
264        match self {
265            ServiceError::ParsingInvoiceError => write!(f, "Incorrect invoice"),
266            ServiceError::ParsingNumberError => write!(f, "Error parsing the number"),
267            ServiceError::InvoiceExpiredError => write!(f, "Invoice has expired"),
268            ServiceError::MinExpirationTimeError => write!(f, "Minimal expiration time on invoice"),
269            ServiceError::InvoiceInvalidError => write!(f, "Invoice is invalid"),
270            ServiceError::MinAmountError => write!(f, "Minimal payment amount"),
271            ServiceError::WrongAmountError => write!(f, "The amount on this invoice is wrong"),
272            ServiceError::NoAPIResponse => write!(f, "Price API not answered - retry"),
273            ServiceError::NoCurrency => write!(f, "Currency requested is not present in the exchange list, please specify a fixed rate"),
274            ServiceError::PriceTooStale => write!(f, "Exchange rate is too stale to price an order - retry or use a fixed rate"),
275            ServiceError::MalformedAPIRes => write!(f, "Malformed answer from exchange quoting request"),
276            ServiceError::NegativeAmount => write!(f, "Negative amount is not valid"),
277            ServiceError::LnAddressWrongAmount => write!(f, "Ln address need amount of 0 sats - please check your order"),
278            ServiceError::LnAddressParseError  => write!(f, "Ln address parsing error - please check your address"),
279            ServiceError::LnPaymentError(e) => write!(f, "Lightning payment failure cause: {}",e),
280            ServiceError::LnNodeError(e) => write!(f, "Lightning node connection failure caused by: {}",e),
281            ServiceError::InvalidOrderId => write!(f, "Order id not present in database"),
282            ServiceError::InvalidPubkey => write!(f, "Invalid pubkey"),
283            ServiceError::DbAccessError(e) => write!(f, "Error in database access: {}",e),
284            ServiceError::HoldInvoiceError(e) => write!(f, "Error holding invoice: {}",e),
285            ServiceError::UpdateOrderStatusError => write!(f, "Error updating order status"),
286            ServiceError::InvalidOrderStatus => write!(f, "Invalid order status"),
287            ServiceError::InvalidOrderKind => write!(f, "Invalid order kind"),
288            ServiceError::DisputeAlreadyExists => write!(f, "Dispute already exists"),
289            ServiceError::DisputeEventError => write!(f, "Error publishing dispute event"),
290            ServiceError::NostrError(e) => write!(f, "Error in nostr: {}",e),
291            ServiceError::InvalidRating => write!(f, "Invalid rating message"),
292            ServiceError::InvalidRatingValue => write!(f, "Invalid rating value"),
293            ServiceError::MessageSerializationError => write!(f, "Error serializing message"),
294            ServiceError::InvalidDisputeId => write!(f, "Invalid dispute id"),
295            ServiceError::InvalidDisputeStatus => write!(f, "Invalid dispute status"),
296            ServiceError::InvalidPayload => write!(f, "Invalid payload"),
297            ServiceError::UnexpectedError(e) => write!(f, "Unexpected error: {}", e),
298            ServiceError::EnvVarError(e) => write!(f, "Environment variable error: {}", e),
299            ServiceError::IOError(e) => write!(f, "IO error: {}", e),
300            ServiceError::EncryptionError(e) => write!(f, "Encryption error: {}", e),
301            ServiceError::DecryptionError(e) => write!(f, "Decryption error: {}", e),
302        }
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn invalid_payload_serializes_to_snake_case() {
312        let json = serde_json::to_string(&CantDoReason::InvalidPayload).unwrap();
313        assert_eq!(json, "\"invalid_payload\"");
314        let round: CantDoReason = serde_json::from_str(&json).unwrap();
315        assert_eq!(round, CantDoReason::InvalidPayload);
316    }
317
318    #[test]
319    fn price_too_stale_serializes_to_snake_case() {
320        let json = serde_json::to_string(&CantDoReason::PriceTooStale).unwrap();
321        assert_eq!(json, "\"price_too_stale\"");
322        let round: CantDoReason = serde_json::from_str(&json).unwrap();
323        assert_eq!(round, CantDoReason::PriceTooStale);
324    }
325    #[test]
326    fn maintenance_mode_serializes_to_snake_case() {
327        let json = serde_json::to_string(&CantDoReason::MaintenanceMode).unwrap();
328        assert_eq!(json, "\"maintenance_mode\"");
329        let round: CantDoReason = serde_json::from_str(&json).unwrap();
330        assert_eq!(round, CantDoReason::MaintenanceMode);
331    }
332
333    #[test]
334    fn payer_history_reasons_serialize_to_snake_case() {
335        for (reason, wire) in [
336            (CantDoReason::InvalidPaymentHash, "\"invalid_payment_hash\""),
337            (CantDoReason::PayerNotDeclared, "\"payer_not_declared\""),
338        ] {
339            let json = serde_json::to_string(&reason).unwrap();
340            assert_eq!(json, wire);
341            let round: CantDoReason = serde_json::from_str(&json).unwrap();
342            assert_eq!(round, reason);
343        }
344    }
345
346    #[test]
347    fn unknown_reason_deserializes_to_unknown_catch_all() {
348        let round: CantDoReason = serde_json::from_str("\"reason_from_the_future\"").unwrap();
349        assert_eq!(round, CantDoReason::Unknown);
350    }
351
352    #[test]
353    fn unknown_reason_inside_cant_do_payload_does_not_break_the_message() {
354        let payload: crate::message::Payload =
355            serde_json::from_str(r#"{"cant_do":"reason_from_the_future"}"#).unwrap();
356        assert!(matches!(
357            payload,
358            crate::message::Payload::CantDo(Some(CantDoReason::Unknown))
359        ));
360    }
361
362    #[test]
363    fn unknown_serializes_to_snake_case() {
364        let json = serde_json::to_string(&CantDoReason::Unknown).unwrap();
365        assert_eq!(json, "\"unknown\"");
366    }
367
368    /// The reasons the protocol's reputation chapter documents, by the exact
369    /// snake_case spelling clients match on.
370    #[test]
371    fn reputation_reasons_travel_with_their_documented_names() {
372        let reasons = [
373            (
374                CantDoReason::ReputationIdentityRequired,
375                "reputation_identity_required",
376            ),
377            (
378                CantDoReason::NotEligibleForReputationExport,
379                "not_eligible_for_reputation_export",
380            ),
381            (
382                CantDoReason::ReputationBoundToOtherIdentity,
383                "reputation_bound_to_other_identity",
384            ),
385            (
386                CantDoReason::InvalidReputationRebind,
387                "invalid_reputation_rebind",
388            ),
389            (
390                CantDoReason::InvalidReputationAttestation,
391                "invalid_reputation_attestation",
392            ),
393            (
394                CantDoReason::UntrustedReputationIssuer,
395                "untrusted_reputation_issuer",
396            ),
397            (
398                CantDoReason::ExpiredReputationAttestation,
399                "expired_reputation_attestation",
400            ),
401            (
402                CantDoReason::ReputationIdentityMismatch,
403                "reputation_identity_mismatch",
404            ),
405            (
406                CantDoReason::ReputationAlreadyImported,
407                "reputation_already_imported",
408            ),
409        ];
410        for (reason, wire) in reasons {
411            let json = serde_json::to_string(&reason).unwrap();
412            assert_eq!(json, format!("\"{wire}\""));
413            assert_eq!(serde_json::from_str::<CantDoReason>(&json).unwrap(), reason);
414        }
415    }
416}