use super::*;
use nom::{
number::complete::be_u64,
combinator::rest,
};
use tox_binary_io::*;
use tox_crypto::*;
use crate::dht::errors::*;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PingResponse {
pub pk: PublicKey,
pub nonce: Nonce,
pub payload: Vec<u8>,
}
impl ToBytes for PingResponse {
fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
do_gen!(buf,
gen_be_u8!(0x01) >>
gen_slice!(self.pk.as_ref()) >>
gen_slice!(self.nonce.as_ref()) >>
gen_slice!(self.payload.as_slice())
)
}
}
impl FromBytes for PingResponse {
named!(from_bytes<PingResponse>, do_parse!(
tag!("\x01") >>
pk: call!(PublicKey::from_bytes) >>
nonce: call!(Nonce::from_bytes) >>
payload: map!(rest, |bytes| bytes.to_vec() ) >>
(PingResponse { pk, nonce, payload })
));
}
impl PingResponse {
pub fn new(shared_secret: &PrecomputedKey, pk: &PublicKey, payload: &PingResponsePayload) -> PingResponse {
let nonce = gen_nonce();
let mut buf = [0; MAX_DHT_PACKET_SIZE];
let (_, size) = payload.to_bytes((&mut buf, 0)).unwrap();
let payload = seal_precomputed(&buf[..size], &nonce, shared_secret);
PingResponse {
pk: *pk,
nonce,
payload,
}
}
pub fn get_payload(&self, shared_secret: &PrecomputedKey) -> Result<PingResponsePayload, GetPayloadError> {
let decrypted = open_precomputed(&self.payload, &self.nonce, shared_secret)
.map_err(|()| {
GetPayloadError::decrypt()
})?;
match PingResponsePayload::from_bytes(&decrypted) {
Err(error) => {
Err(GetPayloadError::deserialize(error, decrypted.clone()))
},
Ok((_, payload)) => {
Ok(payload)
}
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PingResponsePayload {
pub id: u64,
}
impl FromBytes for PingResponsePayload {
named!(from_bytes<PingResponsePayload>, do_parse!(
tag!("\x01") >>
id: be_u64 >>
eof!() >>
(PingResponsePayload { id })
));
}
impl ToBytes for PingResponsePayload {
fn to_bytes<'a>(&self, buf: (&'a mut [u8], usize)) -> Result<(&'a mut [u8], usize), GenError> {
do_gen!(buf,
gen_be_u8!(0x01) >>
gen_be_u64!(self.id)
)
}
}
#[cfg(test)]
mod tests {
use crate::dht::ping_response::*;
use crate::dht::Packet;
encode_decode_test!(
tox_crypto::crypto_init().unwrap(),
ping_response_payload_encode_decode,
PingResponsePayload { id: 42 }
);
dht_packet_encode_decode!(ping_response_encode_decode, PingResponse);
dht_packet_encrypt_decrypt!(
ping_response_payload_encrypt_decrypt,
PingResponse,
PingResponsePayload { id: 42 }
);
dht_packet_encrypt_decrypt_invalid_key!(
ping_response_payload_encrypt_decrypt_invalid_key,
PingResponse,
PingResponsePayload { id: 42 }
);
dht_packet_decode_invalid!(ping_response_decode_invalid, PingResponse);
}