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
use std::{collections::HashMap, net::SocketAddr, time::Duration};

use massa_channel::{sender::MassaSender, MassaChannel};
use massa_models::{
    block_header::SecuredHeader,
    block_id::BlockId,
    prehash::{PreHashMap, PreHashSet},
    stats::NetworkStats,
};
use massa_protocol_exports::{BootstrapPeers, PeerId, ProtocolController, ProtocolError};
use massa_storage::Storage;
use peernet::peer::PeerConnectionType;

use crate::{
    connectivity::ConnectivityCommand,
    handlers::{
        block_handler::{
            commands_propagation::BlockHandlerPropagationCommand,
            commands_retrieval::BlockHandlerRetrievalCommand,
        },
        endorsement_handler::commands_propagation::EndorsementHandlerPropagationCommand,
        operation_handler::commands_propagation::OperationHandlerPropagationCommand,
        peer_handler::models::PeerManagementCmd,
    },
};

#[derive(Clone)]
pub struct ProtocolControllerImpl {
    // Use Option here in order to be able to drop the Sender without dropping the controller
    // using `option.take()`.
    // This is needed as to be able to stop the controller, the Sender has to be dropped,
    // if not, the handler will deadlock on `recv`
    // As this is never None, we allow ourselves to use `unwrap` to acceed to the senders
    pub sender_block_retrieval_handler: Option<MassaSender<BlockHandlerRetrievalCommand>>,
    pub sender_block_handler: Option<MassaSender<BlockHandlerPropagationCommand>>,
    pub sender_operation_handler: Option<MassaSender<OperationHandlerPropagationCommand>>,
    pub sender_endorsement_handler: Option<MassaSender<EndorsementHandlerPropagationCommand>>,
    pub sender_connectivity_thread: Option<MassaSender<ConnectivityCommand>>,
    pub sender_peer_management_thread: Option<MassaSender<PeerManagementCmd>>,
}

impl ProtocolControllerImpl {
    pub fn new(
        sender_block_retrieval_handler: MassaSender<BlockHandlerRetrievalCommand>,
        sender_block_handler: MassaSender<BlockHandlerPropagationCommand>,
        sender_operation_handler: MassaSender<OperationHandlerPropagationCommand>,
        sender_endorsement_handler: MassaSender<EndorsementHandlerPropagationCommand>,
        sender_connectivity_thread: MassaSender<ConnectivityCommand>,
        sender_peer_management_thread: MassaSender<PeerManagementCmd>,
    ) -> Self {
        ProtocolControllerImpl {
            sender_block_retrieval_handler: Some(sender_block_retrieval_handler),
            sender_block_handler: Some(sender_block_handler),
            sender_operation_handler: Some(sender_operation_handler),
            sender_endorsement_handler: Some(sender_endorsement_handler),
            sender_connectivity_thread: Some(sender_connectivity_thread),
            sender_peer_management_thread: Some(sender_peer_management_thread),
        }
    }
}

impl ProtocolController for ProtocolControllerImpl {
    fn stop(&mut self) {
        drop(self.sender_block_handler.take());
        drop(self.sender_operation_handler.take());
        drop(self.sender_endorsement_handler.take());
        drop(self.sender_block_retrieval_handler.take());
    }

    /// Sends the order to propagate the header of a block
    ///
    /// # Arguments
    /// * `block_id`: ID of the block
    /// * `storage`: Storage instance containing references to the block and all its dependencies
    fn integrated_block(&self, block_id: BlockId, storage: Storage) -> Result<(), ProtocolError> {
        self.sender_block_handler
            .as_ref()
            .unwrap()
            .try_send(BlockHandlerPropagationCommand::IntegratedBlock { block_id, storage })
            .map_err(|_| ProtocolError::ChannelError("integrated_block command send error".into()))
    }

