db_signatory.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. use std::collections::HashMap;
  2. use std::sync::Arc;
  3. use bitcoin::bip32::{DerivationPath, Xpriv};
  4. use bitcoin::secp256k1::{self, Secp256k1};
  5. use cdk_common::database;
  6. use cdk_common::dhke::{sign_message, verify_message};
  7. use cdk_common::error::Error;
  8. use cdk_common::mint::MintKeySetInfo;
  9. use cdk_common::nuts::{BlindSignature, BlindedMessage, CurrencyUnit, Id, MintKeySet, Proof};
  10. use tokio::sync::RwLock;
  11. use crate::common::{create_new_keyset, derivation_path_from_unit, init_keysets};
  12. use crate::signatory::{RotateKeyArguments, Signatory, SignatoryKeySet};
  13. /// In-memory Signatory
  14. ///
  15. /// This is the default signatory implementation for the mint.
  16. ///
  17. /// The private keys and the all key-related data is stored in memory, in the same process, but it
  18. /// is not accessible from the outside.
  19. pub struct DbSignatory {
  20. keysets: RwLock<HashMap<Id, (MintKeySetInfo, MintKeySet)>>,
  21. active_keysets: RwLock<HashMap<CurrencyUnit, Id>>,
  22. localstore: Arc<dyn database::MintKeysDatabase<Err = database::Error> + Send + Sync>,
  23. auth_localstore:
  24. Option<Arc<dyn database::MintAuthDatabase<Err = database::Error> + Send + Sync>>,
  25. secp_ctx: Secp256k1<secp256k1::All>,
  26. custom_paths: HashMap<CurrencyUnit, DerivationPath>,
  27. xpriv: Xpriv,
  28. }
  29. impl DbSignatory {
  30. /// Creates a new MemorySignatory instance
  31. pub async fn new(
  32. localstore: Arc<dyn database::MintKeysDatabase<Err = database::Error> + Send + Sync>,
  33. auth_localstore: Option<
  34. Arc<dyn database::MintAuthDatabase<Err = database::Error> + Send + Sync>,
  35. >,
  36. seed: &[u8],
  37. supported_units: HashMap<CurrencyUnit, (u64, u8)>,
  38. custom_paths: HashMap<CurrencyUnit, DerivationPath>,
  39. ) -> Result<Self, Error> {
  40. let secp_ctx = Secp256k1::new();
  41. let xpriv = Xpriv::new_master(bitcoin::Network::Bitcoin, seed).expect("RNG busted");
  42. let (mut active_keysets, active_keyset_units) = init_keysets(
  43. xpriv,
  44. &secp_ctx,
  45. &localstore,
  46. &supported_units,
  47. &custom_paths,
  48. )
  49. .await?;
  50. if let Some(auth_localstore) = auth_localstore.as_ref() {
  51. tracing::info!("Auth enabled creating auth keysets");
  52. let derivation_path = match custom_paths.get(&CurrencyUnit::Auth) {
  53. Some(path) => path.clone(),
  54. None => derivation_path_from_unit(CurrencyUnit::Auth, 0)
  55. .ok_or(Error::UnsupportedUnit)?,
  56. };
  57. let (keyset, keyset_info) = create_new_keyset(
  58. &secp_ctx,
  59. xpriv,
  60. derivation_path,
  61. Some(0),
  62. CurrencyUnit::Auth,
  63. 1,
  64. 0,
  65. );
  66. let id = keyset_info.id;
  67. auth_localstore.add_keyset_info(keyset_info).await?;
  68. auth_localstore.set_active_keyset(id).await?;
  69. active_keysets.insert(id, keyset);
  70. }
  71. // Create new keysets for supported units that aren't covered by the current keysets
  72. for (unit, (fee, max_order)) in supported_units {
  73. if !active_keyset_units.contains(&unit) {
  74. let derivation_path = match custom_paths.get(&unit) {
  75. Some(path) => path.clone(),
  76. None => {
  77. derivation_path_from_unit(unit.clone(), 0).ok_or(Error::UnsupportedUnit)?
  78. }
  79. };
  80. let (keyset, keyset_info) = create_new_keyset(
  81. &secp_ctx,
  82. xpriv,
  83. derivation_path,
  84. Some(0),
  85. unit.clone(),
  86. max_order,
  87. fee,
  88. );
  89. let id = keyset_info.id;
  90. localstore.add_keyset_info(keyset_info).await?;
  91. localstore.set_active_keyset(unit, id).await?;
  92. active_keysets.insert(id, keyset);
  93. }
  94. }
  95. let keys = Self {
  96. keysets: Default::default(),
  97. active_keysets: Default::default(),
  98. auth_localstore,
  99. secp_ctx,
  100. localstore,
  101. custom_paths,
  102. xpriv,
  103. };
  104. keys.reload_keys_from_db().await?;
  105. Ok(keys)
  106. }
  107. /// Load all the keysets from the database, even if they are not active.
  108. ///
  109. /// Since the database is owned by this process, we can load all the keysets in memory, and use
  110. /// it as the primary source, and the database as the persistence layer.
  111. ///
  112. /// Any operation performed with keysets, are done through this trait and never to the database
  113. /// directly.
  114. async fn reload_keys_from_db(&self) -> Result<(), Error> {
  115. let mut keysets = self.keysets.write().await;
  116. let mut active_keysets = self.active_keysets.write().await;
  117. keysets.clear();
  118. active_keysets.clear();
  119. for info in self.localstore.get_keyset_infos().await? {
  120. let id = info.id;
  121. let keyset = self.generate_keyset(&info);
  122. if info.active {
  123. active_keysets.insert(info.unit.clone(), id);
  124. }
  125. keysets.insert(id, (info, keyset));
  126. }
  127. if let Some(auth_db) = self.auth_localstore.clone() {
  128. for info in auth_db.get_keyset_infos().await? {
  129. let id = info.id;
  130. let keyset = self.generate_keyset(&info);
  131. if info.unit != CurrencyUnit::Auth {
  132. continue;
  133. }
  134. if info.active {
  135. active_keysets.insert(info.unit.clone(), id);
  136. }
  137. keysets.insert(id, (info, keyset));
  138. }
  139. }
  140. Ok(())
  141. }
  142. fn generate_keyset(&self, keyset_info: &MintKeySetInfo) -> MintKeySet {
  143. MintKeySet::generate_from_xpriv(
  144. &self.secp_ctx,
  145. self.xpriv,
  146. keyset_info.max_order,
  147. keyset_info.unit.clone(),
  148. keyset_info.derivation_path.clone(),
  149. )
  150. }
  151. }
  152. #[async_trait::async_trait]
  153. impl Signatory for DbSignatory {
  154. async fn blind_sign(&self, blinded_message: BlindedMessage) -> Result<BlindSignature, Error> {
  155. let BlindedMessage {
  156. amount,
  157. blinded_secret,
  158. keyset_id,
  159. ..
  160. } = blinded_message;
  161. let keysets = self.keysets.read().await;
  162. let (info, key) = keysets.get(&keyset_id).ok_or(Error::UnknownKeySet)?;
  163. if !info.active {
  164. return Err(Error::InactiveKeyset);
  165. }
  166. let key_pair = key.keys.get(&amount).ok_or(Error::UnknownKeySet)?;
  167. let c = sign_message(&key_pair.secret_key, &blinded_secret)?;
  168. let blinded_signature = BlindSignature::new(
  169. amount,
  170. c,
  171. keyset_id,
  172. &blinded_message.blinded_secret,
  173. key_pair.secret_key.clone(),
  174. )?;
  175. Ok(blinded_signature)
  176. }
  177. async fn verify_proof(&self, proof: Proof) -> Result<(), Error> {
  178. let keysets = self.keysets.read().await;
  179. let (_, key) = keysets.get(&proof.keyset_id).ok_or(Error::UnknownKeySet)?;
  180. let key_pair = key.keys.get(&proof.amount).ok_or(Error::UnknownKeySet)?;
  181. verify_message(&key_pair.secret_key, proof.c, proof.secret.as_bytes())?;
  182. Ok(())
  183. }
  184. async fn auth_keysets(&self) -> Result<Option<Vec<SignatoryKeySet>>, Error> {
  185. let keyset_id = self
  186. .active_keysets
  187. .read()
  188. .await
  189. .get(&CurrencyUnit::Auth)
  190. .cloned()
  191. .ok_or(Error::NoActiveKeyset)?;
  192. let active_keyset = self
  193. .keysets
  194. .read()
  195. .await
  196. .get(&keyset_id)
  197. .ok_or(Error::UnknownKeySet)?
  198. .into();
  199. Ok(Some(vec![active_keyset]))
  200. }
  201. async fn keysets(&self) -> Result<Vec<SignatoryKeySet>, Error> {
  202. Ok(self
  203. .keysets
  204. .read()
  205. .await
  206. .values()
  207. .map(|k| k.into())
  208. .collect::<Vec<_>>())
  209. }
  210. /// Add current keyset to inactive keysets
  211. /// Generate new keyset
  212. #[tracing::instrument(skip(self))]
  213. async fn rotate_keyset(&self, args: RotateKeyArguments) -> Result<MintKeySetInfo, Error> {
  214. let path_index = if let Some(path_index) = args.derivation_path_index {
  215. path_index
  216. } else {
  217. let current_keyset_id = self
  218. .localstore
  219. .get_active_keyset_id(&args.unit)
  220. .await?
  221. .ok_or(Error::UnsupportedUnit)?;
  222. let keyset_info = self
  223. .localstore
  224. .get_keyset_info(&current_keyset_id)
  225. .await?
  226. .ok_or(Error::UnknownKeySet)?;
  227. keyset_info.derivation_path_index.unwrap_or(1) + 1
  228. };
  229. let derivation_path = match self.custom_paths.get(&args.unit) {
  230. Some(path) => path.clone(),
  231. None => derivation_path_from_unit(args.unit.clone(), path_index)
  232. .ok_or(Error::UnsupportedUnit)?,
  233. };
  234. let (_, keyset_info) = create_new_keyset(
  235. &self.secp_ctx,
  236. self.xpriv,
  237. derivation_path,
  238. Some(path_index),
  239. args.unit.clone(),
  240. args.max_order,
  241. args.input_fee_ppk,
  242. );
  243. let id = keyset_info.id;
  244. self.localstore.add_keyset_info(keyset_info.clone()).await?;
  245. self.localstore.set_active_keyset(args.unit, id).await?;
  246. self.reload_keys_from_db().await?;
  247. Ok(keyset_info)
  248. }
  249. }
  250. #[cfg(test)]
  251. mod test {
  252. use std::collections::HashSet;
  253. use bitcoin::key::Secp256k1;
  254. use bitcoin::Network;
  255. use cashu::{Amount, PublicKey};
  256. use cdk_common::MintKeySet;
  257. use super::*;
  258. #[test]
  259. fn mint_mod_generate_keyset_from_seed() {
  260. let seed = "test_seed".as_bytes();
  261. let keyset = MintKeySet::generate_from_seed(
  262. &Secp256k1::new(),
  263. seed,
  264. 2,
  265. CurrencyUnit::Sat,
  266. derivation_path_from_unit(CurrencyUnit::Sat, 0).unwrap(),
  267. );
  268. assert_eq!(keyset.unit, CurrencyUnit::Sat);
  269. assert_eq!(keyset.keys.len(), 2);
  270. let expected_amounts_and_pubkeys: HashSet<(Amount, PublicKey)> = vec![
  271. (
  272. Amount::from(1),
  273. PublicKey::from_hex(
  274. "0257aed43bf2c1cdbe3e7ae2db2b27a723c6746fc7415e09748f6847916c09176e",
  275. )
  276. .unwrap(),
  277. ),
  278. (
  279. Amount::from(2),
  280. PublicKey::from_hex(
  281. "03ad95811e51adb6231613f9b54ba2ba31e4442c9db9d69f8df42c2b26fbfed26e",
  282. )
  283. .unwrap(),
  284. ),
  285. ]
  286. .into_iter()
  287. .collect();
  288. let amounts_and_pubkeys: HashSet<(Amount, PublicKey)> = keyset
  289. .keys
  290. .iter()
  291. .map(|(amount, pair)| (*amount, pair.public_key))
  292. .collect();
  293. assert_eq!(amounts_and_pubkeys, expected_amounts_and_pubkeys);
  294. }
  295. #[test]
  296. fn mint_mod_generate_keyset_from_xpriv() {
  297. let seed = "test_seed".as_bytes();
  298. let network = Network::Bitcoin;
  299. let xpriv = Xpriv::new_master(network, seed).expect("Failed to create xpriv");
  300. let keyset = MintKeySet::generate_from_xpriv(
  301. &Secp256k1::new(),
  302. xpriv,
  303. 2,
  304. CurrencyUnit::Sat,
  305. derivation_path_from_unit(CurrencyUnit::Sat, 0).unwrap(),
  306. );
  307. assert_eq!(keyset.unit, CurrencyUnit::Sat);
  308. assert_eq!(keyset.keys.len(), 2);
  309. let expected_amounts_and_pubkeys: HashSet<(Amount, PublicKey)> = vec![
  310. (
  311. Amount::from(1),
  312. PublicKey::from_hex(
  313. "0257aed43bf2c1cdbe3e7ae2db2b27a723c6746fc7415e09748f6847916c09176e",
  314. )
  315. .unwrap(),
  316. ),
  317. (
  318. Amount::from(2),
  319. PublicKey::from_hex(
  320. "03ad95811e51adb6231613f9b54ba2ba31e4442c9db9d69f8df42c2b26fbfed26e",
  321. )
  322. .unwrap(),
  323. ),
  324. ]
  325. .into_iter()
  326. .collect();
  327. let amounts_and_pubkeys: HashSet<(Amount, PublicKey)> = keyset
  328. .keys
  329. .iter()
  330. .map(|(amount, pair)| (*amount, pair.public_key))
  331. .collect();
  332. assert_eq!(amounts_and_pubkeys, expected_amounts_and_pubkeys);
  333. }
  334. }