snarkos_node_router_messages/
pong.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::*;
17
18use snarkvm::prelude::{FromBytes, ToBytes};
19
20use std::borrow::Cow;
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct Pong {
24    pub is_fork: Option<bool>,
25}
26
27impl MessageTrait for Pong {
28    /// Returns the message name.
29    #[inline]
30    fn name(&self) -> Cow<'static, str> {
31        "Pong".into()
32    }
33}
34
35impl ToBytes for Pong {
36    fn write_le<W: io::Write>(&self, writer: W) -> io::Result<()> {
37        let serialized_is_fork: u8 = match self.is_fork {
38            Some(true) => 0,
39            Some(false) => 1,
40            None => 2,
41        };
42
43        serialized_is_fork.write_le(writer)
44    }
45}
46
47impl FromBytes for Pong {
48    fn read_le<R: io::Read>(mut reader: R) -> io::Result<Self> {
49        let is_fork = match u8::read_le(&mut reader)? {
50            0 => Some(true),
51            1 => Some(false),
52            2 => None,
53            _ => return Err(error("Invalid 'Pong' message")),
54        };
55
56        Ok(Self { is_fork })
57    }
58}
59
60#[cfg(test)]
61pub mod tests {
62    use crate::Pong;
63    use snarkvm::utilities::{FromBytes, ToBytes};
64
65    use bytes::{Buf, BufMut, BytesMut};
66    use proptest::{
67        option::of,
68        prelude::{BoxedStrategy, Strategy, any},
69    };
70    use test_strategy::proptest;
71
72    pub fn any_pong() -> BoxedStrategy<Pong> {
73        of(any::<bool>()).prop_map(|is_fork| Pong { is_fork }).boxed()
74    }
75
76    #[proptest]
77    fn pong_roundtrip(#[strategy(any_pong())] pong: Pong) {
78        let mut bytes = BytesMut::default().writer();
79        pong.write_le(&mut bytes).unwrap();
80        let decoded = Pong::read_le(&mut bytes.into_inner().reader()).unwrap();
81        assert_eq!(pong, decoded);
82    }
83}