nimiq-consensus 2.2.0

Consensus logic of Nimiq's Albatross implementation
Documentation
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Defines the `BlockRequestComponent`, which handles requesting missing blocks
//! from peers during synchronization. It maintains a list of active peers, manages a queue
//! of block requests, and verifies the integrity of responses.

use std::{
    collections::BTreeSet,
    fmt::{Debug, Formatter},
    pin::Pin,
    sync::Arc,
    task::{Context, Poll},
};

use futures::{FutureExt, Stream, StreamExt};
use nimiq_block::Block;
use nimiq_blockchain_interface::Direction;
use nimiq_hash::Blake2bHash;
use nimiq_network_interface::{
    network::{Network, NetworkEvent},
    request::RequestError,
};
use nimiq_primitives::{networks::NetworkId, policy::Policy, slots_allocation::Validators};
use nimiq_utils::spawn;
use parking_lot::RwLock;
use thiserror::Error;

use crate::{
    messages::{RequestMissingBlocks, ResponseBlocksError},
    sync::{peer_list::PeerList, sync_queue::SyncQueue},
};

/// Result of a successful missing block request.
#[derive(Debug)]
pub struct BlockRequestResult<N: Network> {
    pub target_block_number: u32,
    pub target_block_hash: Blake2bHash,
    pub epoch_validators: Validators,
    pub blocks: Vec<Block>,
    pub sender: N::PeerId,
}

/// Request for a sequence of missing blocks from a peer.
#[derive(Clone)]
pub struct MissingBlockRequest {
    /// The block number of the requested block.
    pub target_block_number: u32,
    /// The hash the last block which is requested with this request.
    pub target_block_hash: Blake2bHash,
    /// The validators of the epoch the target block is from.
    pub epoch_validators: Validators,
    /// List of locator hashes of blocks, sorted from newest to oldest.
    pub locators: Vec<Blake2bHash>,
    /// Flag indicating whether bodies must be included or omitted.
    pub include_body: bool,
    /// The Direction the request is to be executed in.
    /// See [RequestMissingBlocks] for details on the effect.
    pub direction: Direction,
}

impl Debug for MissingBlockRequest {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        let mut dbg = f.debug_struct("MissingBlockRequest");
        dbg.field("target_block_number", &self.target_block_number);
        dbg.field("target_block_hash", &self.target_block_hash);
        dbg.field("num_locators", &self.locators.len());
        dbg.field("include_body", &self.include_body);
        dbg.field("direction", &self.direction);
        dbg.finish()
    }
}

/// Response to a missing block request from a peer.
#[derive(Debug, Clone)]
pub struct MissingBlockResponse<N: Network> {
    pub target_block_number: u32,
    pub target_block_hash: Blake2bHash,
    pub epoch_validators: Validators,
    pub blocks: Vec<Block>,
    pub sender: N::PeerId,
}

/// Error type for missing block requests during sync
#[derive(Clone, Debug, Error)]
pub enum MissingBlockError {
    #[error("request: {0}")]
    Request(RequestError),
    #[error("response: {0}")]
    Response(ResponseBlocksError),
}

/// Error returned when a block request fails within the sync queue.
#[derive(Debug, Error)]
#[error("Sync queue error. Target block hash: {target_block_hash}, target block number {target_block_number}")]
pub struct SyncQueueError {
    /// Target block hash
    pub target_block_hash: Blake2bHash,
    /// Target block number
    pub target_block_number: u32,
}

/// Peer Tracking & Block Request Component.
/// We use this component to request missing blocks from peers.
///
/// This component has:
///
/// - The sync queue which manages the requests and responses.
/// - The peers list.
/// - The network stream of events used to remove the peers that have left.  
/// - Whether we include the body of a block.
///
/// The public interface allows to request blocks, which are not immediately returned.
/// The blocks instead are returned by polling the component.
pub struct BlockRequestComponent<N: Network> {
    sync_queue:
        SyncQueue<N, MissingBlockRequest, MissingBlockResponse<N>, MissingBlockError, NetworkId>, // requesting missing blocks from peers
    peers: Arc<RwLock<PeerList<N>>>,
    include_body: bool,
    /// Pending requests.
    pending_requests: BTreeSet<Blake2bHash>,
}

impl<N: Network> BlockRequestComponent<N> {
    const NUM_PENDING_BLOCKS: usize = 5;

