mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-13 21:01:05 +00:00
ChainSpec extensions (#3692)
* Add some chainspec tests and make sure we validate it. * Manual implementation of Extension + Forks definitions. * Move chain spec to separate crate. * Allow using ChainSpec with extensions. * Renames. * Implement Extension derive. * Implement Extension for Forks. * Support specifying fork blocks. * make for_blocks work * Support forks correctly. * Add a bunch of docs. * Make fork blocks optional. * Add missing docs. * Fix build. * Use struct for check_block params. * Fix tests? * Clean up.
This commit is contained in:
committed by
Gavin Wood
parent
c555b9bf88
commit
667ee95f5d
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "substrate-chain-spec"
|
||||
version = "2.0.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
chain-spec-derive = { package = "substrate-chain-spec-derive", path = "./derive" }
|
||||
impl-trait-for-tuples = "0.1.1"
|
||||
network = { package = "substrate-network", path = "../../core/network" }
|
||||
primitives = { package = "substrate-primitives", path = "../primitives" }
|
||||
serde = { version = "1.0.101", features = ["derive"] }
|
||||
serde_json = "1.0.40"
|
||||
sr-primitives = { path = "../../core/sr-primitives" }
|
||||
tel = { package = "substrate-telemetry", path = "../../core/telemetry" }
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -0,0 +1,17 @@
|
||||
[package]
|
||||
name = "substrate-chain-spec-derive"
|
||||
version = "2.0.0"
|
||||
authors = ["Parity Technologies <admin@parity.io>"]
|
||||
edition = "2018"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro-crate = "0.1.3"
|
||||
proc-macro2 = "1.0.1"
|
||||
quote = "1.0.2"
|
||||
syn = "1.0.5"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
// Copyright 2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::quote;
|
||||
use syn::{DeriveInput, Ident, Error};
|
||||
use proc_macro_crate::crate_name;
|
||||
|
||||
const CRATE_NAME: &str = "substrate-chain-spec";
|
||||
const ATTRIBUTE_NAME: &str = "forks";
|
||||
|
||||
/// Implements `Extension's` `Group` accessor.
|
||||
///
|
||||
/// The struct that derives this implementation will be usable within the `ChainSpec` file.
|
||||
/// The derive implements a by-type accessor method.
|
||||
pub fn extension_derive(ast: &DeriveInput) -> proc_macro::TokenStream {
|
||||
derive(ast, |crate_name, name, generics: &syn::Generics, field_names, field_types, fields| {
|
||||
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
|
||||
let forks = fields.named.iter().find_map(|f| {
|
||||
if f.attrs.iter().any(|attr| attr.path.is_ident(ATTRIBUTE_NAME)) {
|
||||
let typ = &f.ty;
|
||||
Some(quote! { #typ })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}).unwrap_or_else(|| quote! { #crate_name::NoExtension });
|
||||
|
||||
quote! {
|
||||
impl #impl_generics #crate_name::Extension for #name #ty_generics #where_clause {
|
||||
type Forks = #forks;
|
||||
|
||||
fn get<T: 'static>(&self) -> Option<&T> {
|
||||
use std::any::{Any, TypeId};
|
||||
|
||||
match TypeId::of::<T>() {
|
||||
#( x if x == TypeId::of::<#field_types>() => Any::downcast_ref(&self.#field_names) ),*,
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/// Implements required traits and creates `Fork` structs for `ChainSpec` custom parameter group.
|
||||
pub fn group_derive(ast: &DeriveInput) -> proc_macro::TokenStream {
|
||||
derive(ast, |crate_name, name, generics: &syn::Generics, field_names, field_types, _fields| {
|
||||
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
|
||||
let fork_name = Ident::new(&format!("{}Fork", name), Span::call_site());
|
||||
|
||||
let fork_fields = generate_fork_fields(&crate_name, &field_names, &field_types);
|
||||
let to_fork = generate_base_to_fork(&fork_name, &field_names);
|
||||
let combine_with = generate_combine_with(&field_names);
|
||||
let to_base = generate_fork_to_base(name, &field_names);
|
||||
|
||||
quote! {
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecExtension)]
|
||||
pub struct #fork_name #ty_generics #where_clause {
|
||||
#fork_fields
|
||||
}
|
||||
|
||||
impl #impl_generics #crate_name::Group for #name #ty_generics #where_clause {
|
||||
type Fork = #fork_name #ty_generics;
|
||||
|
||||
fn to_fork(self) -> Self::Fork {
|
||||
use #crate_name::Group;
|
||||
#to_fork
|
||||
}
|
||||
}
|
||||
|
||||
impl #impl_generics #crate_name::Fork for #fork_name #ty_generics #where_clause {
|
||||
type Base = #name #ty_generics;
|
||||
|
||||
fn combine_with(&mut self, other: Self) {
|
||||
use #crate_name::Fork;
|
||||
#combine_with
|
||||
}
|
||||
|
||||
fn to_base(self) -> Option<Self::Base> {
|
||||
use #crate_name::Fork;
|
||||
#to_base
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn derive(
|
||||
ast: &DeriveInput,
|
||||
derive: impl Fn(
|
||||
&Ident, &Ident, &syn::Generics, Vec<&Ident>, Vec<&syn::Type>, &syn::FieldsNamed,
|
||||
) -> TokenStream,
|
||||
) -> proc_macro::TokenStream {
|
||||
let err = || {
|
||||
let err = Error::new(
|
||||
Span::call_site(),
|
||||
"ChainSpecGroup is only avaible for structs with named fields."
|
||||
).to_compile_error();
|
||||
quote!( #err ).into()
|
||||
};
|
||||
|
||||
let data = match &ast.data {
|
||||
syn::Data::Struct(ref data) => data,
|
||||
_ => return err(),
|
||||
};
|
||||
|
||||
let fields = match &data.fields {
|
||||
syn::Fields::Named(ref named) => named,
|
||||
_ => return err(),
|
||||
};
|
||||
|
||||
const PROOF: &str = "CARGO_PKG_NAME always defined when compiling; qed";
|
||||
let name = &ast.ident;
|
||||
let crate_name = match crate_name(CRATE_NAME) {
|
||||
Ok(chain_spec_name) => chain_spec_name,
|
||||
Err(e) => if std::env::var("CARGO_PKG_NAME").expect(PROOF) == CRATE_NAME {
|
||||
// we return the name of the crate here instead of `crate` to support doc tests.
|
||||
CRATE_NAME.replace("-", "_")
|
||||
} else {
|
||||
let err = Error::new(Span::call_site(), &e).to_compile_error();
|
||||
return quote!( #err ).into()
|
||||
},
|
||||
};
|
||||
let crate_name = Ident::new(&crate_name, Span::call_site());
|
||||
let field_names = fields.named.iter().flat_map(|x| x.ident.as_ref()).collect::<Vec<_>>();
|
||||
let field_types = fields.named.iter().map(|x| &x.ty).collect::<Vec<_>>();
|
||||
|
||||
derive(&crate_name, name, &ast.generics, field_names, field_types, fields).into()
|
||||
}
|
||||
|
||||
fn generate_fork_fields(
|
||||
crate_name: &Ident,
|
||||
names: &[&Ident],
|
||||
types: &[&syn::Type],
|
||||
) -> TokenStream {
|
||||
let crate_name = std::iter::repeat(crate_name);
|
||||
quote! {
|
||||
#( pub #names: Option<<#types as #crate_name::Group>::Fork>, )*
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_base_to_fork(
|
||||
fork_name: &Ident,
|
||||
names: &[&Ident],
|
||||
) -> TokenStream {
|
||||
let names2 = names.to_vec();
|
||||
|
||||
quote!{
|
||||
#fork_name {
|
||||
#( #names: Some(self.#names2.to_fork()), )*
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_combine_with(
|
||||
names: &[&Ident],
|
||||
) -> TokenStream {
|
||||
let names2 = names.to_vec();
|
||||
|
||||
quote!{
|
||||
#( self.#names.combine_with(other.#names2); )*
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_fork_to_base(
|
||||
fork: &Ident,
|
||||
names: &[&Ident],
|
||||
) -> TokenStream {
|
||||
let names2 = names.to_vec();
|
||||
|
||||
quote!{
|
||||
Some(#fork {
|
||||
#( #names: self.#names2?.to_base()?, )*
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// Copyright 2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Macros to derive chain spec extension traits implementation.
|
||||
|
||||
extern crate proc_macro;
|
||||
|
||||
mod impls;
|
||||
|
||||
use proc_macro::TokenStream;
|
||||
|
||||
#[proc_macro_derive(ChainSpecGroup)]
|
||||
pub fn group_derive(input: TokenStream) -> TokenStream {
|
||||
match syn::parse(input) {
|
||||
Ok(ast) => impls::group_derive(&ast),
|
||||
Err(e) => e.to_compile_error().into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[proc_macro_derive(ChainSpecExtension, attributes(forks))]
|
||||
pub fn extensions_derive(input: TokenStream) -> TokenStream {
|
||||
match syn::parse(input) {
|
||||
Ok(ast) => impls::extension_derive(&ast),
|
||||
Err(e) => e.to_compile_error().into(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "Flaming Fir",
|
||||
"id": "flaming-fir",
|
||||
"properties": {
|
||||
"tokenDecimals": 15,
|
||||
"tokenSymbol": "FIR"
|
||||
},
|
||||
"bootNodes": [
|
||||
"/ip4/35.246.224.91/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV",
|
||||
"/ip4/35.246.224.91/tcp/30334/ws/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV",
|
||||
"/ip4/35.246.210.11/tcp/30333/p2p/QmWv9Ww7znzgLFyCzf21SR6tUKXrmHCZH9KhebeH4gyE9f",
|
||||
"/ip4/35.246.210.11/tcp/30334/ws/p2p/QmWv9Ww7znzgLFyCzf21SR6tUKXrmHCZH9KhebeH4gyE9f",
|
||||
"/ip4/35.198.110.45/tcp/30333/p2p/QmTtcYKJho9vFmqtMA548QBSmLbmwAkBSiEKK3kWKfb6bJ",
|
||||
"/ip4/35.198.110.45/tcp/30334/ws/p2p/QmTtcYKJho9vFmqtMA548QBSmLbmwAkBSiEKK3kWKfb6bJ",
|
||||
"/ip4/35.198.114.154/tcp/30333/p2p/QmQJmDorK9c8KjMF5PdWiH2WGUXyzJtgTeJ55S5gggdju6",
|
||||
"/ip4/35.198.114.154/tcp/30334/ws/p2p/QmQJmDorK9c8KjMF5PdWiH2WGUXyzJtgTeJ55S5gggdju6"
|
||||
],
|
||||
"telemetryEndpoints": [
|
||||
["wss://telemetry.polkadot.io/submit/", 0]
|
||||
],
|
||||
"protocolId": "fir",
|
||||
"consensusEngine": null,
|
||||
"genesis": {
|
||||
"raw": [
|
||||
{
|
||||
"0xb2029f8665aac509629f2d28cea790a3": "0x10f26cdb14b5aec7b2789fd5ca80f979cef3761897ae1f37ffb3e154cbcc1c26633919132b851ef0fd2dae42a7e734fe547af5a6b809006100f48944d7fae8e8ef00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f437800299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378547ff0ab649283a7ae01dbc2eb73932eba2fb09075e9485ff369082a2ff38d655633b70b80a6c8bb16270f82cca6d56b27ed7b76c8fd5af2986a25a4788ce440482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a68655684472b743e456907b398d3a44c113f189e56d1bbfd55e889e295dfde787932cff431e748892fa48e10c63c17d30f80ca42e4de3921e641249cd7fa3c2f482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e9c7a2ee14e565db0c69f78c7b4cd839fbf52b607d867e9e9c5a79042898a0d129becad03e6dcac03cee07edebca5475314861492cdfc96a2144a67bbe96993326e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f91066e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"
|
||||
},
|
||||
{}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "Flaming Fir",
|
||||
"id": "flaming-fir",
|
||||
"properties": {
|
||||
"tokenDecimals": 15,
|
||||
"tokenSymbol": "FIR"
|
||||
},
|
||||
"bootNodes": [
|
||||
"/ip4/35.246.224.91/tcp/30333/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV",
|
||||
"/ip4/35.246.224.91/tcp/30334/ws/p2p/QmSk5HQbn6LhUwDiNMseVUjuRYhEtYj4aUZ6WfWoGURpdV",
|
||||
"/ip4/35.246.210.11/tcp/30333/p2p/QmWv9Ww7znzgLFyCzf21SR6tUKXrmHCZH9KhebeH4gyE9f",
|
||||
"/ip4/35.246.210.11/tcp/30334/ws/p2p/QmWv9Ww7znzgLFyCzf21SR6tUKXrmHCZH9KhebeH4gyE9f",
|
||||
"/ip4/35.198.110.45/tcp/30333/p2p/QmTtcYKJho9vFmqtMA548QBSmLbmwAkBSiEKK3kWKfb6bJ",
|
||||
"/ip4/35.198.110.45/tcp/30334/ws/p2p/QmTtcYKJho9vFmqtMA548QBSmLbmwAkBSiEKK3kWKfb6bJ",
|
||||
"/ip4/35.198.114.154/tcp/30333/p2p/QmQJmDorK9c8KjMF5PdWiH2WGUXyzJtgTeJ55S5gggdju6",
|
||||
"/ip4/35.198.114.154/tcp/30334/ws/p2p/QmQJmDorK9c8KjMF5PdWiH2WGUXyzJtgTeJ55S5gggdju6"
|
||||
],
|
||||
"telemetryEndpoints": [
|
||||
["wss://telemetry.polkadot.io/submit/", 0]
|
||||
],
|
||||
"protocolId": "fir",
|
||||
"consensusEngine": null,
|
||||
"myProperty": "Test Extension",
|
||||
"genesis": {
|
||||
"raw": [
|
||||
{
|
||||
"0xb2029f8665aac509629f2d28cea790a3": "0x10f26cdb14b5aec7b2789fd5ca80f979cef3761897ae1f37ffb3e154cbcc1c26633919132b851ef0fd2dae42a7e734fe547af5a6b809006100f48944d7fae8e8ef00299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f437800299981a2b92f878baaf5dbeba5c18d4e70f2a1fcd9c61b32ea18daf38f4378547ff0ab649283a7ae01dbc2eb73932eba2fb09075e9485ff369082a2ff38d655633b70b80a6c8bb16270f82cca6d56b27ed7b76c8fd5af2986a25a4788ce440482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a482a3389a6cf42d8ed83888cfd920fec738ea30f97e44699ada7323f08c3380a68655684472b743e456907b398d3a44c113f189e56d1bbfd55e889e295dfde787932cff431e748892fa48e10c63c17d30f80ca42e4de3921e641249cd7fa3c2f482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e9c7a2ee14e565db0c69f78c7b4cd839fbf52b607d867e9e9c5a79042898a0d129becad03e6dcac03cee07edebca5475314861492cdfc96a2144a67bbe96993326e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f91066e7e4eb42cbd2e0ab4cae8708ce5509580b8c04d11f6758dbf686d50fe9f9106"
|
||||
},
|
||||
{}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Substrate chain configurations.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::path::PathBuf;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use primitives::storage::{StorageKey, StorageData};
|
||||
use sr_primitives::{BuildStorage, StorageOverlay, ChildrenStorageOverlay};
|
||||
use serde_json as json;
|
||||
use crate::RuntimeGenesis;
|
||||
use network::Multiaddr;
|
||||
use tel::TelemetryEndpoints;
|
||||
|
||||
enum GenesisSource<G> {
|
||||
File(PathBuf),
|
||||
Binary(Cow<'static, [u8]>),
|
||||
Factory(fn() -> G),
|
||||
}
|
||||
|
||||
impl<G> Clone for GenesisSource<G> {
|
||||
fn clone(&self) -> Self {
|
||||
match *self {
|
||||
GenesisSource::File(ref path) => GenesisSource::File(path.clone()),
|
||||
GenesisSource::Binary(ref d) => GenesisSource::Binary(d.clone()),
|
||||
GenesisSource::Factory(f) => GenesisSource::Factory(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<G: RuntimeGenesis> GenesisSource<G> {
|
||||
fn resolve(&self) -> Result<Genesis<G>, String> {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct GenesisContainer<G> {
|
||||
genesis: Genesis<G>,
|
||||
}
|
||||
|
||||
match self {
|
||||
GenesisSource::File(path) => {
|
||||
let file = File::open(path)
|
||||
.map_err(|e| format!("Error opening spec file: {}", e))?;
|
||||
let genesis: GenesisContainer<G> = json::from_reader(file)
|
||||
.map_err(|e| format!("Error parsing spec file: {}", e))?;
|
||||
Ok(genesis.genesis)
|
||||
},
|
||||
GenesisSource::Binary(buf) => {
|
||||
let genesis: GenesisContainer<G> = json::from_reader(buf.as_ref())
|
||||
.map_err(|e| format!("Error parsing embedded file: {}", e))?;
|
||||
Ok(genesis.genesis)
|
||||
},
|
||||
GenesisSource::Factory(f) => Ok(Genesis::Runtime(f())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, G: RuntimeGenesis, E> BuildStorage for &'a ChainSpec<G, E> {
|
||||
fn build_storage(self) -> Result<(StorageOverlay, ChildrenStorageOverlay), String> {
|
||||
match self.genesis.resolve()? {
|
||||
Genesis::Runtime(gc) => gc.build_storage(),
|
||||
Genesis::Raw(map, children_map) => Ok((
|
||||
map.into_iter().map(|(k, v)| (k.0, v.0)).collect(),
|
||||
children_map.into_iter().map(|(sk, map)| (
|
||||
sk.0,
|
||||
map.into_iter().map(|(k, v)| (k.0, v.0)).collect(),
|
||||
)).collect(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn assimilate_storage(
|
||||
self,
|
||||
_: &mut (StorageOverlay, ChildrenStorageOverlay)
|
||||
) -> Result<(), String> {
|
||||
Err("`assimilate_storage` not implemented for `ChainSpec`.".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(deny_unknown_fields)]
|
||||
enum Genesis<G> {
|
||||
Runtime(G),
|
||||
Raw(
|
||||
HashMap<StorageKey, StorageData>,
|
||||
HashMap<StorageKey, HashMap<StorageKey, StorageData>>,
|
||||
),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ChainSpecFile<E> {
|
||||
pub name: String,
|
||||
pub id: String,
|
||||
pub boot_nodes: Vec<String>,
|
||||
pub telemetry_endpoints: Option<TelemetryEndpoints>,
|
||||
pub protocol_id: Option<String>,
|
||||
pub properties: Option<Properties>,
|
||||
#[serde(flatten)]
|
||||
pub extensions: E,
|
||||
// Never used, left only for backward compatibility.
|
||||
consensus_engine: (),
|
||||
#[serde(skip_serializing)]
|
||||
genesis: serde::de::IgnoredAny,
|
||||
}
|
||||
|
||||
/// Arbitrary properties defined in chain spec as a JSON object
|
||||
pub type Properties = json::map::Map<String, json::Value>;
|
||||
|
||||
/// A type denoting empty extensions.
|
||||
///
|
||||
/// We use `Option` here since `()` is not flattenable by serde.
|
||||
pub type NoExtension = Option<()>;
|
||||
|
||||
/// A configuration of a chain. Can be used to build a genesis block.
|
||||
pub struct ChainSpec<G, E = NoExtension> {
|
||||
spec: ChainSpecFile<E>,
|
||||
genesis: GenesisSource<G>,
|
||||
}
|
||||
|
||||
impl<G, E: Clone> Clone for ChainSpec<G, E> {
|
||||
fn clone(&self) -> Self {
|
||||
ChainSpec {
|
||||
spec: self.spec.clone(),
|
||||
genesis: self.genesis.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<G, E> ChainSpec<G, E> {
|
||||
/// A list of bootnode addresses.
|
||||
pub fn boot_nodes(&self) -> &[String] {
|
||||
&self.spec.boot_nodes
|
||||
}
|
||||
|
||||
/// Spec name.
|
||||
pub fn name(&self) -> &str {
|
||||
&self.spec.name
|
||||
}
|
||||
|
||||
/// Spec id.
|
||||
pub fn id(&self) -> &str {
|
||||
&self.spec.id
|
||||
}
|
||||
|
||||
/// Telemetry endpoints (if any)
|
||||
pub fn telemetry_endpoints(&self) -> &Option<TelemetryEndpoints> {
|
||||
&self.spec.telemetry_endpoints
|
||||
}
|
||||
|
||||
/// Network protocol id.
|
||||
pub fn protocol_id(&self) -> Option<&str> {
|
||||
self.spec.protocol_id.as_ref().map(String::as_str)
|
||||
}
|
||||
|
||||
/// Additional loosly-typed properties of the chain.
|
||||
///
|
||||
/// Returns an empty JSON object if 'properties' not defined in config
|
||||
pub fn properties(&self) -> Properties {
|
||||
self.spec.properties.as_ref().unwrap_or(&json::map::Map::new()).clone()
|
||||
}
|
||||
|
||||
/// Add a bootnode to the list.
|
||||
pub fn add_boot_node(&mut self, addr: Multiaddr) {
|
||||
self.spec.boot_nodes.push(addr.to_string())
|
||||
}
|
||||
|
||||
/// Returns a reference to defined chain spec extensions.
|
||||
pub fn extensions(&self) -> &E {
|
||||
&self.spec.extensions
|
||||
}
|
||||
|
||||
/// Create hardcoded spec.
|
||||
pub fn from_genesis(
|
||||
name: &str,
|
||||
id: &str,
|
||||
constructor: fn() -> G,
|
||||
boot_nodes: Vec<String>,
|
||||
telemetry_endpoints: Option<TelemetryEndpoints>,
|
||||
protocol_id: Option<&str>,
|
||||
properties: Option<Properties>,
|
||||
extensions: E,
|
||||
) -> Self {
|
||||
let spec = ChainSpecFile {
|
||||
name: name.to_owned(),
|
||||
id: id.to_owned(),
|
||||
boot_nodes: boot_nodes,
|
||||
telemetry_endpoints,
|
||||
protocol_id: protocol_id.map(str::to_owned),
|
||||
properties,
|
||||
extensions,
|
||||
consensus_engine: (),
|
||||
genesis: Default::default(),
|
||||
};
|
||||
|
||||
ChainSpec {
|
||||
spec,
|
||||
genesis: GenesisSource::Factory(constructor),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<G, E: serde::de::DeserializeOwned> ChainSpec<G, E> {
|
||||
/// Parse json content into a `ChainSpec`
|
||||
pub fn from_json_bytes(json: impl Into<Cow<'static, [u8]>>) -> Result<Self, String> {
|
||||
let json = json.into();
|
||||
let spec = json::from_slice(json.as_ref())
|
||||
.map_err(|e| format!("Error parsing spec file: {}", e))?;
|
||||
Ok(ChainSpec {
|
||||
spec,
|
||||
genesis: GenesisSource::Binary(json),
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse json file into a `ChainSpec`
|
||||
pub fn from_json_file(path: PathBuf) -> Result<Self, String> {
|
||||
let file = File::open(&path)
|
||||
.map_err(|e| format!("Error opening spec file: {}", e))?;
|
||||
let spec = json::from_reader(file)
|
||||
.map_err(|e| format!("Error parsing spec file: {}", e))?;
|
||||
Ok(ChainSpec {
|
||||
spec,
|
||||
genesis: GenesisSource::File(path),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<G: RuntimeGenesis, E: serde::Serialize> ChainSpec<G, E> {
|
||||
/// Dump to json string.
|
||||
pub fn to_json(self, raw: bool) -> Result<String, String> {
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Container<G, E> {
|
||||
#[serde(flatten)]
|
||||
spec: ChainSpecFile<E>,
|
||||
genesis: Genesis<G>,
|
||||
|
||||
};
|
||||
let genesis = match (raw, self.genesis.resolve()?) {
|
||||
(true, Genesis::Runtime(g)) => {
|
||||
let storage = g.build_storage()?;
|
||||
let top = storage.0.into_iter()
|
||||
.map(|(k, v)| (StorageKey(k), StorageData(v)))
|
||||
.collect();
|
||||
let children = storage.1.into_iter()
|
||||
.map(|(sk, child)| (
|
||||
StorageKey(sk),
|
||||
child.into_iter()
|
||||
.map(|(k, v)| (StorageKey(k), StorageData(v)))
|
||||
.collect(),
|
||||
))
|
||||
.collect();
|
||||
|
||||
Genesis::Raw(top, children)
|
||||
},
|
||||
(_, genesis) => genesis,
|
||||
};
|
||||
let spec = Container {
|
||||
spec: self.spec,
|
||||
genesis,
|
||||
};
|
||||
json::to_string_pretty(&spec)
|
||||
.map_err(|e| format!("Error generating spec json: {}", e))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
struct Genesis(HashMap<String, String>);
|
||||
|
||||
impl BuildStorage for Genesis {
|
||||
fn assimilate_storage(
|
||||
self,
|
||||
storage: &mut (StorageOverlay, ChildrenStorageOverlay),
|
||||
) -> Result<(), String> {
|
||||
storage.0.extend(
|
||||
self.0.into_iter().map(|(a, b)| (a.into_bytes(), b.into_bytes()))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
type TestSpec = ChainSpec<Genesis>;
|
||||
|
||||
#[test]
|
||||
fn should_deserailize_example_chain_spec() {
|
||||
let spec1 = TestSpec::from_json_bytes(Cow::Owned(
|
||||
include_bytes!("../res/chain_spec.json").to_vec()
|
||||
)).unwrap();
|
||||
let spec2 = TestSpec::from_json_file(
|
||||
PathBuf::from("./res/chain_spec.json")
|
||||
).unwrap();
|
||||
|
||||
assert_eq!(spec1.to_json(false), spec2.to_json(false));
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Extension1 {
|
||||
my_property: String,
|
||||
}
|
||||
|
||||
type TestSpec2 = ChainSpec<Genesis, Extension1>;
|
||||
|
||||
#[test]
|
||||
fn should_deserialize_chain_spec_with_extensions() {
|
||||
let spec = TestSpec2::from_json_bytes(Cow::Owned(
|
||||
include_bytes!("../res/chain_spec2.json").to_vec()
|
||||
)).unwrap();
|
||||
|
||||
assert_eq!(spec.extensions().my_property, "Test Extension");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
// Copyright 2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Chain Spec extensions helpers.
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::{Serialize, Deserialize, de::DeserializeOwned};
|
||||
|
||||
/// A `ChainSpec` extension.
|
||||
///
|
||||
/// This trait is implemented automatically by `ChainSpecGroup` macro.
|
||||
pub trait Group: Clone + Sized {
|
||||
/// An associated type containing fork definition.
|
||||
type Fork: Fork<Base=Self>;
|
||||
|
||||
/// Convert to fork type.
|
||||
fn to_fork(self) -> Self::Fork;
|
||||
}
|
||||
|
||||
/// A `ChainSpec` extension fork definition.
|
||||
///
|
||||
/// Basically should look the same as `Group`, but
|
||||
/// all parameters are optional. This allows changing
|
||||
/// only one parameter as part of the fork.
|
||||
/// The forks can be combined (summed up) to specify
|
||||
/// a complete set of parameters
|
||||
pub trait Fork: Serialize + DeserializeOwned + Clone + Sized {
|
||||
/// A base `Group` type.
|
||||
type Base: Group<Fork=Self>;
|
||||
|
||||
/// Combine with another struct.
|
||||
///
|
||||
/// All parameters set in `other` should override the
|
||||
/// ones in the current struct.
|
||||
fn combine_with(&mut self, other: Self);
|
||||
|
||||
/// Attempt to convert to the base type if all parameters are set.
|
||||
fn to_base(self) -> Option<Self::Base>;
|
||||
}
|
||||
|
||||
macro_rules! impl_trivial {
|
||||
() => {};
|
||||
($A : ty) => {
|
||||
impl_trivial!($A ,);
|
||||
};
|
||||
($A : ty , $( $B : ty ),*) => {
|
||||
impl_trivial!($( $B ),*);
|
||||
|
||||
impl Group for $A {
|
||||
type Fork = $A;
|
||||
|
||||
fn to_fork(self) -> Self::Fork {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Fork for $A {
|
||||
type Base = $A;
|
||||
|
||||
fn combine_with(&mut self, other: Self) {
|
||||
*self = other;
|
||||
}
|
||||
|
||||
fn to_base(self) -> Option<Self::Base> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_trivial!((), u8, u16, u32, u64, usize, String, Vec<u8>);
|
||||
|
||||
impl<T: Group> Group for Option<T> {
|
||||
type Fork = Option<T::Fork>;
|
||||
|
||||
fn to_fork(self) -> Self::Fork {
|
||||
self.map(|a| a.to_fork())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Fork> Fork for Option<T> {
|
||||
type Base = Option<T::Base>;
|
||||
|
||||
fn combine_with(&mut self, other: Self) {
|
||||
*self = match (self.take(), other) {
|
||||
(Some(mut a), Some(b)) => {
|
||||
a.combine_with(b);
|
||||
Some(a)
|
||||
},
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
}
|
||||
|
||||
fn to_base(self) -> Option<Self::Base> {
|
||||
self.map(|x| x.to_base())
|
||||
}
|
||||
}
|
||||
|
||||
/// A collection of `ChainSpec` extensions.
|
||||
///
|
||||
/// This type can be passed around and allows the core
|
||||
/// modules to request a strongly-typed, but optional configuration.
|
||||
pub trait Extension: Serialize + DeserializeOwned + Clone {
|
||||
type Forks: IsForks;
|
||||
|
||||
/// Get an extension of specific type.
|
||||
fn get<T: 'static>(&self) -> Option<&T>;
|
||||
|
||||
/// Get forkable extensions of specific type.
|
||||
fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>> where
|
||||
BlockNumber: Ord + Clone + 'static,
|
||||
T: Group + 'static,
|
||||
<Self::Forks as IsForks>::Extension: Extension,
|
||||
<<Self::Forks as IsForks>::Extension as Group>::Fork: Extension,
|
||||
{
|
||||
self.get::<Forks<BlockNumber, <Self::Forks as IsForks>::Extension>>()?
|
||||
.for_type()
|
||||
}
|
||||
}
|
||||
|
||||
impl Extension for crate::NoExtension {
|
||||
type Forks = Self;
|
||||
|
||||
fn get<T: 'static>(&self) -> Option<&T> { None }
|
||||
}
|
||||
|
||||
pub trait IsForks {
|
||||
type BlockNumber: Ord + 'static;
|
||||
type Extension: Group + 'static;
|
||||
}
|
||||
|
||||
impl IsForks for Option<()> {
|
||||
type BlockNumber = u64;
|
||||
type Extension = Self;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Forks<BlockNumber: Ord, T: Group> {
|
||||
forks: BTreeMap<BlockNumber, T::Fork>,
|
||||
#[serde(flatten)]
|
||||
base: T,
|
||||
}
|
||||
|
||||
impl<B: Ord, T: Group + Default> Default for Forks<B, T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
base: Default::default(),
|
||||
forks: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: Ord, T: Group> Forks<B, T> where
|
||||
T::Fork: Debug,
|
||||
{
|
||||
/// Create new fork definition given the base and the forks.
|
||||
pub fn new(base: T, forks: BTreeMap<B, T::Fork>) -> Self {
|
||||
Self { base, forks }
|
||||
}
|
||||
|
||||
/// Return a set of parameters for `Group` including all forks up to `block` (inclusive).
|
||||
pub fn at_block(&self, block: B) -> T {
|
||||
let mut start = self.base.clone().to_fork();
|
||||
|
||||
for (_, fork) in self.forks.range(..=block) {
|
||||
start.combine_with(fork.clone());
|
||||
}
|
||||
|
||||
start
|
||||
.to_base()
|
||||
.expect("We start from the `base` object, so it's always fully initialized; qed")
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, T> IsForks for Forks<B, T> where
|
||||
B: Ord + 'static,
|
||||
T: Group + 'static,
|
||||
{
|
||||
type BlockNumber = B;
|
||||
type Extension = T;
|
||||
}
|
||||
|
||||
impl<B: Ord + Clone, T: Group + Extension> Forks<B, T> where
|
||||
T::Fork: Extension,
|
||||
{
|
||||
/// Get forks definition for a subset of this extension.
|
||||
///
|
||||
/// Returns the `Forks` struct, but limited to a particular type
|
||||
/// within the extension.
|
||||
pub fn for_type<X>(&self) -> Option<Forks<B, X>> where
|
||||
X: Group + 'static,
|
||||
{
|
||||
let base = self.base.get::<X>()?.clone();
|
||||
let forks = self.forks.iter().filter_map(|(k, v)| {
|
||||
Some((k.clone(), v.get::<Option<X::Fork>>()?.clone()?))
|
||||
}).collect();
|
||||
|
||||
Some(Forks {
|
||||
base,
|
||||
forks,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, E> Extension for Forks<B, E> where
|
||||
B: Serialize + DeserializeOwned + Ord + Clone + 'static,
|
||||
E: Extension + Group + 'static,
|
||||
{
|
||||
type Forks = Self;
|
||||
|
||||
fn get<T: 'static>(&self) -> Option<&T> {
|
||||
use std::any::{TypeId, Any};
|
||||
|
||||
match TypeId::of::<T>() {
|
||||
x if x == TypeId::of::<E>() => Any::downcast_ref(&self.base),
|
||||
_ => self.base.get(),
|
||||
}
|
||||
}
|
||||
|
||||
fn forks<BlockNumber, T>(&self) -> Option<Forks<BlockNumber, T>> where
|
||||
BlockNumber: Ord + Clone + 'static,
|
||||
T: Group + 'static,
|
||||
<Self::Forks as IsForks>::Extension: Extension,
|
||||
<<Self::Forks as IsForks>::Extension as Group>::Fork: Extension,
|
||||
{
|
||||
use std::any::{TypeId, Any};
|
||||
|
||||
if TypeId::of::<BlockNumber>() == TypeId::of::<B>() {
|
||||
Any::downcast_ref(&self.for_type::<T>()?).cloned()
|
||||
} else {
|
||||
self.get::<Forks<BlockNumber, <Self::Forks as IsForks>::Extension>>()?
|
||||
.for_type()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chain_spec_derive::{ChainSpecGroup, ChainSpecExtension};
|
||||
// Make the proc macro work for tests and doc tests.
|
||||
use crate as substrate_chain_spec;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Extension1 {
|
||||
pub test: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Extension2 {
|
||||
pub test: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Extensions {
|
||||
pub ext1: Extension1,
|
||||
pub ext2: Extension2,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ChainSpecExtension)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Ext2 {
|
||||
#[serde(flatten)]
|
||||
ext1: Extension1,
|
||||
#[forks]
|
||||
forkable: Forks<u64, Extensions>,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forks_should_work_correctly() {
|
||||
use super::Extension as _ ;
|
||||
|
||||
let ext: Ext2 = serde_json::from_str(r#"
|
||||
{
|
||||
"test": 11,
|
||||
"forkable": {
|
||||
"ext1": {
|
||||
"test": 15
|
||||
},
|
||||
"ext2": {
|
||||
"test": 123
|
||||
},
|
||||
"forks": {
|
||||
"1": {
|
||||
"ext1": { "test": 5 }
|
||||
},
|
||||
"2": {
|
||||
"ext2": { "test": 5 }
|
||||
},
|
||||
"5": {
|
||||
"ext2": { "test": 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"#).unwrap();
|
||||
|
||||
assert_eq!(ext.get::<Extension1>(), Some(&Extension1 {
|
||||
test: 11
|
||||
}));
|
||||
|
||||
// get forks definition
|
||||
let forks = ext.get::<Forks<u64, Extensions>>().unwrap();
|
||||
assert_eq!(forks.at_block(0), Extensions {
|
||||
ext1: Extension1 { test: 15 },
|
||||
ext2: Extension2 { test: 123 },
|
||||
});
|
||||
assert_eq!(forks.at_block(1), Extensions {
|
||||
ext1: Extension1 { test: 5 },
|
||||
ext2: Extension2 { test: 123 },
|
||||
});
|
||||
assert_eq!(forks.at_block(2), Extensions {
|
||||
ext1: Extension1 { test: 5 },
|
||||
ext2: Extension2 { test: 5 },
|
||||
});
|
||||
assert_eq!(forks.at_block(4), Extensions {
|
||||
ext1: Extension1 { test: 5 },
|
||||
ext2: Extension2 { test: 5 },
|
||||
});
|
||||
assert_eq!(forks.at_block(5), Extensions {
|
||||
ext1: Extension1 { test: 5 },
|
||||
ext2: Extension2 { test: 1 },
|
||||
});
|
||||
assert_eq!(forks.at_block(10), Extensions {
|
||||
ext1: Extension1 { test: 5 },
|
||||
ext2: Extension2 { test: 1 },
|
||||
});
|
||||
assert!(forks.at_block(10).get::<Extension2>().is_some());
|
||||
|
||||
// filter forks for `Extension2`
|
||||
let ext2 = forks.for_type::<Extension2>().unwrap();
|
||||
assert_eq!(ext2.at_block(0), Extension2 { test: 123 });
|
||||
assert_eq!(ext2.at_block(2), Extension2 { test: 5 });
|
||||
assert_eq!(ext2.at_block(10), Extension2 { test: 1 });
|
||||
|
||||
// make sure that it can return forks correctly
|
||||
let ext2_2 = forks.forks::<u64, Extension2>().unwrap();
|
||||
assert_eq!(ext2, ext2_2);
|
||||
|
||||
// also ext should be able to return forks correctly:
|
||||
let ext2_3 = ext.forks::<u64, Extension2>().unwrap();
|
||||
assert_eq!(ext2_2, ext2_3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Copyright 2019 Parity Technologies (UK) Ltd.
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Substrate is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// Substrate is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
//! Substrate chain configurations.
|
||||
//!
|
||||
//! This crate contains structs and utilities to declare
|
||||
//! a runtime-specific configuration file (a.k.a chain spec).
|
||||
//!
|
||||
//! Basic chain spec type containing all required parameters is
|
||||
//! [`ChainSpec`](./struct.ChainSpec.html). It can be extended with
|
||||
//! additional options that contain configuration specific to your chain.
|
||||
//! Usually the extension is going to be an amalgamate of types exposed
|
||||
//! by Substrate core modules. To allow the core modules to retrieve
|
||||
//! their configuration from your extension you should use `ChainSpecExtension`
|
||||
//! macro exposed by this crate.
|
||||
//!
|
||||
//! ```rust
|
||||
//! use std::collections::HashMap;
|
||||
//! use serde::{Serialize, Deserialize};
|
||||
//! use substrate_chain_spec::{ChainSpec, ChainSpecExtension};
|
||||
//!
|
||||
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecExtension)]
|
||||
//! pub struct MyExtension {
|
||||
//! pub known_blocks: HashMap<u64, String>,
|
||||
//! }
|
||||
//!
|
||||
//! pub type MyChainSpec<G> = ChainSpec<G, MyExtension>;
|
||||
//! ```
|
||||
//!
|
||||
//! Some parameters may require different values depending on the
|
||||
//! current blockchain height (a.k.a. forks). You can use `ChainSpecGroup`
|
||||
//! macro and provided [`Forks`](./struct.Forks.html) structure to put
|
||||
//! such parameters to your chain spec.
|
||||
//! This will allow to override a single parameter starting at specific
|
||||
//! block number.
|
||||
//!
|
||||
//! ```rust
|
||||
//! use serde::{Serialize, Deserialize};
|
||||
//! use substrate_chain_spec::{Forks, ChainSpec, ChainSpecGroup, ChainSpecExtension};
|
||||
//!
|
||||
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)]
|
||||
//! pub struct ClientParams {
|
||||
//! max_block_size: usize,
|
||||
//! max_extrinsic_size: usize,
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)]
|
||||
//! pub struct PoolParams {
|
||||
//! max_transaction_size: usize,
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup, ChainSpecExtension)]
|
||||
//! pub struct Extension {
|
||||
//! pub client: ClientParams,
|
||||
//! pub pool: PoolParams,
|
||||
//! }
|
||||
//!
|
||||
//! pub type BlockNumber = u64;
|
||||
//!
|
||||
//! /// A chain spec supporting forkable `ClientParams`.
|
||||
//! pub type MyChainSpec1<G> = ChainSpec<G, Forks<BlockNumber, ClientParams>>;
|
||||
//!
|
||||
//! /// A chain spec supporting forkable `Extension`.
|
||||
//! pub type MyChainSpec2<G> = ChainSpec<G, Forks<BlockNumber, Extension>>;
|
||||
//! ```
|
||||
//!
|
||||
//! It's also possible to have a set of parameters that is allowed to change
|
||||
//! with block numbers (i.e. is forkable), and another set that is not subject to changes.
|
||||
//! This is also possible by declaring an extension that contains `Forks` within it.
|
||||
//!
|
||||
//!
|
||||
//! ```rust
|
||||
//! use serde::{Serialize, Deserialize};
|
||||
//! use substrate_chain_spec::{Forks, ChainSpec, ChainSpecGroup, ChainSpecExtension};
|
||||
//!
|
||||
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)]
|
||||
//! pub struct ClientParams {
|
||||
//! max_block_size: usize,
|
||||
//! max_extrinsic_size: usize,
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecGroup)]
|
||||
//! pub struct PoolParams {
|
||||
//! max_transaction_size: usize,
|
||||
//! }
|
||||
//!
|
||||
//! #[derive(Clone, Debug, Serialize, Deserialize, ChainSpecExtension)]
|
||||
//! pub struct Extension {
|
||||
//! pub client: ClientParams,
|
||||
//! #[forks]
|
||||
//! pub pool: Forks<u64, PoolParams>,
|
||||
//! }
|
||||
//!
|
||||
//! pub type MyChainSpec<G> = ChainSpec<G, Extension>;
|
||||
//! ```
|
||||
|
||||
|
||||
mod chain_spec;
|
||||
mod extension;
|
||||
|
||||
pub use chain_spec::{ChainSpec, Properties, NoExtension};
|
||||
pub use extension::{Group, Fork, Forks, Extension};
|
||||
pub use chain_spec_derive::{ChainSpecExtension, ChainSpecGroup};
|
||||
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
use sr_primitives::BuildStorage;
|
||||
|
||||
/// A set of traits for the runtime genesis config.
|
||||
pub trait RuntimeGenesis: Serialize + DeserializeOwned + BuildStorage {}
|
||||
impl<T: Serialize + DeserializeOwned + BuildStorage> RuntimeGenesis for T {}
|
||||
|
||||
Reference in New Issue
Block a user