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
// Copyright (c) 2023 MASSA LABS <info@massa.net>

use crate::error::{match_for_io_error, GrpcError};
use crate::server::MassaPublicGrpc;
use futures_util::StreamExt;
use massa_models::block::{BlockDeserializer, BlockDeserializerArgs, SecureShareBlock};
use massa_models::error::ModelsError;
use massa_models::secure_share::SecureShareDeserializer;
use massa_proto_rs::massa::api::v1 as grpc_api;
use massa_serialization::{DeserializeError, Deserializer};
use std::io::ErrorKind;
use std::pin::Pin;
use tokio::sync::mpsc::Sender;
use tonic::Request;
use tracing::{error, warn};

/// Type declaration for SendBlockStream
pub type SendBlocksStreamType = Pin<
    Box<
        dyn futures_util::Stream<Item = Result<grpc_api::SendBlocksResponse, tonic::Status>>
            + Send
            + 'static,
    >,
>;

/// This function takes a streaming request of block messages,
/// verifies, saves and propagates the block received in each message, and sends back a stream of
/// block id messages
#[allow(dead_code)]
pub(crate) async fn send_blocks(
    grpc: &MassaPublicGrpc,
    request: Request<tonic::Streaming<grpc_api::SendBlocksRequest>>,
) -> Result<SendBlocksStreamType, GrpcError> {
    let consensus_controller = grpc.consensus_controller.clone();
    let protocol_command_sender = grpc.protocol_controller.clone();
    let config = grpc.grpc_config.clone();
    let storage = grpc.storage.clone_without_refs();

    // Create a channel to handle communication with the client
    let (tx, rx) = tokio::sync::mpsc::channel(config.max_channel_size);
    // Extract the incoming stream of block messages
    let mut in_stream = request.into_inner();

    // Spawn a task that reads incoming messages and processes the block in each message
    tokio::spawn(async move {
        while let Some(result) = in_stream.next().await {
            match result {
                Ok(req_content) => {
                    if req_content.block.is_empty() {
                        report_error(
                            tx.clone(),
                            tonic::Code::InvalidArgument,
                            "the request payload is empty".to_owned(),
                        )
                        .await;
                        continue;
                    };

                    // Create a block deserializer arguments
                    let args = BlockDeserializerArgs {
                        thread_count: config.thread_count,
                        max_operations_per_block: config.max_operations_per_block,
                        endorsement_count: config.endorsement_count,
                        max_denunciations_per_block_header: config
                            .max_denunciations_per_block_header,
                        last_start_period: Some(config.last_start_period),
                        chain_id: config.chain_id,
                    };
                    // Deserialize and verify received block in the incoming message
                    match SecureShareDeserializer::new(
                        BlockDeserializer::new(args),
                        config.chain_id,
                    )
                    .deserialize::<DeserializeError>(&req_content.block)
                    {
                        Ok(tuple) => {
                            let (rest, res_block): (&[u8], SecureShareBlock) = tuple;
                            if !rest.is_empty() {
                                report_error(
                                    tx.clone(),
                                    tonic::Code::InvalidArgument,
                                    "the request payload is too large".to_owned(),
                                )
                                .await;
                                continue;
                            }
                            if let Err(e) = res_block
                                .verify_signature()
                                .and_then(|_| res_block.content.header.verify_signature())
                                .map(|_| {
                                    res_block
                                        .content
                                        .header
                                        .content
                                        .endorsements
                                        .iter()
                                        .map(|endorsement| endorsement.verify_signature())
                                        .collect::<Vec<Result<(), ModelsError>>>()
                                })
                            {
                                report_error(
                                    tx.clone(),
                                    tonic::Code::InvalidArgument,
                                    format!("wrong signature: {}", e),
                                )
                                .await;
                                continue;
                            }

                            let block_id = res_block.id;
                            let slot = res_block.content.header.content.slot;
                            let mut block_storage = storage.clone_without_refs();

                            // Add the received block to the graph
                            block_storage.store_block(res_block.clone());
                            consensus_controller.register_block(
                                block_id,
                                slot,
                                block_storage.clone(),
                                false,
                            );

                            // Propagate the block(header) to the network
                            if let Err(e) =
                                protocol_command_sender.integrated_block(block_id, block_storage)
                            {
                                // If propagation failed, send an error message back to the client
                                report_error(
                                    tx.clone(),
                                    tonic::Code::Internal,
                                    format!("failed to propagate block: {}", e),
                                )
                                .await;
                                continue;
                            };

                            // Send the response message back to the client
                            if let Err(e) = tx
                                .send(Ok(grpc_api::SendBlocksResponse {
                                    result: Some(grpc_api::send_blocks_response::Result::BlockId(
                                        res_block.id.to_string(),
                                    )),
                                }))
                                .await
                            {
                                error!("failed to send back block response: {}", e);
                            };
                        }
                        // If the verification failed, send an error message back to the client
                        Err(e) => {
                            report_error(
                                tx.clone(),
                                tonic::Code::InvalidArgument,
                                format!("failed to deserialize block: {}", e),
                            )
                            .await;
                            continue;
                        }
                    };
                }
                // Handle any errors that may occur during receiving the data
                Err(err) => {
                    // Check if the error matches any IO errors
                    if let Some(io_err) = match_for_io_error(&err) {
                        if io_err.kind() == ErrorKind::BrokenPipe {
                            warn!("client disconnected, broken pipe: {}", io_err);
                            break;
                        }
                    }
                    error!("{}", err);
                    // Send the error response back to the client
                    if let Err(e) = tx.send(Err(err)).await {
                        error!("failed to send back send_blocks error response: {}", e);
                        break;
                    }
                }
            }
        }
    });

    let out_stream = tokio_stream::wrappers::ReceiverStream::new(rx);
    Ok(Box::pin(out_stream) as SendBlocksStreamType)
}

/// This function reports an error to the sender by sending a gRPC response message to the client
async fn report_error(
    sender: Sender<Result<grpc_api::SendBlocksResponse, tonic::Status>>,
    code: tonic::Code,
    error: String,
) {
    error!("{}", error);
    // Attempt to send the error response message to the sender
    if let Err(e) = sender
        .send(Ok(grpc_api::SendBlocksResponse {
            result: Some(grpc_api::send_blocks_response::Result::Error(
                massa_proto_rs::massa::model::v1::Error {
                    code: code.into(),
                    message: error,
                },
            )),
        }))
        .await
    {
        // If sending the message fails, log the error message
        error!("failed to send back send_blocks error response: {}", e);
    }
}