Skip to main content

fedimint_client/
db.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::time::SystemTime;
3
4use bitcoin::hex::DisplayHex as _;
5use fedimint_api_client::api::ApiVersionSet;
6use fedimint_client_module::db::ClientModuleMigrationFn;
7use fedimint_client_module::module::recovery::RecoveryProgress;
8use fedimint_client_module::oplog::{JsonStringed, OperationLogEntry, OperationOutcome};
9use fedimint_client_module::sm::{ActiveStateMeta, InactiveStateMeta};
10use fedimint_core::config::{ClientConfig, ClientConfigV0, FederationId, GlobalClientConfig};
11use fedimint_core::core::{Account, ModuleInstanceId, OperationId};
12use fedimint_core::db::{
13    Database, DatabaseTransaction, DatabaseVersion, DatabaseVersionKey, DbMigrationError,
14    IDatabaseTransactionOpsCore, IDatabaseTransactionOpsCoreTyped, MODULE_GLOBAL_PREFIX,
15    apply_migrations_dbtx, create_database_version_dbtx, get_current_database_version,
16};
17use fedimint_core::encoding::{
18    Decodable, DecodeError, Encodable, decode_field_from_finite_reader,
19    decode_legacy_system_time_from_finite_reader, encode_legacy_system_time, with_decoding_context,
20};
21use fedimint_core::module::registry::{ModuleDecoderRegistry, ModuleRegistry};
22use fedimint_core::module::{Amounts, SupportedApiVersionsSummary};
23use fedimint_core::{ChainId, PeerId, TransactionId, impl_db_lookup, impl_db_record};
24use fedimint_eventlog::{
25    DB_KEY_PREFIX_EVENT_LOG, DB_KEY_PREFIX_UNORDERED_EVENT_LOG, EventLogId, UnordedEventLogId,
26};
27use fedimint_logging::LOG_CLIENT_DB;
28use futures::StreamExt;
29use serde::{Deserialize, Serialize};
30use strum::IntoEnumIterator as _;
31use strum_macros::EnumIter;
32use tracing::{debug, info, trace, warn};
33
34use crate::backup::{ClientBackup, Metadata};
35use crate::error::ClientSecretError;
36use crate::sm::executor::{
37    ActiveStateKeyBytes, ActiveStateKeyPrefixBytes, ExecutorDbPrefixes, InactiveStateKeyBytes,
38    InactiveStateKeyPrefixBytes,
39};
40
41#[repr(u8)]
42#[derive(Clone, EnumIter, Debug)]
43pub enum DbKeyPrefix {
44    EncodedClientSecret = 0x28,
45    ClientSecret = 0x29, // Unused
46    ClientPreRootSecretHash = 0x2a,
47    OperationLog = 0x2c,
48    ChronologicalOperationLog = 0x2d,
49    CommonApiVersionCache = 0x2e,
50    ClientConfig = 0x2f,
51    PendingClientConfig = 0x3b,
52    ClientInviteCode = 0x30, // Unused; clean out remnant data before re-using!
53    ClientInitState = 0x31,
54    ClientMetadata = 0x32,
55    ClientLastBackup = 0x33,
56    ClientMetaField = 0x34,
57    ClientMetaServiceInfo = 0x35,
58    ApiSecret = 0x36,
59    PeerLastApiVersionsSummaryCache = 0x37,
60    ApiUrlAnnouncement = 0x38,
61    EventLog = fedimint_eventlog::DB_KEY_PREFIX_EVENT_LOG,
62    UnorderedEventLog = fedimint_eventlog::DB_KEY_PREFIX_UNORDERED_EVENT_LOG,
63    EventLogTrimable = fedimint_eventlog::DB_KEY_PREFIX_EVENT_LOG_TRIMABLE,
64    ChainId = 0x3c,
65    ClientModuleRecovery = 0x40,
66    GuardianMetadata = 0x42,
67    TransactionFees = 0x43,
68    OperationAccount = 0x44,
69
70    DatabaseVersion = fedimint_core::db::DbKeyPrefix::DatabaseVersion as u8,
71    ClientBackup = fedimint_core::db::DbKeyPrefix::ClientBackup as u8,
72
73    ActiveStates = ExecutorDbPrefixes::ActiveStates as u8,
74    InactiveStates = ExecutorDbPrefixes::InactiveStates as u8,
75
76    /// Arbitrary data of the applications integrating Fedimint client and
77    /// wanting to store some Federation-specific data in Fedimint client
78    /// database.
79    ///
80    /// New users are encouraged to use this single prefix only.
81    //
82    // TODO: https://github.com/fedimint/fedimint/issues/4444
83    //       in the future, we should make all global access to the db private
84    //       and only expose a getter returning isolated database.
85    UserData = 0xb0,
86    /// Prefixes between 0xb1..=0xcf shall all be considered allocated for
87    /// historical and future external use
88    ExternalReservedStart = 0xb1,
89    /// Prefixes between 0xb1..=0xcf shall all be considered allocated for
90    /// historical and future external use
91    ExternalReservedEnd = 0xcf,
92    /// 0xd0.. reserved for Fedimint internal use
93    // (see [`DbKeyPrefixInternalReserved`] for *internal* details)
94    InternalReservedStart = 0xd0,
95    /// Per-module instance data
96    ModuleGlobalPrefix = 0xff,
97}
98
99/// The account an operation acts on: the balance the primary module funds it
100/// from and credits its change, claims and refunds to.
101///
102/// Written when the operation is created and only for non-primary accounts,
103/// so an absent row reads as [`Account::Primary`]. That is also the only
104/// account an operation recorded before accounts existed can have belonged
105/// to, which is what lets state machines stay unaware of accounts: they look
106/// up their operation's row instead of carrying the account themselves, and
107/// machines persisted before the row existed need no rewrite.
108#[derive(Debug, Clone, Encodable, Decodable)]
109pub struct OperationAccountKey(pub OperationId);
110
111impl_db_record!(
112    key = OperationAccountKey,
113    value = Account,
114    db_prefix = DbKeyPrefix::OperationAccount,
115);
116
117#[repr(u8)]
118#[derive(Clone, EnumIter, Debug)]
119pub(crate) enum DbKeyPrefixInternalReserved {
120    /// [`crate::Client::built_in_application_event_log_tracker`]
121    DefaultApplicationEventLogPos = 0xd0,
122}
123
124pub(crate) async fn verify_client_db_integrity_dbtx(dbtx: &mut DatabaseTransaction<'_>) {
125    let prefixes: BTreeSet<u8> = DbKeyPrefix::iter().map(|prefix| prefix as u8).collect();
126
127    let mut records = dbtx.raw_find_by_prefix(&[]).await.expect("DB fail");
128    while let Some((k, v)) = records.next().await {
129        // from here and above, we don't want to spend time verifying it
130        if DbKeyPrefix::UserData as u8 <= k[0] {
131            break;
132        }
133
134        assert!(
135            prefixes.contains(&k[0]),
136            "Unexpected client db record found: {}: {}",
137            k.as_hex(),
138            v.as_hex()
139        );
140    }
141}
142
143impl std::fmt::Display for DbKeyPrefix {
144    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
145        write!(f, "{self:?}")
146    }
147}
148
149#[derive(Debug, Encodable, Decodable)]
150pub struct EncodedClientSecretKey;
151
152#[derive(Debug, Encodable, Decodable)]
153pub struct EncodedClientSecretKeyPrefix;
154
155impl_db_record!(
156    key = EncodedClientSecretKey,
157    value = Vec<u8>,
158    db_prefix = DbKeyPrefix::EncodedClientSecret,
159);
160impl_db_lookup!(
161    key = EncodedClientSecretKey,
162    query_prefix = EncodedClientSecretKeyPrefix
163);
164
165#[derive(Debug, Encodable, Decodable, Serialize)]
166pub struct OperationLogKey {
167    pub operation_id: OperationId,
168}
169
170impl_db_record!(
171    key = OperationLogKey,
172    value = OperationLogEntry,
173    db_prefix = DbKeyPrefix::OperationLog
174);
175
176#[derive(Debug, Encodable)]
177pub struct OperationLogKeyPrefix;
178
179impl_db_lookup!(key = OperationLogKey, query_prefix = OperationLogKeyPrefix);
180
181#[derive(Debug, Encodable, Decodable, Serialize)]
182pub struct OperationLogKeyV0 {
183    pub operation_id: OperationId,
184}
185
186#[derive(Debug, Encodable)]
187pub struct OperationLogKeyPrefixV0;
188
189impl_db_record!(
190    key = OperationLogKeyV0,
191    value = OperationLogEntryV0,
192    db_prefix = DbKeyPrefix::OperationLog
193);
194
195impl_db_lookup!(
196    key = OperationLogKeyV0,
197    query_prefix = OperationLogKeyPrefixV0
198);
199
200#[derive(Debug, Encodable, Decodable, Serialize)]
201pub struct ClientPreRootSecretHashKey;
202
203impl_db_record!(
204    key = ClientPreRootSecretHashKey,
205    value = [u8; 8],
206    db_prefix = DbKeyPrefix::ClientPreRootSecretHash
207);
208
209/// Key used to lookup operation log entries in chronological order
210#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize, Deserialize)]
211pub struct ChronologicalOperationLogKey {
212    pub creation_time: std::time::SystemTime,
213    pub operation_id: OperationId,
214}
215
216impl Encodable for ChronologicalOperationLogKey {
217    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
218        encode_legacy_system_time(&self.creation_time, writer)?;
219        self.operation_id.consensus_encode(writer)
220    }
221}
222
223impl Decodable for ChronologicalOperationLogKey {
224    fn consensus_decode_partial_from_finite_reader<D: std::io::Read>(
225        decoder: &mut D,
226        modules: &ModuleDecoderRegistry,
227    ) -> Result<Self, DecodeError> {
228        Ok(Self {
229            creation_time: with_decoding_context(
230                decode_legacy_system_time_from_finite_reader(decoder, modules),
231                "Decoding named block field: ChronologicalOperationLogKey{ ... creation_time ... }",
232            )?,
233            operation_id: decode_field_from_finite_reader(
234                decoder,
235                modules,
236                "Decoding named block field: ChronologicalOperationLogKey{ ... operation_id ... }",
237            )?,
238        })
239    }
240}
241
242#[derive(Debug, Encodable)]
243pub struct ChronologicalOperationLogKeyPrefix;
244
245impl_db_record!(
246    key = ChronologicalOperationLogKey,
247    value = (),
248    db_prefix = DbKeyPrefix::ChronologicalOperationLog
249);
250
251impl_db_lookup!(
252    key = ChronologicalOperationLogKey,
253    query_prefix = ChronologicalOperationLogKeyPrefix
254);
255
256#[derive(Debug, Encodable, Decodable)]
257pub struct CachedApiVersionSetKey;
258
259#[derive(Debug, Encodable, Decodable)]
260pub struct CachedApiVersionSet(pub ApiVersionSet);
261
262impl_db_record!(
263    key = CachedApiVersionSetKey,
264    value = CachedApiVersionSet,
265    db_prefix = DbKeyPrefix::CommonApiVersionCache
266);
267
268#[derive(Debug, Encodable, Decodable)]
269pub struct PeerLastApiVersionsSummaryKey(pub PeerId);
270
271#[derive(Debug, Encodable, Decodable)]
272pub struct PeerLastApiVersionsSummary(pub SupportedApiVersionsSummary);
273
274impl_db_record!(
275    key = PeerLastApiVersionsSummaryKey,
276    value = PeerLastApiVersionsSummary,
277    db_prefix = DbKeyPrefix::PeerLastApiVersionsSummaryCache
278);
279
280#[derive(Debug, Encodable, Decodable, Serialize)]
281pub struct ClientConfigKey;
282
283impl_db_record!(
284    key = ClientConfigKey,
285    value = ClientConfig,
286    db_prefix = DbKeyPrefix::ClientConfig
287);
288
289#[derive(Debug, Encodable, Decodable, Serialize)]
290pub struct PendingClientConfigKey;
291
292impl_db_record!(
293    key = PendingClientConfigKey,
294    value = ClientConfig,
295    db_prefix = DbKeyPrefix::PendingClientConfig
296);
297
298#[derive(Debug, Encodable, Decodable, Serialize)]
299pub struct ClientConfigKeyV0 {
300    pub id: FederationId,
301}
302
303#[derive(Debug, Encodable)]
304pub struct ClientConfigKeyPrefixV0;
305
306impl_db_record!(
307    key = ClientConfigKeyV0,
308    value = ClientConfigV0,
309    db_prefix = DbKeyPrefix::ClientConfig
310);
311
312impl_db_lookup!(
313    key = ClientConfigKeyV0,
314    query_prefix = ClientConfigKeyPrefixV0
315);
316
317#[derive(Debug, Encodable, Decodable, Serialize)]
318pub struct ApiSecretKey;
319
320#[derive(Debug, Encodable)]
321pub struct ApiSecretKeyPrefix;
322
323impl_db_record!(
324    key = ApiSecretKey,
325    value = String,
326    db_prefix = DbKeyPrefix::ApiSecret
327);
328
329impl_db_lookup!(key = ApiSecretKey, query_prefix = ApiSecretKeyPrefix);
330
331/// Cached chain ID (bitcoin block hash at height 1) from the federation
332#[derive(Debug, Encodable, Decodable, Serialize)]
333pub struct ChainIdKey;
334
335impl_db_record!(
336    key = ChainIdKey,
337    value = ChainId,
338    db_prefix = DbKeyPrefix::ChainId
339);
340
341/// Fees paid per transaction, stored at finalization time
342#[derive(Debug, Encodable, Decodable)]
343pub struct TransactionFeesKey(pub TransactionId);
344
345impl_db_record!(
346    key = TransactionFeesKey,
347    value = Amounts,
348    db_prefix = DbKeyPrefix::TransactionFees,
349);
350
351/// Client metadata that will be stored/restored on backup&recovery
352#[derive(Debug, Encodable, Decodable, Serialize)]
353pub struct ClientMetadataKey;
354
355#[derive(Debug, Encodable)]
356pub struct ClientMetadataPrefix;
357
358impl_db_record!(
359    key = ClientMetadataKey,
360    value = Metadata,
361    db_prefix = DbKeyPrefix::ClientMetadata
362);
363
364impl_db_lookup!(key = ClientMetadataKey, query_prefix = ClientMetadataPrefix);
365
366/// Does the client modules need to run recovery before being usable?
367#[derive(Debug, Encodable, Decodable, Serialize)]
368pub struct ClientInitStateKey;
369
370#[derive(Debug, Encodable)]
371pub struct ClientInitStatePrefix;
372
373/// Client initialization mode
374#[derive(Debug, Encodable, Decodable)]
375pub enum InitMode {
376    /// Should only be used with freshly generated root secret
377    Fresh,
378    /// Should be used with root secrets provided by the user to recover a
379    /// (even if just possibly) already used secret.
380    Recover { snapshot: Option<ClientBackup> },
381}
382
383/// Like `InitMode`, but without no longer required data.
384///
385/// This is distinct from `InitMode` to prevent holding on to `snapshot`
386/// forever both for user's privacy and space use. In case user get hacked
387/// or phone gets stolen.
388#[derive(Debug, Encodable, Decodable)]
389pub enum InitModeComplete {
390    Fresh,
391    Recover,
392}
393
394/// The state of the client initialization
395#[derive(Debug, Encodable, Decodable)]
396pub enum InitState {
397    /// Client data initialization might still require some work (e.g. client
398    /// recovery)
399    Pending(InitMode),
400    /// Client initialization was complete
401    Complete(InitModeComplete),
402}
403
404impl InitState {
405    pub fn into_complete(self) -> Self {
406        match self {
407            InitState::Pending(p) => InitState::Complete(match p {
408                InitMode::Fresh => InitModeComplete::Fresh,
409                InitMode::Recover { .. } => InitModeComplete::Recover,
410            }),
411            InitState::Complete(t) => InitState::Complete(t),
412        }
413    }
414
415    pub fn does_require_recovery(&self) -> Option<Option<ClientBackup>> {
416        match self {
417            InitState::Pending(p) => match p {
418                InitMode::Fresh => None,
419                InitMode::Recover { snapshot } => Some(snapshot.clone()),
420            },
421            InitState::Complete(_) => None,
422        }
423    }
424
425    pub fn is_pending(&self) -> bool {
426        match self {
427            InitState::Pending(_) => true,
428            InitState::Complete(_) => false,
429        }
430    }
431}
432
433impl_db_record!(
434    key = ClientInitStateKey,
435    value = InitState,
436    db_prefix = DbKeyPrefix::ClientInitState
437);
438
439impl_db_lookup!(
440    key = ClientInitStateKey,
441    query_prefix = ClientInitStatePrefix
442);
443
444#[derive(Debug, Encodable, Decodable, Serialize)]
445pub struct ClientModuleRecovery {
446    pub module_instance_id: ModuleInstanceId,
447}
448
449#[derive(Debug, Clone, Encodable, Decodable)]
450pub struct ClientModuleRecoveryState {
451    pub progress: RecoveryProgress,
452}
453
454impl ClientModuleRecoveryState {
455    pub fn is_done(&self) -> bool {
456        self.progress.is_done()
457    }
458}
459
460impl_db_record!(
461    key = ClientModuleRecovery,
462    value = ClientModuleRecoveryState,
463    db_prefix = DbKeyPrefix::ClientModuleRecovery,
464);
465
466/// Old (incorrect) version of the [`ClientModuleRecoveryState`]
467/// that used the wrong prefix.
468///
469/// See <https://github.com/fedimint/fedimint/issues/7367>.
470///
471/// Used only for the migration.
472#[derive(Debug, Encodable, Decodable, Serialize)]
473pub struct ClientModuleRecoveryIncorrectDoNotUse {
474    pub module_instance_id: ModuleInstanceId,
475}
476
477impl_db_record!(
478    key = ClientModuleRecoveryIncorrectDoNotUse,
479    value = ClientModuleRecoveryState,
480    // This was wrong and we keep it wrong for a migration.
481    db_prefix = DbKeyPrefix::ClientInitState,
482);
483
484/// Last valid backup the client attempted to make
485///
486/// Can be used to find previous valid versions of
487/// module backup.
488#[derive(Debug, Encodable, Decodable)]
489pub struct LastBackupKey;
490
491impl_db_record!(
492    key = LastBackupKey,
493    value = ClientBackup,
494    db_prefix = DbKeyPrefix::ClientLastBackup
495);
496
497#[derive(Encodable, Decodable, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
498pub(crate) struct MetaFieldPrefix;
499
500#[derive(Encodable, Decodable, Debug)]
501pub struct MetaServiceInfoKey;
502
503#[derive(Debug)]
504pub struct MetaServiceInfo {
505    pub last_updated: SystemTime,
506    pub revision: u64,
507}
508
509impl Encodable for MetaServiceInfo {
510    fn consensus_encode<W: std::io::Write>(&self, writer: &mut W) -> Result<(), std::io::Error> {
511        encode_legacy_system_time(&self.last_updated, writer)?;
512        self.revision.consensus_encode(writer)
513    }
514}
515
516impl Decodable for MetaServiceInfo {
517    fn consensus_decode_partial_from_finite_reader<D: std::io::Read>(
518        decoder: &mut D,
519        modules: &ModuleDecoderRegistry,
520    ) -> Result<Self, DecodeError> {
521        Ok(Self {
522            last_updated: with_decoding_context(
523                decode_legacy_system_time_from_finite_reader(decoder, modules),
524                "Decoding named block field: MetaServiceInfo{ ... last_updated ... }",
525            )?,
526            revision: decode_field_from_finite_reader(
527                decoder,
528                modules,
529                "Decoding named block field: MetaServiceInfo{ ... revision ... }",
530            )?,
531        })
532    }
533}
534
535#[derive(
536    Encodable, Decodable, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize,
537)]
538pub(crate) struct MetaFieldKey(pub fedimint_client_module::meta::MetaFieldKey);
539
540#[derive(Encodable, Decodable, Debug, Clone, Serialize, Deserialize)]
541pub(crate) struct MetaFieldValue(pub fedimint_client_module::meta::MetaFieldValue);
542
543impl_db_record!(
544    key = MetaFieldKey,
545    value = MetaFieldValue,
546    db_prefix = DbKeyPrefix::ClientMetaField
547);
548
549impl_db_record!(
550    key = MetaServiceInfoKey,
551    value = MetaServiceInfo,
552    db_prefix = DbKeyPrefix::ClientMetaServiceInfo
553);
554
555impl_db_lookup!(key = MetaFieldKey, query_prefix = MetaFieldPrefix);
556
557pub fn get_core_client_database_migrations()
558-> BTreeMap<DatabaseVersion, fedimint_core::db::ClientCoreDbMigrationFn> {
559    let mut migrations: BTreeMap<DatabaseVersion, fedimint_core::db::ClientCoreDbMigrationFn> =
560        BTreeMap::new();
561    migrations.insert(
562        DatabaseVersion(0),
563        Box::new(|mut ctx| {
564            Box::pin(async move {
565                let mut dbtx = ctx.dbtx();
566
567                let config_v0 = dbtx
568                    .find_by_prefix(&ClientConfigKeyPrefixV0)
569                    .await
570                    .collect::<Vec<_>>()
571                    .await;
572
573                assert!(config_v0.len() <= 1);
574                let Some((id, config_v0)) = config_v0.into_iter().next() else {
575                    return Ok(());
576                };
577
578                let global = GlobalClientConfig {
579                    api_endpoints: config_v0.global.api_endpoints,
580                    broadcast_public_keys: None,
581                    consensus_version: config_v0.global.consensus_version,
582                    meta: config_v0.global.meta,
583                };
584
585                let config = ClientConfig {
586                    global,
587                    modules: config_v0.modules,
588                };
589
590                dbtx.remove_entry(&id).await;
591                dbtx.insert_new_entry(&ClientConfigKey, &config).await;
592                Ok(())
593            })
594        }),
595    );
596
597    // Migration to add outcome_time to OperationLogEntry
598    migrations.insert(
599        DatabaseVersion(1),
600        Box::new(|mut ctx| {
601            Box::pin(async move {
602                let mut dbtx = ctx.dbtx();
603
604                // Read all OperationLogEntries using V0 format
605                let operation_logs = dbtx
606                    .find_by_prefix(&OperationLogKeyPrefixV0)
607                    .await
608                    .collect::<Vec<_>>()
609                    .await;
610
611                // Build a map from operation_id -> max_time of inactive state
612                let mut op_id_max_time = BTreeMap::new();
613
614                // Process inactive states
615                {
616                    let mut inactive_states_stream =
617                        dbtx.find_by_prefix(&InactiveStateKeyPrefixBytes).await;
618
619                    while let Some((state, meta)) = inactive_states_stream.next().await {
620                        let entry = op_id_max_time
621                            .entry(state.operation_id)
622                            .or_insert(meta.exited_at);
623                        *entry = (*entry).max(meta.exited_at);
624                    }
625                }
626                // Migrate each V0 operation log entry to the new format
627                for (op_key_v0, log_entry_v0) in operation_logs {
628                    let new_entry = OperationLogEntry::new(
629                        log_entry_v0.operation_module_kind,
630                        log_entry_v0.meta,
631                        log_entry_v0.outcome.map(|outcome| {
632                            OperationOutcome {
633                                outcome,
634                                // If we found state times, use the max, otherwise use
635                                // current time
636                                time: op_id_max_time
637                                    .get(&op_key_v0.operation_id)
638                                    .copied()
639                                    .unwrap_or_else(fedimint_core::time::now),
640                            }
641                        }),
642                    );
643
644                    dbtx.remove_entry(&op_key_v0).await;
645                    dbtx.insert_entry(
646                        &OperationLogKey {
647                            operation_id: op_key_v0.operation_id,
648                        },
649                        &new_entry,
650                    )
651                    .await;
652                }
653
654                Ok(())
655            })
656        }),
657    );
658
659    // Fix #6948
660    migrations.insert(
661        DatabaseVersion(2),
662        Box::new(|mut ctx: fedimint_core::db::DbMigrationFnContext<'_, _>| {
663            Box::pin(async move {
664                let mut dbtx = ctx.dbtx();
665
666                // Migrate unordered keys that got written to ordered table
667                {
668                    let mut ordered_log_entries = dbtx
669                        .raw_find_by_prefix(&[DB_KEY_PREFIX_EVENT_LOG])
670                        .await
671                        .expect("DB operation failed");
672                    let mut keys_to_migrate = vec![];
673                    while let Some((k, _v)) = ordered_log_entries.next().await {
674                        trace!(target: LOG_CLIENT_DB,
675                            k=%k.as_hex(),
676                            "Checking ordered log key"
677                        );
678                        if EventLogId::consensus_decode_whole(&k[1..], &Default::default()).is_err()
679                        {
680                            assert!(
681                                UnordedEventLogId::consensus_decode_whole(
682                                    &k[1..],
683                                    &Default::default()
684                                )
685                                .is_ok()
686                            );
687                            keys_to_migrate.push(k);
688                        }
689                    }
690                    drop(ordered_log_entries);
691                    for mut key_to_migrate in keys_to_migrate {
692                        warn!(target: LOG_CLIENT_DB,
693                            k=%key_to_migrate.as_hex(),
694                            "Migrating unordered event log entry written to an ordered log"
695                        );
696                        let v = dbtx
697                            .raw_remove_entry(&key_to_migrate)
698                            .await
699                            .expect("DB operation failed")
700                            .expect("Was there a moment ago");
701                        assert_eq!(key_to_migrate[0], 0x39);
702                        key_to_migrate[0] = DB_KEY_PREFIX_UNORDERED_EVENT_LOG;
703                        assert_eq!(key_to_migrate[0], 0x3a);
704                        dbtx.raw_insert_bytes(&key_to_migrate, &v)
705                            .await
706                            .expect("DB operation failed");
707                    }
708                }
709
710                // Migrate ordered keys that got written to unordered table
711                {
712                    let mut unordered_log_entries = dbtx
713                        .raw_find_by_prefix(&[DB_KEY_PREFIX_UNORDERED_EVENT_LOG])
714                        .await
715                        .expect("DB operation failed");
716                    let mut keys_to_migrate = vec![];
717                    while let Some((k, _v)) = unordered_log_entries.next().await {
718                        trace!(target: LOG_CLIENT_DB,
719                            k=%k.as_hex(),
720                            "Checking unordered log key"
721                        );
722                        if UnordedEventLogId::consensus_decode_whole(&k[1..], &Default::default())
723                            .is_err()
724                        {
725                            assert!(
726                                EventLogId::consensus_decode_whole(&k[1..], &Default::default())
727                                    .is_ok()
728                            );
729                            keys_to_migrate.push(k);
730                        }
731                    }
732                    drop(unordered_log_entries);
733                    for mut key_to_migrate in keys_to_migrate {
734                        warn!(target: LOG_CLIENT_DB,
735                            k=%key_to_migrate.as_hex(),
736                            "Migrating ordered event log entry written to an unordered log"
737                        );
738                        let v = dbtx
739                            .raw_remove_entry(&key_to_migrate)
740                            .await
741                            .expect("DB operation failed")
742                            .expect("Was there a moment ago");
743                        assert_eq!(key_to_migrate[0], 0x3a);
744                        key_to_migrate[0] = DB_KEY_PREFIX_EVENT_LOG;
745                        assert_eq!(key_to_migrate[0], 0x39);
746                        dbtx.raw_insert_bytes(&key_to_migrate, &v)
747                            .await
748                            .expect("DB operation failed");
749                    }
750                }
751                Ok(())
752            })
753        }),
754    );
755
756    // Fix #7367
757    migrations.insert(
758        DatabaseVersion(3),
759        Box::new(|mut ctx: fedimint_core::db::DbMigrationFnContext<'_, _>| {
760            Box::pin(async move {
761                let mut dbtx = ctx.dbtx();
762
763                for module_id in 0..u16::MAX {
764                    let old_key = ClientModuleRecoveryIncorrectDoNotUse {
765                        module_instance_id: module_id,
766                    };
767                    let new_key = ClientModuleRecovery {
768                        module_instance_id: module_id,
769                    };
770                    let Some(value) = dbtx.get_value(&old_key).await else {
771                        debug!(target: LOG_CLIENT_DB, %module_id, "No more ClientModuleRecovery keys found for migration");
772                        break;
773                    };
774
775                    debug!(target: LOG_CLIENT_DB, %module_id, "Migrating old ClientModuleRecovery key");
776                    dbtx.remove_entry(&old_key).await.expect("Is there.");
777                    assert!(dbtx.insert_entry(&new_key, &value).await.is_none());
778                }
779
780                Ok(())
781            })
782        }),
783    );
784    migrations
785}
786
787/// Apply core client database migrations
788///
789/// TODO: This should be private.
790pub async fn apply_migrations_core_client_dbtx(
791    dbtx: &mut DatabaseTransaction<'_>,
792    kind: String,
793) -> Result<(), DbMigrationError> {
794    apply_migrations_dbtx(
795        dbtx,
796        (),
797        kind,
798        get_core_client_database_migrations(),
799        None,
800        Some(DbKeyPrefix::UserData as u8),
801    )
802    .await
803}
804
805/// `apply_migrations_client` iterates from the on disk database version for the
806/// client module up to `target_db_version` and executes all of the migrations
807/// that exist in the migrations map, including state machine migrations.
808/// Each migration in the migrations map updates the database to have the
809/// correct on-disk data structures that the code is expecting. The entire
810/// process is atomic, (i.e migration from 0->1 and 1->2 happen atomically).
811/// This function is called before the module is initialized and as long as the
812/// correct migrations are supplied in the migrations map, the module
813/// will be able to read and write from the database successfully.
814pub async fn apply_migrations_client_module(
815    db: &Database,
816    kind: String,
817    migrations: BTreeMap<DatabaseVersion, ClientModuleMigrationFn>,
818    module_instance_id: ModuleInstanceId,
819) -> Result<(), DbMigrationError> {
820    let mut dbtx = db.begin_transaction().await;
821    apply_migrations_client_module_dbtx(
822        &mut dbtx.to_ref_nc(),
823        kind,
824        migrations,
825        module_instance_id,
826    )
827    .await?;
828    Ok(dbtx.commit_tx_result().await?)
829}
830
831pub async fn apply_migrations_client_module_dbtx(
832    dbtx: &mut DatabaseTransaction<'_>,
833    kind: String,
834    migrations: BTreeMap<DatabaseVersion, ClientModuleMigrationFn>,
835    module_instance_id: ModuleInstanceId,
836) -> Result<(), DbMigrationError> {
837    // Newly created databases will not have any data underneath the
838    // `MODULE_GLOBAL_PREFIX` since they have just been instantiated.
839    let is_new_db = dbtx
840        .raw_find_by_prefix(&[MODULE_GLOBAL_PREFIX])
841        .await?
842        .next()
843        .await
844        .is_none();
845
846    let target_version = get_current_database_version(&migrations);
847
848    // First write the database version to disk if it does not exist.
849    create_database_version_dbtx(
850        dbtx,
851        target_version,
852        Some(module_instance_id),
853        kind.clone(),
854        is_new_db,
855    )
856    .await;
857
858    let current_version = dbtx
859        .get_value(&DatabaseVersionKey(module_instance_id))
860        .await;
861
862    let db_version = if let Some(mut current_version) = current_version {
863        if current_version == target_version {
864            trace!(
865                target: LOG_CLIENT_DB,
866                %current_version,
867                %target_version,
868                module_instance_id,
869                kind,
870                "Database version up to date"
871            );
872            return Ok(());
873        }
874
875        if target_version < current_version {
876            return Err(DbMigrationError::VersionTooHigh {
877                kind,
878                on_disk: current_version,
879                target: target_version,
880            });
881        }
882
883        info!(
884            target: LOG_CLIENT_DB,
885            %current_version,
886            %target_version,
887            module_instance_id,
888            kind,
889            "Migrating client module database"
890        );
891        let mut active_states = get_active_states(&mut dbtx.to_ref_nc(), module_instance_id).await;
892        let mut inactive_states =
893            get_inactive_states(&mut dbtx.to_ref_nc(), module_instance_id).await;
894
895        while current_version < target_version {
896            let new_states = if let Some(migration) = migrations.get(&current_version) {
897                debug!(
898                     target: LOG_CLIENT_DB,
899                     module_instance_id,
900                     %kind,
901                     %current_version,
902                     %target_version,
903                     "Running module db migration");
904
905                migration(
906                    &mut dbtx
907                        .to_ref_with_prefix_module_id(module_instance_id)
908                        .0
909                        .into_nc(),
910                    active_states.clone(),
911                    inactive_states.clone(),
912                )
913                .await?
914            } else {
915                warn!(
916                    target: LOG_CLIENT_DB,
917                    ?current_version, "Missing client db migration");
918                None
919            };
920
921            // If the client migration returned new states, a state machine migration has
922            // occurred, and the new states need to be persisted to the database.
923            if let Some((new_active_states, new_inactive_states)) = new_states {
924                remove_old_and_persist_new_active_states(
925                    &mut dbtx.to_ref_nc(),
926                    new_active_states.clone(),
927                    active_states.clone(),
928                    module_instance_id,
929                )
930                .await;
931                remove_old_and_persist_new_inactive_states(
932                    &mut dbtx.to_ref_nc(),
933                    new_inactive_states.clone(),
934                    inactive_states.clone(),
935                    module_instance_id,
936                )
937                .await;
938
939                // the new states become the old states for the next migration
940                active_states = new_active_states;
941                inactive_states = new_inactive_states;
942            }
943
944            current_version = current_version.increment();
945            dbtx.insert_entry(&DatabaseVersionKey(module_instance_id), &current_version)
946                .await;
947        }
948
949        current_version
950    } else {
951        target_version
952    };
953
954    debug!(
955        target: LOG_CLIENT_DB,
956        ?kind, ?db_version, "Client DB Version");
957    Ok(())
958}
959
960/// Reads all active states from the database and returns `Vec<DynState>`.
961/// TODO: It is unfortunate that we can't read states by the module's instance
962/// id so we are forced to return all active states. Once we do a db migration
963/// to add `module_instance_id` to `ActiveStateKey`, this can be improved to
964/// only read the module's relevant states.
965pub async fn get_active_states(
966    dbtx: &mut DatabaseTransaction<'_>,
967    module_instance_id: ModuleInstanceId,
968) -> Vec<(Vec<u8>, OperationId)> {
969    dbtx.find_by_prefix(&ActiveStateKeyPrefixBytes)
970        .await
971        .filter_map(|(state, _)| async move {
972            if module_instance_id == state.module_instance_id {
973                Some((state.state, state.operation_id))
974            } else {
975                None
976            }
977        })
978        .collect::<Vec<_>>()
979        .await
980}
981
982/// Reads all inactive states from the database and returns `Vec<DynState>`.
983/// TODO: It is unfortunate that we can't read states by the module's instance
984/// id so we are forced to return all inactive states. Once we do a db migration
985/// to add `module_instance_id` to `InactiveStateKey`, this can be improved to
986/// only read the module's relevant states.
987pub async fn get_inactive_states(
988    dbtx: &mut DatabaseTransaction<'_>,
989    module_instance_id: ModuleInstanceId,
990) -> Vec<(Vec<u8>, OperationId)> {
991    dbtx.find_by_prefix(&InactiveStateKeyPrefixBytes)
992        .await
993        .filter_map(|(state, _)| async move {
994            if module_instance_id == state.module_instance_id {
995                Some((state.state, state.operation_id))
996            } else {
997                None
998            }
999        })
1000        .collect::<Vec<_>>()
1001        .await
1002}
1003
1004/// Persists new active states by first removing all current active states, and
1005/// re-writing with the new set of active states. `new_active_states` is
1006/// expected to contain all active states, not just the newly created states.
1007pub async fn remove_old_and_persist_new_active_states(
1008    dbtx: &mut DatabaseTransaction<'_>,
1009    new_active_states: Vec<(Vec<u8>, OperationId)>,
1010    states_to_remove: Vec<(Vec<u8>, OperationId)>,
1011    module_instance_id: ModuleInstanceId,
1012) {
1013    // Remove all existing active states
1014    for (bytes, operation_id) in states_to_remove {
1015        dbtx.remove_entry(&ActiveStateKeyBytes {
1016            operation_id,
1017            module_instance_id,
1018            state: bytes,
1019        })
1020        .await
1021        .expect("Did not delete anything");
1022    }
1023
1024    // Insert new "migrated" active states
1025    for (bytes, operation_id) in new_active_states {
1026        dbtx.insert_new_entry(
1027            &ActiveStateKeyBytes {
1028                operation_id,
1029                module_instance_id,
1030                state: bytes,
1031            },
1032            &ActiveStateMeta::default(),
1033        )
1034        .await;
1035    }
1036}
1037
1038/// Persists new inactive states by first removing all current inactive states,
1039/// and re-writing with the new set of inactive states. `new_inactive_states` is
1040/// expected to contain all inactive states, not just the newly created states.
1041pub async fn remove_old_and_persist_new_inactive_states(
1042    dbtx: &mut DatabaseTransaction<'_>,
1043    new_inactive_states: Vec<(Vec<u8>, OperationId)>,
1044    states_to_remove: Vec<(Vec<u8>, OperationId)>,
1045    module_instance_id: ModuleInstanceId,
1046) {
1047    // Remove all existing active states
1048    for (bytes, operation_id) in states_to_remove {
1049        dbtx.remove_entry(&InactiveStateKeyBytes {
1050            operation_id,
1051            module_instance_id,
1052            state: bytes,
1053        })
1054        .await
1055        .expect("Did not delete anything");
1056    }
1057
1058    // Insert new "migrated" inactive states
1059    for (bytes, operation_id) in new_inactive_states {
1060        dbtx.insert_new_entry(
1061            &InactiveStateKeyBytes {
1062                operation_id,
1063                module_instance_id,
1064                state: bytes,
1065            },
1066            &InactiveStateMeta {
1067                created_at: fedimint_core::time::now(),
1068                exited_at: fedimint_core::time::now(),
1069            },
1070        )
1071        .await;
1072    }
1073}
1074
1075/// Fetches the encoded client secret from the database and decodes it.
1076/// If an encoded client secret is not present in the database, or if
1077/// decoding fails, an error is returned.
1078pub async fn get_decoded_client_secret<T: Decodable>(
1079    db: &Database,
1080) -> Result<T, ClientSecretError> {
1081    let mut tx = db.begin_transaction_nc().await;
1082    let client_secret = tx.get_value(&EncodedClientSecretKey).await;
1083
1084    match client_secret {
1085        Some(client_secret) => Ok(T::consensus_decode_whole(
1086            &client_secret,
1087            &ModuleRegistry::default(),
1088        )?),
1089        None => Err(ClientSecretError::NotPresent),
1090    }
1091}
1092
1093/// V0 version of operation log entry for migration purposes
1094#[derive(Debug, Serialize, Deserialize, Encodable, Decodable)]
1095pub struct OperationLogEntryV0 {
1096    pub(crate) operation_module_kind: String,
1097    pub(crate) meta: JsonStringed,
1098    pub(crate) outcome: Option<JsonStringed>,
1099}