Skip to main content

fedimint_gateway_server/
client.rs

1use std::collections::BTreeSet;
2use std::fmt::Debug;
3use std::path::PathBuf;
4use std::sync::Arc;
5
6use fedimint_bip39::{Bip39RootSecretStrategy, Mnemonic};
7use fedimint_client::db::ClientConfigKey;
8use fedimint_client::meta::MetaService;
9use fedimint_client::module_init::ClientModuleInitRegistry;
10use fedimint_client::{Client, ClientBuilder, RootSecret};
11use fedimint_client_module::meta::LegacyMetaSource;
12use fedimint_client_module::secret::{PlainRootSecretStrategy, RootSecretStrategy};
13use fedimint_connectors::ConnectorRegistry;
14use fedimint_core::config::FederationId;
15use fedimint_core::db::{Database, IDatabaseTransactionOpsCoreTyped};
16use fedimint_core::module::registry::ModuleDecoderRegistry;
17use fedimint_derive_secret::DerivableSecret;
18use fedimint_gateway_common::FederationConfig;
19use fedimint_gateway_server_db::GatewayDbExt as _;
20use fedimint_gw_client::GatewayClientInit;
21use fedimint_gwv2_client::GatewayClientInitV2;
22use fedimint_meta_client::MetaModuleMetaSourceWithFallback;
23
24use crate::config::DatabaseBackend;
25use crate::error::AdminGatewayError;
26use crate::{AdminResult, Gateway};
27
28#[derive(Debug, Clone)]
29pub struct GatewayClientBuilder {
30    work_dir: PathBuf,
31    registry: ClientModuleInitRegistry,
32    db_backend: DatabaseBackend,
33    connectors: ConnectorRegistry,
34}
35
36impl GatewayClientBuilder {
37    pub async fn new(
38        work_dir: PathBuf,
39        registry: ClientModuleInitRegistry,
40        db_backend: DatabaseBackend,
41    ) -> anyhow::Result<Self> {
42        Ok(Self {
43            connectors: ConnectorRegistry::build_from_client_env().bind().await,
44            work_dir,
45            registry,
46            db_backend,
47        })
48    }
49
50    pub fn data_dir(&self) -> PathBuf {
51        self.work_dir.clone()
52    }
53
54    /// Reads a plain root secret from a database to construct a database.
55    /// Only used for "legacy" federations before v0.5.0
56    async fn client_plainrootsecret(&self, db: &Database) -> AdminResult<DerivableSecret> {
57        let client_secret = Client::load_decodable_client_secret::<[u8; 64]>(db)
58            .await
59            .map_err(|err| AdminGatewayError::ClientCreationError(err.into()))?;
60        Ok(PlainRootSecretStrategy::to_root_secret(&client_secret))
61    }
62
63    /// Constructs the client builder with the modules, database, and connector
64    /// used to create clients for connected federations.
65    async fn create_client_builder(
66        &self,
67        federation_config: &FederationConfig,
68        gateway: Arc<Gateway>,
69    ) -> AdminResult<ClientBuilder> {
70        let FederationConfig {
71            federation_index, ..
72        } = federation_config.to_owned();
73
74        let mut registry = self.registry.clone();
75
76        registry.attach(GatewayClientInit {
77            federation_index,
78            lightning_manager: gateway.clone(),
79        });
80
81        registry.attach(GatewayClientInitV2 {
82            gateway: gateway.clone(),
83        });
84
85        let mut client_builder = Client::builder().await.with_iroh_enable_dht(true);
86        client_builder.with_meta_service(MetaService::new(MetaModuleMetaSourceWithFallback::<
87            LegacyMetaSource,
88        >::default()));
89        client_builder.with_module_inits(registry);
90        Ok(client_builder)
91    }
92
93    /// Recovers a client with the provided mnemonic. This function will wait
94    /// for the recoveries to finish, but a new client must be created
95    /// afterwards and waited on until the state machines have finished
96    /// for a balance to be present.
97    pub async fn recover(
98        &self,
99        config: FederationConfig,
100        gateway: Arc<Gateway>,
101        mnemonic: &Mnemonic,
102    ) -> AdminResult<()> {
103        let federation_id = config.invite_code.federation_id();
104        let db = gateway.gateway_db.get_client_database(&federation_id);
105        let client_builder = self.create_client_builder(&config, gateway.clone()).await?;
106        let root_secret = RootSecret::StandardDoubleDerive(
107            Bip39RootSecretStrategy::<12>::to_root_secret(mnemonic),
108        );
109        let client = client_builder
110            .preview(self.connectors.clone(), &config.invite_code)
111            .await
112            .map_err(|err| AdminGatewayError::ClientCreationError(err.into()))?
113            .recover(db, root_secret, None)
114            .await
115            .map(Arc::new)
116            .map_err(|err| AdminGatewayError::ClientCreationError(err.into()))?;
117        client
118            .wait_for_all_recoveries()
119            .await
120            .map_err(|err| AdminGatewayError::ClientCreationError(err.into()))?;
121        Ok(())
122    }
123
124    /// Builds a new client with the provided `FederationConfig` and `Mnemonic`.
125    /// Only used for newly joined federations.
126    pub async fn build(
127        &self,
128        config: FederationConfig,
129        gateway: Arc<Gateway>,
130        mnemonic: &Mnemonic,
131    ) -> AdminResult<fedimint_client::ClientHandleArc> {
132        let invite_code = config.invite_code.clone();
133        let federation_id = invite_code.federation_id();
134        let db_path = self.work_dir.join(format!("{federation_id}.db"));
135
136        let (db, root_secret) = if db_path.exists() {
137            let db = match self.db_backend {
138                DatabaseBackend::RocksDb => {
139                    let rocksdb = fedimint_rocksdb::RocksDb::build(db_path.clone())
140                        .open()
141                        .await
142                        .map_err(|err| AdminGatewayError::ClientCreationError(err.into()))?;
143                    Database::new(rocksdb, ModuleDecoderRegistry::default())
144                }
145                DatabaseBackend::CursedRedb => {
146                    let cursed_redb = fedimint_cursed_redb::MemAndRedb::new(db_path.clone())
147                        .await
148                        .map_err(|err| AdminGatewayError::ClientCreationError(err.into()))?;
149                    Database::new(cursed_redb, ModuleDecoderRegistry::default())
150                }
151            };
152            let root_secret = RootSecret::Custom(self.client_plainrootsecret(&db).await?);
153            (db, root_secret)
154        } else {
155            let db = gateway.gateway_db.get_client_database(&federation_id);
156
157            let root_secret = RootSecret::StandardDoubleDerive(
158                Bip39RootSecretStrategy::<12>::to_root_secret(mnemonic),
159            );
160            (db, root_secret)
161        };
162
163        Self::verify_client_config(&db, federation_id).await?;
164
165        let client_builder = self.create_client_builder(&config, gateway).await?;
166
167        if Client::is_initialized(&db).await {
168            client_builder
169                .open(self.connectors.clone(), db, root_secret)
170                .await
171        } else {
172            client_builder
173                .preview(self.connectors.clone(), &invite_code)
174                .await
175                .map_err(|err| AdminGatewayError::ClientCreationError(err.into()))?
176                .join(db, root_secret)
177                .await
178        }
179        .map(Arc::new)
180        .map_err(|err| AdminGatewayError::ClientCreationError(err.into()))
181    }
182
183    /// Verifies that the saved `ClientConfig` contains the expected
184    /// federation's config.
185    async fn verify_client_config(db: &Database, federation_id: FederationId) -> AdminResult<()> {
186        let mut dbtx = db.begin_transaction_nc().await;
187        if let Some(config) = dbtx.get_value(&ClientConfigKey).await
188            && config.calculate_federation_id() != federation_id
189        {
190            return Err(AdminGatewayError::ClientCreationError(anyhow::anyhow!(
191                "Federation Id did not match saved federation ID".to_string()
192            )));
193        }
194        Ok(())
195    }
196
197    /// Returns a vector of "legacy" federations which did not derive their
198    /// client secret's from the gateway's mnemonic.
199    pub fn legacy_federations(&self, all_federations: BTreeSet<FederationId>) -> Vec<FederationId> {
200        all_federations
201            .into_iter()
202            .filter(|federation_id| {
203                let db_path = self.work_dir.join(format!("{federation_id}.db"));
204                db_path.exists()
205            })
206            .collect::<Vec<FederationId>>()
207    }
208}