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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Core implementation of the Albatross consensus protocol.
//!
//! This module manages the consensus state, and facilitates synchronization with peers.
//!
//! It serves as the control center of the blockchain's
//! agreement mechanism, ensuring all nodes converge on a single chain state.

use std::{
    future::Future,
    pin::Pin,
    sync::{
        atomic::{AtomicBool, AtomicU32, Ordering},
        Arc,
    },
    task::{Context, Poll, Waker},
    time::Duration,
};

use futures::{FutureExt, StreamExt};
use instant::Instant;
use nimiq_block::Block;
use nimiq_blockchain_interface::AbstractBlockchain;
use nimiq_blockchain_proxy::BlockchainProxy;
#[cfg(feature = "full")]
use nimiq_blockchain_proxy::BlockchainReadProxy;
use nimiq_hash::Blake2bHash;
use nimiq_network_interface::{network::Network, request::request_handler};
use nimiq_time::{interval, Interval};
use nimiq_utils::{spawn, WakerExt};
use tokio::sync::{
    broadcast,
    mpsc::{self, error::SendError},
    oneshot::{self, error::RecvError},
};
use tokio_stream::wrappers::BroadcastStream;

use self::consensus_proxy::ConsensusProxy;
#[cfg(feature = "full")]
use self::remote_event_dispatcher::RemoteEventDispatcher;
use crate::{
    consensus::head_requests::{HeadRequests, HeadRequestsResult},
    messages::{RequestBlock, RequestHead, RequestMacroChain, RequestMissingBlocks},
    sync::{
        live::block_queue::BlockSource, sync_interface::LiveSyncPushEvent,
        syncer_proxy::SyncerProxy,
    },
};
#[cfg(feature = "full")]
use crate::{
    messages::{
        RequestBatchSet, RequestBlocksProof, RequestHistoryChunk,
        RequestTransactionReceiptsByAddress, RequestTransactionsProof, RequestTrieProof,
    },
    sync::live::{diff_queue::RequestTrieDiff, state_queue::RequestChunk},
};

pub mod consensus_proxy;
mod head_requests;
mod remote_data_store;
#[cfg(feature = "full")]
mod remote_event_dispatcher;

/// Events that are generated by the consensus component to convey the two possible states of consensus:
/// Established consensus (by satisfying some specific consensus criteria), or we lost it
#[derive(Clone)]
pub enum ConsensusEvent {
    /// Consensus is established
    /// Also includes a flag that indicates if we are ready for transaction verification.
    /// The established event can be triggered multiple times with different values for the flag.
    Established { synced_validity_window: bool },
    /// Consensus was lost
    Lost,
}

/// This enum is used to represent different kinds of events that are generated by other peers.
/// This is used for cases where we want to subscribe to other peers to receive notifications about those events.
/// For instance: we might be interested in knowing about transactions, from some specific address, that are included in a block
#[derive(Clone)]
pub enum RemoteEvent {
    /// Interesting receipts: They belong to an address that is interesting to us
    /// We get a vector of (transaction_hash, block_number) tuples
    InterestingReceipts(Vec<(Blake2bHash, u32)>),
    /// Other events, generated by peers, that might be interesting to us
    Placeholder,
}

/// Different Errors for a failed ResolveBlockRequest.
pub enum ResolveBlockError<N: Network> {
    Outdated,
    Duplicate,
    ReceiveError(RecvError),
    SendError(SendError<ConsensusRequest<N>>),
}

impl<N: Network> std::fmt::Debug for ResolveBlockError<N> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResolveBlockError::Outdated => f.debug_tuple("ResolveBlockError::Outdated").finish(),
            ResolveBlockError::Duplicate => f.debug_tuple("ResolveBlockError::Duplicate").finish(),
            ResolveBlockError::ReceiveError(e) => f
                .debug_tuple("ResolveBlockError::ReceiveError")
                .field(e)
                .finish(),
            ResolveBlockError::SendError(e) => f
                .debug_tuple("ResolveBlockError::SendError")
                .field(e)
                .finish(),
        }
    }
}

