mod.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. //! SQLite Mint Auth
  2. use std::collections::HashMap;
  3. use std::ops::DerefMut;
  4. use std::path::Path;
  5. use std::str::FromStr;
  6. use async_trait::async_trait;
  7. use cdk_common::database::{self, MintAuthDatabase};
  8. use cdk_common::mint::MintKeySetInfo;
  9. use cdk_common::nuts::{AuthProof, BlindSignature, Id, PublicKey, State};
  10. use cdk_common::{AuthRequired, ProtectedEndpoint};
  11. use tracing::instrument;
  12. use super::async_rusqlite::AsyncRusqlite;
  13. use super::{sqlite_row_to_blind_signature, sqlite_row_to_keyset_info};
  14. use crate::column_as_string;
  15. use crate::common::{create_sqlite_pool, migrate};
  16. use crate::mint::async_rusqlite::query;
  17. use crate::mint::Error;
  18. /// Mint SQLite Database
  19. #[derive(Debug, Clone)]
  20. pub struct MintSqliteAuthDatabase {
  21. pool: AsyncRusqlite,
  22. }
  23. #[rustfmt::skip]
  24. mod migrations;
  25. impl MintSqliteAuthDatabase {
  26. /// Create new [`MintSqliteAuthDatabase`]
  27. #[cfg(not(feature = "sqlcipher"))]
  28. pub async fn new<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
  29. let pool = create_sqlite_pool(path.as_ref().to_str().ok_or(Error::InvalidDbPath)?);
  30. migrate(pool.get()?.deref_mut(), migrations::MIGRATIONS)?;
  31. Ok(Self {
  32. pool: AsyncRusqlite::new(pool),
  33. })
  34. }
  35. /// Create new [`MintSqliteAuthDatabase`]
  36. #[cfg(feature = "sqlcipher")]
  37. pub async fn new<P: AsRef<Path>>(path: P, password: String) -> Result<Self, Error> {
  38. let pool = create_sqlite_pool(
  39. path.as_ref().to_str().ok_or(Error::InvalidDbPath)?,
  40. password,
  41. );
  42. migrate(pool.get()?.deref_mut(), migrations::MIGRATIONS)?;
  43. Ok(Self {
  44. pool: AsyncRusqlite::new(pool),
  45. })
  46. }
  47. }
  48. #[async_trait]
  49. impl MintAuthDatabase for MintSqliteAuthDatabase {
  50. type Err = database::Error;
  51. #[instrument(skip(self))]
  52. async fn set_active_keyset(&self, id: Id) -> Result<(), Self::Err> {
  53. tracing::info!("Setting auth keyset {id} active");
  54. query(
  55. r#"
  56. UPDATE keyset
  57. SET active = CASE
  58. WHEN id = :id THEN TRUE
  59. ELSE FALSE
  60. END;
  61. "#,
  62. )
  63. .bind(":id", id.to_string())
  64. .execute(&self.pool)
  65. .await?;
  66. Ok(())
  67. }
  68. async fn get_active_keyset_id(&self) -> Result<Option<Id>, Self::Err> {
  69. Ok(query(
  70. r#"
  71. SELECT
  72. id
  73. FROM
  74. keyset
  75. WHERE
  76. active = 1;
  77. "#,
  78. )
  79. .pluck(&self.pool)
  80. .await?
  81. .map(|id| Ok::<_, Error>(column_as_string!(id, Id::from_str, Id::from_bytes)))
  82. .transpose()?)
  83. }
  84. async fn add_keyset_info(&self, keyset: MintKeySetInfo) -> Result<(), Self::Err> {
  85. query(
  86. r#"
  87. INSERT INTO
  88. keyset (
  89. id, unit, active, valid_from, valid_to, derivation_path,
  90. max_order, derivation_path_index
  91. )
  92. VALUES (
  93. :id, :unit, :active, :valid_from, :valid_to, :derivation_path,
  94. :max_order, :derivation_path_index
  95. )
  96. ON CONFLICT(id) DO UPDATE SET
  97. unit = excluded.unit,
  98. active = excluded.active,
  99. valid_from = excluded.valid_from,
  100. valid_to = excluded.valid_to,
  101. derivation_path = excluded.derivation_path,
  102. max_order = excluded.max_order,
  103. derivation_path_index = excluded.derivation_path_index
  104. "#,
  105. )
  106. .bind(":id", keyset.id.to_string())
  107. .bind(":unit", keyset.unit.to_string())
  108. .bind(":active", keyset.active)
  109. .bind(":valid_from", keyset.valid_from as i64)
  110. .bind(":valid_to", keyset.valid_to.map(|v| v as i64))
  111. .bind(":derivation_path", keyset.derivation_path.to_string())
  112. .bind(":max_order", keyset.max_order)
  113. .bind(":derivation_path_index", keyset.derivation_path_index)
  114. .execute(&self.pool)
  115. .await?;
  116. Ok(())
  117. }
  118. async fn get_keyset_info(&self, id: &Id) -> Result<Option<MintKeySetInfo>, Self::Err> {
  119. Ok(query(
  120. r#"SELECT
  121. id,
  122. unit,
  123. active,
  124. valid_from,
  125. valid_to,
  126. derivation_path,
  127. derivation_path_index,
  128. max_order,
  129. input_fee_ppk
  130. FROM
  131. keyset
  132. WHERE id=:id"#,
  133. )
  134. .bind(":id", id.to_string())
  135. .fetch_one(&self.pool)
  136. .await?
  137. .map(sqlite_row_to_keyset_info)
  138. .transpose()?)
  139. }
  140. async fn get_keyset_infos(&self) -> Result<Vec<MintKeySetInfo>, Self::Err> {
  141. Ok(query(
  142. r#"SELECT
  143. id,
  144. unit,
  145. active,
  146. valid_from,
  147. valid_to,
  148. derivation_path,
  149. derivation_path_index,
  150. max_order,
  151. input_fee_ppk
  152. FROM
  153. keyset
  154. WHERE id=:id"#,
  155. )
  156. .fetch_all(&self.pool)
  157. .await?
  158. .into_iter()
  159. .map(sqlite_row_to_keyset_info)
  160. .collect::<Result<Vec<_>, _>>()?)
  161. }
  162. async fn add_proof(&self, proof: AuthProof) -> Result<(), Self::Err> {
  163. if let Err(err) = query(
  164. r#"
  165. INSERT INTO proof
  166. (y, keyset_id, secret, c, state)
  167. VALUES
  168. (:y, :keyset_id, :secret, :c, :state)
  169. "#,
  170. )
  171. .bind(":y", proof.y()?.to_bytes().to_vec())
  172. .bind(":keyset_id", proof.keyset_id.to_string())
  173. .bind(":secret", proof.secret.to_string())
  174. .bind(":c", proof.c.to_bytes().to_vec())
  175. .bind(":state", "UNSPENT".to_string())
  176. .execute(&self.pool)
  177. .await
  178. {
  179. tracing::debug!("Attempting to add known proof. Skipping.... {:?}", err);
  180. }
  181. Ok(())
  182. }
  183. async fn get_proofs_states(&self, ys: &[PublicKey]) -> Result<Vec<Option<State>>, Self::Err> {
  184. let mut current_states = query(r#"SELECT y, state FROM proof WHERE y IN (:ys)"#)
  185. .bind_vec(":ys", ys.iter().map(|y| y.to_bytes().to_vec()).collect())
  186. .fetch_all(&self.pool)
  187. .await?
  188. .into_iter()
  189. .map(|row| {
  190. Ok((
  191. column_as_string!(&row[0], PublicKey::from_hex, PublicKey::from_slice),
  192. column_as_string!(&row[1], State::from_str),
  193. ))
  194. })
  195. .collect::<Result<HashMap<_, _>, Error>>()?;
  196. Ok(ys.iter().map(|y| current_states.remove(y)).collect())
  197. }
  198. async fn update_proof_state(
  199. &self,
  200. y: &PublicKey,
  201. proofs_state: State,
  202. ) -> Result<Option<State>, Self::Err> {
  203. let transaction = self.pool.begin().await?;
  204. let current_state = query(r#"SELECT state FROM proof WHERE y = :y"#)
  205. .bind(":y", y.to_bytes().to_vec())
  206. .pluck(&transaction)
  207. .await?
  208. .map(|state| Ok::<_, Error>(column_as_string!(state, State::from_str)))
  209. .transpose()?;
  210. query(r#"UPDATE proof SET state = :new_state WHERE state = :state AND y = :y"#)
  211. .bind(":y", y.to_bytes().to_vec())
  212. .bind(
  213. ":state",
  214. current_state.as_ref().map(|state| state.to_string()),
  215. )
  216. .bind(":new_state", proofs_state.to_string())
  217. .execute(&transaction)
  218. .await?;
  219. transaction.commit().await?;
  220. Ok(current_state)
  221. }
  222. async fn add_blind_signatures(
  223. &self,
  224. blinded_messages: &[PublicKey],
  225. blind_signatures: &[BlindSignature],
  226. ) -> Result<(), Self::Err> {
  227. let transaction = self.pool.begin().await?;
  228. for (message, signature) in blinded_messages.iter().zip(blind_signatures) {
  229. query(
  230. r#"
  231. INSERT
  232. INTO blind_signature
  233. (y, amount, keyset_id, c)
  234. VALUES
  235. (:y, :amount, :keyset_id, :c)
  236. "#,
  237. )
  238. .bind(":y", message.to_bytes().to_vec())
  239. .bind(":amount", u64::from(signature.amount) as i64)
  240. .bind(":keyset_id", signature.keyset_id.to_string())
  241. .bind(":c", signature.c.to_bytes().to_vec())
  242. .execute(&transaction)
  243. .await?;
  244. }
  245. transaction.commit().await?;
  246. Ok(())
  247. }
  248. async fn get_blind_signatures(
  249. &self,
  250. blinded_messages: &[PublicKey],
  251. ) -> Result<Vec<Option<BlindSignature>>, Self::Err> {
  252. let mut blinded_signatures = query(
  253. r#"SELECT
  254. keyset_id,
  255. amount,
  256. c,
  257. dleq_e,
  258. dleq_s,
  259. y
  260. FROM
  261. blind_signature
  262. WHERE y IN (:y)
  263. "#,
  264. )
  265. .bind_vec(
  266. ":y",
  267. blinded_messages
  268. .iter()
  269. .map(|y| y.to_bytes().to_vec())
  270. .collect(),
  271. )
  272. .fetch_all(&self.pool)
  273. .await?
  274. .into_iter()
  275. .map(|mut row| {
  276. Ok((
  277. column_as_string!(
  278. &row.pop().ok_or(Error::InvalidDbResponse)?,
  279. PublicKey::from_hex,
  280. PublicKey::from_slice
  281. ),
  282. sqlite_row_to_blind_signature(row)?,
  283. ))
  284. })
  285. .collect::<Result<HashMap<_, _>, Error>>()?;
  286. Ok(blinded_messages
  287. .iter()
  288. .map(|y| blinded_signatures.remove(y))
  289. .collect())
  290. }
  291. async fn add_protected_endpoints(
  292. &self,
  293. protected_endpoints: HashMap<ProtectedEndpoint, AuthRequired>,
  294. ) -> Result<(), Self::Err> {
  295. let transaction = self.pool.begin().await?;
  296. for (endpoint, auth) in protected_endpoints.iter() {
  297. if let Err(err) = query(
  298. r#"
  299. INSERT OR REPLACE INTO protected_endpoints
  300. (endpoint, auth)
  301. VALUES (:endpoint, :auth);
  302. "#,
  303. )
  304. .bind(":endpoint", serde_json::to_string(endpoint)?)
  305. .bind(":auth", serde_json::to_string(auth)?)
  306. .execute(&transaction)
  307. .await
  308. {
  309. tracing::debug!(
  310. "Attempting to add protected endpoint. Skipping.... {:?}",
  311. err
  312. );
  313. }
  314. }
  315. transaction.commit().await?;
  316. Ok(())
  317. }
  318. async fn remove_protected_endpoints(
  319. &self,
  320. protected_endpoints: Vec<ProtectedEndpoint>,
  321. ) -> Result<(), Self::Err> {
  322. query(r#"DELETE FROM protected_endpoints WHERE endpoint IN (:endpoints)"#)
  323. .bind_vec(
  324. ":endpoints",
  325. protected_endpoints
  326. .iter()
  327. .map(serde_json::to_string)
  328. .collect::<Result<_, _>>()?,
  329. )
  330. .execute(&self.pool)
  331. .await?;
  332. Ok(())
  333. }
  334. async fn get_auth_for_endpoint(
  335. &self,
  336. protected_endpoint: ProtectedEndpoint,
  337. ) -> Result<Option<AuthRequired>, Self::Err> {
  338. Ok(
  339. query(r#"SELECT auth FROM protected_endpoints WHERE endpoint = :endpoint"#)
  340. .bind(":endpoint", serde_json::to_string(&protected_endpoint)?)
  341. .pluck(&self.pool)
  342. .await?
  343. .map(|auth| {
  344. Ok::<_, Error>(column_as_string!(
  345. auth,
  346. serde_json::from_str,
  347. serde_json::from_slice
  348. ))
  349. })
  350. .transpose()?,
  351. )
  352. }
  353. async fn get_auth_for_endpoints(
  354. &self,
  355. ) -> Result<HashMap<ProtectedEndpoint, Option<AuthRequired>>, Self::Err> {
  356. Ok(query(r#"SELECT endpoint, auth FROM protected_endpoints"#)
  357. .fetch_all(&self.pool)
  358. .await?
  359. .into_iter()
  360. .map(|row| {
  361. let endpoint =
  362. column_as_string!(&row[0], serde_json::from_str, serde_json::from_slice);
  363. let auth = column_as_string!(&row[1], serde_json::from_str, serde_json::from_slice);
  364. Ok((endpoint, Some(auth)))
  365. })
  366. .collect::<Result<HashMap<_, _>, Error>>()?)
  367. }
  368. }