1use std::collections::BTreeMap;
3use std::path::Path;
4use std::sync::{PoisonError, RwLock};
5
6use redb::{Database, ReadableDatabase, ReadableTable, TableDefinition};
7use tracing::{error, info, warn};
8
9use crate::error::{KeepError, Result, StorageError};
10use crate::migration;
11
12fn lock_error<T>(_: PoisonError<T>) -> KeepError {
13 KeepError::Runtime("lock poisoned".into())
14}
15
16pub const KEYS_TABLE: &str = "keys";
18pub const SHARES_TABLE: &str = "shares";
20pub const DESCRIPTORS_TABLE: &str = "wallet_descriptors";
22pub const RELAY_CONFIGS_TABLE: &str = "relay_configs";
24pub const CONFIG_TABLE: &str = "config";
26pub const HEALTH_STATUS_TABLE: &str = "key_health_status";
28pub const SECRETS_TABLE: &str = "secrets";
32pub const SECRET_SEALS_TABLE: &str = "secret_seals";
36pub const STATE_VERSIONS_TABLE: &str = "state_versions";
40
41pub struct AtomicOp<'a> {
44 pub table: &'a str,
46 pub key: &'a [u8],
48 pub value: Option<&'a [u8]>,
50}
51
52pub trait StorageBackend: Send + Sync {
56 fn get(&self, table: &str, key: &[u8]) -> Result<Option<Vec<u8>>>;
58 fn put(&self, table: &str, key: &[u8], value: &[u8]) -> Result<()>;
60 fn delete(&self, table: &str, key: &[u8]) -> Result<bool>;
62 fn list(&self, table: &str) -> Result<Vec<(Vec<u8>, Vec<u8>)>>;
64 fn create_table(&self, table: &str) -> Result<()>;
66
67 fn list_keys_with_prefix(&self, table: &str, prefix: &[u8]) -> Result<Vec<Vec<u8>>> {
71 Ok(self
72 .list(table)?
73 .into_iter()
74 .filter_map(|(k, _)| if k.starts_with(prefix) { Some(k) } else { None })
75 .collect())
76 }
77
78 fn delete_batch(&self, table: &str, keys: &[&[u8]]) -> Result<()> {
82 for key in keys {
83 self.delete(table, key)?;
84 }
85 Ok(())
86 }
87
88 fn put_batch(&self, table: &str, entries: &[(&[u8], &[u8])]) -> Result<()> {
90 for (key, value) in entries {
91 self.put(table, key, value)?;
92 }
93 Ok(())
94 }
95
96 fn write_atomic(&self, ops: &[AtomicOp<'_>]) -> Result<()> {
101 for op in ops {
102 match op.value {
103 Some(v) => self.put(op.table, op.key, v)?,
104 None => {
105 self.delete(op.table, op.key)?;
106 }
107 }
108 }
109 Ok(())
110 }
111
112 fn schema_version(&self) -> Result<u32> {
117 Ok(migration::CURRENT_SCHEMA_VERSION)
118 }
119
120 fn needs_migration(&self) -> Result<bool> {
125 Ok(false)
126 }
127
128 fn run_migrations(&self) -> Result<migration::MigrationResult> {
133 Ok(migration::MigrationResult {
134 from_version: migration::CURRENT_SCHEMA_VERSION,
135 to_version: migration::CURRENT_SCHEMA_VERSION,
136 migrations_run: 0,
137 })
138 }
139}
140
141const KEYS_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("keys");
142const SHARES_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("shares");
143const DESCRIPTORS_TABLE_DEF: TableDefinition<&[u8], &[u8]> =
144 TableDefinition::new("wallet_descriptors");
145const RELAY_CONFIGS_TABLE_DEF: TableDefinition<&[u8], &[u8]> =
146 TableDefinition::new("relay_configs");
147const CONFIG_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("config");
148const HEALTH_STATUS_TABLE_DEF: TableDefinition<&[u8], &[u8]> =
149 TableDefinition::new("key_health_status");
150const SECRETS_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("secrets");
151const SECRET_SEALS_TABLE_DEF: TableDefinition<&[u8], &[u8]> = TableDefinition::new("secret_seals");
152const STATE_VERSIONS_TABLE_DEF: TableDefinition<&[u8], &[u8]> =
153 TableDefinition::new("state_versions");
154
155pub struct RedbBackend {
157 db: Database,
158}
159
160impl RedbBackend {
161 pub fn create(path: &Path) -> Result<Self> {
163 let db = Database::create(path)?;
164 migration::initialize_schema(&db)?;
165 Ok(Self { db })
166 }
167
168 pub fn open(path: &Path) -> Result<Self> {
172 match open_database_with_retry(path) {
173 Ok(db) => {
174 migration::check_compatibility(&db)?;
175 let result = migration::run_migrations(&db)?;
176 if result.migrations_run > 0 {
177 info!(
178 count = result.migrations_run,
179 "vault schema migration completed"
180 );
181 }
182 Ok(Self { db })
183 }
184 Err(OpenWithRetryError::UpgradeRequired(old_version)) => {
185 warn!(
186 old_version,
187 "redb file format upgrade required, migrating automatically"
188 );
189 Self::upgrade_file_format(path)
190 }
191 Err(OpenWithRetryError::Other(e)) => Err(map_open_failure(path, e)),
192 }
193 }
194
195 fn upgrade_file_format(path: &Path) -> Result<Self> {
197 let old_db = redb2::Database::open(path).map_err(|e| {
198 StorageError::database(format!("failed to open old database for migration: {e}"))
199 })?;
200
201 let table_names: &[&str] = &[
202 KEYS_TABLE,
203 SHARES_TABLE,
204 DESCRIPTORS_TABLE,
205 RELAY_CONFIGS_TABLE,
206 CONFIG_TABLE,
207 HEALTH_STATUS_TABLE,
208 SECRETS_TABLE,
212 SECRET_SEALS_TABLE,
213 STATE_VERSIONS_TABLE,
216 ];
217
218 type TableEntries = Vec<(Vec<u8>, Vec<u8>)>;
219 let mut table_data: Vec<(&str, TableEntries)> = Vec::new();
220 let old_schema_version;
221 {
222 use redb2::ReadableTable as _;
223
224 let rtxn = old_db
225 .begin_read()
226 .map_err(|e| StorageError::database(format!("failed to read old database: {e}")))?;
227 for &name in table_names {
228 let table_def: redb2::TableDefinition<&[u8], &[u8]> =
229 redb2::TableDefinition::new(name);
230 match rtxn.open_table(table_def) {
231 Ok(table) => {
232 let entries: Vec<(Vec<u8>, Vec<u8>)> = table
233 .iter()
234 .map_err(|e| {
235 StorageError::database(format!(
236 "failed to iterate table {name}: {e}"
237 ))
238 })?
239 .map(|r| {
240 let (k, v) = r.map_err(|e| {
241 StorageError::database(format!(
242 "failed to read entry in table {name}: {e}"
243 ))
244 })?;
245 Ok((k.value().to_vec(), v.value().to_vec()))
246 })
247 .collect::<Result<Vec<_>>>()?;
248 info!(
249 table = name,
250 count = entries.len(),
251 "read table for migration"
252 );
253 table_data.push((name, entries));
254 }
255 Err(redb2::TableError::TableDoesNotExist(_)) => {}
256 Err(e) => {
257 return Err(StorageError::database(format!(
258 "failed to open table {name}: {e}"
259 ))
260 .into());
261 }
262 }
263 }
264
265 let metadata_def: redb2::TableDefinition<&str, &[u8]> =
266 redb2::TableDefinition::new("metadata");
267 old_schema_version = match rtxn.open_table(metadata_def) {
268 Ok(table) => table
269 .get("schema_version")
270 .map_err(|e| {
271 StorageError::database(format!(
272 "failed to read schema_version from old database: {e}"
273 ))
274 })?
275 .and_then(|v| <[u8; 4]>::try_from(v.value()).ok())
276 .map(u32::from_le_bytes),
277 Err(redb2::TableError::TableDoesNotExist(_)) => None,
278 Err(e) => {
279 return Err(StorageError::database(format!(
280 "failed to open metadata table: {e}"
281 ))
282 .into());
283 }
284 };
285 }
286 drop(old_db);
287
288 let backup_path = path.with_extension("db.old");
289 if backup_path.exists() {
290 let ts = std::time::SystemTime::now()
291 .duration_since(std::time::UNIX_EPOCH)
292 .unwrap_or_default()
293 .as_secs();
294 let alt = path.with_extension(format!("db.old.{ts}"));
295 std::fs::rename(&backup_path, &alt).map_err(|e| {
296 StorageError::database(format!(
297 "failed to move existing backup before migration: {e}"
298 ))
299 })?;
300 warn!(?alt, "moved existing backup aside");
301 }
302 std::fs::rename(path, &backup_path)?;
303 info!(?backup_path, "backed up old database");
304
305 let new_db = Database::create(path).map_err(|e| {
306 if let Err(re) = std::fs::rename(&backup_path, path) {
307 error!(
308 "failed to restore backup after migration failure: {re}; \
309 backup is at {backup_path:?}"
310 );
311 }
312 StorageError::database(format!("failed to create new database: {e}"))
313 })?;
314
315 let write_result: Result<()> = (|| {
316 let wtxn = new_db.begin_write()?;
317 for (name, entries) in &table_data {
318 let table_def: TableDefinition<&[u8], &[u8]> = TableDefinition::new(name);
319 let mut table = wtxn.open_table(table_def)?;
320 for (key, value) in entries {
321 table.insert(key.as_slice(), value.as_slice())?;
322 }
323 }
324 {
325 let metadata: TableDefinition<&str, &[u8]> = TableDefinition::new("metadata");
326 let mut table = wtxn.open_table(metadata)?;
327 let version = old_schema_version.unwrap_or(1);
328 table.insert("schema_version", version.to_le_bytes().as_slice())?;
329 }
330 wtxn.commit()?;
331 Ok(())
332 })();
333 if let Err(e) = write_result {
334 drop(new_db);
335 let _ = std::fs::remove_file(path);
336 if let Err(re) = std::fs::rename(&backup_path, path) {
337 error!(
338 "failed to restore backup after write failure: {re}; \
339 backup is at {backup_path:?}"
340 );
341 }
342 return Err(e);
343 }
344
345 info!("database file format upgrade complete");
346
347 let migrate_result: Result<migration::MigrationResult> = (|| {
348 migration::check_compatibility(&new_db)?;
349 migration::run_migrations(&new_db)
350 })();
351 let result = match migrate_result {
352 Ok(r) => r,
353 Err(e) => {
354 drop(new_db);
355 let _ = std::fs::remove_file(path);
356 if let Err(re) = std::fs::rename(&backup_path, path) {
357 error!(
358 "failed to restore backup after migration failure: {re}; \
359 backup is at {backup_path:?}"
360 );
361 }
362 return Err(e);
363 }
364 };
365 if result.migrations_run > 0 {
366 info!(
367 count = result.migrations_run,
368 "schema migration completed after file format upgrade"
369 );
370 }
371
372 Ok(Self { db: new_db })
373 }
374
375 fn table_def(
376 &self,
377 name: &str,
378 ) -> Result<TableDefinition<'static, &'static [u8], &'static [u8]>> {
379 match name {
380 KEYS_TABLE => Ok(KEYS_TABLE_DEF),
381 SHARES_TABLE => Ok(SHARES_TABLE_DEF),
382 DESCRIPTORS_TABLE => Ok(DESCRIPTORS_TABLE_DEF),
383 RELAY_CONFIGS_TABLE => Ok(RELAY_CONFIGS_TABLE_DEF),
384 CONFIG_TABLE => Ok(CONFIG_TABLE_DEF),
385 HEALTH_STATUS_TABLE => Ok(HEALTH_STATUS_TABLE_DEF),
386 SECRETS_TABLE => Ok(SECRETS_TABLE_DEF),
387 SECRET_SEALS_TABLE => Ok(SECRET_SEALS_TABLE_DEF),
388 STATE_VERSIONS_TABLE => Ok(STATE_VERSIONS_TABLE_DEF),
389 _ => Err(StorageError::database(format!("unknown table: {name}")).into()),
390 }
391 }
392}
393
394pub(crate) enum OpenWithRetryError {
398 UpgradeRequired(u8),
399 Other(redb::DatabaseError),
400}
401
402pub(crate) fn open_database_with_retry(
408 path: &Path,
409) -> std::result::Result<Database, OpenWithRetryError> {
410 const MAX_RETRIES: u32 = 10;
411 const RETRY_DELAY_MS: u64 = 50;
412
413 let mut last_err = None;
414 for _ in 0..MAX_RETRIES {
415 match Database::open(path) {
416 Ok(db) => return Ok(db),
417 Err(redb::DatabaseError::UpgradeRequired(old_version)) => {
418 return Err(OpenWithRetryError::UpgradeRequired(old_version));
419 }
420 Err(e) => {
421 let is_retryable = matches!(
422 &e,
423 redb::DatabaseError::Storage(redb::StorageError::Io(io_err))
424 if io_err.kind() == std::io::ErrorKind::PermissionDenied
425 ) || matches!(&e, redb::DatabaseError::DatabaseAlreadyOpen);
426
427 if is_retryable {
428 last_err = Some(e);
429 std::thread::sleep(std::time::Duration::from_millis(RETRY_DELAY_MS));
430 continue;
431 }
432 return Err(OpenWithRetryError::Other(e));
433 }
434 }
435 }
436 Err(OpenWithRetryError::Other(last_err.unwrap_or_else(|| {
437 redb::DatabaseError::Storage(redb::StorageError::Io(std::io::Error::other(
438 "open failed after retries",
439 )))
440 })))
441}
442
443pub(crate) fn map_open_failure(path: &Path, e: redb::DatabaseError) -> KeepError {
453 if matches!(&e, redb::DatabaseError::DatabaseAlreadyOpen) {
454 return KeepError::VaultAlreadyOpen(format!(
455 "vault at {} is already opened by another process. \
456 A `keep serve` or `keep frost network serve` daemon typically holds the lock; \
457 stop it (or wait for it to exit) and retry. \
458 Read-only commands like `list` route through the running daemon automatically \
459 (#533); see #422 for details.",
460 path.display()
461 ));
462 }
463 e.into()
464}
465
466impl StorageBackend for RedbBackend {
467 fn get(&self, table: &str, key: &[u8]) -> Result<Option<Vec<u8>>> {
468 let rtxn = self.db.begin_read()?;
469 let tbl = rtxn.open_table(self.table_def(table)?)?;
470 Ok(tbl.get(key)?.map(|v| v.value().to_vec()))
471 }
472
473 fn put(&self, table: &str, key: &[u8], value: &[u8]) -> Result<()> {
474 let wtxn = self.db.begin_write()?;
475 wtxn.open_table(self.table_def(table)?)?
476 .insert(key, value)?;
477 wtxn.commit()?;
478 Ok(())
479 }
480
481 fn delete(&self, table: &str, key: &[u8]) -> Result<bool> {
482 let wtxn = self.db.begin_write()?;
483 let existed = wtxn
484 .open_table(self.table_def(table)?)?
485 .remove(key)?
486 .is_some();
487 wtxn.commit()?;
488 Ok(existed)
489 }
490
491 fn list(&self, table: &str) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
492 let rtxn = self.db.begin_read()?;
493 let tbl = rtxn.open_table(self.table_def(table)?)?;
494 tbl.iter()?
495 .map(|result| {
496 let (k, v) = result?;
497 Ok((k.value().to_vec(), v.value().to_vec()))
498 })
499 .collect()
500 }
501
502 fn create_table(&self, table: &str) -> Result<()> {
503 let wtxn = self.db.begin_write()?;
504 wtxn.open_table(self.table_def(table)?)?;
505 wtxn.commit()?;
506 Ok(())
507 }
508
509 fn put_batch(&self, table: &str, entries: &[(&[u8], &[u8])]) -> Result<()> {
510 let wtxn = self.db.begin_write()?;
511 {
512 let mut tbl = wtxn.open_table(self.table_def(table)?)?;
513 for (key, value) in entries {
514 tbl.insert(*key, *value)?;
515 }
516 }
517 wtxn.commit()?;
518 Ok(())
519 }
520
521 fn delete_batch(&self, table: &str, keys: &[&[u8]]) -> Result<()> {
522 let wtxn = self.db.begin_write()?;
523 {
524 let mut tbl = wtxn.open_table(self.table_def(table)?)?;
525 for key in keys {
526 tbl.remove(*key)?;
527 }
528 }
529 wtxn.commit()?;
530 Ok(())
531 }
532
533 fn write_atomic(&self, ops: &[AtomicOp<'_>]) -> Result<()> {
536 let wtxn = self.db.begin_write()?;
537 for op in ops {
538 let mut tbl = wtxn.open_table(self.table_def(op.table)?)?;
539 match op.value {
540 Some(v) => {
541 tbl.insert(op.key, v)?;
542 }
543 None => {
544 tbl.remove(op.key)?;
545 }
546 }
547 }
548 wtxn.commit()?;
549 Ok(())
550 }
551
552 fn list_keys_with_prefix(&self, table: &str, prefix: &[u8]) -> Result<Vec<Vec<u8>>> {
553 let rtxn = self.db.begin_read()?;
554 let tbl = rtxn.open_table(self.table_def(table)?)?;
555 let mut out = Vec::new();
556 for entry in tbl.iter()? {
557 let (k, _) = entry?;
558 let bytes = k.value();
559 if bytes.starts_with(prefix) {
560 out.push(bytes.to_vec());
561 }
562 }
563 Ok(out)
564 }
565
566 fn schema_version(&self) -> Result<u32> {
567 Ok(migration::read_schema_version(&self.db)?.unwrap_or(1))
568 }
569
570 fn needs_migration(&self) -> Result<bool> {
571 migration::needs_migration(&self.db)
572 }
573
574 fn run_migrations(&self) -> Result<migration::MigrationResult> {
575 migration::run_migrations(&self.db)
576 }
577}
578
579type TableData = BTreeMap<Vec<u8>, Vec<u8>>;
580
581pub struct MemoryBackend {
583 tables: RwLock<BTreeMap<String, TableData>>,
584}
585
586impl MemoryBackend {
587 pub fn new() -> Self {
589 Self {
590 tables: RwLock::new(BTreeMap::new()),
591 }
592 }
593}
594
595impl Default for MemoryBackend {
596 fn default() -> Self {
597 Self::new()
598 }
599}
600
601impl StorageBackend for MemoryBackend {
602 fn get(&self, table: &str, key: &[u8]) -> Result<Option<Vec<u8>>> {
603 let tables = self.tables.read().map_err(lock_error)?;
604 Ok(tables.get(table).and_then(|t| t.get(key).cloned()))
605 }
606
607 fn put(&self, table: &str, key: &[u8], value: &[u8]) -> Result<()> {
608 self.tables
609 .write()
610 .map_err(lock_error)?
611 .entry(table.to_string())
612 .or_default()
613 .insert(key.to_vec(), value.to_vec());
614 Ok(())
615 }
616
617 fn delete(&self, table: &str, key: &[u8]) -> Result<bool> {
618 let mut tables = self.tables.write().map_err(lock_error)?;
619 Ok(tables
620 .get_mut(table)
621 .map(|t| t.remove(key).is_some())
622 .unwrap_or(false))
623 }
624
625 fn list(&self, table: &str) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
626 let tables = self.tables.read().map_err(lock_error)?;
627 Ok(tables
628 .get(table)
629 .map(|t| t.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
630 .unwrap_or_default())
631 }
632
633 fn create_table(&self, table: &str) -> Result<()> {
634 self.tables
635 .write()
636 .map_err(lock_error)?
637 .entry(table.to_string())
638 .or_default();
639 Ok(())
640 }
641}
642
643#[cfg(test)]
644mod tests {
645 use super::*;
646 use tempfile::tempdir;
647
648 fn test_backend_operations(backend: &dyn StorageBackend) {
649 backend.create_table(KEYS_TABLE).unwrap();
650
651 assert!(backend.get(KEYS_TABLE, b"key1").unwrap().is_none());
652
653 backend.put(KEYS_TABLE, b"key1", b"value1").unwrap();
654 assert_eq!(
655 backend.get(KEYS_TABLE, b"key1").unwrap(),
656 Some(b"value1".to_vec())
657 );
658
659 backend.put(KEYS_TABLE, b"key2", b"value2").unwrap();
660 let entries = backend.list(KEYS_TABLE).unwrap();
661 assert_eq!(entries.len(), 2);
662
663 assert!(backend.delete(KEYS_TABLE, b"key1").unwrap());
664 assert!(backend.get(KEYS_TABLE, b"key1").unwrap().is_none());
665 assert!(!backend.delete(KEYS_TABLE, b"key1").unwrap());
666 }
667
668 #[test]
669 fn test_memory_backend() {
670 let backend = MemoryBackend::new();
671 test_backend_operations(&backend);
672 }
673
674 #[test]
675 fn test_redb_backend() {
676 let dir = tempdir().unwrap();
677 let backend = RedbBackend::create(&dir.path().join("test.db")).unwrap();
678 test_backend_operations(&backend);
679 }
680
681 #[test]
682 fn test_unknown_table_rejected() {
683 let dir = tempdir().unwrap();
684 let backend = RedbBackend::create(&dir.path().join("test.db")).unwrap();
685 assert!(backend.create_table("unknown").is_err());
686 }
687
688 #[test]
689 fn second_open_surfaces_lock_holder_hint() {
690 let dir = tempdir().unwrap();
697 let db_path = dir.path().join("locked.db");
698 let _first = RedbBackend::create(&db_path).expect("first open holds the lock");
699
700 let err = match RedbBackend::open(&db_path) {
701 Err(e) => e,
702 Ok(_) => panic!("second open while the first is held must fail"),
703 };
704 let msg = err.to_string();
705 assert!(
706 matches!(err, KeepError::VaultAlreadyOpen(_)),
707 "expected VaultAlreadyOpen from map_open_failure, got {err:?}"
708 );
709 assert!(
710 msg.contains("already opened by another process"),
711 "got {msg}"
712 );
713 assert!(
714 msg.contains("keep serve") || msg.contains("frost network serve"),
715 "got {msg}"
716 );
717 assert!(msg.contains("#422"), "got {msg}");
718 assert!(msg.contains(&db_path.display().to_string()), "got {msg}");
719 }
720}