/// Requests the consensus to resolve a given `block_hash` at a specific `block_height`.
/// Additionally the sender of a response channel is presented and a number of peers who are
/// well suited to provide the required data.
pub struct ResolveBlockRequest<N: Network> {
    /// Block number of the to be resolved block.
    pub(crate) block_number: u32,

    /// Block hash of the to be resolved block.
    pub(crate) block_hash: Blake2bHash,

    /// The id of the first peer to ask for this block.
    pub(crate) first_peer_id: N::PeerId,

    /// Sender to a oneshot channel where the response to the request is being awaited.
    pub(crate) response_sender: oneshot::Sender<Result<Block, ResolveBlockError<N>>>,
}

/// Enumeration of all ConsensusRequests available.
pub enum ConsensusRequest<N: Network> {
    ResolveBlock(ResolveBlockRequest<N>),
}

/// This struct is used to track the sync progress to reach consensus.
pub struct SyncProgress {
    pub current_block_number: AtomicU32,
    pub remaining_blocks_to_sync: AtomicU32,
    pub live_sync_progress: Arc<AtomicU32>,
}

/// Coordinates synchronization between the blockchain and the network.
/// Tracks peers, handles event notifications, and manages requests for chain data.
/// Provides channels and flags for other components to maintain chain state.
pub struct Consensus<N: Network> {
    pub blockchain: BlockchainProxy,
    pub network: Arc<N>,

    pub sync: SyncerProxy<N>,
    pub sync_progress: Arc<SyncProgress>,

    events: broadcast::Sender<ConsensusEvent>,
    established_flag: Arc<AtomicBool>,
    #[cfg(feature = "full")]
    last_batch_number: u32,
    synced_validity_window_flag: Arc<AtomicBool>,

    head_requests: Option<HeadRequests<N>>,
    head_requests_time: Option<Instant>,
    head_requests_interval: Interval,

    min_peers: usize,

    /// Sender and Receiver of a consensus request channel used to relay requests from any source
    /// to the Consensus instance. Currently the only source is a ConsensusProxy instance, but
    /// the Consensus is not limited to it.
    ///
    /// Both the sender and receiver are stored such that the sender can be cloned as required,
    /// while the receiver is actually polled within the Consensus poll function.
    ///
    /// The consensus itself is chosen, even though for the initial single request a structure
    /// somewhere deeper down the call stack would be adequate, as other requests may require different
    /// structures. Putting it here seemed to be the most flexible.
    requests: (
        mpsc::Sender<ConsensusRequest<N>>,
        mpsc::Receiver<ConsensusRequest<N>>,
    ),

    waker: Option<Waker>,
}

/// Decides whether a finished head request provides enough evidence to establish
/// consensus. We want at least 2/3 of the peers that responded to report a head
/// block we already know, which is expressed as `num_known >= 2 * num_unknown`.
///
/// We must additionally have heard back from at least one peer. Failed head
/// requests are not counted, so an all-failed request yields `num_known == 0` and
/// `num_unknown == 0`, which would otherwise satisfy the comparison vacuously and
/// establish consensus on zero evidence. The only legitimate zero-response case is
/// a lone seed node (`min_peers == 0`) with no peers to ask, whose head request
/// over an empty peer set completes with `0`/`0`; that case is identified here by
/// `num_agents == 0` (when `min_peers >= 1` the establishment check is only reached
/// with `num_agents >= min_peers >= 1`, so this never masks a failed request).
fn head_request_established(num_known: usize, num_unknown: usize, num_agents: usize) -> bool {
    let num_responses = num_known + num_unknown;
    (num_responses > 0 || num_agents == 0) && num_known >= 2 * num_unknown
}

impl<N: Network> Consensus<N> {
    /// Minimum number of peers for consensus to be established.
    const MIN_PEERS_ESTABLISHED: usize = 3;

    /// Minimum number of block announcements extending the chain for consensus to be established.
    const MIN_BLOCKS_ESTABLISHED: usize = 5;

    /// Timeout after which head requests will be performed (again) to determine consensus
    /// established state and to advance the chain.
    const HEAD_REQUESTS_TIMEOUT: Duration = Duration::from_secs(5);