    pub fn new(network: Arc<N>, network_id: NetworkId, include_body: bool) -> Self {
        let peers = Arc::new(RwLock::new(PeerList::default()));
        let mut network_event_rx = network.subscribe_events();

        // Poll network events to remove peers.
        let peers_weak = Arc::downgrade(&peers);
        spawn(async move {
            while let Some(result) = network_event_rx.next().await {
                if let Ok(NetworkEvent::PeerLeft(peer_id)) = result {
                    // Remove peers that left.
                    let peers = match peers_weak.upgrade() {
                        Some(peers) => peers,
                        None => break,
                    };

                    trace!(%peer_id, "Removing peer from live sync");
                    peers.write().remove_peer(&peer_id);
                }
            }
        });

        Self {
            sync_queue: SyncQueue::with_verification(
                network,
                vec![],
                Arc::clone(&peers),
                Self::NUM_PENDING_BLOCKS,
                |request, network, peer_id| {
                    async move {
                        match Self::request_missing_blocks_from_peer(
                            network,
                            peer_id,
                            request.target_block_hash.clone(),
                            request.locators,
                            request.include_body,
                            request.direction,
                        )
                        .await
                        {
                            Ok(Ok(missing_blocks)) => Ok(MissingBlockResponse {
                                target_block_number: request.target_block_number,
                                target_block_hash: request.target_block_hash,
                                epoch_validators: request.epoch_validators,
                                blocks: missing_blocks,
                                sender: peer_id,
                            }),
                            Ok(Err(error)) => Err(MissingBlockError::Response(error)),
                            Err(error) => Err(MissingBlockError::Request(error)),
                        }
                    }
                    .boxed()
                },
                |request, response, network_id| {
                    // We check general consistency for the response:
                    // 1. Check that the blocks end on target block or macro block
                    // 2. Verify macro block signature (last block)
                    // 3. Check that hash chain verifies
                    // We need to pass through the validators once we reach a new epoch
                    // to be able to verify macro blocks

                    let blocks = &mut response.blocks;

                    // Size checks.
                    if blocks.is_empty() {
                        log::debug!("Received empty missing blocks response");
                        return false;
                    }

                    if blocks.len() > Policy::blocks_per_batch() as usize {
                        log::debug!(
                            blocks_len = blocks.len(),
                            "Received missing blocks response that is too large"
                        );
                        return false;
                    }

                    for block in blocks.iter() {
                        if block.has_body() != request.include_body {
                            log::error!(
                                is_macro = block.is_macro(),
                                has_body = block.has_body(),
                                include_body = request.include_body,
                                "Received block with body where none was expected or vice versa",
                            );
                            return false;
                        }

                        // Verify the header before the chain is hashed below, to cheaply reject
                        // malformed blocks (wrong network/version, oversized extra data, or — for
                        // election blocks — an invalid validator set) without buffering them.
                        // `max_timestamp` is `u64::MAX` because these are historical blocks
                        // requested by hash/height: the future-drift check is only meaningful for
                        // live blocks and is re-applied with the real clock at push time
                        if let Err(error) =
                            block.verify_header(*network_id, block.is_skip(), u64::MAX)
                        {
                            log::error!(
                                %block,
                                %error,
                                "Received missing block with an invalid header"
                            );
                            return false;
                        }
                    }

                    // Checks that the first block's parent was part of the block locators.
                    let first_block = blocks.first().unwrap(); // cannot be empty
                    if !request.locators.contains(first_block.parent_hash()) {
                        log::error!("Received invalid chain of missing blocks (first block's parent not in block locators)");
                        return false;
                    }

                    if first_block.block_number() > request.target_block_number {
                        log::error!(
                            first_block = first_block.block_number(),
                            request.target_block_number,
                            "Received invalid chain of missing blocks (first block > target)"
                        );
                        return false;
                    }

                    // Check that the last block is valid. If it is at the target height it must
                    // be the requested target block, i.e. its hash must match the requested one
                    // (this holds for both macro and micro target blocks). Otherwise it must be
                    // an intermediate macro block below the target that serves as a valid
                    // stopping point; the rest of the chain up to the target is fetched by
                    // follow-up requests.
                    let last_block = blocks.last_mut().unwrap(); // cannot be empty
                    let block_hash = last_block.hash_cached();
                    let valid_last_block =
                        if last_block.block_number() == request.target_block_number {
                            block_hash == request.target_block_hash
                        } else {
                            last_block.is_macro()
                        };
                    if !valid_last_block {
                        log::error!(
                            request.target_block_number,
                            last_block = last_block.block_number(),
                            %block_hash,
                            %request.target_block_hash,
                            "Received invalid missing blocks (invalid target block)"
                        );
                        return false;
                    }

                    // Check that the hash chain of missing blocks is valid.
                    // Also checks block numbers.
                    for i in 1..blocks.len() {
                        let previous_block_hash = blocks[i - 1].hash_cached();

                        if blocks[i].block_number() != blocks[i - 1].block_number() + 1
                            || blocks[i].block_number() > request.target_block_number
                            || blocks[i].parent_hash() != &previous_block_hash
                        {
                            log::error!("Received invalid chain of missing blocks");
                            return false;
                        }
                    }

                    // If it is a macro block, also check the signatures.
                    let last_block = response.blocks.last().unwrap(); // cannot be empty
                    if last_block.is_macro()
                        && let Err(e) = last_block.verify_validators(&request.epoch_validators)
                    {
                        log::error!(
                            last_block = last_block.block_number(),
                            error = %e,
                            "Received invalid chain of missing blocks (macro block does not verify)"
                        );
                        return false;
                    }

                    true
                },
                network_id,
            ),
            peers,
            include_body,
            pending_requests: BTreeSet::new(),
        }
    }

