use ex3_node_error::{Error, OtherError};
use ex3_node_types::{chain::ChainType, PublicKey};
use ex3_serde::cbor;
use serde_bytes::ByteBuf;
use crate::{tx_type_dto::ApiKey, PayloadDecoder, Result};
impl PayloadDecoder {
pub fn decode_to_reset_main_secret(
payload: &[u8],
) -> Result<(ChainType, ex3_node_types::transaction::ResetMainSecret)> {
let payload_str = String::from_utf8(payload.as_ref().to_vec()).expect("should success");
let hexes = payload_str.split('|').collect::<Vec<&str>>();
let invalid_payload_error = OtherError::new("Invalid payload");
if hexes.len() != 3 {
return Err(invalid_payload_error.clone().into());
}
let chain =
u128::from_str_radix(&hexes[0], 16).map_err(|_| invalid_payload_error.clone())?;
let encrypted_pri_key = hex::decode(hexes[1]).map_err(|_| invalid_payload_error.clone())?;
let l2_pub_key = hex::decode(hexes[2]).map_err(|_| invalid_payload_error)?;
let encrypted_pri_key: ByteBuf = ByteBuf::from(encrypted_pri_key);
let l2_pub_key: PublicKey = ByteBuf::from(l2_pub_key);
let reset_main_secret_request = ex3_node_types::transaction::ResetMainSecret {
encrypted_pri_key,
l2_pub_key,
};
Ok((chain.into(), reset_main_secret_request))
}
pub fn decode_to_create_api_secret(
payload: &[u8],
) -> Result<ex3_node_types::transaction::CreateApiSecret> {
let api_key = cbor::deserialize::<ApiKey>(payload).map_err(|e| {
<OtherError as Into<Error>>::into(OtherError::new(format!(
"Failed to deserialize payload to Api key: {}",
e
)))
})?;
Ok(ex3_node_types::transaction::CreateApiSecret(
api_key.pub_key,
))
}
pub fn decode_to_destroy_api_secret(
payload: &[u8],
) -> Result<ex3_node_types::transaction::DestroyApiSecret> {
let api_key = cbor::deserialize::<ApiKey>(payload).map_err(|e| {
<OtherError as Into<Error>>::into(OtherError::new(format!(
"Failed to deserialize payload to Api key: {}",
e
)))
})?;
Ok(ex3_node_types::transaction::DestroyApiSecret(
api_key.pub_key,
))
}
}