1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Contains providers for inherents required for empty block production.

use std::{sync::Arc, time::Duration};

use parity_scale_codec::Encode;
use sp_consensus_aura::{Slot, SlotDuration, AURA_ENGINE_ID};
use sp_consensus_babe::{
    digests::{PreDigest, SecondaryPlainPreDigest},
    BABE_ENGINE_ID,
};
use sp_inherents::InherentData;
use sp_runtime::{
    traits::{Block as BlockT, HashingFor},
    Digest, DigestItem,
};
use sp_state_machine::TestExternalities;
use sp_std::prelude::*;
use strum_macros::{Display, EnumIter};
use tokio::sync::Mutex;

use crate::common::empty_block::inherents::custom_idps;

const RELAYCHAIN_BLOCKTIME_MS: u64 = 6000u64;

/// Trait for providing the inherent data and digest items for block construction.
pub trait InherentProvider<B: BlockT> {
    type Err;

    fn get_inherent_providers_and_pre_digest(
        &self,
        maybe_parent_info: Option<(InherentData, Digest)>,
        parent_header: B::Header,
        ext: Arc<Mutex<TestExternalities<HashingFor<B>>>>,
    ) -> InherentProviderResult<Self::Err>;
}

// Clippy asks that we abstract the return type because it's so long
type InherentProviderResult<Err> =
    Result<(Box<dyn sp_inherents::InherentDataProvider>, Vec<DigestItem>), Err>;

/// Classes of [`InherentProvider`] avaliable.
///
/// Currently only Smart is implemented. New implementations may be added if Smart is not suitable
/// for some edge cases.
#[derive(Debug, Clone, EnumIter, Display, Copy)]
pub enum ProviderVariant {
    /// Smart chain varient will automatically adjust provided inherents based on the given
    /// externalities.
    ///
    /// The blocktime is provided in milliseconds.
    Smart(core::time::Duration),
}

impl<B: BlockT> InherentProvider<B> for ProviderVariant {
    type Err = String;

    fn get_inherent_providers_and_pre_digest(
        &self,
        maybe_parent_info: Option<(InherentData, Digest)>,
        parent_header: B::Header,
        ext: Arc<Mutex<TestExternalities<HashingFor<B>>>>,
    ) -> InherentProviderResult<Self::Err> {
        match *self {
            ProviderVariant::Smart(blocktime) => {
                <SmartInherentProvider as InherentProvider<B>>::get_inherent_providers_and_pre_digest(&SmartInherentProvider {
                     blocktime,
                 }, maybe_parent_info, parent_header, ext)
            }
        }
    }
}

/// Attempts to provide inherents in a fashion that works for as many chains as possible.
///
/// It is currently tested for
/// - Polkadot-based relay chains
/// - Polkadot-ecosystem system parachains
///
/// If it does not work for your Substrate-based chain, [please open an issue](https://github.com/paritytech/try-runtime-cli/issues)
/// and we will look into supporting it.
struct SmartInherentProvider {
    blocktime: Duration,
}

impl<B: BlockT> InherentProvider<B> for SmartInherentProvider {
    type Err = String;

    fn get_inherent_providers_and_pre_digest(
        &self,
        maybe_parent_info: Option<(InherentData, Digest)>,
        parent_header: B::Header,
        ext: Arc<Mutex<TestExternalities<HashingFor<B>>>>,
    ) -> InherentProviderResult<Self::Err> {
        let timestamp_idp = custom_idps::timestamp::InherentDataProvider {
            blocktime_millis: self.blocktime.as_millis() as u64,
            maybe_parent_info,
        };
        let para_parachain_idp = custom_idps::para_parachain::InherentDataProvider::<B> {
            blocktime_millis: RELAYCHAIN_BLOCKTIME_MS,
            parent_header: parent_header.clone(),
            timestamp: timestamp_idp.timestamp(),
            ext_mutex: ext,
        };
        let relay_parachain_data_idp =
            custom_idps::relay_parachains::InherentDataProvider::<B>::new(parent_header);

        let slot = Slot::from_timestamp(
            timestamp_idp.timestamp(),
            SlotDuration::from_millis(self.blocktime.as_millis() as u64),
        );
        let digest = vec![
            DigestItem::PreRuntime(
                BABE_ENGINE_ID,
                PreDigest::SecondaryPlain(SecondaryPlainPreDigest {
                    slot,
                    authority_index: 0,
                })
                .encode(),
            ),
            DigestItem::PreRuntime(AURA_ENGINE_ID, slot.encode()),
        ];

        Ok((
            Box::new((timestamp_idp, para_parachain_idp, relay_parachain_data_idp)),
            digest,
        ))
    }
}