ant_protocol/storage/address/
pointer_address.rs

1use bls::PublicKey;
2use serde::{Deserialize, Serialize};
3use xor_name::XorName;
4
5use super::AddressParseError;
6
7/// Address of a [`crate::storage::pointer::Pointer`]
8/// It is derived from the owner's public key
9#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, Debug)]
10pub struct PointerAddress(PublicKey);
11
12impl PointerAddress {
13    /// Create a new [`PointerAddress`]
14    pub fn new(owner: PublicKey) -> Self {
15        Self(owner)
16    }
17
18    /// Return the network name of the scratchpad.
19    /// This is used to locate the scratchpad on the network.
20    pub fn xorname(&self) -> XorName {
21        XorName::from_content(&self.0.to_bytes())
22    }
23
24    /// Return the owner.
25    pub fn owner(&self) -> &PublicKey {
26        &self.0
27    }
28
29    /// Serialize this [`PointerAddress`] into a hex-encoded string.
30    pub fn to_hex(&self) -> String {
31        hex::encode(self.0.to_bytes())
32    }
33
34    /// Parse a hex-encoded string into a [`PointerAddress`].
35    pub fn from_hex(hex: &str) -> Result<Self, AddressParseError> {
36        let owner = PublicKey::from_hex(hex)?;
37        Ok(Self(owner))
38    }
39}
40
41impl std::fmt::Display for PointerAddress {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        write!(f, "{}", &self.to_hex())
44    }
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn test_pointer_serialization() {
53        let key = bls::SecretKey::random();
54        let pointer_address = PointerAddress::new(key.public_key());
55        let serialized = pointer_address.to_hex();
56        let deserialized = PointerAddress::from_hex(&serialized).unwrap();
57        assert_eq!(pointer_address, deserialized);
58    }
59}