1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
// Copyright (c) 2021-2024 Espresso Systems (espressosys.com)
// This file is part of the HotShot repository.

// You should have received a copy of the MIT License
// along with the HotShot repository. If not, see <https://mit-license.org/>.

use std::{
    collections::{BTreeMap, HashMap},
    fmt::Debug,
    sync::Arc,
    time::Duration,
};

use async_broadcast::{Receiver, Sender};
use async_lock::RwLock;
use async_trait::async_trait;
use hotshot_task::task::TaskState;
use hotshot_types::{
    message::UpgradeLock,
    simple_certificate::{
        ViewSyncCommitCertificate2, ViewSyncFinalizeCertificate2, ViewSyncPreCommitCertificate2,
    },
    simple_vote::{
        ViewSyncCommitData2, ViewSyncCommitVote2, ViewSyncFinalizeData2, ViewSyncFinalizeVote2,
        ViewSyncPreCommitData2, ViewSyncPreCommitVote2,
    },
    traits::{
        election::Membership,
        node_implementation::{ConsensusTime, NodeType, Versions},
        signature_key::SignatureKey,
    },
    utils::EpochTransitionIndicator,
    vote::{Certificate, HasViewNumber, Vote},
};
use tokio::{spawn, task::JoinHandle, time::sleep};
use tracing::instrument;
use utils::anytrace::*;

use crate::{
    events::{HotShotEvent, HotShotTaskCompleted},
    helpers::broadcast_event,
    vote_collection::{
        create_vote_accumulator, AccumulatorInfo, HandleVoteEvent, VoteCollectionTaskState,
    },
};
#[derive(PartialEq, PartialOrd, Clone, Debug, Eq, Hash)]
/// Phases of view sync
pub enum ViewSyncPhase {
    /// No phase; before the protocol has begun
    None,
    /// PreCommit phase
    PreCommit,
    /// Commit phase
    Commit,
    /// Finalize phase
    Finalize,
}

/// Type alias for a map from View Number to Relay to Vote Task
type RelayMap<TYPES, VOTE, CERT, V> = HashMap<
    <TYPES as NodeType>::View,
    BTreeMap<u64, VoteCollectionTaskState<TYPES, VOTE, CERT, V>>,
>;

/// Main view sync task state
pub struct ViewSyncTaskState<TYPES: NodeType, V: Versions> {
    /// View HotShot is currently in
    pub cur_view: TYPES::View,

    /// View HotShot wishes to be in
    pub next_view: TYPES::View,

    /// Epoch HotShot is currently in
    pub cur_epoch: TYPES::Epoch,

    /// Membership for the quorum
    pub membership: Arc<RwLock<TYPES::Membership>>,

    /// This Nodes Public Key
    pub public_key: TYPES::SignatureKey,

    /// Our Private Key
    pub private_key: <TYPES::SignatureKey as SignatureKey>::PrivateKey,

    /// Our node id; for logging
    pub id: u64,

    /// How many timeouts we've seen in a row; is reset upon a successful view change
    pub num_timeouts_tracked: u64,

    /// Map of running replica tasks
    pub replica_task_map: RwLock<HashMap<TYPES::View, ViewSyncReplicaTaskState<TYPES, V>>>,

    /// Map of pre-commit vote accumulates for the relay
    pub pre_commit_relay_map: RwLock<
        RelayMap<TYPES, ViewSyncPreCommitVote2<TYPES>, ViewSyncPreCommitCertificate2<TYPES>, V>,
    >,

    /// Map of commit vote accumulates for the relay
    pub commit_relay_map:
        RwLock<RelayMap<TYPES, ViewSyncCommitVote2<TYPES>, ViewSyncCommitCertificate2<TYPES>, V>>,

    /// Map of finalize vote accumulates for the relay
    pub finalize_relay_map: RwLock<
        RelayMap<TYPES, ViewSyncFinalizeVote2<TYPES>, ViewSyncFinalizeCertificate2<TYPES>, V>,
    >,

    /// Timeout duration for view sync rounds
    pub view_sync_timeout: Duration,

