error.rs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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. /// Invalid response from mint
  307. #[error("Invalid mint response: {0}")]
  308. InvalidMintResponse(String),
  309. /// Subscription error
  310. #[error("Subscription error: {0}")]
  311. SubscriptionError(String),
  312. /// Custom Error
  313. #[error("`{0}`")]
  314. Custom(String),
  315. // External Error conversions
  316. /// Parse invoice error
  317. #[error(transparent)]
  318. Invoice(#[from] lightning_invoice::ParseOrSemanticError),
  319. /// Bip32 error
  320. #[error(transparent)]
  321. Bip32(#[from] bitcoin::bip32::Error),
  322. /// Parse int error
  323. #[error(transparent)]
  324. ParseInt(#[from] std::num::ParseIntError),
  325. /// Parse 9rl Error
  326. #[error(transparent)]
  327. UrlParseError(#[from] url::ParseError),
  328. /// Utf8 parse error
  329. #[error(transparent)]
  330. Utf8ParseError(#[from] std::string::FromUtf8Error),
  331. /// Serde Json error
  332. #[error(transparent)]
  333. SerdeJsonError(#[from] serde_json::Error),
  334. /// Base64 error
  335. #[error(transparent)]
  336. Base64Error(#[from] bitcoin::base64::DecodeError),
  337. /// From hex error
  338. #[error(transparent)]
  339. HexError(#[from] hex::Error),
  340. /// Http transport error
  341. #[error("Http transport error {0:?}: {1}")]
  342. HttpError(Option<u16>, String),
  343. /// Parse invoice error
  344. #[cfg(feature = "mint")]
  345. #[error(transparent)]
  346. Uuid(#[from] uuid::Error),
  347. // Crate error conversions
  348. /// Cashu Url Error
  349. #[error(transparent)]
  350. CashuUrl(#[from] crate::mint_url::Error),
  351. /// Secret error
  352. #[error(transparent)]
  353. Secret(#[from] crate::secret::Error),
  354. /// Amount Error
  355. #[error(transparent)]
  356. AmountError(#[from] crate::amount::Error),
  357. /// DHKE Error
  358. #[error(transparent)]
  359. DHKE(#[from] crate::dhke::Error),
  360. /// NUT00 Error
  361. #[error(transparent)]
  362. NUT00(#[from] crate::nuts::nut00::Error),
  363. /// Nut01 error
  364. #[error(transparent)]
  365. NUT01(#[from] crate::nuts::nut01::Error),
  366. /// NUT02 error
  367. #[error(transparent)]
  368. NUT02(#[from] crate::nuts::nut02::Error),
  369. /// NUT03 error
  370. #[error(transparent)]
  371. NUT03(#[from] crate::nuts::nut03::Error),
  372. /// NUT04 error
  373. #[error(transparent)]
  374. NUT04(#[from] crate::nuts::nut04::Error),
  375. /// NUT05 error
  376. #[error(transparent)]
  377. NUT05(#[from] crate::nuts::nut05::Error),
  378. /// NUT11 Error
  379. #[error(transparent)]
  380. NUT11(#[from] crate::nuts::nut11::Error),
  381. /// NUT12 Error
  382. #[error(transparent)]
  383. NUT12(#[from] crate::nuts::nut12::Error),
  384. /// NUT13 Error
  385. #[error(transparent)]
  386. #[cfg(feature = "wallet")]
  387. NUT13(#[from] crate::nuts::nut13::Error),
  388. /// NUT14 Error
  389. #[error(transparent)]
  390. NUT14(#[from] crate::nuts::nut14::Error),
  391. /// NUT18 Error
  392. #[error(transparent)]
  393. NUT18(#[from] crate::nuts::nut18::Error),
  394. /// NUT20 Error
  395. #[error(transparent)]
  396. NUT20(#[from] crate::nuts::nut20::Error),
  397. /// NUT21 Error
  398. #[error(transparent)]
  399. #[cfg(feature = "auth")]
  400. NUT21(#[from] crate::nuts::nut21::Error),
  401. /// NUT22 Error
  402. #[error(transparent)]
  403. #[cfg(feature = "auth")]
  404. NUT22(#[from] crate::nuts::nut22::Error),
  405. /// NUT23 Error
  406. #[error(transparent)]
  407. NUT23(#[from] crate::nuts::nut23::Error),
  408. /// Quote ID Error
  409. #[error(transparent)]
  410. #[cfg(feature = "mint")]
  411. QuoteId(#[from] crate::quote_id::QuoteIdError),
  412. /// From slice error
  413. #[error(transparent)]
  414. TryFromSliceError(#[from] TryFromSliceError),
  415. /// Database Error
  416. #[error(transparent)]
  417. Database(crate::database::Error),
  418. /// Payment Error
  419. #[error(transparent)]
  420. #[cfg(feature = "mint")]
  421. Payment(#[from] crate::payment::Error),
  422. }
  423. /// CDK Error Response
  424. ///
  425. /// See NUT definition in [00](https://github.com/cashubtc/nuts/blob/main/00.md)
  426. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  427. #[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
  428. pub struct ErrorResponse {
  429. /// Error Code
  430. pub code: ErrorCode,
  431. /// Human readable description
  432. #[serde(default)]
  433. pub detail: String,
  434. }
  435. impl fmt::Display for ErrorResponse {
  436. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  437. write!(f, "code: {}, detail: {}", self.code, self.detail)
  438. }
  439. }
  440. impl ErrorResponse {
  441. /// Create new [`ErrorResponse`]
  442. pub fn new(code: ErrorCode, detail: String) -> Self {
  443. Self { code, detail }
  444. }
  445. /// Error response from json
  446. pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
  447. let value: Value = serde_json::from_str(json)?;
  448. Self::from_value(value)
  449. }
  450. /// Error response from json Value
  451. pub fn from_value(value: Value) -> Result<Self, serde_json::Error> {
  452. match serde_json::from_value::<ErrorResponse>(value.clone()) {
  453. Ok(res) => Ok(res),
  454. Err(_) => Ok(Self {
  455. code: ErrorCode::Unknown(999),
  456. detail: value.to_string(),
  457. }),
  458. }
  459. }
  460. }
  461. /// Maps NUT11 errors to appropriate error codes
  462. /// All NUT11 errors are witness/signature related, so they map to WitnessMissingOrInvalid (20008)
  463. fn map_nut11_error(_nut11_error: &crate::nuts::nut11::Error) -> ErrorCode {
  464. // All NUT11 errors relate to P2PK/witness validation, which maps to 20008
  465. ErrorCode::WitnessMissingOrInvalid
  466. }
  467. impl From<Error> for ErrorResponse {
  468. fn from(err: Error) -> ErrorResponse {
  469. match err {
  470. Error::TokenAlreadySpent => ErrorResponse {
  471. code: ErrorCode::TokenAlreadySpent,
  472. detail: err.to_string(),
  473. },
  474. Error::UnsupportedUnit => ErrorResponse {
  475. code: ErrorCode::UnsupportedUnit,
  476. detail: err.to_string(),
  477. },
  478. Error::PaymentFailed => ErrorResponse {
  479. code: ErrorCode::LightningError,
  480. detail: err.to_string(),
  481. },
  482. Error::RequestAlreadyPaid => ErrorResponse {
  483. code: ErrorCode::InvoiceAlreadyPaid,
  484. detail: "Invoice already paid.".to_string(),
  485. },
  486. Error::TransactionUnbalanced(inputs_total, outputs_total, fee_expected) => {
  487. ErrorResponse {
  488. code: ErrorCode::TransactionUnbalanced,
  489. detail: format!(
  490. "Inputs: {inputs_total}, Outputs: {outputs_total}, expected_fee: {fee_expected}. Transaction inputs should equal outputs less fee"
  491. ),
  492. }
  493. }
  494. Error::MintingDisabled => ErrorResponse {
  495. code: ErrorCode::MintingDisabled,
  496. detail: err.to_string(),
  497. },
  498. Error::BlindedMessageAlreadySigned => ErrorResponse {
  499. code: ErrorCode::BlindedMessageAlreadySigned,
  500. detail: err.to_string(),
  501. },
  502. Error::InsufficientFunds => ErrorResponse {
  503. code: ErrorCode::TransactionUnbalanced,
  504. detail: err.to_string(),
  505. },
  506. Error::AmountOutofLimitRange(_min, _max, _amount) => ErrorResponse {
  507. code: ErrorCode::AmountOutofLimitRange,
  508. detail: err.to_string(),
  509. },
  510. Error::ExpiredQuote(_, _) => ErrorResponse {
  511. code: ErrorCode::QuoteExpired,
  512. detail: err.to_string(),
  513. },
  514. Error::PendingQuote => ErrorResponse {
  515. code: ErrorCode::QuotePending,
  516. detail: err.to_string(),
  517. },
  518. Error::TokenPending => ErrorResponse {
  519. code: ErrorCode::TokenPending,
  520. detail: err.to_string(),
  521. },
  522. Error::ClearAuthRequired => ErrorResponse {
  523. code: ErrorCode::ClearAuthRequired,
  524. detail: Error::ClearAuthRequired.to_string(),
  525. },
  526. Error::ClearAuthFailed => ErrorResponse {
  527. code: ErrorCode::ClearAuthFailed,
  528. detail: Error::ClearAuthFailed.to_string(),
  529. },
  530. Error::BlindAuthRequired => ErrorResponse {
  531. code: ErrorCode::BlindAuthRequired,
  532. detail: Error::BlindAuthRequired.to_string(),
  533. },
  534. Error::BlindAuthFailed => ErrorResponse {
  535. code: ErrorCode::BlindAuthFailed,
  536. detail: Error::BlindAuthFailed.to_string(),
  537. },
  538. Error::NUT20(err) => ErrorResponse {
  539. code: ErrorCode::WitnessMissingOrInvalid,
  540. detail: err.to_string(),
  541. },
  542. Error::DuplicateInputs => ErrorResponse {
  543. code: ErrorCode::DuplicateInputs,
  544. detail: err.to_string(),
  545. },
  546. Error::DuplicateOutputs => ErrorResponse {
  547. code: ErrorCode::DuplicateOutputs,
  548. detail: err.to_string(),
  549. },
  550. Error::MultipleUnits => ErrorResponse {
  551. code: ErrorCode::MultipleUnits,
  552. detail: err.to_string(),
  553. },
  554. Error::UnitMismatch => ErrorResponse {
  555. code: ErrorCode::UnitMismatch,
  556. detail: err.to_string(),
  557. },
  558. Error::UnpaidQuote => ErrorResponse {
  559. code: ErrorCode::QuoteNotPaid,
  560. detail: Error::UnpaidQuote.to_string(),
  561. },
  562. Error::NUT11(err) => {
  563. let code = map_nut11_error(&err);
  564. let extra = if matches!(err, crate::nuts::nut11::Error::SignaturesNotProvided) {
  565. Some("P2PK signatures are required but not provided".to_string())
  566. } else {
  567. None
  568. };
  569. ErrorResponse {
  570. code,
  571. detail: match extra {
  572. Some(extra) => format!("{err}. {extra}"),
  573. None => err.to_string(),
  574. },
  575. }
  576. },
  577. Error::DuplicateSignatureError => ErrorResponse {
  578. code: ErrorCode::WitnessMissingOrInvalid,
  579. detail: err.to_string(),
  580. },
  581. Error::IssuedQuote => ErrorResponse {
  582. code: ErrorCode::TokensAlreadyIssued,
  583. detail: err.to_string(),
  584. },
  585. Error::UnknownKeySet => ErrorResponse {
  586. code: ErrorCode::KeysetNotFound,
  587. detail: err.to_string(),
  588. },
  589. Error::InactiveKeyset => ErrorResponse {
  590. code: ErrorCode::KeysetInactive,
  591. detail: err.to_string(),
  592. },
  593. Error::AmountLessNotAllowed => ErrorResponse {
  594. code: ErrorCode::AmountlessInvoiceNotSupported,
  595. detail: err.to_string(),
  596. },
  597. Error::IncorrectQuoteAmount => ErrorResponse {
  598. code: ErrorCode::IncorrectQuoteAmount,
  599. detail: err.to_string(),
  600. },
  601. Error::PubkeyRequired => ErrorResponse {
  602. code: ErrorCode::PubkeyRequired,
  603. detail: err.to_string(),
  604. },
  605. Error::PaidQuote => ErrorResponse {
  606. code: ErrorCode::InvoiceAlreadyPaid,
  607. detail: err.to_string(),
  608. },
  609. Error::DuplicatePaymentId => ErrorResponse {
  610. code: ErrorCode::InvoiceAlreadyPaid,
  611. detail: err.to_string(),
  612. },
  613. // Database duplicate error indicates another quote with same invoice is already pending/paid
  614. Error::Database(crate::database::Error::Duplicate) => ErrorResponse {
  615. code: ErrorCode::InvoiceAlreadyPaid,
  616. detail: "Invoice already paid or pending".to_string(),
  617. },
  618. // DHKE errors - TokenNotVerified for actual verification failures
  619. Error::DHKE(crate::dhke::Error::TokenNotVerified) => ErrorResponse {
  620. code: ErrorCode::TokenNotVerified,
  621. detail: err.to_string(),
  622. },
  623. Error::DHKE(_) => ErrorResponse {
  624. code: ErrorCode::Unknown(50000),
  625. detail: err.to_string(),
  626. },
  627. // Verification errors
  628. Error::CouldNotVerifyDleq => ErrorResponse {
  629. code: ErrorCode::TokenNotVerified,
  630. detail: err.to_string(),
  631. },
  632. Error::SignatureMissingOrInvalid => ErrorResponse {
  633. code: ErrorCode::WitnessMissingOrInvalid,
  634. detail: err.to_string(),
  635. },
  636. Error::SigAllUsedInMelt => ErrorResponse {
  637. code: ErrorCode::WitnessMissingOrInvalid,
  638. detail: err.to_string(),
  639. },
  640. // Keyset/key errors
  641. Error::AmountKey => ErrorResponse {
  642. code: ErrorCode::KeysetNotFound,
  643. detail: err.to_string(),
  644. },
  645. Error::KeysetUnknown(_) => ErrorResponse {
  646. code: ErrorCode::KeysetNotFound,
  647. detail: err.to_string(),
  648. },
  649. Error::NoActiveKeyset => ErrorResponse {
  650. code: ErrorCode::KeysetInactive,
  651. detail: err.to_string(),
  652. },
  653. // Quote/payment errors
  654. Error::UnknownQuote => ErrorResponse {
  655. code: ErrorCode::Unknown(50000),
  656. detail: err.to_string(),
  657. },
  658. Error::MeltingDisabled => ErrorResponse {
  659. code: ErrorCode::MintingDisabled,
  660. detail: err.to_string(),
  661. },
  662. Error::PaymentPending => ErrorResponse {
  663. code: ErrorCode::QuotePending,
  664. detail: err.to_string(),
  665. },
  666. Error::UnknownPaymentState => ErrorResponse {
  667. code: ErrorCode::Unknown(50000),
  668. detail: err.to_string(),
  669. },
  670. // Transaction/amount errors
  671. Error::SplitValuesGreater => ErrorResponse {
  672. code: ErrorCode::TransactionUnbalanced,
  673. detail: err.to_string(),
  674. },
  675. Error::AmountOverflow => ErrorResponse {
  676. code: ErrorCode::TransactionUnbalanced,
  677. detail: err.to_string(),
  678. },
  679. Error::OverIssue => ErrorResponse {
  680. code: ErrorCode::TransactionUnbalanced,
  681. detail: err.to_string(),
  682. },
  683. // Invoice parsing errors - no spec code for invalid format
  684. Error::InvalidPaymentRequest => ErrorResponse {
  685. code: ErrorCode::Unknown(50000),
  686. detail: err.to_string(),
  687. },
  688. Error::InvoiceAmountUndefined => ErrorResponse {
  689. code: ErrorCode::AmountlessInvoiceNotSupported,
  690. detail: err.to_string(),
  691. },
  692. // Internal/system errors - use Unknown(99999)
  693. Error::Internal => ErrorResponse {
  694. code: ErrorCode::Unknown(50000),
  695. detail: err.to_string(),
  696. },
  697. Error::Database(_) => ErrorResponse {
  698. code: ErrorCode::Unknown(50000),
  699. detail: err.to_string(),
  700. },
  701. // Fallback for any remaining errors - use Unknown(99999) instead of TokenNotVerified
  702. _ => ErrorResponse {
  703. code: ErrorCode::Unknown(50000),
  704. detail: err.to_string(),
  705. },
  706. }
  707. }
  708. }
  709. #[cfg(feature = "mint")]
  710. impl From<crate::database::Error> for Error {
  711. fn from(db_error: crate::database::Error) -> Self {
  712. match db_error {
  713. crate::database::Error::InvalidStateTransition(state) => match state {
  714. crate::state::Error::Pending => Self::TokenPending,
  715. crate::state::Error::AlreadySpent => Self::TokenAlreadySpent,
  716. crate::state::Error::AlreadyPaid => Self::RequestAlreadyPaid,
  717. state => Self::Database(crate::database::Error::InvalidStateTransition(state)),
  718. },
  719. db_error => Self::Database(db_error),
  720. }
  721. }
  722. }
  723. #[cfg(not(feature = "mint"))]
  724. impl From<crate::database::Error> for Error {
  725. fn from(db_error: crate::database::Error) -> Self {
  726. Self::Database(db_error)
  727. }
  728. }
  729. impl From<ErrorResponse> for Error {
  730. fn from(err: ErrorResponse) -> Error {
  731. match err.code {
  732. // 10xxx - Proof/Token verification errors
  733. ErrorCode::TokenNotVerified => Self::DHKE(crate::dhke::Error::TokenNotVerified),
  734. // 11xxx - Input/Output errors
  735. ErrorCode::TokenAlreadySpent => Self::TokenAlreadySpent,
  736. ErrorCode::TokenPending => Self::TokenPending,
  737. ErrorCode::BlindedMessageAlreadySigned => Self::BlindedMessageAlreadySigned,
  738. ErrorCode::OutputsPending => Self::TokenPending, // Map to closest equivalent
  739. ErrorCode::TransactionUnbalanced => Self::TransactionUnbalanced(0, 0, 0),
  740. ErrorCode::AmountOutofLimitRange => {
  741. Self::AmountOutofLimitRange(Amount::default(), Amount::default(), Amount::default())
  742. }
  743. ErrorCode::DuplicateInputs => Self::DuplicateInputs,
  744. ErrorCode::DuplicateOutputs => Self::DuplicateOutputs,
  745. ErrorCode::MultipleUnits => Self::MultipleUnits,
  746. ErrorCode::UnitMismatch => Self::UnitMismatch,
  747. ErrorCode::AmountlessInvoiceNotSupported => Self::AmountLessNotAllowed,
  748. ErrorCode::IncorrectQuoteAmount => Self::IncorrectQuoteAmount,
  749. ErrorCode::UnsupportedUnit => Self::UnsupportedUnit,
  750. // 12xxx - Keyset errors
  751. ErrorCode::KeysetNotFound => Self::UnknownKeySet,
  752. ErrorCode::KeysetInactive => Self::InactiveKeyset,
  753. // 20xxx - Quote/Payment errors
  754. ErrorCode::QuoteNotPaid => Self::UnpaidQuote,
  755. ErrorCode::TokensAlreadyIssued => Self::IssuedQuote,
  756. ErrorCode::MintingDisabled => Self::MintingDisabled,
  757. ErrorCode::LightningError => Self::PaymentFailed,
  758. ErrorCode::QuotePending => Self::PendingQuote,
  759. ErrorCode::InvoiceAlreadyPaid => Self::RequestAlreadyPaid,
  760. ErrorCode::QuoteExpired => Self::ExpiredQuote(0, 0),
  761. ErrorCode::WitnessMissingOrInvalid => Self::SignatureMissingOrInvalid,
  762. ErrorCode::PubkeyRequired => Self::PubkeyRequired,
  763. // 30xxx - Clear auth errors
  764. ErrorCode::ClearAuthRequired => Self::ClearAuthRequired,
  765. ErrorCode::ClearAuthFailed => Self::ClearAuthFailed,
  766. // 31xxx - Blind auth errors
  767. ErrorCode::BlindAuthRequired => Self::BlindAuthRequired,
  768. ErrorCode::BlindAuthFailed => Self::BlindAuthFailed,
  769. ErrorCode::BatMintMaxExceeded => Self::InsufficientBlindAuthTokens,
  770. ErrorCode::BatRateLimitExceeded => Self::InsufficientBlindAuthTokens,
  771. _ => Self::UnknownErrorResponse(err.to_string()),
  772. }
  773. }
  774. }
  775. /// Possible Error Codes
  776. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
  777. #[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
  778. pub enum ErrorCode {
  779. // 10xxx - Proof/Token verification errors
  780. /// Proof verification failed (10001)
  781. TokenNotVerified,
  782. // 11xxx - Input/Output errors
  783. /// Proofs already spent (11001)
  784. TokenAlreadySpent,
  785. /// Proofs are pending (11002)
  786. TokenPending,
  787. /// Outputs already signed (11003)
  788. BlindedMessageAlreadySigned,
  789. /// Outputs are pending (11004)
  790. OutputsPending,
  791. /// Transaction is not balanced (11005)
  792. TransactionUnbalanced,
  793. /// Amount outside of limit range (11006)
  794. AmountOutofLimitRange,
  795. /// Duplicate inputs provided (11007)
  796. DuplicateInputs,
  797. /// Duplicate outputs provided (11008)
  798. DuplicateOutputs,
  799. /// Inputs/Outputs of multiple units (11009)
  800. MultipleUnits,
  801. /// Inputs and outputs not of same unit (11010)
  802. UnitMismatch,
  803. /// Amountless invoice is not supported (11011)
  804. AmountlessInvoiceNotSupported,
  805. /// Amount in request does not equal invoice (11012)
  806. IncorrectQuoteAmount,
  807. /// Unit in request is not supported (11013)
  808. UnsupportedUnit,
  809. // 12xxx - Keyset errors
  810. /// Keyset is not known (12001)
  811. KeysetNotFound,
  812. /// Keyset is inactive, cannot sign messages (12002)
  813. KeysetInactive,
  814. // 20xxx - Quote/Payment errors
  815. /// Quote request is not paid (20001)
  816. QuoteNotPaid,
  817. /// Quote has already been issued (20002)
  818. TokensAlreadyIssued,
  819. /// Minting is disabled (20003)
  820. MintingDisabled,
  821. /// Lightning payment failed (20004)
  822. LightningError,
  823. /// Quote is pending (20005)
  824. QuotePending,
  825. /// Invoice already paid (20006)
  826. InvoiceAlreadyPaid,
  827. /// Quote is expired (20007)
  828. QuoteExpired,
  829. /// Signature for mint request invalid (20008)
  830. WitnessMissingOrInvalid,
  831. /// Pubkey required for mint quote (20009)
  832. PubkeyRequired,
  833. // 30xxx - Clear auth errors
  834. /// Endpoint requires clear auth (30001)
  835. ClearAuthRequired,
  836. /// Clear authentication failed (30002)
  837. ClearAuthFailed,
  838. // 31xxx - Blind auth errors
  839. /// Endpoint requires blind auth (31001)
  840. BlindAuthRequired,
  841. /// Blind authentication failed (31002)
  842. BlindAuthFailed,
  843. /// Maximum BAT mint amount exceeded (31003)
  844. BatMintMaxExceeded,
  845. /// BAT mint rate limit exceeded (31004)
  846. BatRateLimitExceeded,
  847. /// Unknown error code
  848. Unknown(u16),
  849. }
  850. impl ErrorCode {
  851. /// Error code from u16
  852. pub fn from_code(code: u16) -> Self {
  853. match code {
  854. // 10xxx - Proof/Token verification errors
  855. 10001 => Self::TokenNotVerified,
  856. // 11xxx - Input/Output errors
  857. 11001 => Self::TokenAlreadySpent,
  858. 11002 => Self::TokenPending,
  859. 11003 => Self::BlindedMessageAlreadySigned,
  860. 11004 => Self::OutputsPending,
  861. 11005 => Self::TransactionUnbalanced,
  862. 11006 => Self::AmountOutofLimitRange,
  863. 11007 => Self::DuplicateInputs,
  864. 11008 => Self::DuplicateOutputs,
  865. 11009 => Self::MultipleUnits,
  866. 11010 => Self::UnitMismatch,
  867. 11011 => Self::AmountlessInvoiceNotSupported,
  868. 11012 => Self::IncorrectQuoteAmount,
  869. 11013 => Self::UnsupportedUnit,
  870. // 12xxx - Keyset errors
  871. 12001 => Self::KeysetNotFound,
  872. 12002 => Self::KeysetInactive,
  873. // 20xxx - Quote/Payment errors
  874. 20001 => Self::QuoteNotPaid,
  875. 20002 => Self::TokensAlreadyIssued,
  876. 20003 => Self::MintingDisabled,
  877. 20004 => Self::LightningError,
  878. 20005 => Self::QuotePending,
  879. 20006 => Self::InvoiceAlreadyPaid,
  880. 20007 => Self::QuoteExpired,
  881. 20008 => Self::WitnessMissingOrInvalid,
  882. 20009 => Self::PubkeyRequired,
  883. // 30xxx - Clear auth errors
  884. 30001 => Self::ClearAuthRequired,
  885. 30002 => Self::ClearAuthFailed,
  886. // 31xxx - Blind auth errors
  887. 31001 => Self::BlindAuthRequired,
  888. 31002 => Self::BlindAuthFailed,
  889. 31003 => Self::BatMintMaxExceeded,
  890. 31004 => Self::BatRateLimitExceeded,
  891. _ => Self::Unknown(code),
  892. }
  893. }
  894. /// Error code to u16
  895. pub fn to_code(&self) -> u16 {
  896. match self {
  897. // 10xxx - Proof/Token verification errors
  898. Self::TokenNotVerified => 10001,
  899. // 11xxx - Input/Output errors
  900. Self::TokenAlreadySpent => 11001,
  901. Self::TokenPending => 11002,
  902. Self::BlindedMessageAlreadySigned => 11003,
  903. Self::OutputsPending => 11004,
  904. Self::TransactionUnbalanced => 11005,
  905. Self::AmountOutofLimitRange => 11006,
  906. Self::DuplicateInputs => 11007,
  907. Self::DuplicateOutputs => 11008,
  908. Self::MultipleUnits => 11009,
  909. Self::UnitMismatch => 11010,
  910. Self::AmountlessInvoiceNotSupported => 11011,
  911. Self::IncorrectQuoteAmount => 11012,
  912. Self::UnsupportedUnit => 11013,
  913. // 12xxx - Keyset errors
  914. Self::KeysetNotFound => 12001,
  915. Self::KeysetInactive => 12002,
  916. // 20xxx - Quote/Payment errors
  917. Self::QuoteNotPaid => 20001,
  918. Self::TokensAlreadyIssued => 20002,
  919. Self::MintingDisabled => 20003,
  920. Self::LightningError => 20004,
  921. Self::QuotePending => 20005,
  922. Self::InvoiceAlreadyPaid => 20006,
  923. Self::QuoteExpired => 20007,
  924. Self::WitnessMissingOrInvalid => 20008,
  925. Self::PubkeyRequired => 20009,
  926. // 30xxx - Clear auth errors
  927. Self::ClearAuthRequired => 30001,
  928. Self::ClearAuthFailed => 30002,
  929. // 31xxx - Blind auth errors
  930. Self::BlindAuthRequired => 31001,
  931. Self::BlindAuthFailed => 31002,
  932. Self::BatMintMaxExceeded => 31003,
  933. Self::BatRateLimitExceeded => 31004,
  934. Self::Unknown(code) => *code,
  935. }
  936. }
  937. }
  938. impl Serialize for ErrorCode {
  939. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  940. where
  941. S: Serializer,
  942. {
  943. serializer.serialize_u16(self.to_code())
  944. }
  945. }
  946. impl<'de> Deserialize<'de> for ErrorCode {
  947. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  948. where
  949. D: Deserializer<'de>,
  950. {
  951. let code = u16::deserialize(deserializer)?;
  952. Ok(ErrorCode::from_code(code))
  953. }
  954. }
  955. impl fmt::Display for ErrorCode {
  956. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  957. write!(f, "{}", self.to_code())
  958. }
  959. }