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
// Copyright (c) 2021, Facebook, Inc. and its affiliates
// Copyright (c) 2022, Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use crate::primary::PrimaryWorkerMessage;
use config::{SharedCommittee, SharedWorkerCache, WorkerCache, WorkerIndex};
use crypto::PublicKey;
use network::{P2pNetwork, UnreliableNetwork};
use std::{collections::BTreeMap, sync::Arc};
use tap::TapOptional;
use tokio::{sync::watch, task::JoinHandle};
use tracing::{info, warn};
use types::{metered_channel::Receiver, Certificate, ReconfigureNotification, Round};

/// Receives the highest round reached by consensus and update it for all tasks.
pub struct StateHandler {
    /// The public key of this authority.
    name: PublicKey,
    /// The committee information.
    committee: SharedCommittee,
    /// The worker information cache.
    worker_cache: SharedWorkerCache,
    /// Receives the ordered certificates from consensus.
    rx_consensus: Receiver<Certificate>,
    /// Signals a new consensus round
    tx_consensus_round_updates: watch::Sender<u64>,
    /// Receives notifications to reconfigure the system.
    rx_reconfigure: Receiver<ReconfigureNotification>,
    /// Channel to signal committee changes.
    tx_reconfigure: watch::Sender<ReconfigureNotification>,
    /// The latest round committed by consensus.
    last_committed_round: Round,
    /// A network sender to notify our workers of cleanup events.
    network: P2pNetwork,
}

impl StateHandler {
    #[must_use]
    pub fn spawn(
        name: PublicKey,
        committee: SharedCommittee,
        worker_cache: SharedWorkerCache,
        rx_consensus: Receiver<Certificate>,
        tx_consensus_round_updates: watch::Sender<u64>,
        rx_reconfigure: Receiver<ReconfigureNotification>,
        tx_reconfigure: watch::Sender<ReconfigureNotification>,
        network: P2pNetwork,
    ) -> JoinHandle<()> {
        tokio::spawn(async move {
            Self {
                name,
                committee,
                worker_cache,
                rx_consensus,
                tx_consensus_round_updates,
                rx_reconfigure,
                tx_reconfigure,
                last_committed_round: 0,
                network,
            }
            .run()
            .await;
        })
    }

    async fn handle_sequenced(&mut self, certificate: Certificate) {
        // TODO [issue #9]: Re-include batch digests that have not been sequenced into our next block.

        let round = certificate.round();
        if round > self.last_committed_round {
            self.last_committed_round = round;

            // Trigger cleanup on the primary.
            let _ = self.tx_consensus_round_updates.send(round); // ignore error when receivers dropped.

            // Trigger cleanup on the workers..
            let addresses = self
                .worker_cache
                .load()
                .our_workers(&self.name)
                .expect("Our public key or worker id is not in the worker cache")
                .into_iter()
                .map(|x| x.name)
                .collect();
            let message = PrimaryWorkerMessage::Cleanup(round);
            self.network.unreliable_broadcast(addresses, &message);
        }
    }

    async fn run(&mut self) {
        info!(
            "StateHandler on node {} has started successfully.",
            self.name
        );
        loop {
            tokio::select! {
                Some(certificate) = self.rx_consensus.recv() => {
                    self.handle_sequenced(certificate).await;
                },

                Some(message) = self.rx_reconfigure.recv() => {
                    let shutdown = match &message {
                        ReconfigureNotification::NewEpoch(committee) => {
                            // Cleanup the network.
                            self.network.cleanup(self.worker_cache.load().network_diff(committee.keys()));

                            // Update the worker cache.
                            self.worker_cache.swap(Arc::new(WorkerCache {
                                epoch: committee.epoch,
                                workers: committee.keys().iter().map(|key|
                                    (
                                        (*key).clone(),
                                        self.worker_cache
                                            .load()
                                            .workers
                                            .get(key)
                                            .tap_none(||
                                                warn!("Worker cache does not have a key for the new committee member"))
                                            .unwrap_or(&WorkerIndex(BTreeMap::new()))
                                            .clone()
                                    )).collect(),
                            }));

                            // Update the committee.
                            self.committee.swap(Arc::new(committee.clone()));

                            // Trigger cleanup on the primary.
                            let _ = self.tx_consensus_round_updates.send(0); // ignore error when receivers dropped.

                            tracing::debug!("Committee updated to {}", self.committee);
                            false
                        },
                        ReconfigureNotification::UpdateCommittee(committee) => {
                            // Cleanup the network.
                            self.network.cleanup(self.worker_cache.load().network_diff(committee.keys()));

                            // Update the worker cache.
                            self.worker_cache.swap(Arc::new(WorkerCache {
                                epoch: committee.epoch,
                                workers: committee.keys().iter().map(|key|
                                    (
                                        (*key).clone(),
                                        self.worker_cache
                                            .load()
                                            .workers
                                            .get(key)
                                            .tap_none(||
                                                warn!("Worker cache does not have a key for the new committee member"))
                                            .unwrap_or(&WorkerIndex(BTreeMap::new()))
                                            .clone()
                                    )).collect(),
                            }));

                            // Update the committee.
                            self.committee.swap(Arc::new(committee.clone()));

                            tracing::debug!("Committee updated to {}", self.committee);
                            false
                        }
                        ReconfigureNotification::Shutdown => true,
                    };

                    // Notify all other tasks.
                    self.tx_reconfigure
                        .send(message)
                        .expect("Reconfigure channel dropped");

                    // Exit only when we are sure that all the other tasks received
                    // the shutdown message.
                    if shutdown {
                        self.tx_reconfigure.closed().await;
                        return;
                    }
                }
            }
        }
    }
}