Skip to main content

fedimint_recurringdv2/
main.rs

1use std::net::SocketAddr;
2
3use anyhow::{bail, ensure};
4use axum::extract::{Path, Query, State};
5use axum::http::HeaderMap;
6use axum::response::IntoResponse;
7use axum::routing::get;
8use axum::{Json, Router};
9use bitcoin::hashes::sha256;
10use bitcoin::secp256k1::{self, PublicKey};
11use clap::Parser;
12use fedimint_connectors::ConnectorRegistry;
13use fedimint_core::base32::{FEDIMINT_PREFIX, decode_prefixed};
14use fedimint_core::config::FederationId;
15use fedimint_core::encoding::Encodable;
16use fedimint_core::secp256k1::Scalar;
17use fedimint_core::time::duration_since_epoch;
18use fedimint_core::util::SafeUrl;
19use fedimint_core::{Amount, BitcoinHash};
20use fedimint_lnurl::{InvoiceResponse, LnurlResponse, PayResponse, pay_request_tag};
21use fedimint_lnv2_common::contracts::{IncomingContract, PaymentImage};
22use fedimint_lnv2_common::gateway_api::{
23    GatewayConnection, PaymentFee, RealGatewayConnection, RoutingInfo,
24};
25use fedimint_lnv2_common::lnurl::LnurlRequest;
26use fedimint_lnv2_common::{
27    Bolt11InvoiceDescription, GatewayApi, MINIMUM_INCOMING_CONTRACT_AMOUNT, tweak,
28};
29use fedimint_logging::TracingSetup;
30use lightning_invoice::Bolt11Invoice;
31use serde::{Deserialize, Serialize};
32use tokio::net::TcpListener;
33use tower_http::cors;
34use tower_http::cors::CorsLayer;
35use tpe::AggregatePublicKey;
36use tracing::info;
37
38const MAX_SENDABLE_MSAT: u64 = 100_000_000_000;
39const MIN_SENDABLE_MSAT: u64 = 100_000;
40
41#[derive(Debug, Parser)]
42struct CliOpts {
43    /// Address to bind the server to
44    ///
45    /// Should be `0.0.0.0:8176` most of the time, as api connectivity is public
46    /// and direct, and the port should be open in the firewall.
47    #[arg(long, env = "FM_BIND_API", default_value = "0.0.0.0:8176")]
48    bind_api: SocketAddr,
49}
50
51#[derive(Clone)]
52struct AppState {
53    gateway_conn: RealGatewayConnection,
54}
55
56#[tokio::main]
57async fn main() -> anyhow::Result<()> {
58    TracingSetup::default().init()?;
59
60    let cli_opts = CliOpts::parse();
61
62    let connector_registry = ConnectorRegistry::build_from_client_defaults()
63        .with_env_var_overrides()?
64        .bind()
65        .await?;
66
67    let state = AppState {
68        gateway_conn: RealGatewayConnection {
69            api: GatewayApi::new(None, connector_registry),
70        },
71    };
72
73    let cors = CorsLayer::new()
74        .allow_origin(cors::Any)
75        .allow_methods(cors::Any)
76        .allow_headers(cors::Any);
77
78    let app = Router::new()
79        .route("/", get(health_check))
80        .route("/pay/{payload}", get(pay))
81        .route("/invoice/{payload}", get(invoice))
82        .layer(cors)
83        .with_state(state);
84
85    info!(bind_api = %cli_opts.bind_api, "recurringdv2 started");
86
87    let listener = TcpListener::bind(cli_opts.bind_api).await?;
88
89    axum::serve(listener, app).await?;
90
91    Ok(())
92}
93
94async fn health_check(headers: HeaderMap) -> impl IntoResponse {
95    format!("recurringdv2 is up and running at {}", base_url(&headers))
96}
97
98fn base_url(headers: &HeaderMap) -> String {
99    let host = headers
100        .get("x-forwarded-host")
101        .or_else(|| headers.get("host"))
102        .and_then(|h| h.to_str().ok())
103        .unwrap_or("localhost");
104
105    let scheme = headers
106        .get("x-forwarded-proto")
107        .and_then(|h| h.to_str().ok())
108        .unwrap_or("http");
109
110    format!("{scheme}://{host}/")
111}
112
113async fn pay(headers: HeaderMap, Path(payload): Path<String>) -> Json<LnurlResponse<PayResponse>> {
114    Json(LnurlResponse::Ok(PayResponse {
115        callback: format!("{}invoice/{payload}", base_url(&headers)),
116        max_sendable: MAX_SENDABLE_MSAT,
117        min_sendable: MIN_SENDABLE_MSAT,
118        tag: pay_request_tag(),
119        metadata: "[[\"text/plain\", \"Pay to Recurringd\"]]".to_string(),
120    }))
121}
122
123#[derive(Debug, Serialize, Deserialize)]
124struct GetInvoiceParams {
125    amount: u64,
126}
127
128async fn invoice(
129    Path(payload): Path<String>,
130    Query(params): Query<GetInvoiceParams>,
131    State(state): State<AppState>,
132) -> Json<LnurlResponse<InvoiceResponse>> {
133    let Ok(request) = decode_prefixed::<LnurlRequest>(FEDIMINT_PREFIX, &payload) else {
134        return Json(LnurlResponse::error("Failed to decode payload"));
135    };
136
137    if params.amount < MIN_SENDABLE_MSAT || params.amount > MAX_SENDABLE_MSAT {
138        return Json(LnurlResponse::error(format!(
139            "Amount must be between {} and {}",
140            MIN_SENDABLE_MSAT, MAX_SENDABLE_MSAT
141        )));
142    }
143
144    let (gateway, invoice) = match create_contract_and_fetch_invoice(
145        request.federation_id,
146        request.recipient_pk,
147        request.aggregate_pk,
148        request.gateways,
149        params.amount,
150        3600, // standard expiry time of one hour
151        &state.gateway_conn,
152    )
153    .await
154    {
155        Ok(result) => result,
156        Err(e) => {
157            return Json(LnurlResponse::error(e.to_string()));
158        }
159    };
160
161    info!(%params.amount, %gateway, "Created invoice");
162
163    Json(LnurlResponse::Ok(InvoiceResponse {
164        pr: invoice.clone(),
165        verify: Some(format!("{}/verify/{}", gateway, invoice.payment_hash())),
166    }))
167}
168
169#[allow(clippy::too_many_arguments)]
170async fn create_contract_and_fetch_invoice(
171    federation_id: FederationId,
172    recipient_pk: PublicKey,
173    aggregate_pk: AggregatePublicKey,
174    gateways: Vec<SafeUrl>,
175    amount: u64,
176    expiry_secs: u32,
177    gateway_conn: &RealGatewayConnection,
178) -> anyhow::Result<(SafeUrl, Bolt11Invoice)> {
179    let (ephemeral_tweak, ephemeral_pk) = tweak::generate(recipient_pk);
180
181    let scalar = Scalar::from_be_bytes(ephemeral_tweak).expect("Within curve order");
182
183    let claim_pk = recipient_pk
184        .mul_tweak(secp256k1::SECP256K1, &scalar)
185        .expect("Tweak is valid");
186
187    let encryption_seed = ephemeral_tweak
188        .consensus_hash::<sha256::Hash>()
189        .to_byte_array();
190
191    let preimage = encryption_seed
192        .consensus_hash::<sha256::Hash>()
193        .to_byte_array();
194
195    let (routing_info, gateway) = select_gateway(gateways, federation_id, gateway_conn).await?;
196
197    ensure!(
198        routing_info.receive_fee.le(&PaymentFee::RECEIVE_FEE_LIMIT),
199        "Payment fee exceeds limit"
200    );
201
202    let contract_amount = routing_info.receive_fee.subtract_from(amount);
203
204    ensure!(
205        contract_amount >= MINIMUM_INCOMING_CONTRACT_AMOUNT,
206        "Amount too small"
207    );
208
209    let expiration = duration_since_epoch()
210        .as_secs()
211        .saturating_add(u64::from(expiry_secs));
212
213    let contract = IncomingContract::new(
214        aggregate_pk,
215        encryption_seed,
216        preimage,
217        PaymentImage::Hash(preimage.consensus_hash()),
218        contract_amount,
219        expiration,
220        claim_pk,
221        routing_info.module_public_key,
222        ephemeral_pk,
223    );
224
225    let invoice = gateway_conn
226        .bolt11_invoice(
227            gateway.clone(),
228            federation_id,
229            contract.clone(),
230            Amount::from_msats(amount),
231            Bolt11InvoiceDescription::Direct("LNURL Payment".to_string()),
232            expiry_secs,
233        )
234        .await?;
235
236    ensure!(
237        invoice.payment_hash() == &preimage.consensus_hash(),
238        "Invalid invoice payment hash"
239    );
240
241    ensure!(
242        invoice.amount_milli_satoshis() == Some(amount),
243        "Invalid invoice amount"
244    );
245
246    Ok((gateway, invoice))
247}
248
249async fn select_gateway(
250    gateways: Vec<SafeUrl>,
251    federation_id: FederationId,
252    gateway_conn: &RealGatewayConnection,
253) -> anyhow::Result<(RoutingInfo, SafeUrl)> {
254    for gateway in gateways {
255        if let Ok(Some(routing_info)) = gateway_conn
256            .routing_info(gateway.clone(), &federation_id)
257            .await
258        {
259            return Ok((routing_info, gateway));
260        }
261    }
262
263    bail!("All gateways are offline or do not support this federation")
264}