    pub fn from_network(
        blockchain: BlockchainProxy,
        network: Arc<N>,
        syncer: SyncerProxy<N>,
    ) -> Self {
        Self::new(
            blockchain,
            network,
            syncer,
            Self::MIN_PEERS_ESTABLISHED,
            Arc::new(AtomicU32::new(0)),
        )
    }

    pub fn new(
        blockchain: BlockchainProxy,
        network: Arc<N>,
        syncer: SyncerProxy<N>,
        min_peers: usize,
        syncer_tracker: Arc<AtomicU32>,
    ) -> Self {
        Self::init_network_request_receivers(&network, &blockchain);

        #[cfg(feature = "full")]
        Self::init_remote_event_dispatcher(&network, &blockchain);

        let established_flag = Arc::new(AtomicBool::new(false));
        let mut synced_validity_window_flag = true;
        #[cfg(feature = "full")]
        {
            if let BlockchainReadProxy::Full(blockchain) = blockchain.read() {
                synced_validity_window_flag = blockchain.can_enforce_validity_window();
            }
        }
        let synced_validity_window_flag = Arc::new(AtomicBool::new(synced_validity_window_flag));

        let sync_progress = Arc::new(SyncProgress {
            current_block_number: AtomicU32::new(0),
            remaining_blocks_to_sync: AtomicU32::new(0),
            live_sync_progress: syncer_tracker,
        });

        Consensus {
            blockchain,
            network,
            sync: syncer,
            events: broadcast::Sender::new(256),
            established_flag,
            #[cfg(feature = "full")]
            last_batch_number: 0,
            sync_progress,
            synced_validity_window_flag,
            head_requests: None,
            head_requests_time: None,
            head_requests_interval: interval(Self::HEAD_REQUESTS_TIMEOUT),
            min_peers,
            // Choose a small buffer as having a lot of items buffered here indicates a bigger problem.
            requests: mpsc::channel(10),
            waker: None,
        }
    }

    #[cfg(feature = "full")]
    fn init_remote_event_dispatcher(network: &Arc<N>, blockchain: &BlockchainProxy) {
        // We spawn the Remote Event Dispatcher into its own task (this is only available for full nodes and history nodes)

        match blockchain {
            BlockchainProxy::Full(blockchain) => {
                let network = Arc::clone(network);
                let blockchain = Arc::clone(blockchain);
                let remote_event_dispatcher = RemoteEventDispatcher::new(network, blockchain);

                spawn(remote_event_dispatcher);
            }
            BlockchainProxy::Light(_) => {
                // The light blockchain does not provide this functionality
            }
        }
    }

    fn init_network_request_receivers(network: &Arc<N>, blockchain: &BlockchainProxy) {
        let stream = network.receive_requests::<RequestMacroChain>();
        spawn(Box::pin(request_handler(network, stream, blockchain)));

        let stream = network.receive_requests::<RequestBlock>();
        spawn(Box::pin(request_handler(network, stream, blockchain)));

        let stream = network.receive_requests::<RequestMissingBlocks>();
        spawn(Box::pin(request_handler(network, stream, blockchain)));

        let stream = network.receive_requests::<RequestHead>();
        spawn(Box::pin(request_handler(network, stream, blockchain)));
        match blockchain {
            #[cfg(feature = "full")]
            BlockchainProxy::Full(blockchain) => {
                let stream = network.receive_requests::<RequestBatchSet>();
                spawn(Box::pin(request_handler(network, stream, blockchain)));

                let stream = network.receive_requests::<RequestHistoryChunk>();
                spawn(Box::pin(request_handler(network, stream, blockchain)));

                let stream = network.receive_requests::<RequestTrieDiff>();
                spawn(Box::pin(request_handler(network, stream, blockchain)));

                let stream = network.receive_requests::<RequestChunk>();
                spawn(Box::pin(request_handler(network, stream, blockchain)));

                let supports_history_index = blockchain.read().history_store.supports_index();

                // Only spawn these handlers if the history index is enabled.
                if supports_history_index {
                    let stream = network.receive_requests::<RequestTransactionsProof>();
                    spawn(Box::pin(request_handler(network, stream, blockchain)));

                    let stream = network.receive_requests::<RequestTransactionReceiptsByAddress>();
                    spawn(Box::pin(request_handler(network, stream, blockchain)));
                }

                let stream = network.receive_requests::<RequestTrieProof>();
                spawn(Box::pin(request_handler(network, stream, blockchain)));

                let stream = network.receive_requests::<RequestBlocksProof>();
                spawn(Box::pin(request_handler(network, stream, blockchain)));
            }
            BlockchainProxy::Light(_) => {}
        }
    }

