Skip to main content

cuprate_helper/
network.rs

1//! This module contains an enum representing every Monero network: mainnet, testnet, stagenet and functionality
2//! related to that.
3//!
4//! This feels out of place for the helper crate but this is needed through out Cuprate and felt too small to split
5//! into it's own crate.
6//!
7//! `#[no_std]` compatible.
8// TODO: move to types crate.
9
10use core::{
11    fmt::{Display, Formatter},
12    str::FromStr,
13};
14
15const MAINNET_NETWORK_ID: [u8; 16] = [
16    0x12, 0x30, 0xF1, 0x71, 0x61, 0x04, 0x41, 0x61, 0x17, 0x31, 0x00, 0x82, 0x16, 0xA1, 0xA1, 0x10,
17];
18const TESTNET_NETWORK_ID: [u8; 16] = [
19    0x12, 0x30, 0xF1, 0x71, 0x61, 0x04, 0x41, 0x61, 0x17, 0x31, 0x00, 0x82, 0x16, 0xA1, 0xA1, 0x11,
20];
21const STAGENET_NETWORK_ID: [u8; 16] = [
22    0x12, 0x30, 0xF1, 0x71, 0x61, 0x04, 0x41, 0x61, 0x17, 0x31, 0x00, 0x82, 0x16, 0xA1, 0xA1, 0x12,
23];
24
25/// An enum representing every Monero network.
26#[derive(Debug, Clone, Copy, Default, Ord, PartialOrd, Eq, PartialEq)]
27#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
28pub enum Network {
29    /// Mainnet
30    #[default]
31    Mainnet,
32    /// Testnet
33    Testnet,
34    /// Stagenet
35    Stagenet,
36    /// Regtest (fakechain).
37    FakeChain,
38}
39
40impl Network {
41    /// Returns the network ID for the current network.
42    pub const fn network_id(&self) -> [u8; 16] {
43        match self {
44            Self::Mainnet | Self::FakeChain => MAINNET_NETWORK_ID,
45            Self::Testnet => TESTNET_NETWORK_ID,
46            Self::Stagenet => STAGENET_NETWORK_ID,
47        }
48    }
49}
50
51#[derive(Debug, PartialEq, Eq)]
52pub struct ParseNetworkError;
53
54impl FromStr for Network {
55    type Err = ParseNetworkError;
56
57    fn from_str(s: &str) -> Result<Self, Self::Err> {
58        match s {
59            "mainnet" | "Mainnet" => Ok(Self::Mainnet),
60            "testnet" | "Testnet" => Ok(Self::Testnet),
61            "stagenet" | "Stagenet" => Ok(Self::Stagenet),
62            "fakechain" | "FakeChain" => Ok(Self::FakeChain),
63            _ => Err(ParseNetworkError),
64        }
65    }
66}
67impl Display for Network {
68    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
69        f.write_str(match self {
70            Self::Mainnet => "mainnet",
71            Self::Testnet => "testnet",
72            Self::Stagenet => "stagenet",
73            Self::FakeChain => "fakechain",
74        })
75    }
76}