ant_protocol/storage/address/
scratchpad.rs1use bls::PublicKey;
10use serde::{Deserialize, Serialize};
11use std::hash::Hash;
12use xor_name::XorName;
13
14use super::AddressParseError;
15
16#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
19pub struct ScratchpadAddress(PublicKey);
20
21impl ScratchpadAddress {
22    pub fn new(owner: PublicKey) -> Self {
24        Self(owner)
25    }
26
27    pub fn xorname(&self) -> XorName {
30        XorName::from_content(&self.0.to_bytes())
31    }
32
33    pub fn owner(&self) -> &PublicKey {
35        &self.0
36    }
37
38    pub fn to_hex(&self) -> String {
40        hex::encode(self.0.to_bytes())
41    }
42
43    pub fn from_hex(hex: &str) -> Result<Self, AddressParseError> {
45        let owner = PublicKey::from_hex(hex)?;
46        Ok(Self(owner))
47    }
48}
49
50impl std::fmt::Display for ScratchpadAddress {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        write!(f, "{}", &self.to_hex())
53    }
54}
55
56impl std::fmt::Debug for ScratchpadAddress {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        write!(f, "{}", &self.to_hex())
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65    use bls::SecretKey;
66
67    #[test]
68    fn test_scratchpad_hex_conversion() {
69        let owner = SecretKey::random().public_key();
70        let addr = ScratchpadAddress::new(owner);
71        let hex = addr.to_hex();
72        let addr2 = ScratchpadAddress::from_hex(&hex).unwrap();
73
74        assert_eq!(addr, addr2);
75
76        let bad_hex = format!("{hex}0");
77        let err = ScratchpadAddress::from_hex(&bad_hex);
78        assert!(err.is_err());
79    }
80}