    pub fn subscribe_events(&self) -> BroadcastStream<ConsensusEvent> {
        BroadcastStream::new(self.events.subscribe())
    }

    pub fn is_established(&self) -> bool {
        self.established_flag.load(Ordering::Acquire)
    }

    pub fn num_agents(&self) -> usize {
        self.sync.num_peers()
    }

    pub fn proxy(&self) -> ConsensusProxy<N> {
        ConsensusProxy {
            blockchain: self.blockchain.clone(),
            network: Arc::clone(&self.network),
            sync_progress: Arc::clone(&self.sync_progress),
            established_flag: Arc::clone(&self.established_flag),
            synced_validity_window_flag: Arc::clone(&self.synced_validity_window_flag),
            events: self.events.clone(),
            request: self.requests.0.clone(),
        }
    }

    /// Forcefully sets consensus established, should be used for tests only.
    pub fn force_established(&mut self) {
        trace!("Consensus forcefully established.");
        self.established_flag.swap(true, Ordering::Release);

        // Also stop any other checks.
        self.head_requests = None;
        self.head_requests_time = None;

        // We don't care if anyone is listening.
        let (synced_validity_window, _) = self.check_validity_window();
        self.events
            .send(ConsensusEvent::Established {
                synced_validity_window,
            })
            .ok();
    }

    /// Checks if the validity window is available.
    /// This function contains optimizations to only run the check when necessary.
    /// It returns a boolean indicating if the validity window is available
    /// and an consensus event if the value changed in this call.
    fn check_validity_window(&mut self) -> (bool, Option<ConsensusEvent>) {
        // We only check for the validity window if consensus is established
        // and we are in a new batch.
        // The `can_enforce_validity_window` flag can only change on macro blocks:
        // It can change to false during macro sync when pushing macro blocks.
        // It can change to true when we reach an offset of the transaction validity window
        // into a new epoch we have the history for. The validity window is a multiple
        // of the batch size – thus it is again a macro block.
        // We do not subscribe to blockchain events since the consensus polls all relevant channels
        // that add new blocks to the blockchain.
        #[cfg(feature = "full")]
        if let BlockchainReadProxy::Full(ref full_blockchain) = self.blockchain.read() {
            let current_batch_number = full_blockchain.batch_number();
            if current_batch_number > self.last_batch_number {
                self.last_batch_number = current_batch_number;
                let can_enforce_validity_window = full_blockchain.can_enforce_validity_window();
                let old_value = self
                    .synced_validity_window_flag
                    .swap(can_enforce_validity_window, Ordering::Release);
                // If the value changed, send an Established event.
                let mut event = None;
                if old_value != can_enforce_validity_window {
                    event = Some(ConsensusEvent::Established {
                        synced_validity_window: can_enforce_validity_window,
                    });
                }
                return (can_enforce_validity_window, event);
            }
        }
        (true, None)
    }

