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
use std::{ops::DerefMut, str::FromStr, sync::Arc};

use parity_scale_codec::{Decode, Encode};
use sc_cli::Result;
use sc_executor::{HostFunctions, WasmExecutor};
use sp_core::H256;
use sp_inherents::InherentData;
use sp_runtime::{
    traits::{Block as BlockT, HashingFor, Header, NumberFor, One},
    DeserializeOwned, Digest,
};
use sp_state_machine::TestExternalities;
use sp_std::fmt::Debug;
use tokio::sync::Mutex;

use super::inherents::{pre_apply::pre_apply_inherents, providers::InherentProvider};
use crate::{
    common::{empty_block::inherents::providers::ProviderVariant, state::state_machine_call},
    full_extensions,
};

pub async fn mine_block<Block, HostFns: HostFunctions>(
    ext_mutex: Arc<Mutex<TestExternalities<HashingFor<Block>>>>,
    executor: &WasmExecutor<HostFns>,
    previous_block_building_info: Option<(InherentData, Digest)>,
    parent_header: Block::Header,
    provider_variant: ProviderVariant,
    try_state: frame_try_runtime::TryStateSelect,
) -> Result<((InherentData, Digest), Block::Header)>
where
    Block: BlockT<Hash = H256> + DeserializeOwned,
    Block::Header: DeserializeOwned,
    <Block::Hash as FromStr>::Err: Debug,
    NumberFor<Block>: FromStr,
    <NumberFor<Block> as FromStr>::Err: Debug,
{
    // We are saving state before we overwrite it while producing new block.
    let mut ext_guard = ext_mutex.lock().await;
    let ext = ext_guard.deref_mut();
    let backend = ext.as_backend();
    drop(ext_guard);

    log::info!(
        "Producing new empty block at height {:?}",
        *parent_header.number() + One::one()
    );

    let (next_block, new_block_building_info) = produce_next_block::<Block, HostFns>(
        ext_mutex.clone(),
        executor,
        parent_header.clone(),
        provider_variant,
        previous_block_building_info,
    )
    .await?;

    log::info!(
        "Produced a new block ({})",
        array_bytes::bytes2hex("0x", next_block.header().hash())
    );

    let mut ext_guard = ext_mutex.lock().await;
    let ext = ext_guard.deref_mut();

    // And now we restore previous state.
    ext.backend = backend;

    pre_apply_inherents::<Block>(ext);
    let state_root_check = true;
    let signature_check = true;
    let payload = (
        next_block.clone(),
        state_root_check,
        signature_check,
        try_state,
    )
        .encode();
    call::<Block, _>(ext, executor, "TryRuntime_execute_block", &payload).await?;

    log::info!("Executed the new block");

    Ok((new_block_building_info, next_block.header().clone()))
}

/// Produces next block containing only inherents.
pub async fn produce_next_block<Block, HostFns: HostFunctions>(
    ext_mutex: Arc<Mutex<TestExternalities<HashingFor<Block>>>>,
    executor: &WasmExecutor<HostFns>,
    parent_header: Block::Header,
    chain: ProviderVariant,
    previous_block_building_info: Option<(InherentData, Digest)>,
) -> Result<(Block, (InherentData, Digest))>
where
    Block: BlockT<Hash = H256> + DeserializeOwned,
    Block::Header: DeserializeOwned,
    <Block::Hash as FromStr>::Err: Debug,
    NumberFor<Block>: FromStr,
    <NumberFor<Block> as FromStr>::Err: Debug,
{
    let (inherent_data_provider, pre_digest) =
        <ProviderVariant as InherentProvider<Block>>::get_inherent_providers_and_pre_digest(
            &chain,
            previous_block_building_info,
            parent_header.clone(),
            ext_mutex.clone(),
        )?;

    let mut ext_guard = ext_mutex.lock().await;
    let ext = ext_guard.deref_mut();

    pre_apply_inherents::<Block>(ext);
    drop(ext_guard);
    let inherent_data = inherent_data_provider
        .create_inherent_data()
        .await
        .map_err(|s| sc_cli::Error::Input(s.to_string()))?;
    let digest = Digest { logs: pre_digest };

    let header = Block::Header::new(
        *parent_header.number() + One::one(),
        Default::default(),
        Default::default(),
        parent_header.hash(),
        digest.clone(),
    );

    let mut ext_guard = ext_mutex.lock().await;
    let ext = ext_guard.deref_mut();
    call::<Block, _>(ext, executor, "Core_initialize_block", &header.encode()).await?;

    let extrinsics = dry_call::<Vec<Block::Extrinsic>, Block, _>(
        ext,
        executor,
        "BlockBuilder_inherent_extrinsics",
        &inherent_data.encode(),
    )?;

    for xt in &extrinsics {
        call::<Block, _>(ext, executor, "BlockBuilder_apply_extrinsic", &xt.encode()).await?;
    }

    let header = dry_call::<Block::Header, Block, _>(
        ext,
        executor,
        "BlockBuilder_finalize_block",
        &[0u8; 0],
    )?;

    call::<Block, _>(ext, executor, "BlockBuilder_finalize_block", &[0u8; 0]).await?;

    drop(ext_guard);

    Ok((Block::new(header, extrinsics), (inherent_data, digest)))
}

/// Call `method` with `data` and actually save storage changes to `externalities`.
async fn call<Block: BlockT, HostFns: HostFunctions>(
    externalities: &mut TestExternalities<HashingFor<Block>>,
    executor: &WasmExecutor<HostFns>,
    method: &'static str,
    data: &[u8],
) -> Result<()> {
    let (mut changes, _) = state_machine_call::<Block, HostFns>(
        externalities,
        executor,
        method,
        data,
        full_extensions(executor.clone()),
    )?;

    let storage_changes =
        changes.drain_storage_changes(&externalities.backend, externalities.state_version)?;

    externalities.backend.apply_transaction(
        storage_changes.transaction_storage_root,
        storage_changes.transaction,
    );

    Ok(())
}

/// Call `method` with `data` and return the result. `externalities` will not change.
fn dry_call<T: Decode, Block: BlockT, HostFns: HostFunctions>(
    externalities: &TestExternalities<HashingFor<Block>>,
    executor: &WasmExecutor<HostFns>,
    method: &'static str,
    data: &[u8],
) -> Result<T> {
    let (_, result) = state_machine_call::<Block, HostFns>(
        externalities,
        executor,
        method,
        data,
        full_extensions(executor.clone()),
    )?;

    Ok(<T>::decode(&mut &*result)?)
}