Skip to main content

nimiq_consensus/sync/live/block_queue/
proxy.rs

1use std::{
2    collections::{HashSet, VecDeque},
3    future::Future,
4    pin::Pin,
5    sync::{Arc, Weak},
6    task::{Context, Poll},
7};
8
9use futures::{future::BoxFuture, Stream, StreamExt};
10use nimiq_block::Block;
11use nimiq_blockchain_proxy::BlockchainProxy;
12use nimiq_hash::Blake2bHash;
13use nimiq_network_interface::network::Network;
14use nimiq_utils::spawn;
15use parking_lot::Mutex;
16#[cfg(feature = "full")]
17use parking_lot::RwLock;
18use tokio::sync::mpsc::{channel, Receiver};
19use tokio_util::sync::PollSender;
20
21#[cfg(feature = "full")]
22use crate::sync::peer_list::PeerList;
23use crate::{
24    consensus::ResolveBlockRequest,
25    sync::{
26        live::{
27            block_queue::{
28                live_sync::PushOpResult, queue::BlockQueue, BlockAndSource, BlockStream,
29                GossipSubBlockStream, QueuedBlock,
30            },
31            queue::{LiveSyncQueue, QueueConfig},
32        },
33        sync_interface::LiveSyncEvent,
34    },
35    BlsCache,
36};
37
38/// Capacity of the channel between the internal block queue and the live sync consumer. Large
39/// enough that normal operation never fills it, so the queue keeps running while the consumer
40/// pushes, but bounded so that a stalled consumer cannot be made to buffer without limit.
41const QUEUED_BLOCK_BUFFER_SIZE: usize = 256;
42
43/// A proxy to interact with `BlockQueue` running on its independent task.
44pub struct BlockQueueProxy<N: Network> {
45    /// Shared reference to the underlying block queue.
46    queue: Arc<Mutex<BlockQueue<N>>>,
47    /// Channel used to receive queued blocks from the internal background task.
48    receiver: Receiver<QueuedBlock<N>>,
49}
50
51impl<N: Network> BlockQueueProxy<N> {
52    pub async fn new(network: Arc<N>, blockchain: BlockchainProxy, config: QueueConfig) -> Self {
53        let queue = BlockQueue::new(network, blockchain, config).await;
54        Self::with_queue(queue)
55    }
56
57    /// Starts the internal queue with a stream of blocks received via gossip sub.
58    pub fn with_gossipsub_block_stream(
59        blockchain: BlockchainProxy,
60        network: Arc<N>,
61        block_stream: GossipSubBlockStream<N>,
62        config: QueueConfig,
63    ) -> Self {
64        let queue =
65            BlockQueue::with_gossipsub_block_stream(blockchain, network, block_stream, config);
66        Self::with_queue(queue)
67    }
68
69    /// Uses a specific block stream
70    pub fn with_block_stream(
71        blockchain: BlockchainProxy,
72        network: Arc<N>,
73        block_stream: BlockStream<N>,
74        config: QueueConfig,
75    ) -> Self {
76        let queue = BlockQueue::with_block_stream(blockchain, network, block_stream, config);
77        Self::with_queue(queue)
78    }
79
80    /// Spawns the block queue as another task and opens the communication channel to forward block queue results to the current task.
81    pub fn with_queue(queue: BlockQueue<N>) -> Self {
82        let queue = Arc::new(Mutex::new(queue));
83
84        let (sender, receiver) = channel(QUEUED_BLOCK_BUFFER_SIZE);
85
86        let future = BlockQueueFuture {
87            queue: Arc::downgrade(&queue),
88            sender: PollSender::new(sender),
89        };
90        spawn(future);
91
92        Self { queue, receiver }
93    }
94
95    /// Marks the given block as processed in the queue.
96    pub fn on_block_processed(&mut self, block_hash: &Blake2bHash) {
97        self.queue.lock().on_block_processed(block_hash);
98    }
99
100    /// Marks invalid blocks from the queue.
101    pub fn remove_invalid_blocks(&mut self, invalid_blocks: &mut HashSet<Blake2bHash>) {
102        self.queue.lock().remove_invalid_blocks(invalid_blocks);
103    }
104
105    /// Returns the blocks currently buffered in the queue.
106    pub fn buffered_blocks(&self) -> Vec<(u32, Vec<Block>)> {
107        self.queue.lock().buffered_blocks()
108    }
109
110    /// Returns the number of buffered block heights.
111    pub fn num_buffered_heights(&self) -> usize {
112        self.queue.lock().num_buffered_heights()
113    }
114
115    /// Returns the peer list used by the queue
116    #[cfg(feature = "full")]
117    pub(crate) fn peer_list(&self) -> Arc<RwLock<PeerList<N>>> {
118        self.queue.lock().peer_list()
119    }
120}
121
122impl<N: Network> LiveSyncQueue<N> for BlockQueueProxy<N> {
123    type QueueResult = QueuedBlock<N>;
124    type PushResult = PushOpResult<N>;
125
126    fn push_queue_result(
127        network: Arc<N>,
128        blockchain: BlockchainProxy,
129        bls_cache: Arc<Mutex<BlsCache>>,
130        result: Self::QueueResult,
131    ) -> VecDeque<BoxFuture<'static, Self::PushResult>> {
132        BlockQueue::push_queue_result(network, blockchain, bls_cache, result)
133    }
134
135    fn process_push_result(&mut self, item: Self::PushResult) -> Option<LiveSyncEvent<N::PeerId>> {
136        self.queue.lock().process_push_result(item)
137    }
138
139    fn peers(&self) -> Vec<N::PeerId> {
140        self.queue.lock().peers()
141    }
142
143    fn num_peers(&self) -> usize {
144        self.queue.lock().num_peers()
145    }
146
147    fn add_peer(&self, peer_id: N::PeerId) {
148        self.queue.lock().add_peer(peer_id)
149    }
150
151    fn add_block_stream<S>(&mut self, block_stream: S)
152    where
153        S: Stream<Item = BlockAndSource<N>> + Send + 'static,
154    {
155        self.queue.lock().add_block_stream(block_stream)
156    }
157
158    fn include_body(&self) -> bool {
159        self.queue.lock().include_body()
160    }
161
162    fn resolve_block(&mut self, request: ResolveBlockRequest<N>) {
163        self.queue.lock().resolve_block(request)
164    }
165
166    fn acceptance_window_size(&self) -> u32 {
167        self.queue.lock().acceptance_window_size()
168    }
169}
170
171impl<N: Network> Stream for BlockQueueProxy<N> {
172    type Item = QueuedBlock<N>;
173
174    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
175        self.receiver.poll_recv(cx)
176    }
177}
178
179/// Background future that continuously polls the internal `BlockQueue` for new queued blocks.
180struct BlockQueueFuture<N: Network> {
181    queue: Weak<Mutex<BlockQueue<N>>>,
182    sender: PollSender<QueuedBlock<N>>,
183}
184
185impl<N: Network> Future for BlockQueueFuture<N> {
186    type Output = ();
187
188    /// Continuously polls the BlockQueue. If a new queued block is available,
189    /// it sends it to the proxy. Stops if the queue is dropped or the stream ends.
190    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
191        let this = self.get_mut();
192
193        let queue = match this.queue.upgrade() {
194            Some(queue) => queue,
195            None => return Poll::Ready(()),
196        };
197
198        loop {
199            // Reserve capacity before polling the queue, so we never take a block that we cannot
200            // deliver. This is what propagates the consumer's backpressure to the block stream.
201            match this.sender.poll_reserve(cx) {
202                Poll::Ready(Ok(())) => {}
203                Poll::Ready(Err(_)) => return Poll::Ready(()),
204                Poll::Pending => return Poll::Pending,
205            }
206
207            // Bind the result so the queue lock is released before sending.
208            let event = queue.lock().poll_next_unpin(cx);
209            match event {
210                Poll::Ready(Some(queued_block)) => {
211                    if this.sender.send_item(queued_block).is_err() {
212                        return Poll::Ready(());
213                    }
214                }
215                Poll::Ready(None) => return Poll::Ready(()),
216                Poll::Pending => return Poll::Pending,
217            }
218        }
219    }
220}