error.rs 27 KB

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