moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Resolved network endpoints + chain identity.
//!
//! `NetworkConfig` is the canonical "endpoints + chain kind" bundle the
//! session pipeline needs to open node + indexer clients and stamp
//! transactions with the correct `NetworkId`. Hosts (CLI, Flutter SDK,
//! integration tests) populate the struct from whatever config layer
//! they have — the session module itself doesn't know about TOML files
//! or platform-specific config search paths.

use crate::abstractions::NetworkId;

/// Resolved network endpoints + chain identity. Built by callers from
/// their host-specific config layer; consumers use it to open node +
/// indexer clients and to stamp transactions with the right
/// `NetworkId`.
#[derive(Debug, Clone)]
pub struct NetworkConfig {
    pub name: String,
    pub indexer_http: String,
    pub node_ws: String,
    /// Default LOCAL proof-server URL for the network — typically
    /// `http://127.0.0.1:6300` (the dev-loop harness server). Used
    /// when the user picks `LocalProofServer` as their proving
    /// backend without overriding the URL.
    pub proof_server_url: Option<String>,
    /// Official REMOTE proof-server URL hosted by the network
    /// operator. `None` for `localdev` (no public remote). Used
    /// when the user picks `RemoteOfficial` as their proving
    /// backend.
    pub proof_server_remote_url: Option<String>,
    pub network_id: NetworkId,
    pub chain_kind: String,
}

impl NetworkConfig {
    /// `true` iff this network is the production main-net (real funds).
    ///
    /// Returns `false` for `preprod` — preprod is the staging promotion
    /// environment but matches the upstream wallet's policy of treating
    /// it as just another network identifier (see
    /// `midnight-wallet/packages/abstractions/src/NetworkId.ts`). The
    /// CLI layer surfaces an extra confirmation prompt for mainnet only.
    #[must_use]
    pub fn is_mainnet(&self) -> bool {
        self.chain_kind.as_str() == "mainnet"
    }

    /// `true` iff this network carries real-fund-class state — mainnet
    /// or preprod (the official staging promotion environment). Hosts
    /// use this to default to `Finalized` submission and to gate any
    /// non-reversible automation with extra confirmation.
    #[must_use]
    pub fn is_fund_class(&self) -> bool {
        matches!(self.chain_kind.as_str(), "mainnet" | "preprod")
    }
}

/// Environment variable holding a Blockfrost project id.
/// `BLOCKFROST_PROJECT_ID_<NETWORK>` (e.g. `BLOCKFROST_PROJECT_ID_MAINNET`)
/// overrides it for one network, since Blockfrost issues one project per
/// network. Read from the environment rather than a config file so the
/// id never lands in a committed `moonproof.toml`.
pub const BLOCKFROST_PROJECT_ID_ENV: &str = "BLOCKFROST_PROJECT_ID";

const PROJECT_ID: &str = "project_id";

fn is_blockfrost(endpoint: &str) -> bool {
    url::Url::parse(endpoint)
        .is_ok_and(|u| u.host_str().is_some_and(|h| h.ends_with(".blockfrost.io")))
}

fn has_project_id(endpoint: &str) -> bool {
    url::Url::parse(endpoint).is_ok_and(|u| u.query_pairs().any(|(k, _)| k == PROJECT_ID))
}

impl NetworkConfig {
    /// Whether an endpoint is Blockfrost's and still lacks the project
    /// id Blockfrost requires on every request.
    #[must_use]
    pub fn needs_project_id(&self) -> bool {
        [&self.indexer_http, &self.node_ws]
            .into_iter()
            .any(|e| is_blockfrost(e) && !has_project_id(e))
    }

    /// The config with `project_id` on every Blockfrost endpoint, as the
    /// query parameter Blockfrost accepts on HTTP and WebSocket alike.
    pub fn with_project_id(mut self, project_id: &str) -> anyhow::Result<Self> {
        for endpoint in [&mut self.indexer_http, &mut self.node_ws] {
            if is_blockfrost(endpoint) && !has_project_id(endpoint) {
                let mut url = url::Url::parse(endpoint)?;
                url.query_pairs_mut().append_pair(PROJECT_ID, project_id);
                *endpoint = url.to_string();
            }
        }
        Ok(self)
    }

    /// Supply the Blockfrost project id from the environment where the
    /// endpoints need one; see [`BLOCKFROST_PROJECT_ID_ENV`].
    pub fn authenticated_from_env(self) -> anyhow::Result<Self> {
        self.authenticated_with(|name| std::env::var(name).ok())
    }

