main.rs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright 2019-2020 Parity Technologies (UK) Ltd.
  2. // This file is part of Substrate.
  3. // Substrate is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation, either version 3 of the License, or
  6. // (at your option) any later version.
  7. // Substrate is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU General Public License for more details.
  11. // You should have received a copy of the GNU General Public License
  12. // along with Substrate. If not, see <http://www.gnu.org/licenses/>.
  13. use std::{
  14. fs,
  15. path::{Path, PathBuf},
  16. };
  17. use ansi_term::Style;
  18. use rand::{distributions::Alphanumeric, rngs::OsRng, Rng};
  19. use structopt::StructOpt;
  20. use joystream_node::{
  21. chain_spec::{self, chain_spec_properties, membership, AccountId, Moment},
  22. initial_members, proposals_config,
  23. };
  24. use sc_chain_spec::ChainType;
  25. use sc_keystore::Store as Keystore;
  26. use sc_telemetry::TelemetryEndpoints;
  27. use sp_core::{
  28. crypto::{Public, Ss58Codec},
  29. sr25519,
  30. traits::BareCryptoStore,
  31. };
  32. const STAGING_TELEMETRY_URL: &str = "wss://telemetry.polkadot.io/submit/";
  33. /// A utility to easily create a testnet chain spec definition with a given set
  34. /// of authorities and endowed accounts and/or generate random accounts.
  35. #[derive(StructOpt)]
  36. #[structopt(rename_all = "kebab-case")]
  37. enum ChainSpecBuilder {
  38. /// Create a new chain spec with the given authorities, endowed and sudo
  39. /// accounts.
  40. New {
  41. /// Authority key seed.
  42. #[structopt(long, short, required = true)]
  43. authority_seeds: Vec<String>,
  44. /// Endowed account address (SS58 format).
  45. #[structopt(long, short)]
  46. endowed_accounts: Vec<String>,
  47. /// Sudo account address (SS58 format).
  48. #[structopt(long, short)]
  49. sudo_account: String,
  50. /// The path where the chain spec should be saved.
  51. #[structopt(long, short, default_value = "./chain_spec.json")]
  52. chain_spec_path: PathBuf,
  53. /// The path to an initial members data
  54. #[structopt(long, short)]
  55. initial_members_path: Option<PathBuf>,
  56. },
  57. /// Create a new chain spec with the given number of authorities and endowed
  58. /// accounts. Random keys will be generated as required.
  59. Generate {
  60. /// The number of authorities.
  61. #[structopt(long, short)]
  62. authorities: usize,
  63. /// The number of endowed accounts.
  64. #[structopt(long, short, default_value = "0")]
  65. endowed: usize,
  66. /// The path where the chain spec should be saved.
  67. #[structopt(long, short, default_value = "./chain_spec.json")]
  68. chain_spec_path: PathBuf,
  69. /// Path to use when saving generated keystores for each authority.
  70. ///
  71. /// At this path, a new folder will be created for each authority's
  72. /// keystore named `auth-$i` where `i` is the authority index, i.e.
  73. /// `auth-0`, `auth-1`, etc.
  74. #[structopt(long, short)]
  75. keystore_path: Option<PathBuf>,
  76. /// The path to an initial members data
  77. #[structopt(long, short)]
  78. initial_members_path: Option<PathBuf>,
  79. },
  80. }
  81. impl ChainSpecBuilder {
  82. /// Returns the path where the chain spec should be saved.
  83. fn chain_spec_path(&self) -> &Path {
  84. match self {
  85. ChainSpecBuilder::New {
  86. chain_spec_path, ..
  87. } => chain_spec_path.as_path(),
  88. ChainSpecBuilder::Generate {
  89. chain_spec_path, ..
  90. } => chain_spec_path.as_path(),
  91. }
  92. }
  93. /// Returns the path where the chain spec should be saved.
  94. fn initial_members_path(&self) -> &Option<PathBuf> {
  95. match self {
  96. ChainSpecBuilder::New {
  97. initial_members_path,
  98. ..
  99. } => initial_members_path,
  100. ChainSpecBuilder::Generate {
  101. initial_members_path,
  102. ..
  103. } => initial_members_path,
  104. }
  105. }
  106. }
  107. fn genesis_constructor(
  108. authority_seeds: &[String],
  109. endowed_accounts: &[AccountId],
  110. sudo_account: &AccountId,
  111. genesis_members: &Vec<membership::genesis::Member<u64, AccountId, Moment>>,
  112. ) -> chain_spec::GenesisConfig {
  113. let authorities = authority_seeds
  114. .iter()
  115. .map(AsRef::as_ref)
  116. .map(chain_spec::get_authority_keys_from_seed)
  117. .collect::<Vec<_>>();
  118. chain_spec::testnet_genesis(
  119. authorities,
  120. sudo_account.clone(),
  121. endowed_accounts.to_vec(),
  122. proposals_config::default(),
  123. genesis_members.clone(),
  124. )
  125. }
  126. fn generate_chain_spec(
  127. authority_seeds: Vec<String>,
  128. endowed_accounts: Vec<String>,
  129. sudo_account: String,
  130. genesis_members: Vec<membership::genesis::Member<u64, AccountId, Moment>>,
  131. ) -> Result<String, String> {
  132. let parse_account = |address: &String| {
  133. AccountId::from_string(address)
  134. .map_err(|err| format!("Failed to parse account address: {:?}", err))
  135. };
  136. let endowed_accounts = endowed_accounts
  137. .iter()
  138. .map(parse_account)
  139. .collect::<Result<Vec<_>, String>>()?;
  140. let sudo_account = parse_account(&sudo_account)?;
  141. // let boot_nodes = vec![String::from(
  142. // "/dns4/tesnet.joystream.org/tcp/30333/p2p/QmaTTdEF6YVCtynSjsXmGPSGcEesAahoZ8pmcCmmBwSE7S",
  143. // )];
  144. let telemetry_endpoints = TelemetryEndpoints::new(vec![(STAGING_TELEMETRY_URL.to_string(), 0)])
  145. .map_err(|err| format!("Failed to create telemetry endpoints: {:?}", err))?;
  146. let chain_spec = chain_spec::ChainSpec::from_genesis(
  147. "Joystream Testnet",
  148. "joy_testnet",
  149. ChainType::Development,
  150. move || {
  151. genesis_constructor(
  152. &authority_seeds,
  153. &endowed_accounts,
  154. &sudo_account,
  155. &genesis_members,
  156. )
  157. },
  158. vec![],
  159. Some(telemetry_endpoints),
  160. Some(&*"/joy/testnet/0"),
  161. Some(chain_spec_properties()),
  162. None,
  163. );
  164. chain_spec.as_json(false).map_err(|err| err)
  165. }
  166. fn generate_authority_keys_and_store(seeds: &[String], keystore_path: &Path) -> Result<(), String> {
  167. for (n, seed) in seeds.iter().enumerate() {
  168. let keystore = Keystore::open(keystore_path.join(format!("auth-{}", n)), None)
  169. .map_err(|err| err.to_string())?;
  170. let (_, _, grandpa, babe, im_online, _) = chain_spec::get_authority_keys_from_seed(seed);
  171. let insert_key = |key_type, public| {
  172. keystore
  173. .write()
  174. .insert_unknown(key_type, &format!("//{}", seed), public)
  175. .map_err(|_| format!("Failed to insert key: {}", grandpa))
  176. };
  177. insert_key(sp_core::crypto::key_types::BABE, babe.as_slice())?;
  178. insert_key(sp_core::crypto::key_types::GRANDPA, grandpa.as_slice())?;
  179. insert_key(sp_core::crypto::key_types::IM_ONLINE, im_online.as_slice())?;
  180. }
  181. Ok(())
  182. }
  183. fn print_seeds(authority_seeds: &[String], endowed_seeds: &[String], sudo_seed: &str) {
  184. let header = Style::new().bold().underline();
  185. let entry = Style::new().bold();
  186. println!("{}", header.paint("Authority seeds"));
  187. for (n, seed) in authority_seeds.iter().enumerate() {
  188. println!("{} //{}", entry.paint(format!("auth-{}:", n)), seed,);
  189. }
  190. println!();
  191. if !endowed_seeds.is_empty() {
  192. println!("{}", header.paint("Endowed seeds"));
  193. for (n, seed) in endowed_seeds.iter().enumerate() {
  194. println!("{} //{}", entry.paint(format!("endowed-{}:", n)), seed,);
  195. }
  196. println!();
  197. }
  198. println!("{}", header.paint("Sudo seed"));
  199. println!("//{}", sudo_seed);
  200. }
  201. fn main() -> Result<(), String> {
  202. #[cfg(build_type = "debug")]
  203. println!(
  204. "The chain spec builder builds a chain specification that includes a Substrate runtime compiled as WASM. To \
  205. ensure proper functioning of the included runtime compile (or run) the chain spec builder binary in \
  206. `--release` mode.\n",
  207. );
  208. let builder = ChainSpecBuilder::from_args();
  209. let chain_spec_path = builder.chain_spec_path().to_path_buf();
  210. let initial_members_path = builder.initial_members_path();
  211. let members = if let Some(path) = initial_members_path {
  212. initial_members::from_json(path.as_path())
  213. } else {
  214. initial_members::none()
  215. };
  216. let (authority_seeds, endowed_accounts, sudo_account) = match builder {
  217. ChainSpecBuilder::Generate {
  218. authorities,
  219. endowed,
  220. keystore_path,
  221. ..
  222. } => {
  223. let authorities = authorities.max(1);
  224. let rand_str = || -> String { OsRng.sample_iter(&Alphanumeric).take(32).collect() };
  225. let authority_seeds = (0..authorities).map(|_| rand_str()).collect::<Vec<_>>();
  226. let endowed_seeds = (0..endowed).map(|_| rand_str()).collect::<Vec<_>>();
  227. let sudo_seed = rand_str();
  228. print_seeds(&authority_seeds, &endowed_seeds, &sudo_seed);
  229. if let Some(keystore_path) = keystore_path {
  230. generate_authority_keys_and_store(&authority_seeds, &keystore_path)?;
  231. }
  232. let endowed_accounts = endowed_seeds
  233. .iter()
  234. .map(|seed| {
  235. chain_spec::get_account_id_from_seed::<sr25519::Public>(seed).to_ss58check()
  236. })
  237. .collect();
  238. let sudo_account =
  239. chain_spec::get_account_id_from_seed::<sr25519::Public>(&sudo_seed).to_ss58check();
  240. (authority_seeds, endowed_accounts, sudo_account)
  241. }
  242. ChainSpecBuilder::New {
  243. authority_seeds,
  244. endowed_accounts,
  245. sudo_account,
  246. ..
  247. } => (authority_seeds, endowed_accounts, sudo_account),
  248. };
  249. let json = generate_chain_spec(authority_seeds, endowed_accounts, sudo_account, members)?;
  250. fs::write(chain_spec_path, json).map_err(|err| err.to_string())
  251. }