zebra_network/peer_set/inventory_registry.rs
1//! Inventory Registry Implementation
2//!
3//! [RFC]: https://zebra.zfnd.org/dev/rfcs/0003-inventory-tracking.html
4
5use std::{
6 pin::Pin,
7 task::{Context, Poll},
8};
9
10use futures::{FutureExt, Stream, StreamExt};
11use indexmap::{IndexMap, IndexSet};
12use tokio::{
13 sync::broadcast,
14 time::{self, Instant},
15};
16use tokio_stream::wrappers::{errors::BroadcastStreamRecvError, BroadcastStream, IntervalStream};
17
18use zebra_chain::serialization::AtLeastOne;
19
20use crate::{
21 constants::INVENTORY_ROTATION_INTERVAL,
22 protocol::{external::InventoryHash, internal::InventoryResponse},
23 BoxError, PeerSocketAddr,
24};
25
26use self::update::Update;
27
28/// Underlying type for the alias InventoryStatus::*
29use InventoryResponse::*;
30
31pub mod update;
32
33#[cfg(test)]
34mod tests;
35
36/// The maximum number of inventory hashes we will track from a single peer.
37///
38/// # Security
39///
40/// This limits known memory denial of service attacks like <https://invdos.net/> to a total of:
41/// ```text
42/// 1000 inventory * 2 maps * 32-64 bytes per inventory = less than 1 MB
43/// 1000 inventory * 70 peers * 2 maps * 6-18 bytes per address = up to 3 MB
44/// ```
45///
46/// Since the inventory registry is an efficiency optimisation, which falls back to a
47/// random peer, we only need to track a small number of hashes for available inventory.
48///
49/// But we want to be able to track a significant amount of missing inventory,
50/// to limit queries for globally missing inventory.
51//
52// TODO: split this into available (25) and missing (1000 or more?)
53pub const MAX_INV_PER_MAP: usize = 1000;
54
55/// The maximum number of peers we will track inventory for.
56///
57/// # Security
58///
59/// This limits known memory denial of service attacks. See [`MAX_INV_PER_MAP`] for details.
60///
61/// Since the inventory registry is an efficiency optimisation, which falls back to a
62/// random peer, we only need to track a small number of peers per inv for available inventory.
63///
64/// But we want to be able to track missing inventory for almost all our peers,
65/// so we only query a few peers for inventory that is genuinely missing from the network.
66//
67// TODO: split this into available (25) and missing (70)
68pub const MAX_PEERS_PER_INV: usize = 70;
69
70/// A peer inventory status, which tracks a hash for both available and missing inventory.
71pub type InventoryStatus<T> = InventoryResponse<T, T>;
72
73/// A peer inventory status change, used in the inventory status channel.
74///
75/// For performance reasons, advertisements should only be tracked
76/// for hashes that are rare on the network.
77/// So Zebra only tracks single-block inventory messages.
78///
79/// For security reasons, all `notfound` rejections should be tracked.
80/// This also helps with performance, if the hash is rare on the network.
81pub type InventoryChange = InventoryStatus<(AtLeastOne<InventoryHash>, PeerSocketAddr)>;
82
83/// An internal marker used in inventory status hash maps.
84type InventoryMarker = InventoryStatus<()>;
85
86/// The number of repeat requests for a block that were sent to each group of peers, see
87/// [`InventoryRegistry::repeat_requests()`].
88#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
89pub struct RepeatRequests {
90 /// Requests sent to peers that advertised the block.
91 pub advertisers: usize,
92
93 /// Requests sent to peers that didn't advertise the block.
94 pub other_peers: usize,
95}
96
97/// An Inventory Registry for tracking recent inventory advertisements and missing inventory.
98///
99/// For more details please refer to the [RFC].
100///
101/// [RFC]: https://zebra.zfnd.org/dev/rfcs/0003-inventory-tracking.html
102pub struct InventoryRegistry {
103 /// Map tracking the latest inventory status from the current interval
104 /// period.
105 //
106 // TODO: split maps into available and missing, so we can limit them separately.
107 current: IndexMap<InventoryHash, IndexMap<PeerSocketAddr, InventoryMarker>>,
108
109 /// Map tracking inventory statuses from the previous interval period.
110 prev: IndexMap<InventoryHash, IndexMap<PeerSocketAddr, InventoryMarker>>,
111
112 /// Map tracking peers that failed to return inventory in the current interval period.
113 ///
114 /// A failure is a completed peer error or response timeout, not caller cancellation or a
115 /// `notfound` response. Missing inventory is tracked separately; failed peers might still have it.
116 ///
117 /// Failures are tracked separately from inventory statuses, so a peer can't clear its failure
118 /// by advertising the inventory again.
119 ///
120 /// # Security
121 ///
122 /// This map is limited like the status maps, using [`MAX_INV_PER_MAP`] and
123 /// [`MAX_PEERS_PER_INV`]. So it uses up to 3 MB for both intervals.
124 failed_current: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
125
126 /// Map tracking peers that failed to return inventory in the previous interval period.
127 failed_prev: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
128
129 /// Map tracking the peers that returned a block they were asked for because the block was
130 /// advertised, in the current interval period.
131 ///
132 /// # Security
133 ///
134 /// A caller only asks for a block again if it rejected the block it was given. So a second
135 /// request for one of these blocks shows that a peer that advertised it served something
136 /// else, and the advertisements for it can't be trusted. See
137 /// [`InventoryRegistry::served_peers()`].
138 ///
139 /// This map is limited like `failed_current`.
140 served_current: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
141
142 /// Map tracking the peers that returned an advertised block in the previous interval period.
143 served_prev: IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
144
145 /// Map tracking the repeat requests sent for a block in the current interval period, see
146 /// [`InventoryRegistry::repeat_requests()`].
147 ///
148 /// This map is limited like `failed_current`.
149 repeat_current: IndexMap<InventoryHash, RepeatRequests>,
150
151 /// Map tracking the repeat requests sent for a block in the previous interval period.
152 repeat_prev: IndexMap<InventoryHash, RepeatRequests>,
153
154 /// Stream of incoming inventory statuses to register.
155 inv_stream: Pin<
156 Box<dyn Stream<Item = Result<InventoryChange, BroadcastStreamRecvError>> + Send + 'static>,
157 >,
158
159 /// Interval tracking when we should next rotate our maps.
160 interval: IntervalStream,
161}
162
163impl std::fmt::Debug for InventoryRegistry {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 f.debug_struct("InventoryRegistry")
166 .field("current", &self.current)
167 .field("prev", &self.prev)
168 .finish()
169 }
170}
171
172impl InventoryChange {
173 /// Returns a new available inventory change from a single hash.
174 pub fn new_available(hash: InventoryHash, peer: PeerSocketAddr) -> Self {
175 let bv = AtLeastOne::from_vec(vec![hash]).expect("bounded vec must fit");
176 InventoryStatus::Available((bv, peer))
177 }
178
179 /// Returns a new missing inventory change from a single hash.
180 #[allow(dead_code)]
181 pub fn new_missing(hash: InventoryHash, peer: PeerSocketAddr) -> Self {
182 let bv = AtLeastOne::from_vec(vec![hash]).expect("bounded vec must fit");
183 InventoryStatus::Missing((bv, peer))
184 }
185
186 /// Returns a new available multiple inventory change, if `hashes` contains at least one change.
187 pub fn new_available_multi<'a>(
188 hashes: impl IntoIterator<Item = &'a InventoryHash>,
189 peer: PeerSocketAddr,
190 ) -> Option<Self> {
191 let mut hashes: Vec<InventoryHash> = hashes.into_iter().copied().collect();
192
193 // # Security
194 //
195 // Don't send more hashes than we're going to store.
196 // It doesn't matter which hashes we choose, because this is an efficiency optimisation.
197 //
198 // This limits known memory denial of service attacks to:
199 // `1000 hashes * 200 peers/channel capacity * 32-64 bytes = up to 12 MB`
200 hashes.truncate(MAX_INV_PER_MAP);
201
202 let hashes = hashes.try_into().ok();
203
204 hashes.map(|hashes| InventoryStatus::Available((hashes, peer)))
205 }
206
207 /// Returns a new missing multiple inventory change, if `hashes` contains at least one change.
208 pub fn new_missing_multi<'a>(
209 hashes: impl IntoIterator<Item = &'a InventoryHash>,
210 peer: PeerSocketAddr,
211 ) -> Option<Self> {
212 let mut hashes: Vec<InventoryHash> = hashes.into_iter().copied().collect();
213
214 // # Security
215 //
216 // Don't send more hashes than we're going to store.
217 // It doesn't matter which hashes we choose, because this is an efficiency optimisation.
218 hashes.truncate(MAX_INV_PER_MAP);
219
220 let hashes = hashes.try_into().ok();
221
222 hashes.map(|hashes| InventoryStatus::Missing((hashes, peer)))
223 }
224}
225
226impl<T> InventoryStatus<T> {
227 /// Get a marker for the status, without any associated data.
228 pub fn marker(&self) -> InventoryMarker {
229 self.as_ref().map(|_inner| ())
230 }
231
232 /// Maps an `InventoryStatus<T>` to `InventoryStatus<U>` by applying a function to a contained value.
233 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> InventoryStatus<U> {
234 // Based on Option::map from https://doc.rust-lang.org/src/core/option.rs.html#844
235 match self {
236 Available(item) => Available(f(item)),
237 Missing(item) => Missing(f(item)),
238 }
239 }
240}
241
242impl<T: Clone> InventoryStatus<T> {
243 /// Returns a clone of the inner item, regardless of status.
244 pub fn to_inner(&self) -> T {
245 match self {
246 Available(item) | Missing(item) => item.clone(),
247 }
248 }
249}
250
251impl InventoryRegistry {
252 /// Returns a new Inventory Registry for `inv_stream`.
253 pub fn new(inv_stream: broadcast::Receiver<InventoryChange>) -> Self {
254 let interval = INVENTORY_ROTATION_INTERVAL;
255
256 // Don't do an immediate rotation, current and prev are already empty.
257 let mut interval = tokio::time::interval_at(Instant::now() + interval, interval);
258 // # Security
259 //
260 // Delay missed ticks so newly registered inventory survives a full interval.
261 // Per-map caps bound memory use even when polling is delayed.
262 interval.set_missed_tick_behavior(time::MissedTickBehavior::Delay);
263
264 Self {
265 current: Default::default(),
266 prev: Default::default(),
267 failed_current: Default::default(),
268 failed_prev: Default::default(),
269 served_current: Default::default(),
270 served_prev: Default::default(),
271 repeat_current: Default::default(),
272 repeat_prev: Default::default(),
273 inv_stream: BroadcastStream::new(inv_stream).boxed(),
274 interval: IntervalStream::new(interval),
275 }
276 }
277
278 /// Returns an iterator over addrs of peers that have recently advertised `hash` in their inventory.
279 pub fn advertising_peers(&self, hash: InventoryHash) -> impl Iterator<Item = &PeerSocketAddr> {
280 self.status_peers(hash)
281 .filter_map(|addr_status| addr_status.available())
282 }
283
284 /// Returns an iterator over addrs of peers that have recently missed `hash` in their inventory.
285 pub fn missing_peers(&self, hash: InventoryHash) -> impl Iterator<Item = &PeerSocketAddr> {
286 self.status_peers(hash)
287 .filter_map(|addr_status| addr_status.missing())
288 }
289
290 /// Returns an iterator over addrs of peers that recently failed to return `hash`.
291 ///
292 /// Can include the same peer twice, if it failed in the current and previous interval.
293 pub fn failed_peers(&self, hash: InventoryHash) -> impl Iterator<Item = &PeerSocketAddr> {
294 self.failed_current
295 .get(&hash)
296 .into_iter()
297 .chain(self.failed_prev.get(&hash))
298 .flatten()
299 }
300
301 /// Records that `peer` failed to return `hash`.
302 ///
303 /// Failures expire after the registry rotates twice, like inventory statuses.
304 pub fn register_failed(&mut self, hash: InventoryHash, peer: PeerSocketAddr) {
305 Self::register_peer(&mut self.failed_current, hash, peer);
306 }
307
308 /// Returns an iterator over addrs of peers that recently returned `hash` when they were asked
309 /// for it because it was advertised, or in a repeat request.
310 ///
311 /// Can include the same peer twice, if it returned `hash` in the current and previous interval.
312 ///
313 /// # Security
314 ///
315 /// If this isn't empty, a request for `hash` is a repeat: the caller rejected the block one
316 /// of these peers gave it. A block hash only commits to the header, so a peer can advertise a
317 /// block and then serve its header with other transactions. So the caller should only ask
318 /// these peers as a last resort.
319 ///
320 /// Several peers can advertise the same block to get each retry in turn, and the caller can't
321 /// tell them from the honest peers that advertised it. See
322 /// [`InventoryRegistry::repeat_answer_count()`].
323 pub fn served_peers(&self, hash: InventoryHash) -> impl Iterator<Item = &PeerSocketAddr> {
324 self.served_current
325 .get(&hash)
326 .into_iter()
327 .chain(self.served_prev.get(&hash))
328 .flatten()
329 }
330
331 /// Records that `peer` returned `hash` when it was asked for it because it was advertised, or
332 /// in a repeat request.
333 ///
334 /// These records expire after the registry rotates twice, like inventory statuses.
335 pub fn register_served(&mut self, hash: InventoryHash, peer: PeerSocketAddr) {
336 Self::register_peer(&mut self.served_current, hash, peer);
337 }
338
339 /// Returns how many repeat requests for `hash` were recently sent to the peers that
340 /// advertised it, and to the peers that didn't.
341 ///
342 /// # Security
343 ///
344 /// The peers that advertised `hash` and the peers that didn't take turns to get the repeat
345 /// requests for it, and these counts decide whose turn it is. A peer that forges blocks can
346 /// advertise them from several addresses, and it can also connect from addresses that don't
347 /// advertise them and don't answer. So if either group got every repeat request, that group
348 /// could keep them all from the honest peers.
349 ///
350 /// Requests are counted when they are sent, not when they are answered. So several repeat
351 /// requests in flight at the same time take turns too, and a peer can't change the turn by
352 /// delaying its answer.
353 pub fn repeat_requests(&self, hash: InventoryHash) -> RepeatRequests {
354 let current = self.repeat_current.get(&hash).copied().unwrap_or_default();
355 let prev = self.repeat_prev.get(&hash).copied().unwrap_or_default();
356
357 RepeatRequests {
358 advertisers: current.advertisers.saturating_add(prev.advertisers),
359 other_peers: current.other_peers.saturating_add(prev.other_peers),
360 }
361 }
362
363 /// Records that a repeat request for `hash` was sent to a peer that advertised it, if
364 /// `advertised` is true, or to a peer that didn't.
365 ///
366 /// These records expire after the registry rotates twice, like inventory statuses.
367 pub fn register_repeat_request(&mut self, hash: InventoryHash, advertised: bool) {
368 if let Some(index) = self.repeat_current.get_index_of(&hash) {
369 self.repeat_current
370 .move_index(index, self.repeat_current.len() - 1);
371 }
372 let requests = self.repeat_current.entry(hash).or_default();
373 if advertised {
374 requests.advertisers = requests.advertisers.saturating_add(1);
375 } else {
376 requests.other_peers = requests.other_peers.saturating_add(1);
377 }
378
379 // # Security
380 //
381 // Limit the number of stored hashes, removing the oldest entries, like `register_peer()`.
382 if self.repeat_current.len() > MAX_INV_PER_MAP {
383 // Performance: `MAX_INV_PER_MAP` is small, so O(n) performance is acceptable.
384 self.repeat_current.shift_remove_index(0);
385 }
386 }
387
388 /// Adds `peer` to the peers for `hash` in `map`, as the newest entry.
389 fn register_peer(
390 map: &mut IndexMap<InventoryHash, IndexSet<PeerSocketAddr>>,
391 hash: InventoryHash,
392 peer: PeerSocketAddr,
393 ) {
394 if let Some(index) = map.get_index_of(&hash) {
395 map.move_index(index, map.len() - 1);
396 }
397 let peers = map.entry(hash).or_default();
398 let (index, _) = peers.insert_full(peer);
399 peers.move_index(index, peers.len() - 1);
400
401 // # Security
402 //
403 // Limit the number of stored peers and hashes, removing the oldest entries, like
404 // `register()`.
405 if peers.len() > MAX_PEERS_PER_INV {
406 // Performance: `MAX_PEERS_PER_INV` is small, so O(n) performance is acceptable.
407 peers.shift_remove_index(0);
408 }
409 if map.len() > MAX_INV_PER_MAP {
410 // Performance: `MAX_INV_PER_MAP` is small, so O(n) performance is acceptable.
411 map.shift_remove_index(0);
412 }
413 }
414
415 /// Clears failures from previous connections that used `peer`'s transient address.
416 pub fn clear_peer_failures(&mut self, peer: PeerSocketAddr) {
417 for failures in [&mut self.failed_current, &mut self.failed_prev] {
418 failures.retain(|_, peers| {
419 peers.shift_remove(&peer);
420 !peers.is_empty()
421 });
422 }
423 }
424
425 /// Returns an iterator over peer inventory statuses for `hash`.
426 ///
427 /// Prefers current statuses to previously rotated statuses for the same peer.
428 pub fn status_peers(
429 &self,
430 hash: InventoryHash,
431 ) -> impl Iterator<Item = InventoryStatus<&PeerSocketAddr>> {
432 let prev = self.prev.get(&hash);
433 let current = self.current.get(&hash);
434
435 // # Security
436 //
437 // Prefer `current` statuses for the same peer over previously rotated statuses.
438 // This makes sure Zebra is using the most up-to-date network information.
439 let prev = prev
440 .into_iter()
441 .flatten()
442 .filter(move |(addr, _status)| !self.has_current_status(hash, **addr));
443 let current = current.into_iter().flatten();
444
445 current
446 .chain(prev)
447 .map(|(addr, status)| status.map(|()| addr))
448 }
449
450 /// Returns true if there is a current status entry for `hash` and `addr`.
451 pub fn has_current_status(&self, hash: InventoryHash, addr: PeerSocketAddr) -> bool {
452 self.current
453 .get(&hash)
454 .and_then(|current| current.get(&addr))
455 .is_some()
456 }
457
458 /// Returns an iterator over peer inventory status hashes.
459 ///
460 /// Yields current statuses first, then previously rotated statuses.
461 /// This can include multiple statuses for the same hash.
462 #[allow(dead_code)]
463 pub fn status_hashes(
464 &self,
465 ) -> impl Iterator<Item = (&InventoryHash, &IndexMap<PeerSocketAddr, InventoryMarker>)> {
466 self.current.iter().chain(self.prev.iter())
467 }
468
469 /// Returns a future that waits for new registry updates.
470 #[allow(dead_code)]
471 pub fn update(&mut self) -> Update<'_> {
472 Update::new(self)
473 }
474
475 /// Drive periodic inventory tasks.
476 ///
477 /// Rotates the inventory HashMaps on every timer tick.
478 /// Drains the inv_stream channel and registers all advertised inventory.
479 ///
480 /// Returns an error if the inventory channel is closed.
481 ///
482 /// Otherwise, returns `Ok` if it performed at least one update or rotation, or `Poll::Pending`
483 /// if there was no inventory change. Always registers a wakeup for the next inventory update
484 /// or rotation, even when it returns `Ok`.
485 pub fn poll_inventory(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), BoxError>> {
486 let mut result = Poll::Pending;
487
488 // # Correctness
489 //
490 // Registers the current task for wakeup when the timer next becomes ready.
491 // (But doesn't return, because we also want to register the task for wakeup when more
492 // inventory arrives.)
493 //
494 // # Security
495 //
496 // Rotate before registering new inventory. Missed ticks restart the interval, so
497 // repeated polls cannot immediately age out new advertisements or failures.
498 if Pin::new(&mut self.interval).poll_next(cx).is_ready() {
499 self.rotate();
500 result = Poll::Ready(Ok(()));
501 }
502
503 // This module uses a broadcast channel instead of an mpsc channel, even
504 // though there's a single consumer of inventory advertisements, because
505 // the broadcast channel has ring-buffer behavior: when the channel is
506 // full, sending a new message displaces the oldest message in the
507 // channel.
508 //
509 // This is the behavior we want for inventory advertisements, because we
510 // want to have a bounded buffer of unprocessed advertisements, and we
511 // want to prioritize new inventory (which is likely only at a specific
512 // peer) over old inventory (which is likely more widely distributed).
513 //
514 // The broadcast channel reports dropped messages by returning
515 // `RecvError::Lagged`. It's crucial that we handle that error here
516 // rather than propagating it through the peer set's Service::poll_ready
517 // implementation, where reporting a failure means reporting a permanent
518 // failure of the peer set.
519
520 // Returns Pending if all messages are processed, but the channel could get more.
521 loop {
522 let channel_result = self.inv_stream.next().poll_unpin(cx);
523
524 match channel_result {
525 Poll::Ready(Some(Ok(change))) => {
526 self.register(change);
527 result = Poll::Ready(Ok(()));
528 }
529 Poll::Ready(Some(Err(BroadcastStreamRecvError::Lagged(count)))) => {
530 // This isn't a fatal inventory error, it's expected behaviour when Zebra is
531 // under load from peers.
532 metrics::counter!("pool.inventory.dropped").increment(1);
533 metrics::counter!("pool.inventory.dropped.messages").increment(count);
534
535 // If this message happens a lot, we should improve inventory registry
536 // performance, or poll the registry or peer set in a separate task.
537 info!(count, "dropped lagged inventory advertisements");
538 }
539 Poll::Ready(None) => {
540 // If the channel is empty and returns None, all senders, including the one in
541 // the handshaker, have been dropped, which really is a permanent failure.
542 result = Poll::Ready(Err(broadcast::error::RecvError::Closed.into()));
543 }
544 Poll::Pending => {
545 break;
546 }
547 }
548 }
549
550 result
551 }
552
553 /// Record the given inventory `change` for the peer `addr`.
554 ///
555 /// `Missing` markers are not updated until the registry rotates, for security reasons.
556 fn register(&mut self, change: InventoryChange) {
557 let new_status = change.marker();
558 let (invs, addr) = change.to_inner();
559
560 for inv in invs {
561 use InventoryHash::*;
562 assert!(
563 matches!(inv, Block(_) | Tx(_) | Wtx(_)),
564 "unexpected inventory type: {inv:?} from peer: {addr:?}",
565 );
566
567 let hash_peers = self.current.entry(inv).or_default();
568
569 // # Security
570 //
571 // Prefer `missing` over `advertised`, so malicious peers can't reset their own entries,
572 // and funnel multiple failing requests to themselves.
573 if let Some(old_status) = hash_peers.get(&addr) {
574 if old_status.is_missing() && new_status.is_available() {
575 debug!(?new_status, ?old_status, ?addr, ?inv, "skipping new status");
576 continue;
577 }
578
579 debug!(
580 ?new_status,
581 ?old_status,
582 ?addr,
583 ?inv,
584 "keeping both new and old status"
585 );
586 }
587
588 let replaced_status = hash_peers.insert(addr, new_status);
589
590 debug!(
591 ?new_status,
592 ?replaced_status,
593 ?addr,
594 ?inv,
595 "inserted new status"
596 );
597
598 // # Security
599 //
600 // Limit the number of stored peers per hash, removing the oldest entries,
601 // because newer entries are likely to be more relevant.
602 //
603 // TODO: do random or weighted random eviction instead?
604 if hash_peers.len() > MAX_PEERS_PER_INV {
605 // Performance: `MAX_PEERS_PER_INV` is small, so O(n) performance is acceptable.
606 hash_peers.shift_remove_index(0);
607 }
608
609 // # Security
610 //
611 // Limit the number of stored inventory hashes, removing the oldest entries,
612 // because newer entries are likely to be more relevant.
613 //
614 // TODO: do random or weighted random eviction instead?
615 if self.current.len() > MAX_INV_PER_MAP {
616 // Performance: `MAX_INV_PER_MAP` is small, so O(n) performance is acceptable.
617 self.current.shift_remove_index(0);
618 }
619 }
620 }
621
622 /// Replace the prev HashMap with current's and replace current with an empty
623 /// HashMap
624 fn rotate(&mut self) {
625 self.prev = std::mem::take(&mut self.current);
626 self.failed_prev = std::mem::take(&mut self.failed_current);
627 self.served_prev = std::mem::take(&mut self.served_current);
628 self.repeat_prev = std::mem::take(&mut self.repeat_current);
629 }
630}