mod.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. use std::collections::HashSet;
  2. use cashu::dhke::{sign_message, verify_message};
  3. #[cfg(feature = "nut07")]
  4. use cashu::nuts::nut07::{ProofState, State};
  5. use cashu::nuts::{
  6. BlindedMessage, BlindedSignature, MeltBolt11Request, MeltBolt11Response, Proof, SwapRequest,
  7. SwapResponse, *,
  8. };
  9. #[cfg(feature = "nut07")]
  10. use cashu::nuts::{CheckStateRequest, CheckStateResponse};
  11. use cashu::secret::Secret;
  12. use cashu::types::{MeltQuote, MintQuote};
  13. use cashu::Amount;
  14. use serde::{Deserialize, Serialize};
  15. use thiserror::Error;
  16. use tracing::{debug, info};
  17. use crate::Mnemonic;
  18. mod localstore;
  19. use localstore::LocalStore;
  20. #[derive(Debug, Error)]
  21. pub enum Error {
  22. /// Unknown Keyset
  23. #[error("Unknown Keyset")]
  24. UnknownKeySet,
  25. /// Inactive Keyset
  26. #[error("Inactive Keyset")]
  27. InactiveKeyset,
  28. #[error("No key for amount")]
  29. AmountKey,
  30. #[error("Amount")]
  31. Amount,
  32. #[error("Duplicate proofs")]
  33. DuplicateProofs,
  34. #[error("Token Spent")]
  35. TokenSpent,
  36. #[error("Token Pending")]
  37. TokenPending,
  38. #[error("`{0}`")]
  39. Custom(String),
  40. #[error("`{0}`")]
  41. Cashu(#[from] cashu::error::mint::Error),
  42. #[error("`{0}`")]
  43. Localstore(#[from] localstore::Error),
  44. #[error("Unknown quote")]
  45. UnknownQuote,
  46. #[error("Cannot have multiple units")]
  47. MultipleUnits,
  48. }
  49. pub struct Mint<L: LocalStore> {
  50. // pub pubkey: PublicKey
  51. mnemonic: Mnemonic,
  52. pub fee_reserve: FeeReserve,
  53. localstore: L,
  54. }
  55. impl<L: LocalStore> Mint<L> {
  56. pub async fn new(
  57. localstore: L,
  58. mnemonic: Mnemonic,
  59. keysets_info: HashSet<MintKeySetInfo>,
  60. min_fee_reserve: Amount,
  61. percent_fee_reserve: f32,
  62. ) -> Result<Self, Error> {
  63. let mut active_units: HashSet<CurrencyUnit> = HashSet::default();
  64. // Check that there is only one active keyset per unit
  65. for keyset_info in keysets_info {
  66. if keyset_info.active && !active_units.insert(keyset_info.unit.clone()) {
  67. // TODO: Handle Error
  68. todo!()
  69. }
  70. let keyset = nut02::mint::KeySet::generate(
  71. &mnemonic.to_seed_normalized(""),
  72. keyset_info.unit.clone(),
  73. &keyset_info.derivation_path.clone(),
  74. keyset_info.max_order,
  75. );
  76. localstore.add_keyset(keyset).await?;
  77. }
  78. Ok(Self {
  79. localstore,
  80. mnemonic,
  81. fee_reserve: FeeReserve {
  82. min_fee_reserve,
  83. percent_fee_reserve,
  84. },
  85. })
  86. }
  87. pub async fn new_mint_quote(
  88. &self,
  89. request: String,
  90. unit: CurrencyUnit,
  91. amount: Amount,
  92. expiry: u64,
  93. ) -> Result<MintQuote, Error> {
  94. let quote = MintQuote::new(request, unit, amount, expiry);
  95. self.localstore.add_mint_quote(quote.clone()).await?;
  96. Ok(quote)
  97. }
  98. pub async fn new_melt_quote(
  99. &self,
  100. request: String,
  101. unit: CurrencyUnit,
  102. amount: Amount,
  103. fee_reserve: Amount,
  104. expiry: u64,
  105. ) -> Result<MeltQuote, Error> {
  106. let quote = MeltQuote::new(request, unit, amount, fee_reserve, expiry);
  107. self.localstore.add_melt_quote(quote.clone()).await?;
  108. Ok(quote)
  109. }
  110. /// Retrieve the public keys of the active keyset for distribution to
  111. /// wallet clients
  112. pub async fn keyset_pubkeys(&self, keyset_id: &Id) -> Result<Option<KeysResponse>, Error> {
  113. let keyset = match self.localstore.get_keyset(keyset_id).await? {
  114. Some(keyset) => keyset.clone(),
  115. None => {
  116. return Ok(None);
  117. }
  118. };
  119. Ok(Some(KeysResponse {
  120. keysets: vec![keyset.into()],
  121. }))
  122. }
  123. /// Return a list of all supported keysets
  124. pub async fn keysets(&self) -> Result<KeysetResponse, Error> {
  125. let keysets = self.localstore.get_keysets().await?;
  126. let active_keysets: HashSet<Id> = self
  127. .localstore
  128. .get_active_keysets()
  129. .await?
  130. .values()
  131. .cloned()
  132. .collect();
  133. let keysets = keysets
  134. .into_iter()
  135. .map(|k| KeySetInfo {
  136. id: k.id,
  137. unit: k.unit,
  138. active: active_keysets.contains(&k.id),
  139. })
  140. .collect();
  141. Ok(KeysetResponse { keysets })
  142. }
  143. pub async fn keyset(&self, id: &Id) -> Result<Option<KeySet>, Error> {
  144. Ok(self
  145. .localstore
  146. .get_keyset(id)
  147. .await?
  148. .map(|ks| ks.clone().into()))
  149. }
  150. /// Add current keyset to inactive keysets
  151. /// Generate new keyset
  152. pub async fn rotate_keyset(
  153. &mut self,
  154. unit: CurrencyUnit,
  155. derivation_path: &str,
  156. max_order: u8,
  157. ) -> Result<(), Error> {
  158. let new_keyset = MintKeySet::generate(
  159. &self.mnemonic.to_seed_normalized(""),
  160. unit.clone(),
  161. derivation_path,
  162. max_order,
  163. );
  164. self.localstore.add_keyset(new_keyset.clone()).await?;
  165. self.localstore
  166. .add_active_keyset(unit, new_keyset.id)
  167. .await?;
  168. Ok(())
  169. }
  170. pub async fn process_mint_request(
  171. &mut self,
  172. mint_request: nut04::MintBolt11Request,
  173. ) -> Result<nut04::MintBolt11Response, Error> {
  174. let mut blind_signatures = Vec::with_capacity(mint_request.outputs.len());
  175. for blinded_message in mint_request.outputs {
  176. blind_signatures.push(self.blind_sign(&blinded_message).await?);
  177. }
  178. Ok(nut04::MintBolt11Response {
  179. signatures: blind_signatures,
  180. })
  181. }
  182. async fn blind_sign(
  183. &self,
  184. blinded_message: &BlindedMessage,
  185. ) -> Result<BlindedSignature, Error> {
  186. let BlindedMessage {
  187. amount,
  188. b,
  189. keyset_id,
  190. } = blinded_message;
  191. let keyset = self
  192. .localstore
  193. .get_keyset(keyset_id)
  194. .await?
  195. .ok_or(Error::UnknownKeySet)?;
  196. let active = self
  197. .localstore
  198. .get_active_keyset_id(&keyset.unit)
  199. .await?
  200. .ok_or(Error::InactiveKeyset)?;
  201. // Check that the keyset is active and should be used to sign
  202. if keyset.id.ne(&active) {
  203. return Err(Error::InactiveKeyset);
  204. }
  205. let Some(key_pair) = keyset.keys.0.get(amount) else {
  206. // No key for amount
  207. return Err(Error::AmountKey);
  208. };
  209. let c = sign_message(key_pair.secret_key.clone().into(), b.clone().into())?;
  210. Ok(BlindedSignature {
  211. amount: *amount,
  212. c: c.into(),
  213. keyset_id: keyset.id,
  214. })
  215. }
  216. pub async fn process_swap_request(
  217. &mut self,
  218. swap_request: SwapRequest,
  219. ) -> Result<SwapResponse, Error> {
  220. let proofs_total = swap_request.input_amount();
  221. let output_total = swap_request.output_amount();
  222. if proofs_total != output_total {
  223. return Err(Error::Amount);
  224. }
  225. let proof_count = swap_request.inputs.len();
  226. let secrets: HashSet<Secret> = swap_request
  227. .inputs
  228. .iter()
  229. .map(|p| p.secret.clone())
  230. .collect();
  231. // Check that there are no duplicate proofs in request
  232. if secrets.len().ne(&proof_count) {
  233. return Err(Error::DuplicateProofs);
  234. }
  235. for proof in &swap_request.inputs {
  236. self.verify_proof(proof).await?
  237. }
  238. let input_keyset_ids: HashSet<Id> =
  239. swap_request.inputs.iter().map(|p| p.keyset_id).collect();
  240. let mut keyset_units = Vec::with_capacity(input_keyset_ids.capacity());
  241. for id in input_keyset_ids {
  242. let keyset = self
  243. .localstore
  244. .get_keyset(&id)
  245. .await?
  246. .ok_or(Error::UnknownKeySet)?;
  247. keyset_units.push(keyset.unit);
  248. }
  249. let output_keyset_ids: HashSet<Id> =
  250. swap_request.outputs.iter().map(|p| p.keyset_id).collect();
  251. for id in &output_keyset_ids {
  252. let keyset = self
  253. .localstore
  254. .get_keyset(id)
  255. .await?
  256. .ok_or(Error::UnknownKeySet)?;
  257. keyset_units.push(keyset.unit);
  258. }
  259. // Check that all input and output proofs are the same unit
  260. let seen_units: HashSet<CurrencyUnit> = HashSet::new();
  261. if keyset_units.iter().any(|unit| !seen_units.contains(unit)) && seen_units.len() != 1 {
  262. return Err(Error::MultipleUnits);
  263. }
  264. for proof in swap_request.inputs {
  265. self.localstore
  266. .add_spent_proof(proof.secret.clone(), proof)
  267. .await
  268. .unwrap();
  269. }
  270. let mut promises = Vec::with_capacity(swap_request.outputs.len());
  271. for output in swap_request.outputs {
  272. let promise = self.blind_sign(&output).await?;
  273. promises.push(promise);
  274. }
  275. Ok(SwapResponse::new(promises))
  276. }
  277. async fn verify_proof(&self, proof: &Proof) -> Result<(), Error> {
  278. if self
  279. .localstore
  280. .get_spent_proof(&proof.secret)
  281. .await?
  282. .is_some()
  283. {
  284. return Err(Error::TokenSpent);
  285. }
  286. if self
  287. .localstore
  288. .get_pending_proof(&proof.secret)
  289. .await?
  290. .is_some()
  291. {
  292. return Err(Error::TokenPending);
  293. }
  294. let keyset = self
  295. .localstore
  296. .get_keyset(&proof.keyset_id)
  297. .await?
  298. .ok_or(Error::UnknownKeySet)?;
  299. let Some(keypair) = keyset.keys.0.get(&proof.amount) else {
  300. return Err(Error::AmountKey);
  301. };
  302. verify_message(
  303. keypair.secret_key.clone().into(),
  304. proof.c.clone().into(),
  305. &proof.secret,
  306. )?;
  307. Ok(())
  308. }
  309. #[cfg(feature = "nut07")]
  310. pub async fn check_spendable(
  311. &self,
  312. check_spendable: &CheckStateRequest,
  313. ) -> Result<CheckStateResponse, Error> {
  314. let mut states = Vec::with_capacity(check_spendable.secrets.len());
  315. for secret in &check_spendable.secrets {
  316. let state = if self.localstore.get_spent_proof(secret).await?.is_some() {
  317. State::Spent
  318. } else if self.localstore.get_pending_proof(secret).await?.is_some() {
  319. State::Pending
  320. } else {
  321. State::Unspent
  322. };
  323. states.push(ProofState {
  324. secret: secret.clone(),
  325. state,
  326. witness: None,
  327. })
  328. }
  329. Ok(CheckStateResponse { states })
  330. }
  331. pub async fn verify_melt_request(
  332. &mut self,
  333. melt_request: &MeltBolt11Request,
  334. ) -> Result<(), Error> {
  335. let quote = self
  336. .localstore
  337. .get_melt_quote(&melt_request.quote)
  338. .await?
  339. .ok_or(Error::UnknownQuote)?;
  340. let proofs_total = melt_request.proofs_amount();
  341. let required_total = quote.amount + quote.fee_reserve;
  342. if proofs_total < required_total {
  343. debug!(
  344. "Insufficient Proofs: Got: {}, Required: {}",
  345. proofs_total, required_total
  346. );
  347. return Err(Error::Amount);
  348. }
  349. let input_keyset_ids: HashSet<Id> =
  350. melt_request.inputs.iter().map(|p| p.keyset_id).collect();
  351. let mut keyset_units = Vec::with_capacity(input_keyset_ids.capacity());
  352. for id in input_keyset_ids {
  353. let keyset = self
  354. .localstore
  355. .get_keyset(&id)
  356. .await?
  357. .ok_or(Error::UnknownKeySet)?;
  358. keyset_units.push(keyset.unit);
  359. }
  360. if let Some(outputs) = &melt_request.outputs {
  361. let output_keysets_ids: HashSet<Id> = outputs.iter().map(|b| b.keyset_id).collect();
  362. for id in output_keysets_ids {
  363. let keyset = self
  364. .localstore
  365. .get_keyset(&id)
  366. .await?
  367. .ok_or(Error::UnknownKeySet)?;
  368. // Get the active keyset for the unit
  369. let active_keyset_id = self
  370. .localstore
  371. .get_active_keyset_id(&keyset.unit)
  372. .await?
  373. .ok_or(Error::InactiveKeyset)?;
  374. // Check output is for current active keyset
  375. if id.ne(&active_keyset_id) {
  376. return Err(Error::InactiveKeyset);
  377. }
  378. keyset_units.push(keyset.unit);
  379. }
  380. }
  381. // Check that all input and output proofs are the same unit
  382. let seen_units: HashSet<CurrencyUnit> = HashSet::new();
  383. if keyset_units.iter().any(|unit| !seen_units.contains(unit)) && seen_units.len() != 1 {
  384. return Err(Error::MultipleUnits);
  385. }
  386. let secrets: HashSet<&Secret> = melt_request.inputs.iter().map(|p| &p.secret).collect();
  387. // Ensure proofs are unique and not being double spent
  388. if melt_request.inputs.len().ne(&secrets.len()) {
  389. return Err(Error::DuplicateProofs);
  390. }
  391. for proof in &melt_request.inputs {
  392. self.verify_proof(proof).await?
  393. }
  394. Ok(())
  395. }
  396. pub async fn process_melt_request(
  397. &mut self,
  398. melt_request: &MeltBolt11Request,
  399. preimage: &str,
  400. total_spent: Amount,
  401. ) -> Result<MeltBolt11Response, Error> {
  402. self.verify_melt_request(melt_request).await?;
  403. for input in &melt_request.inputs {
  404. self.localstore
  405. .add_spent_proof(input.secret.clone(), input.clone())
  406. .await
  407. .unwrap();
  408. }
  409. let mut change = None;
  410. if let Some(outputs) = melt_request.outputs.clone() {
  411. let change_target = melt_request.proofs_amount() - total_spent;
  412. let mut amounts = change_target.split();
  413. let mut change_sigs = Vec::with_capacity(amounts.len());
  414. if outputs.len().lt(&amounts.len()) {
  415. debug!(
  416. "Providing change requires {} blinded messages, but only {} provided",
  417. amounts.len(),
  418. outputs.len()
  419. );
  420. // In the case that not enough outputs are provided to return all change
  421. // Reverse sort the amounts so that the most amount of change possible is
  422. // returned. The rest is burnt
  423. amounts.sort_by(|a, b| b.cmp(a));
  424. }
  425. for (amount, blinded_message) in amounts.iter().zip(outputs) {
  426. let mut blinded_message = blinded_message;
  427. blinded_message.amount = *amount;
  428. let signature = self.blind_sign(&blinded_message).await?;
  429. change_sigs.push(signature)
  430. }
  431. change = Some(change_sigs);
  432. } else {
  433. info!(
  434. "No change outputs provided. Burnt: {:?} sats",
  435. (melt_request.proofs_amount() - total_spent)
  436. );
  437. }
  438. Ok(MeltBolt11Response {
  439. paid: true,
  440. payment_preimage: Some(preimage.to_string()),
  441. change,
  442. })
  443. }
  444. }
  445. pub struct FeeReserve {
  446. pub min_fee_reserve: Amount,
  447. pub percent_fee_reserve: f32,
  448. }
  449. #[derive(Debug, Hash, Clone, PartialEq, Eq, Serialize, Deserialize)]
  450. pub struct MintKeySetInfo {
  451. pub id: Id,
  452. pub unit: CurrencyUnit,
  453. pub active: bool,
  454. pub valid_from: u64,
  455. pub valid_to: Option<u64>,
  456. pub derivation_path: String,
  457. pub max_order: u8,
  458. }
  459. impl From<MintKeySetInfo> for KeySetInfo {
  460. fn from(keyset_info: MintKeySetInfo) -> Self {
  461. Self {
  462. id: keyset_info.id,
  463. unit: keyset_info.unit,
  464. active: keyset_info.active,
  465. }
  466. }
  467. }