mostro-core 0.17.1

Mostro Core library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
//! Error taxonomy used across the crate.
//!
//! Errors surfaced to clients are modelled as [`MostroError`], which is split
//! into two branches:
//!
//! * [`MostroError::MostroCantDo`] — a "soft" error: the request was
//!   well-formed but the server refuses to perform the action (e.g. the order
//!   is not in the right state). Clients should surface the inner
//!   [`CantDoReason`] to the user.
//! * [`MostroError::MostroInternalErr`] — a "hard" error: something went
//!   wrong while processing the request (database failure, Nostr relay
//!   issue, malformed invoice, etc.). The inner [`ServiceError`] carries the
//!   diagnostic detail.
//!
//! Both inner enums implement [`Display`](std::fmt::Display) with
//! human-readable messages suited for logging.

use crate::prelude::*;

/// Machine-readable reasons carried by a `CantDo` response.
///
/// Serialized in `snake_case` so clients can pattern-match on the value
/// transported in [`crate::message::Payload::CantDo`].
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CantDoReason {
    /// The provided signature is invalid or missing.
    InvalidSignature,
    /// The specified trade index does not exist or is invalid.
    InvalidTradeIndex,
    /// The provided amount is invalid or out of acceptable range.
    InvalidAmount,
    /// The provided invoice is malformed or expired.
    InvalidInvoice,
    /// The payment request is invalid or cannot be processed.
    InvalidPaymentRequest,
    /// The specified peer is invalid or not found.
    InvalidPeer,
    /// The rating value is invalid or out of range.
    InvalidRating,
    /// The text message is invalid or contains prohibited content.
    InvalidTextMessage,
    /// The order kind is invalid.
    InvalidOrderKind,
    /// The order status is invalid.
    InvalidOrderStatus,
    /// The provided public key is invalid.
    InvalidPubkey,
    /// One or more request parameters are invalid.
    InvalidParameters,
    /// The provided payload is the wrong shape for this action,
    /// or carries values that cannot be processed (e.g. a
    /// `BondResolution` requesting a slash against a side with no
    /// active bond row). The caller should correct and resend.
    InvalidPayload,
    /// The targeted order has already been canceled.
    OrderAlreadyCanceled,
    /// User creation failed on the server side.
    CantCreateUser,
    /// The caller tried to operate on an order that does not belong to them.
    IsNotYourOrder,
    /// The requested action is not allowed in the order's current status.
    NotAllowedByStatus,
    /// The fiat amount is outside the allowed range for this order.
    OutOfRangeFiatAmount,
    /// The sats amount is outside the allowed range for this order.
    OutOfRangeSatsAmount,
    /// No fresh exchange rate is available for the order's fiat currency:
    /// the last-known-good price is older than the node's staleness window,
    /// so a market-priced order cannot be created or taken right now. The
    /// caller should retry once pricing recovers, or use a fixed rate.
    PriceTooStale,
    /// The caller tried to operate on a dispute that does not belong to them.
    IsNotYourDispute,
    /// A solver is being notified that an admin has taken over their dispute.
    DisputeTakenByAdmin,
    /// The caller is authenticated but lacks the permission for this action.
    NotAuthorized,
    /// A dispute could not be created (e.g. order not in a disputable state).
    DisputeCreationError,
    /// Generic "resource not found" error.
    NotFound,
    /// The dispute is in an invalid state for the requested action.
    InvalidDisputeStatus,
    /// The requested action is invalid.
    InvalidAction,
    /// The caller already has a pending order and cannot create another.
    PendingOrderExists,
    /// The fiat currency code is not accepted by this Mostro node.
    InvalidFiatCurrency,
    /// The caller is being rate-limited.
    TooManyRequests,
    /// The submitted Cashu token is malformed, cannot be parsed, or its
    /// 2-of-3 spending condition does not match the expected
    /// buyer/seller/Mostro pubkeys.
    InvalidCashuToken,
    /// The configured Cashu mint could not be reached or did not answer the
    /// state check.
    CashuMintUnavailable,
    /// The provided mint URL is malformed or does not match the node's
    /// configured mint.
    InvalidMintUrl,
    /// The requested action needs a locked Cashu escrow, but none has been
    /// recorded for this order.
    CashuEscrowNotLocked,
    /// A required Cashu signature is missing from the request.
    CashuSignatureMissing,
    /// Mostro is in maintenance mode (for example draining escrow before a
    /// Lightning node migration) and is not accepting new orders or takes.
    /// Actions on already existing orders keep working.
    MaintenanceMode,
    /// The `payment_hash` of a payer declaration is not 64 lowercase hex
    /// characters.
    InvalidPaymentHash,
    /// `fiat-sent` was refused because this node requires the buyer to send
    /// `declare-payer` first.
    PayerNotDeclared,
    /// A reputation request carries no identity proof: in full privacy mode
    /// there is no identity-bound reputation to export or import into.
    ReputationIdentityRequired,
    /// The account cannot export its reputation: it is banned, or has fewer
    /// than 10 completed trades or 5 ratings received.
    NotEligibleForReputationExport,
    /// The account is bound to another identity and the export request
    /// carries no rebind authorisation.
    ReputationBoundToOtherIdentity,
    /// The rebind authorisation is malformed, badly signed, not signed by the
    /// bound identity, names another issuer or has expired.
    InvalidReputationRebind,
    /// The attestation does not parse, is badly signed, breaks a tag rule,
    /// is dated in the future or outlives the destination's lifetime cap.
    InvalidReputationAttestation,
    /// The attestation is signed by a key in no trust-list entry, or by the
    /// destination's own issuer key.
    UntrustedReputationIssuer,
    /// The attestation has expired.
    ExpiredReputationAttestation,
    /// The attestation names another identity than the one the request
    /// proves.
    ReputationIdentityMismatch,
    /// The source account, or another account from the same issuer for this
    /// identity, was imported before.
    ReputationAlreadyImported,
    /// Catch-all for reasons this build of `mostro-core` does not know yet.
    ///
    /// Newer daemons may emit reasons added after this release; without this
    /// variant the whole `CantDo` payload would fail to deserialize. Never
    /// emitted by a daemon on purpose.
    #[serde(other)]
    Unknown,
}

