use crate::error::{Error, Result};
use bls::PublicKey;
use serde::{Deserialize, Serialize};
use std::{
fmt::{Debug, Display},
hash::Hash,
};
use xor_name::XorName;
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
pub struct ScratchpadAddress {
pub(crate) owner: PublicKey,
}
impl Display for ScratchpadAddress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "({:?})", &self.to_hex()[0..6])
}
}
impl Debug for ScratchpadAddress {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"ScratchpadAddress({}) {{ owner: {:?} }}",
&self.to_hex()[0..6],
self.owner
)
}
}
impl ScratchpadAddress {
pub fn new(owner: PublicKey) -> Self {
Self { owner }
}
pub fn xorname(&self) -> XorName {
XorName::from_content(&self.owner.to_bytes())
}
pub fn to_hex(&self) -> String {
hex::encode(self.owner.to_bytes())
}
pub fn from_hex(hex: &str) -> Result<Self> {
let owner = PublicKey::from_hex(hex).map_err(|_| Error::ScratchpadHexDeserializeFailed)?;
Ok(Self { owner })
}
pub fn owner(&self) -> &PublicKey {
&self.owner
}
}
#[cfg(test)]
mod tests {
use super::*;
use bls::SecretKey;
#[test]
fn test_scratchpad_hex_conversion() {
let owner = SecretKey::random().public_key();
let addr = ScratchpadAddress::new(owner);
let hex = addr.to_hex();
let addr2 = ScratchpadAddress::from_hex(&hex).unwrap();
assert_eq!(addr, addr2);
let bad_hex = format!("{hex}0");
let err = ScratchpadAddress::from_hex(&bad_hex);
assert_eq!(err, Err(Error::ScratchpadHexDeserializeFailed));
}
}