mod.rs 13 KB

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