snarkos_node_router_messages/
block_request.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(Copy, Clone, Debug, PartialEq, Eq, Hash)]
23pub struct BlockRequest {
24    /// The starting block height (inclusive).
25    pub start_height: u32,
26    /// The ending block height (exclusive).
27    pub end_height: u32,
28}
29
30impl MessageTrait for BlockRequest {
31    /// Returns the message name.
32    #[inline]
33    fn name(&self) -> Cow<'static, str> {
34        let start = self.start_height;
35        let end = self.end_height;
36        match start + 1 == end {
37            true => format!("BlockRequest {start}"),
38            false => format!("BlockRequest {start}..{end}"),
39        }
40        .into()
41    }
42}
43
44impl ToBytes for BlockRequest {
45    fn write_le<W: io::Write>(&self, mut writer: W) -> io::Result<()> {
46        self.start_height.write_le(&mut writer)?;
47        self.end_height.write_le(&mut writer)?;
48        Ok(())
49    }
50}
51
52impl FromBytes for BlockRequest {
53    fn read_le<R: io::Read>(mut reader: R) -> io::Result<Self> {
54        let start_height = u32::read_le(&mut reader)?;
55        let end_height = u32::read_le(&mut reader)?;
56        Ok(Self { start_height, end_height })
57    }
58}
59
60impl Display for BlockRequest {
61    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
62        write!(f, "{}..{}", self.start_height, self.end_height)
63    }
64}
65
66#[cfg(test)]
67pub mod prop_tests {
68    use crate::BlockRequest;
69    use snarkvm::utilities::{FromBytes, ToBytes};
70
71    use bytes::{Buf, BufMut, BytesMut};
72    use proptest::prelude::{BoxedStrategy, Strategy, any};
73    use test_strategy::proptest;
74
75    pub fn any_block_request() -> BoxedStrategy<BlockRequest> {
76        any::<(u32, u32)>().prop_map(|(start_height, end_height)| BlockRequest { start_height, end_height }).boxed()
77    }
78
79    #[proptest]
80    fn block_request_roundtrip(#[strategy(any_block_request())] block_request: BlockRequest) {
81        let mut bytes = BytesMut::default().writer();
82        block_request.write_le(&mut bytes).unwrap();
83        let decoded = BlockRequest::read_le(&mut bytes.into_inner().reader()).unwrap();
84        assert_eq![decoded, block_request];
85    }
86}