    fn authenticated_with(self, lookup: impl Fn(&str) -> Option<String>) -> anyhow::Result<Self> {
        if !self.needs_project_id() {
            return Ok(self);
        }
        let per_network = format!(
            "{BLOCKFROST_PROJECT_ID_ENV}_{}",
            self.name.to_ascii_uppercase().replace('-', "_")
        );
        let Some(project_id) = lookup(&per_network).or_else(|| lookup(BLOCKFROST_PROJECT_ID_ENV))
        else {
            anyhow::bail!(
                "network `{}` is served by Blockfrost, which needs a project id: set \
                 {per_network} or {BLOCKFROST_PROJECT_ID_ENV} to a Blockfrost project id for this \
                 network (https://blockfrost.io)",
                self.name
            );
        };
        self.with_project_id(&project_id)
    }
}

/// Map a `chain_kind` (the canonical chain family label) to the
/// [`NetworkId`] the wallet facade encodes into transactions.
#[must_use]
pub fn network_id_for_chain_kind(chain_kind: &str, fallback: &str) -> NetworkId {
    match chain_kind {
        "mainnet" => NetworkId::MainNet,
        "testnet" => NetworkId::TestNet,
        "devnet" => NetworkId::DevNet,
        "qanet" => NetworkId::QaNet,
        "preview" => NetworkId::Preview,
        "preprod" => NetworkId::PreProd,
        "localdev" | "undeployed" => NetworkId::Undeployed,
        other => NetworkId::from_label(if other.is_empty() { fallback } else { other }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn blockfrost_endpoints_take_the_project_id_from_the_environment() {
        let preprod = crate::session::presets::preprod();
        assert!(preprod.needs_project_id());
        let env = |name: &str| {
            (name == "BLOCKFROST_PROJECT_ID_PREPROD").then(|| "nightpreprodX".to_owned())
        };
        let authed = preprod.authenticated_with(env).unwrap();
        assert!(!authed.needs_project_id());
        assert!(authed.indexer_http.ends_with("?project_id=nightpreprodX"));
        assert!(authed.node_ws.ends_with("?project_id=nightpreprodX"));
    }

    #[test]
    fn a_missing_project_id_names_the_variables_to_set() {
        let err = crate::session::presets::mainnet()
            .authenticated_with(|_| None)
            .unwrap_err()
            .to_string();
        assert!(err.contains("BLOCKFROST_PROJECT_ID_MAINNET"), "{err}");
    }

    #[test]
    fn self_hosted_endpoints_need_nothing() {
        let local = crate::session::presets::localdev();
        assert!(!local.needs_project_id());
        assert_eq!(
            local
                .clone()
                .authenticated_with(|_| None)
                .unwrap()
                .indexer_http,
            local.indexer_http
        );
    }

    #[test]
    fn network_id_mapping_covers_known_chain_kinds() {
        assert!(matches!(
            network_id_for_chain_kind("mainnet", "n"),
            NetworkId::MainNet
        ));
        assert!(matches!(
            network_id_for_chain_kind("testnet", "n"),
            NetworkId::TestNet
        ));
        assert!(matches!(
            network_id_for_chain_kind("localdev", "n"),
            NetworkId::Undeployed
        ));
        assert!(matches!(
            network_id_for_chain_kind("undeployed", "n"),
            NetworkId::Undeployed
        ));
        match network_id_for_chain_kind("acme-stage", "n") {
            NetworkId::Custom(s) => assert_eq!(s, "acme-stage"),
            other => panic!("expected Custom, got {other:?}"),
        }
    }

    #[test]
    fn is_mainnet_flags_only_mainnet() {
        let mn = NetworkConfig {
            name: "n".to_owned(),
            indexer_http: String::new(),
            node_ws: String::new(),
            proof_server_url: None,
            proof_server_remote_url: None,
            network_id: NetworkId::MainNet,
            chain_kind: "mainnet".to_owned(),
        };
        assert!(mn.is_mainnet());
        // preprod is the staging promotion environment but the wallet
        // SDK treats it as just another network — only `mainnet` carries
        // the strict CLI-side confirmation.
        let pp = NetworkConfig {
            chain_kind: "preprod".to_owned(),
            ..mn.clone()
        };
        assert!(!pp.is_mainnet());
        assert!(pp.is_fund_class());
        let local = NetworkConfig {
            chain_kind: "localdev".to_owned(),
            ..mn
        };
        assert!(!local.is_mainnet());
        assert!(!local.is_fund_class());
    }

    #[test]
    fn network_config_roundtrips_proof_server_url() {
        let cfg = NetworkConfig {
            name: "n".to_owned(),
            indexer_http: String::new(),
            node_ws: String::new(),
            proof_server_url: Some("http://127.0.0.1:6300".to_owned()),
            proof_server_remote_url: None,
            network_id: NetworkId::Undeployed,
            chain_kind: "localdev".to_owned(),
        };
        assert_eq!(
            cfg.proof_server_url.as_deref(),
            Some("http://127.0.0.1:6300")
        );
    }
}