Skip to main content

fedimint_gateway_server/
config.rs

1use std::net::SocketAddr;
2use std::path::PathBuf;
3use std::str::FromStr;
4
5use anyhow::ensure;
6use bitcoin::Network;
7use clap::builder::BoolishValueParser;
8use clap::{ArgGroup, Parser};
9use fedimint_core::envs::{FM_IROH_DNS_ENV, FM_IROH_RELAY_ENV};
10use fedimint_core::util::SafeUrl;
11use fedimint_gateway_common::{LightningMode, V1_API_ENDPOINT};
12use fedimint_lnv2_common::gateway_api::PaymentFee;
13
14use super::envs;
15use crate::envs::{
16    FM_BITCOIND_PASSWORD_ENV, FM_BITCOIND_URL_ENV, FM_BITCOIND_USERNAME_ENV, FM_ESPLORA_URL_ENV,
17    FM_GATEWAY_METRICS_LISTEN_ADDR_ENV, FM_GATEWAY_SKIP_SETUP_ENV,
18};
19
20#[derive(Debug, Clone, Copy, clap::ValueEnum)]
21pub enum DatabaseBackend {
22    /// Use RocksDB database backend
23    #[value(name = "rocksdb")]
24    RocksDb,
25    /// Use CursedRedb database backend (hybrid memory/redb)
26    #[value(name = "cursed-redb")]
27    CursedRedb,
28}
29
30/// Command line parameters for starting the gateway. `mode`, `data_dir`,
31/// `listen`, and `api_addr` are all required.
32#[derive(Parser)]
33#[command(version)]
34#[command(
35    group(
36        ArgGroup::new("bitcoind_password_auth")
37           .args(["bitcoind_password", "bitcoind_password_file"])
38           .multiple(true)
39    ),
40    group(
41        ArgGroup::new("bitcoind_auth")
42            .args(["bitcoind_url"])
43            .requires("bitcoind_password_auth")
44            .requires_all(["bitcoind_username", "bitcoind_url"])
45    ),
46    group(
47        ArgGroup::new("bitcoin_rpc")
48            .required(true)
49            .multiple(true)
50            .args(["bitcoind_url", "esplora_url"])
51    )
52)]
53pub struct GatewayOpts {
54    #[clap(subcommand)]
55    pub mode: LightningMode,
56
57    /// Path to folder containing gateway config and data files
58    #[arg(long = "data-dir", env = envs::FM_GATEWAY_DATA_DIR_ENV)]
59    pub data_dir: PathBuf,
60
61    /// Gateway webserver listen address
62    #[arg(long = "listen", env = envs::FM_GATEWAY_LISTEN_ADDR_ENV)]
63    listen: SocketAddr,
64
65    /// Public URL from which the webserver API is reachable
66    #[arg(long = "api-addr", env = envs::FM_GATEWAY_API_ADDR_ENV)]
67    api_addr: Option<SafeUrl>,
68
69    /// Gateway authentication hash (discouraged in argv/environment).
70    /// Prefer --bcrypt-password-hash-file.
71    #[arg(long = "bcrypt-password-hash", env = envs::FM_GATEWAY_BCRYPT_PASSWORD_HASH_ENV, hide_env_values = true, required_unless_present = "bcrypt_password_hash_file")]
72    bcrypt_password_hash: Option<String>,
73
74    /// Read the gateway authentication hash from a file (stdin is not
75    /// supported)
76    #[arg(long)]
77    bcrypt_password_hash_file: Option<PathBuf>,
78
79    /// Gateway liquidity manager for channel and liquidity management
80    /// operations (discouraged in argv/environment). Prefer the file option.
81    #[arg(long = "bcrypt_liquidity_manager_password_hash", env = envs::FM_GATEWAY_LIQUIDITY_MANAGER_BCRYPT_PASSWORD_HASH_ENV, hide_env_values = true)]
82    bcrypt_liquidity_manager_password_hash: Option<String>,
83
84    /// Read the liquidity manager authentication hash from a file (not stdin)
85    #[arg(long)]
86    bcrypt_liquidity_manager_password_hash_file: Option<PathBuf>,
87
88    /// Bitcoin network this gateway will be running on
89    #[arg(long = "network", env = envs::FM_GATEWAY_NETWORK_ENV)]
90    network: Network,
91
92    /// Number of route hints to return in invoices
93    #[arg(
94        long = "num-route-hints",
95        env = envs::FM_NUMBER_OF_ROUTE_HINTS_ENV,
96        default_value_t = super::DEFAULT_NUM_ROUTE_HINTS
97    )]
98    num_route_hints: u32,
99
100    /// Database backend to use.
101    #[arg(long, env = envs::FM_DB_BACKEND_ENV, value_enum, default_value = "rocksdb")]
102    pub db_backend: DatabaseBackend,
103
104    /// The username to use when connecting to bitcoind
105    #[arg(long, env = FM_BITCOIND_USERNAME_ENV)]
106    pub bitcoind_username: Option<String>,
107
108    /// Bitcoin RPC password (discouraged in argv/environment).
109    /// Prefer --bitcoind-password-file.
110    #[arg(long, env = FM_BITCOIND_PASSWORD_ENV, hide_env_values = true)]
111    pub bitcoind_password: Option<String>,
112
113    /// Read the Bitcoin RPC password from a file (stdin is not supported)
114    #[arg(long)]
115    pub bitcoind_password_file: Option<PathBuf>,
116
117    /// Bitcoind RPC URL, e.g. <http://127.0.0.1:8332>
118    /// This should not include authentication parameters, they should be
119    /// included in `FM_BITCOIND_USERNAME` and `FM_BITCOIND_PASSWORD`
120    #[arg(long, env = FM_BITCOIND_URL_ENV)]
121    pub bitcoind_url: Option<SafeUrl>,
122
123    /// Esplora HTTP base URL, e.g. <https://mempool.space/api>
124    #[arg(long, env = FM_ESPLORA_URL_ENV)]
125    pub esplora_url: Option<SafeUrl>,
126
127    /// The default routing fees that are applied to new federations
128    #[arg(long = "default-routing-fees", env = envs::FM_DEFAULT_ROUTING_FEES_ENV, default_value_t = PaymentFee::TRANSACTION_FEE_DEFAULT)]
129    default_routing_fees: PaymentFee,
130
131    /// The default transaction fees that are applied to new federations
132    #[arg(long = "default-transaction-fees", env = envs::FM_DEFAULT_TRANSACTION_FEES_ENV, default_value_t = PaymentFee::TRANSACTION_FEE_DEFAULT)]
133    default_transaction_fees: PaymentFee,
134
135    /// Gateway iroh listen address
136    #[arg(long = "iroh-listen", env = envs::FM_GATEWAY_IROH_LISTEN_ADDR_ENV)]
137    iroh_listen: Option<SocketAddr>,
138
139    /// Gateway metrics listen address. If not set, defaults to localhost on the
140    /// UI port + 1.
141    #[arg(long = "metrics-listen", env = FM_GATEWAY_METRICS_LISTEN_ADDR_ENV)]
142    metrics_listen: Option<SocketAddr>,
143
144    /// Optional URL of the Iroh DNS server
145    #[arg(long, env = FM_IROH_DNS_ENV)]
146    iroh_dns: Option<SafeUrl>,
147
148    /// Optional URLs of the Iroh relays to use for registering
149    #[arg(long, env = FM_IROH_RELAY_ENV, value_delimiter = ',')]
150    iroh_relays: Vec<SafeUrl>,
151
152    #[arg(
153        long,
154        env = FM_GATEWAY_SKIP_SETUP_ENV,
155        default_value_t = false,
156        value_parser = BoolishValueParser::new()
157    )]
158    skip_setup: bool,
159
160    /// Maximum burst of requests to the public invoice creation endpoint
161    /// accepted before rate limiting kicks in
162    #[arg(
163        long = "invoice-rate-limit-burst",
164        env = envs::FM_GATEWAY_INVOICE_RATE_LIMIT_BURST_ENV,
165        default_value_t = super::DEFAULT_INVOICE_RATE_LIMIT_BURST,
166        value_parser = clap::value_parser!(u32).range(1..)
167    )]
168    invoice_rate_limit_burst: u32,
169
170    /// Sustained number of requests per second to the public invoice creation
171    /// endpoint accepted before rate limiting kicks in
172    #[arg(
173        long = "invoice-rate-limit-per-second",
174        env = envs::FM_GATEWAY_INVOICE_RATE_LIMIT_PER_SECOND_ENV,
175        default_value_t = super::DEFAULT_INVOICE_RATE_LIMIT_PER_SECOND,
176        value_parser = clap::value_parser!(u32).range(1..)
177    )]
178    invoice_rate_limit_per_second: u32,
179}
180
181impl GatewayOpts {
182    /// Resolve secrets once at startup, before constructing runtime parameters.
183    /// Reject conflicting sources without echoing their values.
184    pub fn resolve_secret_inputs(&mut self) -> anyhow::Result<()> {
185        let sources = [
186            (
187                &mut self.bcrypt_password_hash,
188                &mut self.bcrypt_password_hash_file,
189            ),
190            (
191                &mut self.bcrypt_liquidity_manager_password_hash,
192                &mut self.bcrypt_liquidity_manager_password_hash_file,
193            ),
194            (
195                &mut self.bitcoind_password,
196                &mut self.bitcoind_password_file,
197            ),
198        ];
199        for (value, file) in &sources {
200            ensure!(
201                value.is_none() || file.is_none(),
202                "Specify only one value or file source for each secret"
203            );
204            ensure!(
205                file.as_deref() != Some(std::path::Path::new("-")),
206                "Daemon secrets require a file; stdin is not supported"
207            );
208        }
209        for (value, file) in sources {
210            if let Some(path) = file.take() {
211                *value = Some(fedimint_core::util::read_secret_file(&path, 1024 * 1024)?);
212            }
213        }
214        Ok(())
215    }
216
217    /// Converts the command line parameters into a helper struct the Gateway
218    /// uses to store runtime parameters.
219    pub fn to_gateway_parameters(&self) -> anyhow::Result<GatewayParameters> {
220        let versioned_api = self.api_addr.clone().map(|api_addr| {
221            api_addr
222                .join(V1_API_ENDPOINT)
223                .expect("Could not join v1 api_addr")
224        });
225        let bcrypt_password_hash = bcrypt::HashParts::from_str(
226            self.bcrypt_password_hash
227                .as_deref()
228                .ok_or_else(|| anyhow::anyhow!("Missing gateway password hash"))?,
229        )
230        .map_err(|_| anyhow::anyhow!("Invalid gateway password hash"))?;
231        let bcrypt_liquidity_manager_password_hash =
232            if let Some(h) = &self.bcrypt_liquidity_manager_password_hash {
233                Some(
234                    bcrypt::HashParts::from_str(h)
235                        .map_err(|_| anyhow::anyhow!("Invalid liquidity manager password hash"))?,
236                )
237            } else {
238                None
239            };
240
241        // The defaults are copied into the config of every federation the gateway
242        // connects to, so they have to satisfy the same limits `set_fees` enforces.
243        // Rejecting them here means a fee that cannot be announced to LNv1 clients
244        // never reaches the database.
245        let send_fees = self
246            .default_routing_fees
247            .checked_add(self.default_transaction_fees)
248            .ok_or_else(|| {
249                anyhow::anyhow!(
250                    "Total of default routing and transaction fees overflowed, they may not exceed {}",
251                    PaymentFee::SEND_FEE_LIMIT
252                )
253            })?;
254        ensure!(
255            send_fees.is_within(&PaymentFee::SEND_FEE_LIMIT),
256            "Total of default routing and transaction fees exceeded {}",
257            PaymentFee::SEND_FEE_LIMIT
258        );
259        ensure!(
260            self.default_transaction_fees
261                .is_within(&PaymentFee::RECEIVE_FEE_LIMIT),
262            "Default transaction fees exceeded RECEIVE LIMIT {}",
263            PaymentFee::RECEIVE_FEE_LIMIT
264        );
265
266        // Default metrics listen to localhost on UI port + 1
267        let metrics_listen = self.metrics_listen.unwrap_or_else(|| {
268            SocketAddr::new(
269                std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
270                self.listen.port() + 1,
271            )
272        });
273
274        Ok(GatewayParameters {
275            listen: self.listen,
276            versioned_api,
277            bcrypt_password_hash,
278            bcrypt_liquidity_manager_password_hash,
279            network: self.network,
280            num_route_hints: self.num_route_hints,
281            default_routing_fees: self.default_routing_fees,
282            default_transaction_fees: self.default_transaction_fees,
283            iroh_listen: self.iroh_listen,
284            iroh_dns: self.iroh_dns.clone(),
285            iroh_relays: self.iroh_relays.clone(),
286            skip_setup: self.skip_setup,
287            metrics_listen,
288            invoice_rate_limit_burst: self.invoice_rate_limit_burst,
289            invoice_rate_limit_per_second: self.invoice_rate_limit_per_second,
290        })
291    }
292}
293
294#[cfg(test)]
295mod tests;
296
297/// `GatewayParameters` is a helper struct that can be derived from
298/// `GatewayOpts` that holds the CLI or environment variables that are specified
299/// by the user.
300///
301/// If `GatewayConfiguration is set in the database, that takes precedence and
302/// the optional parameters will have no affect.
303#[derive(Debug)]
304pub struct GatewayParameters {
305    pub listen: SocketAddr,
306    pub versioned_api: Option<SafeUrl>,
307    pub bcrypt_password_hash: bcrypt::HashParts,
308    pub bcrypt_liquidity_manager_password_hash: Option<bcrypt::HashParts>,
309    pub network: Network,
310    pub num_route_hints: u32,
311    pub default_routing_fees: PaymentFee,
312    pub default_transaction_fees: PaymentFee,
313    pub iroh_listen: Option<SocketAddr>,
314    pub iroh_dns: Option<SafeUrl>,
315    pub iroh_relays: Vec<SafeUrl>,
316    pub skip_setup: bool,
317    pub metrics_listen: SocketAddr,
318    pub invoice_rate_limit_burst: u32,
319    pub invoice_rate_limit_per_second: u32,
320}