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, Debug)]
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
56#[cfg(test)]
57mod tests {
58 use super::*;
59 use bls::SecretKey;
60
61 #[test]
62 fn test_scratchpad_hex_conversion() {
63 let owner = SecretKey::random().public_key();
64 let addr = ScratchpadAddress::new(owner);
65 let hex = addr.to_hex();
66 let addr2 = ScratchpadAddress::from_hex(&hex).unwrap();
67
68 assert_eq!(addr, addr2);
69
70 let bad_hex = format!("{hex}0");
71 let err = ScratchpadAddress::from_hex(&bad_hex);
72 assert!(err.is_err());
73 }
74}