Skip to main content

fedimint_server/config/
setup.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::io::Read as _;
3use std::iter::once;
4use std::mem::discriminant;
5use std::path::{Component, Path, PathBuf};
6use std::str::FromStr as _;
7use std::sync::Arc;
8
9use anyhow::{Context, ensure};
10use async_trait::async_trait;
11use fedimint_core::admin_client::{SetLocalParamsRequest, SetupStatus};
12use fedimint_core::base32::FEDIMINT_PREFIX;
13use fedimint_core::core::{ModuleInstanceId, ModuleKind};
14use fedimint_core::db::Database;
15use fedimint_core::endpoint_constants::{
16    ADD_PEER_SETUP_CODE_ENDPOINT, GET_SETUP_CODE_ENDPOINT, RESET_PEER_SETUP_CODES_ENDPOINT,
17    SET_LOCAL_PARAMS_ENDPOINT, SETUP_STATUS_ENDPOINT, START_DKG_ENDPOINT,
18};
19use fedimint_core::envs::{
20    FM_DISABLE_BASE_FEES_ENV, FM_IROH_API_SECRET_KEY_OVERRIDE_ENV,
21    FM_IROH_P2P_SECRET_KEY_OVERRIDE_ENV, is_env_var_set,
22};
23use fedimint_core::module::{
24    ApiAuth, ApiEndpoint, ApiEndpointContext, ApiError, ApiRequestErased, ApiVersion,
25    admin_api_endpoint, public_api_endpoint,
26};
27use fedimint_core::setup_code::PeerEndpoints;
28use fedimint_core::version::DkgVersion;
29use fedimint_core::{PeerId, base32, runtime};
30use fedimint_server_core::setup_ui::ISetupApi;
31use iroh::SecretKey;
32use rand::rngs::OsRng;
33use tokio::sync::mpsc::Sender;
34use tokio::sync::{Mutex, oneshot};
35use tokio_rustls::rustls;
36
37use crate::config::io::{
38    CONSENSUS_CONFIG, ENCRYPTED_EXT, JSON_EXT, LOCAL_CONFIG, PRIVATE_CONFIG, SALT_FILE,
39    parse_legacy_encrypted_backup, parse_plaintext_backup,
40};
41use crate::config::{ConfigGenParams, ConfigGenSettings, PeerSetupCode, ServerConfig};
42use crate::net::api::HasApiContext;
43use crate::net::p2p_connector::gen_cert_and_key;
44
45/// Result sent from the setup API task to the main setup driver.
46///
47/// Normal DKG sends generated params directly. Restore sends the parsed config
48/// plus a oneshot acknowledgement so the HTTP handler can report success only
49/// after the main setup driver validates and writes the restored config.
50pub enum ConfigGenOutcome {
51    Generated(Box<ConfigGenParams>),
52    Restored(Box<ServerConfig>, oneshot::Sender<Result<(), String>>),
53}
54
55/// State held by the API after receiving a `ConfigGenConnectionsRequest`
56#[derive(Debug, Clone, Default)]
57pub struct SetupState {
58    /// Our local connection
59    local_params: Option<LocalParams>,
60    /// Connection info received from other guardians
61    setup_codes: BTreeSet<PeerSetupCode>,
62    /// Set while a backup restore is being processed
63    restore_in_progress: bool,
64}
65
66#[derive(Clone, Debug)]
67/// Connection information sent between peers in order to start config gen
68pub struct LocalParams {
69    /// Our TLS private key
70    tls_key: Option<Arc<rustls::pki_types::PrivateKeyDer<'static>>>,
71    /// Optional secret key for our iroh api endpoint
72    iroh_api_sk: Option<iroh::SecretKey>,
73    /// Optional secret key for our iroh p2p endpoint
74    iroh_p2p_sk: Option<iroh::SecretKey>,
75    /// Our api and p2p endpoint
76    endpoints: PeerEndpoints,
77    /// Name of the peer, used in TLS auth
78    name: String,
79    /// Whether to disable base fees, set by the leader
80    disable_base_fees: Option<bool>,
81    /// Modules enabled by the leader (if None, all available modules are
82    /// enabled)
83    enabled_modules: Option<BTreeSet<ModuleKind>>,
84    /// Total number of guardians (including the one who sets this), set by the
85    /// leader
86    federation_size: Option<u32>,
87    /// Bitcoin network configured locally
88    network: bitcoin::Network,
89    /// Normalized Fedimint version used for setup and DKG compatibility
90    fedimint_version: DkgVersion,
91}
92
93impl LocalParams {
94    pub fn setup_code(&self) -> PeerSetupCode {
95        PeerSetupCode {
96            name: self.name.clone(),
97            endpoints: self.endpoints.clone(),
98            disable_base_fees: self.disable_base_fees,
99            enabled_modules: self.enabled_modules.clone(),
100            federation_size: self.federation_size,
101            network: self.network,
102            fedimint_version: self.fedimint_version.clone(),
103        }
104    }
105}
106
107fn ensure_fedimint_version_matches(
108    peer_setup_code: &PeerSetupCode,
109    local_fedimint_version: &DkgVersion,
110) -> anyhow::Result<()> {
111    ensure!(
112        peer_setup_code.fedimint_version.compatibility_version()
113            == local_fedimint_version.compatibility_version(),
114        "Guardian uses Fedimint version {} but we use {local_fedimint_version}",
115        peer_setup_code.fedimint_version,
116    );
117
118    Ok(())
119}
120
121/// Serves the config gen API endpoints
122#[derive(Clone)]
123pub struct SetupApi {
124    /// Our config gen settings configured locally
125    settings: ConfigGenSettings,
126    /// In-memory state machine
127    state: Arc<Mutex<SetupState>>,
128    /// DB not really used
129    db: Database,
130    /// Triggers config generation or config restore
131    sender: Sender<ConfigGenOutcome>,
132    /// Exact running version exposed by the setup API and recorded after setup
133    ///
134    /// Compatibility checks parse this boundary value into [`DkgVersion`].
135    code_version_str: String,
136    /// Git hash of the running fedimintd binary
137    code_version_hash: String,
138    /// Password protecting the setup UI login form. `None` ⇒ no login.
139    auth_ui: Option<ApiAuth>,
140    /// Password protecting setup admin RPCs over WS/iroh. `None` ⇒ 401.
141    auth_api: Option<ApiAuth>,
142}
143
144impl SetupApi {
145    pub fn new(
146        settings: ConfigGenSettings,
147        db: Database,
148        sender: Sender<ConfigGenOutcome>,
149        code_version_str: String,
150        code_version_hash: String,
151        auth_ui: Option<ApiAuth>,
152        auth_api: Option<ApiAuth>,
153    ) -> Self {
154        Self {
155            settings,
156            state: Arc::new(Mutex::new(SetupState::default())),
157            db,
158            sender,
159            code_version_str,
160            code_version_hash,
161            auth_ui,
162            auth_api,
163        }
164    }
165
166    pub async fn setup_status(&self) -> SetupStatus {
167        match self.state.lock().await.local_params {
168            Some(..) => SetupStatus::SharingConnectionCodes,
169            None => SetupStatus::AwaitingLocalParams,
170        }
171    }
172}
173
174fn is_expected_backup_path(path: &Path) -> bool {
175    let expected_paths = [
176        PathBuf::from(LOCAL_CONFIG).with_extension(JSON_EXT),
177        PathBuf::from(CONSENSUS_CONFIG).with_extension(JSON_EXT),
178        PathBuf::from(PRIVATE_CONFIG).with_extension(JSON_EXT),
179        PathBuf::from(PRIVATE_CONFIG).with_extension(ENCRYPTED_EXT),
180        PathBuf::from(SALT_FILE),
181    ];
182
183    expected_paths.iter().any(|expected| expected == path)
184}
185
186/// Parse a guardian backup tar into a [`ServerConfig`] entirely in memory.
187///
188/// Validates archive paths and rejects missing, unexpected, duplicate, or
189/// non-file entries. Two backup formats are supported: the current plaintext
190/// format (containing `private.json`) and the legacy encrypted format
191/// (containing `private.encrypt` + `private.salt`), which requires the guardian
192/// password used when the backup was created. Nothing is written to disk; the
193/// caller writes the validated config into the data directory just like a
194/// freshly generated config.
195fn parse_backup(backup: &[u8], password: Option<&str>) -> anyhow::Result<ServerConfig> {
196    let mut archive = tar::Archive::new(backup);
197    let mut files: BTreeMap<PathBuf, Vec<u8>> = BTreeMap::new();
198
199    for entry in archive.entries().context("Reading backup archive")? {
200        let mut entry = entry.context("Reading backup archive entry")?;
201        let path = entry
202            .path()
203            .context("Reading backup archive entry path")?
204            .into_owned();
205        ensure!(
206            path.components()
207                .all(|component| matches!(component, Component::Normal(_))),
208            "Backup archive contains an invalid path"
209        );
210        ensure!(
211            is_expected_backup_path(&path),
212            "Backup archive contains unexpected file {}",
213            path.display()
214        );
215        ensure!(
216            entry.header().entry_type().is_file(),
217            "Backup archive contains non-file entry {}",
218            path.display()
219        );
220
221        let mut bytes = Vec::new();
222        entry
223            .read_to_end(&mut bytes)
224            .context("Reading backup archive entry contents")?;
225        ensure!(
226            files.insert(path.clone(), bytes).is_none(),
227            "Backup archive contains duplicate file {}",
228            path.display()
229        );
230    }
231
232    let local_config = PathBuf::from(LOCAL_CONFIG).with_extension(JSON_EXT);
233    let consensus_config = PathBuf::from(CONSENSUS_CONFIG).with_extension(JSON_EXT);
234    let private_config_json = PathBuf::from(PRIVATE_CONFIG).with_extension(JSON_EXT);
235    let private_config_encrypted = PathBuf::from(PRIVATE_CONFIG).with_extension(ENCRYPTED_EXT);
236    let salt_file = PathBuf::from(SALT_FILE);
237
238    let local = files
239        .get(&local_config)
240        .with_context(|| format!("Backup archive is missing {}", local_config.display()))?;
241    let consensus = files
242        .get(&consensus_config)
243        .with_context(|| format!("Backup archive is missing {}", consensus_config.display()))?;
244
245    // Both formats are parsed into a plaintext config in memory, which the
246    // caller then writes out exactly like a freshly generated config, so a
247    // restored guardian looks like a fresh post-migration setup.
248    if let Some(private) = files.get(&private_config_json) {
249        // Current plaintext format. No password is needed; any supplied
250        // password is ignored.
251        parse_plaintext_backup(local, consensus, private).context("Reading restored config")
252    } else if let Some(private) = files.get(&private_config_encrypted) {
253        // Legacy encrypted format. Requires the salt file and the password used
254        // when the backup was created.
255        let salt = files
256            .get(&salt_file)
257            .with_context(|| format!("Backup archive is missing {}", salt_file.display()))?;
258        let password = password.context(
259            "This backup is encrypted, please provide the guardian password used when it was created",
260        )?;
261        parse_legacy_encrypted_backup(local, consensus, private, salt, password)
262            .context("Reading restored config")
263    } else {
264        anyhow::bail!("Backup archive is missing the private config");
265    }
266}
267
268#[async_trait]
269impl ISetupApi for SetupApi {
270    async fn setup_code(&self) -> Option<String> {
271        self.state
272            .lock()
273            .await
274            .local_params
275            .as_ref()
276            .map(|lp| base32::encode_prefixed(FEDIMINT_PREFIX, &lp.setup_code()))
277    }
278
279    async fn guardian_name(&self) -> Option<String> {
280        self.state
281            .lock()
282            .await
283            .local_params
284            .as_ref()
285            .map(|lp| lp.name.clone())
286    }
287
288    fn auth_ui(&self) -> Option<ApiAuth> {
289        self.auth_ui.clone()
290    }
291
292    async fn connected_peers(&self) -> Vec<String> {
293        self.state
294            .lock()
295            .await
296            .setup_codes
297            .clone()
298            .into_iter()
299            .map(|info| info.name)
300            .collect()
301    }
302
303    fn available_modules(&self) -> BTreeSet<ModuleKind> {
304        self.settings.available_modules.clone()
305    }
306
307    fn default_modules(&self) -> BTreeSet<ModuleKind> {
308        self.settings.default_modules.clone()
309    }
310
311    async fn reset_setup_codes(&self) {
312        self.state.lock().await.setup_codes.clear();
313    }
314
315    async fn set_local_parameters(
316        &self,
317        name: String,
318        disable_base_fees: Option<bool>,
319        enabled_modules: Option<BTreeSet<ModuleKind>>,
320        federation_size: Option<u32>,
321    ) -> anyhow::Result<String> {
322        if let Some(existing_local_parameters) = self.state.lock().await.local_params.clone()
323            && existing_local_parameters.name == name
324            && existing_local_parameters.disable_base_fees == disable_base_fees
325            && existing_local_parameters.enabled_modules == enabled_modules
326            && existing_local_parameters.federation_size == federation_size
327        {
328            return Ok(base32::encode_prefixed(
329                FEDIMINT_PREFIX,
330                &existing_local_parameters.setup_code(),
331            ));
332        }
333
334        ensure!(!name.is_empty(), "The guardian name is empty");
335
336        if let Some(size) = federation_size {
337            ensure!(
338                size == 1 || 4 <= size,
339                "Federation size must be 1 or at least 4"
340            );
341        }
342        let mut state = self.state.lock().await;
343
344        ensure!(
345            state.local_params.is_none(),
346            "Local parameters have already been set"
347        );
348
349        ensure!(
350            !state.restore_in_progress,
351            "A restore is already in progress"
352        );
353
354        let fedimint_version =
355            DkgVersion::parse(&self.code_version_str).context("Invalid local Fedimint version")?;
356
357        let lp = if self.settings.enable_iroh {
358            let iroh_api_sk = if let Ok(var) = std::env::var(FM_IROH_API_SECRET_KEY_OVERRIDE_ENV) {
359                SecretKey::from_str(&var)
360                    .with_context(|| format!("Parsing {FM_IROH_API_SECRET_KEY_OVERRIDE_ENV}"))?
361            } else {
362                SecretKey::generate(&mut OsRng)
363            };
364
365            let iroh_p2p_sk = if let Ok(var) = std::env::var(FM_IROH_P2P_SECRET_KEY_OVERRIDE_ENV) {
366                SecretKey::from_str(&var)
367                    .with_context(|| format!("Parsing {FM_IROH_P2P_SECRET_KEY_OVERRIDE_ENV}"))?
368            } else {
369                SecretKey::generate(&mut OsRng)
370            };
371
372            LocalParams {
373                tls_key: None,
374                iroh_api_sk: Some(iroh_api_sk.clone()),
375                iroh_p2p_sk: Some(iroh_p2p_sk.clone()),
376                endpoints: PeerEndpoints::Iroh {
377                    api_pk: iroh_api_sk.public(),
378                    p2p_pk: iroh_p2p_sk.public(),
379                },
380                name,
381                disable_base_fees,
382                enabled_modules,
383                federation_size,
384                network: self.settings.network,
385                fedimint_version: fedimint_version.clone(),
386            }
387        } else {
388            let (tls_cert, tls_key) =
389                gen_cert_and_key(&name).expect("Failed to generate TLS for given guardian name");
390
391            LocalParams {
392                tls_key: Some(tls_key),
393                iroh_api_sk: None,
394                iroh_p2p_sk: None,
395                endpoints: PeerEndpoints::Tcp {
396                    api_url: self
397                        .settings
398                        .api_url
399                        .clone()
400                        .ok_or_else(|| anyhow::format_err!("Api URL must be configured"))?,
401                    p2p_url: self
402                        .settings
403                        .p2p_url
404                        .clone()
405                        .ok_or_else(|| anyhow::format_err!("P2P URL must be configured"))?,
406
407                    cert: tls_cert.as_ref().to_vec(),
408                },
409                name,
410                disable_base_fees,
411                enabled_modules,
412                federation_size,
413                network: self.settings.network,
414                fedimint_version,
415            }
416        };
417
418        state.local_params = Some(lp.clone());
419
420        Ok(base32::encode_prefixed(FEDIMINT_PREFIX, &lp.setup_code()))
421    }
422
423    async fn add_peer_setup_code(&self, info: String) -> anyhow::Result<String> {
424        let info = base32::decode_prefixed(FEDIMINT_PREFIX, &info)?;
425
426        let mut state = self.state.lock().await;
427
428        if state.setup_codes.contains(&info) {
429            return Ok(info.name.clone());
430        }
431
432        ensure!(
433            !state.restore_in_progress,
434            "A restore is already in progress"
435        );
436
437        let local_params = state
438            .local_params
439            .clone()
440            .expect("The endpoint is authenticated.");
441
442        ensure!(
443            info != local_params.setup_code(),
444            "You cannot add your own setup code"
445        );
446
447        ensure!(
448            discriminant(&info.endpoints) == discriminant(&local_params.endpoints),
449            "Guardian has different endpoint variant (TCP/Iroh) than us.",
450        );
451
452        ensure_fedimint_version_matches(&info, &local_params.fedimint_version)?;
453
454        ensure!(
455            info.network == local_params.network,
456            "Guardian uses Bitcoin network {} but we use {}",
457            info.network,
458            local_params.network,
459        );
460
461        if let Some(disable_base_fees) = state
462            .setup_codes
463            .iter()
464            .chain(once(&local_params.setup_code()))
465            .find_map(|info| info.disable_base_fees)
466        {
467            ensure!(
468                info.disable_base_fees.is_none(),
469                "Base fees setting has already been configured to disabled={disable_base_fees}"
470            );
471        }
472
473        if state
474            .setup_codes
475            .iter()
476            .chain(once(&local_params.setup_code()))
477            .any(|info| info.enabled_modules.is_some())
478        {
479            ensure!(
480                info.enabled_modules.is_none(),
481                "Enabled modules have already been configured by another guardian"
482            );
483        }
484
485        if let Some(federation_size) = state
486            .setup_codes
487            .iter()
488            .chain(once(&local_params.setup_code()))
489            .find_map(|info| info.federation_size)
490        {
491            ensure!(
492                info.federation_size.is_none(),
493                "Federation size has already been set to {federation_size}"
494            );
495        }
496
497        state.setup_codes.insert(info.clone());
498
499        Ok(info.name)
500    }
501
502    async fn start_dkg(&self) -> anyhow::Result<()> {
503        let mut state = self.state.lock().await.clone();
504
505        ensure!(
506            !state.restore_in_progress,
507            "A restore is already in progress"
508        );
509
510        let local_params = state
511            .local_params
512            .clone()
513            .expect("The endpoint is authenticated.");
514
515        let our_setup_code = local_params.setup_code();
516
517        state.setup_codes.insert(our_setup_code.clone());
518
519        for setup_code in &state.setup_codes {
520            ensure_fedimint_version_matches(setup_code, &local_params.fedimint_version)?;
521        }
522
523        ensure!(
524            state.setup_codes.len() == 1 || 4 <= state.setup_codes.len(),
525            "The number of guardians is invalid"
526        );
527
528        if let Some(federation_size) = state
529            .setup_codes
530            .iter()
531            .find_map(|info| info.federation_size)
532        {
533            ensure!(
534                state.setup_codes.len() == federation_size as usize,
535                "Expected {federation_size} guardians but got {}",
536                state.setup_codes.len()
537            );
538        }
539        let disable_base_fees = state
540            .setup_codes
541            .iter()
542            .find_map(|info| info.disable_base_fees)
543            .unwrap_or(is_env_var_set(FM_DISABLE_BASE_FEES_ENV));
544
545        let enabled_modules = state
546            .setup_codes
547            .iter()
548            .find_map(|info| info.enabled_modules.clone())
549            .unwrap_or_else(|| self.settings.default_modules.clone());
550
551        let our_id = state
552            .setup_codes
553            .iter()
554            .position(|info| info == &our_setup_code)
555            .expect("We inserted the key above.");
556
557        let params = ConfigGenParams {
558            identity: PeerId::from(our_id as u16),
559            tls_key: local_params.tls_key,
560            iroh_api_sk: local_params.iroh_api_sk,
561            iroh_p2p_sk: local_params.iroh_p2p_sk,
562            peers: (0..)
563                .map(|i| PeerId::from(i as u16))
564                .zip(state.setup_codes.clone())
565                .collect(),
566            meta: BTreeMap::new(),
567            disable_base_fees,
568            enabled_modules,
569            network: local_params.network,
570        };
571
572        self.sender
573            .send(ConfigGenOutcome::Generated(Box::new(params)))
574            .await
575            .context("Failed to send config gen params")?;
576
577        Ok(())
578    }
579
580    async fn restore_from_backup(
581        &self,
582        password: Option<String>,
583        backup: Vec<u8>,
584    ) -> anyhow::Result<()> {
585        if let Some(password) = &password {
586            ensure!(!password.is_empty(), "The password is empty");
587            ensure!(
588                password.trim() == password,
589                "The password contains leading/trailing whitespace",
590            );
591        }
592        {
593            let mut state = self.state.lock().await;
594            ensure!(
595                state.local_params.is_none(),
596                "Local parameters have already been set"
597            );
598            ensure!(
599                !state.restore_in_progress,
600                "A restore is already in progress"
601            );
602            state.restore_in_progress = true;
603        }
604
605        let state = self.state.clone();
606        let sender = self.sender.clone();
607        runtime::spawn("restore guardian backup", async move {
608            let result = async {
609                let cfg =
610                    tokio::task::spawn_blocking(move || parse_backup(&backup, password.as_deref()))
611                        .await
612                        .context("Restore backup task panicked")??;
613                let (restore_result_sender, restore_result_receiver) = oneshot::channel();
614                let restored = ConfigGenOutcome::Restored(Box::new(cfg), restore_result_sender);
615                if sender.send(restored).await.is_err() {
616                    return Err(anyhow::format_err!("Failed to send restored config"));
617                }
618                restore_result_receiver
619                    .await
620                    .context("Restore result sender dropped")?
621                    .map_err(anyhow::Error::msg)?;
622                Ok(())
623            }
624            .await;
625
626            if result.is_err() {
627                state.lock().await.restore_in_progress = false;
628            }
629            // On success, the setup task consumes the restored config and exits setup mode,
630            // so there is no setup API left that could observe or reset
631            // `restore_in_progress`.
632
633            result
634        })
635        .await
636        .context("Restore task panicked")?
637    }
638
639    async fn federation_size(&self) -> Option<u32> {
640        let state = self.state.lock().await;
641        let local_setup_code = state.local_params.as_ref().map(LocalParams::setup_code);
642        state
643            .setup_codes
644            .iter()
645            .chain(local_setup_code.iter())
646            .find_map(|info| info.federation_size)
647    }
648
649    async fn cfg_federation_name(&self) -> Option<String> {
650        None
651    }
652
653    async fn cfg_base_fees_disabled(&self) -> Option<bool> {
654        let state = self.state.lock().await;
655        let local_setup_code = state.local_params.as_ref().map(LocalParams::setup_code);
656        state
657            .setup_codes
658            .iter()
659            .chain(local_setup_code.iter())
660            .find_map(|info| info.disable_base_fees)
661    }
662
663    async fn cfg_enabled_modules(&self) -> Option<BTreeSet<ModuleKind>> {
664        let state = self.state.lock().await;
665        let local_setup_code = state.local_params.as_ref().map(LocalParams::setup_code);
666        state
667            .setup_codes
668            .iter()
669            .chain(local_setup_code.iter())
670            .find_map(|info| info.enabled_modules.clone())
671    }
672
673    async fn fedimintd_version(&self) -> String {
674        self.code_version_str.clone()
675    }
676
677    async fn fedimintd_version_hash(&self) -> Option<String> {
678        fedimint_core::version::non_zero_version_hash(&self.code_version_hash).map(str::to_owned)
679    }
680}
681
682#[async_trait]
683impl HasApiContext<SetupApi> for SetupApi {
684    async fn context(
685        &self,
686        request: &ApiRequestErased,
687        id: Option<ModuleInstanceId>,
688    ) -> (&SetupApi, ApiEndpointContext) {
689        assert!(id.is_none());
690
691        let db = self.db.clone();
692
693        let is_authenticated = match (&self.auth_api, &request.auth) {
694            (Some(server_auth), Some(req_auth)) => server_auth.verify(req_auth.as_str()),
695            _ => false,
696        };
697
698        let context = ApiEndpointContext::new(db, is_authenticated);
699
700        (self, context)
701    }
702}
703
704pub fn server_endpoints() -> Vec<ApiEndpoint<SetupApi>> {
705    vec![
706        public_api_endpoint! {
707            SETUP_STATUS_ENDPOINT,
708            ApiVersion::new(0, 0),
709            async |config: &SetupApi, _c, _v: ()| -> SetupStatus {
710                Ok(config.setup_status().await)
711            }
712        },
713        admin_api_endpoint! {
714            SET_LOCAL_PARAMS_ENDPOINT,
715            ApiVersion::new(0, 0),
716            async |config: &SetupApi, context, request: SetLocalParamsRequest| -> String {
717
718                config.set_local_parameters(
719                    request.name,
720                    request.disable_base_fees,
721                    request.enabled_modules,
722                    request.federation_size,
723                )
724                    .await
725                    .map_err(|e| ApiError::bad_request(e.to_string()))
726            }
727        },
728        admin_api_endpoint! {
729            ADD_PEER_SETUP_CODE_ENDPOINT,
730            ApiVersion::new(0, 0),
731            async |config: &SetupApi, context, info: String| -> String {
732
733                config.add_peer_setup_code(info.clone())
734                    .await
735                    .map_err(|e|ApiError::bad_request(e.to_string()))
736            }
737        },
738        admin_api_endpoint! {
739            RESET_PEER_SETUP_CODES_ENDPOINT,
740            ApiVersion::new(0, 0),
741            async |config: &SetupApi, context, _v: ()| -> () {
742
743                config.reset_setup_codes().await;
744
745                Ok(())
746            }
747        },
748        admin_api_endpoint! {
749            GET_SETUP_CODE_ENDPOINT,
750            ApiVersion::new(0, 0),
751            async |config: &SetupApi, context, _request: ()| -> Option<String> {
752
753                Ok(config.setup_code().await)
754            }
755        },
756        admin_api_endpoint! {
757            START_DKG_ENDPOINT,
758            ApiVersion::new(0, 0),
759            async |config: &SetupApi, context, _v: ()| -> () {
760
761                config.start_dkg().await.map_err(|e| ApiError::server_error(e.to_string()))
762            }
763        },
764    ]
765}
766
767#[cfg(test)]
768mod tests;