sc_chain_spec/
genesis_config_builder.rs1use codec::{Decode, Encode};
22pub use sc_executor::sp_wasm_interface::HostFunctions;
23use sc_executor::{error::Result, WasmExecutor};
24use serde_json::{from_slice, Value};
25use sp_core::{
26 storage::Storage,
27 traits::{CallContext, CodeExecutor, Externalities, FetchRuntimeCode, RuntimeCode},
28};
29use sp_genesis_builder::{PresetId, Result as BuildResult};
30pub use sp_genesis_builder::{DEV_RUNTIME_PRESET, LOCAL_TESTNET_RUNTIME_PRESET};
31use sp_state_machine::BasicExternalities;
32use std::borrow::Cow;
33
34pub struct GenesisConfigBuilderRuntimeCaller<'a, EHF = ()>
39where
40 EHF: HostFunctions,
41{
42 code: Cow<'a, [u8]>,
43 code_hash: Vec<u8>,
44 executor: WasmExecutor<(sp_io::SubstrateHostFunctions, EHF)>,
45}
46
47impl<'a, EHF> FetchRuntimeCode for GenesisConfigBuilderRuntimeCaller<'a, EHF>
48where
49 EHF: HostFunctions,
50{
51 fn fetch_runtime_code(&self) -> Option<Cow<[u8]>> {
52 Some(self.code.as_ref().into())
53 }
54}
55
56impl<'a, EHF> GenesisConfigBuilderRuntimeCaller<'a, EHF>
57where
58 EHF: HostFunctions,
59{
60 pub fn new(code: &'a [u8]) -> Self {
64 GenesisConfigBuilderRuntimeCaller {
65 code: code.into(),
66 code_hash: sp_crypto_hashing::blake2_256(code).to_vec(),
67 executor: WasmExecutor::<(sp_io::SubstrateHostFunctions, EHF)>::builder()
68 .with_allow_missing_host_functions(true)
69 .build(),
70 }
71 }
72
73 fn call(&self, ext: &mut dyn Externalities, method: &str, data: &[u8]) -> Result<Vec<u8>> {
74 self.executor
75 .call(
76 ext,
77 &RuntimeCode { heap_pages: None, code_fetcher: self, hash: self.code_hash.clone() },
78 method,
79 data,
80 CallContext::Offchain,
81 )
82 .0
83 }
84
85 pub fn get_default_config(&self) -> core::result::Result<Value, String> {
91 self.get_named_preset(None)
92 }
93
94 pub fn get_named_preset(&self, id: Option<&String>) -> core::result::Result<Value, String> {
99 let mut t = BasicExternalities::new_empty();
100 let call_result = self
101 .call(&mut t, "GenesisBuilder_get_preset", &id.encode())
102 .map_err(|e| format!("wasm call error {e}"))?;
103
104 let named_preset = Option::<Vec<u8>>::decode(&mut &call_result[..])
105 .map_err(|e| format!("scale codec error: {e}"))?;
106
107 if let Some(named_preset) = named_preset {
108 Ok(from_slice(&named_preset[..]).expect("returned value is json. qed."))
109 } else {
110 Err(format!("The preset with name {id:?} is not available."))
111 }
112 }
113
114 pub fn get_storage_for_config(&self, config: Value) -> core::result::Result<Storage, String> {
116 let mut ext = BasicExternalities::new_empty();
117
118 let json_pretty_str = serde_json::to_string_pretty(&config)
119 .map_err(|e| format!("json to string failed: {e}"))?;
120
121 let call_result = self
122 .call(&mut ext, "GenesisBuilder_build_state", &json_pretty_str.encode())
123 .map_err(|e| format!("wasm call error {e}"))?;
124
125 BuildResult::decode(&mut &call_result[..])
126 .map_err(|e| format!("scale codec error: {e}"))?
127 .map_err(|e| format!("{e} for blob:\n{}", json_pretty_str))?;
128
129 Ok(ext.into_storages())
130 }
131
132 pub fn get_storage_for_patch(&self, patch: Value) -> core::result::Result<Storage, String> {
151 let mut config = self.get_default_config()?;
152 crate::json_patch::merge(&mut config, patch);
153 self.get_storage_for_config(config)
154 }
155
156 pub fn get_storage_for_named_preset(
157 &self,
158 name: Option<&String>,
159 ) -> core::result::Result<Storage, String> {
160 self.get_storage_for_patch(self.get_named_preset(name)?)
161 }
162
163 pub fn preset_names(&self) -> core::result::Result<Vec<PresetId>, String> {
164 let mut t = BasicExternalities::new_empty();
165 let call_result = self
166 .call(&mut t, "GenesisBuilder_preset_names", &vec![])
167 .map_err(|e| format!("wasm call error {e}"))?;
168
169 let preset_names = Vec::<PresetId>::decode(&mut &call_result[..])
170 .map_err(|e| format!("scale codec error: {e}"))?;
171
172 Ok(preset_names)
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179 use serde_json::{from_str, json};
180 pub use sp_consensus_babe::{AllowedSlots, BabeEpochConfiguration};
181 pub use sp_genesis_builder::PresetId;
182
183 #[test]
184 fn list_presets_works() {
185 sp_tracing::try_init_simple();
186 let presets =
187 <GenesisConfigBuilderRuntimeCaller>::new(substrate_test_runtime::wasm_binary_unwrap())
188 .preset_names()
189 .unwrap();
190 assert_eq!(presets, vec![PresetId::from("foobar"), PresetId::from("staging"),]);
191 }
192
193 #[test]
194 fn get_default_config_works() {
195 let config =
196 <GenesisConfigBuilderRuntimeCaller>::new(substrate_test_runtime::wasm_binary_unwrap())
197 .get_default_config()
198 .unwrap();
199 let expected = r#"{"babe": {"authorities": [], "epochConfig": {"allowed_slots": "PrimaryAndSecondaryVRFSlots", "c": [1, 4]}}, "balances": {"balances": [], "devAccounts": null}, "substrateTest": {"authorities": []}, "system": {}}"#;
200 assert_eq!(from_str::<Value>(expected).unwrap(), config);
201 }
202
203 #[test]
204 fn get_named_preset_works() {
205 sp_tracing::try_init_simple();
206 let config =
207 <GenesisConfigBuilderRuntimeCaller>::new(substrate_test_runtime::wasm_binary_unwrap())
208 .get_named_preset(Some(&"foobar".to_string()))
209 .unwrap();
210 let expected = r#"{"foo":"bar"}"#;
211 assert_eq!(from_str::<Value>(expected).unwrap(), config);
212 }
213
214 #[test]
215 fn get_storage_for_patch_works() {
216 let patch = json!({
217 "babe": {
218 "epochConfig": {
219 "c": [
220 69,
221 696
222 ],
223 "allowed_slots": "PrimaryAndSecondaryPlainSlots"
224 }
225 },
226 });
227
228 let storage =
229 <GenesisConfigBuilderRuntimeCaller>::new(substrate_test_runtime::wasm_binary_unwrap())
230 .get_storage_for_patch(patch)
231 .unwrap();
232
233 let value: Vec<u8> = storage
235 .top
236 .get(
237 &array_bytes::hex2bytes(
238 "1cb6f36e027abb2091cfb5110ab5087fdc6b171b77304263c292cc3ea5ed31ef",
239 )
240 .unwrap(),
241 )
242 .unwrap()
243 .clone();
244
245 assert_eq!(
246 BabeEpochConfiguration::decode(&mut &value[..]).unwrap(),
247 BabeEpochConfiguration {
248 c: (69, 696),
249 allowed_slots: AllowedSlots::PrimaryAndSecondaryPlainSlots
250 }
251 );
252 }
253}