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
use std::{
    cmp,
    cmp::Ordering,
    collections::{BinaryHeap, VecDeque},
    fmt::{Debug, Display},
    future::Future,
    pin::Pin,
    sync::Arc,
    task::{Context, Poll, Waker},
};

use futures::{future, future::BoxFuture, FutureExt, Stream, StreamExt};
use nimiq_network_interface::network::Network;
use nimiq_utils::{stream::FuturesUnordered, WakerExt as _};
use parking_lot::RwLock;
use pin_project::pin_project;

use super::peer_list::PeerList;
use crate::sync::peer_list::PeerListIndex;

/// A wrapper struct that tracks metadata for each in-flight request.
#[pin_project]
#[derive(Debug)]
struct OrderWrapper<TId, TOutput> {
    id: TId,
    #[pin]
    data: TOutput, // A future or a future's output
    index: usize,
    peer: PeerListIndex, // The peer the data is requested from
    num_tries: usize,    // The number of tries this id has been requested
}

impl<TId: Clone, TOutput: Future> Future for OrderWrapper<TId, TOutput> {
    type Output = OrderWrapper<TId, TOutput::Output>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let id = self.id.clone();
        let index = self.index;
        let peer = self.peer.clone();
        let num_tries = self.num_tries;
        self.project().data.poll(cx).map(|output| OrderWrapper {
            id,
            data: output,
            index,
            peer,
            num_tries,
        })
    }
}

impl<TId, TOutput> PartialEq for OrderWrapper<TId, TOutput> {
    fn eq(&self, other: &Self) -> bool {
        self.index == other.index
    }
}
impl<TId, TOutput> Eq for OrderWrapper<TId, TOutput> {}
impl<TId, TOutput> PartialOrd for OrderWrapper<TId, TOutput> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
impl<TId, TOutput> Ord for OrderWrapper<TId, TOutput> {
    fn cmp(&self, other: &Self) -> Ordering {
        // BinaryHeap is a max heap, so compare backwards here.
        other.index.cmp(&self.index)
    }
}

type RequestFn<TId, TNetwork, TOutput, TError> = fn(
    TId,
    Arc<TNetwork>,
    <TNetwork as Network>::PeerId,
) -> BoxFuture<'static, Result<TOutput, TError>>;
type VerifyFn<TId, TOutput, TVerifyState> = fn(&TId, &mut TOutput, &mut TVerifyState) -> bool;

/// The SyncQueue will request a list of ids from a set of peers
/// and implements an ordered stream over the resulting objects.
/// The stream returns an error if an id could not be resolved.
pub struct SyncQueue<
    TNetwork: Network,
    TId: Clone,
    TOutput: 'static,
    TError: 'static,
    TVerifyState: 'static,
> {
    pub(crate) peers: Arc<RwLock<PeerList<TNetwork>>>,
    network: Arc<TNetwork>,
    desired_pending_size: usize,
    ids_to_request: VecDeque<(TId, Option<TNetwork::PeerId>)>,
    pending_futures:
        FuturesUnordered<OrderWrapper<TId, BoxFuture<'static, Option<Result<TOutput, TError>>>>>,
    // outputs received but not yet yielded.
    queued_outputs: BinaryHeap<OrderWrapper<TId, Option<TOutput>>>,
    next_incoming_index: usize,
    next_outgoing_index: usize,
    current_peer_index: PeerListIndex,
    request_fn: RequestFn<TId, TNetwork, TOutput, TError>,
    verify_fn: VerifyFn<TId, TOutput, TVerifyState>,
    verify_state: TVerifyState,
    waker: Option<Waker>,
}

