error.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. //! Errors
  2. use std::fmt;
  3. use cashu::{CurrencyUnit, PaymentMethod};
  4. use serde::{Deserialize, Deserializer, Serialize, Serializer};
  5. use serde_json::Value;
  6. use thiserror::Error;
  7. use crate::nuts::Id;
  8. use crate::util::hex;
  9. #[cfg(feature = "wallet")]
  10. use crate::wallet::WalletKey;
  11. use crate::Amount;
  12. /// CDK Error
  13. #[derive(Debug, Error)]
  14. pub enum Error {
  15. /// Mint does not have a key for amount
  16. #[error("No Key for Amount")]
  17. AmountKey,
  18. /// Keyset is not known
  19. #[error("Keyset id not known: `{0}`")]
  20. KeysetUnknown(Id),
  21. /// Unsupported unit
  22. #[error("Unit unsupported")]
  23. UnsupportedUnit,
  24. /// Payment failed
  25. #[error("Payment failed")]
  26. PaymentFailed,
  27. /// Payment pending
  28. #[error("Payment pending")]
  29. PaymentPending,
  30. /// Invoice already paid
  31. #[error("Request already paid")]
  32. RequestAlreadyPaid,
  33. /// Invalid payment request
  34. #[error("Invalid payment request")]
  35. InvalidPaymentRequest,
  36. /// Bolt11 invoice does not have amount
  37. #[error("Invoice Amount undefined")]
  38. InvoiceAmountUndefined,
  39. /// Split Values must be less then or equal to amount
  40. #[error("Split Values must be less then or equal to amount")]
  41. SplitValuesGreater,
  42. /// Amount overflow
  43. #[error("Amount Overflow")]
  44. AmountOverflow,
  45. /// Witness missing or invalid
  46. #[error("Signature missing or invalid")]
  47. SignatureMissingOrInvalid,
  48. /// Amountless Invoice Not supported
  49. #[error("Amount Less Invoice is not allowed")]
  50. AmountLessNotAllowed,
  51. /// Multi-Part Internal Melt Quotes are not supported
  52. #[error("Multi-Part Internal Melt Quotes are not supported")]
  53. InternalMultiPartMeltQuote,
  54. /// Multi-Part Payment not supported for unit and method
  55. #[error("Multi-Part payment is not supported for unit `{0}` and method `{1}`")]
  56. MppUnitMethodNotSupported(CurrencyUnit, PaymentMethod),
  57. // Mint Errors
  58. /// Minting is disabled
  59. #[error("Minting is disabled")]
  60. MintingDisabled,
  61. /// Quote is not known
  62. #[error("Unknown quote")]
  63. UnknownQuote,
  64. /// Quote is expired
  65. #[error("Expired quote: Expired: `{0}`, Time: `{1}`")]
  66. ExpiredQuote(u64, u64),
  67. /// Amount is outside of allowed range
  68. #[error("Amount must be between `{0}` and `{1}` is `{2}`")]
  69. AmountOutofLimitRange(Amount, Amount, Amount),
  70. /// Quote is not paiud
  71. #[error("Quote not paid")]
  72. UnpaidQuote,
  73. /// Quote is pending
  74. #[error("Quote pending")]
  75. PendingQuote,
  76. /// ecash already issued for quote
  77. #[error("Quote already issued")]
  78. IssuedQuote,
  79. /// Quote has already been paid
  80. #[error("Quote is already paid")]
  81. PaidQuote,
  82. /// Payment state is unknown
  83. #[error("Payment state is unknown")]
  84. UnknownPaymentState,
  85. /// Melting is disabled
  86. #[error("Minting is disabled")]
  87. MeltingDisabled,
  88. /// Unknown Keyset
  89. #[error("Unknown Keyset")]
  90. UnknownKeySet,
  91. /// BlindedMessage is already signed
  92. #[error("Blinded Message is already signed")]
  93. BlindedMessageAlreadySigned,
  94. /// Inactive Keyset
  95. #[error("Inactive Keyset")]
  96. InactiveKeyset,
  97. /// Transaction unbalanced
  98. #[error("Inputs: `{0}`, Outputs: `{1}`, Expected Fee: `{2}`")]
  99. TransactionUnbalanced(u64, u64, u64),
  100. /// Duplicate proofs provided
  101. #[error("Duplicate Inputs")]
  102. DuplicateInputs,
  103. /// Duplicate output
  104. #[error("Duplicate outputs")]
  105. DuplicateOutputs,
  106. /// Multiple units provided
  107. #[error("Cannot have multiple units")]
  108. MultipleUnits,
  109. /// Unit mismatch
  110. #[error("Input unit must match output")]
  111. UnitMismatch,
  112. /// Sig all cannot be used in melt
  113. #[error("Sig all cannot be used in melt")]
  114. SigAllUsedInMelt,
  115. /// Token is already spent
  116. #[error("Token Already Spent")]
  117. TokenAlreadySpent,
  118. /// Token is already pending
  119. #[error("Token Pending")]
  120. TokenPending,
  121. /// Internal Error
  122. #[error("Internal Error")]
  123. Internal,
  124. // Wallet Errors
  125. /// P2PK spending conditions not met
  126. #[error("P2PK condition not met `{0}`")]
  127. P2PKConditionsNotMet(String),
  128. /// Spending Locktime not provided
  129. #[error("Spending condition locktime not provided")]
  130. LocktimeNotProvided,
  131. /// Invalid Spending Conditions
  132. #[error("Invalid spending conditions: `{0}`")]
  133. InvalidSpendConditions(String),
  134. /// Incorrect Wallet
  135. #[error("Incorrect wallet: `{0}`")]
  136. IncorrectWallet(String),
  137. /// Unknown Wallet
  138. #[error("Unknown wallet: `{0}`")]
  139. #[cfg(feature = "wallet")]
  140. UnknownWallet(WalletKey),
  141. /// Max Fee Ecxeded
  142. #[error("Max fee exceeded")]
  143. MaxFeeExceeded,
  144. /// Url path segments could not be joined
  145. #[error("Url path segments could not be joined")]
  146. UrlPathSegments,
  147. /// Unknown error response
  148. #[error("Unknown error response: `{0}`")]
  149. UnknownErrorResponse(String),
  150. /// Invalid DLEQ proof
  151. #[error("Could not verify DLEQ proof")]
  152. CouldNotVerifyDleq,
  153. /// Incorrect Mint
  154. /// Token does not match wallet mint
  155. #[error("Token does not match wallet mint")]
  156. IncorrectMint,
  157. /// Receive can only be used with tokens from single mint
  158. #[error("Multiple mint tokens not supported by receive. Please deconstruct the token and use receive with_proof")]
  159. MultiMintTokenNotSupported,
  160. /// Preimage not provided
  161. #[error("Preimage not provided")]
  162. PreimageNotProvided,
  163. /// Insufficient Funds
  164. #[error("Insufficient funds")]
  165. InsufficientFunds,
  166. /// No active keyset
  167. #[error("No active keyset")]
  168. NoActiveKeyset,
  169. /// Incorrect quote amount
  170. #[error("Incorrect quote amount")]
  171. IncorrectQuoteAmount,
  172. /// Invoice Description not supported
  173. #[error("Invoice Description not supported")]
  174. InvoiceDescriptionUnsupported,
  175. /// Custom Error
  176. #[error("`{0}`")]
  177. Custom(String),
  178. // External Error conversions
  179. /// Parse invoice error
  180. #[error(transparent)]
  181. Invoice(#[from] lightning_invoice::ParseOrSemanticError),
  182. /// Bip32 error
  183. #[error(transparent)]
  184. Bip32(#[from] bitcoin::bip32::Error),
  185. /// Parse int error
  186. #[error(transparent)]
  187. ParseInt(#[from] std::num::ParseIntError),
  188. /// Parse 9rl Error
  189. #[error(transparent)]
  190. UrlParseError(#[from] url::ParseError),
  191. /// Utf8 parse error
  192. #[error(transparent)]
  193. Utf8ParseError(#[from] std::string::FromUtf8Error),
  194. /// Serde Json error
  195. #[error(transparent)]
  196. SerdeJsonError(#[from] serde_json::Error),
  197. /// Base64 error
  198. #[error(transparent)]
  199. Base64Error(#[from] bitcoin::base64::DecodeError),
  200. /// From hex error
  201. #[error(transparent)]
  202. HexError(#[from] hex::Error),
  203. /// Http transport error
  204. #[error("Http transport error: {0}")]
  205. HttpError(String),
  206. // Crate error conversions
  207. /// Cashu Url Error
  208. #[error(transparent)]
  209. CashuUrl(#[from] crate::mint_url::Error),
  210. /// Secret error
  211. #[error(transparent)]
  212. Secret(#[from] crate::secret::Error),
  213. /// Amount Error
  214. #[error(transparent)]
  215. AmountError(#[from] crate::amount::Error),
  216. /// DHKE Error
  217. #[error(transparent)]
  218. DHKE(#[from] crate::dhke::Error),
  219. /// NUT00 Error
  220. #[error(transparent)]
  221. NUT00(#[from] crate::nuts::nut00::Error),
  222. /// Nut01 error
  223. #[error(transparent)]
  224. NUT01(#[from] crate::nuts::nut01::Error),
  225. /// NUT02 error
  226. #[error(transparent)]
  227. NUT02(#[from] crate::nuts::nut02::Error),
  228. /// NUT03 error
  229. #[error(transparent)]
  230. NUT03(#[from] crate::nuts::nut03::Error),
  231. /// NUT04 error
  232. #[error(transparent)]
  233. NUT04(#[from] crate::nuts::nut04::Error),
  234. /// NUT05 error
  235. #[error(transparent)]
  236. NUT05(#[from] crate::nuts::nut05::Error),
  237. /// NUT11 Error
  238. #[error(transparent)]
  239. NUT11(#[from] crate::nuts::nut11::Error),
  240. /// NUT12 Error
  241. #[error(transparent)]
  242. NUT12(#[from] crate::nuts::nut12::Error),
  243. /// NUT13 Error
  244. #[error(transparent)]
  245. #[cfg(feature = "wallet")]
  246. NUT13(#[from] crate::nuts::nut13::Error),
  247. /// NUT14 Error
  248. #[error(transparent)]
  249. NUT14(#[from] crate::nuts::nut14::Error),
  250. /// NUT18 Error
  251. #[error(transparent)]
  252. NUT18(#[from] crate::nuts::nut18::Error),
  253. /// NUT20 Error
  254. #[error(transparent)]
  255. NUT20(#[from] crate::nuts::nut20::Error),
  256. /// Database Error
  257. #[error(transparent)]
  258. Database(#[from] crate::database::Error),
  259. /// Payment Error
  260. #[error(transparent)]
  261. #[cfg(feature = "mint")]
  262. Payment(#[from] crate::payment::Error),
  263. }
  264. /// CDK Error Response
  265. ///
  266. /// See NUT definition in [00](https://github.com/cashubtc/nuts/blob/main/00.md)
  267. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  268. #[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
  269. pub struct ErrorResponse {
  270. /// Error Code
  271. pub code: ErrorCode,
  272. /// Human readable Text
  273. pub error: Option<String>,
  274. /// Longer human readable description
  275. pub detail: Option<String>,
  276. }
  277. impl fmt::Display for ErrorResponse {
  278. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  279. write!(
  280. f,
  281. "code: {}, error: {}, detail: {}",
  282. self.code,
  283. self.error.clone().unwrap_or_default(),
  284. self.detail.clone().unwrap_or_default()
  285. )
  286. }
  287. }
  288. impl ErrorResponse {
  289. /// Create new [`ErrorResponse`]
  290. pub fn new(code: ErrorCode, error: Option<String>, detail: Option<String>) -> Self {
  291. Self {
  292. code,
  293. error,
  294. detail,
  295. }
  296. }
  297. /// Error response from json
  298. pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
  299. let value: Value = serde_json::from_str(json)?;
  300. Self::from_value(value)
  301. }
  302. /// Error response from json Value
  303. pub fn from_value(value: Value) -> Result<Self, serde_json::Error> {
  304. match serde_json::from_value::<ErrorResponse>(value.clone()) {
  305. Ok(res) => Ok(res),
  306. Err(_) => Ok(Self {
  307. code: ErrorCode::Unknown(999),
  308. error: Some(value.to_string()),
  309. detail: None,
  310. }),
  311. }
  312. }
  313. }
  314. impl From<Error> for ErrorResponse {
  315. fn from(err: Error) -> ErrorResponse {
  316. match err {
  317. Error::TokenAlreadySpent => ErrorResponse {
  318. code: ErrorCode::TokenAlreadySpent,
  319. error: Some(err.to_string()),
  320. detail: None,
  321. },
  322. Error::UnsupportedUnit => ErrorResponse {
  323. code: ErrorCode::UnsupportedUnit,
  324. error: Some(err.to_string()),
  325. detail: None,
  326. },
  327. Error::PaymentFailed => ErrorResponse {
  328. code: ErrorCode::LightningError,
  329. error: Some(err.to_string()),
  330. detail: None,
  331. },
  332. Error::RequestAlreadyPaid => ErrorResponse {
  333. code: ErrorCode::InvoiceAlreadyPaid,
  334. error: Some("Invoice already paid.".to_string()),
  335. detail: None,
  336. },
  337. Error::TransactionUnbalanced(inputs_total, outputs_total, fee_expected) => {
  338. ErrorResponse {
  339. code: ErrorCode::TransactionUnbalanced,
  340. error: Some(format!(
  341. "Inputs: {}, Outputs: {}, expected_fee: {}",
  342. inputs_total, outputs_total, fee_expected,
  343. )),
  344. detail: Some("Transaction inputs should equal outputs less fee".to_string()),
  345. }
  346. }
  347. Error::MintingDisabled => ErrorResponse {
  348. code: ErrorCode::MintingDisabled,
  349. error: Some(err.to_string()),
  350. detail: None,
  351. },
  352. Error::BlindedMessageAlreadySigned => ErrorResponse {
  353. code: ErrorCode::BlindedMessageAlreadySigned,
  354. error: Some(err.to_string()),
  355. detail: None,
  356. },
  357. Error::InsufficientFunds => ErrorResponse {
  358. code: ErrorCode::TransactionUnbalanced,
  359. error: Some(err.to_string()),
  360. detail: None,
  361. },
  362. Error::AmountOutofLimitRange(_min, _max, _amount) => ErrorResponse {
  363. code: ErrorCode::AmountOutofLimitRange,
  364. error: Some(err.to_string()),
  365. detail: None,
  366. },
  367. Error::ExpiredQuote(_, _) => ErrorResponse {
  368. code: ErrorCode::QuoteExpired,
  369. error: Some(err.to_string()),
  370. detail: None,
  371. },
  372. Error::PendingQuote => ErrorResponse {
  373. code: ErrorCode::QuotePending,
  374. error: Some(err.to_string()),
  375. detail: None,
  376. },
  377. Error::TokenPending => ErrorResponse {
  378. code: ErrorCode::TokenPending,
  379. error: Some(err.to_string()),
  380. detail: None,
  381. },
  382. Error::NUT20(err) => ErrorResponse {
  383. code: ErrorCode::WitnessMissingOrInvalid,
  384. error: Some(err.to_string()),
  385. detail: None,
  386. },
  387. Error::DuplicateInputs => ErrorResponse {
  388. code: ErrorCode::DuplicateInputs,
  389. error: Some(err.to_string()),
  390. detail: None,
  391. },
  392. Error::DuplicateOutputs => ErrorResponse {
  393. code: ErrorCode::DuplicateOutputs,
  394. error: Some(err.to_string()),
  395. detail: None,
  396. },
  397. Error::MultipleUnits => ErrorResponse {
  398. code: ErrorCode::MultipleUnits,
  399. error: Some(err.to_string()),
  400. detail: None,
  401. },
  402. Error::UnitMismatch => ErrorResponse {
  403. code: ErrorCode::UnitMismatch,
  404. error: Some(err.to_string()),
  405. detail: None,
  406. },
  407. _ => ErrorResponse {
  408. code: ErrorCode::Unknown(9999),
  409. error: Some(err.to_string()),
  410. detail: None,
  411. },
  412. }
  413. }
  414. }
  415. impl From<ErrorResponse> for Error {
  416. fn from(err: ErrorResponse) -> Error {
  417. match err.code {
  418. ErrorCode::TokenAlreadySpent => Self::TokenAlreadySpent,
  419. ErrorCode::QuoteNotPaid => Self::UnpaidQuote,
  420. ErrorCode::QuotePending => Self::PendingQuote,
  421. ErrorCode::QuoteExpired => Self::ExpiredQuote(0, 0),
  422. ErrorCode::KeysetNotFound => Self::UnknownKeySet,
  423. ErrorCode::KeysetInactive => Self::InactiveKeyset,
  424. ErrorCode::BlindedMessageAlreadySigned => Self::BlindedMessageAlreadySigned,
  425. ErrorCode::UnsupportedUnit => Self::UnsupportedUnit,
  426. ErrorCode::TransactionUnbalanced => Self::TransactionUnbalanced(0, 0, 0),
  427. ErrorCode::MintingDisabled => Self::MintingDisabled,
  428. ErrorCode::InvoiceAlreadyPaid => Self::RequestAlreadyPaid,
  429. ErrorCode::TokenNotVerified => Self::DHKE(crate::dhke::Error::TokenNotVerified),
  430. ErrorCode::LightningError => Self::PaymentFailed,
  431. ErrorCode::AmountOutofLimitRange => {
  432. Self::AmountOutofLimitRange(Amount::default(), Amount::default(), Amount::default())
  433. }
  434. ErrorCode::TokenPending => Self::TokenPending,
  435. ErrorCode::WitnessMissingOrInvalid => Self::SignatureMissingOrInvalid,
  436. ErrorCode::DuplicateInputs => Self::DuplicateInputs,
  437. ErrorCode::DuplicateOutputs => Self::DuplicateOutputs,
  438. ErrorCode::MultipleUnits => Self::MultipleUnits,
  439. ErrorCode::UnitMismatch => Self::UnitMismatch,
  440. _ => Self::UnknownErrorResponse(err.to_string()),
  441. }
  442. }
  443. }
  444. /// Possible Error Codes
  445. #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
  446. #[cfg_attr(feature = "swagger", derive(utoipa::ToSchema))]
  447. pub enum ErrorCode {
  448. /// Token is already spent
  449. TokenAlreadySpent,
  450. /// Token Pending
  451. TokenPending,
  452. /// Quote is not paid
  453. QuoteNotPaid,
  454. /// Quote is not expired
  455. QuoteExpired,
  456. /// Quote Pending
  457. QuotePending,
  458. /// Keyset is not found
  459. KeysetNotFound,
  460. /// Keyset inactive
  461. KeysetInactive,
  462. /// Blinded Message Already signed
  463. BlindedMessageAlreadySigned,
  464. /// Unsupported unit
  465. UnsupportedUnit,
  466. /// Token already issed for quote
  467. TokensAlreadyIssued,
  468. /// Minting Disabled
  469. MintingDisabled,
  470. /// Invoice Already Paid
  471. InvoiceAlreadyPaid,
  472. /// Token Not Verified
  473. TokenNotVerified,
  474. /// Lightning Error
  475. LightningError,
  476. /// Unbalanced Error
  477. TransactionUnbalanced,
  478. /// Amount outside of allowed range
  479. AmountOutofLimitRange,
  480. /// Witness missing or invalid
  481. WitnessMissingOrInvalid,
  482. /// Duplicate Inputs
  483. DuplicateInputs,
  484. /// Duplicate Outputs
  485. DuplicateOutputs,
  486. /// Multiple Units
  487. MultipleUnits,
  488. /// Input unit does not match output
  489. UnitMismatch,
  490. /// Unknown error code
  491. Unknown(u16),
  492. }
  493. impl ErrorCode {
  494. /// Error code from u16
  495. pub fn from_code(code: u16) -> Self {
  496. match code {
  497. 10002 => Self::BlindedMessageAlreadySigned,
  498. 10003 => Self::TokenNotVerified,
  499. 11001 => Self::TokenAlreadySpent,
  500. 11002 => Self::TransactionUnbalanced,
  501. 11005 => Self::UnsupportedUnit,
  502. 11006 => Self::AmountOutofLimitRange,
  503. 11007 => Self::DuplicateInputs,
  504. 11008 => Self::DuplicateOutputs,
  505. 11009 => Self::MultipleUnits,
  506. 11010 => Self::UnitMismatch,
  507. 11012 => Self::TokenPending,
  508. 12001 => Self::KeysetNotFound,
  509. 12002 => Self::KeysetInactive,
  510. 20000 => Self::LightningError,
  511. 20001 => Self::QuoteNotPaid,
  512. 20002 => Self::TokensAlreadyIssued,
  513. 20003 => Self::MintingDisabled,
  514. 20005 => Self::QuotePending,
  515. 20006 => Self::InvoiceAlreadyPaid,
  516. 20007 => Self::QuoteExpired,
  517. 20008 => Self::WitnessMissingOrInvalid,
  518. _ => Self::Unknown(code),
  519. }
  520. }
  521. /// Error code to u16
  522. pub fn to_code(&self) -> u16 {
  523. match self {
  524. Self::BlindedMessageAlreadySigned => 10002,
  525. Self::TokenNotVerified => 10003,
  526. Self::TokenAlreadySpent => 11001,
  527. Self::TransactionUnbalanced => 11002,
  528. Self::UnsupportedUnit => 11005,
  529. Self::AmountOutofLimitRange => 11006,
  530. Self::DuplicateInputs => 11007,
  531. Self::DuplicateOutputs => 11008,
  532. Self::MultipleUnits => 11009,
  533. Self::UnitMismatch => 11010,
  534. Self::TokenPending => 11012,
  535. Self::KeysetNotFound => 12001,
  536. Self::KeysetInactive => 12002,
  537. Self::LightningError => 20000,
  538. Self::QuoteNotPaid => 20001,
  539. Self::TokensAlreadyIssued => 20002,
  540. Self::MintingDisabled => 20003,
  541. Self::QuotePending => 20005,
  542. Self::InvoiceAlreadyPaid => 20006,
  543. Self::QuoteExpired => 20007,
  544. Self::WitnessMissingOrInvalid => 20008,
  545. Self::Unknown(code) => *code,
  546. }
  547. }
  548. }
  549. impl Serialize for ErrorCode {
  550. fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
  551. where
  552. S: Serializer,
  553. {
  554. serializer.serialize_u16(self.to_code())
  555. }
  556. }
  557. impl<'de> Deserialize<'de> for ErrorCode {
  558. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  559. where
  560. D: Deserializer<'de>,
  561. {
  562. let code = u16::deserialize(deserializer)?;
  563. Ok(ErrorCode::from_code(code))
  564. }
  565. }
  566. impl fmt::Display for ErrorCode {
  567. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  568. write!(f, "{}", self.to_code())
  569. }
  570. }