mod.rs 12 KB

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