error.rs 24 KB

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