Skip to main content

nectar_primitives/
network_id.rs

1//! Typed Swarm network identifier.
2//!
3//! [`NetworkId`] is mixed into the overlay address (see [`compute_overlay`])
4//! so that a single keypair derives a different overlay on each network.
5//! This is the Swarm-wide partitioning mechanism inherited from bee
6//! (see `pkg/crypto/crypto.go:45-57` for the derivation, and
7//! `pkg/swarm/swarm.go` for canonical IDs).
8//!
9//! [`compute_overlay`]: crate::compute_overlay
10
11use derive_more::{Display, From, Into};
12
13#[cfg(feature = "serde")]
14use serde::{Deserialize, Serialize};
15
16/// Swarm network identifier (u64 wire-compatible with bee).
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Display, From, Into)]
18#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
19#[cfg_attr(feature = "serde", serde(transparent))]
20#[display("{_0}")]
21pub struct NetworkId(u64);
22
23impl NetworkId {
24    /// Canonical Swarm mainnet identifier.
25    pub const MAINNET: Self = Self(1);
26
27    /// Canonical Swarm testnet identifier (Sepolia).
28    pub const TESTNET: Self = Self(10);
29
30    /// Construct from a raw `u64`.
31    #[inline]
32    pub const fn new(raw: u64) -> Self {
33        Self(raw)
34    }
35
36    /// Underlying numeric value.
37    #[inline]
38    pub const fn get(self) -> u64 {
39        self.0
40    }
41
42    /// Eight-byte little-endian representation (used in
43    /// [`compute_overlay`](crate::compute_overlay) per bee).
44    #[inline]
45    pub const fn to_le_bytes(self) -> [u8; 8] {
46        self.0.to_le_bytes()
47    }
48
49    /// Eight-byte big-endian representation (used in the BzzAddress sign-data
50    /// per bee `pkg/bzz/address.go:138-160`).
51    #[inline]
52    pub const fn to_be_bytes(self) -> [u8; 8] {
53        self.0.to_be_bytes()
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn canonical_ids() {
63        assert_eq!(NetworkId::MAINNET.get(), 1);
64        assert_eq!(NetworkId::TESTNET.get(), 10);
65    }
66
67    #[test]
68    fn display_is_decimal() {
69        assert_eq!(format!("{}", NetworkId::new(42)), "42");
70    }
71
72    #[test]
73    fn le_be_byte_distinction() {
74        let id = NetworkId::new(0x0102_0304_0506_0708);
75        assert_eq!(
76            id.to_le_bytes(),
77            [0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01]
78        );
79        assert_eq!(
80            id.to_be_bytes(),
81            [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]
82        );
83    }
84}