Skip to main content

fedimint_client_module/
error.rs

1//! Error types shared between the client and its modules.
2//!
3//! The client implements the traits in [`crate::module`] and [`crate`] for its
4//! modules, so the failures those traits report have to be nameable from both
5//! sides; they live here rather than in `fedimint-client`, which the modules do
6//! not depend on.
7
8use fedimint_core::Amount;
9use fedimint_core::config::{FederationId, ModuleConfigError};
10use fedimint_core::core::{Account, ModuleInstanceId, ModuleKind, OperationId};
11use fedimint_core::db::DatabaseError;
12use fedimint_core::module::AmountUnit;
13use thiserror::Error;
14
15/// The primary module cannot fund a transaction: the balance it holds is
16/// below what the transaction needs.
17#[derive(Debug, Clone, Copy, Eq, PartialEq, Error)]
18pub struct InsufficientBalanceError {
19    /// The amount the transaction needed the primary module to fund.
20    pub requested_amount: Amount,
21    /// The total amount the primary module actually holds.
22    pub total_amount: Amount,
23}
24
25impl std::fmt::Display for InsufficientBalanceError {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        write!(
28            f,
29            "Insufficient balance: requested {} but only {} available",
30            self.requested_amount, self.total_amount
31        )
32    }
33}
34
35/// A failure to add state machines to the client's executor.
36#[derive(Debug, Error)]
37#[non_exhaustive]
38pub enum AddStateMachinesError {
39    /// One of the states is already in the database.
40    #[error("State already exists in database")]
41    StateAlreadyExists,
42
43    /// A state belongs to a module instance the executor does not know.
44    #[error("Unknown module instance {module_instance_id}")]
45    UnknownModule {
46        /// The instance the state claims to belong to.
47        module_instance_id: ModuleInstanceId,
48    },
49
50    /// A state that can no longer transition was handed to the executor,
51    /// which would never make progress on it.
52    #[error("State is already terminal, adding it to the executor does not make sense")]
53    StateAlreadyTerminal,
54
55    /// The database write failed.
56    #[error("Database error")]
57    Database(#[from] DatabaseError),
58}
59
60/// An operation with the same id already exists in the operation log.
61#[derive(Debug, Error)]
62#[error("An operation with id {} already exists", .operation_id.fmt_short())]
63pub struct OperationAlreadyExistsError {
64    /// The id that is already taken.
65    pub operation_id: OperationId,
66}
67
68/// No operation with the requested id exists in the operation log.
69#[derive(Debug, Error)]
70#[error("No operation with id {}", .operation_id.fmt_short())]
71pub struct OperationNotFoundError {
72    /// The id that was looked up.
73    pub operation_id: OperationId,
74}
75
76/// A failure to look up one of a module's own operations.
77#[derive(Debug, Error)]
78#[non_exhaustive]
79pub enum OperationLookupError {
80    /// The operation log has no entry with this id.
81    #[error("The operation does not exist")]
82    NotFound(#[from] OperationNotFoundError),
83
84    /// The operation exists, but was started by a different module.
85    #[error(
86        "Operation {} was started by module {found}, not {expected}",
87        .operation_id.fmt_short()
88    )]
89    WrongModuleKind {
90        /// The operation that was looked up.
91        operation_id: OperationId,
92        /// The kind of the module doing the lookup.
93        expected: ModuleKind,
94        /// The kind of the module that started the operation.
95        found: String,
96    },
97}
98
99/// A failure to build, submit or complete a client transaction.
100///
101/// Covers the whole path a transaction takes on the client: balancing it with
102/// the primary module, recording its operation, registering its state machines,
103/// and waiting for the primary module's outputs to finalize. Submission to the
104/// federation itself is driven by a state machine and is not reported here.
105#[derive(Debug, Error)]
106#[non_exhaustive]
107pub enum TransactionSubmitError {
108    /// The operation the transaction would be recorded under already exists.
109    #[error("The operation already exists")]
110    OperationAlreadyExists(#[from] OperationAlreadyExistsError),
111
112    /// The finalized transaction is larger than the federation accepts.
113    #[error("The transaction is {size} bytes, over the limit of {max}")]
114    TransactionTooLarge {
115        /// The size of the encoded transaction.
116        size: usize,
117        /// The largest transaction the federation accepts.
118        max: usize,
119    },
120
121    /// No primary module can hold funds of this unit, so the transaction
122    /// cannot be balanced.
123    #[error("No primary module for unit {unit}")]
124    NoPrimaryModule {
125        /// The unit that could not be balanced.
126        unit: AmountUnit,
127    },
128
129    /// The primary module for this unit holds a balance for the primary
130    /// account only, so a transaction on another account cannot be balanced.
131    #[error("The primary module for unit {unit} only holds a balance for the primary account")]
132    AccountNotSupported {
133        /// The unit that could not be balanced.
134        unit: AmountUnit,
135        /// The account the transaction acts on.
136        account: Account,
137    },
138
139    /// The primary module failed to balance the transaction or to complete
140    /// its outputs. An insufficient balance reported while balancing the
141    /// transaction is reported as [`Self::InsufficientFunds`] instead.
142    #[error("The primary module failed")]
143    PrimaryModule(#[source] ClientModuleError),
144
145    /// Writing the transaction to the database failed.
146    #[error("Database error")]
147    Database(#[from] DatabaseError),
148
149    /// The transaction's state machines could not be registered.
150    #[error("Failed to add the transaction's state machines")]
151    StateMachines(#[from] AddStateMachinesError),
152
153    /// The primary module holds too little balance to fund the transaction.
154    #[error("Insufficient funds")]
155    InsufficientFunds(#[from] InsufficientBalanceError),
156
157    /// Calculating the transaction balance or fees overflowed.
158    #[error("Transaction amounts or fees overflowed")]
159    AmountOverflow,
160}
161
162impl TransactionSubmitError {
163    /// Whether this failure means the primary module cannot fund the
164    /// transaction, as opposed to a failure of the client, the database or
165    /// the federation.
166    pub fn is_insufficient_funds(&self) -> bool {
167        matches!(self, Self::InsufficientFunds(_))
168    }
169}
170
171/// A primary module's failure to balance a transaction, as the failure of
172/// that transaction: a balance too low to fund it becomes
173/// [`TransactionSubmitError::InsufficientFunds`], so callers can tell it apart
174/// from any other failure of the module, which becomes
175/// [`TransactionSubmitError::PrimaryModule`].
176impl From<ClientModuleError> for TransactionSubmitError {
177    fn from(error: ClientModuleError) -> Self {
178        match error {
179            ClientModuleError::InsufficientBalance(error) => Self::InsufficientFunds(error),
180            other => Self::PrimaryModule(other),
181        }
182    }
183}
184
185/// A failure a client module reports to the client.
186///
187/// The methods a module implements for the client in [`ClientModule`],
188/// [`ClientModuleInit`] and [`RecoveryFromHistory`] report this type, and so
189/// do the type-erased wrappers the client calls them through. The client wraps
190/// it in the error of the operation that needed the module; the JSON command
191/// handlers `handle_cli_command` and `handle_rpc` hand it to the command-line
192/// or RPC caller as it is.
193///
194/// [`ClientModule`]: crate::module::ClientModule
195/// [`ClientModuleInit`]: crate::module::init::ClientModuleInit
196/// [`RecoveryFromHistory`]: crate::module::init::recovery::RecoveryFromHistory
197#[derive(Debug, Error)]
198#[non_exhaustive]
199pub enum ClientModuleError {
200    /// The primary module's balance cannot fund the transaction it was asked
201    /// to balance.
202    ///
203    /// A primary module reports this from `create_final_inputs_and_outputs`,
204    /// and the client passes it on as
205    /// [`TransactionSubmitError::InsufficientFunds`].
206    #[error("The primary module's balance cannot fund the transaction")]
207    InsufficientBalance(#[from] InsufficientBalanceError),
208
209    /// The module does not implement the operation.
210    ///
211    /// The default bodies of `backup`, `create_final_inputs_and_outputs`,
212    /// `await_primary_module_output`, `leave` and `ClientModuleInit::recover`
213    /// report this. The client only asks a module for an operation the module
214    /// declares support for, through `supports_backup`,
215    /// `supports_being_primary` or `recovery_mode`, so the client sees this
216    /// only from a module that declares support it does not implement.
217    /// Calling the operation on a module directly can see it too. The default
218    /// bodies of `handle_cli_command` and `handle_rpc` report it as well, to a
219    /// caller that sends a command or a request to a module that has none.
220    #[error("Module {kind} does not implement {operation}")]
221    Unsupported {
222        /// The kind of the module.
223        kind: ModuleKind,
224        /// The name of the trait method the module does not implement.
225        operation: &'static str,
226    },
227
228    /// Any other failure, kept whole: the module's own error or the error of a
229    /// library it builds on, such as a federation, database or Bitcoin
230    /// backend failure. Its `Display` and `source()` are those of the error it
231    /// carries.
232    #[error(transparent)]
233    Other(Box<dyn std::error::Error + Send + Sync>),
234}
235
236impl ClientModuleError {
237    /// Wraps a failure the other variants do not describe. Accepts anything
238    /// convertible into a boxed error, which includes an `anyhow::Error` and a
239    /// plain message.
240    ///
241    /// A primary module's shortfall must be [`Self::InsufficientBalance`]
242    /// instead: the client does not look inside the error this carries.
243    pub fn other<E>(error: E) -> Self
244    where
245        E: Into<Box<dyn std::error::Error + Send + Sync>>,
246    {
247        Self::Other(error.into())
248    }
249}
250
251/// A failure to find a module able to serve a request.
252#[derive(Debug, Error)]
253#[non_exhaustive]
254pub enum ModuleLookupError {
255    /// The client was not built with a module of this kind, or the federation
256    /// does not offer one.
257    #[error("No module of kind {kind} found")]
258    NoModuleOfKind {
259        /// The kind that was asked for.
260        kind: ModuleKind,
261    },
262
263    /// The client has no module with this instance id.
264    #[error("Unknown module instance {instance_id}")]
265    UnknownInstance {
266        /// The instance id that was asked for.
267        instance_id: ModuleInstanceId,
268    },
269
270    /// The module instance exists, but is not of the requested type.
271    #[error("Module instance {instance_id} is not of type {expected}")]
272    WrongModuleType {
273        /// The instance that was asked for.
274        instance_id: ModuleInstanceId,
275        /// The Rust type the caller asked the instance to be.
276        expected: &'static str,
277    },
278
279    /// No primary module can hold funds of this unit.
280    #[error("No primary module for unit {unit}")]
281    NoPrimaryModule {
282        /// The unit that has no primary module.
283        unit: AmountUnit,
284    },
285
286    /// None of the primary modules for this unit is of the requested kind.
287    #[error("No primary {kind} module for unit {unit}")]
288    NoPrimaryModuleOfKind {
289        /// The kind of module that was asked for.
290        kind: ModuleKind,
291        /// The unit whose primary modules were searched.
292        unit: AmountUnit,
293    },
294}
295
296/// The client and the federation's peers share no core API version.
297///
298/// Module version mismatches are not an error: a module whose versions do not
299/// line up is left out of the negotiated set and stays unusable until one side
300/// is upgraded.
301#[derive(Debug, Error)]
302#[error("Could not find a common core API version")]
303pub struct ApiVersionDiscoveryError;
304
305/// A failure to fetch the federation's meta fields.
306///
307/// The built-in sources produce the specific variants. A [`MetaSource`]
308/// implemented elsewhere reports anything they do not describe through
309/// [`Custom`].
310///
311/// [`MetaSource`]: crate::meta::MetaSource
312/// [`Custom`]: MetaFetchError::Custom
313#[derive(Debug, Error)]
314#[non_exhaustive]
315pub enum MetaFetchError {
316    /// The meta override URL could not be read from the client config.
317    #[error("Failed to read the meta override URL from the client config")]
318    Config(#[from] ModuleConfigError),
319
320    /// The meta override source could not be reached, or its body could not
321    /// be read.
322    #[error("The meta override source could not be fetched")]
323    Http(#[from] reqwest::Error),
324
325    /// The meta override source answered with a non-success status.
326    #[error("The meta override source answered with status {status}")]
327    Status {
328        /// The status the source answered with.
329        status: reqwest::StatusCode,
330    },
331
332    /// The meta override source's body is not the expected JSON.
333    #[error("The meta override source returned invalid JSON")]
334    Json(#[from] serde_json::Error),
335
336    /// The meta override source has no entry for this federation.
337    #[error("The meta override source has no entry for federation {federation_id}")]
338    NoEntry {
339        /// The federation that was looked up.
340        federation_id: FederationId,
341    },
342
343    /// A meta source implemented outside this crate failed in a way the other
344    /// variants do not describe.
345    #[error("The meta source failed")]
346    Custom(#[source] Box<dyn std::error::Error + Send + Sync>),
347}
348
349#[cfg(test)]
350mod tests;