error.rs 25 KB

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