error.rs 27 KB

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