Skip to main content

snarkos_node_bft/helpers/
proposal_cache.rs

1// Copyright (c) 2019-2026 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 crate::helpers::{Proposal, SignedProposals};
17use snarkos_utilities::NodeDataDir;
18
19use snarkvm::{
20    console::{account::Address, network::Network, program::SUBDAG_CERTIFICATES_DEPTH},
21    ledger::narwhal::BatchCertificate,
22    prelude::{FromBytes, IoResult, Read, Result, ToBytes, Write, anyhow, bail, error},
23};
24
25use indexmap::IndexSet;
26use std::fs;
27
28/// A helper type for the cache of proposal and signed proposals.
29#[derive(Debug, PartialEq, Eq)]
30pub struct ProposalCache<N: Network> {
31    /// The latest round this node was on prior to the reboot.
32    latest_round: u64,
33    /// The latest proposal this node has created.
34    proposal: Option<Proposal<N>>,
35    /// The signed proposals this node has received.
36    signed_proposals: SignedProposals<N>,
37    /// The pending certificates in storage that have not been included in the ledger.
38    pending_certificates: IndexSet<BatchCertificate<N>>,
39}
40
41impl<N: Network> ProposalCache<N> {
42    /// Initializes a new instance of the proposal cache.
43    pub fn new(
44        latest_round: u64,
45        proposal: Option<Proposal<N>>,
46        signed_proposals: SignedProposals<N>,
47        pending_certificates: IndexSet<BatchCertificate<N>>,
48    ) -> Self {
49        Self { latest_round, proposal, signed_proposals, pending_certificates }
50    }
51
52    /// Ensure that the proposal and every signed proposal is associated with the `expected_signer`.
53    pub fn is_valid(&self, expected_signer: Address<N>) -> bool {
54        self.proposal
55            .as_ref()
56            .map(|proposal| {
57                proposal.batch_header().author() == expected_signer && self.latest_round == proposal.round()
58            })
59            .unwrap_or(true)
60            && self.signed_proposals.is_valid(expected_signer)
61    }
62
63    /// Returns `true` if a proposal cache exists for the given network and `dev`.
64    pub fn exists(node_data_dir: &NodeDataDir) -> bool {
65        node_data_dir.current_proposal_cache_path().exists()
66    }
67
68    /// Load the proposal cache from the file system and ensure that the proposal cache is valid.
69    pub fn load(expected_signer: Address<N>, node_data_dir: &NodeDataDir) -> Result<Self> {
70        // Construct the proposal cache file system path.
71        let path = node_data_dir.current_proposal_cache_path();
72
73        // Deserialize the proposal cache from the file system.
74        let proposal_cache = match fs::read(&path) {
75            Ok(bytes) => match Self::from_bytes_le(&bytes) {
76                Ok(proposal_cache) => proposal_cache,
77                Err(_) => bail!("Couldn't deserialize the proposal stored at {}", path.display()),
78            },
79            Err(_) => bail!("Couldn't read the proposal stored at {}", path.display()),
80        };
81
82        // Ensure the proposal cache is valid.
83        if !proposal_cache.is_valid(expected_signer) {
84            bail!("The proposal cache at {} is invalid for the given address {expected_signer}", path.display());
85        }
86
87        info!("Loaded the proposal cache from {} at round {}", path.display(), proposal_cache.latest_round);
88
89        Ok(proposal_cache)
90    }
91
92    /// Store the proposal cache to the file system.
93    pub fn store(&self, node_data_dir: &NodeDataDir) -> Result<()> {
94        let path = node_data_dir.current_proposal_cache_path();
95        info!("Storing the proposal cache to {}...", path.display());
96
97        // Serialize the proposal cache.
98        let bytes = self.to_bytes_le()?;
99        // Store the proposal cache to the file system.
100        fs::write(&path, bytes)
101            .map_err(|err| anyhow!("Couldn't write the proposal cache to {} - {err}", path.display()))?;
102
103        Ok(())
104    }
105
106    /// Returns the latest round, proposal, signed proposals, and pending certificates.
107    pub fn into(self) -> (u64, Option<Proposal<N>>, SignedProposals<N>, IndexSet<BatchCertificate<N>>) {
108        (self.latest_round, self.proposal, self.signed_proposals, self.pending_certificates)
109    }
110}
111
112impl<N: Network> ToBytes for ProposalCache<N> {
113    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
114        // Serialize the `latest_round`.
115        self.latest_round.write_le(&mut writer)?;
116        // Serialize the `proposal`.
117        self.proposal.is_some().write_le(&mut writer)?;
118        if let Some(proposal) = &self.proposal {
119            proposal.write_le(&mut writer)?;
120        }
121        // Serialize the `signed_proposals`.
122        self.signed_proposals.write_le(&mut writer)?;
123        // Write the number of pending certificates.
124        u32::try_from(self.pending_certificates.len()).map_err(error)?.write_le(&mut writer)?;
125        // Serialize the pending certificates.
126        for certificate in &self.pending_certificates {
127            certificate.write_le(&mut writer)?;
128        }
129
130        Ok(())
131    }
132}
133
134impl<N: Network> FromBytes for ProposalCache<N> {
135    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
136        // Deserialize `latest_round`.
137        let latest_round = u64::read_le(&mut reader)?;
138        // Deserialize `proposal`.
139        let has_proposal: bool = FromBytes::read_le(&mut reader)?;
140        let proposal = match has_proposal {
141            true => Some(Proposal::read_le(&mut reader)?),
142            false => None,
143        };
144        // Deserialize `signed_proposals`.
145        let signed_proposals = SignedProposals::read_le(&mut reader)?;
146        // Read the number of pending certificates.
147        let num_certificates = u32::read_le(&mut reader)?;
148        // Ensure the number of certificates is within bounds.
149        if num_certificates > 2u32.saturating_pow(SUBDAG_CERTIFICATES_DEPTH as u32) {
150            return Err(error(format!(
151                "Number of certificates ({num_certificates}) exceeds the maximum ({})",
152                2u32.saturating_pow(SUBDAG_CERTIFICATES_DEPTH as u32)
153            )));
154        };
155        // Deserialize the pending certificates.
156        let pending_certificates =
157            (0..num_certificates).map(|_| BatchCertificate::read_le(&mut reader)).collect::<IoResult<IndexSet<_>>>()?;
158
159        Ok(Self::new(latest_round, proposal, signed_proposals, pending_certificates))
160    }
161}
162
163impl<N: Network> Default for ProposalCache<N> {
164    /// Initializes a new instance of the proposal cache.
165    fn default() -> Self {
166        Self::new(0, None, Default::default(), Default::default())
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use crate::helpers::{proposal::tests::sample_proposal, signed_proposals::tests::sample_signed_proposals};
174    use snarkvm::{
175        console::{account::PrivateKey, network::MainnetV0},
176        ledger::narwhal::batch_certificate::test_helpers::sample_batch_certificates,
177        utilities::TestRng,
178    };
179
180    type CurrentNetwork = MainnetV0;
181
182    const ITERATIONS: usize = 100;
183
184    pub(crate) fn sample_proposal_cache(
185        signer: &PrivateKey<CurrentNetwork>,
186        rng: &mut TestRng,
187    ) -> ProposalCache<CurrentNetwork> {
188        let proposal = sample_proposal(rng);
189        let signed_proposals = sample_signed_proposals(signer, rng);
190        let round = proposal.round();
191        let pending_certificates = sample_batch_certificates(rng);
192
193        ProposalCache::new(round, Some(proposal), signed_proposals, pending_certificates)
194    }
195
196    #[test]
197    fn test_bytes() {
198        let rng = &mut TestRng::default();
199        let singer_private_key = PrivateKey::<CurrentNetwork>::new(rng).unwrap();
200
201        for _ in 0..ITERATIONS {
202            let expected = sample_proposal_cache(&singer_private_key, rng);
203            // Check the byte representation.
204            let expected_bytes = expected.to_bytes_le().unwrap();
205            assert_eq!(expected, ProposalCache::read_le(&expected_bytes[..]).unwrap());
206        }
207    }
208}