error.rs 27 KB

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