    /// Last view we garbage collected old tasks
    pub last_garbage_collected_view: TYPES::View,

    /// Lock for a decided upgrade
    pub upgrade_lock: UpgradeLock<TYPES, V>,
}

#[async_trait]
impl<TYPES: NodeType, V: Versions> TaskState for ViewSyncTaskState<TYPES, V> {
    type Event = HotShotEvent<TYPES>;

    async fn handle_event(
        &mut self,
        event: Arc<Self::Event>,
        sender: &Sender<Arc<Self::Event>>,
        _receiver: &Receiver<Arc<Self::Event>>,
    ) -> Result<()> {
        self.handle(event, sender.clone()).await
    }

    fn cancel_subtasks(&mut self) {}
}

/// State of a view sync replica task
pub struct ViewSyncReplicaTaskState<TYPES: NodeType, V: Versions> {
    /// Timeout for view sync rounds
    pub view_sync_timeout: Duration,

    /// Current round HotShot is in
    pub cur_view: TYPES::View,

    /// Round HotShot wishes to be in
    pub next_view: TYPES::View,

    /// Current epoch HotShot is in
    pub cur_epoch: TYPES::Epoch,

    /// The relay index we are currently on
    pub relay: u64,

    /// Whether we have seen a finalized certificate
    pub finalized: bool,

    /// Whether we have already sent a view change event for `next_view`
    pub sent_view_change_event: bool,

    /// Timeout task handle, when it expires we try the next relay
    pub timeout_task: Option<JoinHandle<()>>,

    /// Our node id; for logging
    pub id: u64,

    /// Membership for the quorum
    pub membership: Arc<RwLock<TYPES::Membership>>,

    /// This Nodes Public Key
    pub public_key: TYPES::SignatureKey,

    /// Our Private Key
    pub private_key: <TYPES::SignatureKey as SignatureKey>::PrivateKey,

    /// Lock for a decided upgrade
    pub upgrade_lock: UpgradeLock<TYPES, V>,
}

#[async_trait]
impl<TYPES: NodeType, V: Versions> TaskState for ViewSyncReplicaTaskState<TYPES, V> {
    type Event = HotShotEvent<TYPES>;

    async fn handle_event(
        &mut self,
        event: Arc<Self::Event>,
        sender: &Sender<Arc<Self::Event>>,
        _receiver: &Receiver<Arc<Self::Event>>,
    ) -> Result<()> {
        self.handle(event, sender.clone()).await;

        Ok(())
    }

    fn cancel_subtasks(&mut self) {}
}

impl<TYPES: NodeType, V: Versions> ViewSyncTaskState<TYPES, V> {
    #[instrument(skip_all, fields(id = self.id, view = *self.cur_view), name = "View Sync Main Task", level = "error")]
    #[allow(clippy::type_complexity)]
    /// Handles incoming events for the main view sync task
    pub async fn send_to_or_create_replica(
        &mut self,
        event: Arc<HotShotEvent<TYPES>>,
        view: TYPES::View,
        sender: &Sender<Arc<HotShotEvent<TYPES>>>,
    ) {
        // This certificate is old, we can throw it away
        // If next view = cert round, then that means we should already have a task running for it
        if self.cur_view > view {
            tracing::debug!("Already in a higher view than the view sync message");
            return;
        }

        let mut task_map = self.replica_task_map.write().await;

        if let Some(replica_task) = task_map.get_mut(&view) {
            // Forward event then return
            tracing::debug!("Forwarding message");
            let result = replica_task
                .handle(Arc::clone(&event), sender.clone())
                .await;

            if result == Some(HotShotTaskCompleted) {
                // The protocol has finished
                task_map.remove(&view);
                return;
            }

            return;
        }

        // We do not have a replica task already running, so start one
        let mut replica_state: ViewSyncReplicaTaskState<TYPES, V> = ViewSyncReplicaTaskState {
            cur_view: view,
            next_view: view,
            cur_epoch: self.cur_epoch,
            relay: 0,
            finalized: false,
            sent_view_change_event: false,
            timeout_task: None,
            membership: Arc::clone(&self.membership),
            public_key: self.public_key.clone(),
            private_key: self.private_key.clone(),
            view_sync_timeout: self.view_sync_timeout,
            id: self.id,
            upgrade_lock: self.upgrade_lock.clone(),
        };

        let result = replica_state
            .handle(Arc::clone(&event), sender.clone())
            .await;

        if result == Some(HotShotTaskCompleted) {
            // The protocol has finished
            return;
        }

        task_map.insert(view, replica_state);
    }