impl<TNetwork, TId, TOutput, TError> SyncQueue<TNetwork, TId, TOutput, TError, ()>
where
    TId: Clone + Debug,
    TOutput: Send + Unpin + 'static,
    TError: Debug + Display + Send,
    TNetwork: Network,
{
    #[cfg(feature = "full")]
    pub fn new(
        network: Arc<TNetwork>,
        ids: Vec<(TId, Option<TNetwork::PeerId>)>,
        peers: Arc<RwLock<PeerList<TNetwork>>>,
        desired_pending_size: usize,
        request_fn: RequestFn<TId, TNetwork, TOutput, TError>,
    ) -> Self {
        Self::with_verification(
            network,
            ids,
            peers,
            desired_pending_size,
            request_fn,
            |_, _, _| true,
            (),
        )
    }
}

impl<TNetwork, TId, TOutput, TError, TVerifyState>
    SyncQueue<TNetwork, TId, TOutput, TError, TVerifyState>
where
    TId: Clone + Debug,
    TOutput: Send + Unpin + 'static,
    TError: Debug + Display + Send,
    TNetwork: Network,
{
    const MIN_ATTEMPTS: usize = 4;
    const MAX_ATTEMPTS: usize = 12;

    pub fn with_verification(
        network: Arc<TNetwork>,
        ids: Vec<(TId, Option<TNetwork::PeerId>)>,
        peers: Arc<RwLock<PeerList<TNetwork>>>,
        desired_pending_size: usize,
        request_fn: RequestFn<TId, TNetwork, TOutput, TError>,
        verify_fn: VerifyFn<TId, TOutput, TVerifyState>,
        initial_verify_state: TVerifyState,
    ) -> Self {
        SyncQueue {
            network,
            peers,
            desired_pending_size,
            ids_to_request: VecDeque::from(ids),
            pending_futures: FuturesUnordered::new(),
            queued_outputs: BinaryHeap::new(),
            next_incoming_index: 0,
            next_outgoing_index: 0,
            current_peer_index: PeerListIndex::default(),
            request_fn,
            verify_fn,
            verify_state: initial_verify_state,
            waker: None,
        }
    }

    fn try_push_futures(&mut self) {
        // Determine number of new futures required to maintain desired_pending_size.
        let num_ids_to_request = cmp::min(
            self.ids_to_request.len(), // At most all of the ids
            // The number of pending futures can be higher than the desired pending size
            // (e.g., if there is an error and we re-request)
            self.desired_pending_size
                .saturating_sub(self.pending_futures.len() + self.queued_outputs.len()),
        );

        // Drain ids and produce futures.
        for _ in 0..num_ids_to_request {
            let (id, peer_id) = self.ids_to_request.pop_front().unwrap();

            // If we have a pubsub id, try to get the corresponding peer.
            // If this fails, we still want to get and increment.
            let pubsub_peer = peer_id.and_then(|peer_id| {
                self.peers
                    .read()
                    .index_of(&peer_id)
                    .map(|peer_index| (peer_id, peer_index))
            });

            // If we know the peer that sent us this block, we ask them first.
            let peer = match pubsub_peer {
                Some(pubsub_peer) => Some(pubsub_peer),
                None => self
                    .peers
                    .read()
                    .increment_and_get(&mut self.current_peer_index)
                    .map(|peer_id| (peer_id, self.current_peer_index.clone())),
            };

            let wrapper = match peer {
                Some((peer_id, peer_index)) => {
                    log::trace!(
                        %peer_id,
                        current_peer_index = %peer_index,
                        "Requesting {:?} @ {}",
                        id,
                        self.next_incoming_index,
                    );

                    OrderWrapper {
                        data: (self.request_fn)(id.clone(), Arc::clone(&self.network), peer_id)
                            .map(Some)
                            .boxed(),
                        id,
                        index: self.next_incoming_index,
                        peer: peer_index,
                        num_tries: 1,
                    }
                }
                None => OrderWrapper {
                    data: future::ready(None).boxed(),
                    id,
                    index: self.next_incoming_index,
                    peer: PeerListIndex::default(),
                    num_tries: 1,
                },
            };

            self.next_incoming_index += 1;

            self.pending_futures.push(wrapper);
        }

        if num_ids_to_request > 0 {
            log::trace!(
                "Requesting {} ids (ids_to_request={}, remaining_until_limit={}, pending_futures={}, queued_outputs={}, num_peers={})",
                num_ids_to_request,
                self.ids_to_request.len(),
                self.desired_pending_size
                    .saturating_sub(self.pending_futures.len() + self.queued_outputs.len()),
                self.pending_futures.len(),
                self.queued_outputs.len(),
                self.peers.read().len(),
            );

            self.waker.wake();
        }
    }

    // Handles re-requesting failed items from a different peer.
    fn retry_request(
        &mut self,
        id: TId,
        index: usize,
        mut peer_index: PeerListIndex,
        num_tries: usize,
    ) -> bool {
        // If we tried all peers for this id, return an error.
        // Bound the number of tries such that
        //   - we don't send an excessive number of requests when we have many peers
        //   - we try multiple times with the same peer if we only have few peers
        let max_tries = self
            .peers
            .read()
            .len()
            .clamp(Self::MIN_ATTEMPTS, Self::MAX_ATTEMPTS);
        if num_tries >= max_tries {
            return false;
        }

        // Re-request from different peer. Return an error if there are no more peers.
        let peer = match self.peers.read().increment_and_get(&mut peer_index) {
            Some(peer) => peer,
            None => return false,
        };

        log::debug!(
            peer_id = %peer,
            current_peer_index = %self.current_peer_index,
            "Re-requesting {:?} @ {}",
            id,
            index,
        );

        let wrapper = OrderWrapper {
            data: (self.request_fn)(id.clone(), Arc::clone(&self.network), peer)
                .map(Some)
                .boxed(),
            id,
            index,
            peer: peer_index,
            num_tries: num_tries + 1,
        };

        self.pending_futures.push(wrapper);

        true
    }

    pub fn add_peer(&mut self, peer_id: TNetwork::PeerId) -> bool {
        self.peers.write().add_peer(peer_id)
    }

    pub fn remove_peer(&mut self, peer_id: &TNetwork::PeerId) {
        self.peers.write().remove_peer(peer_id);
    }

    pub fn add_ids(&mut self, ids: Vec<(TId, Option<TNetwork::PeerId>)>) {
        for id in ids {
            self.ids_to_request.push_back(id);
        }

        // Adding new ids needs to wake the task that is polling the SyncQueue.
        self.waker.wake();
    }

    #[cfg(feature = "full")]
    /// Truncates the stored ids, retaining only the first `len` elements.
    /// The elements are counted from the *original* start of the ids vector.
    pub fn truncate_ids(&mut self, len: usize) {
        self.ids_to_request
            .truncate(len.saturating_sub(self.next_incoming_index));
    }

    /// Returns the current number of peers in the peer list.
    #[cfg(feature = "full")]
    pub fn num_peers(&self) -> usize {
        self.peers.read().len()
    }

    /// Returns the total number of unresolved requested items.
    pub fn len(&self) -> usize {
        self.ids_to_request.len() + self.pending_futures.len() + self.queued_outputs.len()
    }

    /// Checks if there are no more items to request and all request responses have been processed and returned.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Sets the internal verification state for the incoming responses' verification.
    #[cfg(feature = "full")]
    pub fn set_verify_state(&mut self, verify_state: TVerifyState) {
        self.verify_state = verify_state;
    }
}

