1use crate::helpers::{check_timestamp_for_liveness, fmt_id};
17use amareleo_chain_tracing::{TracingHandler, TracingHandlerGuard};
18use amareleo_node_bft_ledger_service::LedgerService;
19use amareleo_node_bft_storage_service::StorageService;
20use snarkvm::{
21 ledger::{
22 block::{Block, Transaction},
23 narwhal::{BatchCertificate, BatchHeader, Transmission, TransmissionID},
24 },
25 prelude::{Address, Field, Network, Result, anyhow, bail, ensure},
26 utilities::{cfg_into_iter, cfg_sorted_by},
27};
28
29use indexmap::{IndexMap, IndexSet, map::Entry};
30#[cfg(feature = "locktick")]
31use locktick::parking_lot::RwLock;
32#[cfg(not(feature = "locktick"))]
33use parking_lot::RwLock;
34use rayon::iter::{IntoParallelIterator, ParallelIterator};
35use std::{
36 collections::{HashMap, HashSet},
37 sync::{
38 Arc,
39 atomic::{AtomicU32, AtomicU64, Ordering},
40 },
41};
42use tracing::subscriber::DefaultGuard;
43
44#[derive(Clone, Debug)]
45pub struct Storage<N: Network>(Arc<StorageInner<N>>);
46
47impl<N: Network> std::ops::Deref for Storage<N> {
48 type Target = Arc<StorageInner<N>>;
49
50 fn deref(&self) -> &Self::Target {
51 &self.0
52 }
53}
54
55impl<N: Network> TracingHandlerGuard for Storage<N> {
56 fn get_tracing_guard(&self) -> Option<DefaultGuard> {
58 self.tracing.as_ref().and_then(|trace_handle| trace_handle.get_tracing_guard())
59 }
60}
61
62#[derive(Debug)]
82pub struct StorageInner<N: Network> {
83 ledger: Arc<dyn LedgerService<N>>,
85 current_height: AtomicU32,
88 current_round: AtomicU64,
91 gc_round: AtomicU64,
93 max_gc_rounds: u64,
95 rounds: RwLock<IndexMap<u64, IndexSet<(Field<N>, Field<N>, Address<N>)>>>,
98 certificates: RwLock<IndexMap<Field<N>, BatchCertificate<N>>>,
100 batch_ids: RwLock<IndexMap<Field<N>, u64>>,
102 transmissions: Arc<dyn StorageService<N>>,
104 tracing: Option<TracingHandler>,
106}
107
108impl<N: Network> Storage<N> {
109 pub fn new(
111 ledger: Arc<dyn LedgerService<N>>,
112 transmissions: Arc<dyn StorageService<N>>,
113 max_gc_rounds: u64,
114 tracing: Option<TracingHandler>,
115 ) -> Self {
116 let committee = ledger.current_committee().expect("Ledger is missing a committee.");
119 let current_round = committee.starting_round().max(1);
121
122 let storage = Self(Arc::new(StorageInner {
124 ledger,
125 current_height: Default::default(),
126 current_round: Default::default(),
127 gc_round: Default::default(),
128 max_gc_rounds,
129 rounds: Default::default(),
130 certificates: Default::default(),
131 batch_ids: Default::default(),
132 transmissions,
133 tracing,
134 }));
135 storage.update_current_round(current_round);
137 storage.garbage_collect_certificates(current_round);
140 storage
142 }
143}
144
145impl<N: Network> Storage<N> {
146 pub fn current_height(&self) -> u32 {
148 self.current_height.load(Ordering::SeqCst)
150 }
151}
152
153impl<N: Network> Storage<N> {
154 pub fn current_round(&self) -> u64 {
156 self.current_round.load(Ordering::SeqCst)
158 }
159
160 pub fn gc_round(&self) -> u64 {
162 self.gc_round.load(Ordering::SeqCst)
164 }
165
166 pub fn max_gc_rounds(&self) -> u64 {
168 self.max_gc_rounds
169 }
170
171 pub fn increment_to_next_round(&self, current_round: u64) -> Result<u64> {
174 let next_round = current_round + 1;
176
177 {
179 let storage_round = self.current_round();
181 if next_round < storage_round {
183 return Ok(storage_round);
184 }
185 }
186
187 let current_committee = self.ledger.current_committee()?;
189 let starting_round = current_committee.starting_round();
191 if next_round < starting_round {
193 let latest_block_round = self.ledger.latest_round();
195 guard_info!(
197 self,
198 "Syncing primary round ({next_round}) with the current committee's starting round ({starting_round}). Syncing with the latest block round {latest_block_round}..."
199 );
200 self.sync_round_with_block(latest_block_round);
202 return Ok(latest_block_round);
204 }
205
206 self.update_current_round(next_round);
208
209 #[cfg(feature = "metrics")]
210 metrics::gauge(metrics::bft::LAST_STORED_ROUND, next_round as f64);
211
212 let storage_round = self.current_round();
214 let gc_round = self.gc_round();
216 ensure!(next_round == storage_round, "The next round {next_round} does not match in storage ({storage_round})");
218 ensure!(next_round >= gc_round, "The next round {next_round} is behind the GC round {gc_round}");
220
221 guard_info!(self, "Starting round {next_round}...");
223 Ok(next_round)
224 }
225
226 fn update_current_round(&self, next_round: u64) {
228 self.current_round.store(next_round, Ordering::SeqCst);
230 }
231
232 pub(crate) fn garbage_collect_certificates(&self, next_round: u64) {
234 let current_gc_round = self.gc_round();
236 let next_gc_round = next_round.saturating_sub(self.max_gc_rounds);
238 if next_gc_round > current_gc_round {
240 for gc_round in current_gc_round..=next_gc_round {
242 for id in self.get_certificate_ids_for_round(gc_round).into_iter() {
244 self.remove_certificate(id);
246 }
247 }
248 self.gc_round.store(next_gc_round, Ordering::SeqCst);
250 }
251 }
252}
253
254impl<N: Network> Storage<N> {
255 pub fn contains_certificates_for_round(&self, round: u64) -> bool {
257 self.rounds.read().contains_key(&round)
259 }
260
261 pub fn contains_certificate(&self, certificate_id: Field<N>) -> bool {
263 self.certificates.read().contains_key(&certificate_id)
265 }
266
267 pub fn contains_certificate_in_round_from(&self, round: u64, author: Address<N>) -> bool {
269 self.rounds.read().get(&round).map_or(false, |set| set.iter().any(|(_, _, a)| a == &author))
270 }
271
272 pub fn contains_batch(&self, batch_id: Field<N>) -> bool {
274 self.batch_ids.read().contains_key(&batch_id)
276 }
277
278 pub fn contains_transmission(&self, transmission_id: impl Into<TransmissionID<N>>) -> bool {
280 self.transmissions.contains_transmission(transmission_id.into())
281 }
282
283 pub fn get_transmission(&self, transmission_id: impl Into<TransmissionID<N>>) -> Option<Transmission<N>> {
286 self.transmissions.get_transmission(transmission_id.into())
287 }
288
289 pub fn get_round_for_certificate(&self, certificate_id: Field<N>) -> Option<u64> {
292 self.certificates.read().get(&certificate_id).map(|certificate| certificate.round())
294 }
295
296 pub fn get_round_for_batch(&self, batch_id: Field<N>) -> Option<u64> {
299 self.batch_ids.read().get(&batch_id).copied()
301 }
302
303 pub fn get_certificate_round(&self, certificate_id: Field<N>) -> Option<u64> {
306 self.certificates.read().get(&certificate_id).map(|certificate| certificate.round())
308 }
309
310 pub fn get_certificate(&self, certificate_id: Field<N>) -> Option<BatchCertificate<N>> {
313 self.certificates.read().get(&certificate_id).cloned()
315 }
316
317 pub fn get_certificate_for_round_with_author(&self, round: u64, author: Address<N>) -> Option<BatchCertificate<N>> {
321 if let Some(entries) = self.rounds.read().get(&round) {
323 let certificates = self.certificates.read();
324 entries.iter().find_map(
325 |(certificate_id, _, a)| {
326 if a == &author { certificates.get(certificate_id).cloned() } else { None }
327 },
328 )
329 } else {
330 Default::default()
331 }
332 }
333
334 pub fn get_certificates_for_round(&self, round: u64) -> IndexSet<BatchCertificate<N>> {
337 if round == 0 {
339 return Default::default();
340 }
341 if let Some(entries) = self.rounds.read().get(&round) {
343 let certificates = self.certificates.read();
344 entries.iter().flat_map(|(certificate_id, _, _)| certificates.get(certificate_id).cloned()).collect()
345 } else {
346 Default::default()
347 }
348 }
349
350 pub fn get_certificate_ids_for_round(&self, round: u64) -> IndexSet<Field<N>> {
353 if round == 0 {
355 return Default::default();
356 }
357 if let Some(entries) = self.rounds.read().get(&round) {
359 entries.iter().map(|(certificate_id, _, _)| *certificate_id).collect()
360 } else {
361 Default::default()
362 }
363 }
364
365 pub fn get_certificate_authors_for_round(&self, round: u64) -> HashSet<Address<N>> {
368 if round == 0 {
370 return Default::default();
371 }
372 if let Some(entries) = self.rounds.read().get(&round) {
374 entries.iter().map(|(_, _, author)| *author).collect()
375 } else {
376 Default::default()
377 }
378 }
379
380 pub(crate) fn get_pending_certificates(&self) -> IndexSet<BatchCertificate<N>> {
383 let rounds = self.rounds.read();
385 let certificates = self.certificates.read();
386
387 cfg_sorted_by!(rounds.clone(), |a, _, b, _| a.cmp(b))
389 .flat_map(|(_, certificates_for_round)| {
390 cfg_into_iter!(certificates_for_round).filter_map(|(certificate_id, _, _)| {
392 if self.ledger.contains_certificate(&certificate_id).unwrap_or(false) {
394 None
395 } else {
396 certificates.get(&certificate_id).cloned()
398 }
399 })
400 })
401 .collect()
402 }
403
404 pub fn check_batch_header(
417 &self,
418 batch_header: &BatchHeader<N>,
419 transmissions: HashMap<TransmissionID<N>, Transmission<N>>,
420 aborted_transmissions: HashSet<TransmissionID<N>>,
421 ) -> Result<HashMap<TransmissionID<N>, Transmission<N>>> {
422 let round = batch_header.round();
424 let gc_round = self.gc_round();
426 let gc_log = format!("(gc = {gc_round})");
428
429 if self.contains_batch(batch_header.batch_id()) {
431 bail!("Batch for round {round} already exists in storage {gc_log}")
432 }
433
434 let Ok(committee_lookback) = self.ledger.get_committee_lookback_for_round(round) else {
436 bail!("Storage failed to retrieve the committee lookback for round {round} {gc_log}")
437 };
438 if !committee_lookback.is_committee_member(batch_header.author()) {
440 bail!("Author {} is not in the committee for round {round} {gc_log}", batch_header.author())
441 }
442
443 check_timestamp_for_liveness(batch_header.timestamp())?;
445
446 let missing_transmissions = self
448 .transmissions
449 .find_missing_transmissions(batch_header, transmissions, aborted_transmissions)
450 .map_err(|e| anyhow!("{e} for round {round} {gc_log}"))?;
451
452 let previous_round = round.saturating_sub(1);
454 if previous_round > gc_round {
456 let Ok(previous_committee_lookback) = self.ledger.get_committee_lookback_for_round(previous_round) else {
458 bail!("Missing committee for the previous round {previous_round} in storage {gc_log}")
459 };
460 if !self.contains_certificates_for_round(previous_round) {
462 bail!("Missing certificates for the previous round {previous_round} in storage {gc_log}")
463 }
464 if batch_header.previous_certificate_ids().len() > previous_committee_lookback.num_members() {
466 bail!("Too many previous certificates for round {round} {gc_log}")
467 }
468 let mut previous_authors = HashSet::with_capacity(batch_header.previous_certificate_ids().len());
470 for previous_certificate_id in batch_header.previous_certificate_ids() {
472 let Some(previous_certificate) = self.get_certificate(*previous_certificate_id) else {
474 bail!(
475 "Missing previous certificate '{}' for certificate in round {round} {gc_log}",
476 fmt_id(previous_certificate_id)
477 )
478 };
479 if previous_certificate.round() != previous_round {
481 bail!("Round {round} certificate contains a round {previous_round} certificate {gc_log}")
482 }
483 if previous_authors.contains(&previous_certificate.author()) {
485 bail!("Round {round} certificate contains a duplicate author {gc_log}")
486 }
487 previous_authors.insert(previous_certificate.author());
489 }
490 if !previous_committee_lookback.is_quorum_threshold_reached(&previous_authors) {
492 bail!("Previous certificates for a batch in round {round} did not reach quorum threshold {gc_log}")
493 }
494 }
495 Ok(missing_transmissions)
496 }
497
498 pub fn check_certificate(
514 &self,
515 certificate: &BatchCertificate<N>,
516 transmissions: HashMap<TransmissionID<N>, Transmission<N>>,
517 aborted_transmissions: HashSet<TransmissionID<N>>,
518 ) -> Result<HashMap<TransmissionID<N>, Transmission<N>>> {
519 let round = certificate.round();
521 let gc_round = self.gc_round();
523 let gc_log = format!("(gc = {gc_round})");
525
526 if self.contains_certificate(certificate.id()) {
528 bail!("Certificate for round {round} already exists in storage {gc_log}")
529 }
530
531 if self.contains_certificate_in_round_from(round, certificate.author()) {
533 bail!("Certificate with this author for round {round} already exists in storage {gc_log}")
534 }
535
536 let missing_transmissions =
538 self.check_batch_header(certificate.batch_header(), transmissions, aborted_transmissions)?;
539
540 check_timestamp_for_liveness(certificate.timestamp())?;
542
543 let Ok(committee_lookback) = self.ledger.get_committee_lookback_for_round(round) else {
545 bail!("Storage failed to retrieve the committee for round {round} {gc_log}")
546 };
547
548 let mut signers = HashSet::with_capacity(certificate.signatures().len() + 1);
550 signers.insert(certificate.author());
552
553 for signature in certificate.signatures() {
555 let signer = signature.to_address();
557 if !committee_lookback.is_committee_member(signer) {
559 bail!("Signer {signer} is not in the committee for round {round} {gc_log}")
560 }
561 signers.insert(signer);
563 }
564
565 if !committee_lookback.is_quorum_threshold_reached(&signers) {
567 bail!("Signatures for a batch in round {round} did not reach quorum threshold {gc_log}")
568 }
569 Ok(missing_transmissions)
570 }
571
572 pub fn insert_certificate(
584 &self,
585 certificate: BatchCertificate<N>,
586 transmissions: HashMap<TransmissionID<N>, Transmission<N>>,
587 aborted_transmissions: HashSet<TransmissionID<N>>,
588 ) -> Result<()> {
589 ensure!(certificate.round() > self.gc_round(), "Certificate round is at or below the GC round");
591 let missing_transmissions =
593 self.check_certificate(&certificate, transmissions, aborted_transmissions.clone())?;
594 self.insert_certificate_atomic(certificate, aborted_transmissions, missing_transmissions);
596 Ok(())
597 }
598
599 fn insert_certificate_atomic(
605 &self,
606 certificate: BatchCertificate<N>,
607 aborted_transmission_ids: HashSet<TransmissionID<N>>,
608 missing_transmissions: HashMap<TransmissionID<N>, Transmission<N>>,
609 ) {
610 let round = certificate.round();
612 let certificate_id = certificate.id();
614 let batch_id = certificate.batch_id();
616 let author = certificate.author();
618
619 self.rounds.write().entry(round).or_default().insert((certificate_id, batch_id, author));
621 let transmission_ids = certificate.transmission_ids().clone();
623 self.certificates.write().insert(certificate_id, certificate);
625 self.batch_ids.write().insert(batch_id, round);
627 self.transmissions.insert_transmissions(
629 certificate_id,
630 transmission_ids,
631 aborted_transmission_ids,
632 missing_transmissions,
633 );
634 }
635
636 fn remove_certificate(&self, certificate_id: Field<N>) -> bool {
643 let Some(certificate) = self.get_certificate(certificate_id) else {
645 guard_warn!(self, "Certificate {certificate_id} does not exist in storage");
646 return false;
647 };
648 let round = certificate.round();
650 let batch_id = certificate.batch_id();
652 let author = certificate.author();
654
655 match self.rounds.write().entry(round) {
661 Entry::Occupied(mut entry) => {
662 entry.get_mut().swap_remove(&(certificate_id, batch_id, author));
664 if entry.get().is_empty() {
666 entry.swap_remove();
667 }
668 }
669 Entry::Vacant(_) => {}
670 }
671 self.certificates.write().swap_remove(&certificate_id);
673 self.batch_ids.write().swap_remove(&batch_id);
675 self.transmissions.remove_transmissions(&certificate_id, certificate.transmission_ids());
677 true
679 }
680}
681
682impl<N: Network> Storage<N> {
683 pub(crate) fn sync_height_with_block(&self, next_height: u32) {
685 if next_height > self.current_height() {
687 self.current_height.store(next_height, Ordering::SeqCst);
689 }
690 }
691
692 pub(crate) fn sync_round_with_block(&self, next_round: u64) {
694 let next_round = next_round.max(1);
696 if next_round > self.current_round() {
698 self.update_current_round(next_round);
700 guard_info!(self, "Synced to round {next_round}...");
702 }
703 }
704
705 pub(crate) fn sync_certificate_with_block(
707 &self,
708 block: &Block<N>,
709 certificate: BatchCertificate<N>,
710 unconfirmed_transactions: &HashMap<N::TransactionID, Transaction<N>>,
711 ) {
712 if certificate.round() <= self.gc_round() {
714 return;
715 }
716 if self.contains_certificate(certificate.id()) {
718 return;
719 }
720 let mut missing_transmissions = HashMap::new();
722
723 let mut aborted_transmissions = HashSet::new();
725
726 let aborted_solutions: IndexSet<_> = block.aborted_solution_ids().iter().collect();
728 let aborted_transactions: IndexSet<_> = block.aborted_transaction_ids().iter().collect();
729
730 for transmission_id in certificate.transmission_ids() {
732 if missing_transmissions.contains_key(transmission_id) {
734 continue;
735 }
736 if self.contains_transmission(*transmission_id) {
738 continue;
739 }
740 match transmission_id {
742 TransmissionID::Ratification => (),
743 TransmissionID::Solution(solution_id, _) => {
744 match block.get_solution(solution_id) {
746 Some(solution) => missing_transmissions.insert(*transmission_id, (*solution).into()),
748 None => match self.ledger.get_solution(solution_id) {
750 Ok(solution) => missing_transmissions.insert(*transmission_id, solution.into()),
752 Err(_) => {
754 match aborted_solutions.contains(solution_id)
756 || self.ledger.contains_transmission(transmission_id).unwrap_or(false)
757 {
758 true => {
759 aborted_transmissions.insert(*transmission_id);
760 }
761 false => {
762 guard_error!(self, "Missing solution {solution_id} in block {}", block.height())
763 }
764 }
765 continue;
766 }
767 },
768 };
769 }
770 TransmissionID::Transaction(transaction_id, _) => {
771 match unconfirmed_transactions.get(transaction_id) {
773 Some(transaction) => missing_transmissions.insert(*transmission_id, transaction.clone().into()),
775 None => match self.ledger.get_unconfirmed_transaction(*transaction_id) {
777 Ok(transaction) => missing_transmissions.insert(*transmission_id, transaction.into()),
779 Err(_) => {
781 match aborted_transactions.contains(transaction_id)
783 || self.ledger.contains_transmission(transmission_id).unwrap_or(false)
784 {
785 true => {
786 aborted_transmissions.insert(*transmission_id);
787 }
788 false => guard_warn!(
789 self,
790 "Missing transaction {transaction_id} in block {}",
791 block.height()
792 ),
793 }
794 continue;
795 }
796 },
797 };
798 }
799 }
800 }
801 let certificate_id = fmt_id(certificate.id());
803 guard_debug!(
804 self,
805 "Syncing certificate '{certificate_id}' for round {} with {} transmissions",
806 certificate.round(),
807 certificate.transmission_ids().len()
808 );
809 if let Err(error) = self.insert_certificate(certificate, missing_transmissions, aborted_transmissions) {
810 guard_error!(
811 self,
812 "Failed to insert certificate '{certificate_id}' from block {} - {error}",
813 block.height()
814 );
815 }
816 }
817}
818
819#[cfg(test)]
820impl<N: Network> Storage<N> {
821 pub fn ledger(&self) -> &Arc<dyn LedgerService<N>> {
823 &self.ledger
824 }
825
826 pub fn rounds_iter(&self) -> impl Iterator<Item = (u64, IndexSet<(Field<N>, Field<N>, Address<N>)>)> {
828 self.rounds.read().clone().into_iter()
829 }
830
831 pub fn certificates_iter(&self) -> impl Iterator<Item = (Field<N>, BatchCertificate<N>)> {
833 self.certificates.read().clone().into_iter()
834 }
835
836 pub fn batch_ids_iter(&self) -> impl Iterator<Item = (Field<N>, u64)> {
838 self.batch_ids.read().clone().into_iter()
839 }
840
841 pub fn transmissions_iter(
843 &self,
844 ) -> impl Iterator<Item = (TransmissionID<N>, (Transmission<N>, IndexSet<Field<N>>))> {
845 self.transmissions.as_hashmap().into_iter()
846 }
847
848 #[cfg(test)]
852 #[doc(hidden)]
853 pub(crate) fn testing_only_insert_certificate_testing_only(&self, certificate: BatchCertificate<N>) {
854 let round = certificate.round();
856 let certificate_id = certificate.id();
858 let batch_id = certificate.batch_id();
860 let author = certificate.author();
862
863 self.rounds.write().entry(round).or_default().insert((certificate_id, batch_id, author));
865 let transmission_ids = certificate.transmission_ids().clone();
867 self.certificates.write().insert(certificate_id, certificate);
869 self.batch_ids.write().insert(batch_id, round);
871
872 let missing_transmissions = transmission_ids
874 .iter()
875 .map(|id| (*id, Transmission::Transaction(snarkvm::ledger::narwhal::Data::Buffer(bytes::Bytes::new()))))
876 .collect::<HashMap<_, _>>();
877 self.transmissions.insert_transmissions(
879 certificate_id,
880 transmission_ids,
881 Default::default(),
882 missing_transmissions,
883 );
884 }
885}
886
887#[cfg(test)]
888pub(crate) mod tests {
889 use super::*;
890 use amareleo_node_bft_ledger_service::MockLedgerService;
891 use amareleo_node_bft_storage_service::BFTMemoryService;
892 use snarkvm::{
893 ledger::narwhal::Data,
894 prelude::{Rng, TestRng},
895 };
896
897 use ::bytes::Bytes;
898 use indexmap::indexset;
899
900 type CurrentNetwork = snarkvm::prelude::MainnetV0;
901
902 pub fn assert_storage<N: Network>(
904 storage: &Storage<N>,
905 rounds: &[(u64, IndexSet<(Field<N>, Field<N>, Address<N>)>)],
906 certificates: &[(Field<N>, BatchCertificate<N>)],
907 batch_ids: &[(Field<N>, u64)],
908 transmissions: &HashMap<TransmissionID<N>, (Transmission<N>, IndexSet<Field<N>>)>,
909 ) {
910 assert_eq!(storage.rounds_iter().collect::<Vec<_>>(), *rounds);
912 assert_eq!(storage.certificates_iter().collect::<Vec<_>>(), *certificates);
914 assert_eq!(storage.batch_ids_iter().collect::<Vec<_>>(), *batch_ids);
916 assert_eq!(storage.transmissions_iter().collect::<HashMap<_, _>>(), *transmissions);
918 }
919
920 fn sample_transmission(rng: &mut TestRng) -> Transmission<CurrentNetwork> {
922 let s = |rng: &mut TestRng| Data::Buffer(Bytes::from((0..512).map(|_| rng.gen::<u8>()).collect::<Vec<_>>()));
924 let t = |rng: &mut TestRng| Data::Buffer(Bytes::from((0..2048).map(|_| rng.gen::<u8>()).collect::<Vec<_>>()));
926 match rng.gen::<bool>() {
928 true => Transmission::Solution(s(rng)),
929 false => Transmission::Transaction(t(rng)),
930 }
931 }
932
933 pub(crate) fn sample_transmissions(
935 certificate: &BatchCertificate<CurrentNetwork>,
936 rng: &mut TestRng,
937 ) -> (
938 HashMap<TransmissionID<CurrentNetwork>, Transmission<CurrentNetwork>>,
939 HashMap<TransmissionID<CurrentNetwork>, (Transmission<CurrentNetwork>, IndexSet<Field<CurrentNetwork>>)>,
940 ) {
941 let certificate_id = certificate.id();
943
944 let mut missing_transmissions = HashMap::new();
945 let mut transmissions = HashMap::<_, (_, IndexSet<Field<CurrentNetwork>>)>::new();
946 for transmission_id in certificate.transmission_ids() {
947 let transmission = sample_transmission(rng);
949 missing_transmissions.insert(*transmission_id, transmission.clone());
951 transmissions
953 .entry(*transmission_id)
954 .or_insert((transmission, Default::default()))
955 .1
956 .insert(certificate_id);
957 }
958 (missing_transmissions, transmissions)
959 }
960
961 #[test]
964 fn test_certificate_insert_remove() {
965 let rng = &mut TestRng::default();
966
967 let committee = snarkvm::ledger::committee::test_helpers::sample_committee(rng);
969 let ledger = Arc::new(MockLedgerService::new(committee));
971 let storage = Storage::<CurrentNetwork>::new(ledger, Arc::new(BFTMemoryService::new()), 1, None);
973
974 assert_storage(&storage, &[], &[], &[], &Default::default());
976
977 let certificate = snarkvm::ledger::narwhal::batch_certificate::test_helpers::sample_batch_certificate(rng);
979 let certificate_id = certificate.id();
981 let round = certificate.round();
983 let batch_id = certificate.batch_id();
985 let author = certificate.author();
987
988 let (missing_transmissions, transmissions) = sample_transmissions(&certificate, rng);
990
991 storage.insert_certificate_atomic(certificate.clone(), Default::default(), missing_transmissions);
993 assert!(storage.contains_certificate(certificate_id));
995 assert_eq!(storage.get_certificates_for_round(round), indexset! { certificate.clone() });
997 assert_eq!(storage.get_certificate_for_round_with_author(round, author), Some(certificate.clone()));
999
1000 {
1002 let rounds = [(round, indexset! { (certificate_id, batch_id, author) })];
1004 let certificates = [(certificate_id, certificate.clone())];
1006 let batch_ids = [(batch_id, round)];
1008 assert_storage(&storage, &rounds, &certificates, &batch_ids, &transmissions);
1010 }
1011
1012 let candidate_certificate = storage.get_certificate(certificate_id).unwrap();
1014 assert_eq!(certificate, candidate_certificate);
1016
1017 assert!(storage.remove_certificate(certificate_id));
1019 assert!(!storage.contains_certificate(certificate_id));
1021 assert!(storage.get_certificates_for_round(round).is_empty());
1023 assert_eq!(storage.get_certificate_for_round_with_author(round, author), None);
1025 assert_storage(&storage, &[], &[], &[], &Default::default());
1027 }
1028
1029 #[test]
1030 fn test_certificate_duplicate() {
1031 let rng = &mut TestRng::default();
1032
1033 let committee = snarkvm::ledger::committee::test_helpers::sample_committee(rng);
1035 let ledger = Arc::new(MockLedgerService::new(committee));
1037 let storage = Storage::<CurrentNetwork>::new(ledger, Arc::new(BFTMemoryService::new()), 1, None);
1039
1040 assert_storage(&storage, &[], &[], &[], &Default::default());
1042
1043 let certificate = snarkvm::ledger::narwhal::batch_certificate::test_helpers::sample_batch_certificate(rng);
1045 let certificate_id = certificate.id();
1047 let round = certificate.round();
1049 let batch_id = certificate.batch_id();
1051 let author = certificate.author();
1053
1054 let rounds = [(round, indexset! { (certificate_id, batch_id, author) })];
1056 let certificates = [(certificate_id, certificate.clone())];
1058 let batch_ids = [(batch_id, round)];
1060 let (missing_transmissions, transmissions) = sample_transmissions(&certificate, rng);
1062
1063 storage.insert_certificate_atomic(certificate.clone(), Default::default(), missing_transmissions.clone());
1065 assert!(storage.contains_certificate(certificate_id));
1067 assert_storage(&storage, &rounds, &certificates, &batch_ids, &transmissions);
1069
1070 storage.insert_certificate_atomic(certificate.clone(), Default::default(), Default::default());
1072 assert!(storage.contains_certificate(certificate_id));
1074 assert_storage(&storage, &rounds, &certificates, &batch_ids, &transmissions);
1076
1077 storage.insert_certificate_atomic(certificate, Default::default(), missing_transmissions);
1079 assert!(storage.contains_certificate(certificate_id));
1081 assert_storage(&storage, &rounds, &certificates, &batch_ids, &transmissions);
1083 }
1084}
1085
1086#[cfg(test)]
1087pub mod prop_tests {
1088 use super::*;
1089 use crate::helpers::{now, storage::tests::assert_storage};
1090 use amareleo_node_bft_ledger_service::MockLedgerService;
1091 use amareleo_node_bft_storage_service::BFTMemoryService;
1092 use snarkvm::{
1093 ledger::{
1094 committee::prop_tests::{CommitteeContext, ValidatorSet},
1095 narwhal::{BatchHeader, Data},
1096 puzzle::SolutionID,
1097 },
1098 prelude::{Signature, Uniform},
1099 };
1100
1101 use ::bytes::Bytes;
1102 use indexmap::indexset;
1103 use proptest::{
1104 collection,
1105 prelude::{Arbitrary, BoxedStrategy, Just, Strategy, any},
1106 prop_oneof,
1107 sample::{Selector, size_range},
1108 test_runner::TestRng,
1109 };
1110 use rand::{CryptoRng, Error, Rng, RngCore};
1111 use std::fmt::Debug;
1112 use test_strategy::proptest;
1113
1114 type CurrentNetwork = snarkvm::prelude::MainnetV0;
1115
1116 impl Arbitrary for Storage<CurrentNetwork> {
1117 type Parameters = CommitteeContext;
1118 type Strategy = BoxedStrategy<Storage<CurrentNetwork>>;
1119
1120 fn arbitrary() -> Self::Strategy {
1121 (any::<CommitteeContext>(), 0..BatchHeader::<CurrentNetwork>::MAX_GC_ROUNDS as u64)
1122 .prop_map(|(CommitteeContext(committee, _), gc_rounds)| {
1123 let ledger = Arc::new(MockLedgerService::new(committee));
1124 Storage::<CurrentNetwork>::new(ledger, Arc::new(BFTMemoryService::new()), gc_rounds, None)
1125 })
1126 .boxed()
1127 }
1128
1129 fn arbitrary_with(context: Self::Parameters) -> Self::Strategy {
1130 (Just(context), 0..BatchHeader::<CurrentNetwork>::MAX_GC_ROUNDS as u64)
1131 .prop_map(|(CommitteeContext(committee, _), gc_rounds)| {
1132 let ledger = Arc::new(MockLedgerService::new(committee));
1133 Storage::<CurrentNetwork>::new(ledger, Arc::new(BFTMemoryService::new()), gc_rounds, None)
1134 })
1135 .boxed()
1136 }
1137 }
1138
1139 #[derive(Debug)]
1141 pub struct CryptoTestRng(TestRng);
1142
1143 impl Arbitrary for CryptoTestRng {
1144 type Parameters = ();
1145 type Strategy = BoxedStrategy<CryptoTestRng>;
1146
1147 fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
1148 Just(0).prop_perturb(|_, rng| CryptoTestRng(rng)).boxed()
1149 }
1150 }
1151 impl RngCore for CryptoTestRng {
1152 fn next_u32(&mut self) -> u32 {
1153 self.0.next_u32()
1154 }
1155
1156 fn next_u64(&mut self) -> u64 {
1157 self.0.next_u64()
1158 }
1159
1160 fn fill_bytes(&mut self, dest: &mut [u8]) {
1161 self.0.fill_bytes(dest);
1162 }
1163
1164 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> std::result::Result<(), Error> {
1165 self.0.try_fill_bytes(dest)
1166 }
1167 }
1168
1169 impl CryptoRng for CryptoTestRng {}
1170
1171 #[derive(Debug, Clone)]
1172 pub struct AnyTransmission(pub Transmission<CurrentNetwork>);
1173
1174 impl Arbitrary for AnyTransmission {
1175 type Parameters = ();
1176 type Strategy = BoxedStrategy<AnyTransmission>;
1177
1178 fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
1179 any_transmission().prop_map(AnyTransmission).boxed()
1180 }
1181 }
1182
1183 #[derive(Debug, Clone)]
1184 pub struct AnyTransmissionID(pub TransmissionID<CurrentNetwork>);
1185
1186 impl Arbitrary for AnyTransmissionID {
1187 type Parameters = ();
1188 type Strategy = BoxedStrategy<AnyTransmissionID>;
1189
1190 fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
1191 any_transmission_id().prop_map(AnyTransmissionID).boxed()
1192 }
1193 }
1194
1195 fn any_transmission() -> BoxedStrategy<Transmission<CurrentNetwork>> {
1196 prop_oneof![
1197 (collection::vec(any::<u8>(), 512..=512))
1198 .prop_map(|bytes| Transmission::Solution(Data::Buffer(Bytes::from(bytes)))),
1199 (collection::vec(any::<u8>(), 2048..=2048))
1200 .prop_map(|bytes| Transmission::Transaction(Data::Buffer(Bytes::from(bytes)))),
1201 ]
1202 .boxed()
1203 }
1204
1205 pub fn any_solution_id() -> BoxedStrategy<SolutionID<CurrentNetwork>> {
1206 Just(0).prop_perturb(|_, rng| CryptoTestRng(rng).gen::<u64>().into()).boxed()
1207 }
1208
1209 pub fn any_transaction_id() -> BoxedStrategy<<CurrentNetwork as Network>::TransactionID> {
1210 Just(0)
1211 .prop_perturb(|_, rng| {
1212 <CurrentNetwork as Network>::TransactionID::from(Field::rand(&mut CryptoTestRng(rng)))
1213 })
1214 .boxed()
1215 }
1216
1217 pub fn any_transmission_id() -> BoxedStrategy<TransmissionID<CurrentNetwork>> {
1218 prop_oneof![
1219 any_transaction_id().prop_perturb(|id, mut rng| TransmissionID::Transaction(
1220 id,
1221 rng.gen::<<CurrentNetwork as Network>::TransmissionChecksum>()
1222 )),
1223 any_solution_id().prop_perturb(|id, mut rng| TransmissionID::Solution(
1224 id,
1225 rng.gen::<<CurrentNetwork as Network>::TransmissionChecksum>()
1226 )),
1227 ]
1228 .boxed()
1229 }
1230
1231 pub fn sign_batch_header<R: Rng + CryptoRng>(
1232 validator_set: &ValidatorSet,
1233 batch_header: &BatchHeader<CurrentNetwork>,
1234 rng: &mut R,
1235 ) -> IndexSet<Signature<CurrentNetwork>> {
1236 let mut signatures = IndexSet::with_capacity(validator_set.0.len());
1237 for validator in validator_set.0.iter() {
1238 let private_key = validator.private_key;
1239 signatures.insert(private_key.sign(&[batch_header.batch_id()], rng).unwrap());
1240 }
1241 signatures
1242 }
1243
1244 #[proptest]
1245 fn test_certificate_duplicate(
1246 context: CommitteeContext,
1247 #[any(size_range(1..16).lift())] transmissions: Vec<(AnyTransmissionID, AnyTransmission)>,
1248 mut rng: CryptoTestRng,
1249 selector: Selector,
1250 ) {
1251 let CommitteeContext(committee, ValidatorSet(validators)) = context;
1252 let committee_id = committee.id();
1253
1254 let ledger = Arc::new(MockLedgerService::new(committee));
1256 let storage = Storage::<CurrentNetwork>::new(ledger, Arc::new(BFTMemoryService::new()), 1, None);
1257
1258 assert_storage(&storage, &[], &[], &[], &Default::default());
1260
1261 let signer = selector.select(&validators);
1263
1264 let mut transmission_map = IndexMap::new();
1265
1266 for (AnyTransmissionID(id), AnyTransmission(t)) in transmissions.iter() {
1267 transmission_map.insert(*id, t.clone());
1268 }
1269
1270 let batch_header = BatchHeader::new(
1271 &signer.private_key,
1272 0,
1273 now(),
1274 committee_id,
1275 transmission_map.keys().cloned().collect(),
1276 Default::default(),
1277 &mut rng,
1278 )
1279 .unwrap();
1280
1281 let mut validators = validators.clone();
1284 validators.remove(signer);
1285
1286 let certificate = BatchCertificate::from(
1287 batch_header.clone(),
1288 sign_batch_header(&ValidatorSet(validators), &batch_header, &mut rng),
1289 )
1290 .unwrap();
1291
1292 let certificate_id = certificate.id();
1294 let mut internal_transmissions = HashMap::<_, (_, IndexSet<Field<CurrentNetwork>>)>::new();
1295 for (AnyTransmissionID(id), AnyTransmission(t)) in transmissions.iter().cloned() {
1296 internal_transmissions.entry(id).or_insert((t, Default::default())).1.insert(certificate_id);
1297 }
1298
1299 let round = certificate.round();
1301 let batch_id = certificate.batch_id();
1303 let author = certificate.author();
1305
1306 let rounds = [(round, indexset! { (certificate_id, batch_id, author) })];
1308 let certificates = [(certificate_id, certificate.clone())];
1310 let batch_ids = [(batch_id, round)];
1312
1313 let missing_transmissions: HashMap<TransmissionID<CurrentNetwork>, Transmission<CurrentNetwork>> =
1315 transmission_map.into_iter().collect();
1316 storage.insert_certificate_atomic(certificate.clone(), Default::default(), missing_transmissions.clone());
1317 assert!(storage.contains_certificate(certificate_id));
1319 assert_storage(&storage, &rounds, &certificates, &batch_ids, &internal_transmissions);
1321
1322 storage.insert_certificate_atomic(certificate.clone(), Default::default(), Default::default());
1324 assert!(storage.contains_certificate(certificate_id));
1326 assert_storage(&storage, &rounds, &certificates, &batch_ids, &internal_transmissions);
1328
1329 storage.insert_certificate_atomic(certificate, Default::default(), missing_transmissions);
1331 assert!(storage.contains_certificate(certificate_id));
1333 assert_storage(&storage, &rounds, &certificates, &batch_ids, &internal_transmissions);
1335 }
1336}