    async fn request_missing_blocks_from_peer(
        network: Arc<N>,
        peer_id: N::PeerId,
        target_block_hash: Blake2bHash,
        locators: Vec<Blake2bHash>,
        include_body: bool,
        direction: Direction,
    ) -> Result<Result<Vec<Block>, ResponseBlocksError>, RequestError> {
        network
            .request::<RequestMissingBlocks>(
                RequestMissingBlocks {
                    locators,
                    target_hash: target_block_hash,
                    include_body,
                    direction,
                },
                peer_id,
            )
            .await
            .map(|response| response.map(|r| r.blocks))
    }

    pub fn request_missing_blocks(
        &mut self,
        target_block_number: u32,
        target_block_hash: Blake2bHash,
        locators: Vec<Blake2bHash>,
        direction: Direction,
        epoch_validators: Validators,
        first_peer_id: Option<N::PeerId>,
    ) {
        self.pending_requests.insert(target_block_hash.clone());
        self.sync_queue.add_ids(vec![(
            MissingBlockRequest {
                target_block_number,
                target_block_hash,
                epoch_validators,
                locators,
                direction,
                include_body: self.include_body,
            },
            first_peer_id,
        )]);
    }

    pub fn is_pending(&self, target_block_hash: &Blake2bHash) -> bool {
        self.pending_requests.contains(target_block_hash)
    }

    pub fn add_peer(&self, peer_id: N::PeerId) {
        self.peers.write().add_peer(peer_id);
    }

    pub fn take_peer(&self, peer_id: &N::PeerId) -> Option<N::PeerId> {
        if self.peers.write().remove_peer(peer_id) {
            return Some(*peer_id);
        }
        None
    }

    pub fn num_peers(&self) -> usize {
        self.peers.read().len()
    }

    pub fn peers(&self) -> Vec<N::PeerId> {
        self.peers.read().peers().to_vec()
    }

    pub fn peer_list(&self) -> Arc<RwLock<PeerList<N>>> {
        Arc::clone(&self.peers)
    }
}

impl<N: Network> Stream for BlockRequestComponent<N> {
    type Item = Result<BlockRequestResult<N>, SyncQueueError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
        // Poll self.sync_queue, return results.
        while let Poll::Ready(result) = self.sync_queue.poll_next_unpin(cx) {
            match result {
                // A valid response was received with blocks from a peer.
                Some(Ok(response)) => {
                    // Remove this request from the pending set.
                    self.pending_requests.remove(&response.target_block_hash);
                    return Poll::Ready(Some(Ok(BlockRequestResult {
                        target_block_number: response.target_block_number,
                        target_block_hash: response.target_block_hash,
                        epoch_validators: response.epoch_validators,
                        blocks: response.blocks,
                        sender: response.sender,
                    })));
                }
                // The request failed
                Some(Err(request)) => {
                    self.pending_requests.remove(&request.target_block_hash);
                    debug!(
                        request.target_block_number,
                        ?request.target_block_hash,
                        "Failed to retrieve missing blocks"
                    );
                    return Poll::Ready(Some(Err(SyncQueueError {
                        target_block_hash: request.target_block_hash,
                        target_block_number: request.target_block_number,
                    })));
                }
                None => {}
            }
        }

        Poll::Pending
    }
}