    /// Notify to protocol an attack attempt.
    fn notify_block_attack(&self, block_id: BlockId) -> Result<(), ProtocolError> {
        self.sender_block_handler
            .as_ref()
            .unwrap()
            .try_send(BlockHandlerPropagationCommand::AttackBlockDetected(
                block_id,
            ))
            .map_err(|_| {
                ProtocolError::ChannelError("notify_block_attack command send error".into())
            })
    }

    /// update the block wish list
    fn send_wishlist_delta(
        &self,
        new: PreHashMap<BlockId, Option<SecuredHeader>>,
        remove: PreHashSet<BlockId>,
    ) -> Result<(), ProtocolError> {
        self.sender_block_retrieval_handler
            .as_ref()
            .unwrap()
            .send(BlockHandlerRetrievalCommand::WishlistDelta { new, remove })
            .map_err(|_| {
                ProtocolError::ChannelError("send_wishlist_delta command send error".into())
            })
    }

    /// Propagate a batch of operation ids (from pool).
    ///
    /// note: Full `OperationId` is replaced by a `OperationPrefixId` later by the worker.
    fn propagate_operations(&self, operations: Storage) -> Result<(), ProtocolError> {
        self.sender_operation_handler
            .as_ref()
            .unwrap()
            .try_send(OperationHandlerPropagationCommand::PropagateOperations(
                operations,
            ))
            .map_err(|_| {
                ProtocolError::ChannelError("propagate_operations command send error".into())
            })
    }

    /// propagate endorsements to connected node
    fn propagate_endorsements(&self, endorsements: Storage) -> Result<(), ProtocolError> {
        self.sender_endorsement_handler
            .as_ref()
            .unwrap()
            .try_send(EndorsementHandlerPropagationCommand::PropagateEndorsements(
                endorsements,
            ))
            .map_err(|_| {
                ProtocolError::ChannelError("propagate_endorsements command send error".into())
            })
    }

    fn get_stats(
        &self,
    ) -> Result<
        (
            NetworkStats,
            HashMap<PeerId, (SocketAddr, PeerConnectionType)>,
        ),
        ProtocolError,
    > {
        let (sender, receiver) = MassaChannel::new("get_stats".to_string(), Some(1));
        self.sender_connectivity_thread
            .as_ref()
            .unwrap()
            .try_send(ConnectivityCommand::GetStats { responder: sender })
            .map_err(|_| ProtocolError::ChannelError("get_stats command send error".into()))?;
        receiver
            .recv_timeout(Duration::from_secs(10))
            .map_err(|_| ProtocolError::ChannelError("get_stats command receive error".into()))
    }

    fn ban_peers(&self, peer_ids: Vec<PeerId>) -> Result<(), ProtocolError> {
        self.sender_peer_management_thread
            .as_ref()
            .unwrap()
            .try_send(PeerManagementCmd::Ban(peer_ids))
            .map_err(|_| ProtocolError::ChannelError("ban_peers command send error".into()))
    }

    fn unban_peers(&self, peer_ids: Vec<PeerId>) -> Result<(), ProtocolError> {
        self.sender_peer_management_thread
            .as_ref()
            .unwrap()
            .try_send(PeerManagementCmd::Unban(peer_ids))
            .map_err(|_| ProtocolError::ChannelError("unban_peers command send error".into()))
    }

    fn get_bootstrap_peers(&self) -> Result<BootstrapPeers, ProtocolError> {
        let (sender, receiver) = MassaChannel::new("get_bootstrap_peers".to_string(), Some(1));
        self.sender_peer_management_thread
            .as_ref()
            .unwrap()
            .try_send(PeerManagementCmd::GetBootstrapPeers { responder: sender })
            .map_err(|_| {
                ProtocolError::ChannelError("get_bootstrap_peers command send error".into())
            })?;
        receiver.recv_timeout(Duration::from_secs(10)).map_err(|_| {
            ProtocolError::ChannelError("get_bootstrap_peers command receive error".into())
        })
    }

    fn clone_box(&self) -> Box<dyn ProtocolController> {
        Box::new(self.clone())
    }
}