Skip to main content

fedimint_server_ui/
setup.rs

1use std::collections::BTreeSet;
2
3use axum::Router;
4use axum::extract::{DefaultBodyLimit, Multipart, State};
5use axum::http::StatusCode;
6use axum::response::{Html, IntoResponse, Redirect};
7use axum::routing::{get, post};
8use axum_extra::extract::Form;
9use axum_extra::extract::cookie::CookieJar;
10use fedimint_core::core::ModuleKind;
11use fedimint_server_core::setup_ui::DynSetupApi;
12use fedimint_ui_common::assets::WithStaticRoutesExt;
13use fedimint_ui_common::auth::UserAuth;
14use fedimint_ui_common::{
15    CONNECTIVITY_CHECK_ROUTE, LOGIN_ROUTE, LoginInput, ROOT_ROUTE, UiState,
16    connectivity_check_handler, copiable_text, login_form, login_submit_response,
17    single_card_layout, single_card_layout_with_version,
18};
19use maud::{Markup, PreEscaped, html};
20use qrcode::QrCode;
21use serde::Deserialize;
22
23// Setup route constants
24pub const FEDERATION_SETUP_ROUTE: &str = "/federation_setup";
25pub const ADD_SETUP_CODE_ROUTE: &str = "/add_setup_code";
26pub const RESET_SETUP_CODES_ROUTE: &str = "/reset_setup_codes";
27pub const START_DKG_ROUTE: &str = "/start_dkg";
28pub const START_FEDERATION_ROUTE: &str = "/start_federation";
29pub const RESTORE_GUARDIAN_ROUTE: &str = "/restore_guardian";
30const RESTORE_BACKUP_UPLOAD_LIMIT_BYTES: usize = 10 * 1024 * 1024;
31
32#[derive(Debug, Deserialize)]
33pub(crate) struct SetupInput {
34    pub name: String,
35    #[serde(default)]
36    pub is_lead: bool,
37    #[serde(default)]
38    pub federation_size: String,
39    #[serde(default)] // will not be sent if disabled
40    pub enable_base_fees: bool,
41    #[serde(default)] // list of enabled module kinds
42    pub enabled_modules: Vec<String>,
43}
44
45#[derive(Debug, Deserialize)]
46pub(crate) struct PeerInfoInput {
47    pub peer_info: String,
48}
49
50fn peer_list_section(
51    connected_peers: &[String],
52    federation_size: Option<u32>,
53    cfg_federation_name: &Option<String>,
54    cfg_base_fees_disabled: Option<bool>,
55    cfg_enabled_modules: &Option<BTreeSet<ModuleKind>>,
56    error: Option<&str>,
57) -> Markup {
58    let total_guardians = connected_peers.len() + 1;
59    let can_start_dkg = federation_size
60        .map(|expected| total_guardians == expected as usize)
61        .unwrap_or(false);
62
63    html! {
64        div id="peer-list-section" {
65            @if let Some(expected) = federation_size {
66                p { (format!("{total_guardians} of {expected} guardians connected.")) }
67            } @else {
68                p { "Add setup code for every other guardian." }
69            }
70
71            @if !connected_peers.is_empty() {
72                ul class="list-group mb-2" {
73                    @for peer in connected_peers {
74                        li class="list-group-item" { (peer) }
75                    }
76                }
77
78                form id="reset-form" method="post" action=(RESET_SETUP_CODES_ROUTE) class="d-none" {}
79                div class="text-center mb-4" {
80                    button type="button" class="btn btn-link text-danger text-decoration-none p-0" onclick="if(confirm('Are you sure you want to reset all guardians?')){document.getElementById('reset-form').submit();}" {
81                        "Reset Guardians"
82                    }
83                }
84            }
85
86            @if can_start_dkg {
87                // All guardians connected — show confirm form
88                @let has_settings = cfg_federation_name.is_some()
89                    || federation_size.is_some()
90                    || cfg_base_fees_disabled.is_some()
91                    || cfg_enabled_modules.is_some();
92
93                form id="start-dkg-form" hx-post=(START_DKG_ROUTE) hx-target="#peer-list-section" hx-swap="outerHTML" {
94                    @if let Some(error) = error {
95                        div class="alert alert-danger mb-3" { (error) }
96                    }
97                    button type="submit" class="btn btn-warning w-100 py-2" { "Confirm" }
98                }
99
100                @if has_settings {
101                    p class="text-muted mt-3 mb-0" style="font-size: 0.85rem;" {
102                        @if let Some(name) = cfg_federation_name {
103                            (name) " federation has been configured"
104                        } @else {
105                            "The federation has been configured"
106                        }
107                        @if let Some(disabled) = cfg_base_fees_disabled {
108                            " with base fees "
109                            @if disabled { "disabled" } @else { "enabled" }
110                        }
111                        @if let Some(modules) = cfg_enabled_modules {
112                            " and modules "
113                            (modules.iter().map(|m| m.as_str().to_owned()).collect::<Vec<_>>().join(", "))
114                        }
115                        "."
116                    }
117                }
118            } @else {
119                // Still collecting — show add guardian form
120                form id="add-setup-code-form" hx-post=(ADD_SETUP_CODE_ROUTE) hx-target="#peer-list-section" hx-swap="outerHTML" {
121                    div class="mb-3" {
122                        div class="input-group" {
123                            input type="text" class="form-control" id="peer_info" name="peer_info"
124                                placeholder="Paste Setup Code" required;
125                            button type="button" class="btn btn-outline-secondary" onclick="startQrScanner()" title="Scan QR Code" {
126                                i class="bi bi-qr-code-scan" {}
127                            }
128                        }
129                    }
130
131                    @if let Some(error) = error {
132                        div class="alert alert-danger mb-3" { (error) }
133                    }
134                    button type="submit" class="btn btn-primary w-100 py-2" { "Add Guardian" }
135                }
136            }
137        }
138    }
139}
140
141fn setup_error_message(error: &str) -> Markup {
142    html! {
143        div class="alert alert-danger mb-3" { (error) }
144    }
145}
146
147fn setup_choice_content(error: Option<&str>) -> Markup {
148    html! {
149        @if let Some(error) = error {
150            (setup_error_message(error))
151        }
152
153        div class="d-grid gap-3" {
154            a href=(START_FEDERATION_ROUTE) class="btn btn-primary w-100 py-2" {
155                "Start new Federation"
156            }
157
158            a href=(RESTORE_GUARDIAN_ROUTE) class="btn btn-outline-secondary w-100 py-2" {
159                "Restore from backup"
160            }
161        }
162    }
163}
164
165fn restore_form_content(error: Option<&str>) -> Markup {
166    html! {
167        @if let Some(error) = error {
168            (setup_error_message(error))
169        }
170
171        p class="text-muted" {
172            "Upload a guardian backup tar file. The password is only required for older, encrypted backups; leave it blank otherwise."
173        }
174
175        form method="post" action=(RESTORE_GUARDIAN_ROUTE) enctype="multipart/form-data" {
176            div class="form-group mb-3" {
177                input type="password" class="form-control" name="password" placeholder="Guardian Password (only for encrypted backups)";
178            }
179            div class="form-group mb-3" {
180                input type="file" class="form-control" name="backup" accept="application/x-tar,.tar" required;
181            }
182            button type="submit" class="btn btn-primary w-100 py-2" {
183                "Restore Guardian"
184            }
185        }
186
187        div class="text-center mt-3" {
188            a href=(ROOT_ROUTE) class="btn btn-link text-muted text-decoration-none" {
189                "Back"
190            }
191        }
192    }
193}
194
195fn restore_error_response(error: impl AsRef<str>) -> axum::response::Response {
196    (
197        StatusCode::BAD_REQUEST,
198        Html(
199            single_card_layout(
200                "Restore Guardian",
201                restore_form_content(Some(error.as_ref())),
202            )
203            .into_string(),
204        ),
205    )
206        .into_response()
207}
208
209fn setup_form_content(
210    available_modules: &BTreeSet<ModuleKind>,
211    default_modules: &BTreeSet<ModuleKind>,
212) -> Markup {
213    html! {
214        form id="setup-form" hx-post=(ROOT_ROUTE) hx-target="#setup-error" hx-swap="innerHTML" {
215            style {
216                r#"
217                .toggle-content {
218                    display: none;
219                }
220
221                .toggle-control:checked ~ .toggle-content {
222                    display: block;
223                }
224
225                #base-fees-warning {
226                    display: block;
227                }
228
229                .form-check:has(#enable_base_fees:checked) + #base-fees-warning {
230                    display: none;
231                }
232
233                .accordion-button {
234                    background-color: #f8f9fa;
235                }
236
237                .accordion-button:not(.collapsed) {
238                    background-color: #f8f9fa;
239                    box-shadow: none;
240                }
241
242                .accordion-button:focus {
243                    box-shadow: none;
244                }
245
246                #modules-warning {
247                    display: none;
248                }
249
250                #modules-list:has(.form-check-input:not(:checked)) ~ #modules-warning {
251                    display: block;
252                }
253                "#
254            }
255
256            div class="form-group mb-4" {
257                input type="text" class="form-control" id="name" name="name" placeholder="Your Guardian Name" required;
258            }
259
260            div class="alert alert-warning mb-3" style="font-size: 0.875rem;" {
261                "Exactly one guardian must set the global config."
262            }
263
264            div class="form-group mb-4" {
265                input type="checkbox" class="form-check-input toggle-control" id="is_lead" name="is_lead" value="true";
266
267                label class="form-check-label ms-2" for="is_lead" {
268                    "Set the global config"
269                }
270
271                div class="toggle-content mt-3" {
272                    div class="form-group mt-3" {
273                        label class="form-label" for="federation_size" {
274                            "Total number of guardians (including you)"
275                        }
276                        select class="form-select" id="federation_size" name="federation_size" {
277                            option value="" selected disabled { "Federation Size" }
278                            option value="1" { "1 — Testing" }
279                            option value="4" { "4 — Recommended" }
280                            option value="5" { "5" }
281                            option value="6" { "6" }
282                            option value="7" { "7 — Recommended" }
283                            option value="8" { "8" }
284                            option value="9" { "9" }
285                            option value="10" { "10 — Recommended" }
286                            option value="11" { "11" }
287                            option value="12" { "12" }
288                            option value="13" { "13 — Recommended" }
289                            option value="14" { "14" }
290                            option value="15" { "15" }
291                            option value="16" { "16 — Recommended" }
292                            option value="17" { "17" }
293                            option value="18" { "18" }
294                            option value="19" { "19 — Recommended" }
295                            option value="20" { "20" }
296                        }
297                    }
298
299                    div class="form-check mt-3" {
300                        input type="checkbox" class="form-check-input" id="enable_base_fees" name="enable_base_fees" checked value="true";
301
302                        label class="form-check-label" for="enable_base_fees" {
303                            "Enable base fees for this federation"
304                        }
305                    }
306
307                    div id="base-fees-warning" class="alert alert-warning mt-2" style="font-size: 0.875rem;" {
308                        strong { "Warning: " }
309                        "Base fees discourage spam and wasting storage space. The typical fee is only 1-3 sats per transaction, regardless of the value transferred. We recommend enabling the base fee and it cannot be changed later."
310                    }
311
312                    div class="accordion mt-3" id="modulesAccordion" {
313                        div class="accordion-item" {
314                            h2 class="accordion-header" {
315                                button class="accordion-button collapsed" type="button"
316                                    data-bs-toggle="collapse" data-bs-target="#modulesConfig"
317                                    aria-expanded="false" aria-controls="modulesConfig" {
318                                    "Advanced: Configure Enabled Modules"
319                                }
320                            }
321                            div id="modulesConfig" class="accordion-collapse collapse" data-bs-parent="#modulesAccordion" {
322                                div class="accordion-body" {
323                                    div id="modules-list" {
324                                        @for kind in available_modules {
325                                            div class="form-check" {
326                                                input type="checkbox" class="form-check-input"
327                                                    id=(format!("module_{}", kind.as_str()))
328                                                    name="enabled_modules"
329                                                    value=(kind.as_str())
330                                                    checked[default_modules.contains(kind)];
331
332                                                label class="form-check-label" for=(format!("module_{}", kind.as_str())) {
333                                                    (kind.as_str())
334                                                    @if !default_modules.contains(kind) {
335                                                        span class="badge bg-warning text-dark ms-2" { "legacy" }
336                                                    }
337                                                }
338                                            }
339                                        }
340                                    }
341
342                                    div id="modules-warning" class="alert alert-warning mt-2 mb-0" style="font-size: 0.875rem;" {
343                                        "Only modify this if you know what you are doing. Disabled modules cannot be enabled later."
344                                    }
345                                }
346                            }
347                        }
348                    }
349                }
350            }
351
352            div id="setup-error" {}
353            button type="submit" class="btn btn-primary w-100 py-2" { "Confirm" }
354        }
355    }
356}
357
358// GET handler for the / route (choose setup or restore)
359async fn setup_form(
360    State(state): State<UiState<DynSetupApi>>,
361    _auth: UserAuth,
362) -> impl IntoResponse {
363    if state.api.setup_code().await.is_some() {
364        return Redirect::to(FEDERATION_SETUP_ROUTE).into_response();
365    }
366
367    Html(single_card_layout("Guardian Setup", setup_choice_content(None)).into_string())
368        .into_response()
369}
370
371// GET handler for starting a new federation
372async fn start_federation_form(State(state): State<UiState<DynSetupApi>>) -> impl IntoResponse {
373    if state.api.setup_code().await.is_some() {
374        return Redirect::to(FEDERATION_SETUP_ROUTE).into_response();
375    }
376
377    let available_modules = state.api.available_modules();
378    let default_modules = state.api.default_modules();
379    let content = setup_form_content(&available_modules, &default_modules);
380    let version = state.api.fedimintd_version().await;
381    let version_hash = state.api.fedimintd_version_hash().await;
382
383    Html(
384        single_card_layout_with_version(
385            "Guardian Setup",
386            content,
387            &version,
388            version_hash.as_deref(),
389        )
390        .into_string(),
391    )
392    .into_response()
393}
394
395// POST handler for the /setup route (process the setup form)
396async fn setup_submit(
397    State(state): State<UiState<DynSetupApi>>,
398    _auth: UserAuth,
399    Form(input): Form<SetupInput>,
400) -> impl IntoResponse {
401    // Only use these settings if is_lead is true
402    let disable_base_fees = if input.is_lead {
403        Some(!input.enable_base_fees)
404    } else {
405        None
406    };
407
408    let enabled_modules = if input.is_lead {
409        let enabled: BTreeSet<ModuleKind> = input
410            .enabled_modules
411            .into_iter()
412            .map(|s| ModuleKind::clone_from_str(&s))
413            .collect();
414
415        Some(enabled)
416    } else {
417        None
418    };
419
420    let federation_size = if input.is_lead {
421        let s = input.federation_size.trim();
422        if s.is_empty() {
423            None
424        } else {
425            match s.parse::<u32>() {
426                Ok(size) => Some(size),
427                Err(_) => {
428                    return Html(setup_error_message("Invalid federation size").into_string())
429                        .into_response();
430                }
431            }
432        }
433    } else {
434        None
435    };
436
437    match state
438        .api
439        .set_local_parameters(
440            input.name,
441            disable_base_fees,
442            enabled_modules,
443            federation_size,
444        )
445        .await
446    {
447        Ok(_) => (
448            [("HX-Redirect", FEDERATION_SETUP_ROUTE)],
449            Html(String::new()),
450        )
451            .into_response(),
452        Err(e) => Html(setup_error_message(&e.to_string()).into_string()).into_response(),
453    }
454}
455
456// GET handler for restoring from backup
457async fn restore_form(State(state): State<UiState<DynSetupApi>>) -> impl IntoResponse {
458    if state.api.setup_code().await.is_some() {
459        return Redirect::to(FEDERATION_SETUP_ROUTE).into_response();
460    }
461
462    Html(single_card_layout("Restore Guardian", restore_form_content(None)).into_string())
463        .into_response()
464}
465
466async fn restore_submit(
467    State(state): State<UiState<DynSetupApi>>,
468    mut multipart: Multipart,
469) -> impl IntoResponse {
470    let mut password = None;
471    let mut backup = None;
472
473    loop {
474        let field = match multipart.next_field().await {
475            Ok(Some(field)) => field,
476            Ok(None) => break,
477            Err(e) => return restore_error_response(format!("Failed to read upload: {e}")),
478        };
479
480        match field.name() {
481            Some("password") => match field.text().await {
482                Ok(value) => password = Some(value),
483                Err(e) => return restore_error_response(format!("Failed to read password: {e}")),
484            },
485            Some("backup") => match field.bytes().await {
486                // The setup UI is a local guardian-owner interface. We cap the upload size to
487                // catch accidental oversized requests, but treat malicious tar expansion by the
488                // uploading user as out of scope: they already control this guardian instance.
489                Ok(value) => backup = Some(value.to_vec()),
490                Err(e) => return restore_error_response(format!("Failed to read backup: {e}")),
491            },
492            _ => {}
493        }
494    }
495
496    // An empty password field means the user left it blank, which is the
497    // expected case for current plaintext backups.
498    let password = password.filter(|password| !password.is_empty());
499    let Some(backup) = backup else {
500        return restore_error_response("Missing guardian backup file");
501    };
502
503    match state.api.restore_from_backup(password, backup).await {
504        Ok(()) => {
505            let content = html! {
506                div class="alert alert-success mb-3" {
507                    "Guardian backup restored. The server is starting consensus."
508                }
509                div class="text-center mt-4" {
510                    div class="spinner-border text-primary" role="status" {
511                        span class="visually-hidden" { "Loading..." }
512                    }
513                    p class="mt-2 text-muted" { "Waiting for dashboard..." }
514                }
515                div
516                    hx-get=(ROOT_ROUTE)
517                    hx-trigger="every 2s"
518                    hx-swap="none"
519                    hx-on--after-request={
520                        "if (event.detail.xhr.status === 200) { window.location.href = '" (ROOT_ROUTE) "'; }"
521                    }
522                    style="display: none;"
523                {}
524            };
525            Html(single_card_layout("Guardian Restored", content).into_string()).into_response()
526        }
527        // Render the full error chain so the underlying cause (e.g. an
528        // incorrect password for an encrypted backup) is surfaced rather than
529        // just the outermost "Reading restored config" context.
530        Err(e) => restore_error_response(format!("{e:#}")),
531    }
532}
533
534// GET handler for the /login route (display the login form)
535async fn login_form_handler(State(state): State<UiState<DynSetupApi>>) -> impl IntoResponse {
536    let version = state.api.fedimintd_version().await;
537    let version_hash = state.api.fedimintd_version_hash().await;
538    Html(
539        single_card_layout_with_version(
540            "Enter Password",
541            login_form(None),
542            &version,
543            version_hash.as_deref(),
544        )
545        .into_string(),
546    )
547    .into_response()
548}
549
550// POST handler for the /login route (authenticate and set session cookie).
551// Only mounted when the guardian has a password configured, so `auth()` is
552// always `Some` here.
553async fn login_submit(
554    State(state): State<UiState<DynSetupApi>>,
555    jar: CookieJar,
556    Form(input): Form<LoginInput>,
557) -> impl IntoResponse {
558    login_submit_response(
559        state
560            .api
561            .auth_ui()
562            .expect("login route is mounted only when auth is configured"),
563        state.auth_cookie_name,
564        state.auth_cookie_value,
565        jar,
566        input,
567    )
568}
569
570// GET handler for the /federation-setup route (main federation management page)
571async fn federation_setup(
572    State(state): State<UiState<DynSetupApi>>,
573    _auth: UserAuth,
574) -> impl IntoResponse {
575    let our_connection_info = state
576        .api
577        .setup_code()
578        .await
579        .expect("Successful authentication ensures that the local parameters have been set");
580
581    let version = state.api.fedimintd_version().await;
582    let version_hash = state.api.fedimintd_version_hash().await;
583    let connected_peers = state.api.connected_peers().await;
584    let federation_size = state.api.federation_size().await;
585    let cfg_federation_name = state.api.cfg_federation_name().await;
586    let cfg_base_fees_disabled = state.api.cfg_base_fees_disabled().await;
587    let cfg_enabled_modules = state.api.cfg_enabled_modules().await;
588
589    let content = html! {
590        p { "Share this with your fellow guardians." }
591
592        @let qr_svg = QrCode::new(&our_connection_info)
593            .expect("Failed to generate QR code")
594            .render::<qrcode::render::svg::Color>()
595            .build();
596
597        div class="text-center mb-3" {
598            div class="border rounded p-2 bg-white d-inline-block" style="width: 250px; max-width: 100%;" {
599                div style="width: 100%; height: auto; overflow: hidden;" {
600                    (PreEscaped(format!(r#"<div style="width: 100%; height: auto;">{}</div>"#,
601                        qr_svg.replace("width=", "data-width=")
602                              .replace("height=", "data-height=")
603                              .replace("<svg", r#"<svg style="width: 100%; height: auto; display: block;""#))))
604                }
605            }
606        }
607
608        div class="mb-4" {
609            (copiable_text(&our_connection_info))
610        }
611
612        (peer_list_section(&connected_peers, federation_size, &cfg_federation_name, cfg_base_fees_disabled, &cfg_enabled_modules, None))
613
614        // QR Scanner Modal
615        div class="modal fade" id="qrScannerModal" tabindex="-1" aria-labelledby="qrScannerModalLabel" aria-hidden="true" {
616            div class="modal-dialog modal-dialog-centered" {
617                div class="modal-content" {
618                    div class="modal-header" {
619                        h5 class="modal-title" id="qrScannerModalLabel" { "Scan Setup Code" }
620                        button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" {}
621                    }
622                    div class="modal-body" {
623                        div id="qr-reader" style="width: 100%;" {}
624                        div id="qr-reader-error" class="alert alert-danger mt-3 d-none" {}
625                    }
626                    div class="modal-footer" {
627                        button type="button" class="btn btn-secondary" data-bs-dismiss="modal" { "Cancel" }
628                    }
629                }
630            }
631        }
632
633        script src="/assets/html5-qrcode.min.js" {}
634
635        // QR Scanner JavaScript
636        script {
637            (PreEscaped(r#"
638            var html5QrCode = null;
639            var qrScannerModal = null;
640
641            function startQrScanner() {
642                // Check for Flutter override hook
643                if (typeof window.fedimintQrScannerOverride === 'function') {
644                    window.fedimintQrScannerOverride(function(result) {
645                        if (result) {
646                            document.getElementById('peer_info').value = result;
647                        }
648                    });
649                    return;
650                }
651
652                var modalEl = document.getElementById('qrScannerModal');
653                qrScannerModal = new bootstrap.Modal(modalEl);
654
655                // Reset error message
656                var errorEl = document.getElementById('qr-reader-error');
657                errorEl.classList.add('d-none');
658                errorEl.textContent = '';
659
660                qrScannerModal.show();
661
662                // Wait for modal to be shown before starting camera
663                modalEl.addEventListener('shown.bs.modal', function onShown() {
664                    modalEl.removeEventListener('shown.bs.modal', onShown);
665                    initializeScanner();
666                });
667
668                // Clean up when modal is hidden
669                modalEl.addEventListener('hidden.bs.modal', function onHidden() {
670                    modalEl.removeEventListener('hidden.bs.modal', onHidden);
671                    stopQrScanner();
672                });
673            }
674
675            function initializeScanner() {
676                html5QrCode = new Html5Qrcode("qr-reader");
677
678                var config = {
679                    fps: 10,
680                    qrbox: { width: 250, height: 250 },
681                    aspectRatio: 1.0
682                };
683
684                html5QrCode.start(
685                    { facingMode: "environment" },
686                    config,
687                    function(decodedText, decodedResult) {
688                        // Success - populate input and close modal
689                        document.getElementById('peer_info').value = decodedText;
690                        qrScannerModal.hide();
691                    },
692                    function(errorMessage) {
693                        // Ignore scan errors (happens constantly while searching)
694                    }
695                ).catch(function(err) {
696                    var errorEl = document.getElementById('qr-reader-error');
697                    errorEl.textContent = 'Unable to access camera: ' + err;
698                    errorEl.classList.remove('d-none');
699                });
700            }
701
702            function stopQrScanner() {
703                if (html5QrCode && html5QrCode.isScanning) {
704                    html5QrCode.stop().catch(function(err) {
705                        console.error('Error stopping scanner:', err);
706                    });
707                }
708            }
709            "#))
710        }
711    };
712
713    Html(
714        single_card_layout_with_version(
715            "Federation Setup",
716            content,
717            &version,
718            version_hash.as_deref(),
719        )
720        .into_string(),
721    )
722    .into_response()
723}
724
725// POST handler for adding peer connection info
726async fn post_add_setup_code(
727    State(state): State<UiState<DynSetupApi>>,
728    _auth: UserAuth,
729    Form(input): Form<PeerInfoInput>,
730) -> impl IntoResponse {
731    let error = state.api.add_peer_setup_code(input.peer_info).await.err();
732
733    let connected_peers = state.api.connected_peers().await;
734    let federation_size = state.api.federation_size().await;
735    let cfg_federation_name = state.api.cfg_federation_name().await;
736    let cfg_base_fees_disabled = state.api.cfg_base_fees_disabled().await;
737    let cfg_enabled_modules = state.api.cfg_enabled_modules().await;
738
739    Html(
740        peer_list_section(
741            &connected_peers,
742            federation_size,
743            &cfg_federation_name,
744            cfg_base_fees_disabled,
745            &cfg_enabled_modules,
746            error.as_ref().map(|e| e.to_string()).as_deref(),
747        )
748        .into_string(),
749    )
750    .into_response()
751}
752
753// POST handler for starting the DKG process
754async fn post_start_dkg(
755    State(state): State<UiState<DynSetupApi>>,
756    _auth: UserAuth,
757) -> impl IntoResponse {
758    let our_connection_info = state.api.setup_code().await;
759    let version = state.api.fedimintd_version().await;
760    let version_hash = state.api.fedimintd_version_hash().await;
761
762    match state.api.start_dkg().await {
763        Ok(()) => {
764            let content = html! {
765                @if let Some(ref info) = our_connection_info {
766                    p { "Share with guardians who still need it." }
767                    div class="mb-4" {
768                        (copiable_text(info))
769                    }
770                }
771
772                div class="alert alert-info mb-3" {
773                    "All guardians need to confirm their settings. Once completed you will be redirected to the Dashboard."
774                }
775
776                // Poll until the dashboard is ready, then redirect
777                div
778                    hx-get=(ROOT_ROUTE)
779                    hx-trigger="every 2s"
780                    hx-swap="none"
781                    hx-on--after-request={
782                        "if (event.detail.xhr.status === 200) { window.location.href = '" (ROOT_ROUTE) "'; }"
783                    }
784                    style="display: none;"
785                {}
786
787                div class="text-center mt-4" {
788                    div class="spinner-border text-primary" role="status" {
789                        span class="visually-hidden" { "Loading..." }
790                    }
791                    p class="mt-2 text-muted" { "Waiting for federation setup to complete..." }
792                }
793            };
794
795            (
796                [("HX-Retarget", "body"), ("HX-Reswap", "innerHTML")],
797                Html(
798                    single_card_layout_with_version(
799                        "DKG Started",
800                        content,
801                        &version,
802                        version_hash.as_deref(),
803                    )
804                    .into_string(),
805                ),
806            )
807                .into_response()
808        }
809        Err(e) => {
810            let connected_peers = state.api.connected_peers().await;
811            let federation_size = state.api.federation_size().await;
812            let cfg_federation_name = state.api.cfg_federation_name().await;
813            let cfg_base_fees_disabled = state.api.cfg_base_fees_disabled().await;
814            let cfg_enabled_modules = state.api.cfg_enabled_modules().await;
815
816            Html(
817                peer_list_section(
818                    &connected_peers,
819                    federation_size,
820                    &cfg_federation_name,
821                    cfg_base_fees_disabled,
822                    &cfg_enabled_modules,
823                    Some(&e.to_string()),
824                )
825                .into_string(),
826            )
827            .into_response()
828        }
829    }
830}
831
832// POST handler for resetting peer connection info
833async fn post_reset_setup_codes(
834    State(state): State<UiState<DynSetupApi>>,
835    _auth: UserAuth,
836) -> impl IntoResponse {
837    state.api.reset_setup_codes().await;
838
839    Redirect::to(FEDERATION_SETUP_ROUTE).into_response()
840}
841
842pub fn router(api: DynSetupApi) -> Router {
843    let requires_auth = api.auth_ui().is_some();
844
845    let mut router = Router::new()
846        .route(ROOT_ROUTE, get(setup_form).post(setup_submit))
847        .route(START_FEDERATION_ROUTE, get(start_federation_form))
848        .route(
849            RESTORE_GUARDIAN_ROUTE,
850            get(restore_form)
851                .post(restore_submit)
852                .layer(DefaultBodyLimit::max(RESTORE_BACKUP_UPLOAD_LIMIT_BYTES)),
853        )
854        .route(FEDERATION_SETUP_ROUTE, get(federation_setup))
855        .route(ADD_SETUP_CODE_ROUTE, post(post_add_setup_code))
856        .route(RESET_SETUP_CODES_ROUTE, post(post_reset_setup_codes))
857        .route(START_DKG_ROUTE, post(post_start_dkg))
858        .route(
859            CONNECTIVITY_CHECK_ROUTE,
860            get(connectivity_check_handler::<DynSetupApi>),
861        );
862
863    if requires_auth {
864        router = router.route(LOGIN_ROUTE, get(login_form_handler).post(login_submit));
865    }
866
867    router
868        .with_static_routes()
869        .with_state(UiState::new(api, requires_auth))
870}
871
872#[cfg(test)]
873mod tests;