sc_proof_of_time/
slots.rs

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
use sc_consensus_slots::SlotInfo;
use sp_consensus::SelectChain;
use sp_consensus_slots::Slot;
use sp_inherents::CreateInherentDataProviders;
use sp_runtime::traits::{Block as BlockT, Header};
use std::time::Duration;
use tracing::error;

pub(super) struct SlotInfoProducer<Block, SC, IDP> {
    slot_duration: Duration,
    create_inherent_data_providers: IDP,
    select_chain: SC,
    _phantom: std::marker::PhantomData<Block>,
}

impl<Block, SC, IDP> SlotInfoProducer<Block, SC, IDP> {
    /// Create a new `Slots` stream.
    pub(super) fn new(
        slot_duration: Duration,
        create_inherent_data_providers: IDP,
        select_chain: SC,
    ) -> Self {
        SlotInfoProducer {
            slot_duration,
            create_inherent_data_providers,
            select_chain,
            _phantom: Default::default(),
        }
    }
}

impl<Block, SC, IDP> SlotInfoProducer<Block, SC, IDP>
where
    Block: BlockT,
    SC: SelectChain<Block>,
    IDP: CreateInherentDataProviders<Block, ()> + 'static,
{
    pub(super) async fn produce_slot_info(&self, slot: Slot) -> Option<SlotInfo<Block>> {
        let best_header = match self.select_chain.best_chain().await {
            Ok(best_header) => best_header,
            Err(error) => {
                error!(
                    %error,
                    "Unable to author block in slot. No best block header.",
                );

                return None;
            }
        };

        let inherent_data_providers = match self
            .create_inherent_data_providers
            .create_inherent_data_providers(best_header.hash(), ())
            .await
        {
            Ok(inherent_data_providers) => inherent_data_providers,
            Err(error) => {
                error!(
                    %error,
                    "Unable to author block in slot. Failure creating inherent data provider.",
                );

                return None;
            }
        };

        Some(SlotInfo::new(
            slot,
            Box::new(inherent_data_providers),
            self.slot_duration,
            best_header,
            None,
        ))
    }
}