Skip to main content

karyon_p2p/
util.rs

1use bincode::{Decode, Encode, config};
2
3use crate::Result;
4
5/// Max bytes one decode may claim. Same as the frame limit of
6/// `LengthCodec`, so a valid message is never rejected.
7const DECODE_LIMIT: usize = 4 * 1024 * 1024;
8
9fn bincode_config() -> impl config::Config {
10    // Without the limit, bincode trusts a length prefix from the wire and
11    // allocates that many bytes before reading them.
12    config::standard()
13        .with_fixed_int_encoding()
14        .with_limit::<DECODE_LIMIT>()
15}
16
17/// Encode the given type `T` into a `Vec<u8>`.
18pub fn encode<T: Encode>(src: &T) -> Result<Vec<u8>> {
19    Ok(bincode::encode_to_vec(src, bincode_config())?)
20}
21
22/// Decode a given type `T` from the given slice. Returns the decoded value
23/// along with the number of bytes read.
24pub fn decode<T: Decode<()>>(src: &[u8]) -> Result<(T, usize)> {
25    let (result, bytes_read) = bincode::decode_from_slice::<T, _>(src, bincode_config())?;
26    Ok((result, bytes_read))
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    use bincode::error::DecodeError;
34
35    use crate::{
36        Error,
37        message::{PeerNetCmd, PeerNetMsg, PeerNetMsgHeader, ShutdownMsg},
38    };
39
40    /// Size of the length prefix of a `Vec<u8>` on the wire.
41    const LEN_SIZE: usize = size_of::<u64>();
42
43    #[test]
44    fn decode_rejects_huge_length_prefix() {
45        let msg = PeerNetMsg::new(PeerNetCmd::Shutdown, ShutdownMsg(0)).unwrap();
46        let mut bytes = encode(&msg).unwrap();
47
48        // The message ends with the payload: its length, then one byte.
49        // Claim 2^40 bytes in the length.
50        let at = bytes.len() - 1 - LEN_SIZE;
51        bytes[at..at + LEN_SIZE].copy_from_slice(&(1u64 << 40).to_le_bytes());
52
53        let res = decode::<PeerNetMsg>(&bytes);
54        assert!(matches!(
55            res,
56            Err(Error::BincodeDecode(DecodeError::LimitExceeded))
57        ));
58    }
59
60    #[test]
61    fn decode_accepts_max_size_frame() {
62        // Header (4 bytes) + payload length + payload fill one whole frame.
63        let payload = vec![0u8; DECODE_LIMIT - 4 - LEN_SIZE];
64        let msg = PeerNetMsg {
65            header: PeerNetMsgHeader {
66                command: PeerNetCmd::Protocol,
67            },
68            payload,
69        };
70        let bytes = encode(&msg).unwrap();
71        assert_eq!(bytes.len(), DECODE_LIMIT);
72
73        let (decoded, n) = decode::<PeerNetMsg>(&bytes).unwrap();
74        assert_eq!(n, DECODE_LIMIT);
75        assert_eq!(decoded.payload.len(), msg.payload.len());
76    }
77}