mod.rs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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_common::common::{LnKey, QuoteTTL};
  9. use cdk_common::database::{self, MintDatabase};
  10. use cdk_common::dhke::hash_to_curve;
  11. use cdk_common::mint::{self, MintKeySetInfo, MintQuote};
  12. use cdk_common::nut00::ProofsMethods;
  13. use cdk_common::{
  14. BlindSignature, CurrencyUnit, Id, MeltBolt11Request, MeltQuoteState, MintInfo, MintQuoteState,
  15. Proof, Proofs, PublicKey, State,
  16. };
  17. use migrations::{migrate_01_to_02, migrate_04_to_05};
  18. use redb::{Database, MultimapTableDefinition, ReadableTable, TableDefinition};
  19. use uuid::Uuid;
  20. use super::error::Error;
  21. use crate::migrations::migrate_00_to_01;
  22. use crate::mint::migrations::{migrate_02_to_03, migrate_03_to_04};
  23. mod migrations;
  24. const ACTIVE_KEYSETS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("active_keysets");
  25. const KEYSETS_TABLE: TableDefinition<&str, &str> = TableDefinition::new("keysets");
  26. const MINT_QUOTES_TABLE: TableDefinition<[u8; 16], &str> = TableDefinition::new("mint_quotes");
  27. const MELT_QUOTES_TABLE: TableDefinition<[u8; 16], &str> = TableDefinition::new("melt_quotes");
  28. const PROOFS_TABLE: TableDefinition<[u8; 33], &str> = TableDefinition::new("proofs");
  29. const PROOFS_STATE_TABLE: TableDefinition<[u8; 33], &str> = TableDefinition::new("proofs_state");
  30. const CONFIG_TABLE: TableDefinition<&str, &str> = TableDefinition::new("config");
  31. // Key is hex blinded_message B_ value is blinded_signature
  32. const BLINDED_SIGNATURES: TableDefinition<[u8; 33], &str> =
  33. TableDefinition::new("blinded_signatures");
  34. const QUOTE_PROOFS_TABLE: MultimapTableDefinition<[u8; 16], [u8; 33]> =
  35. MultimapTableDefinition::new("quote_proofs");
  36. const QUOTE_SIGNATURES_TABLE: MultimapTableDefinition<[u8; 16], [u8; 33]> =
  37. MultimapTableDefinition::new("quote_signatures");
  38. const MELT_REQUESTS: TableDefinition<[u8; 16], (&str, &str)> =
  39. TableDefinition::new("melt_requests");
  40. const DATABASE_VERSION: u32 = 5;
  41. /// Mint Redbdatabase
  42. #[derive(Debug, Clone)]
  43. pub struct MintRedbDatabase {
  44. db: Arc<Database>,
  45. }
  46. impl MintRedbDatabase {
  47. /// Create new [`MintRedbDatabase`]
  48. pub fn new(path: &Path) -> Result<Self, Error> {
  49. {
  50. // Check database version
  51. let db = Arc::new(Database::create(path)?);
  52. // Check database version
  53. let read_txn = db.begin_read()?;
  54. let table = read_txn.open_table(CONFIG_TABLE);
  55. let db_version = match table {
  56. Ok(table) => table.get("db_version")?.map(|v| v.value().to_owned()),
  57. Err(_) => None,
  58. };
  59. match db_version {
  60. Some(db_version) => {
  61. let mut current_file_version = u32::from_str(&db_version)?;
  62. match current_file_version.cmp(&DATABASE_VERSION) {
  63. Ordering::Less => {
  64. tracing::info!(
  65. "Database needs to be upgraded at {} current is {}",
  66. current_file_version,
  67. DATABASE_VERSION
  68. );
  69. if current_file_version == 0 {
  70. current_file_version = migrate_00_to_01(Arc::clone(&db))?;
  71. }
  72. if current_file_version == 1 {
  73. current_file_version = migrate_01_to_02(Arc::clone(&db))?;
  74. }
  75. if current_file_version == 2 {
  76. current_file_version = migrate_02_to_03(Arc::clone(&db))?;
  77. }
  78. if current_file_version == 3 {
  79. current_file_version = migrate_03_to_04(Arc::clone(&db))?;
  80. }
  81. if current_file_version == 4 {
  82. current_file_version = migrate_04_to_05(Arc::clone(&db))?;
  83. }
  84. if current_file_version != DATABASE_VERSION {
  85. tracing::warn!(
  86. "Database upgrade did not complete at {} current is {}",
  87. current_file_version,
  88. DATABASE_VERSION
  89. );
  90. return Err(Error::UnknownDatabaseVersion);
  91. }
  92. let write_txn = db.begin_write()?;
  93. {
  94. let mut table = write_txn.open_table(CONFIG_TABLE)?;
  95. table
  96. .insert("db_version", DATABASE_VERSION.to_string().as_str())?;
  97. }
  98. write_txn.commit()?;
  99. }
  100. Ordering::Equal => {
  101. tracing::info!("Database is at current version {}", DATABASE_VERSION);
  102. }
  103. Ordering::Greater => {
  104. tracing::warn!(
  105. "Database upgrade did not complete at {} current is {}",
  106. current_file_version,
  107. DATABASE_VERSION
  108. );
  109. return Err(Error::UnknownDatabaseVersion);
  110. }
  111. }
  112. }
  113. None => {
  114. let write_txn = db.begin_write()?;
  115. {
  116. let mut table = write_txn.open_table(CONFIG_TABLE)?;
  117. // Open all tables to init a new db
  118. let _ = write_txn.open_table(ACTIVE_KEYSETS_TABLE)?;
  119. let _ = write_txn.open_table(KEYSETS_TABLE)?;
  120. let _ = write_txn.open_table(MINT_QUOTES_TABLE)?;
  121. let _ = write_txn.open_table(MELT_QUOTES_TABLE)?;
  122. let _ = write_txn.open_table(PROOFS_TABLE)?;
  123. let _ = write_txn.open_table(PROOFS_STATE_TABLE)?;
  124. let _ = write_txn.open_table(BLINDED_SIGNATURES)?;
  125. let _ = write_txn.open_multimap_table(QUOTE_PROOFS_TABLE)?;
  126. let _ = write_txn.open_multimap_table(QUOTE_SIGNATURES_TABLE)?;
  127. table.insert("db_version", DATABASE_VERSION.to_string().as_str())?;
  128. }
  129. write_txn.commit()?;
  130. }
  131. }
  132. drop(db);
  133. }
  134. let db = Database::create(path)?;
  135. Ok(Self { db: Arc::new(db) })
  136. }
  137. }
  138. #[async_trait]
  139. impl MintDatabase for MintRedbDatabase {
  140. type Err = database::Error;
  141. async fn set_active_keyset(&self, unit: CurrencyUnit, id: Id) -> Result<(), Self::Err> {
  142. let write_txn = self.db.begin_write().map_err(Error::from)?;
  143. {
  144. let mut table = write_txn
  145. .open_table(ACTIVE_KEYSETS_TABLE)
  146. .map_err(Error::from)?;
  147. table
  148. .insert(unit.to_string().as_str(), id.to_string().as_str())
  149. .map_err(Error::from)?;
  150. }
  151. write_txn.commit().map_err(Error::from)?;
  152. Ok(())
  153. }
  154. async fn get_active_keyset_id(&self, unit: &CurrencyUnit) -> Result<Option<Id>, Self::Err> {
  155. let read_txn = self.db.begin_read().map_err(Error::from)?;
  156. let table = read_txn
  157. .open_table(ACTIVE_KEYSETS_TABLE)
  158. .map_err(Error::from)?;
  159. if let Some(id) = table.get(unit.to_string().as_str()).map_err(Error::from)? {
  160. return Ok(Some(Id::from_str(id.value()).map_err(Error::from)?));
  161. }
  162. Ok(None)
  163. }
  164. async fn get_active_keysets(&self) -> Result<HashMap<CurrencyUnit, Id>, Self::Err> {
  165. let read_txn = self.db.begin_read().map_err(Error::from)?;
  166. let table = read_txn
  167. .open_table(ACTIVE_KEYSETS_TABLE)
  168. .map_err(Error::from)?;
  169. let mut active_keysets = HashMap::new();
  170. for (unit, id) in (table.iter().map_err(Error::from)?).flatten() {
  171. let unit = CurrencyUnit::from_str(unit.value())?;
  172. let id = Id::from_str(id.value()).map_err(Error::from)?;
  173. active_keysets.insert(unit, id);
  174. }
  175. Ok(active_keysets)
  176. }
  177. async fn add_keyset_info(&self, keyset: MintKeySetInfo) -> Result<(), Self::Err> {
  178. let write_txn = self.db.begin_write().map_err(Error::from)?;
  179. {
  180. let mut table = write_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
  181. table
  182. .insert(
  183. keyset.id.to_string().as_str(),
  184. serde_json::to_string(&keyset)
  185. .map_err(Error::from)?
  186. .as_str(),
  187. )
  188. .map_err(Error::from)?;
  189. }
  190. write_txn.commit().map_err(Error::from)?;
  191. Ok(())
  192. }
  193. async fn get_keyset_info(&self, keyset_id: &Id) -> Result<Option<MintKeySetInfo>, Self::Err> {
  194. let read_txn = self.db.begin_read().map_err(Error::from)?;
  195. let table = read_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
  196. match table
  197. .get(keyset_id.to_string().as_str())
  198. .map_err(Error::from)?
  199. {
  200. Some(keyset) => Ok(serde_json::from_str(keyset.value()).map_err(Error::from)?),
  201. None => Ok(None),
  202. }
  203. }
  204. async fn get_keyset_infos(&self) -> Result<Vec<MintKeySetInfo>, Self::Err> {
  205. let read_txn = self.db.begin_read().map_err(Error::from)?;
  206. let table = read_txn.open_table(KEYSETS_TABLE).map_err(Error::from)?;
  207. let mut keysets = Vec::new();
  208. for (_id, keyset) in (table.iter().map_err(Error::from)?).flatten() {
  209. let keyset = serde_json::from_str(keyset.value()).map_err(Error::from)?;
  210. keysets.push(keyset)
  211. }
  212. Ok(keysets)
  213. }
  214. async fn add_mint_quote(&self, quote: MintQuote) -> Result<(), Self::Err> {
  215. let write_txn = self.db.begin_write().map_err(Error::from)?;
  216. {
  217. let mut table = write_txn
  218. .open_table(MINT_QUOTES_TABLE)
  219. .map_err(Error::from)?;
  220. table
  221. .insert(
  222. quote.id.as_bytes(),
  223. serde_json::to_string(&quote).map_err(Error::from)?.as_str(),
  224. )
  225. .map_err(Error::from)?;
  226. }
  227. write_txn.commit().map_err(Error::from)?;
  228. Ok(())
  229. }
  230. async fn get_mint_quote(&self, quote_id: &Uuid) -> Result<Option<MintQuote>, Self::Err> {
  231. let read_txn = self.db.begin_read().map_err(Error::from)?;
  232. let table = read_txn
  233. .open_table(MINT_QUOTES_TABLE)
  234. .map_err(Error::from)?;
  235. match table.get(quote_id.as_bytes()).map_err(Error::from)? {
  236. Some(quote) => Ok(serde_json::from_str(quote.value()).map_err(Error::from)?),
  237. None => Ok(None),
  238. }
  239. }
  240. async fn update_mint_quote_state(
  241. &self,
  242. quote_id: &Uuid,
  243. state: MintQuoteState,
  244. ) -> Result<MintQuoteState, Self::Err> {
  245. let write_txn = self.db.begin_write().map_err(Error::from)?;
  246. let current_state;
  247. {
  248. let mut mint_quote: MintQuote;
  249. let mut table = write_txn
  250. .open_table(MINT_QUOTES_TABLE)
  251. .map_err(Error::from)?;
  252. {
  253. let quote_guard = table
  254. .get(quote_id.as_bytes())
  255. .map_err(Error::from)?
  256. .ok_or(Error::UnknownQuote)?;
  257. let quote = quote_guard.value();
  258. mint_quote = serde_json::from_str(quote).map_err(Error::from)?;
  259. }
  260. current_state = mint_quote.state;
  261. mint_quote.state = state;
  262. {
  263. table
  264. .insert(
  265. quote_id.as_bytes(),
  266. serde_json::to_string(&mint_quote)
  267. .map_err(Error::from)?
  268. .as_str(),
  269. )
  270. .map_err(Error::from)?;
  271. }
  272. }
  273. write_txn.commit().map_err(Error::from)?;
  274. Ok(current_state)
  275. }
  276. async fn get_mint_quote_by_request(
  277. &self,
  278. request: &str,
  279. ) -> Result<Option<MintQuote>, Self::Err> {
  280. let quotes = self.get_mint_quotes().await?;
  281. let quote = quotes
  282. .into_iter()
  283. .filter(|q| q.request.eq(request))
  284. .collect::<Vec<MintQuote>>()
  285. .first()
  286. .cloned();
  287. Ok(quote)
  288. }
  289. async fn get_mint_quote_by_request_lookup_id(
  290. &self,
  291. request_lookup_id: &str,
  292. ) -> Result<Option<MintQuote>, Self::Err> {
  293. let quotes = self.get_mint_quotes().await?;
  294. let quote = quotes
  295. .into_iter()
  296. .filter(|q| q.request_lookup_id.eq(request_lookup_id))
  297. .collect::<Vec<MintQuote>>()
  298. .first()
  299. .cloned();
  300. Ok(quote)
  301. }
  302. async fn get_mint_quotes(&self) -> Result<Vec<MintQuote>, Self::Err> {
  303. let read_txn = self.db.begin_read().map_err(Error::from)?;
  304. let table = read_txn
  305. .open_table(MINT_QUOTES_TABLE)
  306. .map_err(Error::from)?;
  307. let mut quotes = Vec::new();
  308. for (_id, quote) in (table.iter().map_err(Error::from)?).flatten() {
  309. let quote = serde_json::from_str(quote.value()).map_err(Error::from)?;
  310. quotes.push(quote)
  311. }
  312. Ok(quotes)
  313. }
  314. async fn get_mint_quotes_with_state(
  315. &self,
  316. state: MintQuoteState,
  317. ) -> Result<Vec<MintQuote>, Self::Err> {
  318. let read_txn = self.db.begin_read().map_err(Error::from)?;
  319. let table = read_txn
  320. .open_table(MINT_QUOTES_TABLE)
  321. .map_err(Error::from)?;
  322. let mut quotes = Vec::new();
  323. for (_id, quote) in (table.iter().map_err(Error::from)?).flatten() {
  324. let quote: MintQuote = serde_json::from_str(quote.value()).map_err(Error::from)?;
  325. if quote.state == state {
  326. quotes.push(quote)
  327. }
  328. }
  329. Ok(quotes)
  330. }
  331. async fn remove_mint_quote(&self, quote_id: &Uuid) -> Result<(), Self::Err> {
  332. let write_txn = self.db.begin_write().map_err(Error::from)?;
  333. {
  334. let mut table = write_txn
  335. .open_table(MINT_QUOTES_TABLE)
  336. .map_err(Error::from)?;
  337. table.remove(quote_id.as_bytes()).map_err(Error::from)?;
  338. }
  339. write_txn.commit().map_err(Error::from)?;
  340. Ok(())
  341. }
  342. async fn add_melt_quote(&self, quote: mint::MeltQuote) -> Result<(), Self::Err> {
  343. let write_txn = self.db.begin_write().map_err(Error::from)?;
  344. {
  345. let mut table = write_txn
  346. .open_table(MELT_QUOTES_TABLE)
  347. .map_err(Error::from)?;
  348. table
  349. .insert(
  350. quote.id.as_bytes(),
  351. serde_json::to_string(&quote).map_err(Error::from)?.as_str(),
  352. )
  353. .map_err(Error::from)?;
  354. }
  355. write_txn.commit().map_err(Error::from)?;
  356. Ok(())
  357. }
  358. async fn get_melt_quote(&self, quote_id: &Uuid) -> Result<Option<mint::MeltQuote>, Self::Err> {
  359. let read_txn = self.db.begin_read().map_err(Error::from)?;
  360. let table = read_txn
  361. .open_table(MELT_QUOTES_TABLE)
  362. .map_err(Error::from)?;
  363. let quote = table.get(quote_id.as_bytes()).map_err(Error::from)?;
  364. Ok(quote.map(|q| serde_json::from_str(q.value()).unwrap()))
  365. }
  366. async fn update_melt_quote_state(
  367. &self,
  368. quote_id: &Uuid,
  369. state: MeltQuoteState,
  370. ) -> Result<MeltQuoteState, Self::Err> {
  371. let write_txn = self.db.begin_write().map_err(Error::from)?;
  372. let current_state;
  373. {
  374. let mut melt_quote: mint::MeltQuote;
  375. let mut table = write_txn
  376. .open_table(MELT_QUOTES_TABLE)
  377. .map_err(Error::from)?;
  378. {
  379. let quote_guard = table
  380. .get(quote_id.as_bytes())
  381. .map_err(Error::from)?
  382. .ok_or(Error::UnknownQuote)?;
  383. let quote = quote_guard.value();
  384. melt_quote = serde_json::from_str(quote).map_err(Error::from)?;
  385. }
  386. current_state = melt_quote.state;
  387. melt_quote.state = state;
  388. {
  389. table
  390. .insert(
  391. quote_id.as_bytes(),
  392. serde_json::to_string(&melt_quote)
  393. .map_err(Error::from)?
  394. .as_str(),
  395. )
  396. .map_err(Error::from)?;
  397. }
  398. }
  399. write_txn.commit().map_err(Error::from)?;
  400. Ok(current_state)
  401. }
  402. async fn get_melt_quotes(&self) -> Result<Vec<mint::MeltQuote>, Self::Err> {
  403. let read_txn = self.db.begin_read().map_err(Error::from)?;
  404. let table = read_txn
  405. .open_table(MELT_QUOTES_TABLE)
  406. .map_err(Error::from)?;
  407. let mut quotes = Vec::new();
  408. for (_id, quote) in (table.iter().map_err(Error::from)?).flatten() {
  409. let quote = serde_json::from_str(quote.value()).map_err(Error::from)?;
  410. quotes.push(quote)
  411. }
  412. Ok(quotes)
  413. }
  414. async fn remove_melt_quote(&self, quote_id: &Uuid) -> Result<(), Self::Err> {
  415. let write_txn = self.db.begin_write().map_err(Error::from)?;
  416. {
  417. let mut table = write_txn
  418. .open_table(MELT_QUOTES_TABLE)
  419. .map_err(Error::from)?;
  420. table.remove(quote_id.as_bytes()).map_err(Error::from)?;
  421. }
  422. write_txn.commit().map_err(Error::from)?;
  423. Ok(())
  424. }
  425. async fn add_proofs(&self, proofs: Proofs, quote_id: Option<Uuid>) -> Result<(), Self::Err> {
  426. let write_txn = self.db.begin_write().map_err(Error::from)?;
  427. {
  428. let mut table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
  429. let mut quote_proofs_table = write_txn
  430. .open_multimap_table(QUOTE_PROOFS_TABLE)
  431. .map_err(Error::from)?;
  432. for proof in proofs {
  433. let y: PublicKey = hash_to_curve(&proof.secret.to_bytes()).map_err(Error::from)?;
  434. let y = y.to_bytes();
  435. if table.get(y).map_err(Error::from)?.is_none() {
  436. table
  437. .insert(
  438. y,
  439. serde_json::to_string(&proof).map_err(Error::from)?.as_str(),
  440. )
  441. .map_err(Error::from)?;
  442. }
  443. if let Some(quote_id) = &quote_id {
  444. quote_proofs_table
  445. .insert(quote_id.as_bytes(), y)
  446. .map_err(Error::from)?;
  447. }
  448. }
  449. }
  450. write_txn.commit().map_err(Error::from)?;
  451. Ok(())
  452. }
  453. async fn remove_proofs(
  454. &self,
  455. ys: &[PublicKey],
  456. quote_id: Option<Uuid>,
  457. ) -> Result<(), Self::Err> {
  458. let write_txn = self.db.begin_write().map_err(Error::from)?;
  459. {
  460. let mut proofs_table = write_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
  461. for y in ys {
  462. proofs_table.remove(&y.to_bytes()).map_err(Error::from)?;
  463. }
  464. }
  465. {
  466. let mut proof_state_table = write_txn
  467. .open_table(PROOFS_STATE_TABLE)
  468. .map_err(Error::from)?;
  469. for y in ys {
  470. proof_state_table
  471. .remove(&y.to_bytes())
  472. .map_err(Error::from)?;
  473. }
  474. }
  475. if let Some(quote_id) = quote_id {
  476. let mut quote_proofs_table = write_txn
  477. .open_multimap_table(QUOTE_PROOFS_TABLE)
  478. .map_err(Error::from)?;
  479. quote_proofs_table
  480. .remove_all(quote_id.as_bytes())
  481. .map_err(Error::from)?;
  482. }
  483. write_txn.commit().map_err(Error::from)?;
  484. Ok(())
  485. }
  486. async fn get_proofs_by_ys(&self, ys: &[PublicKey]) -> Result<Vec<Option<Proof>>, Self::Err> {
  487. let read_txn = self.db.begin_read().map_err(Error::from)?;
  488. let table = read_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
  489. let mut proofs = Vec::with_capacity(ys.len());
  490. for y in ys {
  491. match table.get(y.to_bytes()).map_err(Error::from)? {
  492. Some(proof) => proofs.push(Some(
  493. serde_json::from_str(proof.value()).map_err(Error::from)?,
  494. )),
  495. None => proofs.push(None),
  496. }
  497. }
  498. Ok(proofs)
  499. }
  500. async fn get_proof_ys_by_quote_id(&self, quote_id: &Uuid) -> Result<Vec<PublicKey>, Self::Err> {
  501. let read_txn = self.db.begin_read().map_err(Error::from)?;
  502. let table = read_txn
  503. .open_multimap_table(QUOTE_PROOFS_TABLE)
  504. .map_err(Error::from)?;
  505. let ys = table.get(quote_id.as_bytes()).map_err(Error::from)?;
  506. let proof_ys = ys.fold(Vec::new(), |mut acc, y| {
  507. if let Ok(y) = y {
  508. if let Ok(pubkey) = PublicKey::from_slice(&y.value()) {
  509. acc.push(pubkey);
  510. }
  511. }
  512. acc
  513. });
  514. Ok(proof_ys)
  515. }
  516. async fn get_proofs_states(&self, ys: &[PublicKey]) -> Result<Vec<Option<State>>, Self::Err> {
  517. let read_txn = self.db.begin_read().map_err(Error::from)?;
  518. let table = read_txn
  519. .open_table(PROOFS_STATE_TABLE)
  520. .map_err(Error::from)?;
  521. let mut states = Vec::with_capacity(ys.len());
  522. for y in ys {
  523. match table.get(y.to_bytes()).map_err(Error::from)? {
  524. Some(state) => states.push(Some(
  525. serde_json::from_str(state.value()).map_err(Error::from)?,
  526. )),
  527. None => states.push(None),
  528. }
  529. }
  530. Ok(states)
  531. }
  532. async fn get_proofs_by_keyset_id(
  533. &self,
  534. keyset_id: &Id,
  535. ) -> Result<(Proofs, Vec<Option<State>>), Self::Err> {
  536. let read_txn = self.db.begin_read().map_err(Error::from)?;
  537. let table = read_txn.open_table(PROOFS_TABLE).map_err(Error::from)?;
  538. let proofs_for_id = table
  539. .iter()
  540. .map_err(Error::from)?
  541. .flatten()
  542. .map(|(_, p)| serde_json::from_str::<Proof>(p.value()))
  543. .collect::<Result<Proofs, _>>()?
  544. .into_iter()
  545. .filter(|p| &p.keyset_id == keyset_id)
  546. .collect::<Proofs>();
  547. let proof_ys = proofs_for_id.ys()?;
  548. assert_eq!(proofs_for_id.len(), proof_ys.len());
  549. let states = self.get_proofs_states(&proof_ys).await?;
  550. Ok((proofs_for_id, states))
  551. }
  552. async fn update_proofs_states(
  553. &self,
  554. ys: &[PublicKey],
  555. proofs_state: State,
  556. ) -> Result<Vec<Option<State>>, Self::Err> {
  557. let write_txn = self.db.begin_write().map_err(Error::from)?;
  558. let mut states = Vec::with_capacity(ys.len());
  559. let state_str = serde_json::to_string(&proofs_state).map_err(Error::from)?;
  560. {
  561. let mut table = write_txn
  562. .open_table(PROOFS_STATE_TABLE)
  563. .map_err(Error::from)?;
  564. for y in ys {
  565. let current_state;
  566. {
  567. match table.get(y.to_bytes()).map_err(Error::from)? {
  568. Some(state) => {
  569. current_state =
  570. Some(serde_json::from_str(state.value()).map_err(Error::from)?)
  571. }
  572. None => current_state = None,
  573. }
  574. }
  575. states.push(current_state);
  576. if current_state != Some(State::Spent) {
  577. table
  578. .insert(y.to_bytes(), state_str.as_str())
  579. .map_err(Error::from)?;
  580. }
  581. }
  582. }
  583. write_txn.commit().map_err(Error::from)?;
  584. Ok(states)
  585. }
  586. async fn add_blind_signatures(
  587. &self,
  588. blinded_messages: &[PublicKey],
  589. blind_signatures: &[BlindSignature],
  590. quote_id: Option<Uuid>,
  591. ) -> Result<(), Self::Err> {
  592. let write_txn = self.db.begin_write().map_err(Error::from)?;
  593. {
  594. let mut table = write_txn
  595. .open_table(BLINDED_SIGNATURES)
  596. .map_err(Error::from)?;
  597. let mut quote_sigs_table = write_txn
  598. .open_multimap_table(QUOTE_SIGNATURES_TABLE)
  599. .map_err(Error::from)?;
  600. for (blinded_message, blind_signature) in blinded_messages.iter().zip(blind_signatures)
  601. {
  602. let blind_sig = serde_json::to_string(&blind_signature).map_err(Error::from)?;
  603. table
  604. .insert(blinded_message.to_bytes(), blind_sig.as_str())
  605. .map_err(Error::from)?;
  606. if let Some(quote_id) = &quote_id {
  607. quote_sigs_table
  608. .insert(quote_id.as_bytes(), blinded_message.to_bytes())
  609. .map_err(Error::from)?;
  610. }
  611. }
  612. }
  613. write_txn.commit().map_err(Error::from)?;
  614. Ok(())
  615. }
  616. async fn get_blind_signatures(
  617. &self,
  618. blinded_messages: &[PublicKey],
  619. ) -> Result<Vec<Option<BlindSignature>>, Self::Err> {
  620. let read_txn = self.db.begin_read().map_err(Error::from)?;
  621. let table = read_txn
  622. .open_table(BLINDED_SIGNATURES)
  623. .map_err(Error::from)?;
  624. let mut signatures = Vec::with_capacity(blinded_messages.len());
  625. for blinded_message in blinded_messages {
  626. match table.get(blinded_message.to_bytes()).map_err(Error::from)? {
  627. Some(blind_signature) => signatures.push(Some(
  628. serde_json::from_str(blind_signature.value()).map_err(Error::from)?,
  629. )),
  630. None => signatures.push(None),
  631. }
  632. }
  633. Ok(signatures)
  634. }
  635. async fn get_blind_signatures_for_keyset(
  636. &self,
  637. keyset_id: &Id,
  638. ) -> Result<Vec<BlindSignature>, Self::Err> {
  639. let read_txn = self.db.begin_read().map_err(Error::from)?;
  640. let table = read_txn
  641. .open_table(BLINDED_SIGNATURES)
  642. .map_err(Error::from)?;
  643. Ok(table
  644. .iter()
  645. .map_err(Error::from)?
  646. .flatten()
  647. .filter_map(|(_m, s)| {
  648. match serde_json::from_str::<BlindSignature>(s.value()).ok() {
  649. Some(signature) if &signature.keyset_id == keyset_id => Some(signature), // Filter by keyset_id
  650. _ => None, // Exclude non-matching entries
  651. }
  652. })
  653. .collect())
  654. }
  655. /// Add melt request
  656. async fn add_melt_request(
  657. &self,
  658. melt_request: MeltBolt11Request<Uuid>,
  659. ln_key: LnKey,
  660. ) -> Result<(), Self::Err> {
  661. let write_txn = self.db.begin_write().map_err(Error::from)?;
  662. let mut table = write_txn.open_table(MELT_REQUESTS).map_err(Error::from)?;
  663. table
  664. .insert(
  665. melt_request.quote.as_bytes(),
  666. (
  667. serde_json::to_string(&melt_request)?.as_str(),
  668. serde_json::to_string(&ln_key)?.as_str(),
  669. ),
  670. )
  671. .map_err(Error::from)?;
  672. Ok(())
  673. }
  674. /// Get melt request
  675. async fn get_melt_request(
  676. &self,
  677. quote_id: &Uuid,
  678. ) -> Result<Option<(MeltBolt11Request<Uuid>, LnKey)>, Self::Err> {
  679. let read_txn = self.db.begin_read().map_err(Error::from)?;
  680. let table = read_txn.open_table(MELT_REQUESTS).map_err(Error::from)?;
  681. match table.get(quote_id.as_bytes()).map_err(Error::from)? {
  682. Some(melt_request) => {
  683. let (melt_request_str, ln_key_str) = melt_request.value();
  684. let melt_request = serde_json::from_str(melt_request_str)?;
  685. let ln_key = serde_json::from_str(ln_key_str)?;
  686. Ok(Some((melt_request, ln_key)))
  687. }
  688. None => Ok(None),
  689. }
  690. }
  691. /// Get [`BlindSignature`]s for quote
  692. async fn get_blind_signatures_for_quote(
  693. &self,
  694. quote_id: &Uuid,
  695. ) -> Result<Vec<BlindSignature>, Self::Err> {
  696. let read_txn = self.db.begin_read().map_err(Error::from)?;
  697. let quote_proofs_table = read_txn
  698. .open_multimap_table(QUOTE_SIGNATURES_TABLE)
  699. .map_err(Error::from)?;
  700. let ys = quote_proofs_table.get(quote_id.as_bytes()).unwrap();
  701. let ys: Vec<[u8; 33]> = ys.into_iter().flatten().map(|v| v.value()).collect();
  702. let mut signatures = Vec::new();
  703. let signatures_table = read_txn
  704. .open_table(BLINDED_SIGNATURES)
  705. .map_err(Error::from)?;
  706. for y in ys {
  707. if let Some(sig) = signatures_table.get(y).map_err(Error::from)? {
  708. let sig = serde_json::from_str(sig.value())?;
  709. signatures.push(sig);
  710. }
  711. }
  712. Ok(signatures)
  713. }
  714. async fn set_mint_info(&self, mint_info: MintInfo) -> Result<(), Self::Err> {
  715. let write_txn = self.db.begin_write().map_err(Error::from)?;
  716. {
  717. let mut table = write_txn.open_table(CONFIG_TABLE).map_err(Error::from)?;
  718. table
  719. .insert("mint_info", serde_json::to_string(&mint_info)?.as_str())
  720. .map_err(Error::from)?;
  721. }
  722. write_txn.commit().map_err(Error::from)?;
  723. Ok(())
  724. }
  725. async fn get_mint_info(&self) -> Result<MintInfo, Self::Err> {
  726. let read_txn = self.db.begin_read().map_err(Error::from)?;
  727. let table = read_txn.open_table(CONFIG_TABLE).map_err(Error::from)?;
  728. if let Some(mint_info) = table.get("mint_info").map_err(Error::from)? {
  729. let mint_info = serde_json::from_str(mint_info.value())?;
  730. return Ok(mint_info);
  731. }
  732. Err(Error::UnknownMintInfo.into())
  733. }
  734. async fn set_quote_ttl(&self, quote_ttl: QuoteTTL) -> Result<(), Self::Err> {
  735. let write_txn = self.db.begin_write().map_err(Error::from)?;
  736. {
  737. let mut table = write_txn.open_table(CONFIG_TABLE).map_err(Error::from)?;
  738. table
  739. .insert("quote_ttl", serde_json::to_string(&quote_ttl)?.as_str())
  740. .map_err(Error::from)?;
  741. }
  742. write_txn.commit().map_err(Error::from)?;
  743. Ok(())
  744. }
  745. async fn get_quote_ttl(&self) -> Result<QuoteTTL, Self::Err> {
  746. let read_txn = self.db.begin_read().map_err(Error::from)?;
  747. let table = read_txn.open_table(CONFIG_TABLE).map_err(Error::from)?;
  748. if let Some(quote_ttl) = table.get("quote_ttl").map_err(Error::from)? {
  749. let quote_ttl = serde_json::from_str(quote_ttl.value())?;
  750. return Ok(quote_ttl);
  751. }
  752. Err(Error::UnknownQuoteTTL.into())
  753. }
  754. }