use std::collections::HashMap;
use std::error::Error;
use std::sync::{Arc, Mutex, RwLock};
use crate::security::hsm::HsmManager;
use crate::AnyaResult;
use bitcoin::{Txid, XOnlyPublicKey};
use secp256k1::ecdsa::Signature;
pub struct SecurityManager {
activation_status: RwLock<bool>,
key_cache: Mutex<HashMap<String, Vec<u8>>>,
}
impl SecurityManager {
pub fn new(_hsm: Arc<HsmManager>) -> Self {
Self {
activation_status: RwLock::new(false),
key_cache: Mutex::new(HashMap::new()),
}
}
pub fn enable(&self) -> AnyaResult<bool> {
let mut status = self.activation_status.write().unwrap();
*status = true;
Ok(true)
}
pub fn disable(&self) -> AnyaResult<bool> {
let mut status = self.activation_status.write().unwrap();
*status = false;
Ok(false)
}
pub fn is_enabled(&self) -> bool {
*self.activation_status.read().unwrap()
}
pub async fn sign_repudiation(
&self,
txid: &Txid,
_nonce: &[u8; 32],
) -> Result<Signature, Box<dyn Error>> {
if !self.is_enabled() {
return Err("Security operations are disabled. Enable them first.".into());
}
use bitcoin::hashes::Hash;
let secp = secp256k1::Secp256k1::new();
let secret_key = secp256k1::SecretKey::from_slice(&[42; 32])?;
let txid_bytes = txid.as_byte_array();
let message = secp256k1::Message::from_digest_slice(txid_bytes)?;
Ok(secp.sign_ecdsa(&message, &secret_key))
}
pub async fn generate_key(&self, key_name: &str) -> Result<XOnlyPublicKey, Box<dyn Error>> {
if !self.is_enabled() {
return Err("Security operations are disabled. Enable them first.".into());
}
let secp = secp256k1::Secp256k1::new();
let secret_key = secp256k1::SecretKey::from_slice(&[42; 32])?;
let public_key = secp256k1::PublicKey::from_secret_key(&secp, &secret_key);
let (xonly, _parity) = public_key.x_only_public_key();
let xonly_serialized = xonly.serialize();
let bitcoin_xonly = XOnlyPublicKey::from_slice(&xonly_serialized)?;
let mut cache = self.key_cache.lock().unwrap();
cache.insert(key_name.to_string(), xonly_serialized.to_vec());
Ok(bitcoin_xonly)
}
}