/// Internal errors raised by services behind the Mostro API.
///
/// Unlike [`CantDoReason`], values of this enum are not expected to be
/// forwarded verbatim to end users; they are meant for logs, telemetry and
/// other server-to-server diagnostics.
#[derive(Debug, PartialEq, Eq)]
pub enum ServiceError {
    /// Wraps an error returned by `nostr_sdk`.
    NostrError(String),
    /// The invoice string could not be parsed as a valid BOLT-11 invoice.
    ParsingInvoiceError,
    /// A numeric value could not be parsed.
    ParsingNumberError,
    /// The invoice has expired.
    InvoiceExpiredError,
    /// The invoice is otherwise invalid.
    InvoiceInvalidError,
    /// The invoice expiration time is below the minimum required.
    MinExpirationTimeError,
    /// The invoice amount is below the minimum allowed.
    MinAmountError,
    /// The invoice amount does not match the expected value.
    WrongAmountError,
    /// The price API did not answer in time.
    NoAPIResponse,
    /// The requested currency is not listed by the exchange API.
    NoCurrency,
    /// A price exists but is older than the configured staleness window, so
    /// it must not be used to price an order (the multi-source price
    /// manager serves last-known-good only up to that TTL).
    PriceTooStale,
    /// The exchange API returned a response that could not be parsed.
    MalformedAPIRes,
    /// Amount value is negative where only positives are allowed.
    NegativeAmount,
    /// A Lightning Address could not be parsed.
    LnAddressParseError,
    /// A Lightning Address payment was attempted with a wrong amount.
    LnAddressWrongAmount,
    /// A Lightning payment failed; the inner string carries the reason.
    LnPaymentError(String),
    /// Communication with the Lightning node failed.
    LnNodeError(String),
    /// Order id was not found in the database.
    InvalidOrderId,
    /// Database access failed; the inner string carries the detail.
    DbAccessError(String),
    /// The provided public key is invalid.
    InvalidPubkey,
    /// Hold-invoice operation failed; the inner string carries the detail.
    HoldInvoiceError(String),
    /// Could not update the order status in the database.
    UpdateOrderStatusError,
    /// The order status is invalid.
    InvalidOrderStatus,
    /// The order kind is invalid.
    InvalidOrderKind,
    /// A dispute already exists for this order.
    DisputeAlreadyExists,
    /// Could not publish the dispute Nostr event.
    DisputeEventError,
    /// The rating message itself is invalid.
    InvalidRating,
    /// The rating value is outside the accepted range.
    InvalidRatingValue,
    /// Failed to serialize or deserialize a [`crate::message::Message`].
    MessageSerializationError,
    /// The dispute id is invalid or unknown.
    InvalidDisputeId,
    /// The dispute status is invalid.
    InvalidDisputeStatus,
    /// The payload does not match the action.
    InvalidPayload,
    /// Any other unexpected error; inner string carries the detail.
    UnexpectedError(String),
    /// An environment variable could not be read or parsed.
    EnvVarError(String),
    /// Underlying I/O error.
    IOError(String),
    /// NIP-44/NIP-59 encryption failed.
    EncryptionError(String),
    /// NIP-44/NIP-59 decryption failed.
    DecryptionError(String),
}

