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
// Copyright (c) 2022, Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use crate::{
    block_synchronizer::{
        handler::Error::{BlockDeliveryTimeout, BlockNotFound, Internal, PayloadSyncError},
        BlockSynchronizeResult, Command, SyncError,
    },
    BlockHeader,
};
use async_trait::async_trait;
use fastcrypto::Hash;
use futures::future::join_all;
#[cfg(test)]
use mockall::*;
use std::time::Duration;
use storage::CertificateStore;
use thiserror::Error;
use tokio::{sync::mpsc::channel, time::timeout};
use tracing::{debug, error, instrument, trace};
use types::{metered_channel, Certificate, CertificateDigest, PrimaryMessage};

#[cfg(test)]
#[path = "tests/handler_tests.rs"]
mod handler_tests;

/// The errors returned by the Handler. It translates
/// also the errors returned from the block_synchronizer.
#[derive(Debug, Error, Copy, Clone)]
pub enum Error {
    #[error("Block with id {block_id} not found")]
    BlockNotFound { block_id: CertificateDigest },

    #[error("Block with id {block_id} couldn't be retrieved, internal error occurred")]
    Internal { block_id: CertificateDigest },

    #[error("Timed out while waiting for {block_id} to become available after submitting for processing")]
    BlockDeliveryTimeout { block_id: CertificateDigest },

    #[error("Payload for block with {block_id} couldn't be synchronized: {error}")]
    PayloadSyncError {
        block_id: CertificateDigest,
        error: SyncError,
    },
}

impl Error {
    pub fn block_id(&self) -> CertificateDigest {
        match *self {
            BlockNotFound { block_id }
            | Internal { block_id }
            | BlockDeliveryTimeout { block_id }
            | PayloadSyncError { block_id, .. } => block_id,
        }
    }
}

/// Handler defines an interface to allow us access the BlockSycnhronizer's
/// functionality in a synchronous way without having to deal with message
/// emission. The BlockSynchronizer on its own for the certificates that
/// fetches on the fly from peers doesn't care/deal about any other validation
/// checks than the basic verification offered via the certificate entity
/// it self. For that reason the Handler offers methods to submit the fetched
/// from peers certificates for further validation & processing (e.x ensure
/// parents history is causally complete) to the core and wait until the
/// certificate has been processed, before it returns it back as result.
#[cfg_attr(test, automock)]
#[async_trait]
pub trait Handler {
    /// It retrieves the requested blocks via the block_synchronizer making
    /// sure though that they are fully validated. The certificates will only
    /// be returned when they have properly processed via the core module
    /// and made sure all the requirements have been fulfilled.
    async fn get_and_synchronize_block_headers(
        &self,
        block_ids: Vec<CertificateDigest>,
    ) -> Vec<Result<Certificate, Error>>;

    /// It retrieves the requested blocks via the block_synchronizer, but it
    /// doesn't synchronize the fetched headers, meaning that no processing
    /// will take place (causal completion etc).
    async fn get_block_headers(
        &self,
        block_ids: Vec<CertificateDigest>,
    ) -> Vec<BlockSynchronizeResult<BlockHeader>>;

    /// Synchronizes the block payload for the provided certificates via the
    /// block synchronizer and returns the result back.
    async fn synchronize_block_payloads(
        &self,
        certificates: Vec<Certificate>,
    ) -> Vec<Result<Certificate, Error>>;
}

/// A helper struct to allow us access the block_synchronizer in an asynchronous
/// way. It also offers methods to both fetch the certificates and way to
/// process them and causally complete their history.
pub struct BlockSynchronizerHandler {
    /// Channel to send commands to the block_synchronizer.
    tx_block_synchronizer: metered_channel::Sender<Command>,

    /// Channel to send the fetched certificates to Core for
    /// further processing, validation and possibly causal
    /// completion.
    tx_core: metered_channel::Sender<PrimaryMessage>,

    /// The store that holds the certificates.
    certificate_store: CertificateStore,

    /// The timeout while waiting for a certificate to become available
    /// after submitting for processing to core.
    certificate_deliver_timeout: Duration,
}

impl BlockSynchronizerHandler {
    pub fn new(
        tx_block_synchronizer: metered_channel::Sender<Command>,
        tx_core: metered_channel::Sender<PrimaryMessage>,
        certificate_store: CertificateStore,
        certificate_deliver_timeout: Duration,
    ) -> Self {
        Self {
            tx_block_synchronizer,
            tx_core,
            certificate_store,
            certificate_deliver_timeout,
        }
    }

    async fn wait_all(&self, certificates: Vec<Certificate>) -> Vec<Result<Certificate, Error>> {
        let futures: Vec<_> = certificates
            .into_iter()
            .map(|c| self.wait(c.digest()))
            .collect();

        join_all(futures).await
    }

