Skip to main content

alephium_web3/address/
mod.rs

1// Copyright 2018 - 2022 The Alephium Authors
2// This file is part of the alephium project.
3
4use crate::constants::{PUBLIC_KEY_HASH_SIZE, TOTAL_NUMBER_OF_GROUPS};
5use crate::error::{Error, Result};
6use crate::utils::bs58;
7use blake2::{Blake2b512, Digest};
8use serde::{Deserialize, Serialize};
9
10/// Address types in Alephium
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[repr(u8)]
13pub enum AddressType {
14    /// Pay to Public Key Hash
15    P2PKH = 0x00,
16    /// Pay to Multi-sig Public Key Hash
17    P2MPKH = 0x01,
18    /// Pay to Script Hash
19    P2SH = 0x02,
20    /// Pay to Contract
21    P2C = 0x03,
22    /// Pay to Public Key
23    P2PK = 0x04,
24    /// Pay to Hashed Multi-sig Public Key
25    P2HMPK = 0x05,
26}
27
28impl AddressType {
29    pub fn from_u8(value: u8) -> Result<Self> {
30        match value {
31            0x00 => Ok(AddressType::P2PKH),
32            0x01 => Ok(AddressType::P2MPKH),
33            0x02 => Ok(AddressType::P2SH),
34            0x03 => Ok(AddressType::P2C),
35            0x04 => Ok(AddressType::P2PK),
36            0x05 => Ok(AddressType::P2HMPK),
37            _ => Err(Error::InvalidAddress(format!("Invalid address type: {}", value))),
38        }
39    }
40}
41
42/// Alephium address
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Address {
45    address_type: AddressType,
46    data: Vec<u8>,
47    group_index: Option<u8>,
48}
49
50impl Address {
51    /// Create a new address from components
52    pub fn new(address_type: AddressType, data: Vec<u8>, group_index: Option<u8>) -> Result<Self> {
53        if let Some(group) = group_index {
54            validate_group_index(group)?;
55        }
56        Ok(Self {
57            address_type,
58            data,
59            group_index,
60        })
61    }
62
63    /// Create address from base58 string
64    pub fn from_base58(address: &str) -> Result<Self> {
65        decode_and_validate_address(address)
66    }
67
68    /// Convert address to base58 string
69    pub fn to_base58(&self) -> String {
70        bytes_to_address(&self.to_bytes(), self.group_index)
71    }
72
73    /// Get the address type
74    pub fn address_type(&self) -> AddressType {
75        self.address_type
76    }
77
78    /// Get the group index
79    pub fn group_index(&self) -> Option<u8> {
80        self.group_index
81    }
82
83    /// Convert address to bytes
84    pub fn to_bytes(&self) -> Vec<u8> {
85        let mut bytes = vec![self.address_type as u8];
86        bytes.extend_from_slice(&self.data);
87        bytes
88    }
89
90    /// Create P2PKH address from public key hash
91    pub fn p2pkh(public_key_hash: &[u8]) -> Result<Self> {
92        if public_key_hash.len() != PUBLIC_KEY_HASH_SIZE {
93            return Err(Error::InvalidAddress(format!(
94                "Invalid public key hash size: {}",
95                public_key_hash.len()
96            )));
97        }
98        Self::new(AddressType::P2PKH, public_key_hash.to_vec(), None)
99    }
100
101    /// Create P2C (contract) address from contract ID
102    pub fn p2c(contract_id: &[u8]) -> Result<Self> {
103        if contract_id.len() != 32 {
104            return Err(Error::InvalidAddress(format!(
105                "Invalid contract ID size: {}",
106                contract_id.len()
107            )));
108        }
109        Self::new(AddressType::P2C, contract_id.to_vec(), None)
110    }
111
112    /// Check if address has explicit group index
113    pub fn has_explicit_group_index(&self) -> bool {
114        self.group_index.is_some()
115    }
116}
117
118/// Validate a group index
119pub fn validate_group_index(group: u8) -> Result<()> {
120    if group >= TOTAL_NUMBER_OF_GROUPS {
121        return Err(Error::InvalidGroupIndex(group));
122    }
123    Ok(())
124}
125
126/// Check if address string has explicit group index
127pub fn has_explicit_group_index(address: &str) -> bool {
128    if address.len() >= 2 {
129        let last = address.chars().nth(address.len() - 2);
130        last == Some('@')
131    } else {
132        false
133    }
134}
135
136/// Parse group index from character
137fn parse_group_index(c: char) -> Result<u8> {
138    if !c.is_ascii_digit() {
139        return Err(Error::InvalidAddress(format!("Invalid group index: {}", c)));
140    }
141    let index = c as u8 - b'0';
142    validate_group_index(index)?;
143    Ok(index)
144}
145
146/// Convert address string to bytes
147pub fn address_to_bytes(address: &str) -> Result<Vec<u8>> {
148    if has_explicit_group_index(address) {
149        let _group_index = parse_group_index(address.chars().last().unwrap())?;
150        let address_without_suffix = &address[0..address.len() - 2];
151        bs58::base58_to_bytes(address_without_suffix)
152    } else {
153        bs58::base58_to_bytes(address)
154    }
155}
156
157/// Convert bytes to address string
158pub fn bytes_to_address(bytes: &[u8], group_index: Option<u8>) -> String {
159    let encoded = bs58::bytes_to_base58(bytes);
160    if let Some(index) = group_index {
161        format!("{}@{}", encoded, index)
162    } else {
163        encoded
164    }
165}
166
167/// Decode and validate an address
168fn decode_and_validate_address(address: &str) -> Result<Address> {
169    let decoded = address_to_bytes(address)?;
170    
171    if decoded.is_empty() {
172        return Err(Error::InvalidAddress("Address is empty".to_string()));
173    }
174
175    let address_type = AddressType::from_u8(decoded[0])?;
176    let group_index = if has_explicit_group_index(address) {
177        Some(parse_group_index(address.chars().last().unwrap())?)
178    } else {
179        None
180    };
181
182    match address_type {
183        AddressType::P2PKH | AddressType::P2SH | AddressType::P2C => {
184            if decoded.len() == 33 {
185                Address::new(address_type, decoded[1..].to_vec(), group_index)
186            } else {
187                Err(Error::InvalidAddress(format!("Invalid address length: {}", decoded.len())))
188            }
189        }
190        AddressType::P2MPKH | AddressType::P2PK | AddressType::P2HMPK => {
191            // Simplified validation for now
192            Address::new(address_type, decoded[1..].to_vec(), group_index)
193        }
194    }
195}
196
197/// Validate an address string
198pub fn validate_address(address: &str) -> Result<()> {
199    decode_and_validate_address(address)?;
200    Ok(())
201}
202
203/// Check if an address string is valid
204pub fn is_valid_address(address: &str) -> bool {
205    validate_address(address).is_ok()
206}
207
208/// Hash public key to get public key hash
209pub fn hash_public_key(public_key: &[u8]) -> Vec<u8> {
210    let mut hasher = Blake2b512::new();
211    hasher.update(public_key);
212    let result = hasher.finalize();
213    result[..PUBLIC_KEY_HASH_SIZE].to_vec()
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn test_address_type() {
222        assert_eq!(AddressType::from_u8(0x00).unwrap(), AddressType::P2PKH);
223        assert_eq!(AddressType::from_u8(0x03).unwrap(), AddressType::P2C);
224        assert!(AddressType::from_u8(0xFF).is_err());
225    }
226
227    #[test]
228    fn test_validate_group_index() {
229        assert!(validate_group_index(0).is_ok());
230        assert!(validate_group_index(3).is_ok());
231        assert!(validate_group_index(4).is_err());
232        assert!(validate_group_index(255).is_err());
233    }
234
235    #[test]
236    fn test_has_explicit_group_index() {
237        assert!(has_explicit_group_index("1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH@0"));
238        assert!(!has_explicit_group_index("1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH"));
239    }
240
241    #[test]
242    fn test_address_round_trip() {
243        let address_type = AddressType::P2PKH;
244        let data = vec![1u8; 32];
245        let group_index = Some(2);
246        
247        let address = Address::new(address_type, data.clone(), group_index).unwrap();
248        let base58 = address.to_base58();
249        let decoded = Address::from_base58(&base58).unwrap();
250        
251        assert_eq!(decoded.address_type(), address_type);
252        assert_eq!(decoded.data, data);
253        assert_eq!(decoded.group_index(), group_index);
254    }
255}