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::address::Address;
use crate::error::{Error, Result};
use crate::signer::{KeyType, PrivateKey, PublicKey};
use bip39::{Language, Mnemonic};
use hmac::Hmac;
use pbkdf2::pbkdf2;
use sha2::Sha512;

/// HD wallet for hierarchical deterministic key derivation
#[derive(Clone)]
pub struct HDWallet {
    mnemonic: Mnemonic,
    seed: Vec<u8>,
}

impl HDWallet {
    /// Generate a new HD wallet with a random mnemonic
    pub fn generate(word_count: WordCount) -> Result<Self> {
        let word_count_num = match word_count {
            WordCount::Words12 => 12,
            WordCount::Words15 => 15,
            WordCount::Words18 => 18,
            WordCount::Words21 => 21,
            WordCount::Words24 => 24,
        };

        let mnemonic = Mnemonic::generate_in(Language::English, word_count_num)
            .map_err(|e| Error::InvalidKey(format!("Failed to generate mnemonic: {}", e)))?;

        Self::from_mnemonic(mnemonic, "")
    }

    /// Create HD wallet from mnemonic phrase
    pub fn from_phrase(phrase: &str, passphrase: &str) -> Result<Self> {
        let mnemonic = Mnemonic::parse_in(Language::English, phrase)
            .map_err(|e| Error::InvalidKey(format!("Invalid mnemonic: {}", e)))?;

        Self::from_mnemonic(mnemonic, passphrase)
    }

    /// Create HD wallet from mnemonic
    fn from_mnemonic(mnemonic: Mnemonic, passphrase: &str) -> Result<Self> {
        let seed_bytes = mnemonic.to_seed(passphrase);

        Ok(Self {
            mnemonic,
            seed: seed_bytes.to_vec(),
        })
    }

    /// Get the mnemonic phrase
    pub fn mnemonic_phrase(&self) -> String {
        self.mnemonic.words().collect::<Vec<&str>>().join(" ")
    }

    /// Get seed bytes
    pub fn seed(&self) -> &[u8] {
        &self.seed
    }

    /// Derive a private key at the given path
    /// Path format: m/44'/1234'/account'/change/index
    /// - 44' is BIP44 purpose
    /// - 1234' is Alephium coin type (example)
    /// - account' is the account index
    /// - change is 0 for external, 1 for internal
    /// - index is the address index
    pub fn derive_private_key(&self, path: &DerivationPath, key_type: KeyType) -> Result<PrivateKey> {
        // Simplified derivation using PBKDF2
        // In production, would use proper BIP32 derivation
        let path_str = path.to_string();
        let mut derived_key = vec![0u8; 32];
        
        pbkdf2::<Hmac<Sha512>>(
            &self.seed,
            path_str.as_bytes(),
            2048,
            &mut derived_key,
        )
        .map_err(|e| Error::InvalidKey(format!("Derivation failed: {:?}", e)))?;

        // Create private key from derived bytes
        match key_type {
            KeyType::Secp256k1 => {
                // Validate it's a valid key
                secp256k1::SecretKey::from_slice(&derived_key)
                    .map_err(|e| Error::InvalidKey(format!("Invalid derived key: {}", e)))?;
                
                PrivateKey::new(KeyType::Secp256k1, derived_key.to_vec())
            }
            KeyType::Ed25519 => {
                PrivateKey::new(KeyType::Ed25519, derived_key.to_vec())
            }
            KeyType::Secp256r1 => {
                PrivateKey::new(KeyType::Secp256r1, derived_key.to_vec())
            }
        }
    }

    /// Derive public key at path
    pub fn derive_public_key(&self, path: &DerivationPath, key_type: KeyType) -> Result<PublicKey> {
        let private_key = self.derive_private_key(path, key_type)?;
        private_key.public_key()
    }

    /// Derive address at path
    pub fn derive_address(&self, path: &DerivationPath, key_type: KeyType) -> Result<Address> {
        let public_key = self.derive_public_key(path, key_type)?;
        public_key.to_address()
    }

    /// Generate multiple addresses for an account
    pub fn generate_addresses(
        &self,
        account: u32,
        key_type: KeyType,
        count: usize,
    ) -> Result<Vec<(DerivationPath, Address)>> {
        let mut addresses = Vec::new();
        
        for index in 0..count {
            let path = DerivationPath::bip44(account, 0, index as u32);
            let address = self.derive_address(&path, key_type)?;
            addresses.push((path, address));
        }
        
        Ok(addresses)
    }
}

/// Number of words in mnemonic
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WordCount {
    Words12,
    Words15,
    Words18,
    Words21,
    Words24,
}