/// Top-level error type returned by the Mostro API surface.
///
/// Most public functions in this crate return `Result<T, MostroError>`.
/// Match on the variants to distinguish between user-actionable "can't do"
/// responses and internal service errors.
#[derive(Debug, PartialEq, Eq)]
pub enum MostroError {
    /// An internal service-level error; diagnostic only.
    MostroInternalErr(ServiceError),
    /// A structured "can't do" response to surface to the user.
    MostroCantDo(CantDoReason),
}

impl std::error::Error for MostroError {}

impl std::fmt::Display for MostroError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MostroError::MostroInternalErr(m) => write!(f, "Error caused by {}", m),
            MostroError::MostroCantDo(m) => write!(f, "Sending cantDo message to user for {:?}", m),
        }
    }
}

impl std::fmt::Display for ServiceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ServiceError::ParsingInvoiceError => write!(f, "Incorrect invoice"),
            ServiceError::ParsingNumberError => write!(f, "Error parsing the number"),
            ServiceError::InvoiceExpiredError => write!(f, "Invoice has expired"),
            ServiceError::MinExpirationTimeError => write!(f, "Minimal expiration time on invoice"),
            ServiceError::InvoiceInvalidError => write!(f, "Invoice is invalid"),
            ServiceError::MinAmountError => write!(f, "Minimal payment amount"),
            ServiceError::WrongAmountError => write!(f, "The amount on this invoice is wrong"),
            ServiceError::NoAPIResponse => write!(f, "Price API not answered - retry"),
            ServiceError::NoCurrency => write!(f, "Currency requested is not present in the exchange list, please specify a fixed rate"),
            ServiceError::PriceTooStale => write!(f, "Exchange rate is too stale to price an order - retry or use a fixed rate"),
            ServiceError::MalformedAPIRes => write!(f, "Malformed answer from exchange quoting request"),
            ServiceError::NegativeAmount => write!(f, "Negative amount is not valid"),
            ServiceError::LnAddressWrongAmount => write!(f, "Ln address need amount of 0 sats - please check your order"),
            ServiceError::LnAddressParseError  => write!(f, "Ln address parsing error - please check your address"),
            ServiceError::LnPaymentError(e) => write!(f, "Lightning payment failure cause: {}",e),
            ServiceError::LnNodeError(e) => write!(f, "Lightning node connection failure caused by: {}",e),
            ServiceError::InvalidOrderId => write!(f, "Order id not present in database"),
            ServiceError::InvalidPubkey => write!(f, "Invalid pubkey"),
            ServiceError::DbAccessError(e) => write!(f, "Error in database access: {}",e),
            ServiceError::HoldInvoiceError(e) => write!(f, "Error holding invoice: {}",e),
            ServiceError::UpdateOrderStatusError => write!(f, "Error updating order status"),
            ServiceError::InvalidOrderStatus => write!(f, "Invalid order status"),
            ServiceError::InvalidOrderKind => write!(f, "Invalid order kind"),
            ServiceError::DisputeAlreadyExists => write!(f, "Dispute already exists"),
            ServiceError::DisputeEventError => write!(f, "Error publishing dispute event"),
            ServiceError::NostrError(e) => write!(f, "Error in nostr: {}",e),
            ServiceError::InvalidRating => write!(f, "Invalid rating message"),
            ServiceError::InvalidRatingValue => write!(f, "Invalid rating value"),
            ServiceError::MessageSerializationError => write!(f, "Error serializing message"),
            ServiceError::InvalidDisputeId => write!(f, "Invalid dispute id"),
            ServiceError::InvalidDisputeStatus => write!(f, "Invalid dispute status"),
            ServiceError::InvalidPayload => write!(f, "Invalid payload"),
            ServiceError::UnexpectedError(e) => write!(f, "Unexpected error: {}", e),
            ServiceError::EnvVarError(e) => write!(f, "Environment variable error: {}", e),
            ServiceError::IOError(e) => write!(f, "IO error: {}", e),
            ServiceError::EncryptionError(e) => write!(f, "Encryption error: {}", e),
            ServiceError::DecryptionError(e) => write!(f, "Decryption error: {}", e),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn invalid_payload_serializes_to_snake_case() {
        let json = serde_json::to_string(&CantDoReason::InvalidPayload).unwrap();
        assert_eq!(json, "\"invalid_payload\"");
        let round: CantDoReason = serde_json::from_str(&json).unwrap();
        assert_eq!(round, CantDoReason::InvalidPayload);
    }

    #[test]
    fn price_too_stale_serializes_to_snake_case() {
        let json = serde_json::to_string(&CantDoReason::PriceTooStale).unwrap();
        assert_eq!(json, "\"price_too_stale\"");
        let round: CantDoReason = serde_json::from_str(&json).unwrap();
        assert_eq!(round, CantDoReason::PriceTooStale);
    }
    #[test]
    fn maintenance_mode_serializes_to_snake_case() {
        let json = serde_json::to_string(&CantDoReason::MaintenanceMode).unwrap();
        assert_eq!(json, "\"maintenance_mode\"");
        let round: CantDoReason = serde_json::from_str(&json).unwrap();
        assert_eq!(round, CantDoReason::MaintenanceMode);
    }

    #[test]
    fn payer_history_reasons_serialize_to_snake_case() {
        for (reason, wire) in [
            (CantDoReason::InvalidPaymentHash, "\"invalid_payment_hash\""),
            (CantDoReason::PayerNotDeclared, "\"payer_not_declared\""),
        ] {
            let json = serde_json::to_string(&reason).unwrap();
            assert_eq!(json, wire);
            let round: CantDoReason = serde_json::from_str(&json).unwrap();
            assert_eq!(round, reason);
        }
    }

    #[test]
    fn unknown_reason_deserializes_to_unknown_catch_all() {
        let round: CantDoReason = serde_json::from_str("\"reason_from_the_future\"").unwrap();
        assert_eq!(round, CantDoReason::Unknown);
    }

    #[test]
    fn unknown_reason_inside_cant_do_payload_does_not_break_the_message() {
        let payload: crate::message::Payload =
            serde_json::from_str(r#"{"cant_do":"reason_from_the_future"}"#).unwrap();
        assert!(matches!(
            payload,
            crate::message::Payload::CantDo(Some(CantDoReason::Unknown))
        ));
    }

    #[test]
    fn unknown_serializes_to_snake_case() {
        let json = serde_json::to_string(&CantDoReason::Unknown).unwrap();
        assert_eq!(json, "\"unknown\"");
    }

    /// The reasons the protocol's reputation chapter documents, by the exact
    /// snake_case spelling clients match on.
    #[test]
    fn reputation_reasons_travel_with_their_documented_names() {
        let reasons = [
            (
                CantDoReason::ReputationIdentityRequired,
                "reputation_identity_required",
            ),
            (
                CantDoReason::NotEligibleForReputationExport,
                "not_eligible_for_reputation_export",
            ),
            (
                CantDoReason::ReputationBoundToOtherIdentity,
                "reputation_bound_to_other_identity",
            ),
            (
                CantDoReason::InvalidReputationRebind,
                "invalid_reputation_rebind",
            ),
            (
                CantDoReason::InvalidReputationAttestation,
                "invalid_reputation_attestation",
            ),
            (
                CantDoReason::UntrustedReputationIssuer,
                "untrusted_reputation_issuer",
            ),
            (
                CantDoReason::ExpiredReputationAttestation,
                "expired_reputation_attestation",
            ),
            (
                CantDoReason::ReputationIdentityMismatch,
                "reputation_identity_mismatch",
            ),
            (
                CantDoReason::ReputationAlreadyImported,
                "reputation_already_imported",
            ),
        ];
        for (reason, wire) in reasons {
            let json = serde_json::to_string(&reason).unwrap();
            assert_eq!(json, format!("\"{wire}\""));
            assert_eq!(serde_json::from_str::<CantDoReason>(&json).unwrap(), reason);
        }
    }
}