use std::convert::{TryFrom, TryInto};
use tari_common_types::types::PrivateKey;
use tari_utilities::ByteArray;
use crate::{
base_node::comms_interface::NodeCommsRequest,
proto::{base_node as proto, base_node::base_node_service_request::Request as ProtoNodeCommsRequest},
};
impl TryInto<NodeCommsRequest> for ProtoNodeCommsRequest {
type Error = String;
fn try_into(self) -> Result<NodeCommsRequest, Self::Error> {
use ProtoNodeCommsRequest::{FetchMempoolTransactionsByExcessSigs, GetBlockFromAllChains};
let request = match self {
GetBlockFromAllChains(req) => {
NodeCommsRequest::GetBlockFromAllChains(req.hash.try_into().map_err(|_| "Malformed hash".to_string())?)
},
FetchMempoolTransactionsByExcessSigs(excess_sigs) => {
let excess_sigs = excess_sigs
.excess_sigs
.into_iter()
.map(|bytes| {
PrivateKey::from_canonical_bytes(&bytes).map_err(|_| "Malformed excess sig".to_string())
})
.collect::<Result<_, _>>()?;
NodeCommsRequest::FetchMempoolTransactionsByExcessSigs { excess_sigs }
},
};
Ok(request)
}
}
impl TryFrom<NodeCommsRequest> for ProtoNodeCommsRequest {
type Error = String;
fn try_from(request: NodeCommsRequest) -> Result<Self, Self::Error> {
use NodeCommsRequest::{FetchMempoolTransactionsByExcessSigs, GetBlockFromAllChains};
match request {
GetBlockFromAllChains(hash) => Ok(ProtoNodeCommsRequest::GetBlockFromAllChains(
proto::GetBlockFromAllChainsRequest { hash: hash.to_vec() },
)),
FetchMempoolTransactionsByExcessSigs { excess_sigs } => Ok(
ProtoNodeCommsRequest::FetchMempoolTransactionsByExcessSigs(proto::ExcessSigs {
excess_sigs: excess_sigs.into_iter().map(|sig| sig.to_vec()).collect(),
}),
),
e => Err(format!("{e} request is not supported")),
}
}
}
impl From<Vec<u64>> for proto::BlockHeights {
fn from(heights: Vec<u64>) -> Self {
Self { heights }
}
}