mod.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. //! SQLite Storage for CDK
  2. use std::cmp::Ordering;
  3. use std::collections::HashMap;
  4. use std::path::Path;
  5. use std::str::FromStr;
  6. use std::sync::Arc;
  7. use async_trait::async_trait;
  8. use cdk::cdk_database::MintDatabase;
  9. use cdk::dhke::hash_to_curve;
  10. use cdk::mint::{MintKeySetInfo, MintQuote};
  11. use cdk::nuts::{
  12. BlindSignature, CurrencyUnit, Id, MeltQuoteState, MintQuoteState, Proof, Proofs, PublicKey,
  13. State,
  14. };
  15. use cdk::{cdk_database, mint};
  16. use migrations::migrate_01_to_02;
  17. use redb::{Database, ReadableTable, TableDefinition};
  18. use tokio::sync::Mutex;
  19. use super::error::Error;
  20. use crate::migrations::migrate_00_to_01;
  21. use crate::mint::migrations::migrate_02_to_03;
  22. mod migrations;
  23. const ACTIVE_KEYSETS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("active_keysets");
  24. const KEYSETS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("keysets");
  25. const MINT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("mint_quotes");
  26. const MELT_QUOTES_TABLE: TableDefinition<&str, &str> = TableDefinition::new("melt_quotes");
  27. const PROOFS_TABLE: TableDefinition<[u8; 33], &str> = TableDefinition::new("proofs");
  28. const PROOFS_STATE_TABLE: TableDefinition<[u8; 33], &str> = TableDefinition::new("proofs_state");
  29. const CONFIG_TABLE: TableDefinition<&str, &str> = TableDefinition::new("config");
  30. // Key is hex blinded_message B_ value is blinded_signature
  31. const BLINDED_SIGNATURES: TableDefinition<[u8; 33], &str> =
  32. TableDefinition::new("blinded_signatures");
  33. const DATABASE_VERSION: u32 = 3;
  34. /// Mint Redbdatabase
  35. #[derive(Debug, Clone)]
  36. pub struct MintRedbDatabase {
  37. db: Arc<Mutex<Database>>,
  38. }
  39. impl MintRedbDatabase {
  40. /// Create new [`MintRedbDatabase`]
  41. pub fn new(path: &Path) -> Result<Self, Error> {
  42. {
  43. // Check database version
  44. let db = Arc::new(Database::create(path)?);
  45. // Check database version
  46. let read_txn = db.begin_read()?;
  47. let table = read_txn.open_table(CONFIG_TABLE);
  48. let db_version = match table {
  49. Ok(table) => table.get("db_version")?.map(|v| v.value().to_owned()),
  50. Err(_) => None,
  51. };
  52. match db_version {
  53. Some(db_version) => {
  54. let mut current_file_version = u32::from_str(&db_version)?;
  55. match current_file_version.cmp(&DATABASE_VERSION) {
  56. Ordering::Less => {
  57. tracing::info!(
  58. "Database needs to be upgraded at {} current is {}",
  59. current_file_version,
  60. DATABASE_VERSION
  61. );
  62. if current_file_version == 0 {
  63. current_file_version = migrate_00_to_01(Arc::clone(&db))?;
  64. }
  65. if current_file_version == 1 {
  66. current_file_version = migrate_01_to_02(Arc::clone(&db))?;
  67. }
  68. if current_file_version == 2 {
  69. current_file_version = migrate_02_to_03(Arc::clone(&db))?;
  70. }
  71. if current_file_version != DATABASE_VERSION {
  72. tracing::warn!(
  73. "Database upgrade did not complete at {} current is {}",
  74. current_file_version,
  75. DATABASE_VERSION
  76. );
  77. return Err(Error::UnknownDatabaseVersion);
  78. }
  79. let write_txn = db.begin_write()?;
  80. {
  81. let mut table = write_txn.open_table(CONFIG_TABLE)?;
  82. table
  83. .insert("db_version", DATABASE_VERSION.to_string().as_str())?;
  84. }
  85. write_txn.commit()?;
  86. }
  87. Ordering::Equal => {
  88. tracing::info!("Database is at current version {}", DATABASE_VERSION);
  89. }
  90. Ordering::Greater => {
  91. tracing::warn!(
  92. "Database upgrade did not complete at {} current is {}",
  93. current_file_version,
  94. DATABASE_VERSION
  95. );
  96. return Err(Error::UnknownDatabaseVersion);
  97. }
  98. }
  99. }
  100. None => {
  101. let write_txn = db.begin_write()?;
  102. {
  103. let mut table = write_txn.open_table(CONFIG_TABLE)?;
  104. // Open all tables to init a new db
  105. let _ = write_txn.open_table(ACTIVE_KEYSETS_TABLE)?;
  106. let _ = write_txn.open_table(KEYSETS_TABLE)?;
  107. let _ = write_txn.open_table(MINT_QUOTES_TABLE)?;
  108. let _ = write_txn.open_table(MELT_QUOTES_TABLE)?;
  109. let _ = write_txn.open_table(PROOFS_TABLE)?;
  110. let _ = write_txn.open_table(PROOFS_STATE_TABLE)?;
  111. let _ = write_txn.open_table(BLINDED_SIGNATURES)?;
  112. table.insert("db_version", DATABASE_VERSION.to_string().as_str())?;
  113. }
  114. write_txn.commit()?;
  115. }
  116. }
  117. drop(db);
  118. }
  119. let db = Database::create(path)?;
  120. Ok(Self {
  121. db: Arc::new(Mutex::new(db)),
  122. })
  123. }
  124. }
  125. #[async_trait]
  126. impl MintDatabase for MintRedbDatabase {
  127. type Err = cdk_database::Error;
  128. async fn set_active_keyset(&self, unit: CurrencyUnit, id: Id) -> Result<(), Self::Err> {
  129. let db = self.db.lock().await;
  130. let write_txn = db.begin_write().map_err(Error::from)?;
  131. {
  132. let mut table = write_txn
  133. .open_table(ACTIVE_KEYSETS_TABLE)
  134. .map_err(Error::from)?;
  135. table
  136. .insert(unit.to_string().as_str(), id.to_string().as_str())
  137. .map_err(Error::from)?;
  138. }
  139. write_txn.commit().map_err(Error::from)?;
  140. Ok(())
  141. }
  142. async fn get_active_keyset_id(&self, unit: &CurrencyUnit) -> Result<Option<Id>, Self::Err> {
  143. let db = self.db.lock().await;
  144. let read_txn = db.begin_read().map_err(Error::from)?;
  145. let table = read_txn
  146. .open_table(ACTIVE_KEYSETS_TABLE)
  147. .map_err(Error::from)?;
  148. if let Some(id) = table.get(unit.to_string().as_str()).map_err(Error::from)? {
  149. return Ok(Some(Id::from_str(id.value()).map_err(Error::from)?));
  150. }
  151. Ok(None)
  152. }
  153. async fn get_active_keysets(&self) -> Result<HashMap<CurrencyUnit, Id>, Self::Err> {
  154. let db = self.db.lock().await;
  155. let read_txn = db.begin_read().map_err(Error::from)?;
  156. let table = read_txn
  157. .open_table(ACTIVE_KEYSETS_TABLE)
  158. .map_err(Error::from)?;
  159. let mut active_keysets = HashMap::new();
  160. for (unit, id) in (table.iter().map_err(Error::from)?).flatten() {
  161. let unit = CurrencyUnit::from_str(unit.value())?;
  162. let id = Id::from_str(id.value()).map_err(Error::from)?;
  163. active_keysets.insert(unit, id);
  164. }
  165. Ok(active_keysets)
  166. }
  167. async fn add_keyset_info(&self, keyset: MintKeySetInfo) -> Result<(), Self::Err> {
  168. let db = self.db.lock().await;
  169. let write_txn = db.begin_write().map_err(Error::from)?;
  170. {
  171. let mut table = write_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
  172. table
  173. .insert(
  174. keyset.id.to_string().as_str(),
  175. serde_json::to_string(&keyset)
  176. .map_err(Error::from)?
  177. .as_str(),
  178. )
  179. .map_err(Error::from)?;
  180. }
  181. write_txn.commit().map_err(Error::from)?;
  182. Ok(())
  183. }
  184. async fn get_keyset_info(&self, keyset_id: &Id) -> Result<Option<MintKeySetInfo>, Self::Err> {
  185. let db = self.db.lock().await;
  186. let read_txn = db.begin_read().map_err(Error::from)?;
  187. let table = read_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
  188. match table
  189. .get(keyset_id.to_string().as_str())
  190. .map_err(Error::from)?
  191. {
  192. Some(keyset) => Ok(serde_json::from_str(keyset.value()).map_err(Error::from)?),
  193. None => Ok(None),
  194. }
  195. }
  196. async fn get_keyset_infos(&self) -> Result<Vec<MintKeySetInfo>, Self::Err> {
  197. let db = self.db.lock().await;
  198. let read_txn = db.begin_read().map_err(Error::from)?;
  199. let table = read_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
  200. let mut keysets = Vec::new();
  201. for (_id, keyset) in (table.iter().map_err(Error::from)?).flatten() {
  202. let keyset = serde_json::from_str(keyset.value()).map_err(Error::from)?;
  203. keysets.push(keyset)
  204. }
  205. Ok(keysets)
  206. }
  207. async fn add_mint_quote(&self, quote: MintQuote) -> Result<(), Self::Err> {
  208. let db = self.db.lock().await;
  209. let write_txn = db.begin_write().map_err(Error::from)?;
  210. {
  211. let mut table = write_txn
  212. .open_table(MINT_QUOTES_TABLE)
  213. .map_err(Error::from)?;
  214. table
  215. .insert(
  216. quote.id.as_str(),
  217. serde_json::to_string(&quote).map_err(Error::from)?.as_str(),
  218. )
  219. .map_err(Error::from)?;
  220. }
  221. write_txn.commit().map_err(Error::from)?;
  222. Ok(())
  223. }
  224. async fn get_mint_quote(&self, quote_id: &str) -> Result<Option<MintQuote>, Self::Err> {
  225. let db = self.db.lock().await;
  226. let read_txn = db.begin_read().map_err(Error::from)?;
  227. let table = read_txn
  228. .open_table(MINT_QUOTES_TABLE)
  229. .map_err(Error::from)?;
  230. match table.get(quote_id).map_err(Error::from)? {
  231. Some(quote) => Ok(serde_json::from_str(quote.value()).map_err(Error::from)?),
  232. None => Ok(None),
  233. }
  234. }
  235. async fn update_mint_quote_state(
  236. &self,
  237. quote_id: &str,
  238. state: MintQuoteState,
  239. ) -> Result<MintQuoteState, Self::Err> {
  240. let db = self.db.lock().await;
  241. let mut mint_quote: MintQuote;
  242. {
  243. let read_txn = db.begin_read().map_err(Error::from)?;
  244. let table = read_txn
  245. .open_table(MINT_QUOTES_TABLE)
  246. .map_err(Error::from)?;
  247. let quote_guard = table
  248. .get(quote_id)
  249. .map_err(Error::from)?
  250. .ok_or(Error::UnknownMintInfo)?;
  251. let quote = quote_guard.value();
  252. mint_quote = serde_json::from_str(quote).map_err(Error::from)?;
  253. }
  254. let current_state = mint_quote.state;
  255. mint_quote.state = state;
  256. let write_txn = db.begin_write().map_err(Error::from)?;
  257. {
  258. let mut table = write_txn
  259. .open_table(MINT_QUOTES_TABLE)
  260. .map_err(Error::from)?;
  261. table
  262. .insert(
  263. quote_id,
  264. serde_json::to_string(&mint_quote)
  265. .map_err(Error::from)?
  266. .as_str(),
  267. )
  268. .map_err(Error::from)?;
  269. }
  270. write_txn.commit().map_err(Error::from)?;
  271. Ok(current_state)
  272. }
  273. async fn get_mint_quote_by_request(
  274. &self,
  275. request: &str,
  276. ) -> Result<Option<MintQuote>, Self::Err> {
  277. let quotes = self.get_mint_quotes().await?;
  278. let quote = quotes
  279. .into_iter()
  280. .filter(|q| q.request.eq(request))
  281. .collect::<Vec<MintQuote>>()
  282. .first()
  283. .cloned();
  284. Ok(quote)
  285. }
  286. async fn get_mint_quote_by_request_lookup_id(
  287. &self,
  288. request_lookup_id: &str,
  289. ) -> Result<Option<MintQuote>, Self::Err> {
  290. let quotes = self.get_mint_quotes().await?;
  291. let quote = quotes
  292. .into_iter()
  293. .filter(|q| q.request_lookup_id.eq(request_lookup_id))
  294. .collect::<Vec<MintQuote>>()
  295. .first()
  296. .cloned();
  297. Ok(quote)
  298. }
  299. async fn get_mint_quotes(&self) -> Result<Vec<MintQuote>, Self::Err> {
  300. let db = self.db.lock().await;
  301. let read_txn = db.begin_read().map_err(Error::from)?;
  302. let table = read_txn
  303. .open_table(MINT_QUOTES_TABLE)
  304. .map_err(Error::from)?;
  305. let mut quotes = Vec::new();
  306. for (_id, quote) in (table.iter().map_err(Error::from)?).flatten() {
  307. let quote = serde_json::from_str(quote.value()).map_err(Error::from)?;
  308. quotes.push(quote)
  309. }
  310. Ok(quotes)
  311. }
  312. async fn remove_mint_quote(&self, quote_id: &str) -> Result<(), Self::Err> {
  313. let db = self.db.lock().await;
  314. let write_txn = db.begin_write().map_err(Error::from)?;
  315. {
  316. let mut table = write_txn
  317. .open_table(MINT_QUOTES_TABLE)
  318. .map_err(Error::from)?;
  319. table.remove(quote_id).map_err(Error::from)?;
  320. }
  321. write_txn.commit().map_err(Error::from)?;
  322. Ok(())
  323. }
  324. async fn add_melt_quote(&self, quote: mint::MeltQuote) -> Result<(), Self::Err> {
  325. let db = self.db.lock().await;
  326. let write_txn = db.begin_write().map_err(Error::from)?;
  327. {
  328. let mut table = write_txn
  329. .open_table(MELT_QUOTES_TABLE)
  330. .map_err(Error::from)?;
  331. table
  332. .insert(
  333. quote.id.as_str(),
  334. serde_json::to_string(&quote).map_err(Error::from)?.as_str(),
  335. )
  336. .map_err(Error::from)?;
  337. }
  338. write_txn.commit().map_err(Error::from)?;
  339. Ok(())
  340. }
  341. async fn get_melt_quote(&self, quote_id: &str) -> Result<Option<mint::MeltQuote>, Self::Err> {
  342. let db = self.db.lock().await;
  343. let read_txn = db.begin_read().map_err(Error::from)?;
  344. let table = read_txn
  345. .open_table(MELT_QUOTES_TABLE)
  346. .map_err(Error::from)?;
  347. let quote = table.get(quote_id).map_err(Error::from)?;
  348. Ok(quote.map(|q| serde_json::from_str(q.value()).unwrap()))
  349. }
  350. async fn update_melt_quote_state(
  351. &self,
  352. quote_id: &str,
  353. state: MeltQuoteState,
  354. ) -> Result<MeltQuoteState, Self::Err> {
  355. let db = self.db.lock().await;
  356. let mut melt_quote: mint::MeltQuote;
  357. {
  358. let read_txn = db.begin_read().map_err(Error::from)?;
  359. let table = read_txn
  360. .open_table(MELT_QUOTES_TABLE)
  361. .map_err(Error::from)?;
  362. let quote_guard = table
  363. .get(quote_id)
  364. .map_err(Error::from)?
  365. .ok_or(Error::UnknownMintInfo)?;
  366. let quote = quote_guard.value();
  367. melt_quote = serde_json::from_str(quote).map_err(Error::from)?;
  368. }
  369. let current_state = melt_quote.state;
  370. melt_quote.state = state;
  371. let write_txn = db.begin_write().map_err(Error::from)?;
  372. {
  373. let mut table = write_txn
  374. .open_table(MELT_QUOTES_TABLE)
  375. .map_err(Error::from)?;
  376. table
  377. .insert(
  378. quote_id,
  379. serde_json::to_string(&melt_quote)
  380. .map_err(Error::from)?
  381. .as_str(),
  382. )
  383. .map_err(Error::from)?;
  384. }
  385. write_txn.commit().map_err(Error::from)?;
  386. Ok(current_state)
  387. }
  388. async fn get_melt_quotes(&self) -> Result<Vec<mint::MeltQuote>, Self::Err> {
  389. let db = self.db.lock().await;
  390. let read_txn = db.begin_read().map_err(Error::from)?;
  391. let table = read_txn
  392. .open_table(MELT_QUOTES_TABLE)
  393. .map_err(Error::from)?;
  394. let mut quotes = Vec::new();
  395. for (_id, quote) in (table.iter().map_err(Error::from)?).flatten() {
  396. let quote = serde_json::from_str(quote.value()).map_err(Error::from)?;
  397. quotes.push(quote)
  398. }
  399. Ok(quotes)
  400. }
  401. async fn remove_melt_quote(&self, quote_id: &str) -> Result<(), Self::Err> {
  402. let db = self.db.lock().await;
  403. let write_txn = db.begin_write().map_err(Error::from)?;
  404. {
  405. let mut table = write_txn
  406. .open_table(MELT_QUOTES_TABLE)
  407. .map_err(Error::from)?;
  408. table.remove(quote_id).map_err(Error::from)?;
  409. }
  410. write_txn.commit().map_err(Error::from)?;
  411. Ok(())
  412. }
  413. async fn add_proofs(&self, proofs: Proofs) -> Result<(), Self::Err> {
  414. let db = self.db.lock().await;
  415. let write_txn = db.begin_write().map_err(Error::from)?;
  416. {
  417. let mut table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
  418. for proof in proofs {
  419. let y: PublicKey = hash_to_curve(&proof.secret.to_bytes()).map_err(Error::from)?;
  420. if table.get(y.to_bytes()).map_err(Error::from)?.is_none() {
  421. table
  422. .insert(
  423. y.to_bytes(),
  424. serde_json::to_string(&proof).map_err(Error::from)?.as_str(),
  425. )
  426. .map_err(Error::from)?;
  427. }
  428. }
  429. }
  430. write_txn.commit().map_err(Error::from)?;
  431. Ok(())
  432. }
  433. async fn get_proofs_by_ys(&self, ys: &[PublicKey]) -> Result<Vec<Option<Proof>>, Self::Err> {
  434. let db = self.db.lock().await;
  435. let read_txn = db.begin_read().map_err(Error::from)?;
  436. let table = read_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
  437. let mut proofs = Vec::with_capacity(ys.len());
  438. for y in ys {
  439. match table.get(y.to_bytes()).map_err(Error::from)? {
  440. Some(proof) => proofs.push(Some(
  441. serde_json::from_str(proof.value()).map_err(Error::from)?,
  442. )),
  443. None => proofs.push(None),
  444. }
  445. }
  446. Ok(proofs)
  447. }
  448. async fn get_proofs_states(&self, ys: &[PublicKey]) -> Result<Vec<Option<State>>, Self::Err> {
  449. let db = self.db.lock().await;
  450. let read_txn = db.begin_read().map_err(Error::from)?;
  451. let table = read_txn
  452. .open_table(PROOFS_STATE_TABLE)
  453. .map_err(Error::from)?;
  454. let mut states = Vec::with_capacity(ys.len());
  455. for y in ys {
  456. match table.get(y.to_bytes()).map_err(Error::from)? {
  457. Some(state) => states.push(Some(
  458. serde_json::from_str(state.value()).map_err(Error::from)?,
  459. )),
  460. None => states.push(None),
  461. }
  462. }
  463. Ok(states)
  464. }
  465. async fn update_proofs_states(
  466. &self,
  467. ys: &[PublicKey],
  468. proofs_state: State,
  469. ) -> Result<Vec<Option<State>>, Self::Err> {
  470. let db = self.db.lock().await;
  471. let write_txn = db.begin_write().map_err(Error::from)?;
  472. let mut states = Vec::with_capacity(ys.len());
  473. let state_str = serde_json::to_string(&proofs_state).map_err(Error::from)?;
  474. {
  475. let mut table = write_txn
  476. .open_table(PROOFS_STATE_TABLE)
  477. .map_err(Error::from)?;
  478. for y in ys {
  479. let current_state;
  480. {
  481. match table.get(y.to_bytes()).map_err(Error::from)? {
  482. Some(state) => {
  483. current_state =
  484. Some(serde_json::from_str(state.value()).map_err(Error::from)?)
  485. }
  486. None => current_state = None,
  487. }
  488. }
  489. states.push(current_state);
  490. if current_state != Some(State::Spent) {
  491. table
  492. .insert(y.to_bytes(), state_str.as_str())
  493. .map_err(Error::from)?;
  494. }
  495. }
  496. }
  497. write_txn.commit().map_err(Error::from)?;
  498. Ok(states)
  499. }
  500. async fn add_blind_signatures(
  501. &self,
  502. blinded_messages: &[PublicKey],
  503. blind_signatures: &[BlindSignature],
  504. ) -> Result<(), Self::Err> {
  505. let db = self.db.lock().await;
  506. let write_txn = db.begin_write().map_err(Error::from)?;
  507. {
  508. let mut table = write_txn
  509. .open_table(BLINDED_SIGNATURES)
  510. .map_err(Error::from)?;
  511. for (blinded_message, blind_signature) in blinded_messages.iter().zip(blind_signatures)
  512. {
  513. table
  514. .insert(
  515. blinded_message.to_bytes(),
  516. serde_json::to_string(&blind_signature)
  517. .map_err(Error::from)?
  518. .as_str(),
  519. )
  520. .map_err(Error::from)?;
  521. }
  522. }
  523. write_txn.commit().map_err(Error::from)?;
  524. Ok(())
  525. }
  526. async fn get_blinded_signatures(
  527. &self,
  528. blinded_messages: &[PublicKey],
  529. ) -> Result<Vec<Option<BlindSignature>>, Self::Err> {
  530. let db = self.db.lock().await;
  531. let read_txn = db.begin_read().map_err(Error::from)?;
  532. let table = read_txn
  533. .open_table(BLINDED_SIGNATURES)
  534. .map_err(Error::from)?;
  535. let mut signatures = Vec::with_capacity(blinded_messages.len());
  536. for blinded_message in blinded_messages {
  537. match table.get(blinded_message.to_bytes()).map_err(Error::from)? {
  538. Some(blind_signature) => signatures.push(Some(
  539. serde_json::from_str(blind_signature.value()).map_err(Error::from)?,
  540. )),
  541. None => signatures.push(None),
  542. }
  543. }
  544. Ok(signatures)
  545. }
  546. }