impl<TNetwork, TId, TOutput, TError, TVerifyState> Stream
    for SyncQueue<TNetwork, TId, TOutput, TError, TVerifyState>
where
    TNetwork: Network,
    TId: Clone + Unpin + Debug,
    TOutput: Send + Unpin,
    TError: Debug + Display + Send,
    TVerifyState: Unpin + 'static,
{
    type Item = Result<TOutput, TId>;

    // The stream implementation that returns items in order as they become available and pass verification.
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.waker.store_waker(cx);

        // Try to request more objects.
        self.try_push_futures();

        // Check to see if we've already received the next value.
        if let Some(next_output) = self.queued_outputs.peek()
            && next_output.index == self.next_outgoing_index
        {
            let request = self.queued_outputs.pop().unwrap();

            match request.data {
                Some(mut data) => {
                    if (self.verify_fn)(&request.id, &mut data, &mut self.verify_state) {
                        self.next_outgoing_index += 1;
                        return Poll::Ready(Some(Ok(data)));
                    } else {
                        debug!(peer_id = %request.peer, id = ?request.id, "Verification failed");
                        let id = request.id.clone();
                        if !self.retry_request(
                            request.id,
                            request.index,
                            request.peer,
                            request.num_tries,
                        ) {
                            self.next_outgoing_index += 1;
                            return Poll::Ready(Some(Err(id)));
                        }
                    }
                }
                None => {
                    self.next_outgoing_index += 1;
                    return Poll::Ready(Some(Err(request.id)));
                }
            }
        }

        loop {
            match self.pending_futures.poll_next_unpin(cx) {
                Poll::Ready(Some(result)) => {
                    match result.data {
                        Some(Ok(mut output)) => {
                            if result.index == self.next_outgoing_index {
                                if (self.verify_fn)(&result.id, &mut output, &mut self.verify_state)
                                {
                                    self.next_outgoing_index += 1;
                                    return Poll::Ready(Some(Ok(output)));
                                } else {
                                    debug!(peer_id = %result.peer, id = ?result.id, "Verification failed");
                                }
                            } else {
                                self.queued_outputs.push(OrderWrapper {
                                    id: result.id,
                                    data: Some(output),
                                    index: result.index,
                                    peer: result.peer,
                                    num_tries: result.num_tries,
                                });
                                continue;
                            }
                        }
                        Some(Err(error)) => {
                            debug!(peer_id = %result.peer, id = ?result.id, %error, "Request error");
                        }
                        None => {
                            debug!(id = ?result.id, "Request error: no peers available");
                        }
                    }

                    // The request or verification failed.
                    let id = result.id.clone();
                    let peer = result.peer.clone();
                    if !self.retry_request(result.id, result.index, result.peer, result.num_tries) {
                        if result.index == self.next_outgoing_index {
                            self.next_outgoing_index += 1;
                            return Poll::Ready(Some(Err(id)));
                        } else {
                            self.queued_outputs.push(OrderWrapper {
                                id,
                                data: None,
                                index: result.index,
                                peer,
                                num_tries: result.num_tries,
                            });
                        }
                    }
                }
                Poll::Ready(None) => {
                    if self.ids_to_request.is_empty() || self.peers.read().is_empty() {
                        self.waker.store_waker(cx);
                    } else {
                        self.try_push_futures();
                        if self.ids_to_request.is_empty() {
                            self.waker.store_waker(cx);
                        }
                    }
                    return Poll::Pending;
                }
                Poll::Pending => {
                    if self.ids_to_request.is_empty() {
                        self.waker.store_waker(cx);
                    }
                    return Poll::Pending;
                }
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let len = self.len();
        (len, Some(len))
    }
}

#[cfg(test)]
mod tests {
    use std::{
        sync::Arc,
        task::{Context, Poll},
    };

    use futures::{future, task::noop_waker_ref, FutureExt, StreamExt};
    use nimiq_network_mock::MockHub;
    use thiserror::Error;

    use crate::sync::sync_queue::SyncQueue;

    #[test]
    fn it_can_handle_no_peers() {
        #[derive(Debug, Error)]
        #[error("error")]
        struct Error;

        let mut hub = MockHub::new();
        let network = Arc::new(hub.new_network());

        let mut queue: SyncQueue<_, _, i32, Error, _> = SyncQueue::new(
            network,
            vec![(1, None), (2, None), (3, None), (4, None)],
            Default::default(),
            1,
            |_, _, _| future::ready(Err(Error)).boxed(),
        );

        match queue.poll_next_unpin(&mut Context::from_waker(noop_waker_ref())) {
            Poll::Ready(Some(Err(id))) => assert_eq!(id, 1),
            _ => panic!("Expected error"),
        };
    }
}