snarkos_node_router_messages/
ping.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 Ping<N: Network> {
24    pub version: u32,
25    pub node_type: NodeType,
26    pub block_locators: Option<BlockLocators<N>>,
27}
28
29impl<N: Network> MessageTrait for Ping<N> {
30    /// Returns the message name.
31    #[inline]
32    fn name(&self) -> Cow<'static, str> {
33        "Ping".into()
34    }
35}
36
37impl<N: Network> ToBytes for Ping<N> {
38    fn write_le<W: io::Write>(&self, mut writer: W) -> io::Result<()> {
39        self.version.write_le(&mut writer)?;
40        self.node_type.write_le(&mut writer)?;
41        if let Some(locators) = &self.block_locators {
42            1u8.write_le(&mut writer)?;
43            locators.write_le(&mut writer)?;
44        } else {
45            0u8.write_le(&mut writer)?;
46        }
47
48        Ok(())
49    }
50}
51
52impl<N: Network> FromBytes for Ping<N> {
53    fn read_le<R: io::Read>(mut reader: R) -> io::Result<Self> {
54        let version = u32::read_le(&mut reader)?;
55        let node_type = NodeType::read_le(&mut reader)?;
56
57        let selector = u8::read_le(&mut reader)?;
58        let block_locators = match selector {
59            0 => None,
60            1 => Some(BlockLocators::read_le(&mut reader)?),
61            _ => return Err(error("Invalid block locators marker")),
62        };
63
64        Ok(Self { version, node_type, block_locators })
65    }
66}
67
68impl<N: Network> Ping<N> {
69    pub fn new(node_type: NodeType, block_locators: Option<BlockLocators<N>>) -> Self {
70        Self { version: <Message<N>>::latest_message_version(), node_type, block_locators }
71    }
72}
73
74#[cfg(test)]
75pub mod prop_tests {
76    use crate::{Ping, challenge_request::prop_tests::any_node_type};
77    use snarkos_node_sync_locators::{BlockLocators, test_helpers::sample_block_locators};
78    use snarkvm::utilities::{FromBytes, ToBytes};
79
80    use bytes::{Buf, BufMut, BytesMut};
81    use proptest::prelude::{BoxedStrategy, Strategy, any};
82    use test_strategy::proptest;
83
84    type CurrentNetwork = snarkvm::prelude::MainnetV0;
85
86    pub fn any_block_locators() -> BoxedStrategy<BlockLocators<CurrentNetwork>> {
87        any::<u32>().prop_map(sample_block_locators).boxed()
88    }
89
90    pub fn any_ping() -> BoxedStrategy<Ping<CurrentNetwork>> {
91        (any::<u32>(), any_block_locators(), any_node_type())
92            .prop_map(|(version, bls, node_type)| Ping { version, block_locators: Some(bls), node_type })
93            .boxed()
94    }
95
96    #[proptest]
97    fn ping_roundtrip(#[strategy(any_ping())] ping: Ping<CurrentNetwork>) {
98        let mut bytes = BytesMut::default().writer();
99        ping.write_le(&mut bytes).unwrap();
100        let decoded = Ping::<CurrentNetwork>::read_le(&mut bytes.into_inner().reader()).unwrap();
101        assert_eq!(ping, decoded);
102    }
103}