snarkos_node_bft/helpers/
proposal_cache.rs1use 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#[derive(Debug, PartialEq, Eq)]
30pub struct ProposalCache<N: Network> {
31 latest_round: u64,
33 proposal: Option<Proposal<N>>,
35 signed_proposals: SignedProposals<N>,
37 pending_certificates: IndexSet<BatchCertificate<N>>,
39}
40
41impl<N: Network> ProposalCache<N> {
42 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 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 pub fn exists(node_data_dir: &NodeDataDir) -> bool {
65 node_data_dir.current_proposal_cache_path().exists()
66 }
67
68 pub fn load(expected_signer: Address<N>, node_data_dir: &NodeDataDir) -> Result<Self> {
70 let path = node_data_dir.current_proposal_cache_path();
72
73 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 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 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 let bytes = self.to_bytes_le()?;
99 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 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 self.latest_round.write_le(&mut writer)?;
116 self.proposal.is_some().write_le(&mut writer)?;
118 if let Some(proposal) = &self.proposal {
119 proposal.write_le(&mut writer)?;
120 }
121 self.signed_proposals.write_le(&mut writer)?;
123 u32::try_from(self.pending_certificates.len()).map_err(error)?.write_le(&mut writer)?;
125 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 let latest_round = u64::read_le(&mut reader)?;
138 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 let signed_proposals = SignedProposals::read_le(&mut reader)?;
146 let num_certificates = u32::read_le(&mut reader)?;
148 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 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 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 let expected_bytes = expected.to_bytes_le().unwrap();
205 assert_eq!(expected, ProposalCache::read_le(&expected_bytes[..]).unwrap());
206 }
207 }
208}