alephium-web3 2.0.7

A Rust library to interact with the Alephium platform
Documentation
// Copyright 2018 - 2022 The Alephium Authors
// This file is part of the alephium project.

use crate::constants::{PUBLIC_KEY_HASH_SIZE, TOTAL_NUMBER_OF_GROUPS};
use crate::error::{Error, Result};
use crate::utils::bs58;
use blake2::{Blake2b512, Digest};
use serde::{Deserialize, Serialize};

/// Address types in Alephium
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum AddressType {
    /// Pay to Public Key Hash
    P2PKH = 0x00,
    /// Pay to Multi-sig Public Key Hash
    P2MPKH = 0x01,
    /// Pay to Script Hash
    P2SH = 0x02,
    /// Pay to Contract
    P2C = 0x03,
    /// Pay to Public Key
    P2PK = 0x04,
    /// Pay to Hashed Multi-sig Public Key
    P2HMPK = 0x05,
}

impl AddressType {
    pub fn from_u8(value: u8) -> Result<Self> {
        match value {
            0x00 => Ok(AddressType::P2PKH),
            0x01 => Ok(AddressType::P2MPKH),
            0x02 => Ok(AddressType::P2SH),
            0x03 => Ok(AddressType::P2C),
            0x04 => Ok(AddressType::P2PK),
            0x05 => Ok(AddressType::P2HMPK),
            _ => Err(Error::InvalidAddress(format!("Invalid address type: {}", value))),
        }
    }
}

/// Alephium address
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Address {
    address_type: AddressType,
    data: Vec<u8>,
    group_index: Option<u8>,
}

impl Address {
    /// Create a new address from components
    pub fn new(address_type: AddressType, data: Vec<u8>, group_index: Option<u8>) -> Result<Self> {
        if let Some(group) = group_index {
            validate_group_index(group)?;
        }
        Ok(Self {
            address_type,
            data,
            group_index,
        })
    }

    /// Create address from base58 string
    pub fn from_base58(address: &str) -> Result<Self> {
        decode_and_validate_address(address)
    }

    /// Convert address to base58 string
    pub fn to_base58(&self) -> String {
        bytes_to_address(&self.to_bytes(), self.group_index)
    }

    /// Get the address type
    pub fn address_type(&self) -> AddressType {
        self.address_type
    }

    /// Get the group index
    pub fn group_index(&self) -> Option<u8> {
        self.group_index
    }

    /// Convert address to bytes
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = vec![self.address_type as u8];
        bytes.extend_from_slice(&self.data);
        bytes
    }

    /// Create P2PKH address from public key hash
    pub fn p2pkh(public_key_hash: &[u8]) -> Result<Self> {
        if public_key_hash.len() != PUBLIC_KEY_HASH_SIZE {
            return Err(Error::InvalidAddress(format!(
                "Invalid public key hash size: {}",
                public_key_hash.len()
            )));
        }
        Self::new(AddressType::P2PKH, public_key_hash.to_vec(), None)
    }

    /// Create P2C (contract) address from contract ID
    pub fn p2c(contract_id: &[u8]) -> Result<Self> {
        if contract_id.len() != 32 {
            return Err(Error::InvalidAddress(format!(
                "Invalid contract ID size: {}",
                contract_id.len()
            )));
        }
        Self::new(AddressType::P2C, contract_id.to_vec(), None)
    }

    /// Check if address has explicit group index
    pub fn has_explicit_group_index(&self) -> bool {
        self.group_index.is_some()
    }
}

/// Validate a group index
pub fn validate_group_index(group: u8) -> Result<()> {
    if group >= TOTAL_NUMBER_OF_GROUPS {
        return Err(Error::InvalidGroupIndex(group));
    }
    Ok(())
}

/// Check if address string has explicit group index
pub fn has_explicit_group_index(address: &str) -> bool {
    if address.len() >= 2 {
        let last = address.chars().nth(address.len() - 2);
        last == Some('@')
    } else {
        false
    }
}

