massa_grpc/stream/
send_blocks.rs

1// Copyright (c) 2023 MASSA LABS <info@massa.net>
2
3use crate::error::{match_for_io_error, GrpcError};
4use crate::server::MassaPublicGrpc;
5use futures_util::StreamExt;
6use massa_models::block::{BlockDeserializer, BlockDeserializerArgs, SecureShareBlock};
7use massa_models::error::ModelsError;
8use massa_models::secure_share::SecureShareDeserializer;
9use massa_proto_rs::massa::api::v1 as grpc_api;
10use massa_serialization::{DeserializeError, Deserializer};
11use std::io::ErrorKind;
12use std::pin::Pin;
13use tokio::sync::mpsc::Sender;
14use tonic::Request;
15use tracing::{error, warn};
16
17/// Type declaration for SendBlockStream
18pub type SendBlocksStreamType = Pin<
19    Box<
20        dyn futures_util::Stream<Item = Result<grpc_api::SendBlocksResponse, tonic::Status>>
21            + Send
22            + 'static,
23    >,
24>;
25
26/// This function takes a streaming request of block messages,
27/// verifies, saves and propagates the block received in each message, and sends back a stream of
28/// block id messages
29#[allow(dead_code)]
30pub(crate) async fn send_blocks(
31    grpc: &MassaPublicGrpc,
32    request: Request<tonic::Streaming<grpc_api::SendBlocksRequest>>,
33) -> Result<SendBlocksStreamType, GrpcError> {
34    let consensus_controller = grpc.consensus_controller.clone();
35    let protocol_command_sender = grpc.protocol_controller.clone();
36    let config = grpc.grpc_config.clone();
37    let storage = grpc.storage.clone_without_refs();
38
39    // Create a channel to handle communication with the client
40    let (tx, rx) = tokio::sync::mpsc::channel(config.max_channel_size);
41    // Extract the incoming stream of block messages
42    let mut in_stream = request.into_inner();
43
44    // Spawn a task that reads incoming messages and processes the block in each message
45    tokio::spawn(async move {
46        while let Some(result) = in_stream.next().await {
47            match result {
48                Ok(req_content) => {
49                    if req_content.block.is_empty() {
50                        report_error(
51                            tx.clone(),
52                            tonic::Code::InvalidArgument,
53                            "the request payload is empty".to_owned(),
54                        )
55                        .await;
56                        continue;
57                    };
58
59                    // Create a block deserializer arguments
60                    let args = BlockDeserializerArgs {
61                        thread_count: config.thread_count,
62                        max_operations_per_block: config.max_operations_per_block,
63                        endorsement_count: config.endorsement_count,
64                        max_denunciations_per_block_header: config
65                            .max_denunciations_per_block_header,
66                        last_start_period: Some(config.last_start_period),
67                        chain_id: config.chain_id,
68                    };
69                    // Deserialize and verify received block in the incoming message
70                    match SecureShareDeserializer::new(
71                        BlockDeserializer::new(args),
72                        config.chain_id,
73                    )
74                    .deserialize::<DeserializeError>(&req_content.block)
75                    {
76                        Ok(tuple) => {
77                            let (rest, res_block): (&[u8], SecureShareBlock) = tuple;
78                            if !rest.is_empty() {
79                                report_error(
80                                    tx.clone(),
81                                    tonic::Code::InvalidArgument,
82                                    "the request payload is too large".to_owned(),
83                                )
84                                .await;
85                                continue;
86                            }
87                            if let Err(e) = verify_received_block(&res_block, &config) {
88                                report_error(
89                                    tx.clone(),
90                                    tonic::Code::InvalidArgument,
91                                    format!("wrong signature: {}", e),
92                                )
93                                .await;
94                                continue;
95                            }
96
97                            let block_id = res_block.id;
98                            let slot = res_block.content.header.content.slot;
99                            let mut block_storage = storage.clone_without_refs();
100
101                            // Add the received block to the graph
102                            block_storage.store_block(res_block.clone());
103                            consensus_controller.register_block(
104                                block_id,
105                                slot,
106                                block_storage.clone(),
107                                false,
108                            );
109
110                            // Propagate the block(header) to the network
111                            if let Err(e) =
112                                protocol_command_sender.integrated_block(block_id, block_storage)
113                            {
114                                // If propagation failed, send an error message back to the client
115                                report_error(
116                                    tx.clone(),
117                                    tonic::Code::Internal,
118                                    format!("failed to propagate block: {}", e),
119                                )
120                                .await;
121                                continue;
122                            };
123
124                            // Send the response message back to the client
125                            if let Err(e) = tx
126                                .send(Ok(grpc_api::SendBlocksResponse {
127                                    result: Some(grpc_api::send_blocks_response::Result::BlockId(
128                                        res_block.id.to_string(),
129                                    )),
130                                }))
131                                .await
132                            {
133                                error!("failed to send back block response: {}", e);
134                            };
135                        }
136                        // If the verification failed, send an error message back to the client
137                        Err(e) => {
138                            report_error(
139                                tx.clone(),
140                                tonic::Code::InvalidArgument,
141                                format!("failed to deserialize block: {}", e),
142                            )
143                            .await;
144                            continue;
145                        }
146                    };
147                }
148                // Handle any errors that may occur during receiving the data
149                Err(err) => {
150                    // Check if the error matches any IO errors
151                    if let Some(io_err) = match_for_io_error(&err) {
152                        if io_err.kind() == ErrorKind::BrokenPipe {
153                            warn!("client disconnected, broken pipe: {}", io_err);
154                            break;
155                        }
156                    }
157                    error!("{}", err);
158                    // Send the error response back to the client
159                    if let Err(e) = tx.send(Err(err)).await {
160                        error!("failed to send back send_blocks error response: {}", e);
161                        break;
162                    }
163                }
164            }
165        }
166    });
167
168    let out_stream = tokio_stream::wrappers::ReceiverStream::new(rx);
169    Ok(Box::pin(out_stream) as SendBlocksStreamType)
170}
171
172/// This function reports an error to the sender by sending a gRPC response message to the client
173async fn report_error(
174    sender: Sender<Result<grpc_api::SendBlocksResponse, tonic::Status>>,
175    code: tonic::Code,
176    error: String,
177) {
178    error!("{}", error);
179    // Attempt to send the error response message to the sender
180    if let Err(e) = sender
181        .send(Ok(grpc_api::SendBlocksResponse {
182            result: Some(grpc_api::send_blocks_response::Result::Error(
183                massa_proto_rs::massa::model::v1::Error {
184                    code: code.into(),
185                    message: error,
186                },
187            )),
188        }))
189        .await
190    {
191        // If sending the message fails, log the error message
192        error!("failed to send back send_blocks error response: {}", e);
193    }
194}
195
196fn verify_received_block(
197    block: &SecureShareBlock,
198    config: &crate::config::GrpcConfig,
199) -> Result<(), ModelsError> {
200    // Block::verify_signature delegates to the nested header signing domain (F87).
201    block.verify_signature(config.chain_id)?;
202    for endorsement in block.content.header.content.endorsements.iter() {
203        endorsement.verify_signature(config.chain_id)?;
204    }
205    Ok(())
206}