Skip to main content

fedimint_gateway_ui/
lib.rs

1mod bitcoin;
2mod connect_fed;
3mod federation;
4mod general;
5mod lightning;
6mod mnemonic;
7mod payment_summary;
8mod setup;
9
10use std::collections::BTreeMap;
11use std::fmt::Display;
12use std::sync::Arc;
13
14use ::bitcoin::{Address, Txid};
15use async_trait::async_trait;
16use axum::body::Body;
17use axum::extract::{Query, State};
18use axum::http::header;
19use axum::response::{Html, IntoResponse, Redirect, Response};
20use axum::routing::{get, post};
21use axum::{Form, Router};
22use axum_extra::extract::CookieJar;
23use axum_extra::extract::cookie::{Cookie, SameSite};
24use fedimint_core::bitcoin::Network;
25use fedimint_core::config::FederationId;
26use fedimint_core::invite_code::InviteCode;
27use fedimint_core::secp256k1::serde::Deserialize;
28use fedimint_core::task::TaskGroup;
29use fedimint_core::{PeerId, TieredCounts};
30use fedimint_gateway_common::{
31    ChainSource, CloseChannelsWithPeerRequest, CloseChannelsWithPeerResponse, ConnectFedPayload,
32    CreateInvoiceForOperatorPayload, CreateOfferPayload, CreateOfferResponse,
33    DepositAddressPayload, FederationInfo, GatewayBalances, GatewayInfo, LeaveFedPayload,
34    LightningMode, ListTransactionsPayload, ListTransactionsResponse, MnemonicResponse,
35    OpenChannelRequest, PayInvoiceForOperatorPayload, PayOfferPayload, PayOfferResponse,
36    PaymentLogPayload, PaymentLogResponse, PaymentSummaryPayload, PaymentSummaryResponse,
37    ReceiveEcashPayload, ReceiveEcashResponse, SendOnchainRequest, SetFeesPayload,
38    SetMnemonicPayload, SpendEcashPayload, SpendEcashResponse, WithdrawPayload,
39    WithdrawPreviewPayload, WithdrawPreviewResponse, WithdrawResponse,
40};
41use fedimint_ln_common::contracts::Preimage;
42use fedimint_logging::LOG_GATEWAY_UI;
43use fedimint_ui_common::assets::WithStaticRoutesExt;
44use fedimint_ui_common::auth::UserAuth;
45use fedimint_ui_common::{
46    LOGIN_ROUTE, LoginInput, ROOT_ROUTE, UiState, dashboard_layout,
47    login_form as render_login_form, single_card_layout,
48};
49use lightning_invoice::Bolt11Invoice;
50use maud::html;
51use tracing::debug;
52
53use crate::connect_fed::connect_federation_handler;
54use crate::federation::{
55    deposit_address_handler, leave_federation_handler, receive_ecash_handler, set_fees_handler,
56    spend_ecash_handler, withdraw_confirm_handler, withdraw_preview_handler,
57};
58use crate::lightning::{
59    channels_fragment_handler, close_channel_handler, create_bolt11_invoice_handler,
60    create_receive_invoice_handler, detect_payment_type_handler, generate_receive_address_handler,
61    open_channel_handler, pay_bolt11_invoice_handler, pay_unified_handler,
62    payments_fragment_handler, send_onchain_handler, transactions_fragment_handler,
63    wallet_fragment_handler,
64};
65use crate::mnemonic::{mnemonic_iframe_handler, mnemonic_reveal_handler};
66use crate::payment_summary::payment_log_fragment_handler;
67use crate::setup::{create_wallet_handler, recover_wallet_form, recover_wallet_handler};
68pub type DynGatewayApi<E> = Arc<dyn IAdminGateway<Error = E> + Send + Sync + 'static>;
69
70pub(crate) const OPEN_CHANNEL_ROUTE: &str = "/ui/channels/open";
71pub(crate) const CLOSE_CHANNEL_ROUTE: &str = "/ui/channels/close";
72pub(crate) const CHANNEL_FRAGMENT_ROUTE: &str = "/ui/channels/fragment";
73pub(crate) const LEAVE_FEDERATION_ROUTE: &str = "/ui/federations/{id}/leave";
74pub(crate) const CONNECT_FEDERATION_ROUTE: &str = "/ui/federations/join";
75pub(crate) const SET_FEES_ROUTE: &str = "/ui/federation/set-fees";
76pub(crate) const SEND_ONCHAIN_ROUTE: &str = "/ui/wallet/send";
77pub(crate) const WALLET_FRAGMENT_ROUTE: &str = "/ui/wallet/fragment";
78pub(crate) const LN_ONCHAIN_ADDRESS_ROUTE: &str = "/ui/wallet/receive";
79pub(crate) const DEPOSIT_ADDRESS_ROUTE: &str = "/ui/federations/deposit-address";
80pub(crate) const PAYMENTS_FRAGMENT_ROUTE: &str = "/ui/payments/fragment";
81pub(crate) const CREATE_BOLT11_INVOICE_ROUTE: &str = "/ui/payments/receive/bolt11";
82pub(crate) const CREATE_RECEIVE_INVOICE_ROUTE: &str = "/ui/payments/receive";
83pub(crate) const PAY_BOLT11_INVOICE_ROUTE: &str = "/ui/payments/send/bolt11";
84pub(crate) const PAY_UNIFIED_ROUTE: &str = "/ui/payments/send";
85pub(crate) const DETECT_PAYMENT_TYPE_ROUTE: &str = "/ui/payments/detect";
86pub(crate) const TRANSACTIONS_FRAGMENT_ROUTE: &str = "/ui/transactions/fragment";
87pub(crate) const RECEIVE_ECASH_ROUTE: &str = "/ui/federations/receive";
88pub(crate) const STOP_GATEWAY_ROUTE: &str = "/ui/stop";
89pub(crate) const WITHDRAW_PREVIEW_ROUTE: &str = "/ui/federations/withdraw-preview";
90pub(crate) const WITHDRAW_CONFIRM_ROUTE: &str = "/ui/federations/withdraw-confirm";
91pub(crate) const SPEND_ECASH_ROUTE: &str = "/ui/federations/spend";
92pub(crate) const PAYMENT_LOG_ROUTE: &str = "/ui/payment-log";
93pub(crate) const CREATE_WALLET_ROUTE: &str = "/ui/wallet/create";
94pub(crate) const RECOVER_WALLET_ROUTE: &str = "/ui/wallet/recover";
95pub(crate) const MNEMONIC_IFRAME_ROUTE: &str = "/ui/mnemonic/iframe";
96pub(crate) const EXPORT_INVITE_CODES_ROUTE: &str = "/ui/export-invite-codes";
97
98#[derive(Default, Deserialize)]
99pub struct DashboardQuery {
100    pub success: Option<String>,
101    pub ui_error: Option<String>,
102    pub show_export_reminder: Option<bool>,
103}
104
105fn redirect_success(msg: String) -> impl IntoResponse {
106    let encoded: String = url::form_urlencoded::byte_serialize(msg.as_bytes()).collect();
107    Redirect::to(&format!("/?success={}", encoded))
108}
109
110pub(crate) fn redirect_success_with_export_reminder(msg: String) -> impl IntoResponse {
111    let encoded: String = url::form_urlencoded::byte_serialize(msg.as_bytes()).collect();
112    Redirect::to(&format!("/?success={}&show_export_reminder=true", encoded))
113}
114
115fn redirect_error(msg: String) -> impl IntoResponse {
116    let encoded: String = url::form_urlencoded::byte_serialize(msg.as_bytes()).collect();
117    Redirect::to(&format!("/?ui_error={}", encoded))
118}
119
120pub fn is_allowed_setup_route(path: &str) -> bool {
121    path == ROOT_ROUTE
122        || path == LOGIN_ROUTE
123        || path.starts_with("/assets/")
124        || path == CREATE_WALLET_ROUTE
125        || path == RECOVER_WALLET_ROUTE
126}
127
128#[async_trait]
129pub trait IAdminGateway {
130    type Error;
131
132    async fn handle_get_info(&self) -> Result<GatewayInfo, Self::Error>;
133
134    async fn handle_list_channels_msg(
135        &self,
136    ) -> Result<Vec<fedimint_gateway_common::ChannelInfo>, Self::Error>;
137
138    async fn handle_payment_summary_msg(
139        &self,
140        PaymentSummaryPayload {
141            start_millis,
142            end_millis,
143        }: PaymentSummaryPayload,
144    ) -> Result<PaymentSummaryResponse, Self::Error>;
145
146    async fn handle_leave_federation(
147        &self,
148        payload: LeaveFedPayload,
149    ) -> Result<FederationInfo, Self::Error>;
150
151    async fn handle_connect_federation(
152        &self,
153        payload: ConnectFedPayload,
154    ) -> Result<FederationInfo, Self::Error>;
155
156    async fn handle_set_fees_msg(&self, payload: SetFeesPayload) -> Result<(), Self::Error>;
157
158    async fn handle_mnemonic_msg(&self) -> Result<MnemonicResponse, Self::Error>;
159
160    async fn handle_open_channel_msg(
161        &self,
162        payload: OpenChannelRequest,
163    ) -> Result<Txid, Self::Error>;
164
165    async fn handle_close_channels_with_peer_msg(
166        &self,
167        payload: CloseChannelsWithPeerRequest,
168    ) -> Result<CloseChannelsWithPeerResponse, Self::Error>;
169
170    async fn handle_get_balances_msg(&self) -> Result<GatewayBalances, Self::Error>;
171
172    async fn handle_send_onchain_msg(
173        &self,
174        payload: SendOnchainRequest,
175    ) -> Result<Txid, Self::Error>;
176
177    async fn handle_get_ln_onchain_address_msg(&self) -> Result<Address, Self::Error>;
178
179    async fn handle_deposit_address_msg(
180        &self,
181        payload: DepositAddressPayload,
182    ) -> Result<Address, Self::Error>;
183
184    async fn handle_receive_ecash_msg(
185        &self,
186        payload: ReceiveEcashPayload,
187    ) -> Result<ReceiveEcashResponse, Self::Error>;
188
189    async fn handle_create_invoice_for_operator_msg(
190        &self,
191        payload: CreateInvoiceForOperatorPayload,
192    ) -> Result<Bolt11Invoice, Self::Error>;
193
194    async fn handle_pay_invoice_for_operator_msg(
195        &self,
196        payload: PayInvoiceForOperatorPayload,
197    ) -> Result<Preimage, Self::Error>;
198
199    async fn handle_list_transactions_msg(
200        &self,
201        payload: ListTransactionsPayload,
202    ) -> Result<ListTransactionsResponse, Self::Error>;
203
204    async fn handle_spend_ecash_msg(
205        &self,
206        payload: SpendEcashPayload,
207    ) -> Result<SpendEcashResponse, Self::Error>;
208
209    async fn handle_shutdown_msg(&self, task_group: TaskGroup) -> Result<(), Self::Error>;
210
211    fn get_task_group(&self) -> TaskGroup;
212
213    async fn handle_withdraw_msg(
214        &self,
215        payload: WithdrawPayload,
216    ) -> Result<WithdrawResponse, Self::Error>;
217
218    async fn handle_withdraw_preview_msg(
219        &self,
220        payload: WithdrawPreviewPayload,
221    ) -> Result<WithdrawPreviewResponse, Self::Error>;
222
223    async fn handle_payment_log_msg(
224        &self,
225        payload: PaymentLogPayload,
226    ) -> Result<PaymentLogResponse, Self::Error>;
227
228    async fn handle_export_invite_codes(
229        &self,
230    ) -> BTreeMap<FederationId, BTreeMap<PeerId, (String, InviteCode)>>;
231
232    fn get_password_hash(&self) -> String;
233
234    fn gatewayd_version(&self) -> String;
235
236    async fn get_chain_source(&self) -> (ChainSource, Network);
237
238    fn lightning_mode(&self) -> LightningMode;
239
240    async fn is_configured(&self) -> bool;
241
242    async fn handle_set_mnemonic_msg(&self, payload: SetMnemonicPayload)
243    -> Result<(), Self::Error>;
244
245    async fn handle_create_offer_for_operator_msg(
246        &self,
247        payload: CreateOfferPayload,
248    ) -> Result<CreateOfferResponse, Self::Error>;
249
250    async fn handle_pay_offer_for_operator_msg(
251        &self,
252        payload: PayOfferPayload,
253    ) -> Result<PayOfferResponse, Self::Error>;
254
255    async fn handle_get_note_summary_msg(
256        &self,
257        federation_id: &FederationId,
258    ) -> Result<TieredCounts, Self::Error>;
259}
260
261async fn login_form_handler<E>(
262    State(_state): State<UiState<DynGatewayApi<E>>>,
263) -> impl IntoResponse {
264    Html(single_card_layout("Enter Password", render_login_form(None)).into_string())
265}
266
267// Dashboard login submit handler
268async fn login_submit<E>(
269    State(state): State<UiState<DynGatewayApi<E>>>,
270    jar: CookieJar,
271    Form(input): Form<LoginInput>,
272) -> impl IntoResponse {
273    if let Ok(verify) = bcrypt::verify(&input.password, &state.api.get_password_hash())
274        && verify
275    {
276        let mut cookie = Cookie::new(state.auth_cookie_name.clone(), state.auth_cookie_value);
277        cookie.set_path(ROOT_ROUTE);
278
279        cookie.set_http_only(true);
280        cookie.set_same_site(Some(SameSite::Lax));
281
282        let jar = jar.add(cookie);
283        return (jar, [("HX-Redirect", "/")]).into_response();
284    }
285
286    Html(render_login_form(Some("The password is invalid")).into_string()).into_response()
287}
288
289async fn dashboard_view<E>(
290    State(state): State<UiState<DynGatewayApi<E>>>,
291    _auth: UserAuth,
292    Query(msg): Query<DashboardQuery>,
293) -> impl IntoResponse
294where
295    E: std::fmt::Display,
296{
297    // If gateway is not configured, show setup view instead of dashboard
298    if !state.api.is_configured().await {
299        return setup::setup_view(State(state), Query(msg))
300            .await
301            .into_response();
302    }
303
304    let gatewayd_version = state.api.gatewayd_version();
305    debug!(target: LOG_GATEWAY_UI, "Getting gateway info...");
306    let gateway_info = match state.api.handle_get_info().await {
307        Ok(info) => info,
308        Err(err) => {
309            let content = html! {
310                div class="alert alert-danger mt-4" {
311                    strong { "Failed to fetch gateway info: " }
312                    (err.to_string())
313                }
314            };
315            return Html(dashboard_layout(content, &gatewayd_version).into_string())
316                .into_response();
317        }
318    };
319
320    let content = html! {
321
322       (federation::scripts())
323
324        @if let Some(success) = msg.success {
325            div class="alert alert-success mt-2 d-flex justify-content-between align-items-center" {
326                span {
327                    (success)
328                    @if msg.show_export_reminder.unwrap_or(false) {
329                        " "
330                        a href=(EXPORT_INVITE_CODES_ROUTE) { "Export your invite codes for backup." }
331                    }
332                }
333                a href=(ROOT_ROUTE)
334                class="ms-3 text-decoration-none text-dark fw-bold"
335                style="font-size: 1.5rem; line-height: 1; cursor: pointer;"
336                { "×" }
337            }
338        }
339        @if let Some(error) = msg.ui_error {
340            div class="alert alert-danger mt-2 d-flex justify-content-between align-items-center" {
341                span { (error) }
342                a href=(ROOT_ROUTE)
343                class="ms-3 text-decoration-none text-dark fw-bold"
344                style="font-size: 1.5rem; line-height: 1; cursor: pointer;"
345                { "×" }
346            }
347        }
348
349        div class="row mt-4" {
350            div class="col-md-12 text-end" {
351                a href=(EXPORT_INVITE_CODES_ROUTE) class="btn btn-outline-primary me-2" {
352                    "Export Invite Codes"
353                }
354                form action=(STOP_GATEWAY_ROUTE) method="post" style="display: inline;" {
355                    button class="btn btn-outline-danger" type="submit"
356                        onclick="return confirm('Are you sure you want to safely stop the gateway? The gateway will wait for outstanding payments and then shutdown.');"
357                    {
358                        "Safely Stop Gateway"
359                    }
360                }
361            }
362        }
363
364        div class="row gy-4" {
365            div class="col-md-6" {
366                (general::render(&gateway_info))
367            }
368            div class="col-md-6" {
369                (payment_summary::render(&state.api, &gateway_info.federations).await)
370            }
371        }
372
373        div class="row gy-4 mt-2" {
374            div class="col-md-6" {
375                (bitcoin::render(&state.api).await)
376            }
377            div class="col-md-6" {
378                (mnemonic::render())
379            }
380        }
381
382        div class="row gy-4 mt-2" {
383            div class="col-md-12" {
384                (lightning::render(&gateway_info, &state.api).await)
385            }
386        }
387
388        div class="row gy-4 mt-2" {
389            div class="col-md-12" {
390                (connect_fed::render(&gateway_info.gateway_state))
391            }
392        }
393
394        @let invite_codes = state.api.handle_export_invite_codes().await;
395        @let empty_map = BTreeMap::new();
396
397        @for fed in &gateway_info.federations {
398            @let fed_codes = invite_codes.get(&fed.federation_id).unwrap_or(&empty_map);
399            @let note_summary = state.api.handle_get_note_summary_msg(&fed.federation_id).await;
400            (federation::render(fed, fed_codes, &note_summary))
401        }
402    };
403
404    Html(dashboard_layout(content, &gatewayd_version).into_string()).into_response()
405}
406
407async fn stop_gateway_handler<E>(
408    State(state): State<UiState<DynGatewayApi<E>>>,
409    _auth: UserAuth,
410) -> impl IntoResponse
411where
412    E: std::fmt::Display,
413{
414    match state
415        .api
416        .handle_shutdown_msg(state.api.get_task_group())
417        .await
418    {
419        Ok(_) => redirect_success("Gateway is safely shutting down...".to_string()).into_response(),
420        Err(err) => redirect_error(format!("Failed to stop gateway: {err}")).into_response(),
421    }
422}
423
424async fn export_invite_codes_handler<E>(
425    State(state): State<UiState<DynGatewayApi<E>>>,
426    _auth: UserAuth,
427) -> impl IntoResponse
428where
429    E: std::fmt::Display,
430{
431    let invite_codes: BTreeMap<FederationId, Vec<InviteCode>> = state
432        .api
433        .handle_export_invite_codes()
434        .await
435        .into_iter()
436        .map(|(fed_id, peers)| {
437            let codes = peers.into_values().map(|(_, code)| code).collect();
438            (fed_id, codes)
439        })
440        .collect();
441    let json = match serde_json::to_string_pretty(&invite_codes) {
442        Ok(json) => json,
443        Err(err) => {
444            return Response::builder()
445                .status(500)
446                .body(Body::from(format!(
447                    "Failed to serialize invite codes: {err}"
448                )))
449                .expect("Failed to build error response");
450        }
451    };
452    let filename = "gateway-invite-codes.json";
453
454    Response::builder()
455        .header(header::CONTENT_TYPE, "application/json")
456        .header(
457            header::CONTENT_DISPOSITION,
458            format!("attachment; filename=\"{filename}\""),
459        )
460        .body(Body::from(json))
461        .expect("Failed to build response")
462}
463
464pub fn router<E: Display + Send + Sync + std::fmt::Debug + 'static>(
465    api: DynGatewayApi<E>,
466) -> Router {
467    let app = Router::new()
468        .route(ROOT_ROUTE, get(dashboard_view))
469        .route(LOGIN_ROUTE, get(login_form_handler).post(login_submit))
470        .route(OPEN_CHANNEL_ROUTE, post(open_channel_handler))
471        .route(CLOSE_CHANNEL_ROUTE, post(close_channel_handler))
472        .route(CHANNEL_FRAGMENT_ROUTE, get(channels_fragment_handler))
473        .route(WALLET_FRAGMENT_ROUTE, get(wallet_fragment_handler))
474        .route(LEAVE_FEDERATION_ROUTE, post(leave_federation_handler))
475        .route(CONNECT_FEDERATION_ROUTE, post(connect_federation_handler))
476        .route(SET_FEES_ROUTE, post(set_fees_handler))
477        .route(SEND_ONCHAIN_ROUTE, post(send_onchain_handler))
478        .route(
479            LN_ONCHAIN_ADDRESS_ROUTE,
480            get(generate_receive_address_handler),
481        )
482        .route(DEPOSIT_ADDRESS_ROUTE, post(deposit_address_handler))
483        .route(SPEND_ECASH_ROUTE, post(spend_ecash_handler))
484        .route(RECEIVE_ECASH_ROUTE, post(receive_ecash_handler))
485        .route(PAYMENTS_FRAGMENT_ROUTE, get(payments_fragment_handler))
486        .route(
487            CREATE_BOLT11_INVOICE_ROUTE,
488            post(create_bolt11_invoice_handler),
489        )
490        .route(
491            CREATE_RECEIVE_INVOICE_ROUTE,
492            post(create_receive_invoice_handler),
493        )
494        .route(PAY_BOLT11_INVOICE_ROUTE, post(pay_bolt11_invoice_handler))
495        .route(PAY_UNIFIED_ROUTE, post(pay_unified_handler))
496        .route(DETECT_PAYMENT_TYPE_ROUTE, post(detect_payment_type_handler))
497        .route(
498            TRANSACTIONS_FRAGMENT_ROUTE,
499            get(transactions_fragment_handler),
500        )
501        .route(STOP_GATEWAY_ROUTE, post(stop_gateway_handler))
502        .route(EXPORT_INVITE_CODES_ROUTE, get(export_invite_codes_handler))
503        .route(WITHDRAW_PREVIEW_ROUTE, post(withdraw_preview_handler))
504        .route(WITHDRAW_CONFIRM_ROUTE, post(withdraw_confirm_handler))
505        .route(PAYMENT_LOG_ROUTE, get(payment_log_fragment_handler))
506        .route(CREATE_WALLET_ROUTE, post(create_wallet_handler))
507        .route(
508            RECOVER_WALLET_ROUTE,
509            get(recover_wallet_form).post(recover_wallet_handler),
510        )
511        .route(
512            MNEMONIC_IFRAME_ROUTE,
513            get(mnemonic_iframe_handler).post(mnemonic_reveal_handler),
514        )
515        .with_static_routes();
516
517    app.with_state(UiState::new(api))
518}