Skip to main content

stellar_build/
networks.rs

1use sha2::{Digest, Sha256};
2use std::str::FromStr;
3
4#[derive(Default, Debug)]
5pub enum Network {
6    #[default]
7    Local,
8    Testnet,
9    Futurenet,
10    Mainnet,
11}
12
13#[derive(thiserror::Error, Debug)]
14pub enum Error {
15    #[error("Invalid STELLAR_NETWORK: {0}. Expected: local, testnet, futurenet, or mainnet.")]
16    InvalidNetwork(String),
17    #[error(
18        r#"Invalid STELLAR_PASSPHRASE: {0}. 
19            Expected: "Standalone Network ; February 2017",
20                      "Test SDF Network ; September 2015",
21                      "Test SDF Future Network ; October 2022",
22                      "Public Global Stellar Network ; September 2015" "#
23    )]
24    InvalidNetworkPassphrase(String),
25}
26
27impl FromStr for Network {
28    type Err = Error;
29
30    fn from_str(s: &str) -> Result<Self, Self::Err> {
31        match s.to_lowercase().as_str() {
32            "local" => Ok(Network::Local),
33            "testnet" => Ok(Network::Testnet),
34            "futurenet" => Ok(Network::Futurenet),
35            "mainnet" => Ok(Network::Mainnet),
36            other => Err(Error::InvalidNetwork(other.to_string())),
37        }
38    }
39}
40
41impl Network {
42    pub fn from_env() -> Self {
43        std::env::var("STELLAR_NETWORK")
44            .as_deref()
45            .unwrap_or("local")
46            .parse()
47            .unwrap_or_default()
48    }
49
50    pub fn passphrase_from_env() -> Self {
51        std::env::var("STELLAR_NETWORK_PASSPHRASE")
52            .ok()
53            .and_then(|s| Self::from_passphrase(&s).ok())
54            .unwrap_or_else(Self::from_env)
55    }
56
57    pub fn from_passphrase(passphrase: &str) -> Result<Self, Error> {
58        Ok(match passphrase {
59            "Standalone Network ; February 2017" => Network::Local,
60            "Test SDF Network ; September 2015" => Network::Testnet,
61            "Test SDF Future Network ; October 2022" => Network::Futurenet,
62            "Public Global Stellar Network ; September 2015" => Network::Mainnet,
63            other => return Err(Error::InvalidNetworkPassphrase(other.to_string())),
64        })
65    }
66
67    pub fn passphrase(&self) -> &str {
68        match self {
69            Network::Local => "Standalone Network ; February 2017",
70            Network::Testnet => "Test SDF Network ; September 2015",
71            Network::Futurenet => "Test SDF Future Network ; October 2022",
72            Network::Mainnet => "Public Global Stellar Network ; September 2015",
73        }
74    }
75
76    /// Returns the network ID as a hash
77    pub fn id(&self) -> [u8; 32] {
78        Sha256::digest(self.passphrase().as_bytes()).into()
79    }
80}