1use std::collections::BTreeMap;
72
73use allocative::Allocative;
74use custom_debug_derive::Debug;
75use futures::future::Either;
76use linera_base::{
77 crypto::{AccountPublicKey, CryptoError, ValidatorSecretKey},
78 data_types::{Blob, BlockHeight, Epoch, Round, Timestamp},
79 ensure,
80 identifiers::{AccountOwner, BlobId, ChainId},
81 ownership::ChainOwnership,
82};
83use linera_execution::ExecutionRuntimeContext;
84use linera_views::{
85 context::Context,
86 map_view::MapView,
87 register_view::RegisterView,
88 views::{ClonableView, View},
89 ViewError,
90};
91use rand_chacha::{rand_core::SeedableRng, ChaCha8Rng};
92use rand_distr::{Distribution, WeightedAliasIndex};
93use serde::{Deserialize, Serialize};
94
95use crate::{
96 block::{Block, ConfirmedBlock, Timeout, ValidatedBlock},
97 data_types::{BlockProposal, LiteVote, OriginalProposal, ProposedBlock, Vote},
98 types::{TimeoutCertificate, ValidatedBlockCertificate},
99 ChainError,
100};
101
102#[derive(Eq, PartialEq)]
104pub enum Outcome {
105 Accept,
106 Skip,
107}
108
109pub type ValidatedOrConfirmedVote<'a> = Either<&'a Vote<ValidatedBlock>, &'a Vote<ConfirmedBlock>>;
110
111#[derive(Debug, Clone, Serialize, Deserialize, Allocative)]
115#[cfg_attr(with_testing, derive(Eq, PartialEq))]
116pub enum LockingBlock {
117 Fast(BlockProposal),
119 Regular(ValidatedBlockCertificate),
121}
122
123impl LockingBlock {
124 pub fn round(&self) -> Round {
127 match self {
128 Self::Fast(_) => Round::Fast,
129 Self::Regular(certificate) => certificate.round,
130 }
131 }
132
133 pub fn chain_id(&self) -> ChainId {
134 match self {
135 Self::Fast(proposal) => proposal.content.block.chain_id,
136 Self::Regular(certificate) => certificate.value().chain_id(),
137 }
138 }
139}
140
141#[cfg_attr(with_graphql, derive(async_graphql::SimpleObject), graphql(complex))]
143#[derive(Debug, View, ClonableView, Allocative)]
144#[allocative(bound = "C")]
145pub struct ChainManager<C>
146where
147 C: Clone + Context + Send + Sync + 'static,
148{
149 pub ownership: RegisterView<C, ChainOwnership>,
151 pub seed: RegisterView<C, u64>,
153 #[cfg_attr(with_graphql, graphql(skip))] #[allocative(skip)]
156 pub distribution: RegisterView<C, Option<WeightedAliasIndex<u64>>>,
157 #[cfg_attr(with_graphql, graphql(skip))] #[allocative(skip)]
160 pub fallback_distribution: RegisterView<C, Option<WeightedAliasIndex<u64>>>,
161 #[cfg_attr(with_graphql, graphql(skip))]
166 pub signed_proposal: RegisterView<C, Option<BlockProposal>>,
167 #[cfg_attr(with_graphql, graphql(skip))]
170 pub proposed: RegisterView<C, Option<BlockProposal>>,
171 pub proposed_blobs: MapView<C, BlobId, Blob>,
173 #[cfg_attr(with_graphql, graphql(skip))]
176 pub locking_block: RegisterView<C, Option<LockingBlock>>,
177 pub locking_blobs: MapView<C, BlobId, Blob>,
179 #[cfg_attr(with_graphql, graphql(skip))]
181 pub timeout: RegisterView<C, Option<TimeoutCertificate>>,
182 #[cfg_attr(with_graphql, graphql(skip))]
184 pub confirmed_vote: RegisterView<C, Option<Vote<ConfirmedBlock>>>,
185 #[cfg_attr(with_graphql, graphql(skip))]
187 pub validated_vote: RegisterView<C, Option<Vote<ValidatedBlock>>>,
188 #[cfg_attr(with_graphql, graphql(skip))]
190 pub timeout_vote: RegisterView<C, Option<Vote<Timeout>>>,
191 #[cfg_attr(with_graphql, graphql(skip))]
193 pub fallback_vote: RegisterView<C, Option<Vote<Timeout>>>,
194 pub round_timeout: RegisterView<C, Option<Timestamp>>,
196 #[cfg_attr(with_graphql, graphql(skip))]
203 pub current_round: RegisterView<C, Round>,
204 pub fallback_owners: RegisterView<C, BTreeMap<AccountOwner, u64>>,
206}
207
208#[cfg(with_graphql)]
209#[async_graphql::ComplexObject]
210impl<C> ChainManager<C>
211where
212 C: Context + Clone + Send + Sync + 'static,
213{
214 #[graphql(derived(name = "current_round"))]
221 async fn _current_round(&self) -> Round {
222 self.current_round()
223 }
224}
225
226impl<C> ChainManager<C>
227where
228 C: Context + Clone + Send + Sync + 'static,
229{
230 pub fn reset<'a>(
232 &mut self,
233 ownership: ChainOwnership,
234 height: BlockHeight,
235 local_time: Timestamp,
236 fallback_owners: impl Iterator<Item = (AccountPublicKey, u64)> + 'a,
237 ) -> Result<(), ChainError> {
238 let distribution = calculate_distribution(ownership.owners.iter());
239
240 let fallback_owners = fallback_owners
241 .map(|(pub_key, weight)| (AccountOwner::from(pub_key), weight))
242 .collect::<BTreeMap<_, _>>();
243 let fallback_distribution = calculate_distribution(fallback_owners.iter());
244
245 let current_round = ownership.first_round();
246 let round_duration = ownership.round_timeout(current_round);
247 let round_timeout = round_duration.map(|rd| local_time.saturating_add(rd));
248
249 self.clear();
250 self.seed.set(height.0);
251 self.ownership.set(ownership);
252 self.distribution.set(distribution);
253 self.fallback_distribution.set(fallback_distribution);
254 self.fallback_owners.set(fallback_owners);
255 self.current_round.set(current_round);
256 self.round_timeout.set(round_timeout);
257 Ok(())
258 }
259
260 pub fn confirmed_vote(&self) -> Option<&Vote<ConfirmedBlock>> {
262 self.confirmed_vote.get().as_ref()
263 }
264
265 pub fn validated_vote(&self) -> Option<&Vote<ValidatedBlock>> {
267 self.validated_vote.get().as_ref()
268 }
269
270 pub fn timeout_vote(&self) -> Option<&Vote<Timeout>> {
272 self.timeout_vote.get().as_ref()
273 }
274
275 pub fn fallback_vote(&self) -> Option<&Vote<Timeout>> {
277 self.fallback_vote.get().as_ref()
278 }
279
280 pub fn current_round(&self) -> Round {
287 *self.current_round.get()
288 }
289
290 pub fn check_proposed_block(&self, proposal: &BlockProposal) -> Result<Outcome, ChainError> {
292 let new_block = &proposal.content.block;
293 let new_round = proposal.content.round;
294 if let Some(old_proposal) = self.proposed.get() {
295 if old_proposal.content == proposal.content {
296 return Ok(Outcome::Skip); }
298 }
299 ensure!(
301 new_block.height < BlockHeight::MAX,
302 ChainError::BlockHeightOverflow
303 );
304 let current_round = self.current_round();
305 match new_round {
306 Round::Fast => {}
309 Round::MultiLeader(_) | Round::SingleLeader(0) => {
310 ensure!(
313 self.is_super(&proposal.owner()) || !current_round.is_fast(),
314 ChainError::WrongRound(current_round)
315 );
316 ensure!(
318 new_round >= current_round,
319 ChainError::InsufficientRound(new_round)
320 );
321 }
322 Round::SingleLeader(_) | Round::Validator(_) => {
323 ensure!(
325 new_round == current_round,
326 ChainError::WrongRound(current_round)
327 );
328 }
329 }
330 if let Some(vote) = self.validated_vote() {
332 ensure!(
333 new_round > vote.round,
334 ChainError::InsufficientRoundStrict(vote.round)
335 );
336 }
337 if let Some(locking_block) = self.locking_block.get() {
339 ensure!(
340 locking_block.round() < new_round,
341 ChainError::MustBeNewerThanLockingBlock(new_block.height, locking_block.round())
342 );
343 }
344 if let Some(vote) = self.confirmed_vote() {
347 ensure!(
348 match proposal.original_proposal.as_ref() {
349 None => false,
350 Some(OriginalProposal::Regular { certificate }) =>
351 vote.round <= certificate.round,
352 Some(OriginalProposal::Fast(_)) => {
353 vote.round.is_fast() && vote.value().matches_proposed_block(new_block)
354 }
355 },
356 ChainError::HasIncompatibleConfirmedVote(new_block.height, vote.round)
357 );
358 }
359 Ok(Outcome::Accept)
360 }
361
362 pub fn create_timeout_vote(
365 &mut self,
366 chain_id: ChainId,
367 height: BlockHeight,
368 round: Round,
369 epoch: Epoch,
370 key_pair: Option<&ValidatorSecretKey>,
371 local_time: Timestamp,
372 ) -> Result<bool, ChainError> {
373 let Some(key_pair) = key_pair else {
374 return Ok(false); };
376 ensure!(
377 round == self.current_round(),
378 ChainError::WrongRound(self.current_round())
379 );
380 let Some(round_timeout) = *self.round_timeout.get() else {
381 return Err(ChainError::RoundDoesNotTimeOut);
382 };
383 ensure!(
384 local_time >= round_timeout,
385 ChainError::NotTimedOutYet(round_timeout)
386 );
387 if let Some(vote) = self.timeout_vote.get() {
388 if vote.round == round {
389 return Ok(false); }
391 }
392 let value = Timeout::new(chain_id, height, epoch);
393 self.timeout_vote
394 .set(Some(Vote::new(value, round, key_pair)));
395 Ok(true)
396 }
397
398 pub fn vote_fallback(
403 &mut self,
404 chain_id: ChainId,
405 height: BlockHeight,
406 epoch: Epoch,
407 key_pair: Option<&ValidatorSecretKey>,
408 ) -> bool {
409 let Some(key_pair) = key_pair else {
410 return false; };
412 if self.fallback_vote.get().is_some() || self.current_round() >= Round::Validator(0) {
413 return false; }
415 let value = Timeout::new(chain_id, height, epoch);
416 let last_regular_round = Round::SingleLeader(u32::MAX);
417 self.fallback_vote
418 .set(Some(Vote::new(value, last_regular_round, key_pair)));
419 true
420 }
421
422 pub fn check_validated_block(
424 &self,
425 certificate: &ValidatedBlockCertificate,
426 ) -> Result<Outcome, ChainError> {
427 let new_block = certificate.block();
428 let new_round = certificate.round;
429 if let Some(Vote { value, round, .. }) = self.confirmed_vote.get() {
430 if value.block() == new_block && *round == new_round {
431 return Ok(Outcome::Skip); }
433 }
434
435 if let Some(Vote { round, .. }) = self.validated_vote.get() {
437 ensure!(new_round >= *round, ChainError::InsufficientRound(*round))
438 }
439
440 if let Some(locking) = self.locking_block.get() {
441 ensure!(
442 new_round > locking.round(),
443 ChainError::InsufficientRoundStrict(locking.round())
444 );
445 }
446 Ok(Outcome::Accept)
447 }
448
449 pub fn create_vote(
451 &mut self,
452 proposal: BlockProposal,
453 block: Block,
454 key_pair: Option<&ValidatorSecretKey>,
455 local_time: Timestamp,
456 blobs: BTreeMap<BlobId, Blob>,
457 ) -> Result<Option<ValidatedOrConfirmedVote>, ChainError> {
458 let round = proposal.content.round;
459
460 match &proposal.original_proposal {
461 Some(OriginalProposal::Regular { certificate }) => {
463 if self
464 .locking_block
465 .get()
466 .as_ref()
467 .is_none_or(|locking| locking.round() < certificate.round)
468 {
469 let value = ValidatedBlock::new(block.clone());
470 if let Some(certificate) = certificate.clone().with_value(value) {
471 self.update_locking(LockingBlock::Regular(certificate), blobs.clone())?;
472 }
473 }
474 }
475 Some(OriginalProposal::Fast(signature)) => {
478 if self.locking_block.get().is_none() {
479 let original_proposal = BlockProposal {
480 signature: *signature,
481 ..proposal.clone()
482 };
483 self.update_locking(LockingBlock::Fast(original_proposal), blobs.clone())?;
484 }
485 }
486 None => {
489 if round.is_fast() && self.locking_block.get().is_none() {
490 self.update_locking(LockingBlock::Fast(proposal.clone()), blobs.clone())?;
492 }
493 }
494 }
495
496 self.update_proposed(proposal.clone(), blobs)?;
498 self.update_current_round(local_time);
499
500 let Some(key_pair) = key_pair else {
501 return Ok(None);
503 };
504
505 if round.is_fast() {
507 self.validated_vote.set(None);
508 let value = ConfirmedBlock::new(block);
509 let vote = Vote::new(value, round, key_pair);
510 Ok(Some(Either::Right(
511 self.confirmed_vote.get_mut().insert(vote),
512 )))
513 } else {
514 let value = ValidatedBlock::new(block);
515 let vote = Vote::new(value, round, key_pair);
516 Ok(Some(Either::Left(
517 self.validated_vote.get_mut().insert(vote),
518 )))
519 }
520 }
521
522 pub fn create_final_vote(
524 &mut self,
525 validated: ValidatedBlockCertificate,
526 key_pair: Option<&ValidatorSecretKey>,
527 local_time: Timestamp,
528 blobs: BTreeMap<BlobId, Blob>,
529 ) -> Result<(), ViewError> {
530 let round = validated.round;
531 let confirmed_block = ConfirmedBlock::new(validated.inner().block().clone());
532 self.update_locking(LockingBlock::Regular(validated), blobs)?;
533 self.update_current_round(local_time);
534 if let Some(key_pair) = key_pair {
535 if self.current_round() != round {
536 return Ok(()); }
538 let vote = Vote::new(confirmed_block, round, key_pair);
540 self.confirmed_vote.set(Some(vote));
542 self.validated_vote.set(None);
543 }
544 Ok(())
545 }
546
547 pub async fn pending_blob(&self, blob_id: &BlobId) -> Result<Option<Blob>, ViewError> {
549 if let Some(blob) = self.proposed_blobs.get(blob_id).await? {
550 return Ok(Some(blob));
551 }
552 self.locking_blobs.get(blob_id).await
553 }
554
555 fn update_current_round(&mut self, local_time: Timestamp) {
573 let current_round = self
574 .timeout
575 .get()
576 .iter()
577 .map(|certificate| {
579 self.ownership
580 .get()
581 .next_round(certificate.round)
582 .unwrap_or(Round::Validator(u32::MAX))
583 })
584 .chain(self.locking_block.get().as_ref().map(LockingBlock::round))
587 .chain(
588 self.proposed
589 .get()
590 .iter()
591 .chain(self.signed_proposal.get())
592 .map(|proposal| proposal.content.round),
593 )
594 .max()
595 .unwrap_or_default()
596 .max(self.ownership.get().first_round());
598 if current_round <= self.current_round() {
599 return;
600 }
601 let round_duration = self.ownership.get().round_timeout(current_round);
602 self.round_timeout
603 .set(round_duration.map(|rd| local_time.saturating_add(rd)));
604 self.current_round.set(current_round);
605 }
606
607 pub fn handle_timeout_certificate(
610 &mut self,
611 certificate: TimeoutCertificate,
612 local_time: Timestamp,
613 ) {
614 let round = certificate.round;
615 if let Some(known_certificate) = self.timeout.get() {
616 if known_certificate.round >= round {
617 return;
618 }
619 }
620 self.timeout.set(Some(certificate));
621 self.update_current_round(local_time);
622 }
623
624 pub fn verify_owner(
627 &self,
628 proposal_owner: &AccountOwner,
629 proposal_round: Round,
630 ) -> Result<bool, CryptoError> {
631 if self.ownership.get().super_owners.contains(proposal_owner) {
632 return Ok(true);
633 }
634
635 Ok(match proposal_round {
636 Round::Fast => {
637 false }
639 Round::MultiLeader(_) => {
640 let ownership = self.ownership.get();
641 ownership.open_multi_leader_rounds || ownership.owners.contains_key(proposal_owner)
643 }
644 Round::SingleLeader(r) => {
645 let Some(index) =
646 round_leader_index(r, *self.seed.get(), self.distribution.get().as_ref())
647 else {
648 return Ok(false);
649 };
650 self.ownership.get().owners.keys().nth(index) == Some(proposal_owner)
651 }
652 Round::Validator(r) => {
653 let Some(index) = round_leader_index(
654 r,
655 *self.seed.get(),
656 self.fallback_distribution.get().as_ref(),
657 ) else {
658 return Ok(false);
659 };
660 self.fallback_owners.get().keys().nth(index) == Some(proposal_owner)
661 }
662 })
663 }
664
665 fn round_leader(&self, round: Round) -> Option<&AccountOwner> {
668 match round {
669 Round::SingleLeader(r) => {
670 let index =
671 round_leader_index(r, *self.seed.get(), self.distribution.get().as_ref())?;
672 self.ownership.get().owners.keys().nth(index)
673 }
674 Round::Validator(r) => {
675 let index = round_leader_index(
676 r,
677 *self.seed.get(),
678 self.fallback_distribution.get().as_ref(),
679 )?;
680 self.fallback_owners.get().keys().nth(index)
681 }
682 Round::Fast | Round::MultiLeader(_) => None,
683 }
684 }
685
686 fn is_super(&self, owner: &AccountOwner) -> bool {
688 self.ownership.get().super_owners.contains(owner)
689 }
690
691 pub fn update_signed_proposal(
697 &mut self,
698 proposal: &BlockProposal,
699 local_time: Timestamp,
700 ) -> bool {
701 if proposal.content.round > Round::SingleLeader(0) {
702 return false;
703 }
704 if let Some(old_proposal) = self.signed_proposal.get() {
705 if old_proposal.content.round >= proposal.content.round {
706 if *self.current_round.get() < old_proposal.content.round {
707 tracing::warn!(
708 chain_id = %proposal.content.block.chain_id,
709 current_round = ?self.current_round.get(),
710 proposal_round = ?old_proposal.content.round,
711 "Proposal round is greater than current round. Updating."
712 );
713 self.update_current_round(local_time);
714 return true;
715 }
716 return false;
717 }
718 }
719 if let Some(old_proposal) = self.proposed.get() {
720 if old_proposal.content.round >= proposal.content.round {
721 return false;
722 }
723 }
724 self.signed_proposal.set(Some(proposal.clone()));
725 self.update_current_round(local_time);
726 true
727 }
728
729 fn update_proposed(
731 &mut self,
732 proposal: BlockProposal,
733 blobs: BTreeMap<BlobId, Blob>,
734 ) -> Result<(), ViewError> {
735 if let Some(old_proposal) = self.proposed.get() {
736 if old_proposal.content.round >= proposal.content.round {
737 return Ok(());
738 }
739 }
740 if let Some(old_proposal) = self.signed_proposal.get() {
741 if old_proposal.content.round <= proposal.content.round {
742 self.signed_proposal.set(None);
743 }
744 }
745 self.proposed.set(Some(proposal));
746 self.proposed_blobs.clear();
747 for (blob_id, blob) in blobs {
748 self.proposed_blobs.insert(&blob_id, blob)?;
749 }
750 Ok(())
751 }
752
753 fn update_locking(
755 &mut self,
756 locking: LockingBlock,
757 blobs: BTreeMap<BlobId, Blob>,
758 ) -> Result<(), ViewError> {
759 if let Some(old_locked) = self.locking_block.get() {
760 if old_locked.round() >= locking.round() {
761 return Ok(());
762 }
763 }
764 self.locking_block.set(Some(locking));
765 self.locking_blobs.clear();
766 for (blob_id, blob) in blobs {
767 self.locking_blobs.insert(&blob_id, blob)?;
768 }
769 Ok(())
770 }
771}
772
773#[derive(Default, Clone, Debug, Serialize, Deserialize)]
775#[cfg_attr(with_testing, derive(Eq, PartialEq))]
776pub struct ChainManagerInfo {
777 pub ownership: ChainOwnership,
779 pub requested_signed_proposal: Option<Box<BlockProposal>>,
782 #[debug(skip_if = Option::is_none)]
784 pub requested_proposed: Option<Box<BlockProposal>>,
785 #[debug(skip_if = Option::is_none)]
788 pub requested_locking: Option<Box<LockingBlock>>,
789 #[debug(skip_if = Option::is_none)]
791 pub timeout: Option<Box<TimeoutCertificate>>,
792 #[debug(skip_if = Option::is_none)]
794 pub pending: Option<LiteVote>,
795 #[debug(skip_if = Option::is_none)]
797 pub timeout_vote: Option<LiteVote>,
798 #[debug(skip_if = Option::is_none)]
800 pub fallback_vote: Option<LiteVote>,
801 #[debug(skip_if = Option::is_none)]
803 pub requested_confirmed: Option<Box<ConfirmedBlock>>,
804 #[debug(skip_if = Option::is_none)]
806 pub requested_validated: Option<Box<ValidatedBlock>>,
807 pub current_round: Round,
809 #[debug(skip_if = Option::is_none)]
812 pub leader: Option<AccountOwner>,
813 #[debug(skip_if = Option::is_none)]
815 pub round_timeout: Option<Timestamp>,
816}
817
818impl<C> From<&ChainManager<C>> for ChainManagerInfo
819where
820 C: Context + Clone + Send + Sync + 'static,
821{
822 fn from(manager: &ChainManager<C>) -> Self {
823 let current_round = manager.current_round();
824 let pending = match (manager.confirmed_vote.get(), manager.validated_vote.get()) {
825 (None, None) => None,
826 (Some(confirmed_vote), Some(validated_vote))
827 if validated_vote.round > confirmed_vote.round =>
828 {
829 Some(validated_vote.lite())
830 }
831 (Some(vote), _) => Some(vote.lite()),
832 (None, Some(vote)) => Some(vote.lite()),
833 };
834 ChainManagerInfo {
835 ownership: manager.ownership.get().clone(),
836 requested_signed_proposal: None,
837 requested_proposed: None,
838 requested_locking: None,
839 timeout: manager.timeout.get().clone().map(Box::new),
840 pending,
841 timeout_vote: manager.timeout_vote.get().as_ref().map(Vote::lite),
842 fallback_vote: manager.fallback_vote.get().as_ref().map(Vote::lite),
843 requested_confirmed: None,
844 requested_validated: None,
845 current_round,
846 leader: manager.round_leader(current_round).copied(),
847 round_timeout: *manager.round_timeout.get(),
848 }
849 }
850}
851
852impl ChainManagerInfo {
853 pub fn add_values<C>(&mut self, manager: &ChainManager<C>)
855 where
856 C: Context + Clone + Send + Sync + 'static,
857 C::Extra: ExecutionRuntimeContext,
858 {
859 self.requested_signed_proposal = manager.signed_proposal.get().clone().map(Box::new);
860 self.requested_proposed = manager.proposed.get().clone().map(Box::new);
861 self.requested_locking = manager.locking_block.get().clone().map(Box::new);
862 self.requested_confirmed = manager
863 .confirmed_vote
864 .get()
865 .as_ref()
866 .map(|vote| Box::new(vote.value.clone()));
867 self.requested_validated = manager
868 .validated_vote
869 .get()
870 .as_ref()
871 .map(|vote| Box::new(vote.value.clone()));
872 }
873
874 pub fn can_propose(
877 &self,
878 identity: &AccountOwner,
879 round: Round,
880 seed: u64,
881 current_committee: &BTreeMap<AccountOwner, u64>,
882 ) -> bool {
883 match round {
884 Round::Fast => self.ownership.super_owners.contains(identity),
885 Round::MultiLeader(_) => true,
886 Round::SingleLeader(r) => {
887 if let Some(distribution) = calculate_distribution(self.ownership.owners.iter()) {
888 let leader_index = round_leader_index(r, seed, Some(&distribution))
889 .expect("cannot fail if distribution is set");
890 self.ownership.owners.keys().nth(leader_index) == Some(identity)
891 } else {
892 tracing::warn!("no owners in chain ownership");
893 false
894 }
895 }
896 Round::Validator(r) => {
897 if let Some(distribution) = calculate_distribution(current_committee.iter()) {
898 let leader_index = round_leader_index(r, seed, Some(&distribution))
899 .expect("cannot fail if distribution is set");
900 current_committee.keys().nth(leader_index) == Some(identity)
901 } else {
902 tracing::warn!("no owners in current committee");
903 false
904 }
905 }
906 }
907 }
908
909 pub fn already_handled_proposal(&self, round: Round, proposed_block: &ProposedBlock) -> bool {
911 self.requested_proposed.as_ref().is_some_and(|proposal| {
912 proposal.content.round == round && *proposed_block == proposal.content.block
913 })
914 }
915
916 pub fn has_locking_block_in_current_round(&self) -> bool {
918 self.requested_locking
919 .as_ref()
920 .is_some_and(|locking| locking.round() == self.current_round)
921 }
922}
923
924fn calculate_distribution<'a, T: 'a>(
926 weights: impl IntoIterator<Item = (&'a T, &'a u64)>,
927) -> Option<WeightedAliasIndex<u64>> {
928 let weights: Vec<_> = weights.into_iter().map(|(_, weight)| *weight).collect();
929 if weights.is_empty() {
930 None
931 } else {
932 Some(WeightedAliasIndex::new(weights).ok()?)
933 }
934}
935
936fn round_leader_index(
938 round: u32,
939 seed: u64,
940 distribution: Option<&WeightedAliasIndex<u64>>,
941) -> Option<usize> {
942 let seed = u64::from(round).rotate_left(32).wrapping_add(seed);
943 let mut rng = ChaCha8Rng::seed_from_u64(seed);
944 Some(distribution?.sample(&mut rng))
945}