error.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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. /// BIP353 address parsing error
  110. #[error("Failed to parse BIP353 address: {0}")]
  111. Bip353Parse(String),
  112. /// Operation timeout
  113. #[error("Operation timeout")]
  114. Timeout,
  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. /// Quote ID Error
  355. #[error(transparent)]
  356. #[cfg(feature = "mint")]
  357. QuoteId(#[from] crate::quote_id::QuoteIdError),
  358. /// From slice error
  359. #[error(transparent)]
  360. TryFromSliceError(#[from] TryFromSliceError),
  361. /// Database Error
  362. #[error(transparent)]
  363. Database(crate::database::Error),
  364. /// Payment Error
  365. #[error(transparent)]
  366. #[cfg(feature = "mint")]
  367. Payment(#[from] crate::payment::Error),
  368. }
  369. /// CDK Error Response
  370. ///
  371. /// See NUT definition in [00](https://github.com/cashubtc/nuts/blob/main/00.md)
  372. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  373. #[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
  374. pub struct ErrorResponse {
  375. /// Error Code
  376. pub code: ErrorCode,
  377. /// Human readable Text
  378. pub error: Option<String>,
  379. /// Longer human readable description
  380. pub detail: Option<String>,
  381. }
  382. impl fmt::Display for ErrorResponse {
  383. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  384. write!(
  385. f,
  386. "code: {}, error: {}, detail: {}",
  387. self.code,
  388. self.error.clone().unwrap_or_default(),
  389. self.detail.clone().unwrap_or_default()
  390. )
  391. }
  392. }
  393. impl ErrorResponse {
  394. /// Create new [`ErrorResponse`]
  395. pub fn new(code: ErrorCode, error: Option<String>, detail: Option<String>) -> Self {
  396. Self {
  397. code,
  398. error,
  399. detail,
  400. }
  401. }
  402. /// Error response from json
  403. pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
  404. let value: Value = serde_json::from_str(json)?;
  405. Self::from_value(value)
  406. }
  407. /// Error response from json Value
  408. pub fn from_value(value: Value) -> Result<Self, serde_json::Error> {
  409. match serde_json::from_value::<ErrorResponse>(value.clone()) {
  410. Ok(res) => Ok(res),
  411. Err(_) => Ok(Self {
  412. code: ErrorCode::Unknown(999),
  413. error: Some(value.to_string()),
  414. detail: None,
  415. }),
  416. }
  417. }
  418. }
  419. impl From<Error> for ErrorResponse {
  420. fn from(err: Error) -> ErrorResponse {
  421. match err {
  422. Error::TokenAlreadySpent => ErrorResponse {
  423. code: ErrorCode::TokenAlreadySpent,
  424. error: Some(err.to_string()),
  425. detail: None,
  426. },
  427. Error::UnsupportedUnit => ErrorResponse {
  428. code: ErrorCode::UnsupportedUnit,
  429. error: Some(err.to_string()),
  430. detail: None,
  431. },
  432. Error::PaymentFailed => ErrorResponse {
  433. code: ErrorCode::LightningError,
  434. error: Some(err.to_string()),
  435. detail: None,
  436. },
  437. Error::RequestAlreadyPaid => ErrorResponse {
  438. code: ErrorCode::InvoiceAlreadyPaid,
  439. error: Some("Invoice already paid.".to_string()),
  440. detail: None,
  441. },
  442. Error::TransactionUnbalanced(inputs_total, outputs_total, fee_expected) => {
  443. ErrorResponse {
  444. code: ErrorCode::TransactionUnbalanced,
  445. error: Some(format!(
  446. "Inputs: {inputs_total}, Outputs: {outputs_total}, expected_fee: {fee_expected}",
  447. )),
  448. detail: Some("Transaction inputs should equal outputs less fee".to_string()),
  449. }
  450. }
  451. Error::MintingDisabled => ErrorResponse {
  452. code: ErrorCode::MintingDisabled,
  453. error: Some(err.to_string()),
  454. detail: None,
  455. },
  456. Error::BlindedMessageAlreadySigned => ErrorResponse {
  457. code: ErrorCode::BlindedMessageAlreadySigned,
  458. error: Some(err.to_string()),
  459. detail: None,
  460. },
  461. Error::InsufficientFunds => ErrorResponse {
  462. code: ErrorCode::TransactionUnbalanced,
  463. error: Some(err.to_string()),
  464. detail: None,
  465. },
  466. Error::AmountOutofLimitRange(_min, _max, _amount) => ErrorResponse {
  467. code: ErrorCode::AmountOutofLimitRange,
  468. error: Some(err.to_string()),
  469. detail: None,
  470. },
  471. Error::ExpiredQuote(_, _) => ErrorResponse {
  472. code: ErrorCode::QuoteExpired,
  473. error: Some(err.to_string()),
  474. detail: None,
  475. },
  476. Error::PendingQuote => ErrorResponse {
  477. code: ErrorCode::QuotePending,
  478. error: Some(err.to_string()),
  479. detail: None,
  480. },
  481. Error::TokenPending => ErrorResponse {
  482. code: ErrorCode::TokenPending,
  483. error: Some(err.to_string()),
  484. detail: None,
  485. },
  486. Error::ClearAuthRequired => ErrorResponse {
  487. code: ErrorCode::ClearAuthRequired,
  488. error: None,
  489. detail: None,
  490. },
  491. Error::ClearAuthFailed => ErrorResponse {
  492. code: ErrorCode::ClearAuthFailed,
  493. error: None,
  494. detail: None,
  495. },
  496. Error::BlindAuthRequired => ErrorResponse {
  497. code: ErrorCode::BlindAuthRequired,
  498. error: None,
  499. detail: None,
  500. },
  501. Error::BlindAuthFailed => ErrorResponse {
  502. code: ErrorCode::BlindAuthFailed,
  503. error: None,
  504. detail: None,
  505. },
  506. Error::NUT20(err) => ErrorResponse {
  507. code: ErrorCode::WitnessMissingOrInvalid,
  508. error: Some(err.to_string()),
  509. detail: None,
  510. },
  511. Error::DuplicateInputs => ErrorResponse {
  512. code: ErrorCode::DuplicateInputs,
  513. error: Some(err.to_string()),
  514. detail: None,
  515. },
  516. Error::DuplicateOutputs => ErrorResponse {
  517. code: ErrorCode::DuplicateOutputs,
  518. error: Some(err.to_string()),
  519. detail: None,
  520. },
  521. Error::MultipleUnits => ErrorResponse {
  522. code: ErrorCode::MultipleUnits,
  523. error: Some(err.to_string()),
  524. detail: None,
  525. },
  526. Error::UnitMismatch => ErrorResponse {
  527. code: ErrorCode::UnitMismatch,
  528. error: Some(err.to_string()),
  529. detail: None,
  530. },
  531. Error::UnpaidQuote => ErrorResponse {
  532. code: ErrorCode::QuoteNotPaid,
  533. error: Some(err.to_string()),
  534. detail: None
  535. },
  536. _ => ErrorResponse {
  537. code: ErrorCode::Unknown(9999),
  538. error: Some(err.to_string()),
  539. detail: None,
  540. },
  541. }
  542. }
  543. }
  544. #[cfg(feature = "mint")]
  545. impl From<crate::database::Error> for Error {
  546. fn from(db_error: crate::database::Error) -> Self {
  547. match db_error {
  548. crate::database::Error::InvalidStateTransition(state) => match state {
  549. crate::state::Error::Pending => Self::TokenPending,
  550. crate::state::Error::AlreadySpent => Self::TokenAlreadySpent,
  551. state => Self::Database(crate::database::Error::InvalidStateTransition(state)),
  552. },
  553. db_error => Self::Database(db_error),
  554. }
  555. }
  556. }
  557. #[cfg(not(feature = "mint"))]
  558. impl From<crate::database::Error> for Error {
  559. fn from(db_error: crate::database::Error) -> Self {
  560. Self::Database(db_error)
  561. }
  562. }
  563. impl From<ErrorResponse> for Error {
  564. fn from(err: ErrorResponse) -> Error {
  565. match err.code {
  566. ErrorCode::TokenAlreadySpent => Self::TokenAlreadySpent,
  567. ErrorCode::QuoteNotPaid => Self::UnpaidQuote,
  568. ErrorCode::QuotePending => Self::PendingQuote,
  569. ErrorCode::QuoteExpired => Self::ExpiredQuote(0, 0),
  570. ErrorCode::KeysetNotFound => Self::UnknownKeySet,
  571. ErrorCode::KeysetInactive => Self::InactiveKeyset,
  572. ErrorCode::BlindedMessageAlreadySigned => Self::BlindedMessageAlreadySigned,
  573. ErrorCode::UnsupportedUnit => Self::UnsupportedUnit,
  574. ErrorCode::TransactionUnbalanced => Self::TransactionUnbalanced(0, 0, 0),
  575. ErrorCode::MintingDisabled => Self::MintingDisabled,
  576. ErrorCode::InvoiceAlreadyPaid => Self::RequestAlreadyPaid,
  577. ErrorCode::TokenNotVerified => Self::DHKE(crate::dhke::Error::TokenNotVerified),
  578. ErrorCode::LightningError => Self::PaymentFailed,
  579. ErrorCode::AmountOutofLimitRange => {
  580. Self::AmountOutofLimitRange(Amount::default(), Amount::default(), Amount::default())
  581. }
  582. ErrorCode::TokenPending => Self::TokenPending,
  583. ErrorCode::WitnessMissingOrInvalid => Self::SignatureMissingOrInvalid,
  584. ErrorCode::DuplicateInputs => Self::DuplicateInputs,
  585. ErrorCode::DuplicateOutputs => Self::DuplicateOutputs,
  586. ErrorCode::MultipleUnits => Self::MultipleUnits,
  587. ErrorCode::UnitMismatch => Self::UnitMismatch,
  588. ErrorCode::ClearAuthRequired => Self::ClearAuthRequired,
  589. ErrorCode::BlindAuthRequired => Self::BlindAuthRequired,
  590. _ => Self::UnknownErrorResponse(err.to_string()),
  591. }
  592. }
  593. }
  594. /// Possible Error Codes
  595. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
  596. #[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
  597. pub enum ErrorCode {
  598. /// Token is already spent
  599. TokenAlreadySpent,
  600. /// Token Pending
  601. TokenPending,
  602. /// Quote is not paid
  603. QuoteNotPaid,
  604. /// Quote is not expired
  605. QuoteExpired,
  606. /// Quote Pending
  607. QuotePending,
  608. /// Keyset is not found
  609. KeysetNotFound,
  610. /// Keyset inactive
  611. KeysetInactive,
  612. /// Blinded Message Already signed
  613. BlindedMessageAlreadySigned,
  614. /// Unsupported unit
  615. UnsupportedUnit,
  616. /// Token already issed for quote
  617. TokensAlreadyIssued,
  618. /// Minting Disabled
  619. MintingDisabled,
  620. /// Invoice Already Paid
  621. InvoiceAlreadyPaid,
  622. /// Token Not Verified
  623. TokenNotVerified,
  624. /// Lightning Error
  625. LightningError,
  626. /// Unbalanced Error
  627. TransactionUnbalanced,
  628. /// Amount outside of allowed range
  629. AmountOutofLimitRange,
  630. /// Witness missing or invalid
  631. WitnessMissingOrInvalid,
  632. /// Duplicate Inputs
  633. DuplicateInputs,
  634. /// Duplicate Outputs
  635. DuplicateOutputs,
  636. /// Multiple Units
  637. MultipleUnits,
  638. /// Input unit does not match output
  639. UnitMismatch,
  640. /// Clear Auth Required
  641. ClearAuthRequired,
  642. /// Clear Auth Failed
  643. ClearAuthFailed,
  644. /// Blind Auth Required
  645. BlindAuthRequired,
  646. /// Blind Auth Failed
  647. BlindAuthFailed,
  648. /// Unknown error code
  649. Unknown(u16),
  650. }
  651. impl ErrorCode {
  652. /// Error code from u16
  653. pub fn from_code(code: u16) -> Self {
  654. match code {
  655. 10002 => Self::BlindedMessageAlreadySigned,
  656. 10003 => Self::TokenNotVerified,
  657. 11001 => Self::TokenAlreadySpent,
  658. 11002 => Self::TransactionUnbalanced,
  659. 11005 => Self::UnsupportedUnit,
  660. 11006 => Self::AmountOutofLimitRange,
  661. 11007 => Self::DuplicateInputs,
  662. 11008 => Self::DuplicateOutputs,
  663. 11009 => Self::MultipleUnits,
  664. 11010 => Self::UnitMismatch,
  665. 11012 => Self::TokenPending,
  666. 12001 => Self::KeysetNotFound,
  667. 12002 => Self::KeysetInactive,
  668. 20000 => Self::LightningError,
  669. 20001 => Self::QuoteNotPaid,
  670. 20002 => Self::TokensAlreadyIssued,
  671. 20003 => Self::MintingDisabled,
  672. 20005 => Self::QuotePending,
  673. 20006 => Self::InvoiceAlreadyPaid,
  674. 20007 => Self::QuoteExpired,
  675. 20008 => Self::WitnessMissingOrInvalid,
  676. 30001 => Self::ClearAuthRequired,
  677. 30002 => Self::ClearAuthFailed,
  678. 31001 => Self::BlindAuthRequired,
  679. 31002 => Self::BlindAuthFailed,
  680. _ => Self::Unknown(code),
  681. }
  682. }
  683. /// Error code to u16
  684. pub fn to_code(&self) -> u16 {
  685. match self {
  686. Self::BlindedMessageAlreadySigned => 10002,
  687. Self::TokenNotVerified => 10003,
  688. Self::TokenAlreadySpent => 11001,
  689. Self::TransactionUnbalanced => 11002,
  690. Self::UnsupportedUnit => 11005,
  691. Self::AmountOutofLimitRange => 11006,
  692. Self::DuplicateInputs => 11007,
  693. Self::DuplicateOutputs => 11008,
  694. Self::MultipleUnits => 11009,
  695. Self::UnitMismatch => 11010,
  696. Self::TokenPending => 11012,
  697. Self::KeysetNotFound => 12001,
  698. Self::KeysetInactive => 12002,
  699. Self::LightningError => 20000,
  700. Self::QuoteNotPaid => 20001,
  701. Self::TokensAlreadyIssued => 20002,
  702. Self::MintingDisabled => 20003,
  703. Self::QuotePending => 20005,
  704. Self::InvoiceAlreadyPaid => 20006,
  705. Self::QuoteExpired => 20007,
  706. Self::WitnessMissingOrInvalid => 20008,
  707. Self::ClearAuthRequired => 30001,
  708. Self::ClearAuthFailed => 30002,
  709. Self::BlindAuthRequired => 31001,
  710. Self::BlindAuthFailed => 31002,
  711. Self::Unknown(code) => *code,
  712. }
  713. }
  714. }
  715. impl Serialize for ErrorCode {
  716. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  717. where
  718. S: Serializer,
  719. {
  720. serializer.serialize_u16(self.to_code())
  721. }
  722. }
  723. impl<'de> Deserialize<'de> for ErrorCode {
  724. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  725. where
  726. D: Deserializer<'de>,
  727. {
  728. let code = u16::deserialize(deserializer)?;
  729. Ok(ErrorCode::from_code(code))
  730. }
  731. }
  732. impl fmt::Display for ErrorCode {
  733. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  734. write!(f, "{}", self.to_code())
  735. }
  736. }