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