Skip to main content

chaincraft_rust/crypto/
address.rs

1//! Address generation and validation
2
3use crate::crypto::{hash::keccak256, PublicKey};
4use serde::{Deserialize, Serialize};
5
6/// Blockchain address
7#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
8pub struct Address(String);
9
10impl Address {
11    /// Generate Ethereum-style address from public key
12    pub fn from_public_key(public_key: &PublicKey) -> Self {
13        let hash = keccak256(&public_key.as_bytes());
14        let address = format!("0x{}", hex::encode(&hash[12..]));
15        Self(address)
16    }
17
18    /// Create from hex string
19    pub fn from_hex(hex: &str) -> Option<Self> {
20        if hex.len() == 42 && hex.starts_with("0x") {
21            Some(Self(hex.to_string()))
22        } else {
23            None
24        }
25    }
26
27    /// Get as string
28    pub fn as_str(&self) -> &str {
29        &self.0
30    }
31
32    /// Get as bytes (without 0x prefix)
33    pub fn as_bytes(&self) -> Vec<u8> {
34        hex::decode(&self.0[2..]).unwrap_or_default()
35    }
36}
37
38impl std::fmt::Display for Address {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        write!(f, "{}", self.0)
41    }
42}
43
44impl From<String> for Address {
45    fn from(s: String) -> Self {
46        Self(s)
47    }
48}
49
50impl From<&str> for Address {
51    fn from(s: &str) -> Self {
52        Self(s.to_string())
53    }
54}