linera_chain/
manager.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! # Chain manager
5//!
6//! This module contains the consensus mechanism for all microchains. Whenever a block is
7//! confirmed, a new chain manager is created for the next block height. It manages the consensus
8//! state until a new block is confirmed. As long as less than a third of the validators are faulty,
9//! it guarantees that at most one `ConfirmedBlock` certificate will be created for this height.
10//!
11//! The protocol proceeds in rounds, until it reaches a round where a block gets confirmed.
12//!
13//! There are four kinds of rounds:
14//!
15//! * In `Round::Fast`, only super owners can propose blocks, and validators vote to confirm a
16//!   block immediately. Super owners must be careful to make only one block proposal, or else they
17//!   can permanently block the microchain. If there are no super owners, `Round::Fast` is skipped.
18//! * In cooperative mode (`Round::MultiLeader`), all chain owners can propose blocks at any time.
19//!   The protocol is guaranteed to eventually confirm a block as long as no chain owner
20//!   continuously actively prevents progress.
21//! * In leader rotation mode (`Round::SingleLeader`), chain owners take turns at proposing blocks.
22//!   It can make progress as long as at least one owner is honest, even if other owners try to
23//!   prevent it.
24//! * In fallback/public mode (`Round::Validator`), validators take turns at proposing blocks.
25//!   It can always make progress under the standard assumption that there is a quorum of honest
26//!   validators.
27//!
28//! ## Safety, i.e. at most one block will be confirmed
29//!
30//! In all modes this is guaranteed as follows:
31//!
32//! * Validators (honest ones) never cast a vote if they have already cast any vote in a later
33//!   round.
34//! * Validators never vote for a `ValidatedBlock` **A** in round **r** if they have voted for a
35//!   _different_ `ConfirmedBlock` **B** in an earlier round **s** ≤ **r**, unless there is a
36//!   `ValidatedBlock` certificate (with a quorum of validator signatures) for **A** in some round
37//!   between **s** and **r** included in the block proposal.
38//! * Validators only vote for a `ConfirmedBlock` if there is a `ValidatedBlock` certificate for the
39//!   same block in the same round. (Or, in the `Fast` round, if there is a valid proposal.)
40//!
41//! This guarantees that once a quorum votes for some `ConfirmedBlock`, there can never be a
42//! `ValidatedBlock` certificate (and thus also no `ConfirmedBlock` certificate) for a different
43//! block in a later round. So if there are two different `ConfirmedBlock` certificates, they may
44//! be from different rounds, but they are guaranteed to contain the same block.
45//!
46//! ## Liveness, i.e. some block will eventually be confirmed
47//!
48//! In `Round::Fast`, liveness depends on the super owners coordinating, and proposing at most one
49//! block.
50//!
51//! If they propose none, and there are other owners, `Round::Fast` will eventually time out.
52//!
53//! In cooperative mode, if there is contention, the owners need to agree on a single owner as the
54//! next proposer. That owner should then download all highest-round certificates and block
55//! proposals known to the honest validators. They can then make a proposal in a round higher than
56//! all previous proposals. If there is any `ValidatedBlock` certificate they must include the
57//! highest one in their proposal, and propose that block. Otherwise they can propose a new block.
58//! Now all honest validators are allowed to vote for that proposal, and eventually confirm it.
59//!
60//! If the owners fail to cooperate, any honest owner can initiate the last multi-leader round by
61//! making a proposal there, then wait for it to time out, which starts the leader-based mode:
62//!
63//! In leader-based and fallback/public mode, an honest participant should subscribe to
64//! notifications from all validators, and follow the chain. Whenever another leader's round takes
65//! too long, they should request timeout votes from the validators to make the next round begin.
66//! Once the honest participant becomes the round leader, they should update all validators, so
67//! that they all agree on the current round. Then they download the highest `ValidatedBlock`
68//! certificate known to any honest validator and include that in their block proposal, just like
69//! in the cooperative case.
70
71use std::collections::BTreeMap;
72
73use allocative::Allocative;
74use custom_debug_derive::Debug;
75use futures::future::Either;
76use linera_base::{
77    crypto::{AccountPublicKey, 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/// The result of verifying a (valid) query.
103#[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/// The latest block that validators may have voted to confirm: this is either the block proposal
112/// from the fast round or a validated block certificate. Validators are allowed to vote for this
113/// even if they have locked (i.e. voted to confirm) a different block earlier.
114#[derive(Debug, Clone, Serialize, Deserialize, Allocative)]
115#[cfg_attr(with_testing, derive(Eq, PartialEq))]
116pub enum LockingBlock {
117    /// A proposal in the `Fast` round.
118    Fast(BlockProposal),
119    /// A `ValidatedBlock` certificate in a round other than `Fast`.
120    Regular(ValidatedBlockCertificate),
121}
122
123impl LockingBlock {
124    /// Returns the locking block's round. To propose a different block, a `ValidatedBlock`
125    /// certificate from a higher round is needed.
126    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/// The state of the certification process for a chain's next block.
142#[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    /// The public keys, weights and types of the chain's owners.
150    pub ownership: RegisterView<C, ChainOwnership>,
151    /// The seed for the pseudo-random number generator that determines the round leaders.
152    pub seed: RegisterView<C, u64>,
153    /// The probability distribution for choosing a round leader.
154    #[cfg_attr(with_graphql, graphql(skip))] // Derived from ownership.
155    #[allocative(skip)]
156    pub distribution: RegisterView<C, Option<WeightedAliasIndex<u64>>>,
157    /// The probability distribution for choosing a fallback round leader.
158    #[cfg_attr(with_graphql, graphql(skip))] // Derived from validator weights.
159    #[allocative(skip)]
160    pub fallback_distribution: RegisterView<C, Option<WeightedAliasIndex<u64>>>,
161    /// Highest-round authenticated block that we have received, but not necessarily
162    /// checked yet. If there are multiple proposals in the same round, this contains only the
163    /// first one. This can even contain proposals that did not execute successfully, to determine
164    /// which round to propose in.
165    #[cfg_attr(with_graphql, graphql(skip))]
166    pub signed_proposal: RegisterView<C, Option<BlockProposal>>,
167    /// Highest-round authenticated block that we have received and checked. If there are multiple
168    /// proposals in the same round, this contains only the first one.
169    #[cfg_attr(with_graphql, graphql(skip))]
170    pub proposed: RegisterView<C, Option<BlockProposal>>,
171    /// These are blobs published or read by the proposed block.
172    pub proposed_blobs: MapView<C, BlobId, Blob>,
173    /// Latest validated proposal that a validator may have voted to confirm. This is either the
174    /// latest `ValidatedBlock` we have seen, or the proposal from the `Fast` round.
175    #[cfg_attr(with_graphql, graphql(skip))]
176    pub locking_block: RegisterView<C, Option<LockingBlock>>,
177    /// These are blobs published or read by the locking block.
178    pub locking_blobs: MapView<C, BlobId, Blob>,
179    /// Latest leader timeout certificate we have received.
180    #[cfg_attr(with_graphql, graphql(skip))]
181    pub timeout: RegisterView<C, Option<TimeoutCertificate>>,
182    /// Latest vote we cast to confirm a block.
183    #[cfg_attr(with_graphql, graphql(skip))]
184    pub confirmed_vote: RegisterView<C, Option<Vote<ConfirmedBlock>>>,
185    /// Latest vote we cast to validate a block.
186    #[cfg_attr(with_graphql, graphql(skip))]
187    pub validated_vote: RegisterView<C, Option<Vote<ValidatedBlock>>>,
188    /// Latest timeout vote we cast.
189    #[cfg_attr(with_graphql, graphql(skip))]
190    pub timeout_vote: RegisterView<C, Option<Vote<Timeout>>>,
191    /// Fallback vote we cast.
192    #[cfg_attr(with_graphql, graphql(skip))]
193    pub fallback_vote: RegisterView<C, Option<Vote<Timeout>>>,
194    /// The time after which we are ready to sign a timeout certificate for the current round.
195    pub round_timeout: RegisterView<C, Option<Timestamp>>,
196    /// The lowest round where we can still vote to validate or confirm a block. This is
197    /// the round to which the timeout applies.
198    ///
199    /// Having a leader timeout certificate in any given round causes the next one to become
200    /// current. Seeing a validated block certificate or a valid proposal in any round causes that
201    /// round to become current, unless a higher one already is.
202    #[cfg_attr(with_graphql, graphql(skip))]
203    pub current_round: RegisterView<C, Round>,
204    /// The owners that take over in fallback mode.
205    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    /// Returns the lowest round where we can still vote to validate or confirm a block. This is
215    /// the round to which the timeout applies.
216    ///
217    /// Having a leader timeout certificate in any given round causes the next one to become
218    /// current. Seeing a validated block certificate or a valid proposal in any round causes that
219    /// round to become current, unless a higher one already is.
220    #[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    /// Replaces `self` with a new chain manager.
231    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    /// Returns the most recent confirmed vote we cast.
261    pub fn confirmed_vote(&self) -> Option<&Vote<ConfirmedBlock>> {
262        self.confirmed_vote.get().as_ref()
263    }
264
265    /// Returns the most recent validated vote we cast.
266    pub fn validated_vote(&self) -> Option<&Vote<ValidatedBlock>> {
267        self.validated_vote.get().as_ref()
268    }
269
270    /// Returns the most recent timeout vote we cast.
271    pub fn timeout_vote(&self) -> Option<&Vote<Timeout>> {
272        self.timeout_vote.get().as_ref()
273    }
274
275    /// Returns the most recent fallback vote we cast.
276    pub fn fallback_vote(&self) -> Option<&Vote<Timeout>> {
277        self.fallback_vote.get().as_ref()
278    }
279
280    /// Returns the lowest round where we can still vote to validate or confirm a block. This is
281    /// the round to which the timeout applies.
282    ///
283    /// Having a leader timeout certificate in any given round causes the next one to become
284    /// current. Seeing a validated block certificate or a valid proposal in any round causes that
285    /// round to become current, unless a higher one already is.
286    pub fn current_round(&self) -> Round {
287        *self.current_round.get()
288    }
289
290    /// Verifies that a proposed block is relevant and should be handled.
291    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); // We have already seen this proposal; nothing to do.
297            }
298        }
299        // When a block is certified, incrementing its height must succeed.
300        ensure!(
301            new_block.height < BlockHeight::MAX,
302            ChainError::BlockHeightOverflow
303        );
304        let current_round = self.current_round();
305        match new_round {
306            // The proposal from the fast round may still be relevant as a locking block, so
307            // we don't compare against the current round here.
308            Round::Fast => {}
309            Round::MultiLeader(_) | Round::SingleLeader(0) => {
310                // If the fast round has not timed out yet, only a super owner is allowed to open
311                // a later round by making a proposal.
312                ensure!(
313                    self.is_super(&proposal.owner()) || !current_round.is_fast(),
314                    ChainError::WrongRound(current_round)
315                );
316                // After the fast round, proposals older than the current round are obsolete.
317                ensure!(
318                    new_round >= current_round,
319                    ChainError::InsufficientRound(new_round)
320                );
321            }
322            Round::SingleLeader(_) | Round::Validator(_) => {
323                // After the first single-leader round, only proposals from the current round are relevant.
324                ensure!(
325                    new_round == current_round,
326                    ChainError::WrongRound(current_round)
327                );
328            }
329        }
330        // The round of our validation votes is only allowed to increase.
331        if let Some(vote) = self.validated_vote() {
332            ensure!(
333                new_round > vote.round,
334                ChainError::InsufficientRoundStrict(vote.round)
335            );
336        }
337        // A proposal that isn't newer than the locking block is not relevant anymore.
338        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 we have voted to confirm we cannot vote to validate a different block anymore, except
345        // if there is a validated block certificate from a later round.
346        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    /// Checks if the current round has timed out, and signs a `Timeout`. Returns `true` if the
363    /// chain manager's state has changed.
364    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); // We are not a validator.
375        };
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); // We already signed this timeout.
390            }
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    /// Signs a `Timeout` certificate to switch to fallback mode.
399    ///
400    /// This must only be called after verifying that the condition for fallback mode is
401    /// satisfied locally.
402    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; // We are not a validator.
411        };
412        if self.fallback_vote.get().is_some() || self.current_round() >= Round::Validator(0) {
413            return false; // We already signed this or are already in fallback mode.
414        }
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    /// Verifies that a validated block is still relevant and should be handled.
423    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); // We already voted to confirm this block.
432            }
433        }
434
435        // Check if we already voted to validate in a later round.
436        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    /// Signs a vote to validate the proposed block.
450    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            // If the validated block certificate is more recent, update our locking block.
462            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            // If this contains a proposal from the fast round, we consider that a locking block.
476            // It is useful for clients synchronizing with us, so they can re-propose it.
477            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            // If this proposal itself is from the fast round, it is also a locking block: We
487            // will vote to confirm it, so it is locked.
488            None => {
489                if round.is_fast() && self.locking_block.get().is_none() {
490                    // The fast block also counts as locking.
491                    self.update_locking(LockingBlock::Fast(proposal.clone()), blobs.clone())?;
492                }
493            }
494        }
495
496        // We record the proposed block, in case it affects the current round number.
497        self.update_proposed(proposal.clone(), blobs)?;
498        self.update_current_round(local_time);
499
500        let Some(key_pair) = key_pair else {
501            // Not a validator.
502            return Ok(None);
503        };
504
505        // If this is a fast block, vote to confirm. Otherwise vote to validate.
506        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    /// Signs a vote to confirm the validated block.
523    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(()); // We never vote in a past round.
537            }
538            // Vote to confirm.
539            let vote = Vote::new(confirmed_block, round, key_pair);
540            // Ok to overwrite validation votes with confirmation votes at equal or higher round.
541            self.confirmed_vote.set(Some(vote));
542            self.validated_vote.set(None);
543        }
544        Ok(())
545    }
546
547    /// Returns the requested blob if it belongs to the proposal or the locking block.
548    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    /// Updates `current_round` and `round_timeout` if necessary.
556    ///
557    /// This must be called after every change to `timeout`, `locking`, `proposed` or
558    /// `signed_proposal`.
559    ///
560    /// The current round starts at `Fast` if there is a super owner, `MultiLeader(0)` if at least
561    /// one multi-leader round is configured, or otherwise `SingleLeader(0)`.
562    ///
563    /// Single-leader rounds can only be ended by a timeout certificate for that round.
564    ///
565    /// The presence of any validated block certificate is also proof that a quorum of validators
566    /// is already in that round, even if we have not seen the corresponding timeout.
567    ///
568    /// Multi-leader rounds can always be skipped, so any correctly signed block proposal in a
569    /// later round ends a multi-leader round.
570    /// Since we don't accept proposals that violate that rule, we can compute the current round in
571    /// general by taking the maximum of all the above.
572    fn update_current_round(&mut self, local_time: Timestamp) {
573        let current_round = self
574            .timeout
575            .get()
576            .iter()
577            // A timeout certificate starts the next round.
578            .map(|certificate| {
579                self.ownership
580                    .get()
581                    .next_round(certificate.round)
582                    .unwrap_or(Round::Validator(u32::MAX))
583            })
584            // A locking block or a proposal is proof we have accepted that we are at least in
585            // this round.
586            .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            // Otherwise compute the first round for this chain configuration.
597            .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    /// Updates the round number and timer if the timeout certificate is from a higher round than
608    /// any known certificate.
609    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    /// Returns whether the signer is a valid owner and allowed to propose a block in the
625    /// proposal's round.
626    ///
627    /// Super owners can always propose, except in `Validator` rounds, but it is recommended that
628    /// they don't interfere with single-leader rounds. In multi-leader rounds, any owner can
629    /// propose (or anyone, if `open_multi_leader_rounds`) and in other rounds there is only
630    /// one leader.
631    pub fn can_propose(&self, owner: &AccountOwner, round: Round) -> bool {
632        let ownership = self.ownership.get();
633        if ownership.super_owners.contains(owner) {
634            return !round.is_validator();
635        }
636        match round {
637            Round::Fast => false,
638            Round::MultiLeader(_) => ownership.is_multi_leader_owner(owner),
639            Round::SingleLeader(_) | Round::Validator(_) => self.round_leader(round) == Some(owner),
640        }
641    }
642
643    /// Returns the leader who is allowed to propose a block in the given round, or `None` if every
644    /// owner is allowed to propose. Exception: In `Round::Fast`, only super owners can propose.
645    fn round_leader(&self, round: Round) -> Option<&AccountOwner> {
646        let ownership = self.ownership.get();
647        compute_round_leader(
648            round,
649            *self.seed.get(),
650            ownership.first_leader.as_ref(),
651            &ownership.owners,
652            self.distribution.get().as_ref(),
653            self.fallback_owners.get(),
654            self.fallback_distribution.get().as_ref(),
655        )
656    }
657
658    /// Returns whether the owner is a super owner.
659    fn is_super(&self, owner: &AccountOwner) -> bool {
660        self.ownership.get().super_owners.contains(owner)
661    }
662
663    /// Sets the signed proposal, if it is newer than the known one, at most from the first
664    /// single-leader round. Returns whether it was updated.
665    ///
666    /// We don't update the signed proposal for any rounds later than `SingleLeader(0)`,
667    /// because single-leader rounds cannot be skipped without a timeout certificate.
668    pub fn update_signed_proposal(
669        &mut self,
670        proposal: &BlockProposal,
671        local_time: Timestamp,
672    ) -> bool {
673        if proposal.content.round > Round::SingleLeader(0) {
674            return false;
675        }
676        if let Some(old_proposal) = self.signed_proposal.get() {
677            if old_proposal.content.round >= proposal.content.round {
678                if *self.current_round.get() < old_proposal.content.round {
679                    tracing::warn!(
680                        chain_id = %proposal.content.block.chain_id,
681                        current_round = ?self.current_round.get(),
682                        proposal_round = ?old_proposal.content.round,
683                        "Proposal round is greater than current round. Updating."
684                    );
685                    self.update_current_round(local_time);
686                    return true;
687                }
688                return false;
689            }
690        }
691        if let Some(old_proposal) = self.proposed.get() {
692            if old_proposal.content.round >= proposal.content.round {
693                return false;
694            }
695        }
696        self.signed_proposal.set(Some(proposal.clone()));
697        self.update_current_round(local_time);
698        true
699    }
700
701    /// Sets the proposed block, if it is newer than our known latest proposal.
702    fn update_proposed(
703        &mut self,
704        proposal: BlockProposal,
705        blobs: BTreeMap<BlobId, Blob>,
706    ) -> Result<(), ViewError> {
707        if let Some(old_proposal) = self.proposed.get() {
708            if old_proposal.content.round >= proposal.content.round {
709                return Ok(());
710            }
711        }
712        if let Some(old_proposal) = self.signed_proposal.get() {
713            if old_proposal.content.round <= proposal.content.round {
714                self.signed_proposal.set(None);
715            }
716        }
717        self.proposed.set(Some(proposal));
718        self.proposed_blobs.clear();
719        for (blob_id, blob) in blobs {
720            self.proposed_blobs.insert(&blob_id, blob)?;
721        }
722        Ok(())
723    }
724
725    /// Sets the locking block and the associated blobs, if it is newer than the known one.
726    fn update_locking(
727        &mut self,
728        locking: LockingBlock,
729        blobs: BTreeMap<BlobId, Blob>,
730    ) -> Result<(), ViewError> {
731        if let Some(old_locked) = self.locking_block.get() {
732            if old_locked.round() >= locking.round() {
733                return Ok(());
734            }
735        }
736        self.locking_block.set(Some(locking));
737        self.locking_blobs.clear();
738        for (blob_id, blob) in blobs {
739            self.locking_blobs.insert(&blob_id, blob)?;
740        }
741        Ok(())
742    }
743}
744
745/// Chain manager information that is included in `ChainInfo` sent to clients.
746#[derive(Default, Clone, Debug, Serialize, Deserialize)]
747#[cfg_attr(with_testing, derive(Eq, PartialEq))]
748pub struct ChainManagerInfo {
749    /// The configuration of the chain's owners.
750    pub ownership: ChainOwnership,
751    /// Latest authenticated block that we have received, if requested. This can even contain
752    /// proposals that did not execute successfully, to determine which round to propose in.
753    pub requested_signed_proposal: Option<Box<BlockProposal>>,
754    /// Latest authenticated block that we have received and checked, if requested.
755    #[debug(skip_if = Option::is_none)]
756    pub requested_proposed: Option<Box<BlockProposal>>,
757    /// Latest validated proposal that we have voted to confirm (or would have, if we are not a
758    /// validator).
759    #[debug(skip_if = Option::is_none)]
760    pub requested_locking: Option<Box<LockingBlock>>,
761    /// Latest timeout certificate we have seen.
762    #[debug(skip_if = Option::is_none)]
763    pub timeout: Option<Box<TimeoutCertificate>>,
764    /// Latest vote we cast (either to validate or to confirm a block).
765    #[debug(skip_if = Option::is_none)]
766    pub pending: Option<LiteVote>,
767    /// Latest timeout vote we cast.
768    #[debug(skip_if = Option::is_none)]
769    pub timeout_vote: Option<LiteVote>,
770    /// Fallback vote we cast.
771    #[debug(skip_if = Option::is_none)]
772    pub fallback_vote: Option<LiteVote>,
773    /// The value we voted for, if requested.
774    #[debug(skip_if = Option::is_none)]
775    pub requested_confirmed: Option<Box<ConfirmedBlock>>,
776    /// The value we voted for, if requested.
777    #[debug(skip_if = Option::is_none)]
778    pub requested_validated: Option<Box<ValidatedBlock>>,
779    /// The current round, i.e. the lowest round where we can still vote to validate a block.
780    pub current_round: Round,
781    /// The current leader, who is allowed to propose the next block.
782    /// `None` if everyone is allowed to propose.
783    #[debug(skip_if = Option::is_none)]
784    pub leader: Option<AccountOwner>,
785    /// The timestamp when the current round times out.
786    #[debug(skip_if = Option::is_none)]
787    pub round_timeout: Option<Timestamp>,
788}
789
790impl<C> From<&ChainManager<C>> for ChainManagerInfo
791where
792    C: Context + Clone + Send + Sync + 'static,
793{
794    fn from(manager: &ChainManager<C>) -> Self {
795        let current_round = manager.current_round();
796        let pending = match (manager.confirmed_vote.get(), manager.validated_vote.get()) {
797            (None, None) => None,
798            (Some(confirmed_vote), Some(validated_vote))
799                if validated_vote.round > confirmed_vote.round =>
800            {
801                Some(validated_vote.lite())
802            }
803            (Some(vote), _) => Some(vote.lite()),
804            (None, Some(vote)) => Some(vote.lite()),
805        };
806        ChainManagerInfo {
807            ownership: manager.ownership.get().clone(),
808            requested_signed_proposal: None,
809            requested_proposed: None,
810            requested_locking: None,
811            timeout: manager.timeout.get().clone().map(Box::new),
812            pending,
813            timeout_vote: manager.timeout_vote.get().as_ref().map(Vote::lite),
814            fallback_vote: manager.fallback_vote.get().as_ref().map(Vote::lite),
815            requested_confirmed: None,
816            requested_validated: None,
817            current_round,
818            leader: manager.round_leader(current_round).copied(),
819            round_timeout: *manager.round_timeout.get(),
820        }
821    }
822}
823
824impl ChainManagerInfo {
825    /// Adds requested certificate values and proposals to the `ChainManagerInfo`.
826    pub fn add_values<C>(&mut self, manager: &ChainManager<C>)
827    where
828        C: Context + Clone + Send + Sync + 'static,
829        C::Extra: ExecutionRuntimeContext,
830    {
831        self.requested_signed_proposal = manager.signed_proposal.get().clone().map(Box::new);
832        self.requested_proposed = manager.proposed.get().clone().map(Box::new);
833        self.requested_locking = manager.locking_block.get().clone().map(Box::new);
834        self.requested_confirmed = manager
835            .confirmed_vote
836            .get()
837            .as_ref()
838            .map(|vote| Box::new(vote.value.clone()));
839        self.requested_validated = manager
840            .validated_vote
841            .get()
842            .as_ref()
843            .map(|vote| Box::new(vote.value.clone()));
844    }
845
846    /// Returns whether the `identity` is allowed to propose a block in `round`.
847    ///
848    /// **Exception:** In single-leader rounds, a **super owner** should only propose
849    /// if they are the designated **leader** for that round.
850    pub fn should_propose(
851        &self,
852        identity: &AccountOwner,
853        round: Round,
854        seed: u64,
855        current_committee: &BTreeMap<AccountOwner, u64>,
856    ) -> bool {
857        match round {
858            Round::Fast => self.ownership.super_owners.contains(identity),
859            Round::MultiLeader(_) => self.ownership.is_multi_leader_owner(identity),
860            Round::SingleLeader(_) | Round::Validator(_) => {
861                let distribution = calculate_distribution(self.ownership.owners.iter());
862                let fallback_distribution = calculate_distribution(current_committee.iter());
863                let leader = compute_round_leader(
864                    round,
865                    seed,
866                    self.ownership.first_leader.as_ref(),
867                    &self.ownership.owners,
868                    distribution.as_ref(),
869                    current_committee,
870                    fallback_distribution.as_ref(),
871                );
872                leader == Some(identity)
873            }
874        }
875    }
876
877    /// Returns whether a proposal with this content was already handled.
878    pub fn already_handled_proposal(&self, round: Round, proposed_block: &ProposedBlock) -> bool {
879        self.requested_proposed.as_ref().is_some_and(|proposal| {
880            proposal.content.round == round && *proposed_block == proposal.content.block
881        })
882    }
883
884    /// Returns whether there is a locking block in the current round.
885    pub fn has_locking_block_in_current_round(&self) -> bool {
886        self.requested_locking
887            .as_ref()
888            .is_some_and(|locking| locking.round() == self.current_round)
889    }
890}
891
892/// Calculates a probability distribution from the given weights, or `None` if there are no weights.
893fn calculate_distribution<'a, T: 'a>(
894    weights: impl IntoIterator<Item = (&'a T, &'a u64)>,
895) -> Option<WeightedAliasIndex<u64>> {
896    let weights: Vec<_> = weights.into_iter().map(|(_, weight)| *weight).collect();
897    if weights.is_empty() {
898        None
899    } else {
900        Some(WeightedAliasIndex::new(weights).ok()?)
901    }
902}
903
904/// Returns the designated leader for single-leader or validator rounds.
905/// Returns `None` for fast or multi-leader rounds.
906fn compute_round_leader<'a>(
907    round: Round,
908    seed: u64,
909    first_leader: Option<&'a AccountOwner>,
910    owners: &'a BTreeMap<AccountOwner, u64>,
911    distribution: Option<&WeightedAliasIndex<u64>>,
912    fallback_owners: &'a BTreeMap<AccountOwner, u64>,
913    fallback_distribution: Option<&WeightedAliasIndex<u64>>,
914) -> Option<&'a AccountOwner> {
915    match round {
916        Round::SingleLeader(r) => {
917            if r == 0 {
918                if let Some(first_leader) = first_leader {
919                    return Some(first_leader);
920                }
921            }
922            let index = round_leader_index(r, seed, distribution)?;
923            owners.keys().nth(index)
924        }
925        Round::Validator(r) => {
926            let index = round_leader_index(r, seed, fallback_distribution)?;
927            fallback_owners.keys().nth(index)
928        }
929        Round::Fast | Round::MultiLeader(_) => None,
930    }
931}
932
933/// Returns the index of the leader who is allowed to propose a block in the given round.
934fn round_leader_index(
935    round: u32,
936    seed: u64,
937    distribution: Option<&WeightedAliasIndex<u64>>,
938) -> Option<usize> {
939    let seed = u64::from(round).rotate_left(32).wrapping_add(seed);
940    let mut rng = ChaCha8Rng::seed_from_u64(seed);
941    Some(distribution?.sample(&mut rng))
942}