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            .with_iroh_enable_next(true);
87        client_builder.with_module_inits(registry);
88        Ok(client_builder)
89    }
90
91    /// Recovers a client with the provided mnemonic. This function will wait
92    /// for the recoveries to finish, but a new client must be created
93    /// afterwards and waited on until the state machines have finished
94    /// for a balance to be present.
95    pub async fn recover(
96        &self,
97        config: FederationConfig,
98        gateway: Arc<Gateway>,
99        mnemonic: &Mnemonic,
100    ) -> AdminResult<()> {
101        let federation_id = config.invite_code.federation_id();
102        let db = gateway.gateway_db.get_client_database(&federation_id);
103        let client_builder = self.create_client_builder(&config, gateway.clone()).await?;
104        let root_secret = RootSecret::StandardDoubleDerive(
105            Bip39RootSecretStrategy::<12>::to_root_secret(mnemonic),
106        );
107        let client = client_builder
108            .preview(self.connectors.clone(), &config.invite_code)
109            .await?
110            .recover(db, root_secret, None)
111            .await
112            .map(Arc::new)
113            .map_err(AdminGatewayError::ClientCreationError)?;
114        client
115            .wait_for_all_recoveries()
116            .await
117            .map_err(AdminGatewayError::ClientCreationError)?;
118        Ok(())
119    }
120
121    /// Builds a new client with the provided `FederationConfig` and `Mnemonic`.
122    /// Only used for newly joined federations.
123    pub async fn build(
124        &self,
125        config: FederationConfig,
126        gateway: Arc<Gateway>,
127        mnemonic: &Mnemonic,
128    ) -> AdminResult<fedimint_client::ClientHandleArc> {
129        let invite_code = config.invite_code.clone();
130        let federation_id = invite_code.federation_id();
131        let db_path = self.work_dir.join(format!("{federation_id}.db"));
132
133        let (db, root_secret) = if db_path.exists() {
134            let db = match self.db_backend {
135                DatabaseBackend::RocksDb => {
136                    let rocksdb = fedimint_rocksdb::RocksDb::build(db_path.clone())
137                        .open()
138                        .await
139                        .map_err(AdminGatewayError::ClientCreationError)?;
140                    Database::new(rocksdb, ModuleDecoderRegistry::default())
141                }
142                DatabaseBackend::CursedRedb => {
143                    let cursed_redb = fedimint_cursed_redb::MemAndRedb::new(db_path.clone())
144                        .await
145                        .map_err(AdminGatewayError::ClientCreationError)?;
146                    Database::new(cursed_redb, ModuleDecoderRegistry::default())
147                }
148            };
149            let root_secret = RootSecret::Custom(self.client_plainrootsecret(&db).await?);
150            (db, root_secret)
151        } else {
152            let db = gateway.gateway_db.get_client_database(&federation_id);
153
154            let root_secret = RootSecret::StandardDoubleDerive(
155                Bip39RootSecretStrategy::<12>::to_root_secret(mnemonic),
156            );
157            (db, root_secret)
158        };
159
160        Self::verify_client_config(&db, federation_id).await?;
161
162        let client_builder = self.create_client_builder(&config, gateway).await?;
163
164        if Client::is_initialized(&db).await {
165            client_builder
166                .open(self.connectors.clone(), db, root_secret)
167                .await
168        } else {
169            client_builder
170                .preview(self.connectors.clone(), &invite_code)
171                .await?
172                .join(db, root_secret)
173                .await
174        }
175        .map(Arc::new)
176        .map_err(AdminGatewayError::ClientCreationError)
177    }
178
179    /// Verifies that the saved `ClientConfig` contains the expected
180    /// federation's config.
181    async fn verify_client_config(db: &Database, federation_id: FederationId) -> AdminResult<()> {
182        let mut dbtx = db.begin_transaction_nc().await;
183        if let Some(config) = dbtx.get_value(&ClientConfigKey).await
184            && config.calculate_federation_id() != federation_id
185        {
186            return Err(AdminGatewayError::ClientCreationError(anyhow::anyhow!(
187                "Federation Id did not match saved federation ID".to_string()
188            )));
189        }
190        Ok(())
191    }
192
193    /// Returns a vector of "legacy" federations which did not derive their
194    /// client secret's from the gateway's mnemonic.
195    pub fn legacy_federations(&self, all_federations: BTreeSet<FederationId>) -> Vec<FederationId> {
196        all_federations
197            .into_iter()
198            .filter(|federation_id| {
199                let db_path = self.work_dir.join(format!("{federation_id}.db"));
200                db_path.exists()
201            })
202            .collect::<Vec<FederationId>>()
203    }
204}