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    /// Catch-all for reasons this build of `mostro-core` does not know yet.
113    ///
114    /// Newer daemons may emit reasons added after this release; without this
115    /// variant the whole `CantDo` payload would fail to deserialize. Never
116    /// emitted by a daemon on purpose.
117    #[serde(other)]
118    Unknown,
119}
120
121/// Internal errors raised by services behind the Mostro API.
122///
123/// Unlike [`CantDoReason`], values of this enum are not expected to be
124/// forwarded verbatim to end users; they are meant for logs, telemetry and
125/// other server-to-server diagnostics.
126#[derive(Debug, PartialEq, Eq)]
127pub enum ServiceError {
128    /// Wraps an error returned by `nostr_sdk`.
129    NostrError(String),
130    /// The invoice string could not be parsed as a valid BOLT-11 invoice.
131    ParsingInvoiceError,
132    /// A numeric value could not be parsed.
133    ParsingNumberError,
134    /// The invoice has expired.
135    InvoiceExpiredError,
136    /// The invoice is otherwise invalid.
137    InvoiceInvalidError,
138    /// The invoice expiration time is below the minimum required.
139    MinExpirationTimeError,
140    /// The invoice amount is below the minimum allowed.
141    MinAmountError,
142    /// The invoice amount does not match the expected value.
143    WrongAmountError,
144    /// The price API did not answer in time.
145    NoAPIResponse,
146    /// The requested currency is not listed by the exchange API.
147    NoCurrency,
148    /// A price exists but is older than the configured staleness window, so
149    /// it must not be used to price an order (the multi-source price
150    /// manager serves last-known-good only up to that TTL).
151    PriceTooStale,
152    /// The exchange API returned a response that could not be parsed.
153    MalformedAPIRes,
154    /// Amount value is negative where only positives are allowed.
155    NegativeAmount,
156    /// A Lightning Address could not be parsed.
157    LnAddressParseError,
158    /// A Lightning Address payment was attempted with a wrong amount.
159    LnAddressWrongAmount,
160    /// A Lightning payment failed; the inner string carries the reason.
161    LnPaymentError(String),
162    /// Communication with the Lightning node failed.
163    LnNodeError(String),
164    /// Order id was not found in the database.
165    InvalidOrderId,
166    /// Database access failed; the inner string carries the detail.
167    DbAccessError(String),
168    /// The provided public key is invalid.
169    InvalidPubkey,
170    /// Hold-invoice operation failed; the inner string carries the detail.
171    HoldInvoiceError(String),
172    /// Could not update the order status in the database.
173    UpdateOrderStatusError,
174    /// The order status is invalid.
175    InvalidOrderStatus,
176    /// The order kind is invalid.
177    InvalidOrderKind,
178    /// A dispute already exists for this order.
179    DisputeAlreadyExists,
180    /// Could not publish the dispute Nostr event.
181    DisputeEventError,
182    /// The rating message itself is invalid.
183    InvalidRating,
184    /// The rating value is outside the accepted range.
185    InvalidRatingValue,
186    /// Failed to serialize or deserialize a [`crate::message::Message`].
187    MessageSerializationError,
188    /// The dispute id is invalid or unknown.
189    InvalidDisputeId,
190    /// The dispute status is invalid.
191    InvalidDisputeStatus,
192    /// The payload does not match the action.
193    InvalidPayload,
194    /// Any other unexpected error; inner string carries the detail.
195    UnexpectedError(String),
196    /// An environment variable could not be read or parsed.
197    EnvVarError(String),
198    /// Underlying I/O error.
199    IOError(String),
200    /// NIP-44/NIP-59 encryption failed.
201    EncryptionError(String),
202    /// NIP-44/NIP-59 decryption failed.
203    DecryptionError(String),
204}
205
206/// Top-level error type returned by the Mostro API surface.
207///
208/// Most public functions in this crate return `Result<T, MostroError>`.
209/// Match on the variants to distinguish between user-actionable "can't do"
210/// responses and internal service errors.
211#[derive(Debug, PartialEq, Eq)]
212pub enum MostroError {
213    /// An internal service-level error; diagnostic only.
214    MostroInternalErr(ServiceError),
215    /// A structured "can't do" response to surface to the user.
216    MostroCantDo(CantDoReason),
217}
218
219impl std::error::Error for MostroError {}
220
221impl std::fmt::Display for MostroError {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        match self {
224            MostroError::MostroInternalErr(m) => write!(f, "Error caused by {}", m),
225            MostroError::MostroCantDo(m) => write!(f, "Sending cantDo message to user for {:?}", m),
226        }
227    }
228}
229
230impl std::fmt::Display for ServiceError {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        match self {
233            ServiceError::ParsingInvoiceError => write!(f, "Incorrect invoice"),
234            ServiceError::ParsingNumberError => write!(f, "Error parsing the number"),
235            ServiceError::InvoiceExpiredError => write!(f, "Invoice has expired"),
236            ServiceError::MinExpirationTimeError => write!(f, "Minimal expiration time on invoice"),
237            ServiceError::InvoiceInvalidError => write!(f, "Invoice is invalid"),
238            ServiceError::MinAmountError => write!(f, "Minimal payment amount"),
239            ServiceError::WrongAmountError => write!(f, "The amount on this invoice is wrong"),
240            ServiceError::NoAPIResponse => write!(f, "Price API not answered - retry"),
241            ServiceError::NoCurrency => write!(f, "Currency requested is not present in the exchange list, please specify a fixed rate"),
242            ServiceError::PriceTooStale => write!(f, "Exchange rate is too stale to price an order - retry or use a fixed rate"),
243            ServiceError::MalformedAPIRes => write!(f, "Malformed answer from exchange quoting request"),
244            ServiceError::NegativeAmount => write!(f, "Negative amount is not valid"),
245            ServiceError::LnAddressWrongAmount => write!(f, "Ln address need amount of 0 sats - please check your order"),
246            ServiceError::LnAddressParseError  => write!(f, "Ln address parsing error - please check your address"),
247            ServiceError::LnPaymentError(e) => write!(f, "Lightning payment failure cause: {}",e),
248            ServiceError::LnNodeError(e) => write!(f, "Lightning node connection failure caused by: {}",e),
249            ServiceError::InvalidOrderId => write!(f, "Order id not present in database"),
250            ServiceError::InvalidPubkey => write!(f, "Invalid pubkey"),
251            ServiceError::DbAccessError(e) => write!(f, "Error in database access: {}",e),
252            ServiceError::HoldInvoiceError(e) => write!(f, "Error holding invoice: {}",e),
253            ServiceError::UpdateOrderStatusError => write!(f, "Error updating order status"),
254            ServiceError::InvalidOrderStatus => write!(f, "Invalid order status"),
255            ServiceError::InvalidOrderKind => write!(f, "Invalid order kind"),
256            ServiceError::DisputeAlreadyExists => write!(f, "Dispute already exists"),
257            ServiceError::DisputeEventError => write!(f, "Error publishing dispute event"),
258            ServiceError::NostrError(e) => write!(f, "Error in nostr: {}",e),
259            ServiceError::InvalidRating => write!(f, "Invalid rating message"),
260            ServiceError::InvalidRatingValue => write!(f, "Invalid rating value"),
261            ServiceError::MessageSerializationError => write!(f, "Error serializing message"),
262            ServiceError::InvalidDisputeId => write!(f, "Invalid dispute id"),
263            ServiceError::InvalidDisputeStatus => write!(f, "Invalid dispute status"),
264            ServiceError::InvalidPayload => write!(f, "Invalid payload"),
265            ServiceError::UnexpectedError(e) => write!(f, "Unexpected error: {}", e),
266            ServiceError::EnvVarError(e) => write!(f, "Environment variable error: {}", e),
267            ServiceError::IOError(e) => write!(f, "IO error: {}", e),
268            ServiceError::EncryptionError(e) => write!(f, "Encryption error: {}", e),
269            ServiceError::DecryptionError(e) => write!(f, "Decryption error: {}", e),
270        }
271    }
272}
273
274#[cfg(test)]
275mod tests {
276    use super::*;
277
278    #[test]
279    fn invalid_payload_serializes_to_snake_case() {
280        let json = serde_json::to_string(&CantDoReason::InvalidPayload).unwrap();
281        assert_eq!(json, "\"invalid_payload\"");
282        let round: CantDoReason = serde_json::from_str(&json).unwrap();
283        assert_eq!(round, CantDoReason::InvalidPayload);
284    }
285
286    #[test]
287    fn price_too_stale_serializes_to_snake_case() {
288        let json = serde_json::to_string(&CantDoReason::PriceTooStale).unwrap();
289        assert_eq!(json, "\"price_too_stale\"");
290        let round: CantDoReason = serde_json::from_str(&json).unwrap();
291        assert_eq!(round, CantDoReason::PriceTooStale);
292    }
293    #[test]
294    fn maintenance_mode_serializes_to_snake_case() {
295        let json = serde_json::to_string(&CantDoReason::MaintenanceMode).unwrap();
296        assert_eq!(json, "\"maintenance_mode\"");
297        let round: CantDoReason = serde_json::from_str(&json).unwrap();
298        assert_eq!(round, CantDoReason::MaintenanceMode);
299    }
300
301    #[test]
302    fn unknown_reason_deserializes_to_unknown_catch_all() {
303        let round: CantDoReason = serde_json::from_str("\"reason_from_the_future\"").unwrap();
304        assert_eq!(round, CantDoReason::Unknown);
305    }
306
307    #[test]
308    fn unknown_reason_inside_cant_do_payload_does_not_break_the_message() {
309        let payload: crate::message::Payload =
310            serde_json::from_str(r#"{"cant_do":"reason_from_the_future"}"#).unwrap();
311        assert!(matches!(
312            payload,
313            crate::message::Payload::CantDo(Some(CantDoReason::Unknown))
314        ));
315    }
316
317    #[test]
318    fn unknown_serializes_to_snake_case() {
319        let json = serde_json::to_string(&CantDoReason::Unknown).unwrap();
320        assert_eq!(json, "\"unknown\"");
321    }
322}