error.rs 27 KB

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