Skip to main content

bsv_rs/
error.rs

1//! Error types for the BSV SDK.
2
3use thiserror::Error;
4
5/// Main error type for the BSV SDK.
6#[derive(Error, Debug, Clone, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum Error {
9    // ===================
10    // Primitives errors
11    // ===================
12    /// Invalid key length for cryptographic operations.
13    #[error("invalid key length: expected {expected}, got {actual}")]
14    InvalidKeyLength {
15        /// The length the operation requires, in bytes.
16        expected: usize,
17        /// The length supplied, in bytes.
18        actual: usize,
19    },
20
21    /// Invalid data length for cryptographic operations.
22    #[error("invalid data length: expected {expected}, got {actual}")]
23    InvalidDataLength {
24        /// The length the operation requires, in bytes.
25        expected: usize,
26        /// The length supplied, in bytes.
27        actual: usize,
28    },
29
30    /// Invalid hex string.
31    #[error("invalid hex string: {0}")]
32    InvalidHex(String),
33
34    /// Invalid base58 string.
35    #[error("invalid base58 string: {0}")]
36    InvalidBase58(String),
37
38    /// Invalid base64 string.
39    #[error("invalid base64 string: {0}")]
40    InvalidBase64(String),
41
42    /// Cryptographic operation failed.
43    #[error("cryptographic operation failed: {0}")]
44    CryptoError(String),
45
46    /// Invalid signature.
47    #[error("invalid signature: {0}")]
48    InvalidSignature(String),
49
50    /// Invalid public key.
51    #[error("invalid public key: {0}")]
52    InvalidPublicKey(String),
53
54    /// Invalid private key.
55    #[error("invalid private key: {0}")]
56    InvalidPrivateKey(String),
57
58    /// Point at infinity (invalid for most operations).
59    #[error("point at infinity")]
60    PointAtInfinity,
61
62    /// Decryption failed.
63    #[error("decryption failed")]
64    DecryptionFailed,
65
66    /// Invalid nonce.
67    #[error("invalid nonce: {0}")]
68    InvalidNonce(String),
69
70    /// Invalid tag (for authenticated encryption).
71    #[error("invalid authentication tag")]
72    InvalidTag,
73
74    /// Invalid UTF-8 sequence.
75    #[error("invalid UTF-8 sequence: {0}")]
76    InvalidUtf8(String),
77
78    /// Reader underflow (not enough bytes to read).
79    #[error("reader underflow: need {needed} bytes, only {available} available")]
80    ReaderUnderflow {
81        /// The bytes the read asked for.
82        needed: usize,
83        /// The bytes left in the reader.
84        available: usize,
85    },
86
87    /// A varint using more bytes than its value requires. Width includes the marker.
88    #[error("non-canonical varint: {value} encoded in {width} bytes")]
89    NonCanonicalVarInt {
90        /// The encoded width in bytes, the marker included.
91        width: u8,
92        /// The value the varint carries.
93        value: u64,
94    },
95
96    /// A node CompactSize above `MAX_COMPACT_SIZE`.
97    #[error("compact size too large: {0}")]
98    CompactSizeTooLarge(u64),
99
100    /// Invalid checksum.
101    #[error("invalid checksum")]
102    InvalidChecksum,
103
104    // ===================
105    // Script errors (Phase S1+)
106    // ===================
107    /// Script parse error.
108    #[cfg(feature = "script")]
109    #[error("script parse error: {0}")]
110    ScriptParseError(String),
111
112    /// Script execution error.
113    #[cfg(feature = "script")]
114    #[error("script execution error: {0}")]
115    ScriptExecutionError(String),
116
117    /// Invalid opcode.
118    #[cfg(feature = "script")]
119    #[error("invalid opcode: 0x{0:02x}")]
120    InvalidOpcode(u8),
121
122    /// Disabled opcode.
123    #[cfg(feature = "script")]
124    #[error("disabled opcode: 0x{0:02x}")]
125    DisabledOpcode(u8),
126
127    /// Stack underflow.
128    #[cfg(feature = "script")]
129    #[error("stack underflow")]
130    StackUnderflow,
131
132    /// Stack overflow.
133    #[cfg(feature = "script")]
134    #[error("stack overflow")]
135    StackOverflow,
136
137    /// BIP-276 encoding/decoding error.
138    #[cfg(feature = "script")]
139    #[error("BIP-276 error: {0}")]
140    Bip276Error(String),
141
142    /// Invalid address.
143    #[cfg(feature = "script")]
144    #[error("invalid address: {0}")]
145    InvalidAddress(String),
146
147    /// Invalid address length.
148    #[cfg(feature = "script")]
149    #[error("invalid address length for '{0}'")]
150    InvalidAddressLength(String),
151
152    /// Unsupported address type.
153    #[cfg(feature = "script")]
154    #[error("address not supported {0}")]
155    UnsupportedAddress(String),
156
157    // ===================
158    // Transaction errors
159    // ===================
160    /// Transaction error.
161    #[cfg(feature = "transaction")]
162    #[error("transaction error: {0}")]
163    TransactionError(String),
164
165    /// MerklePath error.
166    #[cfg(feature = "transaction")]
167    #[error("merkle path error: {0}")]
168    MerklePathError(String),
169
170    /// BEEF format error.
171    #[cfg(feature = "transaction")]
172    #[error("BEEF error: {0}")]
173    BeefError(String),
174
175    /// Fee model error.
176    #[cfg(feature = "transaction")]
177    #[error("fee model error: {0}")]
178    FeeModelError(String),
179
180    // ===================
181    // Wallet errors
182    // ===================
183    /// General wallet error.
184    #[cfg(feature = "wallet")]
185    #[error("wallet error: {0}")]
186    WalletError(String),
187
188    /// The wallet is busy: a refusal before acting, in the wallet's word.
189    ///
190    /// The wallet answered that it refused the call before acting (a
191    /// contended store, a lock not acquired) and promised that nothing was
192    /// written, built or locked, so the caller may repeat the same call
193    /// unchanged after `retry_after_ms`, or after a moment when it is `None`.
194    /// The SDK reports the server's promise; it cannot check it.
195    /// `HttpWalletJson` reads it from the body's code (`STORE_BUSY`,
196    /// `ERR_SERVER_BUSY`), never from the HTTP status; a 503 without that
197    /// code is [`Error::WalletTransport`].
198    #[cfg(feature = "wallet")]
199    #[error("wallet busy: {detail}")]
200    WalletBusy {
201        /// What was busy, in the wallet's words.
202        detail: String,
203        /// How long the wallet asks the caller to wait before repeating the
204        /// call, in milliseconds; `None` when it did not say. Unbounded: the
205        /// server's word, not checked (a huge `Retry-After` saturates to
206        /// `u64::MAX`), so a caller caps its own wait.
207        retry_after_ms: Option<u64>,
208    },
209
210    /// The way to the wallet failed: no answer in the wallet's word.
211    ///
212    /// A caller may retry it; it carries no promise about what the wallet
213    /// did (the request may or may not have reached it), which is the one
214    /// way it differs from [`Error::WalletBusy`]. `HttpWalletJson` answers it
215    /// for a 502, 503 or 504 whose body carries no busy code and no numeric
216    /// wallet code, a connection error (refused, reset, DNS) and a timeout;
217    /// every other failure, and every refusal, stays [`Error::WalletError`].
218    /// The crate never retries by itself.
219    #[cfg(feature = "wallet")]
220    #[error("wallet transport fault: {detail}")]
221    WalletTransport {
222        /// The HTTP status of the answer, when one arrived (502, 503 or
223        /// 504); `None` when no answer arrived (a connection error, a
224        /// timeout).
225        status: Option<u16>,
226        /// What failed, in the transport's words.
227        detail: String,
228    },
229
230    /// Key derivation error.
231    #[cfg(feature = "wallet")]
232    #[error("key derivation error: {0}")]
233    KeyDerivationError(String),
234
235    /// Protocol validation error.
236    #[cfg(feature = "wallet")]
237    #[error("protocol validation error: {0}")]
238    ProtocolValidationError(String),
239
240    /// Invalid counterparty.
241    #[cfg(feature = "wallet")]
242    #[error("invalid counterparty: {0}")]
243    InvalidCounterparty(String),
244
245    // ===================
246    // Messages errors
247    // ===================
248    /// Message version mismatch.
249    #[cfg(feature = "messages")]
250    #[error("message version mismatch: expected {expected}, got {actual}")]
251    MessageVersionMismatch {
252        /// The version prefix this crate reads, as hex.
253        expected: String,
254        /// The version prefix the message carries, as hex.
255        actual: String,
256    },
257
258    /// General message error.
259    #[cfg(feature = "messages")]
260    #[error("message error: {0}")]
261    MessageError(String),
262
263    /// Message recipient mismatch.
264    #[cfg(feature = "messages")]
265    #[error("message recipient mismatch: expected {expected}, got {actual}")]
266    MessageRecipientMismatch {
267        /// The recipient public key the message names, compressed, as hex.
268        expected: String,
269        /// The public key of the private key supplied to read it, compressed, as hex.
270        actual: String,
271    },
272
273    // ===================
274    // Compat errors
275    // ===================
276    /// Invalid mnemonic phrase.
277    #[cfg(feature = "compat")]
278    #[error("invalid mnemonic: {0}")]
279    InvalidMnemonic(String),
280
281    /// Invalid entropy length for mnemonic generation.
282    #[cfg(feature = "compat")]
283    #[error("invalid entropy length: expected {expected}, got {actual}")]
284    InvalidEntropyLength {
285        /// The entropy lengths accepted, in bits.
286        expected: String,
287        /// The entropy length supplied, in bits.
288        actual: usize,
289    },
290
291    /// Invalid word in mnemonic phrase.
292    #[cfg(feature = "compat")]
293    #[error("invalid word in mnemonic: {0}")]
294    InvalidMnemonicWord(String),
295
296    /// Invalid extended key.
297    #[cfg(feature = "compat")]
298    #[error("invalid extended key: {0}")]
299    InvalidExtendedKey(String),
300
301    /// Cannot derive hardened child from public key.
302    #[cfg(feature = "compat")]
303    #[error("cannot derive hardened child from public key")]
304    HardenedFromPublic,
305
306    /// Invalid derivation path.
307    #[cfg(feature = "compat")]
308    #[error("invalid derivation path: {0}")]
309    InvalidDerivationPath(String),
310
311    /// ECIES decryption failed.
312    #[cfg(feature = "compat")]
313    #[error("ECIES decryption failed: {0}")]
314    EciesDecryptionFailed(String),
315
316    /// ECIES HMAC verification failed.
317    #[cfg(feature = "compat")]
318    #[error("ECIES HMAC verification failed")]
319    EciesHmacMismatch,
320
321    // ===================
322    // Auth errors
323    // ===================
324    /// General authentication error.
325    #[cfg(feature = "auth")]
326    #[error("authentication error: {0}")]
327    AuthError(String),
328
329    /// Session not found.
330    #[cfg(feature = "auth")]
331    #[error("session not found: {0}")]
332    SessionNotFound(String),
333
334    /// Certificate validation failed.
335    #[cfg(feature = "auth")]
336    #[error("certificate validation failed: {0}")]
337    CertificateValidationError(String),
338
339    /// Transport error.
340    #[cfg(feature = "auth")]
341    #[error("transport error: {0}")]
342    TransportError(String),
343
344    // ===================
345    // Overlay errors
346    // ===================
347    /// General overlay error.
348    #[cfg(feature = "overlay")]
349    #[error("overlay error: {0}")]
350    OverlayError(String),
351
352    /// No hosts found for service.
353    #[cfg(feature = "overlay")]
354    #[error("no hosts found for service: {0}")]
355    NoHostsFound(String),
356
357    /// Broadcast to overlay failed.
358    #[cfg(feature = "overlay")]
359    #[error("overlay broadcast failed: {0}")]
360    OverlayBroadcastFailed(String),
361
362    // ===================
363    // Registry errors
364    // ===================
365    /// General registry error.
366    #[cfg(feature = "registry")]
367    #[error("registry error: {0}")]
368    RegistryError(String),
369
370    /// Definition not found in registry.
371    #[cfg(feature = "registry")]
372    #[error("definition not found: {0}")]
373    DefinitionNotFound(String),
374
375    /// Invalid definition data.
376    #[cfg(feature = "registry")]
377    #[error("invalid definition data: {0}")]
378    InvalidDefinitionData(String),
379
380    // ===================
381    // KVStore errors
382    // ===================
383    /// General kvstore error.
384    #[cfg(feature = "kvstore")]
385    #[error("kvstore error: {0}")]
386    KvStoreError(String),
387
388    /// Key not found in kvstore.
389    #[cfg(feature = "kvstore")]
390    #[error("kvstore key not found: {0}")]
391    KvStoreKeyNotFound(String),
392
393    /// Corrupted kvstore state.
394    #[cfg(feature = "kvstore")]
395    #[error("corrupted kvstore state: {0}")]
396    KvStoreCorruptedState(String),
397
398    /// Empty context (protocol_id) provided to kvstore.
399    #[cfg(feature = "kvstore")]
400    #[error("context cannot be empty")]
401    KvStoreEmptyContext,
402
403    /// Invalid key provided to kvstore (empty).
404    #[cfg(feature = "kvstore")]
405    #[error("invalid key")]
406    KvStoreInvalidKey,
407
408    /// Invalid value provided to kvstore (empty).
409    #[cfg(feature = "kvstore")]
410    #[error("invalid value")]
411    KvStoreInvalidValue,
412
413    // ===================
414    // Identity errors
415    // ===================
416    /// General identity error.
417    #[cfg(feature = "identity")]
418    #[error("identity error: {0}")]
419    IdentityError(String),
420
421    /// Identity not found.
422    #[cfg(feature = "identity")]
423    #[error("identity not found: {0}")]
424    IdentityNotFound(String),
425
426    /// Contact not found.
427    #[cfg(feature = "identity")]
428    #[error("contact not found: {0}")]
429    ContactNotFound(String),
430}
431
432/// Result type alias for BSV SDK operations.
433pub type Result<T> = std::result::Result<T, Error>;