ant_protocol/storage/address/
scratchpad.rs

1// Copyright 2024 MaidSafe.net limited.
2//
3// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
4// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
5// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
6// KIND, either express or implied. Please review the Licences for the specific language governing
7// permissions and limitations relating to use of the SAFE Network Software.
8
9use bls::PublicKey;
10use serde::{Deserialize, Serialize};
11use std::hash::Hash;
12use xor_name::XorName;
13
14use super::AddressParseError;
15
16/// Address of a [`crate::storage::scratchpad::Scratchpad`]
17/// It is derived from the owner's public key
18#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
19pub struct ScratchpadAddress(PublicKey);
20
21impl ScratchpadAddress {
22    /// Create a new [`ScratchpadAddress`]
23    pub fn new(owner: PublicKey) -> Self {
24        Self(owner)
25    }
26
27    /// Return the network name of the scratchpad.
28    /// This is used to locate the scratchpad on the network.
29    pub fn xorname(&self) -> XorName {
30        XorName::from_content(&self.0.to_bytes())
31    }
32
33    /// Return the owner.
34    pub fn owner(&self) -> &PublicKey {
35        &self.0
36    }
37
38    /// Serialize this [`ScratchpadAddress`] into a hex-encoded string.
39    pub fn to_hex(&self) -> String {
40        hex::encode(self.0.to_bytes())
41    }
42
43    /// Parse a hex-encoded string into a [`ScratchpadAddress`].
44    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}