use anyhow::Result;
use sha2::{Digest, Sha256};
use thru_base::tn_tools::{KeyPair, Pubkey};
use thru_base::{derive_manager_program_accounts, derive_uploader_program_accounts};
use crate::error::CliError;
pub fn keypair_from_hex(private_key_hex: &str) -> Result<KeyPair, CliError> {
KeyPair::from_hex_private_key("cli", private_key_hex)
.map_err(|e| CliError::Crypto(e.to_string()))
}
pub fn derive_manager_accounts_from_seed(
seed: &str,
program_id: &Pubkey,
is_ephemeral: bool,
) -> Result<(Pubkey, Pubkey), CliError> {
let seed_bytes = seed.as_bytes();
derive_manager_program_accounts(seed_bytes, program_id, is_ephemeral)
.map_err(|e| CliError::Crypto(e.to_string()))
}
pub fn derive_uploader_accounts_from_seed(
seed: &str,
program_id: &Pubkey,
) -> Result<(Pubkey, Pubkey), CliError> {
let seed_bytes = seed.as_bytes();
derive_uploader_program_accounts(seed_bytes, program_id)
.map_err(|e| CliError::Crypto(e.to_string()))
}
pub fn calculate_sha256(data: &[u8]) -> [u8; 32] {
let mut hasher = Sha256::new();
hasher.update(data);
let hash = hasher.finalize();
let mut result = [0u8; 32];
result.copy_from_slice(&hash);
result
}
#[allow(dead_code)]
pub fn validate_private_key_hex(hex_str: &str) -> Result<(), CliError> {
if hex_str.len() != 64 {
return Err(CliError::Crypto(
"Private key must be exactly 64 hex characters".to_string(),
));
}
hex::decode(hex_str)
.map_err(|e| CliError::Crypto(format!("Invalid hex private key: {}", e)))?;
Ok(())
}
pub fn bytes_to_hex(bytes: &[u8]) -> String {
hex::encode(bytes)
}
#[allow(dead_code)]
pub fn hex_to_bytes(hex_str: &str) -> Result<Vec<u8>, CliError> {
hex::decode(hex_str).map_err(|e| CliError::Crypto(format!("Invalid hex string: {}", e)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_private_key_hex() {
let valid_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
assert!(validate_private_key_hex(valid_key).is_ok());
let short_key = "0123456789abcdef";
assert!(validate_private_key_hex(short_key).is_err());
let long_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef00";
assert!(validate_private_key_hex(long_key).is_err());
let invalid_key = "0123456789abcdefghij456789abcdef0123456789abcdef0123456789abcdef";
assert!(validate_private_key_hex(invalid_key).is_err());
}
#[test]
fn test_calculate_sha256() {
let data = b"hello world";
let hash = calculate_sha256(data);
assert_eq!(hash.len(), 32);
let hash2 = calculate_sha256(data);
assert_eq!(hash, hash2);
}
#[test]
fn test_hex_conversion() {
let bytes = vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef];
let hex_str = bytes_to_hex(&bytes);
assert_eq!(hex_str, "0123456789abcdef");
let converted_back = hex_to_bytes(&hex_str).unwrap();
assert_eq!(bytes, converted_back);
}
}