/// Derivation path for BIP32/BIP44
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DerivationPath {
    purpose: u32,
    coin_type: u32,
    account: u32,
    change: u32,
    index: u32,
}

impl DerivationPath {
    /// Create a BIP44 derivation path
    /// m/44'/1234'/account'/change/index
    pub fn bip44(account: u32, change: u32, index: u32) -> Self {
        Self {
            purpose: 44,
            coin_type: 1234, // Example coin type for Alephium
            account,
            change,
            index,
        }
    }

    /// Create a custom derivation path
    pub fn custom(purpose: u32, coin_type: u32, account: u32, change: u32, index: u32) -> Self {
        Self {
            purpose,
            coin_type,
            account,
            change,
            index,
        }
    }

    /// Parse path from string format: m/44'/1234'/0'/0/0
    pub fn from_str(path: &str) -> Result<Self> {
        let path = path.trim_start_matches("m/");
        let parts: Vec<&str> = path.split('/').collect();
        
        if parts.len() != 5 {
            return Err(Error::InvalidValue("Invalid path format".to_string()));
        }

        let purpose = parts[0].trim_end_matches('\'').parse()
            .map_err(|_| Error::InvalidValue("Invalid purpose".to_string()))?;
        let coin_type = parts[1].trim_end_matches('\'').parse()
            .map_err(|_| Error::InvalidValue("Invalid coin type".to_string()))?;
        let account = parts[2].trim_end_matches('\'').parse()
            .map_err(|_| Error::InvalidValue("Invalid account".to_string()))?;
        let change = parts[3].parse()
            .map_err(|_| Error::InvalidValue("Invalid change".to_string()))?;
        let index = parts[4].parse()
            .map_err(|_| Error::InvalidValue("Invalid index".to_string()))?;

        Ok(Self {
            purpose,
            coin_type,
            account,
            change,
            index,
        })
    }
}

impl std::fmt::Display for DerivationPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "m/{}'/{}'/{}'/{}/{}",
            self.purpose, self.coin_type, self.account, self.change, self.index
        )
    }
}

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

    #[test]
    fn test_hd_wallet_generation() {
        let wallet = HDWallet::generate(WordCount::Words12).unwrap();
        let phrase = wallet.mnemonic_phrase();
        
        // Mnemonic should have 12 words
        assert_eq!(phrase.split_whitespace().count(), 12);
    }

    #[test]
    fn test_hd_wallet_from_phrase() {
        let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let wallet = HDWallet::from_phrase(phrase, "").unwrap();
        
        assert_eq!(wallet.mnemonic_phrase(), phrase);
    }

    #[test]
    fn test_derivation_path_display() {
        let path = DerivationPath::bip44(0, 0, 0);
        assert_eq!(path.to_string(), "m/44'/1234'/0'/0/0");
    }

    #[test]
    fn test_derivation_path_parsing() {
        let path = DerivationPath::from_str("m/44'/1234'/0'/0/5").unwrap();
        assert_eq!(path.purpose, 44);
        assert_eq!(path.coin_type, 1234);
        assert_eq!(path.account, 0);
        assert_eq!(path.change, 0);
        assert_eq!(path.index, 5);
    }

    #[test]
    fn test_derive_address() {
        let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let wallet = HDWallet::from_phrase(phrase, "").unwrap();
        
        let path = DerivationPath::bip44(0, 0, 0);
        let address = wallet.derive_address(&path, KeyType::Secp256k1).unwrap();
        
        // Address should be valid
        assert!(!address.to_base58().is_empty());
    }

    #[test]
    fn test_generate_multiple_addresses() {
        let wallet = HDWallet::generate(WordCount::Words12).unwrap();
        let addresses = wallet.generate_addresses(0, KeyType::Secp256k1, 5).unwrap();
        
        assert_eq!(addresses.len(), 5);
        
        // Each address should be unique
        let unique_addresses: std::collections::HashSet<_> = 
            addresses.iter().map(|(_, addr)| addr.to_base58()).collect();
        assert_eq!(unique_addresses.len(), 5);
    }

    #[test]
    fn test_deterministic_derivation() {
        let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let wallet1 = HDWallet::from_phrase(phrase, "").unwrap();
        let wallet2 = HDWallet::from_phrase(phrase, "").unwrap();
        
        let path = DerivationPath::bip44(0, 0, 0);
        let addr1 = wallet1.derive_address(&path, KeyType::Secp256k1).unwrap();
        let addr2 = wallet2.derive_address(&path, KeyType::Secp256k1).unwrap();
        
        // Same mnemonic and path should produce same address
        assert_eq!(addr1.to_base58(), addr2.to_base58());
    }
}