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

Commit 9b8bfd7

Browse files
authored
chain spec builder: add generate mode for authority keys (#3811)
* core: use trait object for genesis constructor * chain-spec-builder: use structopt * chain-spec-builder: add new command to generate authority keys * chain-spec-builder: use ? in main * chain-spec-builder: fix stored and printed suri from seed * chain-spec-builder: add comment about created keystore folders * chain-spec-builder: simplify file write
1 parent 67b73c4 commit 9b8bfd7

File tree

5 files changed

+249
-56
lines changed

5 files changed

+249
-56
lines changed

Cargo.lock

Lines changed: 4 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

core/chain-spec/src/chain_spec.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use std::borrow::Cow;
2020
use std::collections::HashMap;
2121
use std::fs::File;
2222
use std::path::PathBuf;
23+
use std::rc::Rc;
2324
use serde::{Serialize, Deserialize};
2425
use primitives::storage::{StorageKey, StorageData};
2526
use sr_primitives::{BuildStorage, StorageOverlay, ChildrenStorageOverlay};
@@ -31,15 +32,15 @@ use tel::TelemetryEndpoints;
3132
enum GenesisSource<G> {
3233
File(PathBuf),
3334
Binary(Cow<'static, [u8]>),
34-
Factory(fn() -> G),
35+
Factory(Rc<dyn Fn() -> G>),
3536
}
3637

3738
impl<G> Clone for GenesisSource<G> {
3839
fn clone(&self) -> Self {
3940
match *self {
4041
GenesisSource::File(ref path) => GenesisSource::File(path.clone()),
4142
GenesisSource::Binary(ref d) => GenesisSource::Binary(d.clone()),
42-
GenesisSource::Factory(f) => GenesisSource::Factory(f),
43+
GenesisSource::Factory(ref f) => GenesisSource::Factory(f.clone()),
4344
}
4445
}
4546
}
@@ -187,10 +188,10 @@ impl<G, E> ChainSpec<G, E> {
187188
}
188189

189190
/// Create hardcoded spec.
190-
pub fn from_genesis(
191+
pub fn from_genesis<F: Fn() -> G + 'static>(
191192
name: &str,
192193
id: &str,
193-
constructor: fn() -> G,
194+
constructor: F,
194195
boot_nodes: Vec<String>,
195196
telemetry_endpoints: Option<TelemetryEndpoints>,
196197
protocol_id: Option<&str>,
@@ -211,7 +212,7 @@ impl<G, E> ChainSpec<G, E> {
211212

212213
ChainSpec {
213214
spec,
214-
genesis: GenesisSource::Factory(constructor),
215+
genesis: GenesisSource::Factory(Rc::new(constructor)),
215216
}
216217
}
217218
}

test-utils/chain-spec-builder/Cargo.toml

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@ authors = ["Parity Technologies <[email protected]>"]
55
edition = "2018"
66

77
[dependencies]
8-
clap = { version = "2.33.0", features = ["yaml"] }
8+
ansi_term = "0.12.1"
9+
keystore = { package = "substrate-keystore", path = "../../core/keystore" }
910
node-cli = { path = "../../node/cli" }
1011
primitives = { package = "substrate-primitives", path = "../../core/primitives" }
11-
substrate-service = { path = "../../core/service" }
12+
rand = "0.7.2"
13+
structopt = "0.3.3"

test-utils/chain-spec-builder/src/cli.yml

Lines changed: 0 additions & 24 deletions
This file was deleted.
Lines changed: 235 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,261 @@
1-
use clap::{App, load_yaml};
1+
// Copyright 2019 Parity Technologies (UK) Ltd.
2+
// This file is part of Substrate.
23

4+
// Substrate is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
9+
// Substrate is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU General Public License for more details.
13+
14+
// You should have received a copy of the GNU General Public License
15+
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
16+
17+
use std::{fs, path::{Path, PathBuf}};
18+
19+
use ansi_term::Style;
20+
use rand::{Rng, distributions::Alphanumeric, rngs::OsRng};
21+
use structopt::StructOpt;
22+
23+
use keystore::{Store as Keystore};
324
use node_cli::chain_spec::{self, AccountId};
4-
use substrate_service::chain_ops::build_spec;
25+
use primitives::{crypto::{Public, Ss58Codec}, traits::BareCryptoStore};
526

6-
fn genesis_constructor() -> chain_spec::GenesisConfig {
7-
let yaml = load_yaml!("./cli.yml");
8-
let matches = App::from_yaml(yaml).get_matches();
9-
let authorities = matches.values_of("initial_authority_seed")
10-
.unwrap()
11-
.map(chain_spec::get_authority_keys_from_seed)
12-
.collect();
27+
/// A utility to easily create a testnet chain spec definition with a given set
28+
/// of authorities and endowed accounts and/or generate random accounts.
29+
#[derive(StructOpt)]
30+
#[structopt(rename_all = "kebab-case")]
31+
enum ChainSpecBuilder {
32+
/// Create a new chain spec with the given authorities, endowed and sudo
33+
/// accounts.
34+
New {
35+
/// Authority key seed.
36+
#[structopt(long, short, required = true)]
37+
authority_seeds: Vec<String>,
38+
/// Endowed account address (SS58 format).
39+
#[structopt(long, short)]
40+
endowed_accounts: Vec<String>,
41+
/// Sudo account address (SS58 format).
42+
#[structopt(long, short)]
43+
sudo_account: String,
44+
/// The path where the chain spec should be saved.
45+
#[structopt(long, short, default_value = "./chain_spec.json")]
46+
chain_spec_path: PathBuf,
47+
},
48+
/// Create a new chain spec with the given number of authorities and endowed
49+
/// accounts. Random keys will be generated as required.
50+
Generate {
51+
/// The number of authorities.
52+
#[structopt(long, short)]
53+
authorities: usize,
54+
/// The number of endowed accounts.
55+
#[structopt(long, short, default_value = "0")]
56+
endowed: usize,
57+
/// The path where the chain spec should be saved.
58+
#[structopt(long, short, default_value = "./chain_spec.json")]
59+
chain_spec_path: PathBuf,
60+
/// Path to use when saving generated keystores for each authority.
61+
///
62+
/// At this path, a new folder will be created for each authority's
63+
/// keystore named `auth-$i` where `i` is the authority index, i.e.
64+
/// `auth-0`, `auth-1`, etc.
65+
#[structopt(long, short)]
66+
keystore_path: Option<PathBuf>,
67+
},
68+
}
1369

14-
let endowed_accounts = matches.values_of("endowed_account_seed")
15-
.unwrap()
16-
.map(chain_spec::get_from_seed::<AccountId>)
17-
.collect();
70+
impl ChainSpecBuilder {
71+
/// Returns the path where the chain spec should be saved.
72+
fn chain_spec_path(&self) -> &Path {
73+
match self {
74+
ChainSpecBuilder::New { chain_spec_path, .. } =>
75+
chain_spec_path.as_path(),
76+
ChainSpecBuilder::Generate { chain_spec_path, .. } =>
77+
chain_spec_path.as_path(),
78+
}
79+
}
80+
}
1881

19-
let sudo_key_seed = matches.value_of("sudo_key_seed").unwrap();
20-
let sudo_key = chain_spec::get_from_seed::<AccountId>(sudo_key_seed);
82+
fn genesis_constructor(
83+
authority_seeds: &[String],
84+
endowed_accounts: &[AccountId],
85+
sudo_account: &AccountId,
86+
) -> chain_spec::GenesisConfig {
87+
let authorities = authority_seeds
88+
.iter()
89+
.map(AsRef::as_ref)
90+
.map(chain_spec::get_authority_keys_from_seed)
91+
.collect::<Vec<_>>();
2192

2293
let enable_println = true;
2394

2495
chain_spec::testnet_genesis(
2596
authorities,
26-
sudo_key.into(),
27-
Some(endowed_accounts),
97+
sudo_account.clone(),
98+
Some(endowed_accounts.to_vec()),
2899
enable_println,
29100
)
30101
}
31102

32-
fn generate_chain_spec() -> String {
103+
fn generate_chain_spec(
104+
authority_seeds: Vec<String>,
105+
endowed_accounts: Vec<String>,
106+
sudo_account: String,
107+
) -> Result<String, String> {
108+
let parse_account = |address: &String| {
109+
AccountId::from_string(address)
110+
.map_err(|err| format!("Failed to parse account address: {:?}", err))
111+
};
112+
113+
let endowed_accounts = endowed_accounts
114+
.iter()
115+
.map(parse_account)
116+
.collect::<Result<Vec<_>, String>>()?;
117+
118+
let sudo_account = parse_account(&sudo_account)?;
119+
33120
let chain_spec = chain_spec::ChainSpec::from_genesis(
34121
"Custom",
35122
"custom",
36-
genesis_constructor,
123+
move || genesis_constructor(&authority_seeds, &endowed_accounts, &sudo_account),
37124
vec![],
38125
None,
39126
None,
40127
None,
41128
Default::default(),
42129
);
43-
build_spec(chain_spec, false).unwrap()
130+
131+
chain_spec.to_json(false).map_err(|err| err.to_string())
132+
}
133+
134+
fn generate_authority_keys_and_store(
135+
seeds: &[String],
136+
keystore_path: &Path,
137+
) -> Result<(), String> {
138+
for (n, seed) in seeds.into_iter().enumerate() {
139+
let keystore = Keystore::open(
140+
keystore_path.join(format!("auth-{}", n)),
141+
None,
142+
).map_err(|err| err.to_string())?;
143+
144+
let (_, _, grandpa, babe, im_online) =
145+
chain_spec::get_authority_keys_from_seed(seed);
146+
147+
let insert_key = |key_type, public| {
148+
keystore.write().insert_unknown(
149+
key_type,
150+
&format!("//{}", seed),
151+
public,
152+
).map_err(|_| format!("Failed to insert key: {}", grandpa))
153+
};
154+
155+
insert_key(
156+
primitives::crypto::key_types::BABE,
157+
babe.as_slice(),
158+
)?;
159+
160+
insert_key(
161+
primitives::crypto::key_types::GRANDPA,
162+
grandpa.as_slice(),
163+
)?;
164+
165+
insert_key(
166+
primitives::crypto::key_types::IM_ONLINE,
167+
im_online.as_slice(),
168+
)?;
169+
}
170+
171+
Ok(())
172+
}
173+
174+
fn print_seeds(
175+
authority_seeds: &[String],
176+
endowed_seeds: &[String],
177+
sudo_seed: &str,
178+
) {
179+
let header = Style::new().bold().underline();
180+
let entry = Style::new().bold();
181+
182+
println!("{}", header.paint("Authority seeds"));
183+
184+
for (n, seed) in authority_seeds.iter().enumerate() {
185+
println!("{} //{}",
186+
entry.paint(format!("auth-{}:", n)),
187+
seed,
188+
);
189+
}
190+
191+
println!();
192+
193+
if !endowed_seeds.is_empty() {
194+
println!("{}", header.paint("Endowed seeds"));
195+
for (n, seed) in endowed_seeds.iter().enumerate() {
196+
println!("{} //{}",
197+
entry.paint(format!("endowed-{}:", n)),
198+
seed,
199+
);
200+
}
201+
202+
println!();
203+
}
204+
205+
println!("{}", header.paint("Sudo seed"));
206+
println!("//{}", sudo_seed);
44207
}
45208

46-
fn main() {
47-
let json = generate_chain_spec();
48-
println!("{}", json);
209+
fn main() -> Result<(), String> {
210+
let builder = ChainSpecBuilder::from_args();
211+
let chain_spec_path = builder.chain_spec_path().to_path_buf();
212+
213+
let (authority_seeds, endowed_accounts, sudo_account) = match builder {
214+
ChainSpecBuilder::Generate { authorities, endowed, keystore_path, .. } => {
215+
let authorities = authorities.max(1);
216+
let rand_str = || -> String {
217+
OsRng.sample_iter(&Alphanumeric)
218+
.take(32)
219+
.collect()
220+
};
221+
222+
let authority_seeds = (0..authorities).map(|_| rand_str()).collect::<Vec<_>>();
223+
let endowed_seeds = (0..endowed).map(|_| rand_str()).collect::<Vec<_>>();
224+
let sudo_seed = rand_str();
225+
226+
print_seeds(
227+
&authority_seeds,
228+
&endowed_seeds,
229+
&sudo_seed,
230+
);
231+
232+
if let Some(keystore_path) = keystore_path {
233+
generate_authority_keys_and_store(
234+
&authority_seeds,
235+
&keystore_path,
236+
)?;
237+
}
238+
239+
let endowed_accounts = endowed_seeds.iter().map(|seed| {
240+
chain_spec::get_from_seed::<AccountId>(seed)
241+
.to_ss58check()
242+
}).collect();
243+
244+
let sudo_account = chain_spec::get_from_seed::<AccountId>(&sudo_seed)
245+
.to_ss58check();
246+
247+
(authority_seeds, endowed_accounts, sudo_account)
248+
},
249+
ChainSpecBuilder::New { authority_seeds, endowed_accounts, sudo_account, .. } => {
250+
(authority_seeds, endowed_accounts, sudo_account)
251+
},
252+
};
253+
254+
let json = generate_chain_spec(
255+
authority_seeds,
256+
endowed_accounts,
257+
sudo_account,
258+
)?;
259+
260+
fs::write(chain_spec_path, json).map_err(|err| err.to_string())
49261
}

0 commit comments

Comments
 (0)