Skip to main content

rgb_lib/
error.rs

1//! Errors.
2//!
3//! This module defines the [`Error`] enum, containing all error variants returned by functions in
4//! the library.
5
6use super::*;
7
8/// The error variants returned by functions.
9#[derive(Debug, Clone, PartialEq, thiserror::Error, Deserialize, Serialize)]
10pub enum Error {
11    /// No need to create more allocations
12    #[error("Allocations already available")]
13    AllocationsAlreadyAvailable,
14
15    /// Requested asset was not found
16    #[error("Asset with id {asset_id} not found")]
17    AssetNotFound {
18        /// Asset ID
19        asset_id: String,
20    },
21
22    /// The requested batch transfer was not found
23    #[error("Batch transfer with idx {idx} not found")]
24    BatchTransferNotFound {
25        /// Transfer idx
26        idx: i32,
27    },
28
29    /// The wallet has already been loaded on a different bitcoin network
30    #[error("Bitcoin network mismatch")]
31    BitcoinNetworkMismatch,
32
33    /// A wallet cannot go online twice with different data
34    #[error("Cannot change online object")]
35    CannotChangeOnline,
36
37    /// An out-of-band ACK cannot be provided for this transfer
38    #[error("Cannot provide out-of-band ACK: {details}")]
39    CannotProvideOutOfBandAck {
40        /// Error details
41        details: String,
42    },
43
44    /// The given PSBTs cannot be combined
45    #[error("The given PSBTs cannot be combined")]
46    CannotCombinePsbts,
47
48    /// An out-of-band consignment cannot be provided for this transfer
49    #[error("Cannot provide out-of-band consignment: {details}")]
50    CannotProvideOutOfBandConsignment {
51        /// Error details
52        details: String,
53    },
54
55    /// Requested pending vanilla TX cannot be aborted
56    #[error("Pending vanilla TX cannot be aborted")]
57    CannotAbortPendingVanillaTx,
58
59    /// Requested batch transfer cannot be deleted
60    #[error("Batch transfer cannot be deleted")]
61    CannotDeleteBatchTransfer,
62
63    /// Cannot estimate fees
64    #[error("Cannot estimate fees")]
65    CannotEstimateFees,
66
67    /// Requested batch transfer cannot be failed
68    #[error("Batch transfer cannot be set to failed status")]
69    CannotFailBatchTransfer,
70
71    /// The given PSBT cannot be finalized
72    #[error("The given PSBT cannot be finalized")]
73    CannotFinalizePsbt,
74
75    /// Cannot use IFA schema on mainnet
76    #[error("Cannot use IFA schema on mainnet")]
77    CannotUseIfaOnMainnet,
78
79    /// A database error has been encountered
80    #[error("Database error: {details}")]
81    Database {
82        /// Error details
83        details: String,
84    },
85
86    /// The provided file is empty
87    #[error("Empty file: {file_path}")]
88    EmptyFile {
89        /// File path
90        file_path: String,
91    },
92
93    /// Syncing BDK with the blockchain has failed
94    #[error("Failed bdk sync: {details}")]
95    FailedBdkSync {
96        /// Error details
97        details: String,
98    },
99
100    /// Broadcasting the PSBT has failed
101    #[error("Failed broadcast: {details}")]
102    FailedBroadcast {
103        /// Error details
104        details: String,
105    },
106
107    /// Issued RGB asset has failed the validity check
108    #[error("Failed issuance. Register status: {details}")]
109    FailedIssuance {
110        /// Error details
111        details: String,
112    },
113
114    /// The file already exists
115    #[error("The file already exists: {path}")]
116    FileAlreadyExists {
117        /// The file path
118        path: String,
119    },
120
121    /// The master fingerprint derived from the mnemonic doesn't match the provided one
122    #[error("Fingerprint mismatch")]
123    FingerprintMismatch,
124
125    /// An I/O error has been encountered
126    #[error("I/O error: {details}")]
127    IO {
128        /// Error details
129        details: String,
130    },
131
132    /// An inconsistency has been detected between the wallet's internal (database) and external
133    /// (BDK, RGB) data
134    #[error("Data is inconsistent ({details}). Please check its integrity.")]
135    Inconsistency {
136        /// Error details
137        details: String,
138    },
139
140    /// An error was received from the indexer
141    #[error("Indexer error: {details}")]
142    Indexer {
143        /// Error details
144        details: String,
145    },
146
147    /// The provided directory does not exist
148    #[error("Inexistent data directory")]
149    InexistentDataDir,
150
151    /// The wallet directory holds no manifest to load the wallet from
152    #[error("Inexistent wallet manifest: {path}")]
153    InexistentWalletManifest {
154        /// The manifest path
155        path: String,
156    },
157
158    /// There are not enough available allocation slots (UTXOs with available slots)
159    #[error("Insufficient allocations")]
160    InsufficientAllocationSlots,
161
162    /// There are not enough assignments of the requested asset to fulfill the request
163    #[cfg(any(feature = "electrum", feature = "esplora"))]
164    #[error("Insufficient total assignments for asset: {asset_id}")]
165    InsufficientAssignments {
166        /// Asset ID
167        asset_id: String,
168        /// Available assignments
169        available: AssignmentsCollection,
170    },
171
172    /// There are not enough bitcoins to fulfill the request
173    #[error("Insufficient bitcoin funds: needed '{needed}', available '{available}'")]
174    InsufficientBitcoins {
175        /// Sats needed for some transaction
176        needed: u64,
177        /// Sats available for spending
178        available: u64,
179    },
180
181    /// An internal error has been encountered
182    #[error("Internal error: {details}")]
183    Internal {
184        /// Error details
185        details: String,
186    },
187
188    /// An invalid bitcoin address has been provided
189    #[error("Address error: {details}")]
190    InvalidAddress {
191        /// Error details
192        details: String,
193    },
194
195    /// An invalid 0 amount has been provided
196    #[error("Amount 0 is invalid")]
197    InvalidAmountZero,
198
199    /// An invalid assignment has been provided
200    #[error("Invalid assignment")]
201    InvalidAssignment,
202
203    /// The provided attachments are invalid
204    #[error("Invalid attachments: {details}")]
205    InvalidAttachments {
206        /// Error details
207        details: String,
208    },
209
210    /// Keys derived from the provided data do not match
211    #[error("Invalid bitcoin keys")]
212    InvalidBitcoinKeys,
213
214    /// Invalid bitcoin network
215    #[error("Invalid bitcoin network: {network}")]
216    InvalidBitcoinNetwork {
217        /// The invalid network
218        network: String,
219    },
220
221    /// The provided coloring info is invalid
222    #[error("Invalid coloring info")]
223    InvalidColoringInfo {
224        /// Error details
225        details: String,
226    },
227
228    /// The consignment is invalid
229    #[error("Invalid consignment")]
230    InvalidConsignment,
231
232    /// The provided cosigner is invalid
233    #[error("Invalid cosigner: {details}")]
234    InvalidCosigner {
235        /// Error details
236        details: String,
237    },
238
239    /// The provided asset details is invalid
240    #[error("Invalid details: {details}")]
241    InvalidDetails {
242        /// Error details
243        details: String,
244    },
245
246    /// Electrum server does not provide the required functionality
247    ///
248    /// There are multiple electrum server variants and one with `verbose` support in
249    /// `blockchain.transaction.get` is required, see this
250    /// [issue](https://github.com/Blockstream/electrs/pull/36) on blockstream's electrs fork for
251    /// more info
252    #[error("Invalid electrum server: {details}")]
253    InvalidElectrum {
254        /// Error details
255        details: String,
256    },
257
258    /// Trying to request fee estimation for an invalid block number, it must be between 1 and 1008
259    #[error("Trying to request fee estimation for an invalid block number")]
260    InvalidEstimationBlocks,
261
262    /// The provided expiration is invalid
263    #[error("Invalid expiration")]
264    InvalidExpiration,
265
266    /// The provided fee rate is invalid
267    #[error("Invalid fee rate: {details}")]
268    InvalidFeeRate {
269        /// Error details
270        details: String,
271    },
272
273    /// The provided file path is invalid
274    #[error("Invalid file path: {file_path}")]
275    InvalidFilePath {
276        /// File path
277        file_path: String,
278    },
279
280    /// The fingerprint is invalid
281    #[error("Invalid fingerprint")]
282    InvalidFingerprint,
283
284    /// The provided indexer is invalid
285    #[error("Invalid indexer: {details}")]
286    InvalidIndexer {
287        /// Error details
288        details: String,
289    },
290
291    /// The provided invoice is invalid
292    #[error("Invalid invoice: {details}")]
293    InvalidInvoice {
294        /// Error details
295        details: String,
296    },
297
298    /// The provided mnemonic phrase is invalid
299    #[error("Invalid mnemonic error: {details}")]
300    InvalidMnemonic {
301        /// Error details
302        details: String,
303    },
304
305    /// Invalid multisig threshold
306    #[error("Invalid multisig threshold: required={required} with total={total}")]
307    InvalidMultisigThreshold {
308        /// Required threshold
309        required: u8,
310        /// Total cosigners
311        total: u8,
312    },
313
314    /// The provided asset name is invalid
315    #[error("Invalid name: {details}")]
316    InvalidName {
317        /// Error details
318        details: String,
319    },
320
321    /// The provided asset precision is invalid
322    #[error("Invalid precision: {details}")]
323    InvalidPrecision {
324        /// Error details
325        details: String,
326    },
327
328    /// The provided proxy URL points to a proxy running an unsupported protocol version
329    #[error("Invalid proxy protocol version: {version}")]
330    InvalidProxyProtocol {
331        /// Detected version
332        version: String,
333    },
334
335    /// The provided PSBT is invalid
336    #[error("Invalid PSBT: {details}")]
337    InvalidPsbt {
338        /// Error details
339        details: String,
340    },
341
342    /// The provided pubkey is invalid
343    #[error("Invalid pubkey: {details}")]
344    InvalidPubkey {
345        /// Error details
346        details: String,
347    },
348
349    /// The provided recipient data is invalid
350    #[error("The provided recipient data is invalid: {details}")]
351    InvalidRecipientData {
352        /// Error details
353        details: String,
354    },
355
356    /// The provided recipient ID is neither a blinded UTXO or a script
357    #[error("The provided recipient ID is neither a blinded UTXO or a script")]
358    InvalidRecipientID,
359
360    /// The provided recipient map is invalid
361    #[error("The provided recipient map is invalid")]
362    InvalidRecipientMap,
363
364    /// The provided recipient ID is for a different network than the wallet's one
365    #[error("The provided recipient ID is for a different network than the wallet's one")]
366    InvalidRecipientNetwork,
367
368    /// The provided reject list URL is invalid
369    #[error("Invalid reject list URL: {details}")]
370    InvalidRejectListUrl {
371        /// Error details
372        details: String,
373    },
374
375    /// The provided asset ticker is invalid
376    #[error("Invalid ticker: {details}")]
377    InvalidTicker {
378        /// Error details
379        details: String,
380    },
381
382    /// The provided transport endpoint is invalid
383    #[error("Invalid transport endpoint: {details}")]
384    InvalidTransportEndpoint {
385        /// Error details
386        details: String,
387    },
388
389    /// The provided transport endpoints are invalid
390    #[error("Invalid transport endpoints: {details}")]
391    InvalidTransportEndpoints {
392        /// Error details
393        details: String,
394    },
395
396    /// The provided TXID is invalid
397    #[error("Invalid TXID")]
398    InvalidTxid,
399
400    /// The provided vanilla keychain is invalid
401    #[error("Invalid vanilla keychain")]
402    InvalidVanillaKeychain,
403
404    /// Invalid witness version
405    #[error("Invalid witness version: {witness_version}")]
406    InvalidWitnessVersion {
407        /// The invalid witness version
408        witness_version: String,
409    },
410
411    /// The maximum fee has been exceeded
412    #[error("Max fee exceeded for transfer with TXID: {txid}")]
413    MaxFeeExceeded {
414        /// TXID of the transfer having fee issues
415        txid: String,
416    },
417
418    /// The minimum fee is not met
419    #[error("Min fee not met for transfer with TXID: {txid}")]
420    MinFeeNotMet {
421        /// TXID of the transfer having fee issues
422        txid: String,
423    },
424
425    /// Multisig hub service error
426    #[error("Multisig hub service error: {details}")]
427    MultisigHubService {
428        /// Error details
429        details: String,
430    },
431
432    /// Cannot mark operation as processed
433    #[error("Cannot mark operation as processed: {details}")]
434    MultisigCannotMarkOperationProcessed {
435        /// Error details
436        details: String,
437    },
438
439    /// Cannot respond to operation
440    #[error("Cannot respond to operation: {details}")]
441    MultisigCannotRespondToOperation {
442        /// Error details
443        details: String,
444    },
445
446    /// Cannot initiate a new operation while another is in progress
447    #[error("Cannot initiate a new operation while another is in progress")]
448    MultisigOperationInProgress,
449
450    /// The requested operation was not found
451    #[error("Operation with idx {operation_idx} not found")]
452    MultisigOperationNotFound {
453        /// Operation idx
454        operation_idx: i32,
455    },
456
457    /// Transfer status already set to a different value
458    #[error("Transfer status already set to a different value")]
459    MultisigTransferStatusMismatch,
460
461    /// Received unexpected data from hub
462    #[error("Unexpected hub data: {details}")]
463    MultisigUnexpectedData {
464        /// Error details
465        details: String,
466    },
467
468    /// The user is not a cosigner
469    #[error("User is not a cosigner")]
470    MultisigUserNotCosigner,
471
472    /// A network error occurred
473    #[error("Network error: {details}")]
474    Network {
475        /// Error details
476        details: String,
477    },
478
479    /// Cannot burn an asset with zero amount
480    #[error("Burn request with zero amount")]
481    NoBurnAmount,
482
483    /// No consignment found
484    #[error("No consignment found")]
485    NoConsignment,
486
487    /// No cosigners supplied
488    #[error("No cosigners supplied")]
489    NoCosignersSupplied,
490
491    /// Cannot inflate an asset with unknown o zero amounts
492    #[error("Inflation request with no amounts or zero amounts")]
493    NoInflationAmounts,
494
495    /// Cannot issue an asset without knowing the amounts
496    #[error("Issuance request with no provided amounts")]
497    NoIssuanceAmounts,
498
499    /// No keys supplied
500    #[error("No keys supplied")]
501    NoKeysSupplied,
502
503    /// Cannot allocate assets with zero allocations per UTXO
504    #[error("Cannot allocate assets with zero allocations per UTXO")]
505    NoMaxAllocationsPerUtxo,
506
507    /// Cannot create a wallet with no supported schemas
508    #[error("Cannot create a wallet with no supported schemas")]
509    NoSupportedSchemas,
510
511    /// No valid transport endpoint found
512    #[error("No valid transport endpoint found")]
513    NoValidTransportEndpoint,
514
515    /// Trying to perform an online operation with offline wallet
516    #[error("Wallet is offline. Hint: call go_online")]
517    Offline,
518
519    /// The Online object is needed to perform this operation
520    #[error("The Online object is needed to perform this operation")]
521    OnlineNeeded,
522
523    /// Output created is under the dust limit
524    #[error("Output below the dust limit")]
525    OutputBelowDustLimit,
526
527    /// Error contacting the RGB proxy
528    #[error("Proxy error: {details}")]
529    Proxy {
530        /// Error details
531        details: String,
532    },
533
534    /// Error during PSBT inspection
535    #[error("Error during PSBT inspection: {details}")]
536    PsbtInspection {
537        /// Error details
538        details: String,
539    },
540
541    /// Provided recipient ID has already been used for another transfer
542    #[error("Recipient ID already used")]
543    RecipientIDAlreadyUsed,
544
545    /// Provided recipient map has duplicated recipient IDs
546    #[error("Recipient ID duplicated")]
547    RecipientIDDuplicated,
548
549    /// Error contacting the reject list service
550    #[error("Reject list service error: {details}")]
551    RejectListService {
552        /// Error details
553        details: String,
554    },
555
556    /// Error building a rest client
557    #[error("Error building a rest client")]
558    RestClientBuild {
559        /// Error details
560        details: String,
561    },
562
563    /// Error during RGB inspection
564    #[error("Error during RGB inspection: {details}")]
565    RgbInspection {
566        /// Error details
567        details: String,
568    },
569
570    /// The inflation amount exceeds the max possible supply
571    #[error("The inflation amount exceeds the max possible supply")]
572    TooHighInflationAmounts,
573
574    /// Trying to issue too many assets
575    #[error("Trying to issue too many assets")]
576    TooHighIssuanceAmounts,
577
578    /// Provided too many cosigners
579    #[error("Provided too many cosigners")]
580    TooManyCosigners,
581
582    /// PSBT has too many signatures
583    #[error("PSBT has too many signatures")]
584    TooManySignaturesInPsbt,
585
586    /// The detected RGB schema is unknown
587    #[error("Unknown RGB schema: {schema_id}")]
588    UnknownRgbSchema {
589        /// RGB schema ID
590        schema_id: String,
591    },
592
593    /// The detected transfer is unknown
594    #[error("Unknown transfer: {txid}")]
595    UnknownTransfer {
596        /// Transfer TXID
597        txid: String,
598    },
599
600    /// The backup version is not supported
601    #[error("Backup version not supported")]
602    UnsupportedBackupVersion {
603        /// Backup version
604        version: String,
605    },
606
607    /// The schema doesn't support burn transitions
608    #[error("Burn not supported")]
609    UnsupportedBurn {
610        /// Asset schema
611        asset_schema: AssetSchema,
612    },
613
614    /// The schema doesn't support inflate transitions
615    #[error("Inflation not supported")]
616    UnsupportedInflation {
617        /// Asset schema
618        asset_schema: AssetSchema,
619    },
620
621    /// The given layer 1 is not supported
622    #[error("Layer 1 {layer_1} is not supported")]
623    UnsupportedLayer1 {
624        /// Layer 1
625        layer_1: String,
626    },
627
628    /// The given schema is not supported
629    #[error("Schema {asset_schema} is not supported")]
630    UnsupportedSchema {
631        /// Asset schema
632        asset_schema: AssetSchema,
633    },
634
635    /// The given transport type is not supported
636    #[error("Transport type is not supported")]
637    UnsupportedTransportType,
638
639    /// The wallet manifest version is not supported
640    #[error("Wallet manifest version not supported")]
641    UnsupportedWalletManifestVersion {
642        /// Wallet manifest version
643        version: String,
644    },
645
646    /// The specified wallet directory already exists
647    #[error("The specified wallet directory already exists: {path}")]
648    WalletDirAlreadyExists {
649        /// The directory path
650        path: String,
651    },
652
653    /// A wallet setting fixed when the wallet was created has been given a different value
654    #[error(
655        "Wallet setting '{setting}' cannot be changed: the wallet was created with '{expected}', got '{provided}'"
656    )]
657    WalletSettingMismatch {
658        /// The setting name
659        setting: String,
660        /// The value the wallet was created with
661        expected: String,
662        /// The value that has been provided
663        provided: String,
664    },
665
666    /// The requested operation cannot be processed by a watch-only wallet
667    #[error("Operation not allowed on watch only wallet")]
668    WatchOnly,
669
670    /// The provided password is incorrect
671    #[error("The provided password is incorrect")]
672    WrongPassword,
673}
674
675#[derive(Debug, thiserror::Error)]
676pub(crate) enum IndexerError {
677    #[cfg(feature = "electrum")]
678    #[error("Electrum error: {0}")]
679    Electrum(#[from] ElectrumError),
680
681    #[cfg(feature = "esplora")]
682    #[error("Esplora error: {0}")]
683    Esplora(#[from] EsploraError),
684}
685
686#[derive(Debug, thiserror::Error)]
687pub(crate) enum InternalError {
688    #[cfg(any(feature = "electrum", feature = "esplora"))]
689    #[error("API error: {0}")]
690    Api(#[from] reqwest::Error),
691
692    #[error("Base64 decode error: {0}")]
693    Base64Decode(#[from] base64::DecodeError),
694
695    #[error("Error from bdk adding UTXOs: {0}")]
696    BdkAddUtxoError(#[from] bdk_wallet::tx_builder::AddUtxoError),
697
698    #[error("Error from bdk extracting TX: {0}")]
699    BdkExtractTxError(String),
700
701    #[error("Error from bdk signing: {0}")]
702    BdkSignerError(#[from] bdk_wallet::signer::SignerError),
703
704    #[error("Error creating RGB commitment: {0}")]
705    Commit(String),
706
707    #[error("Confinement error: {0}")]
708    Confinement(#[from] amplify::confinement::Error),
709
710    #[error("Encode error: {0}")]
711    Encode(#[from] bitcoin::consensus::encode::Error),
712
713    #[error("From slice error: {0}")]
714    FromSlice(#[from] amplify::FromSliceError),
715
716    #[error("Hash error: {0}")]
717    HashError(#[from] scrypt::password_hash::phc::Error),
718
719    #[error("Infallible error: {0}")]
720    Infallible(#[from] std::convert::Infallible),
721
722    #[error("PSBT parse error: {0}")]
723    PsbtParse(#[from] bdk_wallet::bitcoin::psbt::PsbtParseError),
724
725    #[error("RGB load error: {0}")]
726    RgbLoad(#[from] rgbstd::containers::LoadError),
727
728    #[error("RGB PSBT error: {0}")]
729    RgbPsbtError(String),
730
731    #[error("Seal parse error: {0}")]
732    SealParse(#[from] rgbstd::txout::explicit::ParseError),
733
734    #[error("Serde JSON error: {0}")]
735    SerdeJSON(#[from] serde_json::Error),
736
737    #[error("Stash error: {0}")]
738    StashError(String),
739
740    #[error("Stock error: {0}")]
741    StockError(String),
742
743    #[error("Strip prefix error: {0}")]
744    StripPrefix(#[from] std::path::StripPrefixError),
745
746    #[error("System time error: {0}")]
747    SystemTime(#[from] std::time::SystemTimeError),
748
749    #[error("Unexpected error")]
750    Unexpected,
751
752    #[error("Zip error: {0}")]
753    ZipError(#[from] zip::result::ZipError),
754}
755
756impl From<bdk_wallet::keys::bip39::Error> for Error {
757    fn from(e: bdk_wallet::keys::bip39::Error) -> Self {
758        Error::InvalidMnemonic {
759            details: e.to_string(),
760        }
761    }
762}
763
764impl From<bdk_wallet::bitcoin::bip32::Error> for Error {
765    fn from(e: bdk_wallet::bitcoin::bip32::Error) -> Self {
766        Error::InvalidPubkey {
767            details: e.to_string(),
768        }
769    }
770}
771
772impl From<bdk_wallet::bitcoin::psbt::PsbtParseError> for Error {
773    fn from(e: bdk_wallet::bitcoin::psbt::PsbtParseError) -> Self {
774        Error::InvalidPsbt {
775            details: e.to_string(),
776        }
777    }
778}
779
780impl From<IndexerError> for Error {
781    fn from(e: IndexerError) -> Self {
782        Error::Indexer {
783            details: e.to_string(),
784        }
785    }
786}
787
788#[cfg(any(feature = "electrum", feature = "esplora"))]
789impl From<reqwest::Error> for Error {
790    fn from(e: reqwest::Error) -> Self {
791        Error::RestClientBuild {
792            details: e.to_string(),
793        }
794    }
795}
796
797impl From<bdk_wallet::bitcoin::psbt::ExtractTxError> for InternalError {
798    fn from(e: bdk_wallet::bitcoin::psbt::ExtractTxError) -> Self {
799        InternalError::BdkExtractTxError(e.to_string())
800    }
801}
802
803impl From<psrgbt::CommitError> for InternalError {
804    fn from(e: psrgbt::CommitError) -> Self {
805        InternalError::Commit(e.to_string())
806    }
807}
808
809impl From<psrgbt::RgbPsbtError> for InternalError {
810    fn from(e: psrgbt::RgbPsbtError) -> Self {
811        InternalError::RgbPsbtError(e.to_string())
812    }
813}
814
815impl From<psrgbt::OpretKeyError> for InternalError {
816    fn from(e: psrgbt::OpretKeyError) -> Self {
817        InternalError::RgbPsbtError(e.to_string())
818    }
819}
820
821impl From<psrgbt::MpcPsbtError> for InternalError {
822    fn from(e: psrgbt::MpcPsbtError) -> Self {
823        InternalError::RgbPsbtError(e.to_string())
824    }
825}
826
827impl From<rgbstd::persistence::StashProviderError<std::convert::Infallible>> for InternalError {
828    fn from(e: rgbstd::persistence::StashProviderError<std::convert::Infallible>) -> Self {
829        InternalError::StashError(e.to_string())
830    }
831}
832
833impl From<rgbstd::persistence::StockError> for InternalError {
834    fn from(e: rgbstd::persistence::StockError) -> Self {
835        InternalError::StockError(e.to_string())
836    }
837}
838
839impl
840    From<
841        rgbstd::persistence::StockError<
842            rgbstd::persistence::MemStash,
843            rgbstd::persistence::MemState,
844            rgbstd::persistence::MemIndex,
845            rgbstd::persistence::ConsignError,
846        >,
847    > for InternalError
848{
849    fn from(
850        e: rgbstd::persistence::StockError<
851            rgbstd::persistence::MemStash,
852            rgbstd::persistence::MemState,
853            rgbstd::persistence::MemIndex,
854            rgbstd::persistence::ConsignError,
855        >,
856    ) -> Self {
857        InternalError::StockError(e.to_string())
858    }
859}
860
861impl
862    From<
863        rgbstd::persistence::StockError<
864            rgbstd::persistence::MemStash,
865            rgbstd::persistence::MemState,
866            rgbstd::persistence::MemIndex,
867            rgbstd::persistence::FasciaError,
868        >,
869    > for InternalError
870{
871    fn from(
872        e: rgbstd::persistence::StockError<
873            rgbstd::persistence::MemStash,
874            rgbstd::persistence::MemState,
875            rgbstd::persistence::MemIndex,
876            rgbstd::persistence::FasciaError,
877        >,
878    ) -> Self {
879        InternalError::StockError(e.to_string())
880    }
881}
882
883impl From<rgbinvoice::TransportParseError> for Error {
884    fn from(e: rgbinvoice::TransportParseError) -> Self {
885        Error::InvalidTransportEndpoint {
886            details: e.to_string(),
887        }
888    }
889}
890
891impl From<bdk_wallet::file_store::StoreErrorWithDump<ChangeSet>> for Error {
892    fn from(e: bdk_wallet::file_store::StoreErrorWithDump<ChangeSet>) -> Self {
893        Error::IO {
894            details: e.to_string(),
895        }
896    }
897}
898
899impl From<bdk_wallet::FileStoreError> for Error {
900    fn from(e: bdk_wallet::FileStoreError) -> Self {
901        Error::IO {
902            details: e.to_string(),
903        }
904    }
905}
906
907impl From<bdk_wallet::CreateWithPersistError<bdk_wallet::FileStoreError>> for Error {
908    fn from(e: bdk_wallet::CreateWithPersistError<bdk_wallet::FileStoreError>) -> Self {
909        Error::IO {
910            details: e.to_string(),
911        }
912    }
913}
914
915impl From<bdk_wallet::LoadWithPersistError<bdk_wallet::FileStoreError>> for Error {
916    fn from(e: bdk_wallet::LoadWithPersistError<bdk_wallet::FileStoreError>) -> Self {
917        match e {
918            bdk_wallet::LoadWithPersistError::InvalidChangeSet(
919                bdk_wallet::LoadError::Mismatch(bdk_wallet::LoadMismatch::Genesis { .. }),
920            ) => Error::BitcoinNetworkMismatch,
921            _ => Error::IO {
922                details: e.to_string(),
923            },
924        }
925    }
926}
927
928impl From<std::io::Error> for Error {
929    fn from(e: std::io::Error) -> Self {
930        Error::IO {
931            details: e.to_string(),
932        }
933    }
934}
935
936impl From<InternalError> for Error {
937    fn from(e: InternalError) -> Self {
938        Error::Internal {
939            details: e.to_string(),
940        }
941    }
942}
943
944impl From<sea_orm::DbErr> for Error {
945    fn from(e: sea_orm::DbErr) -> Self {
946        Error::Database {
947            details: e.to_string(),
948        }
949    }
950}
951
952impl From<rgbstd::contract::BuilderError> for Error {
953    fn from(e: rgbstd::contract::BuilderError) -> Self {
954        Error::Internal {
955            details: e.to_string(),
956        }
957    }
958}
959
960#[cfg(test)]
961mod tests {
962    use super::*;
963
964    const FAKE_PSBT: &str = "cHNidP8BAF4CAAAAATQi69UHNVN1H3GVJyjCt2qx9Xsmt56SLSMwGM/GQxgBAQAAAAD9////AfQBAAAAAAAAIlEgoK74YaTaHlE4t4tfisItYxVkOmBakMt96x+kMAS6ArcZCgAAAAEBK+gDAAAAAAAAIlEgjWk7HP1AQKe/fp/RWQmQzRsfIQWHq+fWUteGf/YfEy0hFoJzo2OMevtseGK/uBkC+bautE/IgnmbDCz6eMojamp4GQA39GtzVgAAgB+fDIAAAACAAAAAAAAAAAABFyCCc6NjjHr7bHhiv7gZAvm2rrRPyIJ5mwws+njKI2pqeAAA";
965
966    #[test]
967    fn from_error() {
968        // NotFound error
969        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
970        let err = Error::from(io_err);
971        assert_matches!(err, Error::IO { details } if details.contains("file not found"));
972
973        // Unexpected error
974        let internal = InternalError::Unexpected;
975        let err = Error::from(internal);
976        assert_matches!(err, Error::Internal { details } if details == "Unexpected error");
977
978        // Bip39 error
979        let bip39_err = bdk_wallet::keys::bip39::Error::BadWordCount(5);
980        let err = Error::from(bip39_err);
981        assert_matches!(err, Error::InvalidMnemonic { details } if !details.is_empty());
982
983        // Bip32 error
984        let bip32_err = bdk_wallet::bitcoin::bip32::Error::CannotDeriveFromHardenedKey;
985        let err = Error::from(bip32_err);
986        assert_matches!(err, Error::InvalidPubkey { details } if !details.is_empty());
987
988        // BuilderError error
989        let err = rgbstd::contract::BuilderError::InvalidStateField(FieldName::from("test"));
990        let err = Error::from(err);
991        assert_matches!(err, Error::Internal { details } if !details.is_empty());
992
993        // LoadWithPersistError error
994        let err = bdk_wallet::LoadWithPersistError::Persist(bdk_wallet::FileStoreError::Write(
995            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "no access"),
996        ));
997        let err = Error::from(err);
998        assert_matches!(err, Error::IO { details } if !details.is_empty());
999
1000        // CreateWithPersistError error
1001        let err = bdk_wallet::CreateWithPersistError::Persist(bdk_wallet::FileStoreError::Write(
1002            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "no access"),
1003        ));
1004        let err = Error::from(err);
1005        assert_matches!(err, Error::IO { details } if !details.is_empty());
1006
1007        // FileStoreError error
1008        let err = bdk_wallet::FileStoreError::Write(std::io::Error::new(
1009            std::io::ErrorKind::PermissionDenied,
1010            "no access",
1011        ));
1012        let err = Error::from(err);
1013        assert_matches!(err, Error::IO { details } if !details.is_empty());
1014
1015        // StoreErrorWithDump error
1016        let err = bdk_wallet::file_store::StoreErrorWithDump::<ChangeSet>::from(
1017            std::io::Error::new(std::io::ErrorKind::PermissionDenied, "no access"),
1018        );
1019        let err = Error::from(err);
1020        assert_matches!(err, Error::IO { details } if !details.is_empty());
1021
1022        // IndexerError error
1023        #[cfg(feature = "electrum")]
1024        {
1025            let err = IndexerError::Electrum(ElectrumError::MissingDomain);
1026            let err = Error::from(err);
1027            assert_matches!(err, Error::Indexer { details } if !details.is_empty());
1028        }
1029        #[cfg(all(feature = "esplora", not(feature = "electrum")))]
1030        {
1031            let err = IndexerError::Esplora(EsploraError::InvalidResponse);
1032            let err = Error::from(err);
1033            assert_matches!(err, Error::Indexer { details } if !details.is_empty());
1034        }
1035    }
1036
1037    #[test]
1038    fn from_internal_error() {
1039        // SerdeJSON error
1040        let serde_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();
1041        let msg = serde_err.to_string();
1042        let internal = InternalError::from(serde_err);
1043        assert_matches!(
1044            internal,
1045            InternalError::SerdeJSON(ref e) if e.to_string() == msg
1046        );
1047
1048        // StripPrefix error
1049        let strip_err = Path::new("foo").strip_prefix("bar").unwrap_err();
1050        let msg = strip_err.to_string();
1051        let internal = InternalError::from(strip_err);
1052        assert_matches!(
1053            internal,
1054            InternalError::StripPrefix(ref e) if e.to_string() == msg
1055        );
1056
1057        // ExtractTxError error
1058        let psbt = Psbt::from_str(FAKE_PSBT).unwrap();
1059        let err = bdk_wallet::bitcoin::psbt::ExtractTxError::SendingTooMuch { psbt };
1060        let err = InternalError::from(err);
1061        assert_matches!(err, InternalError::BdkExtractTxError(ref e) if !e.is_empty());
1062
1063        // RgbPsbtError error
1064        let err = psrgbt::RgbPsbtError::NoContracts;
1065        let err = InternalError::from(err);
1066        assert_matches!(err, InternalError::RgbPsbtError(ref e) if !e.is_empty());
1067
1068        // OpretKeyError error
1069        let err = psrgbt::OpretKeyError::NoCommitment;
1070        let err = InternalError::from(err);
1071        assert_matches!(err, InternalError::RgbPsbtError(ref e) if !e.is_empty());
1072
1073        // MpcPsbtError error
1074        let err = psrgbt::MpcPsbtError::KeyAlreadyPresent;
1075        let err = InternalError::from(err);
1076        assert_matches!(err, InternalError::RgbPsbtError(ref e) if !e.is_empty());
1077
1078        // CommitError error
1079        let err = psrgbt::CommitError::Rgb(psrgbt::RgbPsbtError::NoContracts);
1080        let err = InternalError::from(err);
1081        assert_matches!(err, InternalError::Commit(ref e) if !e.is_empty());
1082
1083        // StockError errors
1084        let err: rgbstd::persistence::StockError<
1085            rgbstd::persistence::MemStash,
1086            rgbstd::persistence::MemState,
1087            rgbstd::persistence::MemIndex,
1088            rgbstd::persistence::FasciaError,
1089        > = rgbstd::persistence::StockError::AbsentValidWitness;
1090        let err = InternalError::from(err);
1091        assert_matches!(err, InternalError::StockError(ref e) if !e.is_empty());
1092        let err: rgbstd::persistence::StockError<
1093            rgbstd::persistence::MemStash,
1094            rgbstd::persistence::MemState,
1095            rgbstd::persistence::MemIndex,
1096            rgbstd::persistence::ConsignError,
1097        > = rgbstd::persistence::StockError::AbsentValidWitness;
1098        let err = InternalError::from(err);
1099        assert_matches!(err, InternalError::StockError(ref e) if !e.is_empty());
1100        let err: rgbstd::persistence::StockError<
1101            rgbstd::persistence::MemStash,
1102            rgbstd::persistence::MemState,
1103            rgbstd::persistence::MemIndex,
1104        > = rgbstd::persistence::StockError::Resolver(s!("test"));
1105        let err = InternalError::from(err);
1106        assert_matches!(err, InternalError::StockError(ref e) if !e.is_empty());
1107    }
1108}