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.

pub mod bs58;
pub mod djb2;

use crate::error::{Error, Result};

/// Check if a string is a valid hex string
pub fn is_hex_string(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }
    let s = s.strip_prefix("0x").unwrap_or(s);
    s.chars().all(|c| c.is_ascii_hexdigit())
}

/// Convert hex string to bytes
pub fn hex_to_bytes(s: &str) -> Result<Vec<u8>> {
    let s = s.strip_prefix("0x").unwrap_or(s);
    hex::decode(s).map_err(|e| Error::InvalidHex(format!("{}: {}", s, e)))
}

/// Convert hex string to bytes without validation (unsafe)
pub fn hex_to_bin_unsafe(s: &str) -> Vec<u8> {
    let s = s.strip_prefix("0x").unwrap_or(s);
    hex::decode(s).unwrap_or_default()
}

/// Convert bytes to hex string
pub fn bin_to_hex(bytes: &[u8]) -> String {
    hex::encode(bytes)
}

/// Convert bytes to hex string with 0x prefix
pub fn bin_to_hex_with_prefix(bytes: &[u8]) -> String {
    format!("0x{}", hex::encode(bytes))
}

/// Concatenate multiple byte slices
pub fn concat_bytes(slices: &[&[u8]]) -> Vec<u8> {
    let total_len: usize = slices.iter().map(|s| s.len()).sum();
    let mut result = Vec::with_capacity(total_len);
    for slice in slices {
        result.extend_from_slice(slice);
    }
    result
}

/// XOR a byte array with a single byte
pub fn xor_byte(bytes: &[u8], byte: u8) -> Vec<u8> {
    bytes.iter().map(|b| b ^ byte).collect()
}

/// Calculate DJB2 hash of a byte array
pub fn djb2_hash(bytes: &[u8]) -> u32 {
    djb2::djb2(bytes)
}

/// Type equality checker (compile-time)
pub trait TypeEq<T> {}
impl<T> TypeEq<T> for T {}

/// Assert that two types are equal at compile time
#[macro_export]
macro_rules! assert_type_eq {
    ($t1:ty, $t2:ty) => {
        const _: () = {
            fn assert_eq<T: $crate::utils::TypeEq<$t2>>() {}
            fn check() {
                assert_eq::<$t1>()
            }
        };
    };
}

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

    #[test]
    fn test_is_hex_string() {
        assert!(is_hex_string("deadbeef"));
        assert!(is_hex_string("0xdeadbeef"));
        assert!(is_hex_string("DEADBEEF"));
        assert!(!is_hex_string("xyz"));
        assert!(!is_hex_string(""));
    }

    #[test]
    fn test_hex_conversion() {
        let bytes = vec![0xde, 0xad, 0xbe, 0xef];
        let hex_str = bin_to_hex(&bytes);
        assert_eq!(hex_str, "deadbeef");
        
        let decoded = hex_to_bytes(&hex_str).unwrap();
        assert_eq!(decoded, bytes);
        
        let decoded_with_prefix = hex_to_bytes("0xdeadbeef").unwrap();
        assert_eq!(decoded_with_prefix, bytes);
    }

    #[test]
    fn test_concat_bytes() {
        let a = vec![1, 2, 3];
        let b = vec![4, 5, 6];
        let c = vec![7, 8, 9];
        let result = concat_bytes(&[&a, &b, &c]);
        assert_eq!(result, vec![1, 2, 3, 4, 5, 6, 7, 8, 9]);
    }

    #[test]
    fn test_xor_byte() {
        let bytes = vec![0x00, 0xFF, 0xAA];
        let result = xor_byte(&bytes, 0xFF);
        assert_eq!(result, vec![0xFF, 0x00, 0x55]);
    }
}