    #[instrument(skip_all, fields(id = self.id, view = *self.cur_view, epoch = *self.cur_epoch), name = "View Sync Main Task", level = "error")]
    #[allow(clippy::type_complexity)]
    /// Handles incoming events for the main view sync task
    pub async fn handle(
        &mut self,
        event: Arc<HotShotEvent<TYPES>>,
        event_stream: Sender<Arc<HotShotEvent<TYPES>>>,
    ) -> Result<()> {
        match event.as_ref() {
            HotShotEvent::ViewSyncPreCommitCertificateRecv(certificate) => {
                tracing::debug!("Received view sync cert for phase {:?}", certificate);
                let view = certificate.view_number();
                self.send_to_or_create_replica(event, view, &event_stream)
                    .await;
            }
            HotShotEvent::ViewSyncCommitCertificateRecv(certificate) => {
                tracing::debug!("Received view sync cert for phase {:?}", certificate);
                let view = certificate.view_number();
                self.send_to_or_create_replica(event, view, &event_stream)
                    .await;
            }
            HotShotEvent::ViewSyncFinalizeCertificateRecv(certificate) => {
                tracing::debug!("Received view sync cert for phase {:?}", certificate);
                let view = certificate.view_number();
                self.send_to_or_create_replica(event, view, &event_stream)
                    .await;
            }
            HotShotEvent::ViewSyncTimeout(view, _, _) => {
                tracing::debug!("view sync timeout in main task {:?}", view);
                let view = *view;
                self.send_to_or_create_replica(event, view, &event_stream)
                    .await;
            }

            HotShotEvent::ViewSyncPreCommitVoteRecv(ref vote) => {
                let mut map = self.pre_commit_relay_map.write().await;
                let vote_view = vote.view_number();
                let relay = vote.date().relay;
                let relay_map = map.entry(vote_view).or_insert(BTreeMap::new());
                if let Some(relay_task) = relay_map.get_mut(&relay) {
                    tracing::debug!("Forwarding message");

                    // Handle the vote and check if the accumulator has returned successfully
                    if relay_task
                        .handle_vote_event(Arc::clone(&event), &event_stream)
                        .await?
                        .is_some()
                    {
                        map.remove(&vote_view);
                    }

                    return Ok(());
                }

                // We do not have a relay task already running, so start one
                ensure!(
                    self.membership
                        .read()
                        .await
                        .leader(vote_view + relay, self.cur_epoch)?
                        == self.public_key,
                    "View sync vote sent to wrong leader"
                );

                let info = AccumulatorInfo {
                    public_key: self.public_key.clone(),
                    membership: Arc::clone(&self.membership),
                    view: vote_view,
                    id: self.id,
                    epoch: vote.data.epoch,
                };
                let vote_collector = create_vote_accumulator(
                    &info,
                    event,
                    &event_stream,
                    self.upgrade_lock.clone(),
                    EpochTransitionIndicator::NotInTransition,
                )
                .await?;

                relay_map.insert(relay, vote_collector);
            }

            HotShotEvent::ViewSyncCommitVoteRecv(ref vote) => {
                let mut map = self.commit_relay_map.write().await;
                let vote_view = vote.view_number();
                let relay = vote.date().relay;
                let relay_map = map.entry(vote_view).or_insert(BTreeMap::new());
                if let Some(relay_task) = relay_map.get_mut(&relay) {
                    tracing::debug!("Forwarding message");

                    // Handle the vote and check if the accumulator has returned successfully
                    if relay_task
                        .handle_vote_event(Arc::clone(&event), &event_stream)
                        .await?
                        .is_some()
                    {
                        map.remove(&vote_view);
                    }

                    return Ok(());
                }

                // We do not have a relay task already running, so start one
                ensure!(
                    self.membership
                        .read()
                        .await
                        .leader(vote_view + relay, self.cur_epoch)?
                        == self.public_key,
                    debug!("View sync vote sent to wrong leader")
                );

                let info = AccumulatorInfo {
                    public_key: self.public_key.clone(),
                    membership: Arc::clone(&self.membership),
                    view: vote_view,
                    id: self.id,
                    epoch: vote.data.epoch,
                };

                let vote_collector = create_vote_accumulator(
                    &info,
                    event,
                    &event_stream,
                    self.upgrade_lock.clone(),
                    EpochTransitionIndicator::NotInTransition,
                )
                .await?;
                relay_map.insert(relay, vote_collector);
            }

            HotShotEvent::ViewSyncFinalizeVoteRecv(vote) => {
                let mut map = self.finalize_relay_map.write().await;
                let vote_view = vote.view_number();
                let relay = vote.date().relay;
                let relay_map = map.entry(vote_view).or_insert(BTreeMap::new());
                if let Some(relay_task) = relay_map.get_mut(&relay) {
                    tracing::debug!("Forwarding message");

                    // Handle the vote and check if the accumulator has returned successfully
                    if relay_task
                        .handle_vote_event(Arc::clone(&event), &event_stream)
                        .await?
                        .is_some()
                    {
                        map.remove(&vote_view);
                    }

                    return Ok(());
                }

                // We do not have a relay task already running, so start one
                ensure!(
                    self.membership
                        .read()
                        .await
                        .leader(vote_view + relay, self.cur_epoch)?
                        == self.public_key,
                    debug!("View sync vote sent to wrong leader")
                );

                let info = AccumulatorInfo {
                    public_key: self.public_key.clone(),
                    membership: Arc::clone(&self.membership),
                    view: vote_view,
                    id: self.id,
                    epoch: vote.data.epoch,
                };
                let vote_collector = create_vote_accumulator(
                    &info,
                    event,
                    &event_stream,
                    self.upgrade_lock.clone(),
                    EpochTransitionIndicator::NotInTransition,
                )
                .await;
                if let Ok(vote_task) = vote_collector {
                    relay_map.insert(relay, vote_task);
                }
            }

            &HotShotEvent::ViewChange(new_view, epoch) => {
                if epoch > self.cur_epoch {
                    self.cur_epoch = epoch;
                }
                let new_view = TYPES::View::new(*new_view);
                if self.cur_view < new_view {
                    tracing::debug!(
                        "Change from view {} to view {} in view sync task",
                        *self.cur_view,
                        *new_view
                    );

                    self.cur_view = new_view;
                    self.next_view = self.cur_view;
                    self.num_timeouts_tracked = 0;

                    // Garbage collect old tasks
                    // We could put this into a separate async task, but that would require making several fields on ViewSyncTaskState thread-safe and harm readability.  In the common case this will have zero tasks to clean up.
                    // run GC
                    for i in *self.last_garbage_collected_view..*self.cur_view {
                        self.replica_task_map
                            .write()
                            .await
                            .remove_entry(&TYPES::View::new(i));
                        self.pre_commit_relay_map
                            .write()
                            .await
                            .remove_entry(&TYPES::View::new(i));
                        self.commit_relay_map
                            .write()
                            .await
                            .remove_entry(&TYPES::View::new(i));
                        self.finalize_relay_map
                            .write()
                            .await
                            .remove_entry(&TYPES::View::new(i));
                    }

                    self.last_garbage_collected_view = self.cur_view - 1;
                }
            }
            &HotShotEvent::Timeout(view_number, ..) => {
                // This is an old timeout and we can ignore it
                ensure!(
                    view_number >= self.cur_view,
                    debug!("Discarding old timeout vote.")
                );

                self.num_timeouts_tracked += 1;
                let leader = self
                    .membership
                    .read()
                    .await
                    .leader(view_number, self.cur_epoch)?;
                tracing::warn!(
                    %leader,
                    leader_mnemonic = hotshot_types::utils::mnemonic(&leader),
                    view_number = *view_number,
                    num_timeouts_tracked = self.num_timeouts_tracked,
                    "view timed out",
                );

                if self.num_timeouts_tracked >= 3 {
                    tracing::error!("Too many consecutive timeouts!  This shouldn't happen");
                }

                if self.num_timeouts_tracked >= 2 {
                    tracing::error!("Starting view sync protocol for view {}", *view_number + 1);

                    self.send_to_or_create_replica(
                        Arc::new(HotShotEvent::ViewSyncTrigger(view_number + 1)),
                        view_number + 1,
                        &event_stream,
                    )
                    .await;
                } else {
                    // If this is the first timeout we've seen advance to the next view
                    self.cur_view = view_number + 1;
                    broadcast_event(
                        Arc::new(HotShotEvent::ViewChange(self.cur_view, self.cur_epoch)),
                        &event_stream,
                    )
                    .await;
                }
            }

            _ => {}
        }
        Ok(())
    }
}

