Skip to main content

hotshot/
lib.rs

1// Copyright (c) 2021-2024 Espresso Systems (espressosys.com)
2// This file is part of the HotShot repository.
3
4// You should have received a copy of the MIT License
5// along with the HotShot repository. If not, see <https://mit-license.org/>.
6
7//! Provides a generic rust implementation of the `HotShot` BFT protocol
8//!
9
10// Documentation module
11#[cfg(feature = "docs")]
12pub mod documentation;
13
14use committable::Committable;
15use futures::future::{Either, select};
16use hotshot_types::{
17    drb::{DrbResult, INITIAL_DRB_RESULT, drb_difficulty_selector},
18    epoch_membership::EpochMembershipCoordinator,
19    message::UpgradeLock,
20    simple_certificate::{CertificatePair, LightClientStateUpdateCertificateV2},
21    traits::{
22        block_contents::BlockHeader, election::Membership, network::BroadcastDelay,
23        signature_key::StateSignatureKey, storage::Storage,
24    },
25    utils::{epoch_from_block_number, is_ge_epoch_root},
26};
27use rand::Rng;
28
29/// Contains traits consumed by [`SystemContext`]
30pub mod traits;
31/// Contains types used by the crate
32pub mod types;
33
34pub mod tasks;
35use hotshot_types::data::QuorumProposalWrapper;
36use versions::{EPOCH_VERSION, Upgrade};
37
38/// Contains helper functions for the crate
39pub mod helpers;
40
41use std::{
42    collections::{BTreeMap, HashMap},
43    num::NonZeroUsize,
44    sync::Arc,
45    time::Duration,
46};
47
48use alloy::primitives::U256;
49use async_broadcast::{InactiveReceiver, Receiver, Sender, broadcast};
50use async_lock::RwLock;
51use async_trait::async_trait;
52use futures::join;
53use hotshot_task::task::{ConsensusTaskRegistry, NetworkTaskRegistry};
54use hotshot_task_impls::{events::HotShotEvent, helpers::broadcast_event};
55// Internal
56/// Reexport error type
57pub use hotshot_types::error::HotShotError;
58use hotshot_types::{
59    HotShotConfig,
60    consensus::{
61        Consensus, ConsensusMetricsValue, OuterConsensus, PayloadWithMetadata, VidShares, View,
62        ViewInner,
63    },
64    constants::{EVENT_CHANNEL_SIZE, EXTERNAL_EVENT_CHANNEL_SIZE},
65    data::{EpochNumber, Leaf2, ViewNumber},
66    event::{EventType, LeafInfo},
67    message::{DataMessage, Message, MessageKind, Proposal},
68    simple_certificate::{NextEpochQuorumCertificate2, QuorumCertificate2, UpgradeCertificate},
69    stake_table::HSStakeTable,
70    storage_metrics::StorageMetricsValue,
71    traits::{
72        consensus_api::ConsensusApi, network::ConnectedNetwork, node_implementation::NodeType,
73        signature_key::SignatureKey, states::ValidatedState,
74    },
75    utils::{genesis_epoch_from_version, option_epoch_from_block_number},
76};
77use hotshot_utils::warn;
78/// Reexport rand crate
79pub use rand;
80use tokio::{spawn, time::sleep};
81use tracing::{Instrument, debug, error_span, info, instrument, trace};
82
83// -- Rexports
84// External
85use crate::{
86    tasks::{add_consensus_tasks, add_network_tasks},
87    traits::NodeImplementation,
88    types::{Event, SystemContextHandle},
89};
90
91/// Length, in bytes, of a 512 bit hash
92pub const H_512: usize = 64;
93/// Length, in bytes, of a 256 bit hash
94pub const H_256: usize = 32;
95
96/// Holds the state needed to participate in `HotShot` consensus
97pub struct SystemContext<TYPES: NodeType, I: NodeImplementation<TYPES>> {
98    /// The public key of this node
99    public_key: TYPES::SignatureKey,
100
101    /// The private key of this node
102    private_key: <TYPES::SignatureKey as SignatureKey>::PrivateKey,
103
104    /// The private key to sign the light client state
105    state_private_key: <TYPES::StateSignatureKey as StateSignatureKey>::StatePrivateKey,
106
107    /// Configuration items for this hotshot instance
108    pub config: HotShotConfig<TYPES>,
109
110    /// The underlying network
111    pub network: Arc<I::Network>,
112
113    /// Memberships used by consensus
114    pub membership_coordinator: EpochMembershipCoordinator<TYPES>,
115
116    /// the metrics that the implementor is using.
117    metrics: Arc<ConsensusMetricsValue>,
118
119    /// The hotstuff implementation
120    consensus: OuterConsensus<TYPES>,
121
122    /// Immutable instance state
123    instance_state: Arc<TYPES::InstanceState>,
124
125    /// The view to enter when first starting consensus
126    start_view: ViewNumber,
127
128    /// The epoch to enter when first starting consensus
129    start_epoch: Option<EpochNumber>,
130
131    /// Access to the output event stream.
132    output_event_stream: (Sender<Event<TYPES>>, InactiveReceiver<Event<TYPES>>),
133
134    /// External event stream for communication with the application.
135    pub(crate) external_event_stream: (Sender<Event<TYPES>>, InactiveReceiver<Event<TYPES>>),
136
137    /// Anchored leaf provided by the initializer.
138    anchored_leaf: Leaf2<TYPES>,
139
140    /// access to the internal event stream, in case we need to, say, shut something down
141    #[allow(clippy::type_complexity)]
142    internal_event_stream: (
143        Sender<Arc<HotShotEvent<TYPES>>>,
144        InactiveReceiver<Arc<HotShotEvent<TYPES>>>,
145    ),
146
147    /// uid for instrumentation
148    pub id: u64,
149
150    /// Reference to the internal storage for consensus datum.
151    pub storage: I::Storage,
152
153    /// Storage metrics
154    pub storage_metrics: Arc<StorageMetricsValue>,
155
156    /// shared lock for upgrade information
157    pub upgrade_lock: UpgradeLock<TYPES>,
158}
159impl<TYPES: NodeType, I: NodeImplementation<TYPES>> Clone for SystemContext<TYPES, I> {
160    #![allow(deprecated)]
161    fn clone(&self) -> Self {
162        Self {
163            public_key: self.public_key.clone(),
164            private_key: self.private_key.clone(),
165            state_private_key: self.state_private_key.clone(),
166            config: self.config.clone(),
167            network: Arc::clone(&self.network),
168            membership_coordinator: self.membership_coordinator.clone(),
169            metrics: Arc::clone(&self.metrics),
170            consensus: self.consensus.clone(),
171            instance_state: Arc::clone(&self.instance_state),
172            start_view: self.start_view,
173            start_epoch: self.start_epoch,
174            output_event_stream: self.output_event_stream.clone(),
175            external_event_stream: self.external_event_stream.clone(),
176            anchored_leaf: self.anchored_leaf.clone(),
177            internal_event_stream: self.internal_event_stream.clone(),
178            id: self.id,
179            storage: self.storage.clone(),
180            storage_metrics: Arc::clone(&self.storage_metrics),
181            upgrade_lock: self.upgrade_lock.clone(),
182        }
183    }
184}
185
186impl<TYPES: NodeType, I: NodeImplementation<TYPES>> SystemContext<TYPES, I> {
187    #![allow(deprecated)]
188    /// Creates a new [`Arc<SystemContext>`] with the given configuration options.
189    ///
190    /// To do a full initialization, use `fn init` instead, which will set up background tasks as
191    /// well.
192    ///
193    /// Use this instead of `init` if you want to start the tasks manually
194    ///
195    /// # Panics
196    ///
197    /// Panics if storage migration fails.
198    #[allow(clippy::too_many_arguments)]
199    pub async fn new(
200        public_key: TYPES::SignatureKey,
201        private_key: <TYPES::SignatureKey as SignatureKey>::PrivateKey,
202        state_private_key: <TYPES::StateSignatureKey as StateSignatureKey>::StatePrivateKey,
203        nonce: u64,
204        config: HotShotConfig<TYPES>,
205        upgrade: versions::Upgrade,
206        memberships: EpochMembershipCoordinator<TYPES>,
207        network: Arc<I::Network>,
208        initializer: HotShotInitializer<TYPES>,
209        consensus_metrics: ConsensusMetricsValue,
210        storage: I::Storage,
211        storage_metrics: StorageMetricsValue,
212    ) -> Arc<Self> {
213        let internal_chan = broadcast(EVENT_CHANNEL_SIZE);
214        let external_chan = broadcast(EXTERNAL_EVENT_CHANNEL_SIZE);
215
216        Self::new_from_channels(
217            public_key,
218            private_key,
219            state_private_key,
220            nonce,
221            config,
222            upgrade,
223            memberships,
224            network,
225            initializer,
226            consensus_metrics,
227            storage,
228            storage_metrics,
229            internal_chan,
230            external_chan,
231        )
232        .await
233    }
234
235    /// Creates a new [`Arc<SystemContext>`] with the given configuration options.
236    ///
237    /// To do a full initialization, use `fn init` instead, which will set up background tasks as
238    /// well.
239    ///
240    /// Use this function if you want to use some preexisting channels and to spin up the tasks
241    /// and start consensus manually.  Mostly useful for tests
242    #[allow(clippy::too_many_arguments, clippy::type_complexity)]
243    pub async fn new_from_channels(
244        public_key: TYPES::SignatureKey,
245        private_key: <TYPES::SignatureKey as SignatureKey>::PrivateKey,
246        state_private_key: <TYPES::StateSignatureKey as StateSignatureKey>::StatePrivateKey,
247        nonce: u64,
248        config: HotShotConfig<TYPES>,
249        upgrade: versions::Upgrade,
250        membership_coordinator: EpochMembershipCoordinator<TYPES>,
251        network: Arc<I::Network>,
252        initializer: HotShotInitializer<TYPES>,
253        consensus_metrics: ConsensusMetricsValue,
254        storage: I::Storage,
255        storage_metrics: StorageMetricsValue,
256        internal_channel: (
257            Sender<Arc<HotShotEvent<TYPES>>>,
258            Receiver<Arc<HotShotEvent<TYPES>>>,
259        ),
260        external_channel: (Sender<Event<TYPES>>, Receiver<Event<TYPES>>),
261    ) -> Arc<Self> {
262        debug!("Creating a new hotshot");
263
264        tracing::warn!("Starting consensus with HotShotConfig:\n\n {config:?}");
265
266        let consensus_metrics = Arc::new(consensus_metrics);
267        let storage_metrics = Arc::new(storage_metrics);
268        let anchored_leaf = initializer.anchor_leaf;
269        let instance_state = initializer.instance_state;
270
271        let (internal_tx, internal_rx) = internal_channel;
272        let (mut external_tx, external_rx) = external_channel;
273
274        let mut internal_rx = internal_rx.new_receiver();
275
276        let mut external_rx = external_rx.new_receiver();
277
278        // Allow overflow on the internal channel as well. We don't want to block consensus if we
279        // have a slow receiver
280        internal_rx.set_overflow(true);
281        // Allow overflow on the external channel, otherwise sending to it may block.
282        external_rx.set_overflow(true);
283
284        tracing::warn!(
285            "Starting consensus with versions:\n\n Base: {:?}\nUpgrade: {:?}.",
286            upgrade.base,
287            upgrade.target
288        );
289        tracing::warn!(
290            "Loading previously decided upgrade certificate from storage: {:?}",
291            initializer.decided_upgrade_certificate
292        );
293
294        let upgrade_lock = UpgradeLock::<TYPES>::from_certificate(
295            upgrade,
296            &initializer.decided_upgrade_certificate,
297        );
298
299        let current_version = if let Some(cert) = initializer.decided_upgrade_certificate {
300            cert.data.new_version
301        } else {
302            upgrade.base
303        };
304
305        debug!("Setting DRB difficulty selector in membership");
306        let drb_difficulty_selector = drb_difficulty_selector(&config);
307
308        membership_coordinator.set_drb_difficulty_selector(drb_difficulty_selector);
309
310        for da_committee in &config.da_committees {
311            if current_version >= da_committee.start_version {
312                membership_coordinator.membership().add_da_committee(
313                    da_committee.start_epoch.into(),
314                    da_committee.committee.clone(),
315                );
316            }
317        }
318
319        // Get the validated state from the initializer or construct an incomplete one from the
320        // block header.
321        let validated_state = initializer.anchor_state;
322
323        load_start_epoch_info(
324            &membership_coordinator,
325            &initializer.start_epoch_info,
326            config.epoch_height,
327            config.epoch_start_block,
328        )
329        .await;
330
331        // #3967 REVIEW NOTE: Should this actually be Some()? How do we know?
332        let epoch = initializer.high_qc.data.block_number.map(|block_number| {
333            EpochNumber::new(epoch_from_block_number(
334                block_number + 1,
335                config.epoch_height,
336            ))
337        });
338
339        // Insert the validated state to state map.
340        let mut validated_state_map = BTreeMap::default();
341        validated_state_map.insert(
342            anchored_leaf.view_number(),
343            View {
344                view_inner: ViewInner::Leaf {
345                    leaf: anchored_leaf.commit(),
346                    state: Arc::clone(&validated_state),
347                    delta: initializer.anchor_state_delta,
348                    epoch,
349                },
350            },
351        );
352        for (view_num, inner) in initializer.undecided_state {
353            validated_state_map.insert(view_num, inner);
354        }
355
356        let mut saved_leaves = HashMap::new();
357        let mut saved_payloads = BTreeMap::new();
358        saved_leaves.insert(anchored_leaf.commit(), anchored_leaf.clone());
359
360        for (_, leaf) in initializer.undecided_leaves {
361            saved_leaves.insert(leaf.commit(), leaf.clone());
362        }
363        if let Some(payload) = anchored_leaf.block_payload() {
364            let metadata = anchored_leaf.block_header().metadata().clone();
365            saved_payloads.insert(
366                anchored_leaf.view_number(),
367                Arc::new(PayloadWithMetadata { payload, metadata }),
368            );
369        }
370        let high_qc_block_number = initializer.high_qc.data.block_number;
371        let (stake_table, success_threshold) =
372            if let Ok(epoch_membership) = membership_coordinator.stake_table_for_epoch(epoch) {
373                (
374                    HSStakeTable::from_iter(epoch_membership.stake_table()),
375                    epoch_membership.success_threshold(),
376                )
377            } else {
378                tracing::warn!(
379                    "Failed to get stake table for epoch {:?} while creating vote participation",
380                    epoch
381                );
382                (HSStakeTable::default(), U256::MAX)
383            };
384
385        let consensus = Consensus::new(
386            validated_state_map,
387            Some(initializer.saved_vid_shares),
388            anchored_leaf.view_number(),
389            epoch,
390            anchored_leaf.view_number(),
391            anchored_leaf.view_number(),
392            initializer.last_actioned_view,
393            initializer.saved_proposals,
394            saved_leaves,
395            saved_payloads,
396            initializer.high_qc,
397            initializer.next_epoch_high_qc,
398            Arc::clone(&consensus_metrics),
399            config.epoch_height,
400            initializer.state_cert,
401            config.drb_difficulty,
402            config.drb_upgrade_difficulty,
403            stake_table,
404            success_threshold,
405        );
406
407        let consensus = Arc::new(RwLock::new(consensus));
408
409        if let Some(epoch) = epoch {
410            tracing::info!(
411                "Triggering catchup for epoch {} and next epoch {}",
412                epoch,
413                epoch + 1
414            );
415            // trigger catchup for the current and next epoch if needed
416            let _ = membership_coordinator.membership_for_epoch(Some(epoch));
417            let _ = membership_coordinator.membership_for_epoch(Some(epoch + 1));
418            // If we already have an epoch root, we can trigger catchup for the epoch
419            // which that root applies to.
420            if let Some(high_qc_block_number) = high_qc_block_number
421                && is_ge_epoch_root(high_qc_block_number, config.epoch_height)
422            {
423                let _ = membership_coordinator.stake_table_for_epoch(Some(epoch + 2));
424            }
425
426            if let Ok(drb_result) = storage.load_drb_result(epoch + 1).await {
427                info!(target: "announce::drb", epoch = %(epoch + 1), "writing drb result for epoch");
428                if let Ok(mem) = membership_coordinator.stake_table_for_epoch(Some(epoch + 1)) {
429                    mem.add_drb_result(drb_result);
430                }
431            }
432        }
433
434        // This makes it so we won't block on broadcasting if there is not a receiver
435        // Our own copy of the receiver is inactive so it doesn't count.
436        external_tx.set_await_active(false);
437
438        let inner: Arc<SystemContext<TYPES, I>> = Arc::new(SystemContext {
439            id: nonce,
440            consensus: OuterConsensus::new(consensus),
441            instance_state: Arc::new(instance_state),
442            public_key,
443            private_key,
444            state_private_key,
445            config,
446            start_view: initializer.start_view,
447            start_epoch: initializer.start_epoch,
448            network,
449            membership_coordinator,
450            metrics: Arc::clone(&consensus_metrics),
451            internal_event_stream: (internal_tx, internal_rx.deactivate()),
452            output_event_stream: (external_tx.clone(), external_rx.clone().deactivate()),
453            external_event_stream: (external_tx, external_rx.deactivate()),
454            anchored_leaf: anchored_leaf.clone(),
455            storage,
456            storage_metrics,
457            upgrade_lock,
458        });
459
460        inner
461    }
462
463    /// "Starts" consensus by sending a `Qc2Formed`, `ViewChange` events
464    ///
465    /// # Panics
466    /// Panics if sending genesis fails
467    #[instrument(skip_all, target = "SystemContext", fields(id = self.id))]
468    pub async fn start_consensus(&self) {
469        #[cfg(all(feature = "rewind", not(debug_assertions)))]
470        compile_error!("Cannot run rewind in production builds!");
471
472        debug!("Starting Consensus");
473        let consensus = self.consensus.read().await;
474
475        let first_epoch = option_epoch_from_block_number(
476            self.upgrade_lock.upgrade().base >= EPOCH_VERSION,
477            self.config.epoch_start_block,
478            self.config.epoch_height,
479        );
480        // `start_epoch` comes from the initializer, it might be the last seen epoch before restart
481        // `first_epoch` is the first epoch after the transition to the epoch version
482        // `initial_view_change_epoch` is the greater of the two, we use it with the initial view change
483        let initial_view_change_epoch = self.start_epoch.max(first_epoch);
484        #[allow(clippy::panic)]
485        self.internal_event_stream
486            .0
487            .broadcast_direct(Arc::new(HotShotEvent::ViewChange(
488                self.start_view,
489                initial_view_change_epoch,
490            )))
491            .await
492            .unwrap_or_else(|_| {
493                panic!(
494                    "Genesis Broadcast failed; event = ViewChange({:?}, {:?})",
495                    self.start_view, initial_view_change_epoch,
496                )
497            });
498
499        // Clone the event stream that we send the timeout event to
500        let event_stream = self.internal_event_stream.0.clone();
501        let next_view_timeout = self.config.next_view_timeout;
502        let start_view = self.start_view;
503        let start_epoch = self.start_epoch;
504
505        // Spawn a task that will sleep for the next view timeout and then send a timeout event
506        // if not cancelled
507        spawn(
508            async move {
509                sleep(Duration::from_millis(next_view_timeout)).await;
510                broadcast_event(
511                    Arc::new(HotShotEvent::Timeout(start_view, start_epoch)),
512                    &event_stream,
513                )
514                .await;
515            }
516            .instrument(error_span!("initial timeout", view = *start_view)),
517        );
518        #[allow(clippy::panic)]
519        self.internal_event_stream
520            .0
521            .broadcast_direct(Arc::new(HotShotEvent::Qc2Formed(either::Left(
522                consensus.high_qc().clone(),
523            ))))
524            .await
525            .unwrap_or_else(|_| {
526                panic!(
527                    "Genesis Broadcast failed; event = Qc2Formed(either::Left({:?}))",
528                    consensus.high_qc()
529                )
530            });
531
532        {
533            // Some applications seem to expect a leaf decide event for the genesis leaf,
534            // which contains only that leaf and nothing else.
535            if self.anchored_leaf.view_number() == ViewNumber::genesis() {
536                let (validated_state, state_delta) =
537                    TYPES::ValidatedState::genesis(&self.instance_state);
538
539                let qc = QuorumCertificate2::genesis(
540                    &validated_state,
541                    self.instance_state.as_ref(),
542                    self.upgrade_lock.upgrade(),
543                )
544                .await;
545
546                broadcast_event(
547                    Event {
548                        view_number: self.anchored_leaf.view_number(),
549                        event: EventType::Decide {
550                            leaf_chain: Arc::new(vec![LeafInfo::new(
551                                self.anchored_leaf.clone(),
552                                Arc::new(validated_state),
553                                Some(Arc::new(state_delta)),
554                                None,
555                                None,
556                            )]),
557                            committing_qc: Arc::new(CertificatePair::non_epoch_change(qc)),
558                            deciding_qc: None,
559                            block_size: None,
560                        },
561                    },
562                    &self.external_event_stream.0,
563                )
564                .await;
565            }
566        }
567    }
568
569    /// Emit an external event
570    async fn send_external_event(&self, event: Event<TYPES>) {
571        debug!(?event, "send_external_event");
572        broadcast_event(event, &self.external_event_stream.0).await;
573    }
574
575    /// Publishes a transaction asynchronously to the network.
576    ///
577    /// # Errors
578    ///
579    /// Always returns Ok; does not return an error if the transaction couldn't be published to the network
580    #[instrument(skip(self), err, target = "SystemContext", fields(id = self.id))]
581    pub async fn publish_transaction_async(
582        &self,
583        transaction: TYPES::Transaction,
584    ) -> Result<(), HotShotError<TYPES>> {
585        trace!("Adding transaction to our own queue");
586
587        let api = self.clone();
588
589        let consensus_reader = api.consensus.read().await;
590        let view_number = consensus_reader.cur_view();
591        let epoch = consensus_reader.cur_epoch();
592        drop(consensus_reader);
593
594        // Wrap up a message
595        let message_kind: DataMessage<TYPES> =
596            DataMessage::SubmitTransaction(transaction.clone(), view_number);
597        let message = Message {
598            sender: api.public_key.clone(),
599            kind: MessageKind::from(message_kind),
600        };
601
602        let serialized_message = self.upgrade_lock.serialize(&message).map_err(|err| {
603            HotShotError::FailedToSerialize(format!("failed to serialize transaction: {err}"))
604        })?;
605
606        let membership = match api.membership_coordinator.membership_for_epoch(epoch) {
607            Ok(m) => m,
608            Err(e) => return Err(HotShotError::InvalidState(e.message)),
609        };
610
611        spawn(async move {
612            let memberships_da_committee_members = membership
613                .da_committee_members(view_number)
614                .cloned()
615                .collect();
616
617            join! {
618                // TODO We should have a function that can return a network error if there is one
619                // but first we'd need to ensure our network implementations can support that
620                // (and not hang instead)
621
622                // version <0, 1> currently fixed; this is the same as VERSION_0_1,
623                // and will be updated to be part of SystemContext. I wanted to use associated
624                // constants in NodeType, but that seems to be unavailable in the current Rust.
625                api
626                    .network.da_broadcast_message(
627                        view_number.u64().into(),
628                        serialized_message,
629                        memberships_da_committee_members,
630                        BroadcastDelay::None,
631                    ),
632                api
633                    .send_external_event(Event {
634                        view_number,
635                        event: EventType::Transactions {
636                            transactions: vec![transaction],
637                        },
638                    }),
639            }
640        });
641        Ok(())
642    }
643
644    /// Returns a copy of the consensus struct
645    #[must_use]
646    pub fn consensus(&self) -> Arc<RwLock<Consensus<TYPES>>> {
647        Arc::clone(&self.consensus.inner_consensus)
648    }
649
650    /// Returns a copy of the instance state
651    pub fn instance_state(&self) -> Arc<TYPES::InstanceState> {
652        Arc::clone(&self.instance_state)
653    }
654
655    /// Returns a copy of the last decided leaf
656    /// # Panics
657    /// Panics if internal leaf for consensus is inconsistent
658    #[instrument(skip_all, target = "SystemContext", fields(id = self.id))]
659    pub async fn decided_leaf(&self) -> Leaf2<TYPES> {
660        self.consensus.read().await.decided_leaf()
661    }
662
663    /// [Non-blocking] instantly returns a copy of the last decided leaf if
664    /// it is available to be read. If not, we return `None`.
665    ///
666    /// # Panics
667    /// Panics if internal state for consensus is inconsistent
668    #[must_use]
669    #[instrument(skip_all, target = "SystemContext", fields(id = self.id))]
670    pub fn try_decided_leaf(&self) -> Option<Leaf2<TYPES>> {
671        self.consensus.try_read().map(|guard| guard.decided_leaf())
672    }
673
674    /// Returns the last decided validated state.
675    ///
676    /// # Panics
677    /// Panics if internal state for consensus is inconsistent
678    #[instrument(skip_all, target = "SystemContext", fields(id = self.id))]
679    pub async fn decided_state(&self) -> Arc<TYPES::ValidatedState> {
680        Arc::clone(&self.consensus.read().await.decided_state())
681    }
682
683    /// Get the validated state from a given `view`.
684    ///
685    /// Returns the requested state, if the [`SystemContext`] is tracking this view. Consensus
686    /// tracks views that have not yet been decided but could be in the future. This function may
687    /// return [`None`] if the requested view has already been decided (but see
688    /// [`decided_state`](Self::decided_state)) or if there is no path for the requested
689    /// view to ever be decided.
690    #[instrument(skip_all, target = "SystemContext", fields(id = self.id))]
691    pub async fn state(&self, view: ViewNumber) -> Option<Arc<TYPES::ValidatedState>> {
692        self.consensus.read().await.state(view).cloned()
693    }
694
695    /// Initializes a new [`SystemContext`] and does the work of setting up all the background tasks
696    ///
697    /// Assumes networking implementation is already primed.
698    ///
699    /// Underlying `HotShot` instance starts out paused, and must be unpaused
700    ///
701    /// Upon encountering an unrecoverable error, such as a failure to send to a broadcast channel,
702    /// the `HotShot` instance will log the error and shut down.
703    ///
704    /// To construct a [`SystemContext`] without setting up tasks, use `fn new` instead.
705    /// # Errors
706    ///
707    /// Can throw an error if `Self::new` fails.
708    #[allow(clippy::too_many_arguments)]
709    pub async fn init(
710        public_key: TYPES::SignatureKey,
711        private_key: <TYPES::SignatureKey as SignatureKey>::PrivateKey,
712        state_private_key: <TYPES::StateSignatureKey as StateSignatureKey>::StatePrivateKey,
713        node_id: u64,
714        config: HotShotConfig<TYPES>,
715        upgrade: versions::Upgrade,
716        memberships: EpochMembershipCoordinator<TYPES>,
717        network: Arc<I::Network>,
718        initializer: HotShotInitializer<TYPES>,
719        consensus_metrics: ConsensusMetricsValue,
720        storage: I::Storage,
721        storage_metrics: StorageMetricsValue,
722    ) -> Result<
723        (
724            SystemContextHandle<TYPES, I>,
725            Sender<Arc<HotShotEvent<TYPES>>>,
726            Receiver<Arc<HotShotEvent<TYPES>>>,
727        ),
728        HotShotError<TYPES>,
729    > {
730        let hotshot = Self::new(
731            public_key,
732            private_key,
733            state_private_key,
734            node_id,
735            config,
736            upgrade,
737            memberships,
738            network,
739            initializer,
740            consensus_metrics,
741            storage,
742            storage_metrics,
743        )
744        .await;
745        let handle = Arc::clone(&hotshot).run_tasks().await;
746        let (tx, rx) = hotshot.internal_event_stream.clone();
747
748        Ok((handle, tx, rx.activate()))
749    }
750    /// return the timeout for a view for `self`
751    #[must_use]
752    pub fn next_view_timeout(&self) -> u64 {
753        self.config.next_view_timeout
754    }
755}
756
757impl<TYPES: NodeType, I: NodeImplementation<TYPES>> SystemContext<TYPES, I> {
758    /// Spawn all tasks that operate on [`SystemContextHandle`].
759    ///
760    /// For a list of which tasks are being spawned, see this module's documentation.
761    pub async fn run_tasks(&self) -> SystemContextHandle<TYPES, I> {
762        let consensus_registry = ConsensusTaskRegistry::new();
763        let network_registry = NetworkTaskRegistry::new();
764
765        let output_event_stream = self.external_event_stream.clone();
766        let internal_event_stream = self.internal_event_stream.clone();
767
768        let mut handle = SystemContextHandle {
769            consensus_registry,
770            network_registry,
771            output_event_stream: output_event_stream.clone(),
772            internal_event_stream: internal_event_stream.clone(),
773            hotshot: self.clone().into(),
774            storage: self.storage.clone(),
775            network: Arc::clone(&self.network),
776            membership_coordinator: self.membership_coordinator.clone(),
777            epoch_height: self.config.epoch_height,
778        };
779
780        add_network_tasks::<TYPES, I>(&mut handle).await;
781        add_consensus_tasks::<TYPES, I>(&mut handle).await;
782
783        handle
784    }
785}
786
787/// An async broadcast channel
788type Channel<S> = (Sender<Arc<S>>, Receiver<Arc<S>>);
789
790/// Trait for handling messages for a node with a twin copy of consensus
791#[async_trait]
792pub trait TwinsHandlerState<TYPES, I>
793where
794    Self: std::fmt::Debug + Send + Sync,
795    TYPES: NodeType,
796    I: NodeImplementation<TYPES>,
797{
798    /// Handle a message sent to the twin from the network task, forwarding it to one of the two twins.
799    async fn send_handler(
800        &mut self,
801        event: &HotShotEvent<TYPES>,
802    ) -> Vec<Either<HotShotEvent<TYPES>, HotShotEvent<TYPES>>>;
803
804    /// Handle a message from either twin, forwarding it to the network task
805    async fn recv_handler(
806        &mut self,
807        event: &Either<HotShotEvent<TYPES>, HotShotEvent<TYPES>>,
808    ) -> Vec<HotShotEvent<TYPES>>;
809
810    /// Fuse two channels into a single channel
811    ///
812    /// Note: the channels are fused using two async loops, whose `JoinHandle`s are dropped.
813    fn fuse_channels(
814        &'static mut self,
815        left: Channel<HotShotEvent<TYPES>>,
816        right: Channel<HotShotEvent<TYPES>>,
817    ) -> Channel<HotShotEvent<TYPES>> {
818        let send_state = Arc::new(RwLock::new(self));
819        let recv_state = Arc::clone(&send_state);
820
821        let (left_sender, mut left_receiver) = (left.0, left.1);
822        let (right_sender, mut right_receiver) = (right.0, right.1);
823
824        // channel to the network task
825        let (sender_to_network, network_task_receiver) = broadcast(EVENT_CHANNEL_SIZE);
826        // channel from the network task
827        let (network_task_sender, mut receiver_from_network): Channel<HotShotEvent<TYPES>> =
828            broadcast(EVENT_CHANNEL_SIZE);
829
830        let _recv_loop_handle = spawn(async move {
831            loop {
832                let msg = match select(left_receiver.recv(), right_receiver.recv()).await {
833                    Either::Left(msg) => Either::Left(msg.0.unwrap().as_ref().clone()),
834                    Either::Right(msg) => Either::Right(msg.0.unwrap().as_ref().clone()),
835                };
836
837                let mut state = recv_state.write().await;
838                let mut result = state.recv_handler(&msg).await;
839
840                while let Some(event) = result.pop() {
841                    let _ = sender_to_network.broadcast(event.into()).await;
842                }
843            }
844        });
845
846        let _send_loop_handle = spawn(async move {
847            loop {
848                if let Ok(msg) = receiver_from_network.recv().await {
849                    let mut state = send_state.write().await;
850
851                    let mut result = state.send_handler(&msg).await;
852
853                    while let Some(event) = result.pop() {
854                        match event {
855                            Either::Left(msg) => {
856                                let _ = left_sender.broadcast(msg.into()).await;
857                            },
858                            Either::Right(msg) => {
859                                let _ = right_sender.broadcast(msg.into()).await;
860                            },
861                        }
862                    }
863                }
864            }
865        });
866
867        (network_task_sender, network_task_receiver)
868    }
869
870    #[allow(clippy::too_many_arguments)]
871    /// Spawn all tasks that operate on [`SystemContextHandle`].
872    ///
873    /// For a list of which tasks are being spawned, see this module's documentation.
874    async fn spawn_twin_handles(
875        &'static mut self,
876        public_key: TYPES::SignatureKey,
877        private_key: <TYPES::SignatureKey as SignatureKey>::PrivateKey,
878        state_private_key: <TYPES::StateSignatureKey as StateSignatureKey>::StatePrivateKey,
879        nonce: u64,
880        config: HotShotConfig<TYPES>,
881        upgrade: versions::Upgrade,
882        memberships: EpochMembershipCoordinator<TYPES>,
883        network: Arc<I::Network>,
884        initializer: HotShotInitializer<TYPES>,
885        consensus_metrics: ConsensusMetricsValue,
886        storage: I::Storage,
887        storage_metrics: StorageMetricsValue,
888    ) -> (SystemContextHandle<TYPES, I>, SystemContextHandle<TYPES, I>) {
889        let epoch_height = config.epoch_height;
890        let left_system_context = SystemContext::new(
891            public_key.clone(),
892            private_key.clone(),
893            state_private_key.clone(),
894            nonce,
895            config.clone(),
896            upgrade,
897            memberships.clone(),
898            Arc::clone(&network),
899            initializer.clone(),
900            consensus_metrics.clone(),
901            storage.clone(),
902            storage_metrics.clone(),
903        )
904        .await;
905        let right_system_context = SystemContext::new(
906            public_key,
907            private_key,
908            state_private_key,
909            nonce,
910            config,
911            upgrade,
912            memberships,
913            network,
914            initializer,
915            consensus_metrics,
916            storage,
917            storage_metrics,
918        )
919        .await;
920
921        // create registries for both handles
922        let left_consensus_registry = ConsensusTaskRegistry::new();
923        let left_network_registry = NetworkTaskRegistry::new();
924
925        let right_consensus_registry = ConsensusTaskRegistry::new();
926        let right_network_registry = NetworkTaskRegistry::new();
927
928        // create external channels for both handles
929        let (left_external_sender, left_external_receiver) = broadcast(EXTERNAL_EVENT_CHANNEL_SIZE);
930        let left_external_event_stream =
931            (left_external_sender, left_external_receiver.deactivate());
932
933        let (right_external_sender, right_external_receiver) =
934            broadcast(EXTERNAL_EVENT_CHANNEL_SIZE);
935        let right_external_event_stream =
936            (right_external_sender, right_external_receiver.deactivate());
937
938        // create internal channels for both handles
939        let (left_internal_sender, left_internal_receiver) = broadcast(EVENT_CHANNEL_SIZE);
940        let left_internal_event_stream = (
941            left_internal_sender.clone(),
942            left_internal_receiver.clone().deactivate(),
943        );
944
945        let (right_internal_sender, right_internal_receiver) = broadcast(EVENT_CHANNEL_SIZE);
946        let right_internal_event_stream = (
947            right_internal_sender.clone(),
948            right_internal_receiver.clone().deactivate(),
949        );
950
951        // create each handle
952        let mut left_handle = SystemContextHandle::<_, I> {
953            consensus_registry: left_consensus_registry,
954            network_registry: left_network_registry,
955            output_event_stream: left_external_event_stream.clone(),
956            internal_event_stream: left_internal_event_stream.clone(),
957            hotshot: Arc::clone(&left_system_context),
958            storage: left_system_context.storage.clone(),
959            network: Arc::clone(&left_system_context.network),
960            membership_coordinator: left_system_context.membership_coordinator.clone(),
961            epoch_height,
962        };
963
964        let mut right_handle = SystemContextHandle::<_, I> {
965            consensus_registry: right_consensus_registry,
966            network_registry: right_network_registry,
967            output_event_stream: right_external_event_stream.clone(),
968            internal_event_stream: right_internal_event_stream.clone(),
969            hotshot: Arc::clone(&right_system_context),
970            storage: right_system_context.storage.clone(),
971            network: Arc::clone(&right_system_context.network),
972            membership_coordinator: right_system_context.membership_coordinator.clone(),
973            epoch_height,
974        };
975
976        // add consensus tasks to each handle, using their individual internal event streams
977        add_consensus_tasks::<TYPES, I>(&mut left_handle).await;
978        add_consensus_tasks::<TYPES, I>(&mut right_handle).await;
979
980        // fuse the event streams from both handles before initializing the network tasks
981        let fused_internal_event_stream = self.fuse_channels(
982            (left_internal_sender, left_internal_receiver),
983            (right_internal_sender, right_internal_receiver),
984        );
985
986        // swap out the event stream on the left handle
987        left_handle.internal_event_stream = (
988            fused_internal_event_stream.0,
989            fused_internal_event_stream.1.deactivate(),
990        );
991
992        // add the network tasks to the left handle. note: because the left handle has the fused event stream, the network tasks on the left handle will handle messages from both handles.
993        add_network_tasks::<TYPES, I>(&mut left_handle).await;
994
995        // revert to the original event stream on the left handle, for any applications that want to listen to it
996        left_handle.internal_event_stream = left_internal_event_stream.clone();
997
998        (left_handle, right_handle)
999    }
1000}
1001
1002#[derive(Debug)]
1003/// A `TwinsHandlerState` that randomly forwards a message to either twin,
1004/// and returns messages from both.
1005pub struct RandomTwinsHandler;
1006
1007#[async_trait]
1008impl<TYPES: NodeType, I: NodeImplementation<TYPES>> TwinsHandlerState<TYPES, I>
1009    for RandomTwinsHandler
1010{
1011    async fn send_handler(
1012        &mut self,
1013        event: &HotShotEvent<TYPES>,
1014    ) -> Vec<Either<HotShotEvent<TYPES>, HotShotEvent<TYPES>>> {
1015        let random: bool = rand::thread_rng().r#gen();
1016
1017        #[allow(clippy::match_bool)]
1018        match random {
1019            true => vec![Either::Left(event.clone())],
1020            false => vec![Either::Right(event.clone())],
1021        }
1022    }
1023
1024    async fn recv_handler(
1025        &mut self,
1026        event: &Either<HotShotEvent<TYPES>, HotShotEvent<TYPES>>,
1027    ) -> Vec<HotShotEvent<TYPES>> {
1028        match event {
1029            Either::Left(msg) | Either::Right(msg) => vec![msg.clone()],
1030        }
1031    }
1032}
1033
1034/// A `TwinsHandlerState` that forwards each message to both twins,
1035/// and returns messages from each of them.
1036#[derive(Debug)]
1037pub struct DoubleTwinsHandler;
1038
1039#[async_trait]
1040impl<TYPES: NodeType, I: NodeImplementation<TYPES>> TwinsHandlerState<TYPES, I>
1041    for DoubleTwinsHandler
1042{
1043    async fn send_handler(
1044        &mut self,
1045        event: &HotShotEvent<TYPES>,
1046    ) -> Vec<Either<HotShotEvent<TYPES>, HotShotEvent<TYPES>>> {
1047        vec![Either::Left(event.clone()), Either::Right(event.clone())]
1048    }
1049
1050    async fn recv_handler(
1051        &mut self,
1052        event: &Either<HotShotEvent<TYPES>, HotShotEvent<TYPES>>,
1053    ) -> Vec<HotShotEvent<TYPES>> {
1054        match event {
1055            Either::Left(msg) | Either::Right(msg) => vec![msg.clone()],
1056        }
1057    }
1058}
1059
1060#[async_trait]
1061impl<TYPES: NodeType, I: NodeImplementation<TYPES>> ConsensusApi<TYPES, I>
1062    for SystemContextHandle<TYPES, I>
1063{
1064    fn total_nodes(&self) -> NonZeroUsize {
1065        self.hotshot.config.num_nodes_with_stake
1066    }
1067
1068    fn builder_timeout(&self) -> Duration {
1069        self.hotshot.config.builder_timeout
1070    }
1071
1072    async fn send_event(&self, event: Event<TYPES>) {
1073        debug!(?event, "send_event");
1074        broadcast_event(event, &self.hotshot.external_event_stream.0).await;
1075    }
1076
1077    fn public_key(&self) -> &TYPES::SignatureKey {
1078        &self.hotshot.public_key
1079    }
1080
1081    fn private_key(&self) -> &<TYPES::SignatureKey as SignatureKey>::PrivateKey {
1082        &self.hotshot.private_key
1083    }
1084
1085    fn state_private_key(
1086        &self,
1087    ) -> &<TYPES::StateSignatureKey as StateSignatureKey>::StatePrivateKey {
1088        &self.hotshot.state_private_key
1089    }
1090}
1091
1092#[derive(Clone, Debug, PartialEq)]
1093pub struct InitializerEpochInfo<TYPES: NodeType> {
1094    pub epoch: EpochNumber,
1095    pub drb_result: DrbResult,
1096    // pub stake_table: Option<StakeTable>, // TODO: Figure out how to connect this up
1097    pub block_header: Option<TYPES::BlockHeader>,
1098}
1099
1100/// initializer struct for creating starting block
1101#[derive(Clone, Debug)]
1102pub struct HotShotInitializer<TYPES: NodeType> {
1103    /// Instance-level state.
1104    pub instance_state: TYPES::InstanceState,
1105
1106    /// Epoch height
1107    pub epoch_height: u64,
1108
1109    /// Epoch start block
1110    pub epoch_start_block: u64,
1111
1112    /// the anchor leaf for the hotshot initializer
1113    pub anchor_leaf: Leaf2<TYPES>,
1114
1115    /// ValidatedState for the anchor leaf
1116    pub anchor_state: Arc<TYPES::ValidatedState>,
1117
1118    /// ValidatedState::Delta for the anchor leaf, optional.
1119    pub anchor_state_delta: Option<Arc<<TYPES::ValidatedState as ValidatedState<TYPES>>::Delta>>,
1120
1121    /// Starting view number that should be equivalent to the view the node shut down with last.
1122    pub start_view: ViewNumber,
1123
1124    /// The view we last performed an action in.  An action is proposing or voting for
1125    /// either the quorum or DA.
1126    pub last_actioned_view: ViewNumber,
1127
1128    /// Starting epoch number that should be equivalent to the epoch the node shut down with last.
1129    pub start_epoch: Option<EpochNumber>,
1130
1131    /// Highest QC that was seen, for genesis it's the genesis QC.  It should be for a view greater
1132    /// than `inner`s view number for the non genesis case because we must have seen higher QCs
1133    /// to decide on the leaf.
1134    pub high_qc: QuorumCertificate2<TYPES>,
1135
1136    /// Next epoch highest QC that was seen. This is needed to propose during epoch transition after restart.
1137    pub next_epoch_high_qc: Option<NextEpochQuorumCertificate2<TYPES>>,
1138
1139    /// Proposals we have sent out to provide to others for catchup
1140    pub saved_proposals: BTreeMap<ViewNumber, Proposal<TYPES, QuorumProposalWrapper<TYPES>>>,
1141
1142    /// Previously decided upgrade certificate; this is necessary if an upgrade has happened and we are not restarting with the new version
1143    pub decided_upgrade_certificate: Option<UpgradeCertificate<TYPES>>,
1144
1145    /// Undecided leaves that were seen, but not yet decided on.  These allow a restarting node
1146    /// to vote and propose right away if they didn't miss anything while down.
1147    pub undecided_leaves: BTreeMap<ViewNumber, Leaf2<TYPES>>,
1148
1149    /// Not yet decided state
1150    pub undecided_state: BTreeMap<ViewNumber, View<TYPES>>,
1151
1152    /// Saved VID shares
1153    pub saved_vid_shares: VidShares<TYPES>,
1154
1155    /// The last formed light client state update certificate if there's any
1156    pub state_cert: Option<LightClientStateUpdateCertificateV2<TYPES>>,
1157
1158    /// Saved epoch information. This must be sorted ascending by epoch.
1159    pub start_epoch_info: Vec<InitializerEpochInfo<TYPES>>,
1160}
1161
1162impl<TYPES: NodeType> HotShotInitializer<TYPES> {
1163    /// initialize from genesis
1164    /// # Errors
1165    /// If we are unable to apply the genesis block to the default state
1166    pub async fn from_genesis(
1167        instance_state: TYPES::InstanceState,
1168        epoch_height: u64,
1169        epoch_start_block: u64,
1170        start_epoch_info: Vec<InitializerEpochInfo<TYPES>>,
1171        upgrade: Upgrade,
1172    ) -> Result<Self, HotShotError<TYPES>> {
1173        let (validated_state, state_delta) = TYPES::ValidatedState::genesis(&instance_state);
1174        let high_qc = QuorumCertificate2::genesis(&validated_state, &instance_state, upgrade).await;
1175
1176        Ok(Self {
1177            anchor_leaf: Leaf2::genesis(&validated_state, &instance_state, upgrade.base).await,
1178            anchor_state: Arc::new(validated_state),
1179            anchor_state_delta: Some(Arc::new(state_delta)),
1180            start_view: ViewNumber::new(0),
1181            start_epoch: genesis_epoch_from_version(upgrade.base),
1182            last_actioned_view: ViewNumber::new(0),
1183            saved_proposals: BTreeMap::new(),
1184            high_qc,
1185            next_epoch_high_qc: None,
1186            decided_upgrade_certificate: None,
1187            undecided_leaves: BTreeMap::new(),
1188            undecided_state: BTreeMap::new(),
1189            instance_state,
1190            saved_vid_shares: BTreeMap::new(),
1191            epoch_height,
1192            state_cert: None,
1193            epoch_start_block,
1194            start_epoch_info,
1195        })
1196    }
1197
1198    /// Use saved proposals to update undecided leaves and state
1199    #[must_use]
1200    pub fn update_undecided(self) -> Self {
1201        let mut undecided_leaves = self.undecided_leaves.clone();
1202        let mut undecided_state = self.undecided_state.clone();
1203
1204        for proposal in self.saved_proposals.values() {
1205            // skip proposals unless they're newer than the anchor leaf
1206            if proposal.data.view_number() <= self.anchor_leaf.view_number() {
1207                continue;
1208            }
1209
1210            undecided_leaves.insert(
1211                proposal.data.view_number(),
1212                Leaf2::from_quorum_proposal(&proposal.data),
1213            );
1214        }
1215
1216        for leaf in undecided_leaves.values() {
1217            let view_inner = ViewInner::Leaf {
1218                leaf: leaf.commit(),
1219                state: Arc::new(TYPES::ValidatedState::from_header(leaf.block_header())),
1220                delta: None,
1221                epoch: leaf.epoch(self.epoch_height),
1222            };
1223            let view = View { view_inner };
1224
1225            undecided_state.insert(leaf.view_number(), view);
1226        }
1227
1228        Self {
1229            undecided_leaves,
1230            undecided_state,
1231            ..self
1232        }
1233    }
1234
1235    /// Create a `HotShotInitializer` from the given information.
1236    ///
1237    /// This function uses the anchor leaf to set the initial validated state,
1238    /// and populates `undecided_leaves` and `undecided_state` using `saved_proposals`.
1239    ///
1240    /// If you are able to or would prefer to set these yourself,
1241    /// you should use the `HotShotInitializer` constructor directly.
1242    #[allow(clippy::too_many_arguments)]
1243    pub fn load(
1244        instance_state: TYPES::InstanceState,
1245        epoch_height: u64,
1246        epoch_start_block: u64,
1247        start_epoch_info: Vec<InitializerEpochInfo<TYPES>>,
1248        anchor_leaf: Leaf2<TYPES>,
1249        (start_view, start_epoch): (ViewNumber, Option<EpochNumber>),
1250        (high_qc, next_epoch_high_qc): (
1251            QuorumCertificate2<TYPES>,
1252            Option<NextEpochQuorumCertificate2<TYPES>>,
1253        ),
1254        last_actioned_view: ViewNumber,
1255        saved_proposals: BTreeMap<ViewNumber, Proposal<TYPES, QuorumProposalWrapper<TYPES>>>,
1256        saved_vid_shares: VidShares<TYPES>,
1257        decided_upgrade_certificate: Option<UpgradeCertificate<TYPES>>,
1258        state_cert: Option<LightClientStateUpdateCertificateV2<TYPES>>,
1259    ) -> Self {
1260        let anchor_state = Arc::new(TYPES::ValidatedState::from_header(
1261            anchor_leaf.block_header(),
1262        ));
1263        let anchor_state_delta = None;
1264
1265        let initializer = Self {
1266            instance_state,
1267            epoch_height,
1268            epoch_start_block,
1269            anchor_leaf,
1270            anchor_state,
1271            anchor_state_delta,
1272            high_qc,
1273            start_view,
1274            start_epoch,
1275            last_actioned_view,
1276            saved_proposals,
1277            saved_vid_shares,
1278            next_epoch_high_qc,
1279            decided_upgrade_certificate,
1280            undecided_leaves: BTreeMap::new(),
1281            undecided_state: BTreeMap::new(),
1282            state_cert,
1283            start_epoch_info,
1284        };
1285
1286        initializer.update_undecided()
1287    }
1288}
1289
1290async fn load_start_epoch_info<TYPES: NodeType>(
1291    coordinator: &EpochMembershipCoordinator<TYPES>,
1292    start_epoch_info: &Vec<InitializerEpochInfo<TYPES>>,
1293    epoch_height: u64,
1294    epoch_start_block: u64,
1295) {
1296    let membership = coordinator.membership();
1297    let first_epoch_number =
1298        EpochNumber::new(epoch_from_block_number(epoch_start_block, epoch_height));
1299
1300    tracing::warn!("Calling set_first_epoch for epoch {first_epoch_number}");
1301    membership.set_first_epoch(first_epoch_number, INITIAL_DRB_RESULT);
1302
1303    let mut sorted_epoch_info = start_epoch_info.clone();
1304    sorted_epoch_info.sort_by_key(|info| info.epoch);
1305    for epoch_info in sorted_epoch_info {
1306        if let Some(block_header) = &epoch_info.block_header {
1307            tracing::warn!("Calling add_epoch_root for epoch {}", epoch_info.epoch);
1308
1309            coordinator
1310                .add_epoch_root(block_header.clone())
1311                .await
1312                .unwrap_or_else(|err| {
1313                    // REVIEW NOTE: Should we panic here? a failure here seems like it should be fatal
1314                    tracing::error!(
1315                        "Failed to add epoch root for epoch {}: {err}",
1316                        epoch_info.epoch
1317                    );
1318                });
1319        }
1320    }
1321
1322    for epoch_info in start_epoch_info {
1323        tracing::warn!("Calling add_drb_result for epoch {}", epoch_info.epoch);
1324        membership.add_drb_result(epoch_info.epoch, epoch_info.drb_result);
1325    }
1326}