error.rs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. //! Errors
  2. use std::array::TryFromSliceError;
  3. use std::fmt;
  4. use cashu::{CurrencyUnit, PaymentMethod};
  5. use serde::{Deserialize, Deserializer, Serialize, Serializer};
  6. use serde_json::Value;
  7. use thiserror::Error;
  8. use crate::nuts::Id;
  9. use crate::util::hex;
  10. #[cfg(feature = "wallet")]
  11. use crate::wallet::WalletKey;
  12. use crate::Amount;
  13. /// CDK Error
  14. #[derive(Debug, Error)]
  15. pub enum Error {
  16. /// Mint does not have a key for amount
  17. #[error("No Key for Amount")]
  18. AmountKey,
  19. /// Keyset is not known
  20. #[error("Keyset id not known: `{0}`")]
  21. KeysetUnknown(Id),
  22. /// Unsupported unit
  23. #[error("Unit unsupported")]
  24. UnsupportedUnit,
  25. /// Payment failed
  26. #[error("Payment failed")]
  27. PaymentFailed,
  28. /// Payment pending
  29. #[error("Payment pending")]
  30. PaymentPending,
  31. /// Invoice already paid
  32. #[error("Request already paid")]
  33. RequestAlreadyPaid,
  34. /// Invalid payment request
  35. #[error("Invalid payment request")]
  36. InvalidPaymentRequest,
  37. /// Bolt11 invoice does not have amount
  38. #[error("Invoice Amount undefined")]
  39. InvoiceAmountUndefined,
  40. /// Split Values must be less then or equal to amount
  41. #[error("Split Values must be less then or equal to amount")]
  42. SplitValuesGreater,
  43. /// Amount overflow
  44. #[error("Amount Overflow")]
  45. AmountOverflow,
  46. /// Witness missing or invalid
  47. #[error("Signature missing or invalid")]
  48. SignatureMissingOrInvalid,
  49. /// Amountless Invoice Not supported
  50. #[error("Amount Less Invoice is not allowed")]
  51. AmountLessNotAllowed,
  52. /// Multi-Part Internal Melt Quotes are not supported
  53. #[error("Multi-Part Internal Melt Quotes are not supported")]
  54. InternalMultiPartMeltQuote,
  55. /// Multi-Part Payment not supported for unit and method
  56. #[error("Multi-Part payment is not supported for unit `{0}` and method `{1}`")]
  57. MppUnitMethodNotSupported(CurrencyUnit, PaymentMethod),
  58. /// Clear Auth Required
  59. #[error("Clear Auth Required")]
  60. ClearAuthRequired,
  61. /// Blind Auth Required
  62. #[error("Blind Auth Required")]
  63. BlindAuthRequired,
  64. /// Clear Auth Failed
  65. #[error("Clear Auth Failed")]
  66. ClearAuthFailed,
  67. /// Blind Auth Failed
  68. #[error("Blind Auth Failed")]
  69. BlindAuthFailed,
  70. /// Auth settings undefined
  71. #[error("Auth settings undefined")]
  72. AuthSettingsUndefined,
  73. /// Mint time outside of tolerance
  74. #[error("Mint time outside of tolerance")]
  75. MintTimeExceedsTolerance,
  76. /// Insufficient blind auth tokens
  77. #[error("Insufficient blind auth tokens, must reauth")]
  78. InsufficientBlindAuthTokens,
  79. /// Auth localstore undefined
  80. #[error("Auth localstore undefined")]
  81. AuthLocalstoreUndefined,
  82. /// Wallet cat not set
  83. #[error("Wallet cat not set")]
  84. CatNotSet,
  85. /// Could not get mint info
  86. #[error("Could not get mint info")]
  87. CouldNotGetMintInfo,
  88. /// Multi-Part Payment not supported for unit and method
  89. #[error("Amountless invoices are not supported for unit `{0}` and method `{1}`")]
  90. AmountlessInvoiceNotSupported(CurrencyUnit, PaymentMethod),
  91. /// Duplicate Payment id
  92. #[error("Payment id seen for mint")]
  93. DuplicatePaymentId,
  94. /// Pubkey required
  95. #[error("Pubkey required")]
  96. PubkeyRequired,
  97. /// Invalid payment method
  98. #[error("Invalid payment method")]
  99. InvalidPaymentMethod,
  100. /// Amount undefined
  101. #[error("Amount undefined")]
  102. AmountUndefined,
  103. /// Unsupported payment method
  104. #[error("Payment method unsupported")]
  105. UnsupportedPaymentMethod,
  106. /// Could not parse bolt12
  107. #[error("Could not parse bolt12")]
  108. Bolt12parse,
  109. /// Operation timeout
  110. #[error("Operation timeout")]
  111. Timeout,
  112. /// Internal Error - Send error
  113. #[error("Internal send error: {0}")]
  114. SendError(String),
  115. /// Internal Error - Recv error
  116. #[error("Internal receive error: {0}")]
  117. RecvError(String),
  118. // Mint Errors
  119. /// Minting is disabled
  120. #[error("Minting is disabled")]
  121. MintingDisabled,
  122. /// Quote is not known
  123. #[error("Unknown quote")]
  124. UnknownQuote,
  125. /// Quote is expired
  126. #[error("Expired quote: Expired: `{0}`, Time: `{1}`")]
  127. ExpiredQuote(u64, u64),
  128. /// Amount is outside of allowed range
  129. #[error("Amount must be between `{0}` and `{1}` is `{2}`")]
  130. AmountOutofLimitRange(Amount, Amount, Amount),
  131. /// Quote is not paiud
  132. #[error("Quote not paid")]
  133. UnpaidQuote,
  134. /// Quote is pending
  135. #[error("Quote pending")]
  136. PendingQuote,
  137. /// ecash already issued for quote
  138. #[error("Quote already issued")]
  139. IssuedQuote,
  140. /// Quote has already been paid
  141. #[error("Quote is already paid")]
  142. PaidQuote,
  143. /// Payment state is unknown
  144. #[error("Payment state is unknown")]
  145. UnknownPaymentState,
  146. /// Melting is disabled
  147. #[error("Minting is disabled")]
  148. MeltingDisabled,
  149. /// Unknown Keyset
  150. #[error("Unknown Keyset")]
  151. UnknownKeySet,
  152. /// BlindedMessage is already signed
  153. #[error("Blinded Message is already signed")]
  154. BlindedMessageAlreadySigned,
  155. /// Inactive Keyset
  156. #[error("Inactive Keyset")]
  157. InactiveKeyset,
  158. /// Transaction unbalanced
  159. #[error("Inputs: `{0}`, Outputs: `{1}`, Expected Fee: `{2}`")]
  160. TransactionUnbalanced(u64, u64, u64),
  161. /// Duplicate proofs provided
  162. #[error("Duplicate Inputs")]
  163. DuplicateInputs,
  164. /// Duplicate output
  165. #[error("Duplicate outputs")]
  166. DuplicateOutputs,
  167. /// Multiple units provided
  168. #[error("Cannot have multiple units")]
  169. MultipleUnits,
  170. /// Unit mismatch
  171. #[error("Input unit must match output")]
  172. UnitMismatch,
  173. /// Sig all cannot be used in melt
  174. #[error("Sig all cannot be used in melt")]
  175. SigAllUsedInMelt,
  176. /// Token is already spent
  177. #[error("Token Already Spent")]
  178. TokenAlreadySpent,
  179. /// Token is already pending
  180. #[error("Token Pending")]
  181. TokenPending,
  182. /// Internal Error
  183. #[error("Internal Error")]
  184. Internal,
  185. /// Oidc config not set
  186. #[error("Oidc client not set")]
  187. OidcNotSet,
  188. // Wallet Errors
  189. /// P2PK spending conditions not met
  190. #[error("P2PK condition not met `{0}`")]
  191. P2PKConditionsNotMet(String),
  192. /// Spending Locktime not provided
  193. #[error("Spending condition locktime not provided")]
  194. LocktimeNotProvided,
  195. /// Invalid Spending Conditions
  196. #[error("Invalid spending conditions: `{0}`")]
  197. InvalidSpendConditions(String),
  198. /// Incorrect Wallet
  199. #[error("Incorrect wallet: `{0}`")]
  200. IncorrectWallet(String),
  201. /// Unknown Wallet
  202. #[error("Unknown wallet: `{0}`")]
  203. #[cfg(feature = "wallet")]
  204. UnknownWallet(WalletKey),
  205. /// Max Fee Ecxeded
  206. #[error("Max fee exceeded")]
  207. MaxFeeExceeded,
  208. /// Url path segments could not be joined
  209. #[error("Url path segments could not be joined")]
  210. UrlPathSegments,
  211. /// Unknown error response
  212. #[error("Unknown error response: `{0}`")]
  213. UnknownErrorResponse(String),
  214. /// Invalid DLEQ proof
  215. #[error("Could not verify DLEQ proof")]
  216. CouldNotVerifyDleq,
  217. /// Dleq Proof not provided for signature
  218. #[error("Dleq proof not provided for signature")]
  219. DleqProofNotProvided,
  220. /// Incorrect Mint
  221. /// Token does not match wallet mint
  222. #[error("Token does not match wallet mint")]
  223. IncorrectMint,
  224. /// Receive can only be used with tokens from single mint
  225. #[error("Multiple mint tokens not supported by receive. Please deconstruct the token and use receive with_proof")]
  226. MultiMintTokenNotSupported,
  227. /// Preimage not provided
  228. #[error("Preimage not provided")]
  229. PreimageNotProvided,
  230. /// Insufficient Funds
  231. #[error("Insufficient funds")]
  232. InsufficientFunds,
  233. /// Unexpected proof state
  234. #[error("Unexpected proof state")]
  235. UnexpectedProofState,
  236. /// No active keyset
  237. #[error("No active keyset")]
  238. NoActiveKeyset,
  239. /// Incorrect quote amount
  240. #[error("Incorrect quote amount")]
  241. IncorrectQuoteAmount,
  242. /// Invoice Description not supported
  243. #[error("Invoice Description not supported")]
  244. InvoiceDescriptionUnsupported,
  245. /// Invalid transaction direction
  246. #[error("Invalid transaction direction")]
  247. InvalidTransactionDirection,
  248. /// Invalid transaction id
  249. #[error("Invalid transaction id")]
  250. InvalidTransactionId,
  251. /// Transaction not found
  252. #[error("Transaction not found")]
  253. TransactionNotFound,
  254. /// Custom Error
  255. #[error("`{0}`")]
  256. Custom(String),
  257. // External Error conversions
  258. /// Parse invoice error
  259. #[error(transparent)]
  260. Invoice(#[from] lightning_invoice::ParseOrSemanticError),
  261. /// Bip32 error
  262. #[error(transparent)]
  263. Bip32(#[from] bitcoin::bip32::Error),
  264. /// Parse int error
  265. #[error(transparent)]
  266. ParseInt(#[from] std::num::ParseIntError),
  267. /// Parse 9rl Error
  268. #[error(transparent)]
  269. UrlParseError(#[from] url::ParseError),
  270. /// Utf8 parse error
  271. #[error(transparent)]
  272. Utf8ParseError(#[from] std::string::FromUtf8Error),
  273. /// Serde Json error
  274. #[error(transparent)]
  275. SerdeJsonError(#[from] serde_json::Error),
  276. /// Base64 error
  277. #[error(transparent)]
  278. Base64Error(#[from] bitcoin::base64::DecodeError),
  279. /// From hex error
  280. #[error(transparent)]
  281. HexError(#[from] hex::Error),
  282. /// Http transport error
  283. #[error("Http transport error {0:?}: {1}")]
  284. HttpError(Option<u16>, String),
  285. #[cfg(feature = "wallet")]
  286. // Crate error conversions
  287. /// Cashu Url Error
  288. #[error(transparent)]
  289. CashuUrl(#[from] crate::mint_url::Error),
  290. /// Secret error
  291. #[error(transparent)]
  292. Secret(#[from] crate::secret::Error),
  293. /// Amount Error
  294. #[error(transparent)]
  295. AmountError(#[from] crate::amount::Error),
  296. /// DHKE Error
  297. #[error(transparent)]
  298. DHKE(#[from] crate::dhke::Error),
  299. /// NUT00 Error
  300. #[error(transparent)]
  301. NUT00(#[from] crate::nuts::nut00::Error),
  302. /// Nut01 error
  303. #[error(transparent)]
  304. NUT01(#[from] crate::nuts::nut01::Error),
  305. /// NUT02 error
  306. #[error(transparent)]
  307. NUT02(#[from] crate::nuts::nut02::Error),
  308. /// NUT03 error
  309. #[error(transparent)]
  310. NUT03(#[from] crate::nuts::nut03::Error),
  311. /// NUT04 error
  312. #[error(transparent)]
  313. NUT04(#[from] crate::nuts::nut04::Error),
  314. /// NUT05 error
  315. #[error(transparent)]
  316. NUT05(#[from] crate::nuts::nut05::Error),
  317. /// NUT11 Error
  318. #[error(transparent)]
  319. NUT11(#[from] crate::nuts::nut11::Error),
  320. /// NUT12 Error
  321. #[error(transparent)]
  322. NUT12(#[from] crate::nuts::nut12::Error),
  323. /// NUT13 Error
  324. #[error(transparent)]
  325. #[cfg(feature = "wallet")]
  326. NUT13(#[from] crate::nuts::nut13::Error),
  327. /// NUT14 Error
  328. #[error(transparent)]
  329. NUT14(#[from] crate::nuts::nut14::Error),
  330. /// NUT18 Error
  331. #[error(transparent)]
  332. NUT18(#[from] crate::nuts::nut18::Error),
  333. /// NUT20 Error
  334. #[error(transparent)]
  335. NUT20(#[from] crate::nuts::nut20::Error),
  336. /// NUT21 Error
  337. #[error(transparent)]
  338. NUT21(#[from] crate::nuts::nut21::Error),
  339. /// NUT22 Error
  340. #[error(transparent)]
  341. NUT22(#[from] crate::nuts::nut22::Error),
  342. /// NUT23 Error
  343. #[error(transparent)]
  344. NUT23(#[from] crate::nuts::nut23::Error),
  345. /// From slice error
  346. #[error(transparent)]
  347. TryFromSliceError(#[from] TryFromSliceError),
  348. /// Database Error
  349. #[error(transparent)]
  350. Database(crate::database::Error),
  351. /// Payment Error
  352. #[error(transparent)]
  353. #[cfg(feature = "mint")]
  354. Payment(#[from] crate::payment::Error),
  355. }
  356. /// CDK Error Response
  357. ///
  358. /// See NUT definition in [00](https://github.com/cashubtc/nuts/blob/main/00.md)
  359. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  360. #[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
  361. pub struct ErrorResponse {
  362. /// Error Code
  363. pub code: ErrorCode,
  364. /// Human readable Text
  365. pub error: Option<String>,
  366. /// Longer human readable description
  367. pub detail: Option<String>,
  368. }
  369. impl fmt::Display for ErrorResponse {
  370. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  371. write!(
  372. f,
  373. "code: {}, error: {}, detail: {}",
  374. self.code,
  375. self.error.clone().unwrap_or_default(),
  376. self.detail.clone().unwrap_or_default()
  377. )
  378. }
  379. }
  380. impl ErrorResponse {
  381. /// Create new [`ErrorResponse`]
  382. pub fn new(code: ErrorCode, error: Option<String>, detail: Option<String>) -> Self {
  383. Self {
  384. code,
  385. error,
  386. detail,
  387. }
  388. }
  389. /// Error response from json
  390. pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
  391. let value: Value = serde_json::from_str(json)?;
  392. Self::from_value(value)
  393. }
  394. /// Error response from json Value
  395. pub fn from_value(value: Value) -> Result<Self, serde_json::Error> {
  396. match serde_json::from_value::<ErrorResponse>(value.clone()) {
  397. Ok(res) => Ok(res),
  398. Err(_) => Ok(Self {
  399. code: ErrorCode::Unknown(999),
  400. error: Some(value.to_string()),
  401. detail: None,
  402. }),
  403. }
  404. }
  405. }
  406. impl From<Error> for ErrorResponse {
  407. fn from(err: Error) -> ErrorResponse {
  408. match err {
  409. Error::TokenAlreadySpent => ErrorResponse {
  410. code: ErrorCode::TokenAlreadySpent,
  411. error: Some(err.to_string()),
  412. detail: None,
  413. },
  414. Error::UnsupportedUnit => ErrorResponse {
  415. code: ErrorCode::UnsupportedUnit,
  416. error: Some(err.to_string()),
  417. detail: None,
  418. },
  419. Error::PaymentFailed => ErrorResponse {
  420. code: ErrorCode::LightningError,
  421. error: Some(err.to_string()),
  422. detail: None,
  423. },
  424. Error::RequestAlreadyPaid => ErrorResponse {
  425. code: ErrorCode::InvoiceAlreadyPaid,
  426. error: Some("Invoice already paid.".to_string()),
  427. detail: None,
  428. },
  429. Error::TransactionUnbalanced(inputs_total, outputs_total, fee_expected) => {
  430. ErrorResponse {
  431. code: ErrorCode::TransactionUnbalanced,
  432. error: Some(format!(
  433. "Inputs: {inputs_total}, Outputs: {outputs_total}, expected_fee: {fee_expected}",
  434. )),
  435. detail: Some("Transaction inputs should equal outputs less fee".to_string()),
  436. }
  437. }
  438. Error::MintingDisabled => ErrorResponse {
  439. code: ErrorCode::MintingDisabled,
  440. error: Some(err.to_string()),
  441. detail: None,
  442. },
  443. Error::BlindedMessageAlreadySigned => ErrorResponse {
  444. code: ErrorCode::BlindedMessageAlreadySigned,
  445. error: Some(err.to_string()),
  446. detail: None,
  447. },
  448. Error::InsufficientFunds => ErrorResponse {
  449. code: ErrorCode::TransactionUnbalanced,
  450. error: Some(err.to_string()),
  451. detail: None,
  452. },
  453. Error::AmountOutofLimitRange(_min, _max, _amount) => ErrorResponse {
  454. code: ErrorCode::AmountOutofLimitRange,
  455. error: Some(err.to_string()),
  456. detail: None,
  457. },
  458. Error::ExpiredQuote(_, _) => ErrorResponse {
  459. code: ErrorCode::QuoteExpired,
  460. error: Some(err.to_string()),
  461. detail: None,
  462. },
  463. Error::PendingQuote => ErrorResponse {
  464. code: ErrorCode::QuotePending,
  465. error: Some(err.to_string()),
  466. detail: None,
  467. },
  468. Error::TokenPending => ErrorResponse {
  469. code: ErrorCode::TokenPending,
  470. error: Some(err.to_string()),
  471. detail: None,
  472. },
  473. Error::ClearAuthRequired => ErrorResponse {
  474. code: ErrorCode::ClearAuthRequired,
  475. error: None,
  476. detail: None,
  477. },
  478. Error::ClearAuthFailed => ErrorResponse {
  479. code: ErrorCode::ClearAuthFailed,
  480. error: None,
  481. detail: None,
  482. },
  483. Error::BlindAuthRequired => ErrorResponse {
  484. code: ErrorCode::BlindAuthRequired,
  485. error: None,
  486. detail: None,
  487. },
  488. Error::BlindAuthFailed => ErrorResponse {
  489. code: ErrorCode::BlindAuthFailed,
  490. error: None,
  491. detail: None,
  492. },
  493. Error::NUT20(err) => ErrorResponse {
  494. code: ErrorCode::WitnessMissingOrInvalid,
  495. error: Some(err.to_string()),
  496. detail: None,
  497. },
  498. Error::DuplicateInputs => ErrorResponse {
  499. code: ErrorCode::DuplicateInputs,
  500. error: Some(err.to_string()),
  501. detail: None,
  502. },
  503. Error::DuplicateOutputs => ErrorResponse {
  504. code: ErrorCode::DuplicateOutputs,
  505. error: Some(err.to_string()),
  506. detail: None,
  507. },
  508. Error::MultipleUnits => ErrorResponse {
  509. code: ErrorCode::MultipleUnits,
  510. error: Some(err.to_string()),
  511. detail: None,
  512. },
  513. Error::UnitMismatch => ErrorResponse {
  514. code: ErrorCode::UnitMismatch,
  515. error: Some(err.to_string()),
  516. detail: None,
  517. },
  518. _ => ErrorResponse {
  519. code: ErrorCode::Unknown(9999),
  520. error: Some(err.to_string()),
  521. detail: None,
  522. },
  523. }
  524. }
  525. }
  526. #[cfg(feature = "mint")]
  527. impl From<crate::database::Error> for Error {
  528. fn from(db_error: crate::database::Error) -> Self {
  529. match db_error {
  530. crate::database::Error::InvalidStateTransition(state) => match state {
  531. crate::state::Error::Pending => Self::TokenPending,
  532. crate::state::Error::AlreadySpent => Self::TokenAlreadySpent,
  533. state => Self::Database(crate::database::Error::InvalidStateTransition(state)),
  534. },
  535. db_error => Self::Database(db_error),
  536. }
  537. }
  538. }
  539. #[cfg(not(feature = "mint"))]
  540. impl From<crate::database::Error> for Error {
  541. fn from(db_error: crate::database::Error) -> Self {
  542. Self::Database(db_error)
  543. }
  544. }
  545. impl From<ErrorResponse> for Error {
  546. fn from(err: ErrorResponse) -> Error {
  547. match err.code {
  548. ErrorCode::TokenAlreadySpent => Self::TokenAlreadySpent,
  549. ErrorCode::QuoteNotPaid => Self::UnpaidQuote,
  550. ErrorCode::QuotePending => Self::PendingQuote,
  551. ErrorCode::QuoteExpired => Self::ExpiredQuote(0, 0),
  552. ErrorCode::KeysetNotFound => Self::UnknownKeySet,
  553. ErrorCode::KeysetInactive => Self::InactiveKeyset,
  554. ErrorCode::BlindedMessageAlreadySigned => Self::BlindedMessageAlreadySigned,
  555. ErrorCode::UnsupportedUnit => Self::UnsupportedUnit,
  556. ErrorCode::TransactionUnbalanced => Self::TransactionUnbalanced(0, 0, 0),
  557. ErrorCode::MintingDisabled => Self::MintingDisabled,
  558. ErrorCode::InvoiceAlreadyPaid => Self::RequestAlreadyPaid,
  559. ErrorCode::TokenNotVerified => Self::DHKE(crate::dhke::Error::TokenNotVerified),
  560. ErrorCode::LightningError => Self::PaymentFailed,
  561. ErrorCode::AmountOutofLimitRange => {
  562. Self::AmountOutofLimitRange(Amount::default(), Amount::default(), Amount::default())
  563. }
  564. ErrorCode::TokenPending => Self::TokenPending,
  565. ErrorCode::WitnessMissingOrInvalid => Self::SignatureMissingOrInvalid,
  566. ErrorCode::DuplicateInputs => Self::DuplicateInputs,
  567. ErrorCode::DuplicateOutputs => Self::DuplicateOutputs,
  568. ErrorCode::MultipleUnits => Self::MultipleUnits,
  569. ErrorCode::UnitMismatch => Self::UnitMismatch,
  570. ErrorCode::ClearAuthRequired => Self::ClearAuthRequired,
  571. ErrorCode::BlindAuthRequired => Self::BlindAuthRequired,
  572. _ => Self::UnknownErrorResponse(err.to_string()),
  573. }
  574. }
  575. }
  576. /// Possible Error Codes
  577. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
  578. #[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
  579. pub enum ErrorCode {
  580. /// Token is already spent
  581. TokenAlreadySpent,
  582. /// Token Pending
  583. TokenPending,
  584. /// Quote is not paid
  585. QuoteNotPaid,
  586. /// Quote is not expired
  587. QuoteExpired,
  588. /// Quote Pending
  589. QuotePending,
  590. /// Keyset is not found
  591. KeysetNotFound,
  592. /// Keyset inactive
  593. KeysetInactive,
  594. /// Blinded Message Already signed
  595. BlindedMessageAlreadySigned,
  596. /// Unsupported unit
  597. UnsupportedUnit,
  598. /// Token already issed for quote
  599. TokensAlreadyIssued,
  600. /// Minting Disabled
  601. MintingDisabled,
  602. /// Invoice Already Paid
  603. InvoiceAlreadyPaid,
  604. /// Token Not Verified
  605. TokenNotVerified,
  606. /// Lightning Error
  607. LightningError,
  608. /// Unbalanced Error
  609. TransactionUnbalanced,
  610. /// Amount outside of allowed range
  611. AmountOutofLimitRange,
  612. /// Witness missing or invalid
  613. WitnessMissingOrInvalid,
  614. /// Duplicate Inputs
  615. DuplicateInputs,
  616. /// Duplicate Outputs
  617. DuplicateOutputs,
  618. /// Multiple Units
  619. MultipleUnits,
  620. /// Input unit does not match output
  621. UnitMismatch,
  622. /// Clear Auth Required
  623. ClearAuthRequired,
  624. /// Clear Auth Failed
  625. ClearAuthFailed,
  626. /// Blind Auth Required
  627. BlindAuthRequired,
  628. /// Blind Auth Failed
  629. BlindAuthFailed,
  630. /// Unknown error code
  631. Unknown(u16),
  632. }
  633. impl ErrorCode {
  634. /// Error code from u16
  635. pub fn from_code(code: u16) -> Self {
  636. match code {
  637. 10002 => Self::BlindedMessageAlreadySigned,
  638. 10003 => Self::TokenNotVerified,
  639. 11001 => Self::TokenAlreadySpent,
  640. 11002 => Self::TransactionUnbalanced,
  641. 11005 => Self::UnsupportedUnit,
  642. 11006 => Self::AmountOutofLimitRange,
  643. 11007 => Self::DuplicateInputs,
  644. 11008 => Self::DuplicateOutputs,
  645. 11009 => Self::MultipleUnits,
  646. 11010 => Self::UnitMismatch,
  647. 11012 => Self::TokenPending,
  648. 12001 => Self::KeysetNotFound,
  649. 12002 => Self::KeysetInactive,
  650. 20000 => Self::LightningError,
  651. 20001 => Self::QuoteNotPaid,
  652. 20002 => Self::TokensAlreadyIssued,
  653. 20003 => Self::MintingDisabled,
  654. 20005 => Self::QuotePending,
  655. 20006 => Self::InvoiceAlreadyPaid,
  656. 20007 => Self::QuoteExpired,
  657. 20008 => Self::WitnessMissingOrInvalid,
  658. 30001 => Self::ClearAuthRequired,
  659. 30002 => Self::ClearAuthFailed,
  660. 31001 => Self::BlindAuthRequired,
  661. 31002 => Self::BlindAuthFailed,
  662. _ => Self::Unknown(code),
  663. }
  664. }
  665. /// Error code to u16
  666. pub fn to_code(&self) -> u16 {
  667. match self {
  668. Self::BlindedMessageAlreadySigned => 10002,
  669. Self::TokenNotVerified => 10003,
  670. Self::TokenAlreadySpent => 11001,
  671. Self::TransactionUnbalanced => 11002,
  672. Self::UnsupportedUnit => 11005,
  673. Self::AmountOutofLimitRange => 11006,
  674. Self::DuplicateInputs => 11007,
  675. Self::DuplicateOutputs => 11008,
  676. Self::MultipleUnits => 11009,
  677. Self::UnitMismatch => 11010,
  678. Self::TokenPending => 11012,
  679. Self::KeysetNotFound => 12001,
  680. Self::KeysetInactive => 12002,
  681. Self::LightningError => 20000,
  682. Self::QuoteNotPaid => 20001,
  683. Self::TokensAlreadyIssued => 20002,
  684. Self::MintingDisabled => 20003,
  685. Self::QuotePending => 20005,
  686. Self::InvoiceAlreadyPaid => 20006,
  687. Self::QuoteExpired => 20007,
  688. Self::WitnessMissingOrInvalid => 20008,
  689. Self::ClearAuthRequired => 30001,
  690. Self::ClearAuthFailed => 30002,
  691. Self::BlindAuthRequired => 31001,
  692. Self::BlindAuthFailed => 31002,
  693. Self::Unknown(code) => *code,
  694. }
  695. }
  696. }
  697. impl Serialize for ErrorCode {
  698. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  699. where
  700. S: Serializer,
  701. {
  702. serializer.serialize_u16(self.to_code())
  703. }
  704. }
  705. impl<'de> Deserialize<'de> for ErrorCode {
  706. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  707. where
  708. D: Deserializer<'de>,
  709. {
  710. let code = u16::deserialize(deserializer)?;
  711. Ok(ErrorCode::from_code(code))
  712. }
  713. }
  714. impl fmt::Display for ErrorCode {
  715. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  716. write!(f, "{}", self.to_code())
  717. }
  718. }