error.rs 24 KB

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