Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit ad53996

Browse files
yjhmelodybkchr
andauthored
chore: move genesis block builder to chain-spec crate. (#13427)
* chore: move genesis block builder to block builder crate. * add missing file * chore: move genesis block builder to sc-chain-spec * Update client/chain-spec/src/genesis.rs Co-authored-by: Bastian Köcher <[email protected]> * Update test-utils/runtime/src/genesismap.rs Co-authored-by: Bastian Köcher <[email protected]> * Update test-utils/runtime/client/src/lib.rs * fix warnings * fix warnings --------- Co-authored-by: Bastian Köcher <[email protected]>
1 parent b7e0518 commit ad53996

File tree

12 files changed

+88
-74
lines changed

12 files changed

+88
-74
lines changed

Diff for: Cargo.lock

+5
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: client/block-builder/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" }
2323
sp-core = { version = "7.0.0", path = "../../primitives/core" }
2424
sp-inherents = { version = "4.0.0-dev", path = "../../primitives/inherents" }
2525
sp-runtime = { version = "7.0.0", path = "../../primitives/runtime" }
26-
sp-state-machine = { version = "0.13.0", path = "../../primitives/state-machine" }
2726

2827
[dev-dependencies]
28+
sp-state-machine = { version = "0.13.0", path = "../../primitives/state-machine" }
2929
substrate-test-runtime-client = { path = "../../test-utils/runtime/client" }

Diff for: client/block-builder/src/lib.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,8 @@ use sp_runtime::{
3939
Digest,
4040
};
4141

42-
pub use sp_block_builder::BlockBuilder as BlockBuilderApi;
43-
4442
use sc_client_api::backend;
43+
pub use sp_block_builder::BlockBuilder as BlockBuilderApi;
4544

4645
/// Used as parameter to [`BlockBuilderProvider`] to express if proof recording should be enabled.
4746
///

Diff for: client/chain-spec/Cargo.toml

+4
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,12 @@ targets = ["x86_64-unknown-linux-gnu"]
1616
memmap2 = "0.5.0"
1717
serde = { version = "1.0.136", features = ["derive"] }
1818
serde_json = "1.0.85"
19+
sc-client-api = { version = "4.0.0-dev", path = "../api" }
1920
sc-chain-spec-derive = { version = "4.0.0-dev", path = "./derive" }
21+
sc-executor = { version = "0.10.0-dev", path = "../executor" }
2022
sc-network-common = { version = "0.10.0-dev", path = "../network/common" }
2123
sc-telemetry = { version = "4.0.0-dev", path = "../telemetry" }
24+
sp-blockchain = { version = "4.0.0-dev", path = "../../primitives/blockchain" }
2225
sp-core = { version = "7.0.0", path = "../../primitives/core" }
2326
sp-runtime = { version = "7.0.0", path = "../../primitives/runtime" }
27+
sp-state-machine = { version = "0.13.0", path = "../../primitives/state-machine" }

Diff for: client/service/src/client/genesis.rs renamed to client/chain-spec/src/genesis.rs

+42-7
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,56 @@
1818

1919
//! Tool for creating the genesis block.
2020
21+
use std::{collections::hash_map::DefaultHasher, marker::PhantomData, sync::Arc};
22+
2123
use sc_client_api::{backend::Backend, BlockImportOperation};
2224
use sc_executor::RuntimeVersionOf;
23-
use sp_core::storage::Storage;
25+
use sp_core::storage::{well_known_keys, StateVersion, Storage};
2426
use sp_runtime::{
2527
traits::{Block as BlockT, Hash as HashT, Header as HeaderT, Zero},
2628
BuildStorage,
2729
};
28-
use std::{marker::PhantomData, sync::Arc};
30+
31+
/// Return the state version given the genesis storage and executor.
32+
pub fn resolve_state_version_from_wasm<E>(
33+
storage: &Storage,
34+
executor: &E,
35+
) -> sp_blockchain::Result<StateVersion>
36+
where
37+
E: RuntimeVersionOf,
38+
{
39+
if let Some(wasm) = storage.top.get(well_known_keys::CODE) {
40+
let mut ext = sp_state_machine::BasicExternalities::new_empty(); // just to read runtime version.
41+
42+
let code_fetcher = sp_core::traits::WrappedRuntimeCode(wasm.as_slice().into());
43+
let runtime_code = sp_core::traits::RuntimeCode {
44+
code_fetcher: &code_fetcher,
45+
heap_pages: None,
46+
hash: {
47+
use std::hash::{Hash, Hasher};
48+
let mut state = DefaultHasher::new();
49+
wasm.hash(&mut state);
50+
state.finish().to_le_bytes().to_vec()
51+
},
52+
};
53+
let runtime_version = RuntimeVersionOf::runtime_version(executor, &mut ext, &runtime_code)
54+
.map_err(|e| sp_blockchain::Error::VersionInvalid(e.to_string()))?;
55+
Ok(runtime_version.state_version())
56+
} else {
57+
Err(sp_blockchain::Error::VersionInvalid(
58+
"Runtime missing from initial storage, could not read state version.".to_string(),
59+
))
60+
}
61+
}
2962

3063
/// Create a genesis block, given the initial storage.
31-
pub fn construct_genesis_block<Block: BlockT>(state_root: Block::Hash) -> Block {
64+
pub fn construct_genesis_block<Block: BlockT>(
65+
state_root: Block::Hash,
66+
state_version: StateVersion,
67+
) -> Block {
3268
let extrinsics_root = <<<Block as BlockT>::Header as HeaderT>::Hashing as HashT>::trie_root(
3369
Vec::new(),
34-
sp_runtime::StateVersion::V0,
70+
state_version,
3571
);
3672

3773
Block::new(
@@ -93,12 +129,11 @@ impl<Block: BlockT, B: Backend<Block>, E: RuntimeVersionOf> BuildGenesisBlock<Bl
93129
fn build_genesis_block(self) -> sp_blockchain::Result<(Block, Self::BlockImportOperation)> {
94130
let Self { genesis_storage, commit_genesis_state, backend, executor, _phantom } = self;
95131

96-
let genesis_state_version =
97-
crate::resolve_state_version_from_wasm(&genesis_storage, &executor)?;
132+
let genesis_state_version = resolve_state_version_from_wasm(&genesis_storage, &executor)?;
98133
let mut op = backend.begin_operation()?;
99134
let state_root =
100135
op.set_genesis_state(genesis_storage, commit_genesis_state, genesis_state_version)?;
101-
let genesis_block = construct_genesis_block::<Block>(state_root);
136+
let genesis_block = construct_genesis_block::<Block>(state_root, genesis_state_version);
102137

103138
Ok((genesis_block, op))
104139
}

Diff for: client/chain-spec/src/lib.rs

+8-3
Original file line numberDiff line numberDiff line change
@@ -177,10 +177,15 @@
177177
178178
mod chain_spec;
179179
mod extension;
180+
mod genesis;
180181

181-
pub use chain_spec::{ChainSpec as GenericChainSpec, NoExtension};
182-
pub use extension::{
183-
get_extension, get_extension_mut, Extension, Fork, Forks, GetExtension, Group,
182+
pub use self::{
183+
chain_spec::{ChainSpec as GenericChainSpec, NoExtension},
184+
extension::{get_extension, get_extension_mut, Extension, Fork, Forks, GetExtension, Group},
185+
genesis::{
186+
construct_genesis_block, resolve_state_version_from_wasm, BuildGenesisBlock,
187+
GenesisBlockBuilder,
188+
},
184189
};
185190
pub use sc_chain_spec_derive::{ChainSpecExtension, ChainSpecGroup};
186191

Diff for: client/service/src/client/client.rs

+8-42
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,14 @@
1818

1919
//! Substrate Client
2020
21-
use super::{
22-
block_rules::{BlockRules, LookupResult as BlockLookupResult},
23-
genesis::BuildGenesisBlock,
24-
};
21+
use super::block_rules::{BlockRules, LookupResult as BlockLookupResult};
2522
use futures::{FutureExt, StreamExt};
2623
use log::{error, info, trace, warn};
2724
use parking_lot::{Mutex, RwLock};
2825
use prometheus_endpoint::Registry;
2926
use rand::Rng;
3027
use sc_block_builder::{BlockBuilderApi, BlockBuilderProvider, RecordProof};
28+
use sc_chain_spec::{resolve_state_version_from_wasm, BuildGenesisBlock};
3129
use sc_client_api::{
3230
backend::{
3331
self, apply_aux, BlockImportOperation, ClientImportOperation, FinalizeSummary, Finalizer,
@@ -46,7 +44,7 @@ use sc_client_api::{
4644
use sc_consensus::{
4745
BlockCheckParams, BlockImportParams, ForkChoiceStrategy, ImportResult, StateAction,
4846
};
49-
use sc_executor::{RuntimeVersion, RuntimeVersionOf};
47+
use sc_executor::RuntimeVersion;
5048
use sc_telemetry::{telemetry, TelemetryHandle, SUBSTRATE_INFO};
5149
use sp_api::{
5250
ApiExt, ApiRef, CallApiAt, CallApiAtParams, ConstructRuntimeApi, Core as CoreApi,
@@ -61,8 +59,8 @@ use sp_consensus::{BlockOrigin, BlockStatus, Error as ConsensusError};
6159
use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedSender};
6260
use sp_core::{
6361
storage::{
64-
well_known_keys, ChildInfo, ChildType, PrefixedStorageKey, Storage, StorageChild,
65-
StorageData, StorageKey,
62+
well_known_keys, ChildInfo, ChildType, PrefixedStorageKey, StorageChild, StorageData,
63+
StorageKey,
6664
},
6765
traits::SpawnNamed,
6866
};
@@ -84,7 +82,7 @@ use sp_state_machine::{
8482
};
8583
use sp_trie::{CompactProof, StorageProof};
8684
use std::{
87-
collections::{hash_map::DefaultHasher, HashMap, HashSet},
85+
collections::{HashMap, HashSet},
8886
marker::PhantomData,
8987
path::PathBuf,
9088
sync::Arc,
@@ -172,7 +170,7 @@ pub fn new_in_mem<E, Block, G, RA>(
172170
Client<in_mem::Backend<Block>, LocalCallExecutor<Block, in_mem::Backend<Block>, E>, Block, RA>,
173171
>
174172
where
175-
E: CodeExecutor + RuntimeVersionOf,
173+
E: CodeExecutor + sc_executor::RuntimeVersionOf,
176174
Block: BlockT,
177175
G: BuildGenesisBlock<
178176
Block,
@@ -233,7 +231,7 @@ pub fn new_with_backend<B, E, Block, G, RA>(
233231
config: ClientConfig<Block>,
234232
) -> sp_blockchain::Result<Client<B, LocalCallExecutor<Block, B, E>, Block, RA>>
235233
where
236-
E: CodeExecutor + RuntimeVersionOf,
234+
E: CodeExecutor + sc_executor::RuntimeVersionOf,
237235
G: BuildGenesisBlock<
238236
Block,
239237
BlockImportOperation = <B as backend::Backend<Block>>::BlockImportOperation,
@@ -1222,38 +1220,6 @@ where
12221220
}
12231221
}
12241222

1225-
/// Return the genesis state version given the genesis storage and executor.
1226-
pub fn resolve_state_version_from_wasm<E>(
1227-
storage: &Storage,
1228-
executor: &E,
1229-
) -> sp_blockchain::Result<StateVersion>
1230-
where
1231-
E: RuntimeVersionOf,
1232-
{
1233-
if let Some(wasm) = storage.top.get(well_known_keys::CODE) {
1234-
let mut ext = sp_state_machine::BasicExternalities::new_empty(); // just to read runtime version.
1235-
1236-
let code_fetcher = sp_core::traits::WrappedRuntimeCode(wasm.as_slice().into());
1237-
let runtime_code = sp_core::traits::RuntimeCode {
1238-
code_fetcher: &code_fetcher,
1239-
heap_pages: None,
1240-
hash: {
1241-
use std::hash::{Hash, Hasher};
1242-
let mut state = DefaultHasher::new();
1243-
wasm.hash(&mut state);
1244-
state.finish().to_le_bytes().to_vec()
1245-
},
1246-
};
1247-
let runtime_version = RuntimeVersionOf::runtime_version(executor, &mut ext, &runtime_code)
1248-
.map_err(|e| sp_blockchain::Error::VersionInvalid(e.to_string()))?;
1249-
Ok(runtime_version.state_version())
1250-
} else {
1251-
Err(sp_blockchain::Error::VersionInvalid(
1252-
"Runtime missing from initial storage, could not read state version.".to_string(),
1253-
))
1254-
}
1255-
}
1256-
12571223
impl<B, E, Block, RA> UsageProvider<Block> for Client<B, E, Block, RA>
12581224
where
12591225
B: backend::Backend<Block>,

Diff for: client/service/src/client/mod.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,12 @@
4747
mod block_rules;
4848
mod call_executor;
4949
mod client;
50-
pub mod genesis;
5150
mod wasm_override;
5251
mod wasm_substitutes;
5352

5453
pub use self::{
5554
call_executor::LocalCallExecutor,
56-
client::{resolve_state_version_from_wasm, Client, ClientConfig},
55+
client::{Client, ClientConfig},
5756
};
5857

5958
#[cfg(feature = "test-helpers")]

Diff for: client/service/src/lib.rs

+7-4
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,15 @@ pub use self::{
6161
new_full_parts, spawn_tasks, BuildNetworkParams, KeystoreContainer, NetworkStarter,
6262
SpawnTasksParams, TFullBackend, TFullCallExecutor, TFullClient,
6363
},
64-
client::{
65-
genesis::{BuildGenesisBlock, GenesisBlockBuilder},
66-
resolve_state_version_from_wasm, ClientConfig, LocalCallExecutor,
67-
},
64+
client::{ClientConfig, LocalCallExecutor},
6865
error::Error,
6966
};
67+
68+
pub use sc_chain_spec::{
69+
construct_genesis_block, resolve_state_version_from_wasm, BuildGenesisBlock,
70+
GenesisBlockBuilder,
71+
};
72+
7073
pub use config::{
7174
BasePath, BlocksPruning, Configuration, DatabaseSource, PruningMode, Role, RpcMethods, TaskType,
7275
};

Diff for: test-utils/runtime/client/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"]
1515
codec = { package = "parity-scale-codec", version = "3.2.2" }
1616
futures = "0.3.21"
1717
sc-block-builder = { version = "0.10.0-dev", path = "../../../client/block-builder" }
18+
sc-chain-spec = { version = "4.0.0-dev", path = "../../../client/chain-spec" }
1819
sc-client-api = { version = "4.0.0-dev", path = "../../../client/api" }
1920
sc-consensus = { version = "0.10.0-dev", path = "../../../client/consensus/common" }
2021
sp-api = { version = "4.0.0-dev", path = "../../../primitives/api" }

Diff for: test-utils/runtime/client/src/lib.rs

+7-10
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ pub use substrate_test_runtime as runtime;
3030

3131
pub use self::block_builder_ext::BlockBuilderExt;
3232

33+
use sc_chain_spec::construct_genesis_block;
34+
use sp_api::StateVersion;
3335
use sp_core::{
3436
sr25519,
3537
storage::{ChildInfo, Storage, StorageChild},
@@ -122,7 +124,7 @@ impl GenesisParameters {
122124
}
123125
}
124126

125-
impl substrate_test_client::GenesisInit for GenesisParameters {
127+
impl GenesisInit for GenesisParameters {
126128
fn genesis_storage(&self) -> Storage {
127129
use codec::Encode;
128130

@@ -148,7 +150,7 @@ impl substrate_test_client::GenesisInit for GenesisParameters {
148150
storage.top.clone().into_iter().chain(child_roots).collect(),
149151
sp_runtime::StateVersion::V1,
150152
);
151-
let block: runtime::Block = client::genesis::construct_genesis_block(state_root);
153+
let block: runtime::Block = construct_genesis_block(state_root, StateVersion::V1);
152154
storage.top.extend(additional_storage_with_genesis(&block));
153155

154156
storage
@@ -260,7 +262,7 @@ impl<B> TestClientBuilderExt<B>
260262
client::LocalCallExecutor<
261263
substrate_test_runtime::Block,
262264
B,
263-
sc_executor::NativeElseWasmExecutor<LocalExecutorDispatch>,
265+
NativeElseWasmExecutor<LocalExecutorDispatch>,
264266
>,
265267
B,
266268
> where
@@ -288,11 +290,6 @@ pub fn new() -> Client<Backend> {
288290
}
289291

290292
/// Create a new native executor.
291-
pub fn new_native_executor() -> sc_executor::NativeElseWasmExecutor<LocalExecutorDispatch> {
292-
sc_executor::NativeElseWasmExecutor::new(
293-
sc_executor::WasmExecutionMethod::Interpreted,
294-
None,
295-
8,
296-
2,
297-
)
293+
pub fn new_native_executor() -> NativeElseWasmExecutor<LocalExecutorDispatch> {
294+
NativeElseWasmExecutor::new(sc_executor::WasmExecutionMethod::Interpreted, None, 8, 2)
298295
}

Diff for: test-utils/runtime/src/genesismap.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@
2020
use super::{system, wasm_binary_unwrap, AccountId, AuthorityId, Runtime};
2121
use codec::{Encode, Joiner, KeyedVec};
2222
use frame_support::traits::GenesisBuild;
23-
use sc_service::client::genesis;
23+
use sc_service::construct_genesis_block;
2424
use sp_core::{
2525
map,
26-
storage::{well_known_keys, Storage},
26+
storage::{well_known_keys, StateVersion, Storage},
2727
};
2828
use sp_io::hashing::{blake2_256, twox_128};
2929
use sp_runtime::traits::{Block as BlockT, Hash as HashT, Header as HeaderT};
@@ -106,7 +106,7 @@ pub fn insert_genesis_block(storage: &mut Storage) -> sp_core::hash::H256 {
106106
storage.top.clone().into_iter().collect(),
107107
sp_runtime::StateVersion::V1,
108108
);
109-
let block: crate::Block = genesis::construct_genesis_block(state_root);
109+
let block: crate::Block = construct_genesis_block(state_root, StateVersion::V1);
110110
let genesis_hash = block.header.hash();
111111
storage.top.extend(additional_storage_with_genesis(&block));
112112
genesis_hash

0 commit comments

Comments
 (0)