    async fn wait(&self, block_id: CertificateDigest) -> Result<Certificate, Error> {
        if let Ok(result) = timeout(
            self.certificate_deliver_timeout,
            self.certificate_store.notify_read(block_id),
        )
        .await
        {
            result.map_err(|_| Error::Internal { block_id })
        } else {
            Err(Error::BlockDeliveryTimeout { block_id })
        }
    }
}

#[async_trait]
impl Handler for BlockSynchronizerHandler {
    /// The method will return a separate result for each requested block id.
    /// If a certificate has been successfully retrieved (and processed via core
    /// if has been fetched from peers) then an OK result will be returned with the
    /// certificate value.
    /// In case of error, the following outcomes are possible:
    /// * BlockNotFound: Failed to retrieve the certificate either via the store or via the peers
    /// * Internal: An internal error caused
    /// * BlockDeliveryTimeout: Timed out while waiting for the certificate to become available
    /// after submitting it for processing to core
    #[instrument(level="trace", skip_all, fields(num_block_ids = block_ids.len()))]
    async fn get_and_synchronize_block_headers(
        &self,
        block_ids: Vec<CertificateDigest>,
    ) -> Vec<Result<Certificate, Error>> {
        if block_ids.is_empty() {
            trace!("No blocks were provided, will now return an empty list");
            return vec![];
        }

        let sync_results = self.get_block_headers(block_ids).await;
        let mut results: Vec<Result<Certificate, Error>> = Vec::new();

        // send certificates to core for processing and potential
        // causal completion
        let mut wait_for = Vec::new();

        for result in sync_results {
            match result {
                Ok(block_header) => {
                    if !block_header.fetched_from_storage {
                        // we need to perform causal completion since this
                        // entity has not been fetched from storage.
                        self.tx_core
                            .send(PrimaryMessage::Certificate(
                                block_header.certificate.clone(),
                            ))
                            .await
                            .expect("Couldn't send certificate to core");
                        wait_for.push(block_header.certificate.clone());

                        debug!(
                            "Need to causally complete {}",
                            block_header.certificate.digest()
                        );
                    } else {
                        // Otherwise, if certificate fetched from storage, just
                        // add directly the certificate to the results - no need
                        // for further processing, validation, causal completion
                        // as all that have already happened.
                        results.push(Ok(block_header.certificate));
                    }
                }
                Err(err) => {
                    error!(
                        "Error occurred while synchronizing requested certificate {:?}",
                        err
                    );
                    results.push(Err(BlockNotFound {
                        block_id: err.block_id(),
                    }));
                }
            }
        }

        // now wait for the certificates to become available - timeout so we can
        // serve requests.
        let mut wait_results = self.wait_all(wait_for).await;

        // append the results we were waiting for
        results.append(&mut wait_results);

        results
    }

    #[instrument(level="trace", skip_all, fields(num_block_ids = block_ids.len()))]
    async fn get_block_headers(
        &self,
        block_ids: Vec<CertificateDigest>,
    ) -> Vec<BlockSynchronizeResult<BlockHeader>> {
        if block_ids.is_empty() {
            trace!("No blocks were provided, will now return an empty list");
            return vec![];
        }

        let (tx, mut rx) = channel(block_ids.len());

        self.tx_block_synchronizer
            .send(Command::SynchronizeBlockHeaders {
                block_ids,
                respond_to: tx,
            })
            .await
            .expect("Couldn't send message to block synchronizer");

        // now wait to retrieve all the results
        let mut results = Vec::new();

        // We want to block and wait until we get all the results back.
        while let Some(result) = rx.recv().await {
            results.push(result)
        }
        results
    }

    #[instrument(level = "trace", skip_all, fields(num_certificates = certificates.len()))]
    async fn synchronize_block_payloads(
        &self,
        certificates: Vec<Certificate>,
    ) -> Vec<Result<Certificate, Error>> {
        if certificates.is_empty() {
            trace!("No certificates were provided, will now return an empty list");
            return vec![];
        }

        let (tx, mut rx) = channel(certificates.len());

        self.tx_block_synchronizer
            .send(Command::SynchronizeBlockPayload {
                certificates,
                respond_to: tx,
            })
            .await
            .expect("Couldn't send message to block synchronizer");

        // now wait to retrieve all the results
        let mut results = Vec::new();

        // We want to block and wait until we get all the results back.
        while let Some(result) = rx.recv().await {
            let r = result
                .map(|h| h.certificate)
                .map_err(|e| Error::PayloadSyncError {
                    block_id: e.block_id(),
                    error: e,
                });

            if let Err(err) = r {
                error!(
                    "Error for payload synchronization with block id {}, error: {err}",
                    err.block_id()
                );
            }

            results.push(r)
        }

        results
    }
}