Skip to main content

fedimint_core/
envs.rs

1use std::collections::BTreeMap;
2use std::ffi::OsString;
3use std::str::FromStr;
4use std::{cmp, env};
5
6use fedimint_core::util::SafeUrl;
7use fedimint_derive::{Decodable, Encodable};
8use fedimint_logging::LOG_CORE;
9use jsonrpsee_core::Serialize;
10use serde::Deserialize;
11use thiserror::Error;
12use tracing::warn;
13
14use crate::util::FmtCompact as _;
15pub use crate::{is_running_in_test_env, next_poll_delay};
16
17/// In tests we want to routinely enable an extra unknown module to ensure
18/// all client code handles correct modules that client doesn't know about.
19pub const FM_USE_UNKNOWN_MODULE_ENV: &str = "FM_USE_UNKNOWN_MODULE";
20
21/// Disable automatic consensus version voting for testing and development
22/// environments
23pub const FM_WALLET_DISABLE_AUTOMATIC_CONSENSUS_VERSION_VOTING_ENV: &str =
24    "FM_WALLET_DISABLE_AUTOMATIC_CONSENSUS_VERSION_VOTING";
25
26pub const FM_ENABLE_MODULE_LNV1_ENV: &str = "FM_ENABLE_MODULE_LNV1";
27pub const FM_ENABLE_MODULE_LNV2_ENV: &str = "FM_ENABLE_MODULE_LNV2";
28pub const FM_ENABLE_MODULE_MINT_ENV: &str = "FM_ENABLE_MODULE_MINT";
29pub const FM_ENABLE_MODULE_MINTV2_ENV: &str = "FM_ENABLE_MODULE_MINTV2";
30pub const FM_ENABLE_MODULE_WALLET_ENV: &str = "FM_ENABLE_MODULE_WALLET";
31pub const FM_ENABLE_MODULE_WALLETV2_ENV: &str = "FM_ENABLE_MODULE_WALLETV2";
32
33/// Disable mint base fees for testing and development environments
34pub const FM_DISABLE_BASE_FEES_ENV: &str = "FM_DISABLE_BASE_FEES";
35
36/// Print sensitive secrets without redacting them. Use only for debugging.
37pub const FM_DEBUG_SHOW_SECRETS_ENV: &str = "FM_DEBUG_SHOW_SECRETS";
38
39/// Check if env variable is set and not equal `0` or `false` which are common
40/// ways to disable something.
41pub fn is_env_var_set(var: &str) -> bool {
42    let Some(val) = std::env::var_os(var) else {
43        return false;
44    };
45    match val.as_encoded_bytes() {
46        b"0" | b"false" => false,
47        b"1" | b"true" => true,
48        _ => {
49            warn!(
50                target: LOG_CORE,
51                %var,
52                val = %val.to_string_lossy(),
53                "Env var value invalid is invalid and ignored, assuming `true`"
54            );
55            true
56        }
57    }
58}
59
60/// Check if env variable is set and not equal `0` or `false` which are common
61/// ways to disable a setting. `None` if env var not set at all, which allows
62/// handling the default value.
63pub fn is_env_var_set_opt(var: &str) -> Option<bool> {
64    let val = std::env::var_os(var)?;
65    match val.as_encoded_bytes() {
66        b"0" | b"false" => Some(false),
67        b"1" | b"true" => Some(true),
68        _ => {
69            warn!(
70                target: LOG_CORE,
71                %var,
72                val = %val.to_string_lossy(),
73                "Env var value invalid is invalid and ignored"
74            );
75            None
76        }
77    }
78}
79
80/// Detect unit tests in the calling crate, nextest, or devimint.
81///
82/// The macro evaluates `cfg!(test)` in the calling crate. Inside a dependency's
83/// function, `cfg!(test)` describes that dependency's build and cannot detect
84/// the consuming crate's unit tests. Code compiled without `cfg(test)` still
85/// needs the runtime signal `NEXTEST` or `FM_IN_DEVIMINT`.
86///
87/// ```
88/// use fedimint_core::envs::{FM_IN_DEVIMINT_ENV, is_env_var_set, is_running_in_test_env};
89///
90/// // Doctests compile without cfg(test), like normal applications.
91/// assert!(!cfg!(test));
92/// assert_eq!(
93///     is_running_in_test_env!(),
94///     is_env_var_set("NEXTEST") || is_env_var_set(FM_IN_DEVIMINT_ENV),
95/// );
96/// ```
97#[macro_export]
98macro_rules! is_running_in_test_env {
99    () => {
100        cfg!(test)
101            || $crate::envs::is_env_var_set("NEXTEST")
102            || $crate::envs::is_env_var_set($crate::envs::FM_IN_DEVIMINT_ENV)
103    };
104}
105
106/// Return the delay before polling peers again for their supported module
107/// consensus versions.
108///
109/// After a restart, the first poll can run before peers' API servers bind.
110/// Retry soon if a round fails to reach all peers, so activation need not wait
111/// for the full interval. Keep polling unreachable peers at the short interval,
112/// a few requests per minute.
113///
114/// Like [`is_running_in_test_env!`], this macro checks for unit tests in the
115/// calling crate. It evaluates its argument exactly once, including in test
116/// mode.
117///
118/// ```
119/// use std::time::Duration;
120///
121/// use fedimint_core::envs::{is_running_in_test_env, next_poll_delay};
122///
123/// assert!(!cfg!(test));
124/// let in_test_env = is_running_in_test_env!();
125/// assert_eq!(
126///     next_poll_delay!(true),
127///     Duration::from_secs(if in_test_env { 5 } else { 600 }),
128/// );
129/// assert_eq!(
130///     next_poll_delay!(false),
131///     Duration::from_secs(if in_test_env { 5 } else { 30 }),
132/// );
133/// ```
134#[macro_export]
135macro_rules! next_poll_delay {
136    ($reached_all_peers:expr $(,)?) => {{
137        let reached_all_peers = $reached_all_peers;
138        if $crate::envs::is_running_in_test_env!() {
139            ::std::time::Duration::from_secs(5)
140        } else if reached_all_peers {
141            ::std::time::Duration::from_secs(600)
142        } else {
143            ::std::time::Duration::from_secs(30)
144        }
145    }};
146}
147
148/// Use to disable automatic consensus version voting for testing and
149/// development environments
150pub fn is_automatic_consensus_version_voting_disabled() -> bool {
151    is_env_var_set(FM_WALLET_DISABLE_AUTOMATIC_CONSENSUS_VERSION_VOTING_ENV)
152}
153
154/// Get value of `FEDIMINT_BUILD_CODE_VERSION` at compile time
155#[macro_export]
156macro_rules! fedimint_build_code_version_env {
157    () => {
158        env!("FEDIMINT_BUILD_CODE_VERSION")
159    };
160}
161
162/// Env var for bitcoin RPC kind (obsolete, use FM_DEFAULT_* instead)
163pub const FM_BITCOIN_RPC_KIND_ENV: &str = "FM_BITCOIN_RPC_KIND";
164/// Env var for bitcoin URL (obsolete, use FM_DEFAULT_* instead)
165pub const FM_BITCOIN_RPC_URL_ENV: &str = "FM_BITCOIN_RPC_URL";
166/// Env var how often to poll bitcoin source
167pub const FM_BITCOIN_POLLING_INTERVAL_SECS_ENV: &str = "FM_BITCOIN_POLLING_INTERVAL_SECS";
168
169/// Env var for bitcoin RPC kind (default, used only as a default value for DKG
170/// config settings)
171pub const FM_DEFAULT_BITCOIN_RPC_KIND_ENV: &str = "FM_DEFAULT_BITCOIN_RPC_KIND";
172pub const FM_DEFAULT_BITCOIN_RPC_KIND_BAD_ENV: &str = "FM_DEFAULT_BITCOIND_RPC_KIND";
173/// Env var for bitcoin URL (default, used only as a default value for DKG
174/// config settings)
175pub const FM_DEFAULT_BITCOIN_RPC_URL_ENV: &str = "FM_DEFAULT_BITCOIN_RPC_URL";
176pub const FM_DEFAULT_BITCOIN_RPC_URL_BAD_ENV: &str = "FM_DEFAULT_BITCOIND_RPC_URL";
177
178/// Env var for bitcoin RPC kind (forced, takes priority over config settings)
179pub const FM_FORCE_BITCOIN_RPC_KIND_ENV: &str = "FM_FORCE_BITCOIN_RPC_KIND";
180pub const FM_FORCE_BITCOIN_RPC_KIND_BAD_ENV: &str = "FM_FORCE_BITCOIND_RPC_BAD_KIND";
181/// Env var for bitcoin URL (default, takes priority over config settings)
182pub const FM_FORCE_BITCOIN_RPC_URL_ENV: &str = "FM_FORCE_BITCOIN_RPC_URL";
183pub const FM_FORCE_BITCOIN_RPC_URL_BAD_ENV: &str = "FM_FORCE_BITCOIND_RPC_URL";
184
185/// Env var to override iroh connectivity, in the legacy iroh 0.35 `NodeTicket`
186/// format.
187///
188/// Comma separated key-value list
189/// (`<node_id>=<ticket>,<node_id>=<ticket>,...`). Only still read by pre-0.12
190/// binaries that link iroh 0.35; current binaries
191/// read [`FM_IROH_CONNECT_OVERRIDES_PLAIN_ENV`] instead. iroh 1.0 no longer
192/// ships the `NodeTicket` format, so the override format had to become version
193/// agnostic; rather than overload this var with two incompatible formats, the
194/// new format lives under its own name and both are emitted side by side.
195pub const FM_IROH_CONNECT_OVERRIDES_ENV: &str = "FM_IROH_CONNECT_OVERRIDES";
196
197/// Env var to override iroh connectivity, in the legacy iroh 0.35 `NodeTicket`
198/// format. Gateway counterpart of [`FM_IROH_CONNECT_OVERRIDES_ENV`].
199pub const FM_GW_IROH_CONNECT_OVERRIDES_ENV: &str = "FM_GW_IROH_CONNECT_OVERRIDES";
200
201/// Env var to override iroh connectivity, in the plain `<id>=<addr>` format.
202///
203/// Comma separated key-value list (`<node_id>=<socket_addr>,...`). The value is
204/// a single direct address; the consumer rebuilds the iroh node/endpoint
205/// address from the id and address, so the format works on both iroh 0.35 and
206/// iroh 1.0. Current binaries read this; pre-0.12 binaries read the legacy
207/// [`FM_IROH_CONNECT_OVERRIDES_ENV`] instead.
208pub const FM_IROH_CONNECT_OVERRIDES_PLAIN_ENV: &str = "FM_IROH_CONNECT_OVERRIDES_PLAIN";
209
210/// Env var to override iroh connectivity, in the plain `<id>=<addr>` format.
211/// Gateway counterpart of [`FM_IROH_CONNECT_OVERRIDES_PLAIN_ENV`].
212pub const FM_GW_IROH_CONNECT_OVERRIDES_PLAIN_ENV: &str = "FM_GW_IROH_CONNECT_OVERRIDES_PLAIN";
213
214/// Env var to override iroh DNS server
215pub const FM_IROH_DNS_ENV: &str = "FM_IROH_DNS";
216
217/// Env var to override iroh relays server
218pub const FM_IROH_RELAY_ENV: &str = "FM_IROH_RELAY";
219
220/// Env var to enable Iroh's use of DHT
221pub const FM_IROH_DHT_ENABLE_ENV: &str = "FM_IROH_DHT_ENABLE";
222
223/// Env var to disable default n0 discovery
224pub const FM_IROH_N0_DISCOVERY_ENABLE_ENV: &str = "FM_IROH_N0_DISCOVERY_ENABLE";
225
226/// Env var to disable default pkarr resolver
227pub const FM_IROH_PKARR_RESOLVER_ENABLE_ENV: &str = "FM_IROH_PKARR_RESOLVER_ENABLE";
228
229/// Env var to disable default pkarr publisher
230pub const FM_IROH_PKARR_PUBLISHER_ENABLE_ENV: &str = "FM_IROH_PKARR_PUBLISHER_ENABLE";
231
232/// Env var to disable Iroh's use of relays
233pub const FM_IROH_RELAYS_ENABLE_ENV: &str = "FM_IROH_RELAYS_ENABLE";
234
235/// Enable direct IP transports on guardian Iroh 1.x endpoints (default: true).
236///
237/// Set to `false` or `0` for relay-only guardian P2P, transitional API
238/// listeners, and guardian-origin API connections on Iroh 1.x. Does not affect
239/// legacy Iroh 0.35 connections or TLS transports.
240pub const FM_IROH_P2P_ENABLE_ENV: &str = "FM_IROH_P2P_ENABLE";
241
242/// Env var to disable all pkarr publishing (enabled by default)
243pub const FM_PKARR_ENABLE_ENV: &str = "FM_PKARR_ENABLE";
244
245/// Env var to enable pkarr DHT publishing (disabled by default)
246pub const FM_PKARR_DHT_ENABLE_ENV: &str = "FM_PKARR_DHT_ENABLE";
247
248/// Env var to disable pkarr relay publishing (enabled by default)
249pub const FM_PKARR_RELAYS_ENABLE_ENV: &str = "FM_PKARR_RELAYS_ENABLE";
250
251/// Env var to override tcp api connectivity
252///
253/// Comma separated key-value list (`peer_id=url,peer_id=url`)
254pub const FM_WS_API_CONNECT_OVERRIDES_ENV: &str = "FM_WS_API_CONNECT_OVERRIDES";
255
256pub const FM_IROH_API_SECRET_KEY_OVERRIDE_ENV: &str = "FM_IROH_API_SECRET_KEY_OVERRIDE";
257pub const FM_IROH_P2P_SECRET_KEY_OVERRIDE_ENV: &str = "FM_IROH_P2P_SECRET_KEY_OVERRIDE";
258
259/// List of json api endpoint sources to use as a source of
260/// fee rate estimation.
261///
262/// `;`-separated list of urls with part after `#`
263/// ("fragment") specifying jq filter to extract sats/vB fee rate.
264/// Eg. `https://mempool.space/api/v1/fees/recommended#.halfHourFee`
265///
266/// Note that `#` is a standalone separator and *not* parsed as a part of the
267/// Url. Which means there's no need to escape it.
268pub const FM_WALLET_FEERATE_SOURCES_ENV: &str = "FM_WALLET_FEERATE_SOURCES";
269
270/// `devimint` will set when code is running inside `devimint`
271pub const FM_IN_DEVIMINT_ENV: &str = "FM_IN_DEVIMINT";
272
273/// Configuration for the bitcoin RPC
274#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize, Encodable, Decodable)]
275pub struct BitcoinRpcConfig {
276    pub kind: String,
277    pub url: SafeUrl,
278}
279
280impl BitcoinRpcConfig {
281    pub fn get_defaults_from_env_vars() -> Result<Self, EnvParseError> {
282        Self::defaults_from_lookup(&|var: &str| env::var_os(var))
283    }
284
285    /// The defaults, reading the variables through `lookup` rather than from
286    /// the process environment.
287    fn defaults_from_lookup<L>(lookup: &L) -> Result<Self, EnvParseError>
288    where
289        L: Fn(&str) -> Option<OsString>,
290    {
291        let (_, kind) = first_env_var_set(
292            BITCOIN_RPC_KIND_ENVS,
293            FM_DEFAULT_BITCOIN_RPC_KIND_ENV,
294            lookup,
295        )?;
296        let (url_var, url) =
297            first_env_var_set(BITCOIN_RPC_URL_ENVS, FM_DEFAULT_BITCOIN_RPC_URL_ENV, lookup)?;
298
299        Ok(Self {
300            kind,
301            url: url.parse().map_err(|source| EnvParseError::InvalidUrl {
302                var: url_var,
303                source,
304            })?,
305        })
306    }
307}
308
309/// The environment variables holding the Bitcoin RPC kind, in lookup order,
310/// each paired with the variable that replaces it if it is deprecated.
311const BITCOIN_RPC_KIND_ENVS: &[(&str, Option<&str>)] = &[
312    (FM_FORCE_BITCOIN_RPC_KIND_ENV, None),
313    (FM_DEFAULT_BITCOIN_RPC_KIND_ENV, None),
314    (
315        FM_BITCOIN_RPC_KIND_ENV,
316        Some(FM_DEFAULT_BITCOIN_RPC_KIND_ENV),
317    ),
318    (
319        FM_FORCE_BITCOIN_RPC_KIND_BAD_ENV,
320        Some(FM_FORCE_BITCOIN_RPC_KIND_ENV),
321    ),
322    (
323        FM_DEFAULT_BITCOIN_RPC_KIND_BAD_ENV,
324        Some(FM_DEFAULT_BITCOIN_RPC_KIND_ENV),
325    ),
326];
327
328/// The environment variables holding the Bitcoin RPC URL, in lookup order,
329/// each paired with the variable that replaces it if it is deprecated.
330const BITCOIN_RPC_URL_ENVS: &[(&str, Option<&str>)] = &[
331    (FM_FORCE_BITCOIN_RPC_URL_ENV, None),
332    (FM_DEFAULT_BITCOIN_RPC_URL_ENV, None),
333    (FM_BITCOIN_RPC_URL_ENV, Some(FM_DEFAULT_BITCOIN_RPC_URL_ENV)),
334    (
335        FM_FORCE_BITCOIN_RPC_URL_BAD_ENV,
336        Some(FM_FORCE_BITCOIN_RPC_URL_ENV),
337    ),
338    (
339        FM_DEFAULT_BITCOIN_RPC_URL_BAD_ENV,
340        Some(FM_DEFAULT_BITCOIN_RPC_URL_ENV),
341    ),
342];
343
344/// The value of the first variable of `vars` that `lookup` finds, together
345/// with the name of that variable, warning about the deprecated ones on the
346/// way.
347///
348/// `canonical` is the variable a user should set, reported when none of them
349/// is.
350///
351/// A variable that is set but does not hold valid Unicode fails even when a
352/// lower-priority variable holds a usable value, because silently ignoring a
353/// variable the user did set would surprise them.
354fn first_env_var_set<L>(
355    vars: &[(&'static str, Option<&'static str>)],
356    canonical: &'static str,
357    lookup: &L,
358) -> Result<(&'static str, String), EnvParseError>
359where
360    L: Fn(&str) -> Option<OsString>,
361{
362    for &(var, replacement) in vars {
363        let Some(value) = lookup(var) else {
364            continue;
365        };
366        let Ok(value) = value.into_string() else {
367            return Err(EnvParseError::NotUnicode { var });
368        };
369
370        if let Some(replacement) = replacement {
371            warn!(target: LOG_CORE, "{var} is obsolete, use {replacement} instead");
372        }
373
374        return Ok((var, value));
375    }
376
377    Err(EnvParseError::NotSet { var: canonical })
378}
379
380/// Failure to build a configuration value from environment variables.
381#[derive(Debug, Error)]
382#[non_exhaustive]
383pub enum EnvParseError {
384    /// None of the accepted variables is set; `var` is the canonical one to
385    /// set.
386    #[error("Environment variable {var} (or one of its aliases) is not set")]
387    NotSet { var: &'static str },
388    /// The variable is set but its value is not valid Unicode. A lower-priority
389    /// alias is not consulted once a variable is set.
390    #[error("Environment variable {var} is not valid Unicode")]
391    NotUnicode { var: &'static str },
392    /// The variable is set but is not a valid URL.
393    #[error("Environment variable {var} is not a valid URL")]
394    InvalidUrl {
395        var: &'static str,
396        #[source]
397        source: url::ParseError,
398    },
399}
400
401pub fn parse_kv_list_from_env<K, V>(env: &str) -> BTreeMap<K, V>
402where
403    K: FromStr + cmp::Ord,
404    <K as FromStr>::Err: std::error::Error,
405    V: FromStr,
406    <V as FromStr>::Err: std::error::Error,
407{
408    let mut map = BTreeMap::new();
409    let Ok(env_value) = std::env::var(env) else {
410        return BTreeMap::new();
411    };
412    for kv in env_value.split(',') {
413        let kv = kv.trim();
414
415        if kv.is_empty() {
416            continue;
417        }
418
419        if let Some((k, v)) = kv.split_once('=') {
420            let Some(k) = K::from_str(k)
421                .inspect_err(|err| {
422                    warn!(
423                        target: LOG_CORE,
424                        err = %err.fmt_compact(),
425                        "Error parsing value"
426                    );
427                })
428                .ok()
429            else {
430                continue;
431            };
432            let Some(v) = V::from_str(v)
433                .inspect_err(|err| {
434                    warn!(
435                        target: LOG_CORE,
436                        err = %err.fmt_compact(),
437                        "Error parsing value"
438                    );
439                })
440                .ok()
441            else {
442                continue;
443            };
444
445            map.insert(k, v);
446        }
447    }
448
449    map
450}
451
452#[cfg(test)]
453mod tests;