/// Parse group index from character
fn parse_group_index(c: char) -> Result<u8> {
    if !c.is_ascii_digit() {
        return Err(Error::InvalidAddress(format!("Invalid group index: {}", c)));
    }
    let index = c as u8 - b'0';
    validate_group_index(index)?;
    Ok(index)
}

/// Convert address string to bytes
pub fn address_to_bytes(address: &str) -> Result<Vec<u8>> {
    if has_explicit_group_index(address) {
        let _group_index = parse_group_index(address.chars().last().unwrap())?;
        let address_without_suffix = &address[0..address.len() - 2];
        bs58::base58_to_bytes(address_without_suffix)
    } else {
        bs58::base58_to_bytes(address)
    }
}

/// Convert bytes to address string
pub fn bytes_to_address(bytes: &[u8], group_index: Option<u8>) -> String {
    let encoded = bs58::bytes_to_base58(bytes);
    if let Some(index) = group_index {
        format!("{}@{}", encoded, index)
    } else {
        encoded
    }
}

/// Decode and validate an address
fn decode_and_validate_address(address: &str) -> Result<Address> {
    let decoded = address_to_bytes(address)?;
    
    if decoded.is_empty() {
        return Err(Error::InvalidAddress("Address is empty".to_string()));
    }

    let address_type = AddressType::from_u8(decoded[0])?;
    let group_index = if has_explicit_group_index(address) {
        Some(parse_group_index(address.chars().last().unwrap())?)
    } else {
        None
    };

    match address_type {
        AddressType::P2PKH | AddressType::P2SH | AddressType::P2C => {
            if decoded.len() == 33 {
                Address::new(address_type, decoded[1..].to_vec(), group_index)
            } else {
                Err(Error::InvalidAddress(format!("Invalid address length: {}", decoded.len())))
            }
        }
        AddressType::P2MPKH | AddressType::P2PK | AddressType::P2HMPK => {
            // Simplified validation for now
            Address::new(address_type, decoded[1..].to_vec(), group_index)
        }
    }
}

/// Validate an address string
pub fn validate_address(address: &str) -> Result<()> {
    decode_and_validate_address(address)?;
    Ok(())
}

/// Check if an address string is valid
pub fn is_valid_address(address: &str) -> bool {
    validate_address(address).is_ok()
}

/// Hash public key to get public key hash
pub fn hash_public_key(public_key: &[u8]) -> Vec<u8> {
    let mut hasher = Blake2b512::new();
    hasher.update(public_key);
    let result = hasher.finalize();
    result[..PUBLIC_KEY_HASH_SIZE].to_vec()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_address_type() {
        assert_eq!(AddressType::from_u8(0x00).unwrap(), AddressType::P2PKH);
        assert_eq!(AddressType::from_u8(0x03).unwrap(), AddressType::P2C);
        assert!(AddressType::from_u8(0xFF).is_err());
    }

    #[test]
    fn test_validate_group_index() {
        assert!(validate_group_index(0).is_ok());
        assert!(validate_group_index(3).is_ok());
        assert!(validate_group_index(4).is_err());
        assert!(validate_group_index(255).is_err());
    }

    #[test]
    fn test_has_explicit_group_index() {
        assert!(has_explicit_group_index("1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH@0"));
        assert!(!has_explicit_group_index("1DrDyTr9RpRsQnDnXo2YRiPzPW4ooHX5LLoqXrqfMrpQH"));
    }

    #[test]
    fn test_address_round_trip() {
        let address_type = AddressType::P2PKH;
        let data = vec![1u8; 32];
        let group_index = Some(2);
        
        let address = Address::new(address_type, data.clone(), group_index).unwrap();
        let base58 = address.to_base58();
        let decoded = Address::from_base58(&base58).unwrap();
        
        assert_eq!(decoded.address_type(), address_type);
        assert_eq!(decoded.data, data);
        assert_eq!(decoded.group_index(), group_index);
    }
}