mint.rs 11 KB

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