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}
37
38impl Network {
39    /// Returns the network ID for the current network.
40    pub const fn network_id(&self) -> [u8; 16] {
41        match self {
42            Self::Mainnet => MAINNET_NETWORK_ID,
43            Self::Testnet => TESTNET_NETWORK_ID,
44            Self::Stagenet => STAGENET_NETWORK_ID,
45        }
46    }
47}
48
49#[derive(Debug, PartialEq, Eq)]
50pub struct ParseNetworkError;
51
52impl FromStr for Network {
53    type Err = ParseNetworkError;
54
55    fn from_str(s: &str) -> Result<Self, Self::Err> {
56        match s {
57            "mainnet" | "Mainnet" => Ok(Self::Mainnet),
58            "testnet" | "Testnet" => Ok(Self::Testnet),
59            "stagenet" | "Stagenet" => Ok(Self::Stagenet),
60            _ => Err(ParseNetworkError),
61        }
62    }
63}
64impl Display for Network {
65    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
66        f.write_str(match self {
67            Self::Mainnet => "mainnet",
68            Self::Testnet => "testnet",
69            Self::Stagenet => "stagenet",
70        })
71    }
72}