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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//! Provides functionality of adding inherent extrinsics to the Domain.
//! Unlike Primary chain where inherent data is first derived the block author
//! and the data is verified by the on primary runtime, domains inherents
//! short circuit the derivation and verification of inherent data
//! as the inherent data is directly taken from the primary block from which
//! domain block is being built.
//!
//! One of the first use case for this is passing Timestamp data. Before building a
//! domain block using a primary block, we take the current time from the primary runtime
//! and then create an unsigned extrinsic that is put on top the bundle extrinsics.
//!
//! Deriving these extrinsics during fraud proof verification should be possible since
//! verification environment will have access to consensus chain.

use sp_api::{ApiExt, ProvideRuntimeApi};
use sp_blockchain::HeaderBackend;
use sp_domains::{DomainId, DomainsApi, DomainsDigestItem};
use sp_inherents::{CreateInherentDataProviders, InherentData, InherentDataProvider};
use sp_messenger::MessengerApi;
use sp_runtime::traits::{Block as BlockT, Header, NumberFor};
use sp_timestamp::InherentType;
use std::error::Error;
use std::sync::Arc;

pub async fn get_inherent_data<CClient, CBlock, Block>(
    consensus_client: Arc<CClient>,
    consensus_block_hash: CBlock::Hash,
    parent_hash: Block::Hash,
    domain_id: DomainId,
) -> Result<InherentData, sp_blockchain::Error>
where
    CBlock: BlockT,
    Block: BlockT,
    CClient: ProvideRuntimeApi<CBlock> + HeaderBackend<CBlock>,
    CClient::Api:
        DomainsApi<CBlock, Block::Header> + MessengerApi<CBlock, NumberFor<CBlock>, CBlock::Hash>,
{
    let create_inherent_data_providers =
        CreateInherentDataProvider::new(consensus_client, Some(consensus_block_hash), domain_id);
    let inherent_data_providers = <CreateInherentDataProvider<_, _> as CreateInherentDataProviders<
        Block,
        (),
    >>::create_inherent_data_providers(
        &create_inherent_data_providers, parent_hash, ()
    )
        .await?;
    let mut inherent_data = InherentData::new();
    inherent_data_providers
        .provide_inherent_data(&mut inherent_data)
        .await
        .map_err(|err| {
            sp_blockchain::Error::Application(Box::from(format!(
                "failed to provide inherent data: {err:?}"
            )))
        })?;

    Ok(inherent_data)
}

pub(crate) fn is_runtime_upgraded<CClient, CBlock, Block>(
    consensus_client: &Arc<CClient>,
    consensus_block_hash: CBlock::Hash,
    domain_id: DomainId,
) -> Result<bool, sp_blockchain::Error>
where
    CClient: ProvideRuntimeApi<CBlock> + HeaderBackend<CBlock>,
    CClient::Api: DomainsApi<CBlock, Block::Header>,
    CBlock: BlockT,
    Block: BlockT,
{
    let header = consensus_client.header(consensus_block_hash)?.ok_or(
        sp_blockchain::Error::MissingHeader(format!(
            "No header found for {consensus_block_hash:?}"
        )),
    )?;

    let runtime_api = consensus_client.runtime_api();
    let runtime_id = runtime_api
        .runtime_id(consensus_block_hash, domain_id)?
        .ok_or(sp_blockchain::Error::Application(Box::from(format!(
            "No RuntimeId found for {domain_id:?}"
        ))))?;

    Ok(header
        .digest()
        .logs
        .iter()
        .filter_map(|log| log.as_domain_runtime_upgrade())
        .any(|upgraded_runtime_id| upgraded_runtime_id == runtime_id))
}

/// Returns new upgraded runtime if upgraded did happen in the provided consensus block.
pub fn extract_domain_runtime_upgrade_code<CClient, CBlock, Block>(
    consensus_client: &Arc<CClient>,
    consensus_block_hash: CBlock::Hash,
    domain_id: DomainId,
) -> Result<Option<Vec<u8>>, sp_blockchain::Error>
where
    CClient: ProvideRuntimeApi<CBlock> + HeaderBackend<CBlock>,
    CClient::Api: DomainsApi<CBlock, Block::Header>,
    CBlock: BlockT,
    Block: BlockT,
{
    let header = consensus_client.header(consensus_block_hash)?.ok_or(
        sp_blockchain::Error::MissingHeader(format!(
            "No header found for {consensus_block_hash:?}"
        )),
    )?;

    let runtime_api = consensus_client.runtime_api();
    let runtime_id = runtime_api
        .runtime_id(consensus_block_hash, domain_id)?
        .ok_or(sp_blockchain::Error::Application(Box::from(format!(
            "No RuntimeId found for {domain_id:?}"
        ))))?;

    if header
        .digest()
        .logs
        .iter()
        .filter_map(|log| log.as_domain_runtime_upgrade())
        .any(|upgraded_runtime_id| upgraded_runtime_id == runtime_id)
    {
        let new_domain_runtime = runtime_api
            .domain_runtime_code(consensus_block_hash, domain_id)?
            .ok_or_else(|| {
                sp_blockchain::Error::Application(Box::from(format!(
                    "No new runtime code for {domain_id:?}"
                )))
            })?;

        Ok(Some(new_domain_runtime))
    } else {
        Ok(None)
    }
}