    /// Calculates and sets established state, returns a ConsensusEvent if the state changed.
    /// Once consensus is established, we can only lose it if we lose all our peers.
    /// To reach consensus established state, we need at least `minPeers` peers and
    /// one of the following conditions must be true:
    /// - we accepted at least `MIN_BLOCKS_ESTABLISHED` block announcements
    /// - we know at least 2/3 of the head blocks of our peers
    ///
    /// The latter check is started immediately once we reach the minimum number of peers
    /// and is potentially repeated in an interval of `HEAD_REQUESTS_TIMEOUT` until one
    /// of the conditions above is true.
    /// Any unknown blocks resulting of the head check are handled similarly as block announcements
    /// via the block queue.
    fn check_established(
        &mut self,
        finished_head_request: Option<HeadRequestsResult<N>>,
    ) -> Option<ConsensusEvent> {
        // We can only lose established state right now if we drop below our minimum peer threshold.
        if self.is_established() {
            if self.num_agents() < self.min_peers {
                warn!("Lost consensus!");
                self.established_flag.swap(false, Ordering::Release);
                return Some(ConsensusEvent::Lost);
            }
            // Check if validity window availability changed.
            if let (_, Some(event)) = self.check_validity_window() {
                return Some(event);
            }
        } else {
            // We have three conditions on whether we move to the established state.
            // First, we always need a minimum number of peers connected.
            // Second, the state must always be complete.
            // Then, we check that we either:
            // - accepted a minimum number of block announcements, or
            // - know the head state of a majority of our peers
            if self.num_agents() >= self.min_peers && self.sync.state_complete() {
                if self.sync.accepted_block_announcements() >= Self::MIN_BLOCKS_ESTABLISHED {
                    info!("Consensus established, number of accepted announcements satisfied.");
                    self.established_flag.swap(true, Ordering::Release);

                    // Also stop any other checks.
                    self.head_requests = None;
                    self.head_requests_time = None;

                    let (synced_validity_window, _) = self.check_validity_window();
                    return Some(ConsensusEvent::Established {
                        synced_validity_window,
                    });
                } else {
                    // The head state check is carried out immediately after we reach the minimum
                    // number of peers and then after certain time intervals until consensus is reached.
                    // If we have a finished one, check its outcome.
                    if let Some(head_request) = finished_head_request {
                        debug!("Trying to establish consensus, checking head request ({} known, {} unknown).", head_request.num_known_blocks, head_request.num_unknown_blocks);
                        // We would like that 2/3 of our peers have a known state, and
                        // that at least one peer actually responded (see
                        // `head_request_established`).
                        if head_request_established(
                            head_request.num_known_blocks,
                            head_request.num_unknown_blocks,
                            self.num_agents(),
                        ) {
                            info!("Consensus established, 2/3 of heads known.");
                            self.established_flag.swap(true, Ordering::Release);

                            let (synced_validity_window, _) = self.check_validity_window();
                            return Some(ConsensusEvent::Established {
                                synced_validity_window,
                            });
                        }
                    }

                    // If there's no ongoing head request, check whether we should start a new one.
                    if self.should_request_heads() {
                        self.request_heads();
                    }
                }
            }
        }
        None
    }

    fn should_request_heads(&self) -> bool {
        // Wait for an ongoing head request to finish.
        if self.head_requests.is_some() {
            return false;
        }

        // We need at least one synced peer to perform a head request.
        // Specifying `min_peers = 0` in the consensus config allows the first seed node
        // on a network to establish consensus without any other nodes present.
        if self.num_agents() == 0 && self.min_peers > 0 {
            return false;
        }

        // This is the case if `head_requests_time` is unset or the timeout is hit.
        self.head_requests_time
            .map(|time| time.elapsed() >= Self::HEAD_REQUESTS_TIMEOUT)
            .unwrap_or(true)
    }

    /// Requests heads from connected peers.
    fn request_heads(&mut self) {
        debug!(
            "Initiating head requests (to {} peers)",
            self.sync.num_peers()
        );

        self.head_requests = Some(HeadRequests::new(
            self.sync.peers(),
            Arc::clone(&self.network),
            self.blockchain.clone(),
        ));

        self.head_requests_time = Some(Instant::now());
        self.head_requests_interval = interval(Self::HEAD_REQUESTS_TIMEOUT);

        // Wake up the task such that we start working on the head request immediately.
        self.waker.wake();
    }

    fn resolve_block(&mut self, request: ResolveBlockRequest<N>) {
        self.sync.resolve_block(request)
    }
}

