Skip to main content

consensus_core/
test_dag_builder.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::BTreeMap,
6    ops::{Bound::Included, RangeInclusive},
7    sync::Arc,
8};
9
10use consensus_config::AuthorityIndex;
11use consensus_types::block::{BlockDigest, BlockRef, BlockTimestampMs, Round, TransactionIndex};
12use parking_lot::RwLock;
13use rand::{Rng, SeedableRng, rngs::StdRng, seq::SliceRandom, thread_rng};
14
15#[cfg(test)]
16use crate::commit::CertifiedCommit;
17use crate::{
18    CommitRef, CommittedSubDag, Transaction,
19    block::{BlockAPI, BlockTransactionVotes, Slot, TestBlock, VerifiedBlock, genesis_blocks},
20    commit::{CommitDigest, TrustedCommit},
21    context::Context,
22    dag_state::DagState,
23    leader_schedule::{LeaderSchedule, LeaderSwapTable},
24    linearizer::{BlockStoreAPI, Linearizer},
25};
26
27/// DagBuilder API
28///
29/// Usage:
30///
31/// DAG Building
32/// ```ignore
33/// let context = Arc::new(Context::new_for_test(4).0);
34/// let mut dag_builder = DagBuilder::new(context);
35/// dag_builder.layer(1).build(); // Round 1 is fully connected with parents by default.
36/// dag_builder.layers(2..=10).build(); // Rounds 2 ~ 10 are fully connected with parents by default.
37/// dag_builder.layer(11).min_parent_links().build(); // Round 11 is minimally and randomly connected with parents, without weak links.
38/// dag_builder.layer(12).no_leader_block(0).build(); // Round 12 misses leader block. Other blocks are fully connected with parents.
39/// dag_builder.layer(13).no_leader_link(12, 0).build(); // Round 13 misses votes for leader block. Other blocks are fully connected with parents.
40/// dag_builder.layer(14).authorities(vec![3,5]).skip_block().build(); // Round 14 authorities 3 and 5 will not propose any block.
41/// dag_builder.layer(15).authorities(vec![3,5]).skip_ancestor_links(vec![1,2]).build(); // Round 15 authorities 3 and 5 will not link to ancestors 1 and 2
42/// dag_builder.layer(16).authorities(vec![3,5]).equivocate(3).build(); // Round 16 authorities 3 and 5 will produce 3 equivocating blocks.
43/// ```
44///
45/// Persisting to DagState by Layer
46/// ```ignore
47/// let dag_state = Arc::new(RwLock::new(DagState::new(
48///    dag_builder.context.clone(),
49///    Arc::new(MemStore::new()),
50/// )));
51/// let context = Arc::new(Context::new_for_test(4).0);
52/// let mut dag_builder = DagBuilder::new(context);
53/// dag_builder.layer(1).build().persist_layers(dag_state.clone()); // persist the layer
54/// ```
55///
56/// Persisting entire DAG to DagState
57/// ```ignore
58/// let dag_state = Arc::new(RwLock::new(DagState::new(
59///    dag_builder.context.clone(),
60///    Arc::new(MemStore::new()),
61/// )));
62/// let context = Arc::new(Context::new_for_test(4).0);
63/// let mut dag_builder = DagBuilder::new(context);
64/// dag_builder.layer(1).build();
65/// dag_builder.layers(2..=10).build();
66/// dag_builder.persist_all_blocks(dag_state.clone()); // persist entire DAG
67/// ```
68///
69/// Printing DAG
70/// ```ignore
71/// let context = Arc::new(Context::new_for_test(4).0);
72/// let mut dag_builder = DagBuilder::new(context);
73/// dag_builder.layer(1).build();
74/// dag_builder.print(); // pretty print the entire DAG
75/// ```
76pub struct DagBuilder {
77    pub(crate) context: Arc<Context>,
78    pub(crate) leader_schedule: LeaderSchedule,
79    // The genesis blocks
80    pub(crate) genesis: BTreeMap<BlockRef, VerifiedBlock>,
81    // The current set of ancestors that any new layer will attempt to connect to.
82    pub(crate) last_ancestors: Vec<BlockRef>,
83    // All blocks created by dag builder. Will be used to pretty print or to be
84    // retrieved for testing/persiting to dag state.
85    pub(crate) blocks: BTreeMap<BlockRef, VerifiedBlock>,
86    // All the committed sub dags created by the dag builder.
87    pub(crate) committed_sub_dags: Vec<(CommittedSubDag, TrustedCommit)>,
88    pub(crate) last_committed_rounds: Vec<Round>,
89
90    number_of_leaders: u32,
91}
92
93impl DagBuilder {
94    pub fn new(context: Arc<Context>) -> Self {
95        let leader_schedule = LeaderSchedule::new(context.clone(), LeaderSwapTable::default());
96        let genesis_blocks = genesis_blocks(context.as_ref());
97        let genesis: BTreeMap<BlockRef, VerifiedBlock> = genesis_blocks
98            .into_iter()
99            .map(|block| (block.reference(), block))
100            .collect();
101        let last_ancestors = genesis.keys().cloned().collect();
102        Self {
103            last_committed_rounds: vec![0; context.committee.size()],
104            context,
105            leader_schedule,
106            number_of_leaders: 1,
107            genesis,
108            last_ancestors,
109            blocks: BTreeMap::new(),
110            committed_sub_dags: vec![],
111        }
112    }
113
114    pub fn blocks(&self, rounds: RangeInclusive<Round>) -> Vec<VerifiedBlock> {
115        assert!(
116            !self.blocks.is_empty(),
117            "No blocks have been created, please make sure that you have called build method"
118        );
119        self.blocks
120            .iter()
121            .filter_map(|(block_ref, block)| rounds.contains(&block_ref.round).then_some(block))
122            .cloned()
123            .collect::<Vec<VerifiedBlock>>()
124    }
125
126    pub fn all_blocks(&self) -> Vec<VerifiedBlock> {
127        assert!(
128            !self.blocks.is_empty(),
129            "No blocks have been created, please make sure that you have called build method"
130        );
131        self.blocks.values().cloned().collect()
132    }
133
134    pub fn get_sub_dag_and_commits(
135        &mut self,
136        leader_rounds: RangeInclusive<Round>,
137    ) -> Vec<(CommittedSubDag, TrustedCommit)> {
138        let (last_leader_round, mut last_commit_ref, mut last_timestamp_ms) =
139            if let Some((sub_dag, _)) = self.committed_sub_dags.last() {
140                (
141                    sub_dag.leader.round,
142                    sub_dag.commit_ref,
143                    sub_dag.timestamp_ms,
144                )
145            } else {
146                (0, CommitRef::new(0, CommitDigest::MIN), 0)
147            };
148
149        struct BlockStorage {
150            gc_round: Round,
151            blocks: BTreeMap<BlockRef, (VerifiedBlock, bool)>, // the tuple represends the block and whether it is committed
152            genesis: BTreeMap<BlockRef, VerifiedBlock>,
153        }
154        impl BlockStoreAPI for BlockStorage {
155            fn get_blocks(&self, refs: &[BlockRef]) -> Vec<Option<VerifiedBlock>> {
156                refs.iter()
157                    .map(|block_ref| {
158                        if block_ref.round == 0 {
159                            return self.genesis.get(block_ref).cloned();
160                        }
161                        self.blocks
162                            .get(block_ref)
163                            .map(|(block, _committed)| block.clone())
164                    })
165                    .collect()
166            }
167
168            fn gc_round(&self) -> Round {
169                self.gc_round
170            }
171
172            fn set_committed(&mut self, block_ref: &BlockRef) -> bool {
173                let Some((_block, committed)) = self.blocks.get_mut(block_ref) else {
174                    panic!("Block {:?} should be found in store", block_ref);
175                };
176                if !*committed {
177                    *committed = true;
178                    return true;
179                }
180                false
181            }
182
183            fn is_committed(&self, block_ref: &BlockRef) -> bool {
184                self.blocks
185                    .get(block_ref)
186                    .map(|(_, committed)| *committed)
187                    .expect("Block should be found in store")
188            }
189        }
190
191        let mut storage = BlockStorage {
192            blocks: self
193                .blocks
194                .clone()
195                .into_iter()
196                .map(|(k, v)| (k, (v, false)))
197                .collect(),
198            genesis: self.genesis.clone(),
199            gc_round: 0,
200        };
201
202        // Create any remaining committed sub dags
203        for leader_block in self
204            .leader_blocks(last_leader_round + 1..=*leader_rounds.end())
205            .into_iter()
206            .flatten()
207        {
208            // set the gc round to the round of the leader block
209            storage.gc_round = leader_block
210                .round()
211                .saturating_sub(1)
212                .saturating_sub(self.context.protocol_config.gc_depth());
213
214            let leader_block_ref = leader_block.reference();
215
216            let to_commit = Linearizer::linearize_sub_dag(
217                leader_block.clone(),
218                &mut storage,
219                self.context.protocol_config.shuffle_commit_blocks(),
220            );
221
222            last_timestamp_ms = Linearizer::calculate_commit_timestamp(
223                &self.context.clone(),
224                &mut storage,
225                &leader_block,
226                last_timestamp_ms,
227            );
228
229            // Update the last committed rounds
230            for block in &to_commit {
231                self.last_committed_rounds[block.author()] =
232                    self.last_committed_rounds[block.author()].max(block.round());
233            }
234
235            let commit = TrustedCommit::new_for_test(
236                last_commit_ref.index + 1,
237                last_commit_ref.digest,
238                last_timestamp_ms,
239                leader_block_ref,
240                to_commit
241                    .iter()
242                    .map(|block| block.reference())
243                    .collect::<Vec<_>>(),
244            );
245
246            last_commit_ref = commit.reference();
247
248            let sub_dag = CommittedSubDag::new(
249                leader_block_ref,
250                to_commit,
251                last_timestamp_ms,
252                commit.reference(),
253            );
254
255            self.committed_sub_dags.push((sub_dag, commit));
256        }
257
258        self.committed_sub_dags
259            .clone()
260            .into_iter()
261            .filter(|(sub_dag, _)| leader_rounds.contains(&sub_dag.leader.round))
262            .collect()
263    }
264
265    #[cfg(test)]
266    pub(crate) fn get_sub_dag_and_certified_commits(
267        &mut self,
268        leader_rounds: RangeInclusive<Round>,
269    ) -> Vec<(CommittedSubDag, CertifiedCommit)> {
270        let commits = self.get_sub_dag_and_commits(leader_rounds);
271        commits
272            .into_iter()
273            .map(|(sub_dag, commit)| {
274                let certified_commit =
275                    CertifiedCommit::new_certified(commit, sub_dag.blocks.clone());
276                (sub_dag, certified_commit)
277            })
278            .collect()
279    }
280
281    pub fn leader_blocks(&self, rounds: RangeInclusive<Round>) -> Vec<Option<VerifiedBlock>> {
282        assert!(
283            !self.blocks.is_empty(),
284            "No blocks have been created, please make sure that you have called build method"
285        );
286        rounds
287            .into_iter()
288            .map(|round| self.leader_block(round))
289            .collect()
290    }
291
292    pub fn leader_block(&self, round: Round) -> Option<VerifiedBlock> {
293        assert!(
294            !self.blocks.is_empty(),
295            "No blocks have been created, please make sure that you have called build method"
296        );
297        self.blocks
298            .iter()
299            .find(|(block_ref, _block)| {
300                block_ref.round == round
301                    && block_ref.author == self.leader_schedule.elect_leader(round, 0)
302            })
303            .map(|(_block_ref, block)| block.clone())
304    }
305
306    pub fn layer(&mut self, round: Round) -> LayerBuilder<'_> {
307        LayerBuilder::new(self, round)
308    }
309
310    pub fn layers(&mut self, rounds: RangeInclusive<Round>) -> LayerBuilder<'_> {
311        let mut builder = LayerBuilder::new(self, *rounds.start());
312        builder.end_round = Some(*rounds.end());
313        builder
314    }
315
316    pub fn persist_all_blocks(&self, dag_state: Arc<RwLock<DagState>>) {
317        dag_state
318            .write()
319            .accept_blocks(self.blocks.values().cloned().collect());
320    }
321
322    pub fn print(&self) {
323        let mut dag_str = "DAG {\n".to_string();
324
325        let mut round = 0;
326        for block in self.blocks.values() {
327            if block.round() > round {
328                round = block.round();
329                dag_str.push_str(&format!("Round {round} : \n"));
330            }
331            dag_str.push_str(&format!("    Block {block:#?}\n"));
332        }
333        dag_str.push_str("}\n");
334
335        tracing::info!("{dag_str}");
336    }
337
338    // TODO: merge into layer builder?
339    // This method allows the user to specify specific links to ancestors. The
340    // layer is written to dag state and the blocks are cached in [`DagBuilder`]
341    // state.
342    pub fn layer_with_connections(
343        &mut self,
344        connections: Vec<(AuthorityIndex, Vec<BlockRef>)>,
345        round: Round,
346    ) {
347        let mut references = Vec::new();
348        for (authority, ancestors) in connections {
349            let author = authority.value() as u32;
350            let base_ts = round as BlockTimestampMs * 1000;
351            let block = VerifiedBlock::new_for_test(
352                TestBlock::new(round, author)
353                    .set_ancestors(ancestors)
354                    .set_timestamp_ms(base_ts + author as u64)
355                    .build(),
356            );
357            references.push(block.reference());
358            self.blocks.insert(block.reference(), block.clone());
359        }
360        self.last_ancestors = references;
361    }
362
363    /// Gets all uncommitted blocks in a slot.
364    pub fn get_uncommitted_blocks_at_slot(&self, slot: Slot) -> Vec<VerifiedBlock> {
365        let mut blocks = vec![];
366        for (_block_ref, block) in self.blocks.range((
367            Included(BlockRef::new(slot.round, slot.authority, BlockDigest::MIN)),
368            Included(BlockRef::new(slot.round, slot.authority, BlockDigest::MAX)),
369        )) {
370            blocks.push(block.clone())
371        }
372        blocks
373    }
374
375    pub fn genesis_block_refs(&self) -> Vec<BlockRef> {
376        self.genesis.keys().cloned().collect()
377    }
378}
379
380/// Refer to doc comments for [`DagBuilder`] for usage information.
381pub struct LayerBuilder<'a> {
382    dag_builder: &'a mut DagBuilder,
383
384    start_round: Round,
385    end_round: Option<Round>,
386
387    // Configuration options applied to specified authorities
388    // TODO: convert configuration options into an enum
389    specified_authorities: Option<Vec<AuthorityIndex>>,
390    // Number of transactions to include per block.
391    num_transactions: u32,
392    // Whether to include rejected transactions
393    rejected_transactions_pct: u8,
394    rejected_transactions_seed: u64,
395    // Number of equivocating blocks per specified authority
396    equivocations: usize,
397    // Skip block proposal for specified authorities
398    skip_block: bool,
399    // Skip specified ancestor links for specified authorities
400    skip_ancestor_links: Option<Vec<AuthorityIndex>>,
401    // Skip leader link for specified authorities
402    no_leader_link: bool,
403    // Use to override last ancestors in dag builder
404    override_last_ancestors: bool,
405
406    // Skip leader block proposal
407    no_leader_block: bool,
408    // Used for leader based configurations
409    specified_leader_link_offsets: Option<Vec<u32>>,
410    specified_leader_block_offsets: Option<Vec<u32>>,
411    leader_round: Option<Round>,
412
413    // All ancestors will be linked to the current layer
414    fully_linked_ancestors: bool,
415    // Only 2f+1 random ancestors will be linked to the current layer using a
416    // seed, if provided
417    min_ancestor_links: bool,
418    min_ancestor_links_random_seed: Option<u64>,
419    // Add random weak links to the current layer using a seed, if provided
420    random_weak_links: bool,
421    random_weak_links_random_seed: Option<u64>,
422
423    // Ancestors to link to the current layer
424    ancestors: Vec<BlockRef>,
425    // override last ancestors in dag_builder
426    specified_ancestors: Vec<BlockRef>,
427
428    // The block timestamps for the layer for each specified authority. This will work as base timestamp and the round will be added to make sure that timestamps do offset.
429    timestamps: Vec<BlockTimestampMs>,
430
431    // Accumulated blocks to write to dag state
432    blocks: Vec<VerifiedBlock>,
433}
434
435impl<'a> LayerBuilder<'a> {
436    fn new(dag_builder: &'a mut DagBuilder, start_round: Round) -> Self {
437        assert!(start_round > 0, "genesis round is created by default");
438        let ancestors = dag_builder.last_ancestors.clone();
439        Self {
440            dag_builder,
441            start_round,
442            end_round: None,
443            specified_authorities: None,
444            num_transactions: 0,
445            rejected_transactions_pct: 0,
446            rejected_transactions_seed: 0,
447            equivocations: 0,
448            skip_block: false,
449            skip_ancestor_links: None,
450            override_last_ancestors: false,
451            no_leader_link: false,
452            no_leader_block: false,
453            specified_leader_link_offsets: None,
454            specified_leader_block_offsets: None,
455            leader_round: None,
456            fully_linked_ancestors: true,
457            min_ancestor_links: false,
458            min_ancestor_links_random_seed: None,
459            random_weak_links: false,
460            random_weak_links_random_seed: None,
461            ancestors,
462            specified_ancestors: vec![],
463            timestamps: vec![],
464            blocks: vec![],
465        }
466    }
467
468    // Configuration methods
469
470    // If you try to add blocks to the same layer you will end up with the last
471    // ancestors replaced with blocks from the current layer. Use this method
472    // to override the last ancestors with the references you manually have kept.
473    pub fn override_last_ancestors(mut self, ancestors: Vec<BlockRef>) -> Self {
474        self.specified_ancestors = ancestors;
475        self.override_last_ancestors = true;
476        self.build()
477    }
478
479    // Only link 2f+1 random ancestors to the current layer round using a seed,
480    // if provided. Also provide a flag to guarantee the leader is included.
481    // note: configuration is terminal and layer will be built after this call.
482    pub fn min_ancestor_links(mut self, include_leader: bool, seed: Option<u64>) -> Self {
483        self.min_ancestor_links = true;
484        self.min_ancestor_links_random_seed = seed;
485        if include_leader {
486            self.leader_round = Some(self.ancestors.iter().max_by_key(|b| b.round).unwrap().round);
487        }
488        self.fully_linked_ancestors = false;
489        self.build()
490    }
491
492    // No links will be created between the specified ancestors and the specified
493    // authorities at the layer round.
494    // note: configuration is terminal and layer will be built after this call.
495    pub fn skip_ancestor_links(mut self, ancestors_to_skip: Vec<AuthorityIndex>) -> Self {
496        // authorities must be specified for this to apply
497        assert!(self.specified_authorities.is_some());
498        self.skip_ancestor_links = Some(ancestors_to_skip);
499        self.fully_linked_ancestors = false;
500        self.build()
501    }
502
503    // Add random weak links to the current layer round using a seed, if provided
504    pub fn random_weak_links(mut self, seed: Option<u64>) -> Self {
505        self.random_weak_links = true;
506        self.random_weak_links_random_seed = seed;
507        self
508    }
509
510    // Should be called when building a leader round. Will ensure leader block is missing.
511    // A list of specified leader offsets can be provided to skip those leaders.
512    // If none are provided all potential leaders for the round will be skipped.
513    pub fn no_leader_block(mut self, specified_leader_offsets: Vec<u32>) -> Self {
514        self.no_leader_block = true;
515        self.specified_leader_block_offsets = Some(specified_leader_offsets);
516        self
517    }
518
519    // Should be called when building a voting round. Will ensure vote is missing.
520    // A list of specified leader offsets can be provided to skip those leader links.
521    // If none are provided all potential leaders for the round will be skipped.
522    // note: configuration is terminal and layer will be built after this call.
523    pub fn no_leader_link(
524        mut self,
525        leader_round: Round,
526        specified_leader_offsets: Vec<u32>,
527    ) -> Self {
528        self.no_leader_link = true;
529        self.specified_leader_link_offsets = Some(specified_leader_offsets);
530        self.leader_round = Some(leader_round);
531        self.fully_linked_ancestors = false;
532        self.build()
533    }
534
535    pub fn authorities(mut self, authorities: Vec<AuthorityIndex>) -> Self {
536        assert!(
537            self.specified_authorities.is_none(),
538            "Specified authorities already set"
539        );
540        self.specified_authorities = Some(authorities);
541        self
542    }
543
544    // Number of transactions to include per block.
545    pub fn num_transactions(mut self, num_transactions: u32) -> Self {
546        self.num_transactions = num_transactions;
547        self
548    }
549
550    pub fn rejected_transactions_pct(mut self, pct: u8, seed: Option<u64>) -> Self {
551        self.rejected_transactions_pct = pct;
552        self.rejected_transactions_seed = if let Some(seed) = seed {
553            seed
554        } else {
555            thread_rng().r#gen()
556        };
557        self
558    }
559
560    // Multiple blocks will be created for the specified authorities at the layer round.
561    pub fn equivocate(mut self, equivocations: usize) -> Self {
562        // authorities must be specified for this to apply
563        assert!(self.specified_authorities.is_some());
564        self.equivocations = equivocations;
565        self
566    }
567
568    // No blocks will be created for the specified authorities at the layer round.
569    pub fn skip_block(mut self) -> Self {
570        // authorities must be specified for this to apply
571        assert!(self.specified_authorities.is_some());
572        self.skip_block = true;
573        self
574    }
575
576    pub fn with_timestamps(mut self, timestamps: Vec<BlockTimestampMs>) -> Self {
577        // authorities must be specified for this to apply
578        assert!(self.specified_authorities.is_some());
579        assert_eq!(
580            self.specified_authorities.as_ref().unwrap().len(),
581            timestamps.len(),
582            "Timestamps should be provided for each specified authority"
583        );
584        self.timestamps = timestamps;
585        self
586    }
587
588    // Apply the configurations & build the dag layer(s).
589    pub fn build(mut self) -> Self {
590        for round in self.start_round..=self.end_round.unwrap_or(self.start_round) {
591            tracing::debug!("BUILDING LAYER ROUND {round}...");
592
593            let authorities = if self.specified_authorities.is_some() {
594                self.specified_authorities.clone().unwrap()
595            } else {
596                self.dag_builder
597                    .context
598                    .committee
599                    .authorities()
600                    .map(|x| x.0)
601                    .collect()
602            };
603
604            // TODO: investigate if these configurations can be called in combination
605            // for the same layer
606            let mut connections = if self.override_last_ancestors {
607                self.configure_specifed_ancestors()
608            } else if self.fully_linked_ancestors {
609                self.configure_fully_linked_ancestors(round)
610            } else if self.min_ancestor_links {
611                self.configure_min_parent_links(round)
612            } else if self.no_leader_link {
613                self.configure_no_leader_links(authorities.clone(), round)
614            } else if self.skip_ancestor_links.is_some() {
615                self.configure_skipped_ancestor_links(
616                    authorities,
617                    self.skip_ancestor_links.clone().unwrap(),
618                )
619            } else {
620                vec![]
621            };
622
623            if self.random_weak_links {
624                connections.append(&mut self.configure_random_weak_links());
625            }
626
627            self.create_blocks(round, connections);
628        }
629
630        self.dag_builder.last_ancestors = self.ancestors.clone();
631        self
632    }
633
634    pub fn persist_layers(&self, dag_state: Arc<RwLock<DagState>>) {
635        assert!(
636            !self.blocks.is_empty(),
637            "Called to persist layers although no blocks have been created. Make sure you have called build before."
638        );
639        dag_state.write().accept_blocks(self.blocks.clone());
640    }
641
642    // Layer round is minimally and randomly connected with ancestors.
643    pub fn configure_min_parent_links(
644        &mut self,
645        round: Round,
646    ) -> Vec<(AuthorityIndex, Vec<BlockRef>)> {
647        let quorum_threshold = self.dag_builder.context.committee.quorum_threshold() as usize;
648        let authorities: Vec<AuthorityIndex> = self
649            .dag_builder
650            .context
651            .committee
652            .authorities()
653            .map(|authority| authority.0)
654            .collect();
655
656        let mut rng = match self.min_ancestor_links_random_seed {
657            Some(s) => StdRng::seed_from_u64(s),
658            None => StdRng::from_entropy(),
659        };
660
661        let mut authorities_to_shuffle = authorities.clone();
662        let ancestors_by_author = self
663            .ancestors
664            .iter()
665            .filter(|ancestor| ancestor.round < round)
666            .fold(
667                BTreeMap::<AuthorityIndex, Vec<BlockRef>>::new(),
668                |mut grouped, ancestor| {
669                    grouped.entry(ancestor.author).or_default().push(*ancestor);
670                    grouped
671                },
672            );
673
674        let mut leaders = vec![];
675        if let Some(leader_round) = self.leader_round {
676            let leader_offsets = (0..self.dag_builder.number_of_leaders).collect::<Vec<_>>();
677
678            for leader_offset in leader_offsets {
679                leaders.push(
680                    self.dag_builder
681                        .leader_schedule
682                        .elect_leader(leader_round, leader_offset),
683                );
684            }
685        }
686
687        authorities
688            .iter()
689            .map(|authority| {
690                authorities_to_shuffle.shuffle(&mut rng);
691
692                // TODO: handle quroum threshold properly with stake
693                let mut selected_authorities = vec![*authority];
694                selected_authorities.extend(
695                    authorities_to_shuffle
696                        .iter()
697                        .filter(|ancestor_author| **ancestor_author != *authority)
698                        .take(quorum_threshold - 1)
699                        .cloned(),
700                );
701                for leader in &leaders {
702                    if !selected_authorities.contains(leader) {
703                        selected_authorities.push(*leader);
704                    }
705                }
706
707                (
708                    *authority,
709                    selected_authorities
710                        .into_iter()
711                        .filter_map(|ancestor_author| {
712                            ancestors_by_author
713                                .get(&ancestor_author)
714                                .and_then(|ancestors| ancestors.choose(&mut rng))
715                                .copied()
716                        })
717                        .collect::<Vec<BlockRef>>(),
718                )
719            })
720            .collect()
721    }
722
723    // TODO: configure layer round randomly connected with weak links.
724    fn configure_random_weak_links(&mut self) -> Vec<(AuthorityIndex, Vec<BlockRef>)> {
725        unimplemented!("configure_random_weak_links");
726    }
727
728    // Layer round misses link to leader, but other blocks are fully connected with ancestors.
729    fn configure_no_leader_links(
730        &mut self,
731        authorities: Vec<AuthorityIndex>,
732        _round: Round,
733    ) -> Vec<(AuthorityIndex, Vec<BlockRef>)> {
734        let mut missing_leaders = Vec::new();
735        let mut specified_leader_offsets = self
736            .specified_leader_link_offsets
737            .clone()
738            .expect("specified_leader_offsets should be set");
739        let leader_round = self.leader_round.expect("leader round should be set");
740
741        // When no specified leader offsets are available, all leaders are
742        // expected to be missing.
743        if specified_leader_offsets.is_empty() {
744            specified_leader_offsets.extend(0..self.dag_builder.number_of_leaders);
745        }
746
747        for leader_offset in specified_leader_offsets {
748            missing_leaders.push(
749                self.dag_builder
750                    .leader_schedule
751                    .elect_leader(leader_round, leader_offset),
752            );
753        }
754
755        self.configure_skipped_ancestor_links(authorities, missing_leaders)
756    }
757
758    fn configure_specifed_ancestors(&mut self) -> Vec<(AuthorityIndex, Vec<BlockRef>)> {
759        self.dag_builder
760            .context
761            .committee
762            .authorities()
763            .map(|authority| (authority.0, self.specified_ancestors.clone()))
764            .collect::<Vec<_>>()
765    }
766
767    fn configure_fully_linked_ancestors(
768        &mut self,
769        round: Round,
770    ) -> Vec<(AuthorityIndex, Vec<BlockRef>)> {
771        self.dag_builder
772            .context
773            .committee
774            .authorities()
775            .map(|authority| {
776                (
777                    authority.0,
778                    // don't connect to ancestors of this round
779                    self.ancestors
780                        .clone()
781                        .into_iter()
782                        .filter(|a| a.round != round)
783                        .collect::<Vec<_>>(),
784                )
785            })
786            .collect::<Vec<_>>()
787    }
788
789    fn configure_skipped_ancestor_links(
790        &mut self,
791        authorities: Vec<AuthorityIndex>,
792        ancestors_to_skip: Vec<AuthorityIndex>,
793    ) -> Vec<(AuthorityIndex, Vec<BlockRef>)> {
794        let filtered_ancestors = self
795            .ancestors
796            .clone()
797            .into_iter()
798            .filter(|ancestor| !ancestors_to_skip.contains(&ancestor.author))
799            .collect::<Vec<_>>();
800        authorities
801            .into_iter()
802            .map(|authority| (authority, filtered_ancestors.clone()))
803            .collect::<Vec<_>>()
804    }
805
806    // Creates the blocks for the new layer based on configured connections, also
807    // sets the ancestors for future layers to be linked to
808    fn create_blocks(&mut self, round: Round, connections: Vec<(AuthorityIndex, Vec<BlockRef>)>) {
809        let mut references = Vec::new();
810        let mut reject_rng =
811            StdRng::seed_from_u64(self.rejected_transactions_seed ^ (round as u64));
812        for (authority, ancestors) in connections {
813            if self.should_skip_block(round, authority) {
814                continue;
815            };
816            let transactions = (0..self.num_transactions)
817                .map(|_| Transaction::new(vec![1_u8; 16]))
818                .collect::<Vec<_>>();
819            let num_blocks = self.num_blocks_to_create(authority);
820            for num_block in 0..num_blocks {
821                let mut votes = vec![];
822                if self.rejected_transactions_pct > 0 {
823                    for ancestor in &ancestors {
824                        let mut rejects = vec![];
825                        for i in 0..self.num_transactions {
826                            if reject_rng.gen_range(1..=100) <= self.rejected_transactions_pct {
827                                rejects.push(i as TransactionIndex);
828                            }
829                        }
830                        if !rejects.is_empty() {
831                            votes.push(BlockTransactionVotes {
832                                block_ref: *ancestor,
833                                rejects,
834                            });
835                        }
836                    }
837                }
838                let timestamp = self.block_timestamp(authority, round, num_block);
839                let block = VerifiedBlock::new_for_test(
840                    TestBlock::new(round, authority.value() as u32)
841                        .set_transactions(transactions.clone())
842                        .set_transaction_votes(votes)
843                        .set_ancestors(ancestors.clone())
844                        .set_timestamp_ms(timestamp)
845                        .build(),
846                );
847                references.push(block.reference());
848                self.dag_builder
849                    .blocks
850                    .insert(block.reference(), block.clone());
851                self.blocks.push(block);
852            }
853        }
854        self.ancestors = references;
855    }
856
857    fn num_blocks_to_create(&self, authority: AuthorityIndex) -> u32 {
858        if self.specified_authorities.is_some()
859            && self
860                .specified_authorities
861                .clone()
862                .unwrap()
863                .contains(&authority)
864        {
865            // Always create 1 block and then the equivocating blocks on top of that.
866            1 + self.equivocations as u32
867        } else {
868            1
869        }
870    }
871
872    fn block_timestamp(
873        &self,
874        authority: AuthorityIndex,
875        round: Round,
876        num_block: u32,
877    ) -> BlockTimestampMs {
878        if let Some(specified_authorities) = self.specified_authorities.as_ref()
879            && !self.timestamps.is_empty()
880            && let Some(position) = specified_authorities.iter().position(|&x| x == authority)
881        {
882            return self.timestamps[position] + (round + num_block) as u64;
883        }
884        let author = authority.value() as u32;
885        let base_ts = round as BlockTimestampMs * 1000;
886        base_ts + (author + round + num_block) as u64
887    }
888
889    fn should_skip_block(&self, round: Round, authority: AuthorityIndex) -> bool {
890        // Safe to unwrap as specified authorites has to be set before skip
891        // is specified.
892        if self.skip_block
893            && self
894                .specified_authorities
895                .clone()
896                .unwrap()
897                .contains(&authority)
898        {
899            return true;
900        }
901        if self.no_leader_block {
902            let mut specified_leader_offsets = self
903                .specified_leader_block_offsets
904                .clone()
905                .expect("specified_leader_block_offsets should be set");
906
907            // When no specified leader offsets are available, all leaders are
908            // expected to be skipped.
909            if specified_leader_offsets.is_empty() {
910                specified_leader_offsets.extend(0..self.dag_builder.number_of_leaders);
911            }
912
913            for leader_offset in specified_leader_offsets {
914                let leader = self
915                    .dag_builder
916                    .leader_schedule
917                    .elect_leader(round, leader_offset);
918
919                if leader == authority {
920                    return true;
921                }
922            }
923        }
924        false
925    }
926}