#[derive(Debug)]
pub struct CreateInherentDataProvider<CClient, CBlock: BlockT> {
    consensus_client: Arc<CClient>,
    maybe_consensus_block_hash: Option<CBlock::Hash>,
    domain_id: DomainId,
}

impl<CClient, CBlock: BlockT + Clone> Clone for CreateInherentDataProvider<CClient, CBlock> {
    fn clone(&self) -> Self {
        Self {
            consensus_client: self.consensus_client.clone(),
            maybe_consensus_block_hash: self.maybe_consensus_block_hash,
            domain_id: self.domain_id,
        }
    }
}

impl<CClient, CBlock: BlockT> CreateInherentDataProvider<CClient, CBlock> {
    pub fn new(
        consensus_client: Arc<CClient>,
        maybe_consensus_block_hash: Option<CBlock::Hash>,
        domain_id: DomainId,
    ) -> Self {
        Self {
            consensus_client,
            maybe_consensus_block_hash,
            domain_id,
        }
    }
}

#[async_trait::async_trait]
impl<CClient, CBlock, Block> CreateInherentDataProviders<Block, ()>
    for CreateInherentDataProvider<CClient, CBlock>
where
    Block: BlockT,
    CBlock: BlockT,
    CClient: ProvideRuntimeApi<CBlock> + HeaderBackend<CBlock>,
    CClient::Api:
        DomainsApi<CBlock, Block::Header> + MessengerApi<CBlock, NumberFor<CBlock>, CBlock::Hash>,
{
    type InherentDataProviders = (
        sp_timestamp::InherentDataProvider,
        sp_block_fees::InherentDataProvider,
        sp_executive::InherentDataProvider,
        sp_messenger::InherentDataProvider,
        sp_domain_sudo::InherentDataProvider,
    );

    async fn create_inherent_data_providers(
        &self,
        _parent: Block::Hash,
        _extra_args: (),
    ) -> Result<Self::InherentDataProviders, Box<dyn Error + Send + Sync>> {
        // always prefer the consensus block hash that was given but eth_rpc
        // uses this inherent provider to while fetching pending state
        // https://github.com/paritytech/frontier/blob/master/client/rpc/src/eth/pending.rs#L70
        // This is a non mutable call used by web3 api and using the best consensus block hash
        // here is completely ok.
        let consensus_block_hash = self
            .maybe_consensus_block_hash
            .unwrap_or(self.consensus_client.info().best_hash);
        let runtime_api = self.consensus_client.runtime_api();
        let timestamp = runtime_api.timestamp(consensus_block_hash)?;
        let timestamp_provider =
            sp_timestamp::InherentDataProvider::new(InherentType::new(timestamp));

        let maybe_runtime_upgrade_code = extract_domain_runtime_upgrade_code::<_, _, Block>(
            &self.consensus_client,
            consensus_block_hash,
            self.domain_id,
        )?;
        let runtime_upgrade_provider =
            sp_executive::InherentDataProvider::new(maybe_runtime_upgrade_code);

        let consensus_chain_byte_fee =
            runtime_api.consensus_chain_byte_fee(consensus_block_hash)?;
        let storage_price_provider =
            sp_block_fees::InherentDataProvider::new(consensus_chain_byte_fee);

        // TODO: remove version check before next network
        let messenger_api_version = runtime_api
            .api_version::<dyn MessengerApi<CBlock, NumberFor<CBlock>, CBlock::Hash>>(
                consensus_block_hash,
            )?
            // safe to return default version as 1 since there will always be version 1.
            .unwrap_or(1);

        let domain_chains_allowlist_update = if messenger_api_version >= 3 {
            runtime_api.domain_chains_allowlist_update(consensus_block_hash, self.domain_id)?
        } else {
            None
        };

        let messenger_inherent_provider =
            sp_messenger::InherentDataProvider::new(sp_messenger::InherentType {
                maybe_updates: domain_chains_allowlist_update,
            });

        // TODO: remove version check before next network
        let domain_api_version = runtime_api
            .api_version::<dyn DomainsApi<CBlock, Block::Header>>(consensus_block_hash)?
            // safe to return default version as 1 since there will always be version 1.
            .unwrap_or(1);

        let maybe_domain_sudo_call = if domain_api_version >= 5 {
            runtime_api.domain_sudo_call(consensus_block_hash, self.domain_id)?
        } else {
            None
        };
        let domain_sudo_call_inherent_provider =
            sp_domain_sudo::InherentDataProvider::new(maybe_domain_sudo_call);

        Ok((
            timestamp_provider,
            storage_price_provider,
            runtime_upgrade_provider,
            messenger_inherent_provider,
            domain_sudo_call_inherent_provider,
        ))
    }
}