impl<TYPES: NodeType, V: Versions> ViewSyncReplicaTaskState<TYPES, V> {
    #[instrument(skip_all, fields(id = self.id, view = *self.cur_view, epoch = *self.cur_epoch), name = "View Sync Replica Task", level = "error")]
    /// Handle incoming events for the view sync replica task
    pub async fn handle(
        &mut self,
        event: Arc<HotShotEvent<TYPES>>,
        event_stream: Sender<Arc<HotShotEvent<TYPES>>>,
    ) -> Option<HotShotTaskCompleted> {
        match event.as_ref() {
            HotShotEvent::ViewSyncPreCommitCertificateRecv(certificate) => {
                let last_seen_certificate = ViewSyncPhase::PreCommit;

                // Ignore certificate if it is for an older round
                if certificate.view_number() < self.next_view {
                    tracing::warn!("We're already in a higher round");

                    return None;
                }

                let membership_reader = self.membership.read().await;
                let membership_stake_table = membership_reader.stake_table(self.cur_epoch);
                let membership_failure_threshold =
                    membership_reader.failure_threshold(self.cur_epoch);
                drop(membership_reader);

                // If certificate is not valid, return current state
                if !certificate
                    .is_valid_cert(
                        membership_stake_table,
                        membership_failure_threshold,
                        &self.upgrade_lock,
                    )
                    .await
                {
                    tracing::error!("Not valid view sync cert! {:?}", certificate.data());

                    return None;
                }

                // If certificate is for a higher round shutdown this task
                // since another task should have been started for the higher round
                if certificate.view_number() > self.next_view {
                    return Some(HotShotTaskCompleted);
                }

                if certificate.data().relay > self.relay {
                    self.relay = certificate.data().relay;
                }

                let Ok(vote) = ViewSyncCommitVote2::<TYPES>::create_signed_vote(
                    ViewSyncCommitData2 {
                        relay: certificate.data().relay,
                        round: self.next_view,
                        epoch: certificate.data().epoch,
                    },
                    self.next_view,
                    &self.public_key,
                    &self.private_key,
                    &self.upgrade_lock,
                )
                .await
                else {
                    tracing::error!("Failed to sign ViewSyncCommitData!");
                    return None;
                };

                broadcast_event(
                    Arc::new(HotShotEvent::ViewSyncCommitVoteSend(vote)),
                    &event_stream,
                )
                .await;

                if let Some(timeout_task) = self.timeout_task.take() {
                    timeout_task.abort();
                }

                self.timeout_task = Some(spawn({
                    let stream = event_stream.clone();
                    let phase = last_seen_certificate;
                    let relay = self.relay;
                    let next_view = self.next_view;
                    let timeout = self.view_sync_timeout;
                    async move {
                        sleep(timeout).await;
                        tracing::warn!("Vote sending timed out in ViewSyncPreCommitCertificateRecv, Relay = {}", relay);

                        broadcast_event(
                            Arc::new(HotShotEvent::ViewSyncTimeout(
                                TYPES::View::new(*next_view),
                                relay,
                                phase,
                            )),
                            &stream,
                        )
                        .await;
                    }
                }));
            }

            HotShotEvent::ViewSyncCommitCertificateRecv(certificate) => {
                let last_seen_certificate = ViewSyncPhase::Commit;

                // Ignore certificate if it is for an older round
                if certificate.view_number() < self.next_view {
                    tracing::warn!("We're already in a higher round");

                    return None;
                }

                let membership_reader = self.membership.read().await;
                let membership_stake_table = membership_reader.stake_table(self.cur_epoch);
                let membership_success_threshold =
                    membership_reader.success_threshold(self.cur_epoch);
                drop(membership_reader);

                // If certificate is not valid, return current state
                if !certificate
                    .is_valid_cert(
                        membership_stake_table,
                        membership_success_threshold,
                        &self.upgrade_lock,
                    )
                    .await
                {
                    tracing::error!("Not valid view sync cert! {:?}", certificate.data());

                    return None;
                }

                // If certificate is for a higher round shutdown this task
                // since another task should have been started for the higher round
                if certificate.view_number() > self.next_view {
                    return Some(HotShotTaskCompleted);
                }

                if certificate.data().relay > self.relay {
                    self.relay = certificate.data().relay;
                }

                let Ok(vote) = ViewSyncFinalizeVote2::<TYPES>::create_signed_vote(
                    ViewSyncFinalizeData2 {
                        relay: certificate.data().relay,
                        round: self.next_view,
                        epoch: certificate.data().epoch,
                    },
                    self.next_view,
                    &self.public_key,
                    &self.private_key,
                    &self.upgrade_lock,
                )
                .await
                else {
                    tracing::error!("Failed to sign view sync finalized vote!");
                    return None;
                };

                broadcast_event(
                    Arc::new(HotShotEvent::ViewSyncFinalizeVoteSend(vote)),
                    &event_stream,
                )
                .await;

                tracing::info!(
                    "View sync protocol has received view sync evidence to update the view to {}",
                    *self.next_view
                );

                // TODO: Figure out the correct way to view sync across epochs if needed
                broadcast_event(
                    Arc::new(HotShotEvent::ViewChange(self.next_view, self.cur_epoch)),
                    &event_stream,
                )
                .await;

                if let Some(timeout_task) = self.timeout_task.take() {
                    timeout_task.abort();
                }
                self.timeout_task = Some(spawn({
                    let stream = event_stream.clone();
                    let phase = last_seen_certificate;
                    let relay = self.relay;
                    let next_view = self.next_view;
                    let timeout = self.view_sync_timeout;
                    async move {
                        sleep(timeout).await;
                        tracing::warn!(
                            "Vote sending timed out in ViewSyncCommitCertificateRecv, relay = {}",
                            relay
                        );
                        broadcast_event(
                            Arc::new(HotShotEvent::ViewSyncTimeout(
                                TYPES::View::new(*next_view),
                                relay,
                                phase,
                            )),
                            &stream,
                        )
                        .await;
                    }
                }));
            }

            HotShotEvent::ViewSyncFinalizeCertificateRecv(certificate) => {
                // Ignore certificate if it is for an older round
                if certificate.view_number() < self.next_view {
                    tracing::warn!("We're already in a higher round");

                    return None;
                }

                let membership_reader = self.membership.read().await;
                let membership_stake_table = membership_reader.stake_table(self.cur_epoch);
                let membership_success_threshold =
                    membership_reader.success_threshold(self.cur_epoch);
                drop(membership_reader);

                // If certificate is not valid, return current state
                if !certificate
                    .is_valid_cert(
                        membership_stake_table,
                        membership_success_threshold,
                        &self.upgrade_lock,
                    )
                    .await
                {
                    tracing::error!("Not valid view sync cert! {:?}", certificate.data());

                    return None;
                }

                // If certificate is for a higher round shutdown this task
                // since another task should have been started for the higher round
                if certificate.view_number() > self.next_view {
                    return Some(HotShotTaskCompleted);
                }

                if certificate.data().relay > self.relay {
                    self.relay = certificate.data().relay;
                }

                if let Some(timeout_task) = self.timeout_task.take() {
                    timeout_task.abort();
                }

                // TODO: Figure out the correct way to view sync across epochs if needed
                broadcast_event(
                    Arc::new(HotShotEvent::ViewChange(self.next_view, self.cur_epoch)),
                    &event_stream,
                )
                .await;
                return Some(HotShotTaskCompleted);
            }

            HotShotEvent::ViewSyncTrigger(view_number) => {
                let view_number = *view_number;
                if self.next_view != TYPES::View::new(*view_number) {
                    tracing::error!("Unexpected view number to trigger view sync");
                    return None;
                }

                let epoch = self.cur_epoch;
                let Ok(vote) = ViewSyncPreCommitVote2::<TYPES>::create_signed_vote(
                    ViewSyncPreCommitData2 {
                        relay: 0,
                        round: view_number,
                        epoch,
                    },
                    view_number,
                    &self.public_key,
                    &self.private_key,
                    &self.upgrade_lock,
                )
                .await
                else {
                    tracing::error!("Failed to sign pre commit vote!");
                    return None;
                };

                broadcast_event(
                    Arc::new(HotShotEvent::ViewSyncPreCommitVoteSend(vote)),
                    &event_stream,
                )
                .await;

                self.timeout_task = Some(spawn({
                    let stream = event_stream.clone();
                    let relay = self.relay;
                    let next_view = self.next_view;
                    let timeout = self.view_sync_timeout;
                    async move {
                        sleep(timeout).await;
                        tracing::warn!("Vote sending timed out in ViewSyncTrigger");
                        broadcast_event(
                            Arc::new(HotShotEvent::ViewSyncTimeout(
                                TYPES::View::new(*next_view),
                                relay,
                                ViewSyncPhase::None,
                            )),
                            &stream,
                        )
                        .await;
                    }
                }));

                return None;
            }

            HotShotEvent::ViewSyncTimeout(round, relay, last_seen_certificate) => {
                let round = *round;
                // Shouldn't ever receive a timeout for a relay higher than ours
                if TYPES::View::new(*round) == self.next_view && *relay == self.relay {
                    if let Some(timeout_task) = self.timeout_task.take() {
                        timeout_task.abort();
                    }
                    self.relay += 1;
                    match last_seen_certificate {
                        ViewSyncPhase::None | ViewSyncPhase::PreCommit | ViewSyncPhase::Commit => {
                            let Ok(vote) = ViewSyncPreCommitVote2::<TYPES>::create_signed_vote(
                                ViewSyncPreCommitData2 {
                                    relay: self.relay,
                                    round: self.next_view,
                                    epoch: self.cur_epoch,
                                },
                                self.next_view,
                                &self.public_key,
                                &self.private_key,
                                &self.upgrade_lock,
                            )
                            .await
                            else {
                                tracing::error!("Failed to sign ViewSyncPreCommitData!");
                                return None;
                            };

                            broadcast_event(
                                Arc::new(HotShotEvent::ViewSyncPreCommitVoteSend(vote)),
                                &event_stream,
                            )
                            .await;
                        }
                        ViewSyncPhase::Finalize => {
                            // This should never occur
                            unimplemented!()
                        }
                    }

                    self.timeout_task = Some(spawn({
                        let stream = event_stream.clone();
                        let relay = self.relay;
                        let next_view = self.next_view;
                        let timeout = self.view_sync_timeout;
                        let last_cert = last_seen_certificate.clone();
                        async move {
                            sleep(timeout).await;
                            tracing::warn!(
                                "Vote sending timed out in ViewSyncTimeout relay = {}",
                                relay
                            );
                            broadcast_event(
                                Arc::new(HotShotEvent::ViewSyncTimeout(
                                    TYPES::View::new(*next_view),
                                    relay,
                                    last_cert,
                                )),
                                &stream,
                            )
                            .await;
                        }
                    }));

                    return None;
                }
            }
            _ => return None,
        }
        None
    }
}