use std::collections::BTreeMap;
use crate::bencode::{decode_with_limits, encode, BencodeValue};
use crate::dht::messages::{DhtMessage, DhtMethod, DhtQuery, DhtResponse};
use crate::error::{Error, Result};
use crate::security::DecodeLimits;
pub fn encode_query(query: &DhtQuery) -> Vec<u8> {
let root = BencodeValue::Dict(BTreeMap::from([
(b"t".to_vec(), BencodeValue::Bytes(query.transaction_id.clone())),
(b"y".to_vec(), BencodeValue::Bytes(b"q".to_vec())),
(
b"q".to_vec(),
BencodeValue::Bytes(query.method.as_str().as_bytes().to_vec()),
),
(b"a".to_vec(), BencodeValue::Dict(query.arguments.clone())),
]));
encode(&root)
}
pub fn encode_response(response: &DhtResponse) -> Vec<u8> {
let root = BencodeValue::Dict(BTreeMap::from([
(
b"t".to_vec(),
BencodeValue::Bytes(response.transaction_id.clone()),
),
(b"y".to_vec(), BencodeValue::Bytes(b"r".to_vec())),
(
b"r".to_vec(),
BencodeValue::Dict(response.values.clone()),
),
]));
encode(&root)
}
pub fn decode_message(input: &[u8]) -> Result<DhtMessage> {
let root = decode_with_limits(input, DecodeLimits::NETWORK)?;
let dict = root
.as_dict()
.ok_or_else(|| Error::Dht("message root must be dict".into()))?;
let kind = dict
.get(b"y".as_ref())
.and_then(|v| v.as_bytes())
.ok_or_else(|| Error::Dht("missing message type".into()))?;
let transaction_id = dict
.get(b"t".as_ref())
.and_then(|v| v.as_bytes())
.ok_or_else(|| Error::Dht("missing transaction id".into()))?
.to_vec();
match kind {
b"q" => {
let method_raw = dict
.get(b"q".as_ref())
.and_then(|v| v.as_bytes())
.ok_or_else(|| Error::Dht("missing query method".into()))?;
let method = std::str::from_utf8(method_raw)
.ok()
.and_then(DhtMethod::parse)
.ok_or_else(|| Error::Dht("unknown query method".into()))?;
let arguments = dict
.get(b"a".as_ref())
.and_then(|v| v.as_dict())
.cloned()
.ok_or_else(|| Error::Dht("missing query args".into()))?;
Ok(DhtMessage::Query(DhtQuery {
transaction_id,
method,
arguments,
}))
}
b"r" => {
let values = dict
.get(b"r".as_ref())
.and_then(|v| v.as_dict())
.cloned()
.ok_or_else(|| Error::Dht("missing response body".into()))?;
Ok(DhtMessage::Response(DhtResponse {
transaction_id,
values,
}))
}
_ => Err(Error::Dht("unsupported message type".into())),
}
}