impl<N: Network> Future for Consensus<N> {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // Poll and advance block queue
        while let Poll::Ready(Some(event)) = self.sync.poll_next_unpin(cx) {
            match event {
                LiveSyncPushEvent::AcceptedAnnouncedBlock(_) => {
                    // Reset the head request timer when an announced block was accepted.
                    self.head_requests_time = Some(Instant::now());
                    self.head_requests_interval = interval(Self::HEAD_REQUESTS_TIMEOUT);
                }
                LiveSyncPushEvent::AcceptedBufferedBlock(_, remaining_in_buffer) => {
                    if !self.is_established() {
                        // Note: this output is parsed by our testing infrastructure (specifically devnet.sh),
                        // so please test that nothing breaks in there if you change this.
                        let block_number = {
                            let blockchain = self.blockchain.read();
                            blockchain.block_number()
                        };

                        info!(
                            "Catching up to tip of the chain (now at #{}, {} blocks remaining)",
                            block_number, remaining_in_buffer
                        );

                        self.sync_progress
                            .current_block_number
                            .store(block_number, Ordering::Release);
                        self.sync_progress
                            .remaining_blocks_to_sync
                            .store(remaining_in_buffer as u32, Ordering::Release);

                        if remaining_in_buffer == 0 {
                            self.head_requests_time = None;
                        }
                    }
                }
                LiveSyncPushEvent::ReceivedMissingBlocks(_) => {
                    if !self.is_established() {
                        // When syncing a stopped chain, we want to immediately start a new head request
                        // after receiving blocks for the current epoch.
                        self.head_requests_time = None;
                    }
                }
                LiveSyncPushEvent::RejectedBlock(hash) => {
                    warn!("Rejected block {}", hash);
                }
                LiveSyncPushEvent::AcceptedChunks(_) => {}
            }
        }

        // Check consensus established state on changes.
        if let Some(event) = self.check_established(None) {
            self.events.send(event).ok();
        }

        // Poll any head requests if active.
        if let Some(ref mut head_requests) = self.head_requests
            && let Poll::Ready(mut result) = head_requests.poll_unpin(cx)
        {
            // Reset head requests.
            self.head_requests = None;

            // Push unknown blocks to the block queue, trying to sync.
            for (block, peer_id) in result.unknown_blocks.drain(..) {
                self.sync.push_block(block, BlockSource::requested(peer_id));
            }

            // Update established state using the result.
            if let Some(event) = self.check_established(Some(result)) {
                self.events.send(event).ok();
            }
        }

        // Check if a ConsensusRequest was received
        while let Poll::Ready(Some(request)) = self.requests.1.poll_recv(cx) {
            match request {
                ConsensusRequest::ResolveBlock(request) => self.resolve_block(request),
            }
        }

        // Poll interval to wake up this task on a regular basis to perform head requests.
        while self.head_requests_interval.poll_next_unpin(cx).is_ready() {}

        // Advance consensus and catch-up through head requests.
        if self.should_request_heads() {
            self.request_heads();
        }

        self.waker.store_waker(cx);
        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use super::head_request_established;

    #[test]
    fn all_failed_head_request_does_not_establish() {
        // An all-failed head request yields 0 known / 0 unknown. With peers present
        // (e.g. the default `min_peers = 3`) this must NOT establish consensus, even
        // though `0 >= 2 * 0` holds: we have zero evidence about our peers' heads.
        assert!(!head_request_established(0, 0, 3));
        assert!(!head_request_established(0, 0, 1));
    }

    #[test]
    fn lone_seed_node_establishes_on_empty_result() {
        // A seed node configured with `min_peers = 0` and no peers issues a head
        // request over an empty peer set, which completes with 0 known / 0 unknown.
        // This is the sole legitimate zero-response case and must still establish.
        assert!(head_request_established(0, 0, 0));
    }

    #[test]
    fn establishes_when_two_thirds_of_heads_are_known() {
        // 2/3 (or more) of the responding peers report a known head.
        assert!(head_request_established(2, 1, 3));
        assert!(head_request_established(4, 2, 6));
        assert!(head_request_established(1, 0, 3));
    }

    #[test]
    fn does_not_establish_below_two_thirds_known() {
        // Fewer than 2/3 of the responding peers report a known head.
        assert!(!head_request_established(1, 1, 3));
        assert!(!head_request_established(2, 3, 5));
    }
}