Skip to main content

consensus_core/
commit_test_fixture.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared test fixture for commit-related tests.
5//! Used by both commit_finalizer.rs tests and randomized_tests.rs.
6
7use std::collections::{BTreeMap, BTreeSet, VecDeque};
8use std::ops::Bound::Included;
9use std::sync::Arc;
10
11use consensus_config::{AuthorityIndex, Stake};
12use consensus_types::block::{BlockDigest, BlockRef};
13use consensus_types::block::{Round, TransactionIndex};
14use mysten_metrics::monitored_mpsc::unbounded_channel;
15use parking_lot::RwLock;
16use rand::prelude::SliceRandom;
17use rand::{Rng, rngs::StdRng};
18
19use crate::Transaction;
20use crate::block::{BlockTransactionVotes, TestBlock, genesis_blocks};
21use crate::{
22    block::{BlockAPI, VerifiedBlock},
23    block_manager::BlockManager,
24    block_verifier::NoopBlockVerifier,
25    commit::{CommittedSubDag, DecidedLeader},
26    commit_finalizer::CommitFinalizer,
27    context::Context,
28    dag_state::DagState,
29    leader_schedule::{LeaderSchedule, LeaderSwapTable},
30    linearizer::Linearizer,
31    storage::mem_store::MemStore,
32    transaction_vote_tracker::TransactionVoteTracker,
33    universal_committer::{
34        UniversalCommitter, universal_committer_builder::UniversalCommitterBuilder,
35    },
36};
37
38/// A test fixture that provides all the components needed for testing commit processing,
39/// similar to the actual logic in Core::try_commit() and CommitFinalizer::run().
40pub struct CommitTestFixture {
41    pub context: Arc<Context>,
42    pub linearizer: Linearizer,
43    pub transaction_vote_tracker: TransactionVoteTracker,
44    pub commit_finalizer: CommitFinalizer,
45
46    dag_state: Arc<RwLock<DagState>>,
47    block_manager: BlockManager,
48    committer: UniversalCommitter,
49}
50
51impl CommitTestFixture {
52    /// Creates a new CommitTestFixture from a context.
53    pub fn new(context: Arc<Context>) -> Self {
54        let leader_schedule = Arc::new(LeaderSchedule::new(
55            context.clone(),
56            LeaderSwapTable::default(),
57        ));
58        let dag_state = Arc::new(RwLock::new(DagState::new(
59            context.clone(),
60            Arc::new(MemStore::new()),
61        )));
62
63        // Create committer with pipelining and only 1 leader per leader round
64        let committer =
65            UniversalCommitterBuilder::new(context.clone(), leader_schedule, dag_state.clone())
66                .with_pipeline(true)
67                .build();
68
69        let block_manager = BlockManager::new(context.clone(), dag_state.clone());
70
71        let linearizer = Linearizer::new(context.clone(), dag_state.clone());
72        let transaction_vote_tracker = TransactionVoteTracker::new(
73            context.clone(),
74            Arc::new(NoopBlockVerifier {}),
75            dag_state.clone(),
76        );
77        let (commit_sender, _commit_receiver) = unbounded_channel("consensus_commit_output");
78        let commit_finalizer = CommitFinalizer::new(
79            context.clone(),
80            dag_state.clone(),
81            transaction_vote_tracker.clone(),
82            commit_sender,
83        );
84
85        Self {
86            context,
87            linearizer,
88            transaction_vote_tracker,
89            commit_finalizer,
90            dag_state,
91            block_manager,
92            committer,
93        }
94    }
95
96    /// Creates a new CommitTestFixture with more options.
97    pub fn with_options(
98        num_authorities: usize,
99        authority_index: u32,
100        gc_depth: Option<u32>,
101    ) -> Self {
102        Self::new(Self::context_with_options(
103            num_authorities,
104            authority_index,
105            gc_depth,
106        ))
107    }
108
109    pub fn context_with_options(
110        num_authorities: usize,
111        authority_index: u32,
112        gc_depth: Option<u32>,
113    ) -> Arc<Context> {
114        let (mut context, _keys) = Context::new_for_test(num_authorities);
115        if let Some(gc_depth) = gc_depth {
116            context.protocol_config.set_gc_depth_for_testing(gc_depth);
117        }
118        // Skipping equivocation validation is necessary when testing with equivocators.
119        // Also it is ok when only testing the commit code path.
120        context.parameters.internal.skip_equivocation_validation = true;
121        Arc::new(context.with_authority_index(AuthorityIndex::new_for_test(authority_index)))
122    }
123
124    // Adds the blocks to the transaction vote tracker and then tries to accept them via BlockManager.
125    /// This registers the blocks for reject vote tracking (with no reject votes).
126    pub fn try_accept_blocks(&mut self, blocks: Vec<VerifiedBlock>) {
127        self.transaction_vote_tracker
128            .add_voted_blocks(blocks.iter().map(|b| (b.clone(), vec![])).collect());
129        self.block_manager.try_accept_blocks(blocks);
130    }
131
132    /// Adds blocks to the transaction vote tracker and dag state.
133    /// This registers the blocks for reject vote tracking (with no reject votes).
134    pub fn add_blocks(&self, blocks: Vec<VerifiedBlock>) {
135        let blocks_and_votes = blocks.iter().map(|b| (b.clone(), vec![])).collect();
136        self.transaction_vote_tracker
137            .add_voted_blocks(blocks_and_votes);
138        self.dag_state.write().accept_blocks(blocks);
139    }
140
141    pub fn add_blocks_with_own_votes(
142        &self,
143        blocks_and_votes: Vec<(VerifiedBlock, Vec<TransactionIndex>)>,
144    ) {
145        let blocks = blocks_and_votes.iter().map(|(b, _)| b.clone()).collect();
146        self.transaction_vote_tracker
147            .add_voted_blocks(blocks_and_votes);
148        self.dag_state.write().accept_blocks(blocks);
149    }
150
151    /// Checks if the block manager has no suspended blocks.
152    #[cfg(test)]
153    pub(crate) fn has_no_suspended_blocks(&self) -> bool {
154        self.block_manager.is_empty()
155    }
156
157    /// Tries to decide leaders, process and finalize commits, returning finalized commits
158    /// and the updated last_decided slot.
159    pub async fn try_commit(
160        &mut self,
161        last_decided: crate::block::Slot,
162    ) -> (Vec<CommittedSubDag>, crate::block::Slot) {
163        let (finalized, last_decided, _) = self.try_commit_with_skip_count(last_decided).await;
164        (finalized, last_decided)
165    }
166
167    /// Tries to decide leaders and returns the number of skipped leaders alongside
168    /// finalized commits. This is useful for asserting Byzantine test scenarios.
169    pub(crate) async fn try_commit_with_skip_count(
170        &mut self,
171        last_decided: crate::block::Slot,
172    ) -> (Vec<CommittedSubDag>, crate::block::Slot, usize) {
173        let sequence = self.committer.try_decide(last_decided);
174        let new_last_decided = sequence
175            .last()
176            .map(|leader| leader.slot())
177            .unwrap_or(last_decided);
178        let skipped = sequence
179            .iter()
180            .filter(|leader| matches!(leader, DecidedLeader::Skip(_)))
181            .count();
182        let finalized = self.process_commits(sequence).await;
183        (finalized, new_last_decided, skipped)
184    }
185
186    /// Process decided leaders through linearizer and commit finalizer,
187    /// similar to Core::try_commit() and CommitFinalizer::run().
188    ///
189    /// This extracts leader blocks from DecidedLeader::Commit, creates CommittedSubDags
190    /// via the linearizer, and processes them through the commit finalizer.
191    pub(crate) async fn process_commits(
192        &mut self,
193        sequence: Vec<DecidedLeader>,
194    ) -> Vec<CommittedSubDag> {
195        // Extract leader blocks from DecidedLeader::Commit (skip Skip decisions)
196        let leaders: Vec<VerifiedBlock> = sequence
197            .into_iter()
198            .filter_map(|d| match d {
199                DecidedLeader::Commit(block, _) => Some(block),
200                DecidedLeader::Skip(_) => None,
201            })
202            .collect();
203
204        if leaders.is_empty() {
205            return vec![];
206        }
207
208        // Use linearizer to create CommittedSubDag
209        let committed_sub_dags = self.linearizer.handle_commit(leaders);
210
211        // After handle_commit(), the GC round is updated. We need to unsuspend any blocks that were
212        // suspended because of missing ancestors that are now GC'ed.
213        self.block_manager
214            .try_unsuspend_blocks_for_latest_gc_round();
215
216        // Process through commit finalizer
217        let mut finalized_commits = vec![];
218        for mut subdag in committed_sub_dags {
219            subdag.decided_with_local_blocks = true;
220            let finalized = self.commit_finalizer.process_commit(subdag).await.unwrap();
221            finalized_commits.extend(finalized);
222        }
223
224        finalized_commits
225    }
226}
227
228/// Compare commit sequences across all runs, asserting they are identical.
229/// Returns the shortest commit sequence for additional assertions if needed.
230pub fn assert_commit_sequences_match(
231    commit_sequences: Vec<Vec<CommittedSubDag>>,
232) -> Vec<CommittedSubDag> {
233    let (shortest_idx, shortest_sequence) = commit_sequences
234        .iter()
235        .enumerate()
236        .min_by_key(|(_, seq)| seq.len())
237        .expect("commit_sequences should not be empty");
238
239    for (run, commit_sequence) in commit_sequences.iter().enumerate() {
240        // Since INDIRECT_REJECT_DEPTH is 3, the maximum number of commits buffered in CommitFinalizer is 3.
241        // And because of the direct finalization optimization, it might happen the last 3 commits are pending in
242        // one run but all finalized in another.
243        assert!(
244            commit_sequence.len() <= shortest_sequence.len() + 3,
245            "Commit sequence at run {run} is more than 3 commits longer than shortest (run {shortest_idx}): {} vs {}",
246            commit_sequence.len(),
247            shortest_sequence.len()
248        );
249
250        #[allow(clippy::disallowed_methods)]
251        // Intentional zip: comparing prefix between sequences of varying lengths
252        for (commit_index, (c1, c2)) in commit_sequence
253            .iter()
254            .zip(shortest_sequence.iter())
255            .enumerate()
256        {
257            assert_eq!(
258                c1.leader, c2.leader,
259                "Leader mismatch at run {run} commit {commit_index}"
260            );
261            assert_eq!(
262                c1.commit_ref, c2.commit_ref,
263                "Commit sequence mismatch at run {run} commit {commit_index}"
264            );
265            assert_eq!(
266                c1.rejected_transactions_by_block, c2.rejected_transactions_by_block,
267                "Rejected transactions mismatch at run {run} commit {commit_index}"
268            );
269        }
270    }
271
272    let mut total_transactions = 0;
273    let mut rejected_transactions = 0;
274    let mut reject_votes = 0;
275    let mut blocks = 4;
276    for commit in shortest_sequence.iter() {
277        total_transactions += commit
278            .blocks
279            .iter()
280            .map(|block| block.transactions().len())
281            .sum::<usize>();
282        rejected_transactions += commit
283            .rejected_transactions_by_block
284            .values()
285            .map(|transactions| transactions.len())
286            .sum::<usize>();
287        reject_votes += commit
288            .blocks
289            .iter()
290            .map(|block| block.transaction_votes().len())
291            .sum::<usize>();
292        blocks += commit.blocks.len();
293    }
294
295    tracing::info!(
296        "Finished comparing commit sequences. Commits: {}, Blocks: {}, Total transactions: {}, Rejected transactions: {}, Reject votes: {}",
297        shortest_sequence.len(),
298        blocks,
299        total_transactions,
300        rejected_transactions,
301        reject_votes
302    );
303
304    shortest_sequence.clone()
305}
306
307// ---- RandomDag, RandomDagConfig and RandomDagIterator ----
308
309/// Configuration for generating a randomized DAG.
310pub struct RandomDagConfig {
311    // Number of distinct authorities creating blocks.
312    pub num_authorities: usize,
313    // Number of rounds to generate.
314    pub num_rounds: Round,
315    // Number of transactions per block.
316    pub num_transactions: u32,
317    // Percentage chance of transactions to randomly reject.
318    pub reject_percentage: u8,
319    // Each element specifies the authority index, and the number of equivocators
320    // that are acting under this authority.
321    pub equivocators: Vec<(AuthorityIndex, u16)>,
322}
323
324/// A randomly generated DAG for testing commit patterns with reject votes.
325pub struct RandomDag {
326    context: Arc<Context>,
327    pub blocks: Vec<VerifiedBlock>,
328    num_rounds: Round,
329}
330
331impl RandomDag {
332    /// Creates a new RandomDag with generated blocks containing transactions and reject votes.
333    pub fn new(context: Arc<Context>, rng: &mut StdRng, config: RandomDagConfig) -> Self {
334        let RandomDagConfig {
335            num_authorities: _,
336            num_rounds,
337            num_transactions,
338            reject_percentage,
339            equivocators,
340        } = config;
341
342        let committee = &context.committee;
343        let quorum_threshold = committee.quorum_threshold();
344        let total_stake = committee.total_stake();
345
346        // Create instance ID for each authority and equivocators.
347        let mut instances: Vec<InstanceID> = committee.authorities().map(|(a, _)| (a, 0)).collect();
348        for (authority, num_equivocators) in equivocators {
349            for i in 1..=num_equivocators {
350                instances.push((authority, i));
351            }
352        }
353
354        let genesis_blocks = genesis_blocks(&context)
355            .into_iter()
356            .map(|b| (b.author(), b))
357            .collect::<BTreeMap<AuthorityIndex, VerifiedBlock>>();
358        let last_round_blocks: Vec<VerifiedBlock> = genesis_blocks.values().cloned().collect();
359
360        // Store all blocks for lookup and range search.
361        let mut all_blocks: BTreeMap<BlockRef, VerifiedBlock> = BTreeMap::new();
362        // Initialize with genesis blocks.
363        for block in &last_round_blocks {
364            all_blocks.insert(block.reference(), block.clone());
365        }
366
367        // Track the latest block per instance. Equivocators start from the same genesis blocks per authority.
368        let mut latest_blocks = instances
369            .iter()
370            .map(|&(a, i)| {
371                let b = genesis_blocks.get(&a).unwrap();
372                ((a, i), b.clone())
373            })
374            .collect::<BTreeMap<InstanceID, VerifiedBlock>>();
375
376        // Track included blocks per instance (simulates link_causal_history).
377        let mut included_refs = BTreeMap::<InstanceID, BTreeSet<BlockRef>>::new();
378
379        for r in 1..=num_rounds {
380            // Select random quorum-or-more stake to produce blocks this round.
381            let target_stake = rng.gen_range(quorum_threshold..=total_stake);
382
383            // Select random instances to produce blocks this round.
384            // Equivocations are allowed when multiple instances from the same authority propose at
385            // the same slot.
386            let mut proposers = instances.clone();
387            proposers.shuffle(rng);
388            let mut selected_stake = 0;
389            // Ensure stake across equivocations are counted only once.
390            let mut selected_authorities = vec![false; committee.size()];
391            let selected_proposers: Vec<_> = proposers
392                .into_iter()
393                .take_while(|instance| {
394                    if selected_stake >= target_stake {
395                        return false;
396                    }
397                    if !selected_authorities[instance.0.value()] {
398                        selected_authorities[instance.0.value()] = true;
399                        selected_stake += committee.stake(instance.0);
400                    }
401                    true
402                })
403                .collect();
404
405            let mut current_round_blocks = Vec::new();
406            for instance_id in selected_proposers {
407                let block = build_block_for_instance(
408                    &context,
409                    &instances,
410                    rng,
411                    r,
412                    instance_id,
413                    num_transactions,
414                    reject_percentage,
415                    &all_blocks,
416                    &mut latest_blocks,
417                    &mut included_refs,
418                );
419                current_round_blocks.push((instance_id, block));
420            }
421
422            // Update state with current round blocks.
423            for (instance_id, block) in current_round_blocks {
424                all_blocks.insert(block.reference(), block.clone());
425                latest_blocks.insert(instance_id, block);
426            }
427        }
428
429        RandomDag {
430            context,
431            blocks: all_blocks.values().cloned().collect(),
432            num_rounds,
433        }
434    }
435
436    /// Creates a RandomDag from existing blocks.
437    pub fn from_blocks(context: Arc<Context>, blocks: Vec<VerifiedBlock>) -> Self {
438        let num_rounds = blocks.iter().map(|b| b.round()).max().unwrap_or(0);
439        RandomDag {
440            context,
441            blocks,
442            num_rounds,
443        }
444    }
445
446    /// Creates an iterator yielding blocks in constrained random order.
447    pub fn random_iter<'a>(
448        &'a self,
449        rng: &'a mut StdRng,
450        max_step: Round,
451    ) -> RandomDagIterator<'a> {
452        RandomDagIterator::new(self, rng, max_step)
453    }
454}
455
456// Identifies a consensus instance, by its authority index and another index to differentiate between equivocators.
457type InstanceID = (AuthorityIndex, u16);
458
459/// Builds a single block for the given consensus instance at the specified round.
460fn build_block_for_instance(
461    context: &Arc<Context>,
462    instances: &[InstanceID],
463    rng: &mut StdRng,
464    round: Round,
465    own_instance: InstanceID,
466    num_transactions: u32,
467    reject_percentage: u8,
468    all_blocks: &BTreeMap<BlockRef, VerifiedBlock>,
469    latest_blocks: &mut BTreeMap<InstanceID, VerifiedBlock>,
470    included_refs: &mut BTreeMap<InstanceID, BTreeSet<BlockRef>>,
471) -> VerifiedBlock {
472    let committee = &context.committee;
473    let quorum_threshold = committee.quorum_threshold();
474    let own_authority = own_instance.0;
475
476    // Select blocks from the previous round until quorum stake is reached.
477    let prev_round = round - 1;
478    let mut prev_round_blocks: Vec<_> = all_blocks
479        .range((
480            Included(BlockRef::new(
481                prev_round,
482                AuthorityIndex::MIN,
483                BlockDigest::MIN,
484            )),
485            Included(BlockRef::new(
486                prev_round,
487                AuthorityIndex::MAX,
488                BlockDigest::MAX,
489            )),
490        ))
491        .map(|(_, b)| b)
492        .cloned()
493        .collect();
494    prev_round_blocks.shuffle(rng);
495    let mut parent_stake: Stake = 0;
496    // Ensure only one block gets selected per authority, regardless of equivocations.
497    let mut selected_authorities = vec![false; committee.size()];
498    let quorum_parents: Vec<_> = prev_round_blocks
499        .into_iter()
500        .filter_map(|b| {
501            if parent_stake >= quorum_threshold {
502                return None;
503            }
504            if selected_authorities[b.author().value()] {
505                return None;
506            }
507            selected_authorities[b.author().value()] = true;
508            parent_stake += committee.stake(b.author());
509            Some(b)
510        })
511        .collect();
512
513    // Find so far unselected instances.
514    let mut unselected_instances: Vec<_> = instances
515        .iter()
516        .filter(|(authority, _)| !selected_authorities[authority.value()])
517        .cloned()
518        .collect();
519
520    // Randomly select extra blocks to link to among ancestors.
521    unselected_instances.shuffle(rng);
522    // Use min of two uniform samples to bias toward fewer additional ancestors
523    // while maintaining non-zero probability for all counts.
524    let extra_count = rng
525        .gen_range(0..=unselected_instances.len())
526        .min(rng.gen_range(0..=unselected_instances.len()));
527    let additional_ancestor_blocks: Vec<_> = unselected_instances[0..extra_count]
528        .iter()
529        .filter_map(|&(authority, instance)| {
530            if selected_authorities[authority.value()] {
531                return None;
532            }
533            let block = latest_blocks.get(&(authority, instance))?;
534            assert!(
535                block.round() < round,
536                "latest_blocks should only contain blocks from previous rounds"
537            );
538            selected_authorities[authority.value()] = true;
539            Some(block.clone())
540        })
541        .collect();
542
543    // Combine ancestors: quorum parents + extra ancestors from unselected authorities + own latest block if necessary.
544    let mut ancestor_blocks = quorum_parents;
545    ancestor_blocks.extend(additional_ancestor_blocks);
546    if !ancestor_blocks.iter().any(|b| b.author() == own_authority) {
547        ancestor_blocks.push(latest_blocks[&own_instance].clone());
548    }
549    let ancestors: Vec<_> = ancestor_blocks.iter().map(|b| b.reference()).collect();
550
551    // Find newly connected blocks via BFS (similar to link_causal_history).
552    let mut newly_connected = Vec::new();
553    let mut queue = VecDeque::from_iter(ancestors.iter().copied());
554    while let Some(block_ref) = queue.pop_front() {
555        if block_ref.round == 0 {
556            continue; // Skip genesis blocks.
557        }
558        if included_refs
559            .entry(own_instance)
560            .or_default()
561            .contains(&block_ref)
562        {
563            continue; // Already included.
564        }
565        included_refs
566            .entry(own_instance)
567            .or_default()
568            .insert(block_ref);
569        newly_connected.push(block_ref);
570        // Traverse ancestors.
571        if let Some(block) = all_blocks.get(&block_ref) {
572            queue.extend(block.ancestors().iter().cloned());
573        }
574    }
575
576    // Generate random reject votes for newly connected blocks only.
577    let votes: Vec<_> = newly_connected
578        .iter()
579        .filter(|_| reject_percentage > 0)
580        .filter_map(|&block_ref| {
581            let rejects: Vec<_> = (0..num_transactions)
582                .filter(|_| rng.gen_range(0..100) < reject_percentage)
583                .map(|idx| idx as TransactionIndex)
584                .collect();
585            (!rejects.is_empty()).then_some(BlockTransactionVotes { block_ref, rejects })
586        })
587        .collect();
588
589    let transactions: Vec<_> = (0..num_transactions)
590        .map(|_| Transaction::new(vec![1_u8; 16]))
591        .collect();
592
593    let timestamp = (round as u64) * 1000 + (own_authority.value() as u64) + rng.gen_range(0..100);
594
595    VerifiedBlock::new_for_test(
596        TestBlock::new(round, own_authority.value() as u32)
597            .set_transactions(transactions)
598            .set_transaction_votes(votes)
599            .set_ancestors(ancestors)
600            .set_timestamp_ms(timestamp)
601            .build(),
602    )
603}
604
605/// Per-round state for iteration.
606#[derive(Clone, Default)]
607struct RoundState {
608    // Total stake of visited blocks in this round.
609    visited_stake: Stake,
610    // Authors with a block visited in this round. Equivocations only count once
611    // toward the quorum stake that controls the delivery window.
612    visited_authors: BTreeSet<AuthorityIndex>,
613    // Indices of unvisited blocks in this round.
614    unvisited: Vec<usize>,
615}
616
617/// Iterator yielding blocks in constrained random order. Selects from rounds
618/// `completed_round + 1` to `quorum_round + max_step`, simulating arrival with delays.
619pub struct RandomDagIterator<'a> {
620    dag: &'a RandomDag,
621    rng: &'a mut StdRng,
622    quorum_threshold: Stake,
623    max_step: Round,
624    // Highest round where all prior rounds have quorum stake visited.
625    quorum_round: Round,
626    // Highest round where all prior rounds have all blocks visited.
627    completed_round: Round,
628    // State of each round.
629    round_states: Vec<RoundState>,
630    // Number of blocks remaining to visit.
631    num_remaining: usize,
632}
633
634impl<'a> RandomDagIterator<'a> {
635    fn new(dag: &'a RandomDag, rng: &'a mut StdRng, max_step: Round) -> Self {
636        let num_rounds = dag.num_rounds as usize;
637        let committee = &dag.context.committee;
638        let quorum_threshold = committee.quorum_threshold();
639
640        let mut round_states: Vec<RoundState> = vec![RoundState::default(); num_rounds + 1];
641
642        for (idx, block) in dag.blocks.iter().enumerate() {
643            let round = block.round() as usize;
644            round_states[round].unvisited.push(idx);
645        }
646
647        let num_remaining = dag.blocks.len();
648
649        Self {
650            dag,
651            rng,
652            max_step,
653            quorum_round: 0,
654            completed_round: 0,
655            quorum_threshold,
656            round_states,
657            num_remaining,
658        }
659    }
660}
661
662impl Iterator for RandomDagIterator<'_> {
663    type Item = VerifiedBlock;
664
665    /// The high level algorithm is to randomly select a block from unvisited blocks,
666    /// up to quorum_round + max_step round.
667    /// It is possible a sequence of blocks are suspended until their common ancestors
668    /// gets selected and accepted.
669    ///
670    /// An alternative approach is to keep track of selected blocks, and only select blocks without
671    /// missing dependencies. Even though block selection order is also randomized, this approach
672    /// seems to have less test coverage, and was unable to expose errors when incorrect logic was
673    /// introduced to CommitFinalizer.
674    fn next(&mut self) -> Option<Self::Item> {
675        if self.num_remaining == 0 {
676            return None;
677        }
678
679        // Eligible rounds: from first unvisited to quorum_round + max_step.
680        let min_round = self.completed_round as usize + 1;
681        let max_round =
682            ((self.quorum_round + self.max_step) as usize).min(self.round_states.len() - 1);
683        let eligible_rounds = min_round..=max_round;
684
685        let total_candidates: usize = eligible_rounds
686            .clone()
687            .map(|r| self.round_states[r].unvisited.len())
688            .sum();
689
690        if total_candidates == 0 {
691            return None;
692        }
693
694        // Select random candidate by index across eligible rounds.
695        let mut selection = self.rng.gen_range(0..total_candidates);
696        let mut selected_round = 0;
697        let mut selected_pos = 0;
698
699        for r in eligible_rounds {
700            let count = self.round_states[r].unvisited.len();
701            if selection < count {
702                selected_round = r;
703                selected_pos = selection;
704                break;
705            }
706            selection -= count;
707        }
708
709        // Get block index and remove from unvisited.
710        let block_idx = self.round_states[selected_round]
711            .unvisited
712            .swap_remove(selected_pos);
713        let block = self.dag.blocks[block_idx].clone();
714
715        // Update visited stake for this round.
716        let round_state = &mut self.round_states[selected_round];
717        if round_state.visited_authors.insert(block.author()) {
718            round_state.visited_stake += self.dag.context.committee.stake(block.author());
719        }
720        self.num_remaining -= 1;
721
722        // Advance completed_round while next round has all blocks visited.
723        while self
724            .round_states
725            .get(self.completed_round as usize + 1)
726            .is_some_and(|s| s.unvisited.is_empty())
727        {
728            self.completed_round += 1;
729        }
730
731        // Advance quorum_round while next round has quorum stake visited.
732        while self
733            .round_states
734            .get(self.quorum_round as usize + 1)
735            .is_some_and(|s| s.visited_stake >= self.quorum_threshold)
736        {
737            self.quorum_round += 1;
738        }
739
740        Some(block)
741    }
742}